context
stringlengths
2.52k
185k
gt
stringclasses
1 value
namespace AdMaiora.AppKit.IO { using System; using System.IO; using System.Linq; using Android.App; using Android.OS; using Android.Webkit; public class FileSystemPlatformAndroid : IFileSystemPlatform { public void CopyFile(FileUri sourceUri, FileUri destinationUri, bool overwrite) { File.Copy(sourceUri.AbsolutePath, destinationUri.AbsolutePath, overwrite); } public void CreateFolder(FolderUri uri) { Directory.CreateDirectory(uri.AbsolutePath); } public void DeleteFile(FileUri uri) { File.Delete(uri.AbsolutePath); } public void DeleteFolder(FolderUri uri) { Directory.Delete(uri.AbsolutePath, true); } public bool FileExists(FileUri uri) { switch (uri.Location) { case StorageLocation.Bundle: try { using(var stream = new StreamReader(uri.AbsolutePath)) { if(stream == null) return false; return true; } } catch { return false; } case StorageLocation.Internal: return File.Exists(uri.AbsolutePath); case StorageLocation.External: return File.Exists(uri.AbsolutePath); default: return false; } } public bool FolderExists(FolderUri uri) { return Directory.Exists(uri.AbsolutePath); } public ulong GetAvailableDiskSpace(FolderUri uri) { try { Java.Lang.Process proc = Java.Lang.Runtime.GetRuntime().Exec(String.Format("df {0}", uri.AbsolutePath)); proc.WaitFor(); var resi = proc.InputStream; var rdr = new StreamReader(resi); string str = rdr.ReadToEnd(); string[] lines = str.Split('\n'); if (lines.Length < 2) throw new InvalidOperationException("Unable to get size from shell."); string[] entries = lines[1] .Split(' ') .Where(e => !String.IsNullOrWhiteSpace(e)) .ToArray(); string entry = entries[3]; ulong value = (ulong)Int32.Parse(entry.Substring(0, entry.Length - 1)); string unit = entry.Substring(entry.Length - 1, 1); switch (unit) { // Value is in bytes case "B": return value; // Value is in Kbytes case "K": return value * 1024; // Value is in Mbytes case "M": return value * 1024 * 1024; // Value is in Gbytes case "G": return value * 1024 * 1024 * 1024; default: throw new InvalidOperationException("Unknown size unit."); } } catch (Exception ex) { StatFs stats = new StatFs(uri.AbsolutePath); return (ulong)(stats.AvailableBlocks * stats.BlockSize); } } public ulong GetFileSize(FileUri uri) { if (!FileExists(uri)) return 0; FileInfo fi = new FileInfo(uri.AbsolutePath); return (ulong)fi.Length; } public void MoveFile(FileUri sourceUri, FileUri destinationUri) { File.Move(sourceUri.AbsolutePath, destinationUri.AbsolutePath); } public Stream OpenFile(FileUri uri, UniversalFileMode mode, UniversalFileAccess access, UniversalFileShare share) { switch (uri.Location) { case StorageLocation.Bundle: return Application.Context.Assets.Open(uri.RelativePath); case StorageLocation.Internal: return File.Open(uri.AbsolutePath, (FileMode)mode, (FileAccess)access, (FileShare)share); case StorageLocation.External: return File.Open(uri.AbsolutePath, (FileMode)mode, (FileAccess)access, (FileShare)share); default: return null; } } public string GetAbsolutePath(StorageLocation location, string path) { switch (location) { case StorageLocation.Bundle: return Path.Combine(Directory.GetCurrentDirectory(), path); case StorageLocation.Internal: return Path.Combine(Android.App.Application.Context.FilesDir.Path, path); case StorageLocation.External: return Path.Combine(Android.App.Application.Context.GetExternalFilesDir(null).Path, path); } return null; } public UniversalFileInfo GetFileInfo(FileUri uri) { if (!FileExists(uri)) throw new InvalidOperationException("File doesn't exists."); FileInfo fi = new FileInfo(uri.AbsolutePath); return new UniversalFileInfo { CreationTime = fi.CreationTime, LastAccessTime = fi.LastAccessTime, LastWriteTime = fi.LastWriteTime, Length = (ulong)fi.Length }; } public string[] GetFolderFiles(FolderUri uri, string searchPattern, bool recursive) { return Directory.GetFiles(uri.AbsolutePath, searchPattern, recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); } public string GetMimeType(string fileUriOrExt) { if (String.IsNullOrWhiteSpace(fileUriOrExt)) return null; string extension = Path.GetExtension(fileUriOrExt); if (extension == null) return null; MimeTypeMap myMime = MimeTypeMap.Singleton; String mimeType = myMime.GetMimeTypeFromExtension(extension.Substring(1)); return mimeType; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Azure.Core.TestFramework; using Azure.Data.Tables.Models; using Azure.Data.Tables.Sas; using NUnit.Framework; namespace Azure.Data.Tables.Tests { /// <summary> /// The suite of tests for the <see cref="TableServiceClient"/> class. /// </summary> /// <remarks> /// These tests have a dependency on live Azure services and may incur costs for the associated /// Azure subscription. /// </remarks> public class TableClientLiveTests : TableServiceLiveTestsBase { public TableClientLiveTests(bool isAsync, TableEndpointType endpointType) : base(isAsync, endpointType /* To record tests, add this argument, RecordedTestMode.Record */) { } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CreateIfNotExists() { // Call CreateIfNotExists when the table already exists. Assert.That(async () => await CosmosThrottleWrapper(async () => await client.CreateIfNotExistsAsync().ConfigureAwait(false)), Throws.Nothing); // Call CreateIfNotExists when the table does not already exist. var newTableName = Recording.GenerateAlphaNumericId("testtable", useOnlyLowercase: true); TableItem table; TableClient tableClient = null; try { tableClient = service.GetTableClient(newTableName); table = await CosmosThrottleWrapper(async () => await tableClient.CreateIfNotExistsAsync().ConfigureAwait(false)); } finally { await tableClient.DeleteAsync().ConfigureAwait(false); } Assert.That(table.TableName, Is.EqualTo(newTableName)); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task ValidateCreateDeleteTable() { // Get the TableClient of a table that hasn't been created yet. var validTableName = Recording.GenerateAlphaNumericId("testtable", useOnlyLowercase: true); var tableClient = service.GetTableClient(validTableName); // Create the table using the TableClient method. await CosmosThrottleWrapper(async () => await tableClient.CreateAsync().ConfigureAwait(false)); // Check that the table was created. var tableResponses = (await service.GetTablesAsync(filter: $"TableName eq '{validTableName}'").ToEnumerableAsync().ConfigureAwait(false)).ToList(); Assert.That(() => tableResponses, Is.Not.Empty); // Delete the table using the TableClient method. await CosmosThrottleWrapper(async () => await tableClient.DeleteAsync().ConfigureAwait(false)); // Check that the table was deleted. tableResponses = (await service.GetTablesAsync(filter: $"TableName eq '{validTableName}'").ToEnumerableAsync().ConfigureAwait(false)).ToList(); Assert.That(() => tableResponses, Is.Empty); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public void ValidateSasCredentials() { // Create a SharedKeyCredential that we can use to sign the SAS token var credential = new TableSharedKeyCredential(AccountName, AccountKey); // Build a shared access signature with only Read permissions. TableSasBuilder sas = client.GetSasBuilder(TableSasPermissions.Read, new DateTime(2040, 1, 1, 1, 1, 0, DateTimeKind.Utc)); if (_endpointType == TableEndpointType.CosmosTable) { sas.Version = "2017-07-29"; } string token = sas.Sign(credential); // Build a SAS URI UriBuilder sasUri = new UriBuilder(ServiceUri) { Query = token }; // Create the TableServiceClient using the SAS URI. var sasAuthedService = InstrumentClient(new TableServiceClient(sasUri.Uri, InstrumentClientOptions(new TableClientOptions()))); var sasTableclient = sasAuthedService.GetTableClient(tableName); // Validate that we are able to query the table from the service. Assert.That(async () => await sasTableclient.QueryAsync<TableEntity>().ToEnumerableAsync().ConfigureAwait(false), Throws.Nothing); // Validate that we are not able to upsert an entity to the table. Assert.That(async () => await sasTableclient.UpsertEntityAsync(CreateTableEntities("partition", 1).First(), TableUpdateMode.Replace).ConfigureAwait(false), Throws.InstanceOf<RequestFailedException>().And.Property("Status").EqualTo((int)HttpStatusCode.Forbidden)); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task ValidateSasCredentialsWithRowKeyAndPartitionKeyRanges() { List<TableEntity> entitiesToCreate = CreateTableEntities(PartitionKeyValue, 2); // Create a SharedKeyCredential that we can use to sign the SAS token var credential = new TableSharedKeyCredential(AccountName, AccountKey); // Build a shared access signature with only All permissions. TableSasBuilder sas = client.GetSasBuilder(TableSasPermissions.All, new DateTime(2040, 1, 1, 1, 1, 0, DateTimeKind.Utc)); // Add PartitionKey restrictions. sas.PartitionKeyStart = PartitionKeyValue; sas.PartitionKeyEnd = PartitionKeyValue; // Add RowKey restrictions so that only the first entity is visible. sas.RowKeyStart = entitiesToCreate[0].RowKey; sas.RowKeyEnd = entitiesToCreate[0].RowKey; if (_endpointType == TableEndpointType.CosmosTable) { sas.Version = "2017-07-29"; } string token = sas.Sign(credential); // Build a SAS URI UriBuilder sasUri = new UriBuilder(ServiceUri) { Query = token }; // Create the TableServiceClient using the SAS URI. var sasAuthedService = InstrumentClient(new TableServiceClient(sasUri.Uri, InstrumentClientOptions(new TableClientOptions()))); var sasTableclient = sasAuthedService.GetTableClient(tableName); // Insert the entities foreach (var entity in entitiesToCreate) { await client.AddEntityAsync(entity).ConfigureAwait(false); } // Validate that we are able to query the table from the service. var entities = await sasTableclient.QueryAsync<TableEntity>().ToEnumerableAsync().ConfigureAwait(false); Assert.That(entities.Count, Is.EqualTo(1)); // Validate that we are not able to fetch the entity outside the range of the row key filter. Assert.That(async () => await sasTableclient.GetEntityAsync<TableEntity>(PartitionKeyValue, entitiesToCreate[1].RowKey).ConfigureAwait(false), Throws.InstanceOf<RequestFailedException>().And.Property("Status").EqualTo((int)HttpStatusCode.NotFound)); // Validate that we are able to fetch the entity with the client with full access. Assert.That(async () => await client.GetEntityAsync<TableEntity>(PartitionKeyValue, entitiesToCreate[1].RowKey).ConfigureAwait(false), Throws.Nothing); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] [TestCase(null)] [TestCase(5)] public async Task CreatedEntitiesCanBeQueriedWithAndWithoutPagination(int? pageCount) { List<TableEntity> entityResults; List<TableEntity> entitiesToCreate = CreateTableEntities(PartitionKeyValue, 20); // Create the new entities. await CreateTestEntities(entitiesToCreate).ConfigureAwait(false); // Query the entities. entityResults = await client.QueryAsync<TableEntity>(maxPerPage: pageCount).ToEnumerableAsync().ConfigureAwait(false); Assert.That(entityResults.Count, Is.EqualTo(entitiesToCreate.Count), "The entity result count should match the created count"); entityResults.Clear(); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CreatedDynamicEntitiesCanBeQueriedWithFilters() { List<TableEntity> entityResults; List<TableEntity> entitiesToCreate = CreateDictionaryTableEntities(PartitionKeyValue, 20); // Create the new entities. foreach (var entity in entitiesToCreate) { await client.AddEntityAsync(entity).ConfigureAwait(false); } // Query the entities with a filter specifying that to RowKey value must be greater than or equal to '10'. entityResults = await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey gt '10'").ToEnumerableAsync().ConfigureAwait(false); Assert.That(entityResults.Count, Is.EqualTo(10), "The entity result count should be 10"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CreatedEntitiesCanBeQueriedWithFilters() { List<TableEntity> entityResults; List<TableEntity> entitiesToCreate = CreateTableEntities(PartitionKeyValue, 20); // Create the new entities. await CreateTestEntities(entitiesToCreate).ConfigureAwait(false); // Query the entities with a filter specifying that to RowKey value must be greater than or equal to '10'. entityResults = await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey gt '10'").ToEnumerableAsync().ConfigureAwait(false); Assert.That(entityResults.Count, Is.EqualTo(10), "The entity result count should be 10"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task EntityCanBeUpserted() { string tableName = $"testtable{Recording.GenerateId()}"; const string rowKeyValue = "1"; const string propertyName = "SomeStringProperty"; const string originalValue = "This is the original"; const string updatedValue = "This is new and improved!"; var entity = new TableEntity { {"PartitionKey", PartitionKeyValue}, {"RowKey", rowKeyValue}, {propertyName, originalValue} }; // Create the new entity. await client.UpsertEntityAsync(entity, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the created entity from the service. var entityToUpdate = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); entityToUpdate[propertyName] = updatedValue; await client.UpsertEntityAsync(entityToUpdate, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the updated entity from the service. var updatedEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue), $"The property value should be {updatedValue}"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task EntityUpdateRespectsEtag() { string tableName = $"testtable{Recording.GenerateId()}"; const string rowKeyValue = "1"; const string propertyName = "SomeStringProperty"; const string originalValue = "This is the original"; const string updatedValue = "This is new and improved!"; const string updatedValue2 = "This changed due to a matching Etag"; var entity = new TableEntity { {"PartitionKey", PartitionKeyValue}, {"RowKey", rowKeyValue}, {propertyName, originalValue} }; // Create the new entity. await client.UpsertEntityAsync(entity, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the created entity from the service. var originalEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); originalEntity[propertyName] = updatedValue; // Use a wildcard ETag to update unconditionally. await client.UpdateEntityAsync(originalEntity, ETag.All, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the updated entity from the service. var updatedEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue), $"The property value should be {updatedValue}"); updatedEntity[propertyName] = updatedValue2; // Use a non-matching ETag. Assert.That(async () => await client.UpdateEntityAsync(updatedEntity, originalEntity.ETag, TableUpdateMode.Replace).ConfigureAwait(false), Throws.InstanceOf<RequestFailedException>()); // Use a matching ETag. await client.UpdateEntityAsync(updatedEntity, updatedEntity.ETag, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the newly updated entity from the service. updatedEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue2), $"The property value should be {updatedValue2}"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task EntityMergeRespectsEtag() { string tableName = $"testtable{Recording.GenerateId()}"; const string rowKeyValue = "1"; const string propertyName = "SomeStringProperty"; const string originalValue = "This is the original"; const string updatedValue = "This is new and improved!"; const string updatedValue2 = "This changed due to a matching Etag"; var entity = new TableEntity { {"PartitionKey", PartitionKeyValue}, {"RowKey", rowKeyValue}, {propertyName, originalValue} }; // Create the new entity. await client.UpsertEntityAsync(entity, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the created entity from the service. var originalEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); originalEntity[propertyName] = updatedValue; // Use a wildcard ETag to update unconditionally. await client.UpdateEntityAsync(originalEntity, ETag.All, TableUpdateMode.Merge).ConfigureAwait(false); // Fetch the updated entity from the service. var updatedEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue), $"The property value should be {updatedValue}"); updatedEntity[propertyName] = updatedValue2; // Use a non-matching ETag. Assert.That(async () => await client.UpdateEntityAsync(updatedEntity, originalEntity.ETag, TableUpdateMode.Merge).ConfigureAwait(false), Throws.InstanceOf<RequestFailedException>()); // Use a matching ETag. await client.UpdateEntityAsync(updatedEntity, updatedEntity.ETag, TableUpdateMode.Merge).ConfigureAwait(false); // Fetch the newly updated entity from the service. updatedEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue2), $"The property value should be {updatedValue2}"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task EntityMergeDoesPartialPropertyUpdates() { string tableName = $"testtable{Recording.GenerateId()}"; const string rowKeyValue = "1"; const string propertyName = "SomeStringProperty"; const string mergepropertyName = "MergedProperty"; const string originalValue = "This is the original"; const string mergeValue = "This was merged!"; const string mergeUpdatedValue = "merged value was updated!"; var entity = new TableEntity { {"PartitionKey", PartitionKeyValue}, {"RowKey", rowKeyValue}, {propertyName, originalValue} }; var partialEntity = new TableEntity { {"PartitionKey", PartitionKeyValue}, {"RowKey", rowKeyValue}, {mergepropertyName, mergeValue} }; // Create the new entity. await client.UpsertEntityAsync(entity, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the created entity from the service. var originalEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); // Verify that the merge property does not yet exist yet and that the original property does exist. Assert.That(originalEntity.TryGetValue(mergepropertyName, out var _), Is.False); Assert.That(originalEntity[propertyName], Is.EqualTo(originalValue)); await client.UpsertEntityAsync(partialEntity, TableUpdateMode.Merge).ConfigureAwait(false); // Fetch the updated entity from the service. var mergedEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); // Verify that the merge property does not yet exist yet and that the original property does exist. Assert.That(mergedEntity[mergepropertyName], Is.EqualTo(mergeValue)); Assert.That(mergedEntity[propertyName], Is.EqualTo(originalValue)); // Update just the merged value. partialEntity[mergepropertyName] = mergeUpdatedValue; await client.UpsertEntityAsync(partialEntity, TableUpdateMode.Merge).ConfigureAwait(false); // Fetch the updated entity from the service. mergedEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); // Verify that the merge property does not yet exist yet and that the original property does exist. Assert.That(mergedEntity[mergepropertyName], Is.EqualTo(mergeUpdatedValue)); Assert.That(mergedEntity[propertyName], Is.EqualTo(originalValue)); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task EntityDeleteRespectsEtag() { string tableName = $"testtable{Recording.GenerateId()}"; const string rowKeyValue = "1"; const string propertyName = "SomeStringProperty"; const string originalValue = "This is the original"; var entity = new TableEntity { {"PartitionKey", PartitionKeyValue}, {"RowKey", rowKeyValue}, {propertyName, originalValue} }; // Create the new entity. await client.UpsertEntityAsync(entity, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the created entity from the service. var originalEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); var staleEtag = originalEntity.ETag; // Use a wildcard ETag to delete unconditionally. await client.DeleteEntityAsync(PartitionKeyValue, rowKeyValue).ConfigureAwait(false); // Validate that the entity is deleted. var emptyresult = await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false); Assert.That(emptyresult, Is.Empty, $"The query should have returned no results."); // Create the new entity again. await client.UpsertEntityAsync(entity, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the created entity from the service. originalEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); // Use a non-matching ETag. Assert.That(async () => await client.DeleteEntityAsync(PartitionKeyValue, rowKeyValue, staleEtag).ConfigureAwait(false), Throws.InstanceOf<RequestFailedException>()); // Use a matching ETag. await client.DeleteEntityAsync(PartitionKeyValue, rowKeyValue, originalEntity.ETag).ConfigureAwait(false); // Validate that the entity is deleted. emptyresult = await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false); Assert.That(emptyresult, Is.Empty, $"The query should have returned no results."); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CreatedEntitiesAreRoundtrippedWithProperOdataAnnoations() { List<TableEntity> entityResults; List<TableEntity> entitiesToCreate = CreateTableEntities(PartitionKeyValue, 1); // Create the new entities. await CreateTestEntities(entitiesToCreate).ConfigureAwait(false); // Query the entities with a filter specifying that to RowKey value must be greater than or equal to '10'. entityResults = await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '01'").ToEnumerableAsync().ConfigureAwait(false); Assert.That(entityResults.First().PartitionKey, Is.TypeOf<string>(), "The entity property should be of type string"); Assert.That(entityResults.First().RowKey, Is.TypeOf<string>(), "The entity property should be of type string"); Assert.That(entityResults.First().Timestamp, Is.TypeOf<DateTimeOffset>(), "The entity property should be of type DateTimeOffset?"); Assert.That(entityResults.First().Timestamp, Is.Not.Null, "The entity property should not be null"); Assert.That(entityResults.First()[StringTypePropertyName], Is.TypeOf<string>(), "The entity property should be of type string"); Assert.That(entityResults.First()[DateTypePropertyName], Is.TypeOf<DateTimeOffset>(), "The entity property should be of type DateTime"); Assert.That(entityResults.First()[GuidTypePropertyName], Is.TypeOf<Guid>(), "The entity property should be of type Guid"); Assert.That(entityResults.First()[BinaryTypePropertyName], Is.TypeOf<byte[]>(), "The entity property should be of type byte[]"); Assert.That(entityResults.First()[Int64TypePropertyName], Is.TypeOf<long>(), "The entity property should be of type int64"); //TODO: Remove conditional after fixing https://github.com/Azure/azure-sdk-for-net/issues/13552 if (_endpointType != TableEndpointType.CosmosTable) { Assert.That(entityResults.First()[DoubleTypePropertyName], Is.TypeOf<double>(), "The entity property should be of type double"); } Assert.That(entityResults.First()[DoubleDecimalTypePropertyName], Is.TypeOf<double>(), "The entity property should be of type double"); Assert.That(entityResults.First()[IntTypePropertyName], Is.TypeOf<int>(), "The entity property should be of type int"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task UpsertedEntitiesAreRoundtrippedWithProperOdataAnnoations() { List<TableEntity> entityResults; List<TableEntity> entitiesToCreate = CreateTableEntities(PartitionKeyValue, 1); // Upsert the new entities. await UpsertTestEntities(entitiesToCreate, TableUpdateMode.Replace).ConfigureAwait(false); // Query the entities with a filter specifying that to RowKey value must be greater than or equal to '10'. entityResults = await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '01'").ToEnumerableAsync().ConfigureAwait(false); Assert.That(entityResults.First()[StringTypePropertyName], Is.TypeOf<string>(), "The entity property should be of type string"); Assert.That(entityResults.First()[DateTypePropertyName], Is.TypeOf<DateTimeOffset>(), "The entity property should be of type DateTime"); Assert.That(entityResults.First()[GuidTypePropertyName], Is.TypeOf<Guid>(), "The entity property should be of type Guid"); Assert.That(entityResults.First()[BinaryTypePropertyName], Is.TypeOf<byte[]>(), "The entity property should be of type byte[]"); Assert.That(entityResults.First()[Int64TypePropertyName], Is.TypeOf<long>(), "The entity property should be of type int64"); //TODO: Remove conditional after fixing https://github.com/Azure/azure-sdk-for-net/issues/13552 if (_endpointType != TableEndpointType.CosmosTable) { Assert.That(entityResults.First()[DoubleTypePropertyName], Is.TypeOf<double>(), "The entity property should be of type double"); } Assert.That(entityResults.First()[DoubleDecimalTypePropertyName], Is.TypeOf<double>(), "The entity property should be of type double"); Assert.That(entityResults.First()[IntTypePropertyName], Is.TypeOf<int>(), "The entity property should be of type int"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CreateEntityReturnsEntitiesWithoutOdataAnnoations() { TableEntity entityToCreate = CreateTableEntities(PartitionKeyValue, 1).First(); // Create an entity. await client.AddEntityAsync(entityToCreate).ConfigureAwait(false); TableEntity entity = await client.GetEntityAsync<TableEntity>(entityToCreate.PartitionKey, entityToCreate.RowKey).ConfigureAwait(false); Assert.That(entity.Keys.Count(k => k.EndsWith(TableConstants.Odata.OdataTypeString)), Is.Zero, "The entity should not containt any odata data annotation properties"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CreateEntityAllowsSelect() { TableEntity entityToCreate = CreateTableEntities(PartitionKeyValue, 1).First(); // Create an entity. await client.AddEntityAsync(entityToCreate).ConfigureAwait(false); TableEntity entity = await client.GetEntityAsync<TableEntity>(entityToCreate.PartitionKey, entityToCreate.RowKey, new[] { nameof(entityToCreate.Timestamp) }).ConfigureAwait(false); Assert.That(entity.PartitionKey, Is.Null, "The entity property should be null"); Assert.That(entity.RowKey, Is.Null, "The entity property should be null"); Assert.That(entity.Timestamp, Is.Not.Null, "The entity property should not be null"); Assert.That(entity.TryGetValue(StringTypePropertyName, out _), Is.False, "The entity property should not exist"); Assert.That(entity.TryGetValue(DateTypePropertyName, out _), Is.False, "The entity property should not exist"); Assert.That(entity.TryGetValue(GuidTypePropertyName, out _), Is.False, "The entity property should not exist"); Assert.That(entity.TryGetValue(BinaryTypePropertyName, out _), Is.False, "The entity property should not exist"); Assert.That(entity.TryGetValue(Int64TypePropertyName, out _), Is.False, "The entity property should not exist"); Assert.That(entity.TryGetValue(DoubleTypePropertyName, out _), Is.False, "The entity property should not exist"); Assert.That(entity.TryGetValue(DoubleDecimalTypePropertyName, out _), Is.False, "The entity property should not exist"); Assert.That(entity.TryGetValue(IntTypePropertyName, out _), Is.False, "The entity property should not exist"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task QueryReturnsEntitiesWithoutOdataAnnoations() { List<TableEntity> entityResults; List<TableEntity> entitiesToCreate = CreateTableEntities(PartitionKeyValue, 1); // Upsert the new entities. await UpsertTestEntities(entitiesToCreate, TableUpdateMode.Replace).ConfigureAwait(false); // Query the entities with a filter specifying that to RowKey value must be greater than or equal to '10'. entityResults = await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '01'").ToEnumerableAsync().ConfigureAwait(false); Assert.That(entityResults.First().Keys.Count(k => k.EndsWith(TableConstants.Odata.OdataTypeString)), Is.Zero, "The entity should not containt any odata data annotation properties"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] [TestCase(null)] [TestCase(5)] public async Task CreatedCustomEntitiesCanBeQueriedWithAndWithoutPagination(int? pageCount) { List<TestEntity> entityResults; var entitiesToCreate = CreateCustomTableEntities(PartitionKeyValue, 20); // Create the new entities. await CreateTestEntities(entitiesToCreate).ConfigureAwait(false); // Query the entities. entityResults = await client.QueryAsync<TestEntity>(maxPerPage: pageCount).ToEnumerableAsync().ConfigureAwait(false); Assert.That(entityResults.Count, Is.EqualTo(entitiesToCreate.Count), "The entity result count should match the created count"); entityResults.Clear(); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CreatedCustomEntitiesCanBeQueriedWithFilters() { List<TestEntity> entityResults; var entitiesToCreate = CreateCustomTableEntities(PartitionKeyValue, 20); // Create the new entities. await CreateTestEntities(entitiesToCreate).ConfigureAwait(false); // Query the entities with a filter specifying that to RowKey value must be greater than or equal to '10'. entityResults = await client.QueryAsync<TestEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey gt '10'").ToEnumerableAsync().ConfigureAwait(false); Assert.That(entityResults.Count, Is.EqualTo(10), "The entity result count should be 10"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CustomEntityCanBeUpserted() { string tableName = $"testtable{Recording.GenerateId()}"; const string rowKeyValue = "1"; const string propertyName = "SomeStringProperty"; const string originalValue = "This is the original"; const string updatedValue = "This is new and improved!"; var entity = new SimpleTestEntity { PartitionKey = PartitionKeyValue, RowKey = rowKeyValue, StringTypeProperty = originalValue, }; // Create the new entity. await client.UpsertEntityAsync(entity, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the created entity from the service. var entityToUpdate = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); entityToUpdate[propertyName] = updatedValue; await client.UpsertEntityAsync(entityToUpdate, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the updated entity from the service. var updatedEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue), $"The property value should be {updatedValue}"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CustomEntityUpdateRespectsEtag() { string tableName = $"testtable{Recording.GenerateId()}"; const string rowKeyValue = "1"; const string propertyName = "SomeStringProperty"; const string originalValue = "This is the original"; const string updatedValue = "This is new and improved!"; const string updatedValue2 = "This changed due to a matching Etag"; var entity = new SimpleTestEntity { PartitionKey = PartitionKeyValue, RowKey = rowKeyValue, StringTypeProperty = originalValue, }; // Create the new entity. await client.UpsertEntityAsync(entity, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the created entity from the service. var originalEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); originalEntity[propertyName] = updatedValue; // Use a wildcard ETag to update unconditionally. await client.UpdateEntityAsync(originalEntity, ETag.All, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the updated entity from the service. var updatedEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue), $"The property value should be {updatedValue}"); updatedEntity[propertyName] = updatedValue2; // Use a non-matching ETag. Assert.That(async () => await client.UpdateEntityAsync(updatedEntity, originalEntity.ETag, TableUpdateMode.Replace).ConfigureAwait(false), Throws.InstanceOf<RequestFailedException>()); // Use a matching ETag. await client.UpdateEntityAsync(updatedEntity, updatedEntity.ETag, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the newly updated entity from the service. updatedEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue2), $"The property value should be {updatedValue2}"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CustomEntityMergeRespectsEtag() { string tableName = $"testtable{Recording.GenerateId()}"; const string rowKeyValue = "1"; const string propertyName = "SomeStringProperty"; const string originalValue = "This is the original"; const string updatedValue = "This is new and improved!"; const string updatedValue2 = "This changed due to a matching Etag"; var entity = new SimpleTestEntity { PartitionKey = PartitionKeyValue, RowKey = rowKeyValue, StringTypeProperty = originalValue, }; // Create the new entity. await client.UpsertEntityAsync(entity, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the created entity from the service. var originalEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); originalEntity[propertyName] = updatedValue; // Use a wildcard ETag to update unconditionally. await client.UpdateEntityAsync(originalEntity, ETag.All, TableUpdateMode.Merge).ConfigureAwait(false); // Fetch the updated entity from the service. var updatedEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue), $"The property value should be {updatedValue}"); updatedEntity[propertyName] = updatedValue2; // Use a non-matching ETag. Assert.That(async () => await client.UpdateEntityAsync(updatedEntity, originalEntity.ETag, TableUpdateMode.Merge).ConfigureAwait(false), Throws.InstanceOf<RequestFailedException>()); // Use a matching ETag. await client.UpdateEntityAsync(updatedEntity, updatedEntity.ETag, TableUpdateMode.Merge).ConfigureAwait(false); // Fetch the newly updated entity from the service. updatedEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); Assert.That(updatedEntity[propertyName], Is.EqualTo(updatedValue2), $"The property value should be {updatedValue2}"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CustomEntityDeleteRespectsEtag() { string tableName = $"testtable{Recording.GenerateId()}"; const string rowKeyValue = "1"; const string originalValue = "This is the original"; var entity = new SimpleTestEntity { PartitionKey = PartitionKeyValue, RowKey = rowKeyValue, StringTypeProperty = originalValue, }; // Create the new entity. await client.UpsertEntityAsync(entity, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the created entity from the service. var originalEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); var staleEtag = originalEntity.ETag; // Use a wildcard ETag to delete unconditionally. await client.DeleteEntityAsync(PartitionKeyValue, rowKeyValue).ConfigureAwait(false); // Validate that the entity is deleted. var emptyresult = await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false); Assert.That(emptyresult, Is.Empty, $"The query should have returned no results."); // Create the new entity again. await client.UpsertEntityAsync(entity, TableUpdateMode.Replace).ConfigureAwait(false); // Fetch the created entity from the service. originalEntity = (await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false)).Single(); // Use a non-matching ETag. Assert.That(async () => await client.DeleteEntityAsync(PartitionKeyValue, rowKeyValue, staleEtag).ConfigureAwait(false), Throws.InstanceOf<RequestFailedException>()); // Use a matching ETag. await client.DeleteEntityAsync(PartitionKeyValue, rowKeyValue, originalEntity.ETag).ConfigureAwait(false); // Validate that the entity is deleted. emptyresult = await client.QueryAsync<TableEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '{rowKeyValue}'").ToEnumerableAsync().ConfigureAwait(false); Assert.That(emptyresult, Is.Empty, $"The query should have returned no results."); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CreatedCustomEntitiesAreRoundtrippedProprly() { List<TestEntity> entityResults; var entitiesToCreate = CreateCustomTableEntities(PartitionKeyValue, 1); // Create the new entities. foreach (var entity in entitiesToCreate) { await client.AddEntityAsync(entity).ConfigureAwait(false); } // Query the entities with a filter specifying that to RowKey value must be greater than or equal to '10'. entityResults = await client.QueryAsync<TestEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '01'").ToEnumerableAsync().ConfigureAwait(false); entityResults.Sort((first, second) => first.IntTypeProperty.CompareTo(second.IntTypeProperty)); for (int i = 0; i < entityResults.Count; i++) { Assert.That(entityResults[i].BinaryTypeProperty, Is.EqualTo(entitiesToCreate[i].BinaryTypeProperty), "The entities should be equivalent"); Assert.That(entityResults[i].DatetimeOffsetTypeProperty, Is.EqualTo(entitiesToCreate[i].DatetimeOffsetTypeProperty), "The entities should be equivalent"); Assert.That(entityResults[i].DatetimeTypeProperty, Is.EqualTo(entitiesToCreate[i].DatetimeTypeProperty), "The entities should be equivalent"); Assert.That(entityResults[i].DoubleTypeProperty, Is.EqualTo(entitiesToCreate[i].DoubleTypeProperty), "The entities should be equivalent"); Assert.That(entityResults[i].GuidTypeProperty, Is.EqualTo(entitiesToCreate[i].GuidTypeProperty), "The entities should be equivalent"); Assert.That(entityResults[i].Int64TypeProperty, Is.EqualTo(entitiesToCreate[i].Int64TypeProperty), "The entities should be equivalent"); Assert.That(entityResults[i].IntTypeProperty, Is.EqualTo(entitiesToCreate[i].IntTypeProperty), "The entities should be equivalent"); Assert.That(entityResults[i].PartitionKey, Is.EqualTo(entitiesToCreate[i].PartitionKey), "The entities should be equivalent"); Assert.That(entityResults[i].RowKey, Is.EqualTo(entitiesToCreate[i].RowKey), "The entities should be equivalent"); Assert.That(entityResults[i].StringTypeProperty, Is.EqualTo(entitiesToCreate[i].StringTypeProperty), "The entities should be equivalent"); Assert.That(entityResults[i].ETag, Is.Not.EqualTo(default(ETag)), $"ETag value should not be default: {entityResults[i].ETag}"); } } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task CreatedEnumEntitiesAreRoundtrippedProperly() { List<EnumEntity> entityResults; var entitiesToCreate = new[] { new EnumEntity{ PartitionKey = PartitionKeyValue, RowKey = "01", MyFoo = Foo.Two} }; // Create the new entities. foreach (var entity in entitiesToCreate) { await client.AddEntityAsync(entity).ConfigureAwait(false); } // Query the entities with a filter specifying that to RowKey value must be greater than or equal to '10'. entityResults = await client.QueryAsync<EnumEntity>(filter: $"PartitionKey eq '{PartitionKeyValue}' and RowKey eq '01'").ToEnumerableAsync().ConfigureAwait(false); for (int i = 0; i < entityResults.Count; i++) { Assert.That(entityResults[i].PartitionKey, Is.EqualTo(entitiesToCreate[i].PartitionKey), "The entities should be equivalent"); Assert.That(entityResults[i].RowKey, Is.EqualTo(entitiesToCreate[i].RowKey), "The entities should be equivalent"); Assert.That(entityResults[i].MyFoo, Is.EqualTo(entitiesToCreate[i].MyFoo), "The entities should be equivalent"); } } /// <summary> /// Validates the functionality of the TableServiceClient. /// </summary> [RecordedTest] public async Task GetAccessPoliciesReturnsPolicies() { // Create some policies. var policyToCreate = new List<SignedIdentifier> { new SignedIdentifier("MyPolicy", new TableAccessPolicy(new DateTime(2020, 1,1,1,1,0,DateTimeKind.Utc), new DateTime(2021, 1,1,1,1,0,DateTimeKind.Utc), "r")) }; await client.SetAccessPolicyAsync(tableAcl: policyToCreate); // Get the created policy. var policies = await client.GetAccessPolicyAsync(); Assert.That(policies.Value[0].Id, Is.EqualTo(policyToCreate[0].Id)); Assert.That(policies.Value[0].AccessPolicy.ExpiresOn, Is.EqualTo(policyToCreate[0].AccessPolicy.ExpiresOn)); Assert.That(policies.Value[0].AccessPolicy.Permission, Is.EqualTo(policyToCreate[0].AccessPolicy.Permission)); Assert.That(policies.Value[0].AccessPolicy.StartsOn, Is.EqualTo(policyToCreate[0].AccessPolicy.StartsOn)); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task GetEntityReturnsSingleEntity() { TableEntity entityResults; List<TableEntity> entitiesToCreate = CreateTableEntities(PartitionKeyValue, 1); // Upsert the new entities. await UpsertTestEntities(entitiesToCreate, TableUpdateMode.Replace).ConfigureAwait(false); // Get the single entity by PartitionKey and RowKey. entityResults = (await client.GetEntityAsync<TableEntity>(PartitionKeyValue, "01").ConfigureAwait(false)).Value; Assert.That(entityResults, Is.Not.Null, "The entity should not be null."); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task BatchInsert() { var entitiesToCreate = CreateCustomTableEntities(PartitionKeyValue, 5); // Create the batch. var batch = InstrumentClient(client.CreateTransactionalBatch(entitiesToCreate[0].PartitionKey)); batch.SetBatchGuids(Recording.Random.NewGuid(), Recording.Random.NewGuid()); // Add the entities to the batch. batch.AddEntities(entitiesToCreate); TableBatchResponse response = await batch.SubmitBatchAsync().ConfigureAwait(false); foreach (var entity in entitiesToCreate) { Assert.That(response.GetResponseForEntity(entity.RowKey).Status, Is.EqualTo((int)HttpStatusCode.NoContent)); } Assert.That(response.ResponseCount, Is.EqualTo(entitiesToCreate.Count)); // Query the entities. var entityResults = await client.QueryAsync<TestEntity>().ToEnumerableAsync().ConfigureAwait(false); Assert.That(entityResults.Count, Is.EqualTo(entitiesToCreate.Count), "The entity result count should match the created count"); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task BatchInsertAndMergeAndDelete() { const string updatedString = "the string was updated!"; var entitiesToCreate = CreateCustomTableEntities(PartitionKeyValue, 5); // Add just the first three entities await client.AddEntityAsync(entitiesToCreate[0]).ConfigureAwait(false); await client.AddEntityAsync(entitiesToCreate[1]).ConfigureAwait(false); await client.AddEntityAsync(entitiesToCreate[2]).ConfigureAwait(false); // Create the batch. TableTransactionalBatch batch = InstrumentClient(client.CreateTransactionalBatch(PartitionKeyValue)); batch.SetBatchGuids(Recording.Random.NewGuid(), Recording.Random.NewGuid()); // Add a Merge operation to the entity we are adding. var mergeEntity = new TableEntity(PartitionKeyValue, entitiesToCreate[0].RowKey); mergeEntity.Add("MergedProperty", "foo"); batch.UpdateEntity(mergeEntity, ETag.All, TableUpdateMode.Merge); // Add a Delete operation. var entityToDelete = entitiesToCreate[1]; batch.DeleteEntity(entityToDelete.RowKey, ETag.All); // Add an Upsert operation to replace the entity with an updated value. entitiesToCreate[2].StringTypeProperty = updatedString; batch.UpsertEntity(entitiesToCreate[2], TableUpdateMode.Replace); // Add an Upsert operation to add an entity. batch.UpsertEntity(entitiesToCreate[3], TableUpdateMode.Replace); // Add the last entity. batch.AddEntity(entitiesToCreate.Last()); // Submit the batch. TableBatchResponse response = await batch.SubmitBatchAsync().ConfigureAwait(false); // Validate that the batch throws if we try to send it again. Assert.ThrowsAsync<InvalidOperationException>(() => batch.SubmitBatchAsync()); // Validate that adding more operations to the batch throws. Assert.Throws<InvalidOperationException>(() => batch.AddEntity(new TableEntity())); foreach (var entity in entitiesToCreate) { Assert.That(response.GetResponseForEntity(entity.RowKey).Status, Is.EqualTo((int)HttpStatusCode.NoContent)); } Assert.That(response.ResponseCount, Is.EqualTo(entitiesToCreate.Count)); // Query the entities. var entityResults = await client.QueryAsync<TableEntity>().ToEnumerableAsync().ConfigureAwait(false); Assert.That(entityResults.Count, Is.EqualTo(entitiesToCreate.Count - 1), "The entity result count should match the created count minus the deleted count."); Assert.That(entityResults.Single(e => e.RowKey == entitiesToCreate[0].RowKey).ContainsKey("StringTypeProperty"), "The merged entity result should still contain StringTypeProperty."); Assert.That(entityResults.Single(e => e.RowKey == entitiesToCreate[0].RowKey)["MergedProperty"], Is.EqualTo("foo"), "The merged entity should have merged the value of MergedProperty."); Assert.That(entityResults.Single(e => e.RowKey == entitiesToCreate[2].RowKey)["StringTypeProperty"], Is.EqualTo(updatedString), "The entity result property should have been updated."); } /// <summary> /// Validates the functionality of the TableClient. /// </summary> [RecordedTest] public async Task BatchError() { var entitiesToCreate = CreateCustomTableEntities(PartitionKeyValue, 4); // Create the batch. var batch = InstrumentClient(client.CreateTransactionalBatch(entitiesToCreate[0].PartitionKey)); batch.SetBatchGuids(Recording.Random.NewGuid(), Recording.Random.NewGuid()); // Add the last entity to the table prior to adding it as part of the batch to cause a batch failure. await client.AddEntityAsync(entitiesToCreate.Last()); // Add the entities to the batch batch.AddEntities(entitiesToCreate); try { TableBatchResponse response = await batch.SubmitBatchAsync().ConfigureAwait(false); } catch (RequestFailedException ex) { Assert.That(ex.Status == (int)HttpStatusCode.Conflict, $"Status should be {HttpStatusCode.Conflict}"); Assert.That(ex.Message, Is.Not.Null, "Message should not be null"); Assert.That(batch.TryGetFailedEntityFromException(ex, out ITableEntity failedEntity), Is.True); Assert.That(failedEntity.RowKey, Is.EqualTo(entitiesToCreate.Last().RowKey)); Assert.That(ex.Message.Contains(nameof(TableTransactionalBatch.TryGetFailedEntityFromException))); } } } }
// 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.ComponentModel; using System.Runtime.InteropServices; using System.Threading; using System.Linq; using Xunit; using System.Threading.Tasks; namespace System.Diagnostics.Tests { public class ProcessThreadTests : ProcessTestBase { [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestCommonPriorityAndTimeProperties() { CreateDefaultProcess(); ProcessThreadCollection threadCollection = _process.Threads; Assert.True(threadCollection.Count > 0); ProcessThread thread = threadCollection[0]; try { if (ThreadState.Terminated != thread.ThreadState) { // On OSX, thread id is a 64bit unsigned value. We truncate the ulong to int // due to .NET API surface area. Hence, on overflow id can be negative while // casting the ulong to int. Assert.True(thread.Id >= 0 || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)); Assert.Equal(_process.BasePriority, thread.BasePriority); Assert.True(thread.CurrentPriority >= 0); Assert.True(thread.PrivilegedProcessorTime.TotalSeconds >= 0); Assert.True(thread.UserProcessorTime.TotalSeconds >= 0); Assert.True(thread.TotalProcessorTime.TotalSeconds >= 0); } } catch (Exception e) when (e is Win32Exception || e is InvalidOperationException) { // Win32Exception is thrown when getting threadinfo fails, or // InvalidOperationException if it fails because the thread already exited. } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestThreadCount() { int numOfThreads = 10; CountdownEvent counter = new CountdownEvent(numOfThreads); ManualResetEventSlim mre = new ManualResetEventSlim(); for (int i = 0; i < numOfThreads; i++) { new Thread(() => { counter.Signal(); mre.Wait(); }) { IsBackground = true }.Start(); } counter.Wait(); try { Assert.True(Process.GetCurrentProcess().Threads.Count >= numOfThreads); } finally { mre.Set(); } } [Fact] [PlatformSpecific(TestPlatforms.OSX|TestPlatforms.FreeBSD)] // OSX and FreeBSD throw PNSE from StartTime public void TestStartTimeProperty_OSX() { using (Process p = Process.GetCurrentProcess()) { ProcessThreadCollection threads = p.Threads; Assert.NotNull(threads); Assert.NotEmpty(threads); ProcessThread thread = threads[0]; Assert.NotNull(thread); Assert.Throws<PlatformNotSupportedException>(() => thread.StartTime); } } [Fact] [PlatformSpecific(TestPlatforms.Linux|TestPlatforms.Windows)] // OSX and FreeBSD throw PNSE from StartTime [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public async Task TestStartTimeProperty() { TimeSpan allowedWindow = TimeSpan.FromSeconds(1); using (Process p = Process.GetCurrentProcess()) { // Get the process' start time DateTime startTime = p.StartTime.ToUniversalTime(); // Get the process' threads ProcessThreadCollection threads = p.Threads; Assert.NotNull(threads); Assert.NotEmpty(threads); // Get the current time DateTime curTime = DateTime.UtcNow; // Make sure each thread's start time is at least the process' // start time and not beyond the current time. int passed = 0; foreach (ProcessThread t in threads.Cast<ProcessThread>()) { try { Assert.InRange(t.StartTime.ToUniversalTime(), startTime - allowedWindow, curTime + allowedWindow); passed++; } catch (InvalidOperationException) { // The thread may have gone away between our getting its info and attempting to access its StartTime } } Assert.True(passed > 0, "Expected at least one thread to be valid for StartTime"); // Now add a thread, and from that thread, while it's still alive, verify // that there's at least one thread greater than the current time we previously grabbed. await Task.Factory.StartNew(() => { p.Refresh(); try { Assert.Contains(p.Threads.Cast<ProcessThread>(), t => t.StartTime.ToUniversalTime() >= curTime - allowedWindow); } catch (InvalidOperationException) { // A thread may have gone away between our getting its info and attempting to access its StartTime } }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestStartAddressProperty() { using (Process p = Process.GetCurrentProcess()) { ProcessThreadCollection threads = p.Threads; Assert.NotNull(threads); Assert.NotEmpty(threads); IntPtr startAddress = threads[0].StartAddress; // There's nothing we can really validate about StartAddress, other than that we can get its value // without throwing. All values (even zero) are valid on all platforms. } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestPriorityLevelProperty() { CreateDefaultProcess(); ProcessThread thread = _process.Threads[0]; if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { Assert.Throws<PlatformNotSupportedException>(() => thread.PriorityLevel); Assert.Throws<PlatformNotSupportedException>(() => thread.PriorityLevel = ThreadPriorityLevel.AboveNormal); return; } ThreadPriorityLevel originalPriority = thread.PriorityLevel; if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { Assert.Throws<PlatformNotSupportedException>(() => thread.PriorityLevel = ThreadPriorityLevel.AboveNormal); return; } if (RuntimeInformation.IsOSPlatform(OSPlatform.Create("FREEBSD"))) { Assert.Throws<PlatformNotSupportedException>(() => thread.PriorityLevel = ThreadPriorityLevel.AboveNormal); return; } try { thread.PriorityLevel = ThreadPriorityLevel.AboveNormal; Assert.Equal(ThreadPriorityLevel.AboveNormal, thread.PriorityLevel); } finally { thread.PriorityLevel = originalPriority; Assert.Equal(originalPriority, thread.PriorityLevel); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void TestThreadStateProperty() { CreateDefaultProcess(); ProcessThread thread = _process.Threads[0]; if (ThreadState.Wait != thread.ThreadState) { Assert.Throws<InvalidOperationException>(() => thread.WaitReason); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Retrieving information about local processes is not supported on uap")] public void Threads_GetMultipleTimes_ReturnsSameInstance() { CreateDefaultProcess(); Assert.Same(_process.Threads, _process.Threads); } [Fact] public void Threads_GetNotStarted_ThrowsInvalidOperationException() { var process = new Process(); Assert.Throws<InvalidOperationException>(() => process.Threads); } } }
// 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.Security.Principal; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Http.Functional.Tests { using Configuration = System.Net.Test.Common.Configuration; [PlatformSpecific(TestPlatforms.Windows)] public abstract class DefaultCredentialsTest : HttpClientHandlerTestBase { private static bool DomainJoinedTestsEnabled => !string.IsNullOrEmpty(Configuration.Http.DomainJoinedHttpHost); private static bool DomainProxyTestsEnabled => !string.IsNullOrEmpty(Configuration.Http.DomainJoinedProxyHost); // Enable this to test against local HttpListener over loopback // Note this doesn't work as expected with WinHttpHandler, because WinHttpHandler will always authenticate the // current user against a loopback server using NTLM or Negotiate. private static bool LocalHttpListenerTestsEnabled = false; public static bool ServerAuthenticationTestsEnabled => (LocalHttpListenerTestsEnabled || DomainJoinedTestsEnabled); private static string s_specificUserName = Configuration.Security.ActiveDirectoryUserName; private static string s_specificPassword = Configuration.Security.ActiveDirectoryUserPassword; private static string s_specificDomain = Configuration.Security.ActiveDirectoryName; private readonly NetworkCredential _specificCredential = new NetworkCredential(s_specificUserName, s_specificPassword, s_specificDomain); private static Uri s_authenticatedServer = DomainJoinedTestsEnabled ? new Uri($"http://{Configuration.Http.DomainJoinedHttpHost}/test/auth/negotiate/showidentity.ashx") : null; public DefaultCredentialsTest(ITestOutputHelper output) : base(output) { } [OuterLoop("Uses external server")] [ConditionalTheory(nameof(ServerAuthenticationTestsEnabled))] [MemberData(nameof(AuthenticatedServers))] public async Task UseDefaultCredentials_DefaultValue_Unauthorized(string uri, bool useProxy) { HttpClientHandler handler = CreateHttpClientHandler(); handler.UseProxy = useProxy; using (HttpClient client = CreateHttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } [OuterLoop("Uses external server")] [ConditionalTheory(nameof(ServerAuthenticationTestsEnabled))] [MemberData(nameof(AuthenticatedServers))] public async Task UseDefaultCredentials_SetFalse_Unauthorized(string uri, bool useProxy) { HttpClientHandler handler = CreateHttpClientHandler(); handler.UseProxy = useProxy; handler.UseDefaultCredentials = false; using (HttpClient client = CreateHttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } [OuterLoop("Uses external server")] [ConditionalTheory(nameof(ServerAuthenticationTestsEnabled))] [MemberData(nameof(AuthenticatedServers))] public async Task UseDefaultCredentials_SetTrue_ConnectAsCurrentIdentity(string uri, bool useProxy) { HttpClientHandler handler = CreateHttpClientHandler(); handler.UseProxy = useProxy; handler.UseDefaultCredentials = true; using (HttpClient client = CreateHttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseBody = await response.Content.ReadAsStringAsync(); WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent(); _output.WriteLine("currentIdentity={0}", currentIdentity.Name); VerifyAuthentication(responseBody, true, currentIdentity.Name); } } [OuterLoop("Uses external server")] [ConditionalTheory(nameof(ServerAuthenticationTestsEnabled))] [MemberData(nameof(AuthenticatedServers))] public async Task Credentials_SetToWrappedDefaultCredential_ConnectAsCurrentIdentity(string uri, bool useProxy) { HttpClientHandler handler = CreateHttpClientHandler(); handler.UseProxy = useProxy; handler.Credentials = new CredentialWrapper { InnerCredentials = CredentialCache.DefaultCredentials }; using (HttpClient client = CreateHttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseBody = await response.Content.ReadAsStringAsync(); WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent(); _output.WriteLine("currentIdentity={0}", currentIdentity.Name); VerifyAuthentication(responseBody, true, currentIdentity.Name); } } [OuterLoop("Uses external server")] [ConditionalTheory(nameof(ServerAuthenticationTestsEnabled))] [MemberData(nameof(AuthenticatedServers))] public async Task Credentials_SetToBadCredential_Unauthorized(string uri, bool useProxy) { HttpClientHandler handler = CreateHttpClientHandler(); handler.UseProxy = useProxy; handler.Credentials = new NetworkCredential("notarealuser", "123456"); using (HttpClient client = CreateHttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode); } } [OuterLoop("Uses external server")] [ActiveIssue(10041)] [ConditionalTheory(nameof(DomainJoinedTestsEnabled))] [InlineData(false)] [InlineData(true)] public async Task Credentials_SetToSpecificCredential_ConnectAsSpecificIdentity(bool useProxy) { HttpClientHandler handler = CreateHttpClientHandler(); handler.UseProxy = useProxy; handler.UseDefaultCredentials = false; handler.Credentials = _specificCredential; using (HttpClient client = CreateHttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(s_authenticatedServer)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseBody = await response.Content.ReadAsStringAsync(); VerifyAuthentication(responseBody, true, s_specificDomain + "\\" + s_specificUserName); } } [OuterLoop("Uses external server")] [ActiveIssue(10041)] [ConditionalFact(nameof(DomainProxyTestsEnabled))] public async Task Proxy_UseAuthenticatedProxyWithNoCredentials_ProxyAuthenticationRequired() { HttpClientHandler handler = CreateHttpClientHandler(); handler.Proxy = new AuthenticatedProxy(null); using (HttpClient client = CreateHttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, response.StatusCode); } } [OuterLoop("Uses external server")] [ActiveIssue(10041)] [ConditionalFact(nameof(DomainProxyTestsEnabled))] public async Task Proxy_UseAuthenticatedProxyWithDefaultCredentials_OK() { HttpClientHandler handler = CreateHttpClientHandler(); handler.Proxy = new AuthenticatedProxy(CredentialCache.DefaultCredentials); using (HttpClient client = CreateHttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } [OuterLoop("Uses external server")] [ConditionalFact(nameof(DomainProxyTestsEnabled))] public async Task Proxy_UseAuthenticatedProxyWithWrappedDefaultCredentials_OK() { ICredentials wrappedCreds = new CredentialWrapper { InnerCredentials = CredentialCache.DefaultCredentials }; HttpClientHandler handler = CreateHttpClientHandler(); handler.Proxy = new AuthenticatedProxy(wrappedCreds); using (HttpClient client = CreateHttpClient(handler)) using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } public static IEnumerable<object[]> AuthenticatedServers() { // Note that localhost will not actually use the proxy, but there's no harm in testing it. foreach (bool b in new bool[] { true, false }) { if (LocalHttpListenerTestsEnabled) { yield return new object[] { HttpListenerAuthenticatedLoopbackServer.NtlmOnly.Uri, b }; yield return new object[] { HttpListenerAuthenticatedLoopbackServer.NegotiateOnly.Uri, b }; yield return new object[] { HttpListenerAuthenticatedLoopbackServer.NegotiateAndNtlm.Uri, b }; yield return new object[] { HttpListenerAuthenticatedLoopbackServer.BasicAndNtlm.Uri, b }; } if (!string.IsNullOrEmpty(Configuration.Http.DomainJoinedHttpHost)) { yield return new object[] { $"http://{Configuration.Http.DomainJoinedHttpHost}/test/auth/negotiate/showidentity.ashx", b }; yield return new object[] { $"http://{Configuration.Http.DomainJoinedHttpHost}/test/auth/multipleschemes/showidentity.ashx", b }; } } } private void VerifyAuthentication(string response, bool authenticated, string user) { // Convert all strings to lowercase to compare. Windows treats domain and username as case-insensitive. response = response.ToLower(); user = user.ToLower(); _output.WriteLine(response); if (!authenticated) { Assert.True( TestHelper.JsonMessageContainsKeyValue(response, "authenticated", "false"), "authenticated == false"); } else { Assert.True( TestHelper.JsonMessageContainsKeyValue(response, "authenticated", "true"), "authenticated == true"); Assert.True( TestHelper.JsonMessageContainsKeyValue(response, "user", user), $"user == {user}"); } } private class CredentialWrapper : ICredentials { public ICredentials InnerCredentials { get; set; } public NetworkCredential GetCredential(Uri uri, string authType) => InnerCredentials?.GetCredential(uri, authType); } private class AuthenticatedProxy : IWebProxy { ICredentials _credentials; Uri _proxyUri; public AuthenticatedProxy(ICredentials credentials) { _credentials = credentials; string host = Configuration.Http.DomainJoinedProxyHost; Assert.False(string.IsNullOrEmpty(host), "DomainJoinedProxyHost must specify proxy hostname"); string portString = Configuration.Http.DomainJoinedProxyPort; Assert.False(string.IsNullOrEmpty(portString), "DomainJoinedProxyPort must specify proxy port number"); int port; Assert.True(int.TryParse(portString, out port), "DomainJoinedProxyPort must be a valid port number"); _proxyUri = new Uri(string.Format("http://{0}:{1}", host, port)); } public ICredentials Credentials { get { return _credentials; } set { throw new NotImplementedException(); } } public Uri GetProxy(Uri destination) { return _proxyUri; } public bool IsBypassed(Uri host) { return false; } } private sealed class HttpListenerAuthenticatedLoopbackServer { private readonly HttpListener _listener; private readonly string _uri; public static readonly HttpListenerAuthenticatedLoopbackServer NtlmOnly = new HttpListenerAuthenticatedLoopbackServer("http://localhost:8080/", AuthenticationSchemes.Ntlm); public static readonly HttpListenerAuthenticatedLoopbackServer NegotiateOnly = new HttpListenerAuthenticatedLoopbackServer("http://localhost:8081/", AuthenticationSchemes.Negotiate); public static readonly HttpListenerAuthenticatedLoopbackServer NegotiateAndNtlm = new HttpListenerAuthenticatedLoopbackServer("http://localhost:8082/", AuthenticationSchemes.Negotiate | AuthenticationSchemes.Ntlm); public static readonly HttpListenerAuthenticatedLoopbackServer BasicAndNtlm = new HttpListenerAuthenticatedLoopbackServer("http://localhost:8083/", AuthenticationSchemes.Basic | AuthenticationSchemes.Ntlm); // Don't construct directly, use instances above private HttpListenerAuthenticatedLoopbackServer(string uri, AuthenticationSchemes authenticationSchemes) { _uri = uri; _listener = new HttpListener(); _listener.Prefixes.Add(uri); _listener.AuthenticationSchemes = authenticationSchemes; _listener.Start(); Task.Run(() => ProcessRequests()); } public string Uri => _uri; private async Task ProcessRequests() { while (true) { var context = await _listener.GetContextAsync(); // Send a response in the JSON format that the client expects string username = context.User.Identity.Name; await context.Response.OutputStream.WriteAsync(System.Text.Encoding.UTF8.GetBytes($"{{\"authenticated\": \"true\", \"user\": \"{username}\" }}")); context.Response.Close(); } } } } }
using System; using System.Collections.Generic; using Newtonsoft.Json; using UnityEngine; namespace GLTF.JsonExtensions { public static class JsonReaderExtensions { public static List<string> ReadStringList(this JsonReader reader) { if (reader.Read() && reader.TokenType != JsonToken.StartArray) { throw new Exception(string.Format("Invalid array at: {0}", reader.Path)); } var list = new List<string>(); while (reader.Read() && reader.TokenType != JsonToken.EndArray) { list.Add(reader.Value.ToString()); } return list; } public static List<double> ReadDoubleList(this JsonReader reader) { if (reader.Read() && reader.TokenType != JsonToken.StartArray) { throw new Exception(string.Format("Invalid array at: {0}", reader.Path)); } var list = new List<double>(); while (reader.Read() && reader.TokenType != JsonToken.EndArray) { list.Add(double.Parse(reader.Value.ToString())); } return list; } public static List<T> ReadList<T>(this JsonReader reader, Func<T> deserializerFunc) { if (reader.Read() && reader.TokenType != JsonToken.StartArray) { throw new Exception(string.Format("Invalid array at: {0}", reader.Path)); } var list = new List<T>(); while (reader.Read() && reader.TokenType != JsonToken.EndArray) { list.Add(deserializerFunc()); } return list; } public static Color ReadAsRGBAColor(this JsonReader reader) { if (reader.Read() && reader.TokenType != JsonToken.StartArray) { throw new Exception(string.Format("Invalid color value at: {0}", reader.Path)); } var color = new Color { r = (float) reader.ReadAsDouble().Value, g = (float) reader.ReadAsDouble().Value, b = (float) reader.ReadAsDouble().Value, a = (float) reader.ReadAsDouble().Value }; if (reader.Read() && reader.TokenType != JsonToken.EndArray) { throw new Exception(string.Format("Invalid color value at: {0}", reader.Path)); } return color; } public static Color ReadAsRGBColor(this JsonReader reader) { if (reader.Read() && reader.TokenType != JsonToken.StartArray) { throw new Exception(string.Format("Invalid vector value at: {0}", reader.Path)); } var color = new Color { r = (float) reader.ReadAsDouble().Value, g = (float) reader.ReadAsDouble().Value, b = (float) reader.ReadAsDouble().Value, a = 1.0f }; if (reader.Read() && reader.TokenType != JsonToken.EndArray) { throw new Exception(string.Format("Invalid color value at: {0}", reader.Path)); } return color; } public static Vector3 ReadAsVector3(this JsonReader reader) { if (reader.Read() && reader.TokenType != JsonToken.StartArray) { throw new Exception(string.Format("Invalid vector value at: {0}", reader.Path)); } var vector = new Vector3 { x = (float) reader.ReadAsDouble().Value, y = (float) reader.ReadAsDouble().Value, z = (float) reader.ReadAsDouble().Value }; if (reader.Read() && reader.TokenType != JsonToken.EndArray) { throw new Exception(string.Format("Invalid vector value at: {0}", reader.Path)); } return vector; } public static Quaternion ReadAsQuaternion(this JsonReader reader) { if (reader.Read() && reader.TokenType != JsonToken.StartArray) { throw new Exception(string.Format("Invalid vector value at: {0}", reader.Path)); } var quat = new Quaternion { x = (float) reader.ReadAsDouble().Value, y = (float) reader.ReadAsDouble().Value, z = (float) reader.ReadAsDouble().Value, w = (float) reader.ReadAsDouble().Value }; if (reader.Read() && reader.TokenType != JsonToken.EndArray) { throw new Exception(string.Format("Invalid vector value at: {0}", reader.Path)); } return quat; } public static Dictionary<string, T> ReadAsDictionary<T>(this JsonReader reader, Func<T> deserializerFunc) { if (reader.Read() && reader.TokenType != JsonToken.StartObject) { throw new Exception(string.Format("Dictionary must be an object at: {0}", reader.Path)); } var dict = new Dictionary<string, T>(); while (reader.Read() && reader.TokenType != JsonToken.EndObject) { dict.Add(reader.Value.ToString(), deserializerFunc()); } return dict; } public static Dictionary<string, object> ReadAsObjectDictionary(this JsonReader reader, bool skipStartObjectRead = false) { if (!skipStartObjectRead && reader.Read() && reader.TokenType != JsonToken.StartObject) { throw new Exception(string.Format("Dictionary must be an object at: {0}", reader.Path)); } var dict = new Dictionary<string, object>(); while (reader.Read() && reader.TokenType != JsonToken.EndObject) { dict.Add(reader.Value.ToString(), ReadDictionaryValue(reader)); } return dict; } private static object ReadDictionaryValue(JsonReader reader) { if (!reader.Read()) { return null; } switch (reader.TokenType) { case JsonToken.StartArray: return reader.ReadObjectList(); case JsonToken.StartObject: return reader.ReadAsObjectDictionary(true); default: return reader.Value; } } private static List<object> ReadObjectList(this JsonReader reader) { var list = new List<object>(); while (reader.Read() && reader.TokenType != JsonToken.EndArray) { list.Add(reader.Value); } return list; } public static T ReadStringEnum<T>(this JsonReader reader) { return (T) Enum.Parse(typeof(T), reader.ReadAsString()); } } }
using UnityEngine; namespace Pathfinding { /** Holds a coordinate in integers */ public struct Int3 { public int x; public int y; public int z; //These should be set to the same value (only PrecisionFactor should be 1 divided by Precision) /** Precision for the integer coordinates. * One world unit is divided into [value] pieces. A value of 1000 would mean millimeter precision, a value of 1 would mean meter precision (assuming 1 world unit = 1 meter). * This value affects the maximum coordinates for nodes as well as how large the cost values are for moving between two nodes. * A higher value means that you also have to set all penalty values to a higher value to compensate since the normal cost of moving will be higher. */ public const int Precision = 1000; /** #Precision as a float */ public const float FloatPrecision = 1000F; /** 1 divided by #Precision */ public const float PrecisionFactor = 0.001F; /* Factor to multiply cost with */ //public const float CostFactor = 0.01F; private static Int3 _zero = new Int3(0,0,0); public static Int3 zero { get { return _zero; } } public Int3 (Vector3 position) { x = (int)System.Math.Round (position.x*FloatPrecision); y = (int)System.Math.Round (position.y*FloatPrecision); z = (int)System.Math.Round (position.z*FloatPrecision); //x = Mathf.RoundToInt (position.x); //y = Mathf.RoundToInt (position.y); //z = Mathf.RoundToInt (position.z); } public Int3 (int _x, int _y, int _z) { x = _x; y = _y; z = _z; } public static bool operator == (Int3 lhs, Int3 rhs) { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z; } public static bool operator != (Int3 lhs, Int3 rhs) { return lhs.x != rhs.x || lhs.y != rhs.y || lhs.z != rhs.z; } public static explicit operator Int3 (Vector3 ob) { return new Int3 ( (int)System.Math.Round (ob.x*FloatPrecision), (int)System.Math.Round (ob.y*FloatPrecision), (int)System.Math.Round (ob.z*FloatPrecision) ); //return new Int3 (Mathf.RoundToInt (ob.x*FloatPrecision),Mathf.RoundToInt (ob.y*FloatPrecision),Mathf.RoundToInt (ob.z*FloatPrecision)); } public static explicit operator Vector3 (Int3 ob) { return new Vector3 (ob.x*PrecisionFactor,ob.y*PrecisionFactor,ob.z*PrecisionFactor); } public static Int3 operator - (Int3 lhs, Int3 rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; lhs.z -= rhs.z; return lhs; } public static Int3 operator - (Int3 lhs) { lhs.x = -lhs.x; lhs.y = -lhs.y; lhs.z = -lhs.z; return lhs; } public static Int3 operator + (Int3 lhs, Int3 rhs) { lhs.x += rhs.x; lhs.y += rhs.y; lhs.z += rhs.z; return lhs; } public static Int3 operator * (Int3 lhs, int rhs) { lhs.x *= rhs; lhs.y *= rhs; lhs.z *= rhs; return lhs; } public static Int3 operator * (Int3 lhs, float rhs) { lhs.x = (int)System.Math.Round (lhs.x * rhs); lhs.y = (int)System.Math.Round (lhs.y * rhs); lhs.z = (int)System.Math.Round (lhs.z * rhs); return lhs; } public static Int3 operator * (Int3 lhs, double rhs) { lhs.x = (int)System.Math.Round (lhs.x * rhs); lhs.y = (int)System.Math.Round (lhs.y * rhs); lhs.z = (int)System.Math.Round (lhs.z * rhs); return lhs; } public static Int3 operator * (Int3 lhs, Vector3 rhs) { lhs.x = (int)System.Math.Round (lhs.x * rhs.x); lhs.y = (int)System.Math.Round (lhs.y * rhs.y); lhs.z = (int)System.Math.Round (lhs.z * rhs.z); return lhs; } public static Int3 operator / (Int3 lhs, float rhs) { lhs.x = (int)System.Math.Round (lhs.x / rhs); lhs.y = (int)System.Math.Round (lhs.y / rhs); lhs.z = (int)System.Math.Round (lhs.z / rhs); return lhs; } public Int3 DivBy2 () { x >>= 1; y >>= 1; z >>= 1; return this; } public int this[int i] { get { return i == 0 ? x : (i == 1 ? y : z); } set { if (i == 0) x = value; else if (i == 1) y = value; else z = value; } } /** Angle between the vectors in radians */ public static float Angle (Int3 lhs, Int3 rhs) { double cos = Dot(lhs,rhs)/ ((double)lhs.magnitude*(double)rhs.magnitude); cos = cos < -1 ? -1 : ( cos > 1 ? 1 : cos ); return (float)System.Math.Acos( cos ); } public static int Dot (Int3 lhs, Int3 rhs) { return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z; } public static long DotLong (Int3 lhs, Int3 rhs) { return (long)lhs.x * (long)rhs.x + (long)lhs.y * (long)rhs.y + (long)lhs.z * (long)rhs.z; } /** Normal in 2D space (XZ). * Equivalent to Cross(this, Int3(0,1,0) ) * except that the Y coordinate is left unchanged with this operation. */ public Int3 Normal2D () { return new Int3 ( z, y, -x ); } public Int3 NormalizeTo (int newMagn) { float magn = magnitude; if (magn == 0) { return this; } x *= newMagn; y *= newMagn; z *= newMagn; x = (int)System.Math.Round (x/magn); y = (int)System.Math.Round (y/magn); z = (int)System.Math.Round (z/magn); return this; } /** Returns the magnitude of the vector. The magnitude is the 'length' of the vector from 0,0,0 to this point. Can be used for distance calculations: * \code Debug.Log ("Distance between 3,4,5 and 6,7,8 is: "+(new Int3(3,4,5) - new Int3(6,7,8)).magnitude); \endcode */ public float magnitude { get { //It turns out that using doubles is just as fast as using ints with Mathf.Sqrt. And this can also handle larger numbers (possibly with small errors when using huge numbers)! double _x = x; double _y = y; double _z = z; return (float)System.Math.Sqrt (_x*_x+_y*_y+_z*_z); //return Mathf.Sqrt (x*x+y*y+z*z); } } /** Magnitude used for the cost between two nodes. The default cost between two nodes can be calculated like this: * \code int cost = (node1.position-node2.position).costMagnitude; \endcode * * This is simply the magnitude, rounded to the nearest integer */ public int costMagnitude { get { return (int)System.Math.Round (magnitude); } } /** The magnitude in world units */ public float worldMagnitude { get { double _x = x; double _y = y; double _z = z; return (float)System.Math.Sqrt (_x*_x+_y*_y+_z*_z)*PrecisionFactor; //Scale numbers down /*float _x = x*PrecisionFactor; float _y = y*PrecisionFactor; float _z = z*PrecisionFactor; return Mathf.Sqrt (_x*_x+_y*_y+_z*_z);*/ } } /** The squared magnitude of the vector */ public float sqrMagnitude { get { double _x = x; double _y = y; double _z = z; return (float)(_x*_x+_y*_y+_z*_z); } } /** The squared magnitude of the vector */ public long sqrMagnitudeLong { get { long _x = x; long _y = y; long _z = z; return (_x*_x+_y*_y+_z*_z); } } /** \warning Can cause number overflows if the magnitude is too large */ public int unsafeSqrMagnitude { get { return x*x+y*y+z*z; } } public static implicit operator string (Int3 ob) { return ob.ToString (); } /** Returns a nicely formatted string representing the vector */ public override string ToString () { return "( "+x+", "+y+", "+z+")"; } public override bool Equals (System.Object o) { if (o == null) return false; var rhs = (Int3)o; return x == rhs.x && y == rhs.y && z == rhs.z; } public override int GetHashCode () { return x*73856093 ^ y*19349663 ^ z*83492791; } } /** Two Dimensional Integer Coordinate Pair */ public struct Int2 { public int x; public int y; public Int2 (int x, int y) { this.x = x; this.y = y; } public int sqrMagnitude { get { return x*x+y*y; } } public long sqrMagnitudeLong { get { return (long)x*(long)x+(long)y*(long)y; } } public static Int2 operator + (Int2 a, Int2 b) { return new Int2 (a.x+b.x, a.y+b.y); } public static Int2 operator - (Int2 a, Int2 b) { return new Int2 (a.x-b.x, a.y-b.y); } public static bool operator == (Int2 a, Int2 b) { return a.x == b.x && a.y == b.y; } public static bool operator != (Int2 a, Int2 b) { return a.x != b.x || a.y != b.y; } public static int Dot (Int2 a, Int2 b) { return a.x*b.x + a.y*b.y; } public static long DotLong (Int2 a, Int2 b) { return (long)a.x*(long)b.x + (long)a.y*(long)b.y; } public override bool Equals (System.Object o) { if (o == null) return false; var rhs = (Int2)o; return x == rhs.x && y == rhs.y; } public override int GetHashCode () { return x*49157+y*98317; } /** Matrices for rotation. * Each group of 4 elements is a 2x2 matrix. * The XZ position is multiplied by this. * So * \code * //A rotation by 90 degrees clockwise, second matrix in the array * (5,2) * ((0, 1), (-1, 0)) = (2,-5) * \endcode */ private static readonly int[] Rotations = { 1, 0, //Identity matrix 0, 1, 0, 1, -1, 0, -1, 0, 0,-1, 0,-1, 1, 0 }; /** Returns a new Int2 rotated 90*r degrees around the origin. */ public static Int2 Rotate ( Int2 v, int r ) { r = r % 4; return new Int2 ( v.x*Rotations[r*4+0] + v.y*Rotations[r*4+1], v.x*Rotations[r*4+2] + v.y*Rotations[r*4+3] ); } public static Int2 Min (Int2 a, Int2 b) { return new Int2 (System.Math.Min (a.x,b.x), System.Math.Min (a.y,b.y)); } public static Int2 Max (Int2 a, Int2 b) { return new Int2 (System.Math.Max (a.x,b.x), System.Math.Max (a.y,b.y)); } public static Int2 FromInt3XZ (Int3 o) { return new Int2 (o.x,o.z); } public static Int3 ToInt3XZ (Int2 o) { return new Int3 (o.x,0,o.y); } public override string ToString () { return "("+x+", " +y+")"; } } }
using System; using System.Runtime.InteropServices; namespace bv.winclient.Core { public class ActivityMonitor : IDisposable { #region interop stuff public delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId); [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern bool UnhookWindowsHookEx(int idHook); [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] public static extern int CallNextHookEx(int idHook, int nCode, IntPtr wParam, IntPtr lParam); [DllImport("user32.dll")] public static extern int GetKeyState(int vKey); private const byte VK_LCONTROL = 0xA2; private const byte VK_L = 76; public enum HookType { WH_JOURNALRECORD = 0, WH_JOURNALPLAYBACK = 1, WH_KEYBOARD = 2, WH_GETMESSAGE = 3, WH_CALLWNDPROC = 4, WH_CBT = 5, WH_SYSMSGFILTER = 6, WH_MOUSE = 7, WH_HARDWARE = 8, WH_DEBUG = 9, WH_SHELL = 10, WH_FOREGROUNDIDLE = 11, WH_CALLWNDPROCRET = 12, WH_KEYBOARD_LL = 13, WH_MOUSE_LL = 14 } private enum MouseMessages { WM_LBUTTONDOWN = 0x201, WM_LBUTTONUP = 0x202, WM_MOUSEMOVE = 0x200, WM_MOUSEWHEEL = 0x20A, WM_RBUTTONDOWN = 0x204, WM_RBUTTONUP = 0x205 } [StructLayout(LayoutKind.Sequential)] private struct POINT { public int x; public int y; } [StructLayout(LayoutKind.Sequential)] private struct MSLLHOOKSTRUCT { public POINT pt; public UInt32 mouseData; public UInt32 flags; public UInt32 time; public IntPtr dwExtraInfo; } private const int WM_KEYDOWN = 0x100; private HookProc _keyboardProc; private int _keyboardHookID = 0; private HookProc _mouseProc; private int _mouseHookID = 0; #endregion private System.Windows.Forms.Timer _timer = new System.Windows.Forms.Timer(); public ActivityMonitor() { LastActivity = DateTime.Now; _keyboardProc = new HookProc(KeyboardHookCallback); _mouseProc = new HookProc(MouseHookCallback); _keyboardHookID = SetKeyboardHook(_keyboardProc); _mouseHookID = SetMouseHook(_mouseProc); _timer.Interval = 1000; _timer.Tick += new System.EventHandler(_timer_Tick); _timer.Start(); } public double MaxMinutesIdle = 30; //default private DateTime LastActivity; private EventHandler IdleEvent; public event EventHandler Idle { add { IdleEvent = (EventHandler)System.Delegate.Combine(IdleEvent, value); } remove { IdleEvent = (EventHandler)System.Delegate.Remove(IdleEvent, value); } } private bool _enabled = false; public bool Enabled { get { return _enabled; } set { _enabled = value; } } private bool m_IsLogoff; public bool IsLogoff { get { return m_IsLogoff; } } private void UpdateState() { if (Enabled == false) { return; } double timeElapsed = System.Convert.ToDouble((DateTime.Now - LastActivity).TotalMinutes); double timeLeft = MaxMinutesIdle - timeElapsed; if (timeLeft <= 0) { m_IsLogoff = true; OnIdle(); } else { m_IsLogoff = true; } } private void OnIdle() { if (IdleEvent != null) IdleEvent(this, EventArgs.Empty); } #region mouse Hook private int SetMouseHook(HookProc proc) { #pragma warning disable 612,618 //Dim threadId As Integer = Threading.Thread.CurrentThread.ManagedThreadId // Don't touch it! int threadId = AppDomain.GetCurrentThreadId(); #pragma warning restore 612,618 return SetWindowsHookEx(System.Convert.ToInt32(HookType.WH_MOUSE), proc, IntPtr.Zero, threadId); } private int MouseHookCallback(int nCode, IntPtr wParam, IntPtr lParam) { MouseMessages mouseInfo = (MouseMessages)wParam; if (nCode >= 0 && ((mouseInfo == MouseMessages.WM_LBUTTONDOWN) || (mouseInfo == MouseMessages.WM_RBUTTONDOWN))) { LastActivity = DateTime.Now; //Debug.WriteLine("MouseHookCallback: " + _currState.ToString() + "\t" + DateTime.Now.ToString() + "\t" + nCode.ToString() + "\t" + wParam + "\t" + lParam); //Debug.WriteLine("\t" + hookStruct.flags.ToString() + "\t" + hookStruct.mouseData.ToString() + "\t" + hookStruct.time.ToString()); } return CallNextHookEx(_mouseHookID, nCode, wParam, lParam); } #endregion #region keyboard Hook private int SetKeyboardHook(HookProc proc) { #pragma warning disable 612,618 //Dim threadId As Integer = Threading.Thread.CurrentThread.ManagedThreadId // Don't touch it! int threadId = AppDomain.GetCurrentThreadId(); #pragma warning restore 612,618 return SetWindowsHookEx(System.Convert.ToInt32(HookType.WH_KEYBOARD), proc, IntPtr.Zero, threadId); } private int KeyboardHookCallback(int nCode, IntPtr wParam, IntPtr lParam) { if (nCode > 0) { LastActivity = DateTime.Now; if ((GetKeyState(System.Convert.ToInt32(VK_LCONTROL)) & 0x80) != 0 && (GetKeyState(System.Convert.ToInt32(VK_L)) & 0x80) != 0) { LastActivity = DateTime.Now.AddMinutes(System.Convert.ToDouble(-MaxMinutesIdle - 1)); UpdateState(); } // Debug.WriteLine(String.Format("{0} KeyboardHookCallback: nCode={1} w={2} l={3}", DateTime.Now.ToString(), nCode, wParam, lParam)); } return CallNextHookEx(_keyboardHookID, nCode, wParam, lParam); } #endregion private void _timer_Tick(object sender, EventArgs e) { UpdateState(); } public void Dispose() { UnhookWindowsHookEx(_keyboardHookID); UnhookWindowsHookEx(_mouseHookID); } } }
// Copyright 2019 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. using Android.App; using Android.Content; using Android.OS; using Android.Widget; using ArcGISRuntime; using Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Http; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Security; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.UI; using Esri.ArcGISRuntime.UI.Controls; using Esri.ArcGISRuntime.UtilityNetworks; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ArcGISRuntimeXamarin.Samples.TraceUtilityNetwork { [Activity(ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)] [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Trace utility network", category: "Utility network", description: "Discover connected features in a utility network using connected, subnetwork, upstream, and downstream traces.", instructions: "Tap on one or more features while 'Add starting locations' or 'Add barriers' is selected. When a junction feature is identified, you may be prompted to select a terminal. When an edge feature is identified, the distance from the tapped location to the beginning of the edge feature will be computed. Select the type of trace using the drop down menu. Tap 'Trace' to initiate a trace on the network. Tap 'Reset' to clear the trace parameters and start over.", tags: new[] { "condition barriers", "downstream trace", "network analysis", "subnetwork trace", "trace configuration", "traversability", "upstream trace", "utility network", "validate consistency", "Featured" })] [ArcGISRuntime.Samples.Shared.Attributes.AndroidLayout("TraceUtilityNetwork.axml")] [ArcGISRuntime.Samples.Shared.Attributes.OfflineData()] public class TraceUtilityNetwork : Activity { // Hold references to the UI controls. private MapView _myMapView; private RadioButton _addStartButton; private RadioButton _addBarrierButton; private Button _traceButton; private Button _resetButton; private Button _traceTypeButton; private TextView _status; private ProgressBar _progressBar; private bool isAddingStart = true; // Feature service for an electric utility network in Naperville, Illinois. private const string FeatureServiceUrl = "https://sampleserver7.arcgisonline.com/server/rest/services/UtilityNetwork/NapervilleElectric/FeatureServer"; // Viewpoint in the utility network area. private Viewpoint _startingViewpoint = new Viewpoint(new Envelope(-9812980.8041217551, 5128523.87694709, -9812798.4363710005, 5128627.6261982173, SpatialReferences.WebMercator)); // Utility network objects. private UtilityNetwork _utilityNetwork; private List<UtilityElement> _startingLocations = new List<UtilityElement>(); private List<UtilityElement> _barriers = new List<UtilityElement>(); private UtilityTier _mediumVoltageTier; private UtilityTraceType _utilityTraceType = UtilityTraceType.Connected; // Task completion source for the user selected terminal. private TaskCompletionSource<int> _terminalCompletionSource = null; // Markers for the utility elements. private SimpleMarkerSymbol _startingPointSymbol; private SimpleMarkerSymbol _barrierPointSymbol; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); Title = "Trace a utility network"; CreateLayout(); Initialize(); } private async void Initialize() { // As of ArcGIS Enterprise 10.8.1, using utility network functionality requires a licensed user. The following login for the sample server is licensed to perform utility network operations. AuthenticationManager.Current.ChallengeHandler = new ChallengeHandler(async (info) => { try { // WARNING: Never hardcode login information in a production application. This is done solely for the sake of the sample. string sampleServer7User = "viewer01"; string sampleServer7Pass = "I68VGU^nMurF"; return await AuthenticationManager.Current.GenerateCredentialAsync(info.ServiceUri, sampleServer7User, sampleServer7Pass); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); return null; } }); try { _progressBar.Visibility = Android.Views.ViewStates.Visible; _status.Text = "Loading Utility Network..."; // Create a map. _myMapView.Map = new Map(new Basemap(new Uri("https://www.arcgis.com/home/item.html?id=1970c1995b8f44749f4b9b6e81b5ba45"))) { InitialViewpoint = _startingViewpoint }; // Add the layer with electric distribution lines. FeatureLayer lineLayer = new FeatureLayer(new Uri($"{FeatureServiceUrl}/3")); UniqueValue mediumVoltageValue = new UniqueValue("N/A", "Medium Voltage", new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, System.Drawing.Color.DarkCyan, 3), 5); UniqueValue lowVoltageValue = new UniqueValue("N/A", "Low Voltage", new SimpleLineSymbol(SimpleLineSymbolStyle.Dash, System.Drawing.Color.DarkCyan, 3), 3); lineLayer.Renderer = new UniqueValueRenderer(new List<string>() { "ASSETGROUP" }, new List<UniqueValue>() { mediumVoltageValue, lowVoltageValue }, "", new SimpleLineSymbol()); _myMapView.Map.OperationalLayers.Add(lineLayer); // Add the layer with electric devices. FeatureLayer electricDevicelayer = new FeatureLayer(new Uri($"{FeatureServiceUrl}/0")); _myMapView.Map.OperationalLayers.Add(electricDevicelayer); // Set the selection color for features in the map view. _myMapView.SelectionProperties = new SelectionProperties(System.Drawing.Color.Yellow); // Create and load the utility network. _utilityNetwork = await UtilityNetwork.CreateAsync(new Uri(FeatureServiceUrl), _myMapView.Map); // Get the utility tier used for traces in this network. For this data set, the "Medium Voltage Radial" tier from the "ElectricDistribution" domain network is used. UtilityDomainNetwork domainNetwork = _utilityNetwork.Definition.GetDomainNetwork("ElectricDistribution"); _mediumVoltageTier = domainNetwork.GetTier("Medium Voltage Radial"); // More complex datasets may require using utility trace configurations from different tiers. The following LINQ expression gets all tiers present in the utility network. //IEnumerable<UtilityTier> tiers = _utilityNetwork.Definition.DomainNetworks.Select(domain => domain.Tiers).SelectMany(tier => tier); // Create symbols for starting locations and barriers. _startingPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.Cross, System.Drawing.Color.LightGreen, 25d); _barrierPointSymbol = new SimpleMarkerSymbol(SimpleMarkerSymbolStyle.X, System.Drawing.Color.OrangeRed, 25d); // Create a graphics overlay. GraphicsOverlay graphicsOverlay = new GraphicsOverlay(); _myMapView.GraphicsOverlays.Add(graphicsOverlay); // Set the instruction text. _status.Text = "Tap on the network lines or points to add a utility element."; } catch (Exception ex) { _status.Text = "Loading Utility Network failed..."; CreateDialog(ex.Message, title: ex.GetType().Name); } finally { _progressBar.Visibility = Android.Views.ViewStates.Invisible; } } private async void GeoViewTapped(object sender, GeoViewInputEventArgs e) { try { _progressBar.Visibility = Android.Views.ViewStates.Visible; _status.Text = "Identifying trace locations..."; // Identify the feature to be used. IEnumerable<IdentifyLayerResult> identifyResult = await _myMapView.IdentifyLayersAsync(e.Position, 10.0, false); ArcGISFeature feature = identifyResult?.FirstOrDefault()?.GeoElements?.FirstOrDefault() as ArcGISFeature; if (feature == null) { return; } // Create element from the identified feature. UtilityElement element = _utilityNetwork.CreateElement(feature); if (element.NetworkSource.SourceType == UtilityNetworkSourceType.Junction) { // Select terminal for junction feature. IEnumerable<UtilityTerminal> terminals = element.AssetType.TerminalConfiguration?.Terminals; if (terminals?.Count() > 1) { element.Terminal = await WaitForTerminal(terminals); } _status.Text = $"Terminal: {element.Terminal?.Name ?? "default"}"; } else if (element.NetworkSource.SourceType == UtilityNetworkSourceType.Edge) { // Compute how far tapped location is along the edge feature. if (feature.Geometry is Polyline line) { line = GeometryEngine.RemoveZ(line) as Polyline; double fraction = GeometryEngine.FractionAlong(line, e.Location, -1); if (double.IsNaN(fraction)) { return; } element.FractionAlongEdge = fraction; _status.Text = $"Fraction along edge: {element.FractionAlongEdge}"; } } // Check whether starting location or barrier is added to update the right collection and symbology. Symbol symbol = null; if (isAddingStart) { _startingLocations.Add(element); symbol = _startingPointSymbol; } else { _barriers.Add(element); symbol = _barrierPointSymbol; } // Add a graphic for the new utility element. Graphic traceLocationGraphic = new Graphic(feature.Geometry as MapPoint ?? e.Location, symbol); _myMapView.GraphicsOverlays.FirstOrDefault()?.Graphics.Add(traceLocationGraphic); } catch (Exception ex) { _status.Text = "Identifying locations failed."; CreateDialog(ex.Message, ex.GetType().Name); } finally { if (_status.Text.Equals("Identifying trace locations...")) { _status.Text = "Could not identify location."; } _progressBar.Visibility = Android.Views.ViewStates.Invisible; } } private async Task<UtilityTerminal> WaitForTerminal(IEnumerable<UtilityTerminal> terminals) { // Create an array of the terminal names for the UI. string[] terminalNames = terminals.ToList().Select(t => t.Name).ToArray(); // Create UI for terminal selection. AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.SetTitle("Select terminal for junction"); builder.SetItems(terminalNames, Choose_Click); builder.SetCancelable(false); builder.Show(); // Return the selected terminal. _terminalCompletionSource = new TaskCompletionSource<int>(); string selectedName = terminalNames[await _terminalCompletionSource.Task]; return terminals.Where(x => x.Name.Equals(selectedName)).FirstOrDefault(); } private void Choose_Click(object sender, DialogClickEventArgs e) { _terminalCompletionSource.TrySetResult(e.Which); } private void ChooseTraceType(object sender, EventArgs e) { // Create UI for trace type selection. AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.SetTitle("Select trace type"); builder.SetItems(new string[] { "Connected", "Subnetwork", "Upstream", "Downstream" }, ChangeTraceType); builder.SetCancelable(true); builder.Show(); } private void ChangeTraceType(object sender, DialogClickEventArgs e) { _utilityTraceType = (UtilityTraceType)Enum.GetValues(typeof(UtilityTraceType)).GetValue(e.Which); _traceTypeButton.Text = $"Trace type: {_utilityTraceType}"; } private async void Trace_Click(object sender, EventArgs e) { try { // Update the UI. _progressBar.Visibility = Android.Views.ViewStates.Visible; _status.Text = $"Running {_utilityTraceType.ToString().ToLower()} trace..."; // Clear previous selection from the layers. _myMapView.Map.OperationalLayers.OfType<FeatureLayer>().ToList().ForEach(layer => layer.ClearSelection()); // Build trace parameters. UtilityTraceParameters parameters = new UtilityTraceParameters(_utilityTraceType, _startingLocations); foreach (UtilityElement barrier in _barriers) { parameters.Barriers.Add(barrier); } // Set the trace configuration using the tier from the utility domain network. parameters.TraceConfiguration = _mediumVoltageTier.GetDefaultTraceConfiguration(); // Get the trace result from the utility network. IEnumerable<UtilityTraceResult> traceResult = await _utilityNetwork.TraceAsync(parameters); UtilityElementTraceResult elementTraceResult = traceResult?.FirstOrDefault() as UtilityElementTraceResult; // Check if there are any elements in the result. if (elementTraceResult?.Elements?.Count > 0) { foreach (FeatureLayer layer in _myMapView.Map.OperationalLayers.OfType<FeatureLayer>()) { IEnumerable<UtilityElement> elements = elementTraceResult.Elements.Where(element => element.NetworkSource.Name == layer.FeatureTable.TableName); IEnumerable<Feature> features = await _utilityNetwork.GetFeaturesForElementsAsync(elements); layer.SelectFeatures(features); } } _status.Text = "Trace completed."; } catch (Exception ex) { _status.Text = "Trace failed..."; if (ex is ArcGISWebException && ex.Message == null) { CreateDialog("Trace failed.", ex.GetType().Name); } else { CreateDialog(ex.Message, ex.GetType().Name); } } finally { _progressBar.Visibility = Android.Views.ViewStates.Invisible; } } private void Reset_Click(object sender, EventArgs e) { // Reset the UI. _status.Text = "Tap on the network lines or points to add a utility element."; _progressBar.Visibility = Android.Views.ViewStates.Invisible; // Clear the utility trace parameters. _startingLocations.Clear(); _barriers.Clear(); // Clear the map layers and graphics. _myMapView.GraphicsOverlays.FirstOrDefault()?.Graphics.Clear(); _myMapView.Map.OperationalLayers.OfType<FeatureLayer>().ToList().ForEach(layer => layer.ClearSelection()); } private void CreateLayout() { // Create a new vertical layout for the app. SetContentView(Resource.Layout.TraceUtilityNetwork); _myMapView = FindViewById<MapView>(Resource.Id.MapView); _addStartButton = FindViewById<RadioButton>(Resource.Id.addStart); _addBarrierButton = FindViewById<RadioButton>(Resource.Id.addBarrier); _traceButton = FindViewById<Button>(Resource.Id.traceButton); _resetButton = FindViewById<Button>(Resource.Id.resetButton); _traceTypeButton = FindViewById<Button>(Resource.Id.traceTypeButton); _status = FindViewById<TextView>(Resource.Id.statusLabel); _progressBar = FindViewById<ProgressBar>(Resource.Id.progressBar); _myMapView.GeoViewTapped += GeoViewTapped; _traceButton.Click += Trace_Click; _resetButton.Click += Reset_Click; _traceTypeButton.Click += ChooseTraceType; _addStartButton.Click += (s, e) => { isAddingStart = true; }; _addBarrierButton.Click += (s, e) => { isAddingStart = false; }; } private void CreateDialog(string message, string title = null) { // Create a dialog to show message to user. AlertDialog alert = new AlertDialog.Builder(this).Create(); if (title != null) alert.SetTitle(title); alert.SetMessage(message); alert.Show(); } } }
using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Web.DynamicData.ModelProviders; using System.Web.Resources; using System.Collections.Concurrent; namespace System.Web.DynamicData { /// <summary> /// Object that represents a database or a number of databases used by the dynamic data. It can have multiple different data contexts registered on it. /// </summary> public class MetaModel : IMetaModel { private List<Type> _contextTypes = new List<Type>(); private static object _lock = new object(); private List<MetaTable> _tables = new List<MetaTable>(); private ReadOnlyCollection<MetaTable> _tablesRO; private Dictionary<string, MetaTable> _tablesByUniqueName = new Dictionary<string, MetaTable>(StringComparer.OrdinalIgnoreCase); private Dictionary<ContextTypeTableNamePair, MetaTable> _tablesByContextAndName = new Dictionary<ContextTypeTableNamePair, MetaTable>(); private SchemaCreator _schemaCreator; private EntityTemplateFactory _entityTemplateFactory; private IFieldTemplateFactory _fieldTemplateFactory; private FilterFactory _filterFactory; private static Exception s_registrationException; private static MetaModel s_defaultModel; private string _dynamicDataFolderVirtualPath; private HttpContextBase _context; private readonly static ConcurrentDictionary<Type, bool> s_registeredMetadataTypes = new ConcurrentDictionary<Type, bool>(); // Use global registration is true by default private bool _registerGlobally = true; internal virtual int RegisteredDataModelsCount { get { return _contextTypes.Count; } } /// <summary> /// ctor /// </summary> public MetaModel() : this(true /* registerGlobally */) { } public MetaModel(bool registerGlobally) : this(SchemaCreator.Instance, registerGlobally) { } // constructor for testing purposes internal MetaModel(SchemaCreator schemaCreator, bool registerGlobally) { // Create a readonly wrapper for handing out _tablesRO = new ReadOnlyCollection<MetaTable>(_tables); _schemaCreator = schemaCreator; _registerGlobally = registerGlobally; // Don't touch Default.Model when we're not using global registration if (registerGlobally) { lock (_lock) { if (Default == null) { Default = this; } } } } internal HttpContextBase Context { get { return _context ?? HttpContext.Current.ToWrapper(); } set { _context = value; } } /// <summary> /// allows for setting of the DynamicData folder for this mode. The default is ~/DynamicData/ /// </summary> public string DynamicDataFolderVirtualPath { get { if (_dynamicDataFolderVirtualPath == null) { _dynamicDataFolderVirtualPath = "~/DynamicData/"; } return _dynamicDataFolderVirtualPath; } set { // Make sure it ends with a slash _dynamicDataFolderVirtualPath = VirtualPathUtility.AppendTrailingSlash(value); } } /// <summary> /// Returns a reference to the first instance of MetaModel that is created in an app. Provides a simple way of referencing /// the default MetaModel instance. Applications that will use multiple models will have to provide their own way of storing /// references to any additional meta models. One way of looking them up is by using the GetModel method. /// </summary> public static MetaModel Default { get { CheckForRegistrationException(); return s_defaultModel; } internal set { s_defaultModel = value; } } /// <summary> /// Gets the model instance that had the contextType registered with it /// </summary> /// <param name="contextType">A DataContext or ObjectContext type (e.g. NorthwindDataContext)</param> /// <returns>a model</returns> public static MetaModel GetModel(Type contextType) { CheckForRegistrationException(); if (contextType == null) { throw new ArgumentNullException("contextType"); } MetaModel model; if (MetaModelManager.TryGetModel(contextType, out model)) { return model; } else { throw new InvalidOperationException(String.Format( CultureInfo.CurrentCulture, DynamicDataResources.MetaModel_ContextDoesNotBelongToModel, contextType.FullName)); } } /// <summary> /// Registers a context. Uses the default ContextConfiguration options. /// </summary> /// <param name="contextType"></param> public void RegisterContext(Type contextType) { RegisterContext(contextType, new ContextConfiguration()); } /// <summary> /// Registers a context. Uses the the given ContextConfiguration options. /// </summary> /// <param name="contextType"></param> /// <param name="configuration"></param> public void RegisterContext(Type contextType, ContextConfiguration configuration) { if (contextType == null) { throw new ArgumentNullException("contextType"); } RegisterContext(() => Activator.CreateInstance(contextType), configuration); } /// <summary> /// Registers a context. Uses default ContextConfiguration. Accepts a context factory that is a delegate used for /// instantiating the context. This allows developers to instantiate context using a custom constructor. /// </summary> /// <param name="contextFactory"></param> public void RegisterContext(Func<object> contextFactory) { RegisterContext(contextFactory, new ContextConfiguration()); } /// <summary> /// Registers a context. Uses given ContextConfiguration. Accepts a context factory that is a delegate used for /// instantiating the context. This allows developers to instantiate context using a custom constructor. /// </summary> /// <param name="contextFactory"></param> /// <param name="configuration"></param> public void RegisterContext(Func<object> contextFactory, ContextConfiguration configuration) { object contextInstance = null; try { if (contextFactory == null) { throw new ArgumentNullException("contextFactory"); } contextInstance = contextFactory(); if (contextInstance == null) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, DynamicDataResources.MetaModel_ContextFactoryReturnsNull), "contextFactory"); } Type contextType = contextInstance.GetType(); if (!_schemaCreator.ValidDataContextType(contextType)) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, DynamicDataResources.MetaModel_ContextTypeNotSupported, contextType.FullName)); } } catch (Exception e) { s_registrationException = e; throw; } // create model abstraction RegisterContext(_schemaCreator.CreateDataModel(contextInstance, contextFactory), configuration); } /// <summary> /// Register context using give model provider. Uses default context configuration. /// </summary> /// <param name="dataModelProvider"></param> public void RegisterContext(DataModelProvider dataModelProvider) { RegisterContext(dataModelProvider, new ContextConfiguration()); } /// <summary> /// Register context using give model provider. Uses given context configuration. /// </summary> /// <param name="dataModelProvider"></param> /// <param name="configuration"></param> [SuppressMessage("Microsoft.Security", "CA2119:SealMethodsThatSatisfyPrivateInterfaces", Justification = "Interface is not used in any security sesitive code paths.")] public virtual void RegisterContext(DataModelProvider dataModelProvider, ContextConfiguration configuration) { if (dataModelProvider == null) { throw new ArgumentNullException("dataModelProvider"); } if (configuration == null) { throw new ArgumentNullException("configuration"); } if (_registerGlobally) { CheckForRegistrationException(); } // check if context has already been registered if (_contextTypes.Contains(dataModelProvider.ContextType)) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, DynamicDataResources.MetaModel_ContextAlreadyRegistered, dataModelProvider.ContextType.FullName)); } try { IEnumerable<TableProvider> tableProviders = dataModelProvider.Tables; // create and validate model var tablesToInitialize = new List<MetaTable>(); foreach (TableProvider tableProvider in tableProviders) { RegisterMetadataTypeDescriptionProvider(tableProvider, configuration.MetadataProviderFactory); MetaTable table = CreateTable(tableProvider); table.CreateColumns(); var tableNameAttribute = tableProvider.Attributes.OfType<TableNameAttribute>().SingleOrDefault(); string nameOverride = tableNameAttribute != null ? tableNameAttribute.Name : null; table.SetScaffoldAndName(configuration.ScaffoldAllTables, nameOverride); CheckTableNameConflict(table, nameOverride, tablesToInitialize); tablesToInitialize.Add(table); } _contextTypes.Add(dataModelProvider.ContextType); if (_registerGlobally) { MetaModelManager.AddModel(dataModelProvider.ContextType, this); } foreach (MetaTable table in tablesToInitialize) { AddTable(table); } // perform initialization at the very end to ensure all references will be properly registered foreach (MetaTable table in tablesToInitialize) { table.Initialize(); } } catch (Exception e) { if (_registerGlobally) { s_registrationException = e; } throw; } } internal static void CheckForRegistrationException() { if (s_registrationException != null) { throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, DynamicDataResources.MetaModel_RegistrationErrorOccurred), s_registrationException); } } /// <summary> /// Reset any previous registration error that may have happened. Normally, the behavior is that when an error /// occurs during registration, the exception is cached and rethrown on all subsequent operations. This is done /// so that if an error occurs in Application_Start, it shows up on every request. Calling this method clears /// out the error and potentially allows new RegisterContext calls. /// </summary> public static void ResetRegistrationException() { s_registrationException = null; } // Used for unit tests internal static void ClearSimpleCache() { s_registeredMetadataTypes.Clear(); } internal static MetaModel CreateSimpleModel(Type entityType) { // Never register a TDP more than once for a type if (!s_registeredMetadataTypes.ContainsKey(entityType)) { var provider = new AssociatedMetadataTypeTypeDescriptionProvider(entityType); TypeDescriptor.AddProviderTransparent(provider, entityType); s_registeredMetadataTypes.TryAdd(entityType, true); } MetaModel model = new MetaModel(false /* registerGlobally */); // Pass a null provider factory since we registered the provider ourselves model.RegisterContext(new SimpleDataModelProvider(entityType), new ContextConfiguration { MetadataProviderFactory = null }); return model; } internal static MetaModel CreateSimpleModel(ICustomTypeDescriptor descriptor) { MetaModel model = new MetaModel(false /* registerGlobally */); // model.RegisterContext(new SimpleDataModelProvider(descriptor)); return model; } /// <summary> /// Instantiate a MetaTable object. Can be overridden to instantiate a derived type /// </summary> /// <returns></returns> protected virtual MetaTable CreateTable(TableProvider provider) { return new MetaTable(this, provider); } private void AddTable(MetaTable table) { _tables.Add(table); _tablesByUniqueName.Add(table.Name, table); if (_registerGlobally) { MetaModelManager.AddTable(table.EntityType, table); } if (table.DataContextType != null) { // need to use the name from the provider since the name from the table could have been modified by use of TableNameAttribute _tablesByContextAndName.Add(new ContextTypeTableNamePair(table.DataContextType, table.Provider.Name), table); } } private void CheckTableNameConflict(MetaTable table, string nameOverride, List<MetaTable> tablesToInitialize) { // try to find name conflict in tables from other context, or already processed tables in current context MetaTable nameConflictTable; if (!_tablesByUniqueName.TryGetValue(table.Name, out nameConflictTable)) { nameConflictTable = tablesToInitialize.Find(t => t.Name.Equals(table.Name, StringComparison.CurrentCulture)); } if (nameConflictTable != null) { if (String.IsNullOrEmpty(nameOverride)) { throw new ArgumentException(String.Format( CultureInfo.CurrentCulture, DynamicDataResources.MetaModel_EntityNameConflict, table.EntityType.FullName, table.DataContextType.FullName, nameConflictTable.EntityType.FullName, nameConflictTable.DataContextType.FullName)); } else { throw new ArgumentException(String.Format( CultureInfo.CurrentCulture, DynamicDataResources.MetaModel_EntityNameOverrideConflict, nameOverride, table.EntityType.FullName, table.DataContextType.FullName, nameConflictTable.EntityType.FullName, nameConflictTable.DataContextType.FullName)); } } } private static void RegisterMetadataTypeDescriptionProvider(TableProvider entity, Func<Type, TypeDescriptionProvider> providerFactory) { if (providerFactory != null) { Type entityType = entity.EntityType; // Support for type-less MetaTable if (entityType != null) { TypeDescriptionProvider provider = providerFactory(entityType); if (provider != null) { TypeDescriptor.AddProviderTransparent(provider, entityType); } } } } /// <summary> /// Returns a collection of all the tables that are part of the context, regardless of whether they are visible or not. /// </summary> public ReadOnlyCollection<MetaTable> Tables { get { CheckForRegistrationException(); return _tablesRO; } } /// <summary> /// Returns a collection of the currently visible tables for this context. Currently visible is defined as: /// - a table whose EntityType is not abstract /// - a table with scaffolding enabled /// - a table for which a custom page for the list action can be found and that can be read by the current User /// </summary> public List<MetaTable> VisibleTables { get { CheckForRegistrationException(); return Tables.Where(IsTableVisible).OrderBy(t => t.DisplayName).ToList(); } } private bool IsTableVisible(MetaTable table) { return !table.EntityType.IsAbstract && !String.IsNullOrEmpty(table.ListActionPath) && table.CanRead(Context.User); } /// <summary> /// Looks up a MetaTable by the entity type. Throws an exception if one is not found. /// </summary> /// <param name="entityType"></param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "We really want this to be a Type.")] public MetaTable GetTable(Type entityType) { MetaTable table; if (!TryGetTable(entityType, out table)) { throw new ArgumentException(String.Format( CultureInfo.CurrentCulture, DynamicDataResources.MetaModel_UnknownEntityType, entityType.FullName)); } return table; } /// <summary> /// Tries to look up a MetaTable by the entity type. /// </summary> /// <param name="entityType"></param> /// <param name="table"></param> /// <returns></returns> public bool TryGetTable(Type entityType, out MetaTable table) { CheckForRegistrationException(); if (entityType == null) { throw new ArgumentNullException("entityType"); } if (!_registerGlobally) { table = Tables.SingleOrDefault(t => t.EntityType == entityType); return table != null; } return MetaModelManager.TryGetTable(entityType, out table); } /// <summary> /// Looks up a MetaTable by unique name. Throws if one is not found. The unique name defaults to the table name, or an override /// can be provided via ContextConfiguration when the context that contains the table is registered. The unique name uniquely /// identifies a table within a give MetaModel. It is used for URL generation. /// </summary> /// <param name="uniqueTableName"></param> /// <returns></returns> public MetaTable GetTable(string uniqueTableName) { CheckForRegistrationException(); MetaTable table; if (!TryGetTable(uniqueTableName, out table)) { throw new ArgumentException(String.Format( CultureInfo.CurrentCulture, DynamicDataResources.MetaModel_UnknownTable, uniqueTableName)); } return table; } /// <summary> /// Tries to look up a MetaTable by unique name. Doe /// </summary> /// <param name="uniqueTableName"></param> /// <param name="table"></param> /// <returns></returns> public bool TryGetTable(string uniqueTableName, out MetaTable table) { CheckForRegistrationException(); if (uniqueTableName == null) { throw new ArgumentNullException("uniqueTableName"); } return _tablesByUniqueName.TryGetValue(uniqueTableName, out table); } /// <summary> /// Looks up a MetaTable by the contextType/tableName combination. Throws if one is not found. /// </summary> /// <param name="tableName"></param> /// <param name="contextType"></param> /// <returns></returns> public MetaTable GetTable(string tableName, Type contextType) { CheckForRegistrationException(); if (tableName == null) { throw new ArgumentNullException("tableName"); } if (contextType == null) { throw new ArgumentNullException("contextType"); } MetaTable table; if (!_tablesByContextAndName.TryGetValue(new ContextTypeTableNamePair(contextType, tableName), out table)) { if (!_contextTypes.Contains(contextType)) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, DynamicDataResources.MetaModel_UnknownContextType, contextType.FullName)); } else { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, DynamicDataResources.MetaModel_UnknownTableInContext, contextType.FullName, tableName)); } } return table; } /// <summary> /// Lets you set a custom IFieldTemplateFactory. An IFieldTemplateFactor lets you customize which field templates are created /// for the various columns. /// </summary> public IFieldTemplateFactory FieldTemplateFactory { get { // If no custom factory was set, use our default if (_fieldTemplateFactory == null) { FieldTemplateFactory = new FieldTemplateFactory(); } return _fieldTemplateFactory; } set { _fieldTemplateFactory = value; // Give the model to the factory if (_fieldTemplateFactory != null) { _fieldTemplateFactory.Initialize(this); } } } public EntityTemplateFactory EntityTemplateFactory { get { if (_entityTemplateFactory == null) { EntityTemplateFactory = new EntityTemplateFactory(); } return _entityTemplateFactory; } set { _entityTemplateFactory = value; if (_entityTemplateFactory != null) { _entityTemplateFactory.Initialize(this); } } } public FilterFactory FilterFactory { get { if (_filterFactory == null) { FilterFactory = new FilterFactory(); } return _filterFactory; } set { _filterFactory = value; if (_filterFactory != null) { _filterFactory.Initialize(this); } } } private string _queryStringKeyPrefix = String.Empty; /// <summary> /// Lets you get an action path (URL) to an action for a particular table/action/entity instance combo. /// </summary> /// <param name="tableName"></param> /// <param name="action"></param> /// <param name="row">An object representing a single row of data in a table. Used to provide values for query string parameters.</param> /// <returns></returns> public string GetActionPath(string tableName, string action, object row) { return GetTable(tableName).GetActionPath(action, row); } private class ContextTypeTableNamePair : IEquatable<ContextTypeTableNamePair> { public ContextTypeTableNamePair(Type contextType, string tableName) { Debug.Assert(contextType != null); Debug.Assert(tableName != null); ContextType = contextType; TableName = tableName; HashCode = ContextType.GetHashCode() ^ TableName.GetHashCode(); } private int HashCode { get; set; } public Type ContextType { get; private set; } public string TableName { get; private set; } public bool Equals(ContextTypeTableNamePair other) { if (other == null) { return false; } return ContextType == other.ContextType && TableName.Equals(other.TableName, StringComparison.Ordinal); } public override int GetHashCode() { return HashCode; } public override bool Equals(object obj) { return Equals(obj as ContextTypeTableNamePair); } } internal static class MetaModelManager { private static Hashtable s_modelByContextType = new Hashtable(); private static Hashtable s_tableByEntityType = new Hashtable(); internal static void AddModel(Type contextType, MetaModel model) { Debug.Assert(contextType != null); Debug.Assert(model != null); lock (s_modelByContextType) { s_modelByContextType.Add(contextType, model); } } internal static bool TryGetModel(Type contextType, out MetaModel model) { model = (MetaModel)s_modelByContextType[contextType]; return model != null; } internal static void AddTable(Type entityType, MetaTable table) { Debug.Assert(entityType != null); Debug.Assert(table != null); lock (s_tableByEntityType) { s_tableByEntityType[entityType] = table; } } internal static void Clear() { lock (s_modelByContextType) { s_modelByContextType.Clear(); } lock (s_tableByEntityType) { s_tableByEntityType.Clear(); } } internal static bool TryGetTable(Type type, out MetaTable table) { table = (MetaTable)s_tableByEntityType[type]; return table != null; } } ReadOnlyCollection<IMetaTable> IMetaModel.Tables { get { return Tables.OfType<IMetaTable>().ToList().AsReadOnly(); } } bool IMetaModel.TryGetTable(string uniqueTableName, out IMetaTable table) { MetaTable metaTable; table = null; if (TryGetTable(uniqueTableName, out metaTable)) { table = metaTable; return true; } return false; } bool IMetaModel.TryGetTable(Type entityType, out IMetaTable table) { MetaTable metaTable; table = null; if (TryGetTable(entityType, out metaTable)) { table = metaTable; return true; } return false; } List<IMetaTable> IMetaModel.VisibleTables { get { return VisibleTables.OfType<IMetaTable>().ToList(); } } IMetaTable IMetaModel.GetTable(string tableName, Type contextType) { return GetTable(tableName, contextType); } IMetaTable IMetaModel.GetTable(string uniqueTableName) { return GetTable(uniqueTableName); } IMetaTable IMetaModel.GetTable(Type entityType) { return GetTable(entityType); } } }
/** * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. * * You are hereby granted a non-exclusive, worldwide, royalty-free license to use, * copy, modify, and distribute this software in source code or binary form for use * in connection with the web services and APIs provided by Facebook. * * As with any software that integrates with the Facebook platform, your use of * this software is subject to the Facebook Developer Principles and Policies * [http://developers.facebook.com/policy/]. This copyright notice shall be * included in all copies or substantial portions of the software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Facebook.Unity.Editor { using System; using System.Collections.Generic; using Facebook.Unity.Canvas; using Facebook.Unity.Editor.Dialogs; using Facebook.Unity.Mobile; internal class EditorFacebook : FacebookBase, IMobileFacebookImplementation, ICanvasFacebookImplementation { private const string WarningMessage = "You are using the facebook SDK in the Unity Editor. " + "Behavior may not be the same as when used on iOS, Android, or Web."; private const string AccessTokenKey = "com.facebook.unity.editor.accesstoken"; private IEditorWrapper editorWrapper; public EditorFacebook(IEditorWrapper wrapper, CallbackManager callbackManager) : base(callbackManager) { this.editorWrapper = wrapper; } public EditorFacebook() : this(new EditorWrapper(EditorFacebook.EditorGameObject), new CallbackManager()) { } public override bool LimitEventUsage { get; set; } public ShareDialogMode ShareDialogMode { get; set; } public override string SDKName { get { return "FBUnityEditorSDK"; } } public override string SDKVersion { get { return Facebook.Unity.FacebookSdkVersion.Build; } } private static IFacebookCallbackHandler EditorGameObject { get { return ComponentFactory.GetComponent<EditorFacebookGameObject>(); } } public override void Init( HideUnityDelegate hideUnityDelegate, InitDelegate onInitComplete) { // Warn that editor behavior will not match supported platforms FacebookLogger.Warn(WarningMessage); base.Init( hideUnityDelegate, onInitComplete); this.editorWrapper.Init(); } public override void LogInWithReadPermissions( IEnumerable<string> permissions, FacebookDelegate<ILoginResult> callback) { // For the editor don't worry about the difference between // LogInWithReadPermissions and LogInWithPublishPermissions this.LogInWithPublishPermissions(permissions, callback); } public override void LogInWithPublishPermissions( IEnumerable<string> permissions, FacebookDelegate<ILoginResult> callback) { this.editorWrapper.ShowLoginMockDialog( this.OnLoginComplete, this.CallbackManager.AddFacebookDelegate(callback), permissions.ToCommaSeparateList()); } public override void AppRequest( string message, OGActionType? actionType, string objectId, IEnumerable<string> to, IEnumerable<object> filters, IEnumerable<string> excludeIds, int? maxRecipients, string data, string title, FacebookDelegate<IAppRequestResult> callback) { this.editorWrapper.ShowAppRequestMockDialog( this.OnAppRequestsComplete, this.CallbackManager.AddFacebookDelegate(callback)); } public override void ShareLink( Uri contentURL, string contentTitle, string contentDescription, Uri photoURL, FacebookDelegate<IShareResult> callback) { this.editorWrapper.ShowMockShareDialog( this.OnShareLinkComplete, "ShareLink", this.CallbackManager.AddFacebookDelegate(callback)); } public override void FeedShare( string toId, Uri link, string linkName, string linkCaption, string linkDescription, Uri picture, string mediaSource, FacebookDelegate<IShareResult> callback) { this.editorWrapper.ShowMockShareDialog( this.OnShareLinkComplete, "FeedShare", this.CallbackManager.AddFacebookDelegate(callback)); } public override void GameGroupCreate( string name, string description, string privacy, FacebookDelegate<IGroupCreateResult> callback) { this.editorWrapper.ShowGameGroupCreateMockDialog( this.OnGroupCreateComplete, this.CallbackManager.AddFacebookDelegate(callback)); } public override void GameGroupJoin( string id, FacebookDelegate<IGroupJoinResult> callback) { this.editorWrapper.ShowGameGroupJoinMockDialog( this.OnGroupJoinComplete, this.CallbackManager.AddFacebookDelegate(callback)); } public override void ActivateApp(string appId) { FacebookLogger.Info("This only needs to be called for iOS or Android."); } public override void GetAppLink(FacebookDelegate<IAppLinkResult> callback) { var result = new Dictionary<string, object>(); result[Constants.UrlKey] = "mockurl://testing.url"; result[Constants.CallbackIdKey] = this.CallbackManager.AddFacebookDelegate(callback); this.OnGetAppLinkComplete(new ResultContainer(result)); } public override void AppEventsLogEvent( string logEvent, float? valueToSum, Dictionary<string, object> parameters) { FacebookLogger.Log("Pew! Pretending to send this off. Doesn't actually work in the editor"); } public override void AppEventsLogPurchase( float logPurchase, string currency, Dictionary<string, object> parameters) { FacebookLogger.Log("Pew! Pretending to send this off. Doesn't actually work in the editor"); } public void AppInvite( Uri appLinkUrl, Uri previewImageUrl, FacebookDelegate<IAppInviteResult> callback) { this.editorWrapper.ShowAppInviteMockDialog( this.OnAppInviteComplete, this.CallbackManager.AddFacebookDelegate(callback)); } public void FetchDeferredAppLink( FacebookDelegate<IAppLinkResult> callback) { var result = new Dictionary<string, object>(); result[Constants.UrlKey] = "mockurl://testing.url"; result[Constants.RefKey] = "mock ref"; result[Constants.ExtrasKey] = new Dictionary<string, object>() { { "mock extra key", "mock extra value" } }; result[Constants.TargetUrlKey] = "mocktargeturl://mocktarget.url"; result[Constants.CallbackIdKey] = this.CallbackManager.AddFacebookDelegate(callback); this.OnFetchDeferredAppLinkComplete(new ResultContainer(result)); } public void Pay( string product, string action, int quantity, int? quantityMin, int? quantityMax, string requestId, string pricepointId, string testCurrency, FacebookDelegate<IPayResult> callback) { this.editorWrapper.ShowPayMockDialog( this.OnPayComplete, this.CallbackManager.AddFacebookDelegate(callback)); } public void RefreshCurrentAccessToken( FacebookDelegate<IAccessTokenRefreshResult> callback) { if (callback == null) { return; } var result = new Dictionary<string, object>() { { Constants.CallbackIdKey, this.CallbackManager.AddFacebookDelegate(callback) } }; if (AccessToken.CurrentAccessToken == null) { result[Constants.ErrorKey] = "No current access token"; } else { var accessTokenDic = (IDictionary<string, object>)MiniJSON.Json.Deserialize( AccessToken.CurrentAccessToken.ToJson()); result.AddAllKVPFrom(accessTokenDic); } this.OnRefreshCurrentAccessTokenComplete(new ResultContainer(result)); } public override void OnAppRequestsComplete(ResultContainer resultContainer) { var result = new AppRequestResult(resultContainer); CallbackManager.OnFacebookResponse(result); } public override void OnGetAppLinkComplete(ResultContainer resultContainer) { var result = new AppLinkResult(resultContainer); CallbackManager.OnFacebookResponse(result); } public override void OnGroupCreateComplete(ResultContainer resultContainer) { var result = new GroupCreateResult(resultContainer); CallbackManager.OnFacebookResponse(result); } public override void OnGroupJoinComplete(ResultContainer resultContainer) { var result = new GroupJoinResult(resultContainer); CallbackManager.OnFacebookResponse(result); } public override void OnLoginComplete(ResultContainer resultContainer) { var result = new LoginResult(resultContainer); this.OnAuthResponse(result); } public override void OnShareLinkComplete(ResultContainer resultContainer) { var result = new ShareResult(resultContainer); CallbackManager.OnFacebookResponse(result); } public void OnAppInviteComplete(ResultContainer resultContainer) { var result = new AppInviteResult(resultContainer); CallbackManager.OnFacebookResponse(result); } public void OnFetchDeferredAppLinkComplete(ResultContainer resultContainer) { var result = new AppLinkResult(resultContainer); CallbackManager.OnFacebookResponse(result); } public void OnPayComplete(ResultContainer resultContainer) { var result = new PayResult(resultContainer); CallbackManager.OnFacebookResponse(result); } public void OnRefreshCurrentAccessTokenComplete(ResultContainer resultContainer) { var result = new AccessTokenRefreshResult(resultContainer); CallbackManager.OnFacebookResponse(result); } #region Canvas Dummy Methods public void OnFacebookAuthResponseChange(ResultContainer resultContainer) { throw new NotSupportedException(); } public void OnUrlResponse(string message) { throw new NotSupportedException(); } #endregion } }
using UnityEngine; using System.Collections; using Pathfinding; using System; using System.Collections.Generic; namespace Pathfinding { /** Contains various spline functions. * \ingroup utils */ class AstarSplines { public static Vector3 CatmullRom(Vector3 previous,Vector3 start, Vector3 end, Vector3 next, float elapsedTime) { // References used: // p.266 GemsV1 // // tension is often set to 0.5 but you can use any reasonable value: // http://www.cs.cmu.edu/~462/projects/assn2/assn2/catmullRom.pdf // // bias and tension controls: // http://local.wasp.uwa.edu.au/~pbourke/miscellaneous/interpolation/ float percentComplete = elapsedTime; float percentCompleteSquared = percentComplete * percentComplete; float percentCompleteCubed = percentCompleteSquared * percentComplete; /*return previous * (-0.5F*percentCompleteCubed + percentCompleteSquared - tension*percentComplete) + start * ((2-tension) *percentCompleteCubed + (tension - 3)*percentCompleteSquared + 1.0F) + end * ((tension - 2)*percentCompleteCubed + 2.0F *percentCompleteSquared + 0.5F*percentComplete) + next * (0.5F*percentCompleteCubed - tension*percentCompleteSquared);*/ return previous * (-0.5F*percentCompleteCubed + percentCompleteSquared - 0.5F*percentComplete) + start * (1.5F*percentCompleteCubed + -2.5F*percentCompleteSquared + 1.0F) + end * (-1.5F*percentCompleteCubed + 2.0F*percentCompleteSquared + 0.5F*percentComplete) + next * (0.5F*percentCompleteCubed - 0.5F*percentCompleteSquared); } public static Vector3 CatmullRomOLD (Vector3 previous,Vector3 start, Vector3 end, Vector3 next, float elapsedTime) { // References used: // p.266 GemsV1 // // tension is often set to 0.5 but you can use any reasonable value: // http://www.cs.cmu.edu/~462/projects/assn2/assn2/catmullRom.pdf // // bias and tension controls: // http://local.wasp.uwa.edu.au/~pbourke/miscellaneous/interpolation/ float percentComplete = elapsedTime; float percentCompleteSquared = percentComplete * percentComplete; float percentCompleteCubed = percentCompleteSquared * percentComplete; return previous * (-0.5F*percentCompleteCubed + percentCompleteSquared - 0.5F*percentComplete) + start * (1.5F*percentCompleteCubed + -2.5F*percentCompleteSquared + 1.0F) + end * (-1.5F*percentCompleteCubed + 2.0F*percentCompleteSquared + 0.5F*percentComplete) + next * (0.5F*percentCompleteCubed - 0.5F*percentCompleteSquared); } } /** Utility functions for working with numbers, lines and vectors. * \ingroup utils * \see Polygon */ public class Mathfx { /** Returns a hash value for a integer vector. Code got from the internet */ public static int ComputeVertexHash (int x, int y, int z) { uint h1 = 0x8da6b343; // Large multiplicative constants; uint h2 = 0xd8163841; // here arbitrarily chosen primes uint h3 = 0xcb1ab31f; uint n = (uint)(h1 * x + h2 * y + h3 * z); return (int)(n & ((1<<30)-1)); } /** Returns the closest point on the line. The line is treated as infinite. * \see NearestPointStrict */ public static Vector3 NearestPoint(Vector3 lineStart, Vector3 lineEnd, Vector3 point) { Vector3 lineDirection = Vector3.Normalize(lineEnd-lineStart); float closestPoint = Vector3.Dot((point-lineStart),lineDirection); //Vector3.Dot(lineDirection,lineDirection); return lineStart+(closestPoint*lineDirection); } public static float NearestPointFactor (Vector3 lineStart, Vector3 lineEnd, Vector3 point) { Vector3 lineDirection = lineEnd-lineStart; float magn = lineDirection.magnitude; lineDirection /= magn; float closestPoint = Vector3.Dot((point-lineStart),lineDirection); //Vector3.Dot(lineDirection,lineDirection); return closestPoint / magn; } /** Returns the closest point on the line segment. The line is NOT treated as infinite. * \see NearestPoint */ public static Vector3 NearestPointStrict(Vector3 lineStart, Vector3 lineEnd, Vector3 point) { Vector3 fullDirection = lineEnd-lineStart; Vector3 lineDirection = Vector3.Normalize(fullDirection); float closestPoint = Vector3.Dot((point-lineStart),lineDirection); //WASTE OF CPU POWER - This is always ONE -- Vector3.Dot(lineDirection,lineDirection); return lineStart+(Mathf.Clamp(closestPoint,0.0f,fullDirection.magnitude)*lineDirection); } /** Returns the closest point on the line segment on the XZ plane. The line is NOT treated as infinite. * \see NearestPoint */ public static Vector3 NearestPointStrictXZ (Vector3 lineStart, Vector3 lineEnd, Vector3 point) { lineStart.y = point.y; lineEnd.y = point.y; Vector3 fullDirection = lineEnd-lineStart; Vector3 fullDirection2 = fullDirection; fullDirection2.y = 0; Vector3 lineDirection = Vector3.Normalize(fullDirection2); //lineDirection.y = 0; float closestPoint = Vector3.Dot((point-lineStart),lineDirection); //WASTE OF CPU POWER - This is always ONE -- Vector3.Dot(lineDirection,lineDirection); return lineStart+(Mathf.Clamp(closestPoint,0.0f,fullDirection2.magnitude)*lineDirection); } /** Returns the approximate shortest distance between x,z and the line p-q. The line is considered infinite. This function is not entirely exact, but it is about twice as fast as DistancePointSegment2. */ public static float DistancePointSegment (int x,int z, int px, int pz, int qx, int qz) { float pqx = (float)(qx - px); float pqz = (float)(qz - pz); float dx = (float)(x - px); float dz = (float)(z - pz); float d = pqx*pqx + pqz*pqz; float t = pqx*dx + pqz*dz; if (d > 0) t /= d; if (t < 0) t = 0; else if (t > 1) t = 1; dx = px + t*pqx - x; dz = pz + t*pqz - z; return dx*dx + dz*dz; } /*public static float DistancePointSegment2 (int x,int z, int px, int pz, int qx, int qz) { Vector3 p = new Vector3 (x,0,z); Vector3 p1 = new Vector3 (px,0,pz); Vector3 p2 = new Vector3 (qx,0,qz); Vector3 nearest = NearestPoint (p1,p2,p); return (nearest-p).sqrMagnitude; }*/ /** Returns the distance between x,z and the line p-q. The line is considered infinite. */ public static float DistancePointSegment2 (int x,int z, int px, int pz, int qx, int qz) { Vector3 p = new Vector3 (x,0,z); Vector3 p1 = new Vector3 (px,0,pz); Vector3 p2 = new Vector3 (qx,0,qz); return DistancePointSegment2 (p1,p2,p); } /** Returns the distance between c and the line a-b. The line is considered infinite. */ public static float DistancePointSegment2 (Vector3 a, Vector3 b, Vector3 p) { float bax = b.x - a.x; float baz = b.z - a.z; float area = Mathf.Abs (bax * (p.z - a.z) - (p.x - a.x) * baz); float d = bax*bax+baz*baz; if (d > 0) { return area / Mathf.Sqrt (d); } return (a-p).magnitude; } /** Returns the squared distance between c and the line a-b. The line is not considered infinite. */ public static float DistancePointSegmentStrict (Vector3 a, Vector3 b, Vector3 p) { Vector3 nearest = NearestPointStrict (a,b,p); return (nearest-p).sqrMagnitude; } /** Returns a point on a hermite curve. Slow start and slow end, fast in the middle */ public static float Hermite(float start, float end, float value) { return Mathf.Lerp(start, end, value * value * (3.0f - 2.0f * value)); } /** Returns a point on a cubic bezier curve. \a t is clamped between 0 and 1 */ public static Vector3 CubicBezier (Vector3 p0,Vector3 p1,Vector3 p2,Vector3 p3, float t) { t = Mathf.Clamp01 (t); float t2 = 1-t; return Mathf.Pow(t2,3) * p0 + 3 * Mathf.Pow(t2,2) * t * p1 + 3 * t2 * Mathf.Pow(t,2) * p2 + Mathf.Pow(t,3) * p3; } /** Maps a value between startMin and startMax to be between 0 and 1 */ public static float MapTo (float startMin,float startMax, float value) { value -= startMin; value /= (startMax-startMin); value = Mathf.Clamp01 (value); return value; } /** Maps a value (0...1) to be between targetMin and targetMax */ public static float MapToRange (float targetMin,float targetMax, float value) { value *= (targetMax-targetMin); value += targetMin; return value; } /** Maps a value between startMin and startMax to be between targetMin and targetMax */ public static float MapTo (float startMin,float startMax, float targetMin, float targetMax, float value) { value -= startMin; value /= (startMax-startMin); value = Mathf.Clamp01 (value); value *= (targetMax-targetMin); value += targetMin; return value; } /** Returns a nicely formatted string for the number of bytes (kB, MB, GB etc). Uses decimal values, not binary ones * \see FormatBytesBinary */ public static string FormatBytes (int bytes) { double sign = bytes >= 0 ? 1D : -1D; bytes = bytes >= 0 ? bytes : -bytes; if (bytes < 1000) { return (bytes*sign).ToString ()+" bytes"; } else if (bytes < 1000000) { return ((bytes/1000D)*sign).ToString ("0.0") + " kb"; } else if (bytes < 1000000000) { return ((bytes/1000000D)*sign).ToString ("0.0") +" mb"; } else { return ((bytes/1000000000D)*sign).ToString ("0.0") +" gb"; } } /** Returns a nicely formatted string for the number of bytes (KiB, MiB, GiB etc). Uses decimal names (KB, Mb - 1000) but calculates using binary values (KiB, MiB - 1024) */ public static string FormatBytesBinary (int bytes) { double sign = bytes >= 0 ? 1D : -1D; bytes = bytes >= 0 ? bytes : -bytes; if (bytes < 1024) { return (bytes*sign).ToString ()+" bytes"; } else if (bytes < 1024) { return ((bytes/1024D)*sign).ToString ("0.0") + " kb"; } else if (bytes < 1000000000) { return ((bytes/(1024D*1024D))*sign).ToString ("0.0") +" mb"; } else { return ((bytes/(1024D*1024D*1024D))*sign).ToString ("0.0") +" gb"; } } /** Returns bit number \a b from int \a a. The bit number is zero based. Relevant \a b values are from 0 to 31\n * Equals to (a >> b) & 1 */ public static int Bit (int a, int b) { return (a >> b) & 1; //return (a & (1 << b)) >> b; //Original code, one extra shift operation required } /** Returns a nice color from int \a i with alpha \a a. Got code from the open-source Recast project, works really good\n * Seems like there are only 64 possible colors from studying the code*/ public static Color IntToColor (int i, float a) { int r = Bit(i, 1) + Bit(i, 3) * 2 + 1; int g = Bit(i, 2) + Bit(i, 4) * 2 + 1; int b = Bit(i, 0) + Bit(i, 5) * 2 + 1; return new Color (r*0.25F,g*0.25F,b*0.25F,a); } /** Distance between two points on the XZ plane */ public static float MagnitudeXZ (Vector3 a, Vector3 b) { Vector3 delta = a-b; return (float)Math.Sqrt (delta.x*delta.x+delta.z*delta.z); } /** Squared distance between two points on the XZ plane */ public static float SqrMagnitudeXZ (Vector3 a, Vector3 b) { Vector3 delta = a-b; return delta.x*delta.x+delta.z*delta.z; } public static int Repeat (int i, int n) { while (i >= n) { i -= n; } return i; } public static float Abs (float a) { if (a < 0) { return -a; } return a; } public static int Abs (int a) { if (a < 0) { return -a; } return a; } public static float Min (float a, float b) { return a < b ? a : b; } public static int Min (int a, int b) { return a < b ? a : b; } public static uint Min (uint a, uint b) { return a < b ? a : b; } public static float Max (float a, float b) { return a > b ? a : b; } public static int Max (int a, int b) { return a > b ? a : b; } public static uint Max (uint a, uint b) { return a > b ? a : b; } public static ushort Max (ushort a, ushort b) { return a > b ? a : b; } public static float Sign (float a) { return a < 0 ? -1F : 1F; } public static int Sign (int a) { return a < 0 ? -1 : 1; } public static float Clamp (float a, float b, float c) { return a > c ? c : a < b ? b : a; } public static int Clamp (int a, int b, int c) { return a > c ? c : a < b ? b : a; } public static float Clamp01 (float a) { return a > 1 ? 1 : a < 0 ? 0 : a; } public static int Clamp01 (int a) { return a > 1 ? 1 : a < 0 ? 0 : a; } public static float Lerp (float a,float b, float t) { return a + (b-a)*(t > 1 ? 1 : t < 0 ? 0 : t); } public static int RoundToInt (float v) { return (int)(v+0.5F); } public static int RoundToInt (double v) { return (int)(v+0.5D); } } /** Utility functions for working with polygons, lines, and other vector math. * All functions which accepts Vector3s but work in 2D space uses the XZ space if nothing else is said. * \ingroup utils */ public class Polygon { /** Area of a triangle This will be negative for clockwise triangles and positive for counter-clockwise ones */ public static long TriangleArea2 (Int3 a, Int3 b, Int3 c) { return (long)(b.x - a.x) * (long)(c.z - a.z) - (long)(c.x - a.x) * (long)(b.z - a.z); //a.x*b.z+b.x*c.z+c.x*a.z-a.x*c.z-c.x*b.z-b.x*a.z; } public static float TriangleArea2 (Vector3 a, Vector3 b, Vector3 c) { return (b.x - a.x) * (c.z - a.z) - (c.x - a.x) * (b.z - a.z); //return a.x*b.z+b.x*c.z+c.x*a.z-a.x*c.z-c.x*b.z-b.x*a.z; } public static long TriangleArea (Int3 a, Int3 b, Int3 c) { return (long)(b.x - a.x) * (long)(c.z - a.z) - (long)(c.x - a.x) * (long)(b.z - a.z); //a.x*b.z+b.x*c.z+c.x*a.z-a.x*c.z-c.x*b.z-b.x*a.z; } public static float TriangleArea (Vector3 a, Vector3 b, Vector3 c) { return (b.x - a.x) * (c.z - a.z) - (c.x - a.x) * (b.z - a.z); //return a.x*b.z+b.x*c.z+c.x*a.z-a.x*c.z-c.x*b.z-b.x*a.z; } /** Returns if the triangle \a ABC contains the point \a p in XZ space */ public static bool ContainsPoint (Vector3 a, Vector3 b, Vector3 c, Vector3 p) { return Polygon.IsClockwiseMargin (a,b, p) && Polygon.IsClockwiseMargin (b,c, p) && Polygon.IsClockwiseMargin (c,a, p); } /** Checks if \a p is inside the polygon. * \author http://unifycommunity.com/wiki/index.php?title=PolyContainsPoint (Eric5h5) */ public static bool ContainsPoint (Vector2[] polyPoints,Vector2 p) { int j = polyPoints.Length-1; bool inside = false; for (int i = 0; i < polyPoints.Length; j = i++) { if ( ((polyPoints[i].y <= p.y && p.y < polyPoints[j].y) || (polyPoints[j].y <= p.y && p.y < polyPoints[i].y)) && (p.x < (polyPoints[j].x - polyPoints[i].x) * (p.y - polyPoints[i].y) / (polyPoints[j].y - polyPoints[i].y) + polyPoints[i].x)) inside = !inside; } return inside; } /** Checks if \a p is inside the polygon (XZ space) * \author http://unifycommunity.com/wiki/index.php?title=PolyContainsPoint (Eric5h5) */ public static bool ContainsPoint (Vector3[] polyPoints,Vector3 p) { int j = polyPoints.Length-1; bool inside = false; for (int i = 0; i < polyPoints.Length; j = i++) { if ( ((polyPoints[i].z <= p.z && p.z < polyPoints[j].z) || (polyPoints[j].z <= p.z && p.z < polyPoints[i].z)) && (p.x < (polyPoints[j].x - polyPoints[i].x) * (p.z - polyPoints[i].z) / (polyPoints[j].z - polyPoints[i].z) + polyPoints[i].x)) inside = !inside; } return inside; } /** Returns if \a p lies on the left side of the line \a a - \a b. Uses XZ space. Also returns true if the points are colinear */ public static bool Left (Vector3 a, Vector3 b, Vector3 p) { return (b.x - a.x) * (p.z - a.z) - (p.x - a.x) * (b.z - a.z) <= 0; } /** Returns if \a p lies on the left side of the line \a a - \a b. Uses XZ space. Also returns true if the points are colinear */ public static bool Left (Int3 a, Int3 b, Int3 c) { return (long)(b.x - a.x) * (long)(c.z - a.z) - (long)(c.x - a.x) * (long)(b.z - a.z) <= 0; } /** Returns if the points a in a clockwise order. * Will return true even if the points are colinear or very slightly counter-clockwise * (if the signed area of the triangle formed by the points has an area less than or equals to float.Epsilon) */ public static bool IsClockwiseMargin (Vector3 a, Vector3 b, Vector3 c) { return (b.x-a.x)*(c.z-a.z)-(c.x-a.x)*(b.z-a.z) <= float.Epsilon; } /** Returns if the points a in a clockwise order */ public static bool IsClockwise (Vector3 a, Vector3 b, Vector3 c) { return (b.x-a.x)*(c.z-a.z)-(c.x-a.x)*(b.z-a.z) < 0; } /** Returns if the points a in a clockwise order */ public static bool IsClockwise (Int3 a, Int3 b, Int3 c) { return (long)(b.x - a.x) * (long)(c.z - a.z) - (long)(c.x - a.x) * (long)(b.z - a.z) < 0; } /** Returns if the points are colinear (lie on a straight line) */ public static bool IsColinear (Int3 a, Int3 b, Int3 c) { return (long)(b.x - a.x) * (long)(c.z - a.z) - (long)(c.x - a.x) * (long)(b.z - a.z) == 0; } /** Returns if the points are colinear (lie on a straight line) */ public static bool IsColinear (Vector3 a, Vector3 b, Vector3 c) { return Mathf.Approximately ((b.x-a.x)*(c.z-a.z)-(c.x-a.x)*(b.z-a.z), 0); } /** Returns if the line segment \a a2 - \a b2 intersects the infinite line \a a - \a b. a-b is infinite, a2-b2 is not infinite */ public static bool IntersectsUnclamped (Vector3 a, Vector3 b, Vector3 a2, Vector3 b2) { return Left (a,b,a2) != Left (a,b,b2); } /** Returns if the two line segments intersects. The lines are NOT treated as infinite (just for clarification) * \see IntersectionPoint */ public static bool Intersects (Vector3 start1, Vector3 end1, Vector3 start2, Vector3 end2) { Vector3 dir1 = end1-start1; Vector3 dir2 = end2-start2; float den = dir2.z*dir1.x - dir2.x * dir1.z; if (den == 0) { return false; } float nom = dir2.x*(start1.z-start2.z)- dir2.z*(start1.x-start2.x); float nom2 = dir1.x*(start1.z-start2.z) - dir1.z * (start1.x - start2.x); float u = nom/den; float u2 = nom2/den; if (u < 0F || u > 1F || u2 < 0F || u2 > 1F) { return false; } //Debug.DrawLine (start2,end2,Color.magenta); //Debug.DrawRay (start1,dir1*5,Color.green); return true; //Vector2 intersection = start1 + dir1*u; //return intersection; } /** Intersection point between two infinite lines. * Lines are treated as infinite. If the lines are parallel 'start1' will be returned. Intersections are calculated on the XZ plane. */ public static Vector3 IntersectionPointOptimized (Vector3 start1, Vector3 dir1, Vector3 start2, Vector3 dir2) { float den = dir2.z*dir1.x - dir2.x * dir1.z; if (den == 0) { return start1; } float nom = dir2.x*(start1.z-start2.z)- dir2.z*(start1.x-start2.x); float u = nom/den; return start1 + dir1*u; } /** Intersection point between two infinite lines. * Lines are treated as infinite. If the lines are parallel 'start1' will be returned. Intersections are calculated on the XZ plane. */ public static Vector3 IntersectionPointOptimized (Vector3 start1, Vector3 dir1, Vector3 start2, Vector3 dir2, out bool intersects) { float den = dir2.z*dir1.x - dir2.x * dir1.z; if (den == 0) { intersects = false; return start1; } float nom = dir2.x*(start1.z-start2.z)- dir2.z*(start1.x-start2.x); float u = nom/den; intersects = true; return start1 + dir1*u; } /** Returns the intersection factors for line 1 and line 2. The intersection factors is a distance along the line \a start - \a end where the other line intersects it.\n * \code intersectionPoint = start1 + factor1 * (end1-start1) \endcode * \code intersectionPoint2 = start2 + factor2 * (end2-start2) \endcode * Lines are treated as infinite.\n * false is returned if the lines are parallel and true if they are not */ public static bool IntersectionFactor (Vector3 start1, Vector3 end1, Vector3 start2, Vector3 end2, out float factor1, out float factor2) { Vector3 dir1 = end1-start1; Vector3 dir2 = end2-start2; //Color rnd = new Color (Random.value,Random.value,Random.value); //Debug.DrawRay (start1,dir1,rnd); //Debug.DrawRay (start2,dir2,rnd); float den = dir2.z*dir1.x - dir2.x * dir1.z; if (den == 0) { factor1 = 0; factor2 = 0; return false; } float nom = dir2.x*(start1.z-start2.z)- dir2.z*(start1.x-start2.x); float nom2 = dir1.x*(start1.z-start2.z) - dir1.z * (start1.x - start2.x); float u = nom/den; float u2 = nom2/den; factor1 = u; factor2 = u2; //Debug.DrawLine (start2,end2,Color.magenta); //Debug.DrawRay (start1,dir1*5,Color.green); return true; } /** Returns the intersection factor for line 1 with line 2. * The intersection factor is a distance along the line \a start1 - \a end1 where the line \a start2 - \a end2 intersects it.\n * \code intersectionPoint = start1 + intersectionFactor * (end1-start1) \endcode. * Lines are treated as infinite.\n * -1 is returned if the lines are parallel (note that this is a valid return value if they are not parallel too) */ public static float IntersectionFactor (Vector3 start1, Vector3 end1, Vector3 start2, Vector3 end2) { Vector3 dir1 = end1-start1; Vector3 dir2 = end2-start2; //Color rnd = new Color (Random.value,Random.value,Random.value); //Debug.DrawRay (start1,dir1,rnd); //Debug.DrawRay (start2,dir2,rnd); float den = dir2.z*dir1.x - dir2.x * dir1.z; if (den == 0) { return -1; } float nom = dir2.x*(start1.z-start2.z)- dir2.z*(start1.x-start2.x); float u = nom/den; //Debug.DrawLine (start2,end2,Color.magenta); //Debug.DrawRay (start1,dir1*5,Color.green); return u; } /** Returns the intersection point between the two lines. Lines are treated as infinite. \a start1 is returned if the lines are parallel */ public static Vector3 IntersectionPoint (Vector3 start1, Vector3 end1, Vector3 start2, Vector3 end2) { bool s; return IntersectionPoint (start1,end1,start2,end2, out s); } /** Returns the intersection point between the two lines. Lines are treated as infinite. \a start1 is returned if the lines are parallel */ public static Vector3 IntersectionPoint (Vector3 start1, Vector3 end1, Vector3 start2, Vector3 end2, out bool intersects) { Vector3 dir1 = end1-start1; Vector3 dir2 = end2-start2; //Color rnd = new Color (Random.value,Random.value,Random.value); //Debug.DrawRay (start1,dir1,rnd); //Debug.DrawRay (start2,dir2,rnd); float den = dir2.z*dir1.x - dir2.x * dir1.z; if (den == 0) { intersects = false; return start1; } float nom = dir2.x*(start1.z-start2.z)- dir2.z*(start1.x-start2.x); float u = nom/den; //Debug.DrawLine (start2,end2,Color.magenta); //Debug.DrawRay (start1,dir1*5,Color.green); intersects = true; return start1 + dir1*u; } /** Returns the intersection point between the two lines. Lines are treated as infinite. \a start1 is returned if the lines are parallel */ public static Vector2 IntersectionPoint (Vector2 start1, Vector2 end1, Vector2 start2, Vector2 end2) { bool s; return IntersectionPoint (start1,end1,start2,end2, out s); } /** Returns the intersection point between the two lines. Lines are treated as infinite. \a start1 is returned if the lines are parallel */ public static Vector2 IntersectionPoint (Vector2 start1, Vector2 end1, Vector2 start2, Vector2 end2, out bool intersects) { Vector2 dir1 = end1-start1; Vector2 dir2 = end2-start2; //Color rnd = new Color (Random.value,Random.value,Random.value); //Debug.DrawRay (start1,dir1,rnd); //Debug.DrawRay (start2,dir2,rnd); float den = dir2.y*dir1.x - dir2.x * dir1.y; if (den == 0) { intersects = false; return start1; } float nom = dir2.x*(start1.y-start2.y)- dir2.y*(start1.x-start2.x); float u = nom/den; //Debug.DrawLine (start2,end2,Color.magenta); //Debug.DrawRay (start1,dir1*5,Color.green); intersects = true; return start1 + dir1*u; } /** Returns the intersection point between the two line segments. * Lines are NOT treated as infinite. \a start1 is returned if the line segments do not intersect */ public static Vector3 SegmentIntersectionPoint (Vector3 start1, Vector3 end1, Vector3 start2, Vector3 end2, out bool intersects) { Vector3 dir1 = end1-start1; Vector3 dir2 = end2-start2; //Color rnd = new Color (Random.value,Random.value,Random.value); //Debug.DrawRay (start1,dir1,rnd); //Debug.DrawRay (start2,dir2,rnd); float den = dir2.z*dir1.x - dir2.x * dir1.z; if (den == 0) { intersects = false; return start1; } float nom = dir2.x*(start1.z-start2.z)- dir2.z*(start1.x-start2.x); float nom2 = dir1.x*(start1.z-start2.z) - dir1.z * (start1.x - start2.x); float u = nom/den; float u2 = nom2/den; if (u < 0F || u > 1F || u2 < 0F || u2 > 1F) { intersects = false; return start1; } //Debug.Log ("U1 "+u.ToString ("0.00")+" U2 "+u2.ToString ("0.00")+"\nP1: "+(start1 + dir1*u)+"\nP2: "+(start2 + dir2*u2)+"\nStart1: "+start1+" End1: "+end1); //Debug.DrawLine (start2,end2,Color.magenta); //Debug.DrawRay (start1,dir1*5,Color.green); intersects = true; return start1 + dir1*u; } public static List<Vector3> hullCache = new List<Vector3>(); /** Calculates convex hull in XZ space for the points. * Implemented using the very simple Gift Wrapping Algorithm * which has a complexity of O(nh) where \a n is the number of points and \a h is the number of points on the hull, * so it is in the worst case quadratic. */ public static Vector3[] ConvexHull (Vector3[] points) { if (points.Length == 0) return new Vector3[0]; lock (hullCache) { List<Vector3> hull = hullCache; hull.Clear (); #if ASTARDEBUG for (int i=0;i<points.Length;i++) { Debug.DrawLine (points[i],points[(i+1)%points.Length],Color.blue); } #endif int pointOnHull = 0; for (int i=1;i<points.Length;i++) if (points[i].x < points[pointOnHull].x) pointOnHull = i; int startpoint = pointOnHull; int counter = 0; do { hull.Add (points[pointOnHull]); int endpoint = 0; for (int i=0;i<points.Length;i++) if (endpoint == pointOnHull || !Left (points[pointOnHull],points[endpoint],points[i])) endpoint = i; pointOnHull = endpoint; counter++; if (counter > 10000) { Debug.LogWarning ("Infinite Loop in Convex Hull Calculation"); break; } } while (pointOnHull != startpoint); return hull.ToArray (); } } /** Does the line segment intersect the bounding box. * The line is NOT treated as infinite. * \author Slightly modified code from http://www.3dkingdoms.com/weekly/weekly.php?a=21 */ public static bool LineIntersectsBounds (Bounds bounds, Vector3 a, Vector3 b) { // Put line in box space //CMatrix MInv = m_M.InvertSimple(); //CVec3 LB1 = MInv * L1; //CVec3 LB2 = MInv * L2; a -= bounds.center; b -= bounds.center; // Get line midpoint and extent Vector3 LMid = (a + b) * 0.5F; Vector3 L = (a - LMid); Vector3 LExt = new Vector3 ( Math.Abs(L.x), Math.Abs(L.y), Math.Abs(L.z) ); Vector3 extent = bounds.extents; // Use Separating Axis Test // Separation vector from box center to line center is LMid, since the line is in box space if ( Math.Abs( LMid.x ) > extent.x + LExt.x ) return false; if ( Math.Abs( LMid.y ) > extent.y + LExt.y ) return false; if ( Math.Abs( LMid.z ) > extent.z + LExt.z ) return false; // Crossproducts of line and each axis if ( Math.Abs( LMid.y * L.z - LMid.z * L.y) > (extent.y * LExt.z + extent.z * LExt.y) ) return false; if ( Math.Abs( LMid.x * L.z - LMid.z * L.x) > (extent.x * LExt.z + extent.z * LExt.x) ) return false; if ( Math.Abs( LMid.x * L.y - LMid.y * L.x) > (extent.x * LExt.y + extent.y * LExt.x) ) return false; // No separating axis, the line intersects return true; } /** Dot product of two vectors. \todo Why is this function defined here? */ public static float Dot (Vector3 lhs, Vector3 rhs) { return lhs.x * rhs.x + lhs.y * rhs.y + lhs.z * rhs.z; } /* public static Vector3[] WeightedSubdivide (Vector3[] path, int subdivisions) { Vector3[] path2 = new Vector3[(path.Length-1)*(int)Mathf.Pow (2,subdivisions)+1]; int c = 0; for (int p=0;p<path.Length-1;p++) { float step = 1.0F/Mathf.Pow (2,subdivisions); for (float i=0;i<1.0F;i+=step) { path2[c] = Vector3.Lerp (path[p],path[p+1],Mathfx.Hermite (0F,1F,i));//Mathf.SmoothStep (0,1, i)); c++; } } //Debug.Log (path2.Length +" "+c); path2[c] = path[path.Length-1]; return path2; }*/ /** Subdivides \a path and returns the new array with interpolated values. The returned array is \a path subdivided \a subdivisions times, the resulting points are interpolated using Mathf.SmoothStep.\n * If \a subdivisions is less or equal to 0 (zero), the original array will be returned */ public static Vector3[] Subdivide (Vector3[] path, int subdivisions) { subdivisions = subdivisions < 0 ? 0 : subdivisions; if (subdivisions == 0) { return path; } Vector3[] path2 = new Vector3[(path.Length-1)*(int)Mathf.Pow (2,subdivisions)+1]; int c = 0; for (int p=0;p<path.Length-1;p++) { float step = 1.0F/Mathf.Pow (2,subdivisions); for (float i=0;i<1.0F;i+=step) { path2[c] = Vector3.Lerp (path[p],path[p+1],Mathf.SmoothStep (0,1, i)); c++; } } //Debug.Log (path2.Length +" "+c); path2[c] = path[path.Length-1]; return path2; } /** Returns the closest point on the triangle. The \a triangle array must have a length of at least 3. * \see ClosesPointOnTriangle(Vector3,Vector3,Vector3,Vector3); */ public static Vector3 ClosestPointOnTriangle ( Vector3[] triangle, Vector3 point ) { return ClosestPointOnTriangle (triangle[0],triangle[1],triangle[2],point); } /** Returns the closest point on the triangle. \note Got code from the internet, changed a bit to work with the Unity API * \todo Uses Dot product to get the sqrMagnitude of a vector, should change to sqrMagnitude for readability and possibly for speed (unlikely though) */ public static Vector3 ClosestPointOnTriangle (Vector3 tr0, Vector3 tr1, Vector3 tr2, Vector3 point ) { Vector3 edge0 = tr1 - tr0; Vector3 edge1 = tr2 - tr0; Vector3 v0 = tr0 - point; float a = Vector3.Dot (edge0,edge0);//edge0.dot( edge0 ); //Equals to sqrMagnitude float b = Vector3.Dot (edge0, edge1 ); float c = Vector3.Dot (edge1, edge1 ); //Equals to sqrMagnitude float d = Vector3.Dot (edge0, v0 ); float e = Vector3.Dot (edge1, v0 ); float det = a*c - b*b; float s = b*e - c*d; float t = b*d - a*e; if ( s + t < det ) { if ( s < 0.0F ) { if ( t < 0.0F ) { if ( d < 0.0F ) { s = Mathfx.Clamp01 ( -d/a); t = 0.0F; } else { s = 0.0F; t = Mathfx.Clamp01 ( -e/c); } } else { s = 0.0F; t = Mathfx.Clamp01 ( -e/c); } } else if ( t < 0.0F ) { s = Mathfx.Clamp01 ( -d/a); t = 0.0F; } else { float invDet = 1.0F / det; s *= invDet; t *= invDet; } } else { if ( s < 0.0F ) { float tmp0 = b+d; float tmp1 = c+e; if ( tmp1 > tmp0 ) { float numer = tmp1 - tmp0; float denom = a-2*b+c; s = Mathfx.Clamp01 ( numer/denom); t = 1-s; } else { t = Mathfx.Clamp01 ( -e/c); s = 0.0F; } } else if ( t < 0.0F ) { if ( a+d > b+e ) { float numer = c+e-b-d; float denom = a-2*b+c; s = Mathfx.Clamp01 ( numer/denom); t = 1-s; } else { s = Mathfx.Clamp01 ( -e/c); t = 0.0F; } } else { float numer = c+e-b-d; float denom = a-2*b+c; s = Mathfx.Clamp01 ( numer/denom); t = 1.0F - s; } } return tr0 + s * edge0 + t * edge1; } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Runtime.Serialization; using TrackableEntities; using TrackableEntities.Client; using System.ComponentModel.DataAnnotations; namespace AIM.Web.Admin.Models.EntityModels { [JsonObject(IsReference = true)] [DataContract(IsReference = true, Namespace = "http://schemas.datacontract.org/2004/07/TrackableEntities.Models")] public partial class Store : ModelBase<Store>, IEquatable<Store>, ITrackable { public Store() { this.OpenJobs = new ChangeTrackingCollection<OpenJob>(); } [DataMember] [Display(Name = "Store ID")] public int StoreId { get { return _StoreId; } set { if (Equals(value, _StoreId)) return; _StoreId = value; NotifyPropertyChanged(m => m.StoreId); } } private int _StoreId; [DataMember] [Display(Name = "Store Name")] public string Name { get { return _Name; } set { if (Equals(value, _Name)) return; _Name = value; NotifyPropertyChanged(m => m.Name); } } private string _Name; [DataMember] [Display(Name = "Region ID")] public int? RegionId { get { return _RegionId; } set { if (Equals(value, _RegionId)) return; _RegionId = value; NotifyPropertyChanged(m => m.RegionId); } } private int? _RegionId; [DataMember] [Display(Name = "Street")] public string Street { get { return _Street; } set { if (Equals(value, _Street)) return; _Street = value; NotifyPropertyChanged(m => m.Street); } } private string _Street; [DataMember] [Display(Name = "Street 2")] public string Street2 { get { return _Street2; } set { if (Equals(value, _Street2)) return; _Street2 = value; NotifyPropertyChanged(m => m.Street2); } } private string _Street2; [DataMember] [Display(Name = "City")] public string City { get { return _City; } set { if (Equals(value, _City)) return; _City = value; NotifyPropertyChanged(m => m.City); } } private string _City; [DataMember] [Display(Name = "State")] public StateEnum? State { get { return _state; } set { if (Equals(value, _state)) return; _state = value; NotifyPropertyChanged(m => m.State); } } private StateEnum? _state; [DataMember] [Display(Name = "Zip Code")] public string Zip { get { return _Zip; } set { if (Equals(value, _Zip)) return; _Zip = value; NotifyPropertyChanged(m => m.Zip); } } private string _Zip; [DataMember] [Display(Name = "Open Jobs")] public ChangeTrackingCollection<OpenJob> OpenJobs { get { return _OpenJobs; } set { if (Equals(value, _OpenJobs)) return; _OpenJobs = value; NotifyPropertyChanged(m => m.OpenJobs); } } private ChangeTrackingCollection<OpenJob> _OpenJobs; [DataMember] [Display(Name = "Region")] public Region Region { get { return _Region; } set { if (Equals(value, _Region)) return; _Region = value; RegionChangeTracker = _Region == null ? null : new ChangeTrackingCollection<Region> { _Region }; NotifyPropertyChanged(m => m.Region); } } private Region _Region; private ChangeTrackingCollection<Region> RegionChangeTracker { get; set; } #region Change Tracking [DataMember] public TrackingState TrackingState { get; set; } [DataMember] public ICollection<string> ModifiedProperties { get; set; } [JsonProperty, DataMember] private Guid EntityIdentifier { get; set; } #pragma warning disable 414 [JsonProperty, DataMember] private Guid _entityIdentity = default(Guid); #pragma warning restore 414 bool IEquatable<Store>.Equals(Store other) { if (EntityIdentifier != default(Guid)) return EntityIdentifier == other.EntityIdentifier; return false; } #endregion Change Tracking } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Versioning; using System.Xml.Linq; using Microsoft.DotNet.PlatformAbstractions; using Microsoft.DotNet.ProjectModel.Utilities; using Microsoft.Extensions.DependencyModel.Resolution; using NuGet.Frameworks; namespace Microsoft.DotNet.ProjectModel.Resolution { public class FrameworkReferenceResolver { // FrameworkConstants doesn't have dnx46 yet private static readonly NuGetFramework Dnx46 = new NuGetFramework( FrameworkConstants.FrameworkIdentifiers.Dnx, new Version(4, 6)); private static FrameworkReferenceResolver _default; private readonly ConcurrentDictionary<NuGetFramework, FrameworkInformation> _cache = new ConcurrentDictionary<NuGetFramework, FrameworkInformation>(); private static readonly IDictionary<NuGetFramework, NuGetFramework[]> _aliases = new Dictionary<NuGetFramework, NuGetFramework[]> { { FrameworkConstants.CommonFrameworks.Dnx451, new [] { FrameworkConstants.CommonFrameworks.Net451 } }, { Dnx46, new [] { FrameworkConstants.CommonFrameworks.Net46 } } }; public FrameworkReferenceResolver(string referenceAssembliesPath) { ReferenceAssembliesPath = referenceAssembliesPath; } public string ReferenceAssembliesPath { get; } public static FrameworkReferenceResolver Default { get { if (_default == null) { _default = new FrameworkReferenceResolver(GetDefaultReferenceAssembliesPath()); } return _default; } } public static string GetDefaultReferenceAssembliesPath() { // Allow setting the reference assemblies path via an environment variable var referenceAssembliesPath = DotNetReferenceAssembliesPathResolver.Resolve(); if (!string.IsNullOrEmpty(referenceAssembliesPath)) { return referenceAssembliesPath; } if (RuntimeEnvironment.OperatingSystemPlatform != Platform.Windows) { // There is no reference assemblies path outside of windows // The environment variable can be used to specify one return null; } // References assemblies are in %ProgramFiles(x86)% on // 64 bit machines var programFiles = Environment.GetEnvironmentVariable("ProgramFiles(x86)"); if (string.IsNullOrEmpty(programFiles)) { // On 32 bit machines they are in %ProgramFiles% programFiles = Environment.GetEnvironmentVariable("ProgramFiles"); } if (string.IsNullOrEmpty(programFiles)) { // Reference assemblies aren't installed return null; } return Path.Combine( programFiles, "Reference Assemblies", "Microsoft", "Framework"); } public bool TryGetAssembly(string name, NuGetFramework targetFramework, out string path, out Version version) { path = null; version = null; var information = _cache.GetOrAdd(targetFramework, GetFrameworkInformation); if (information == null || !information.Exists) { return false; } lock (information.Assemblies) { AssemblyEntry entry; if (information.Assemblies.TryGetValue(name, out entry)) { if (string.IsNullOrEmpty(entry.Path)) { entry.Path = GetAssemblyPath(information.SearchPaths, name); } if (!string.IsNullOrEmpty(entry.Path) && entry.Version == null) { // This code path should only run on mono entry.Version = VersionUtility.GetAssemblyVersion(entry.Path).Version; } path = entry.Path; version = entry.Version; } } return !string.IsNullOrEmpty(path); } public bool IsInstalled(NuGetFramework targetFramework) { var information = _cache.GetOrAdd(targetFramework, GetFrameworkInformation); return information?.Exists == true; } public string GetFrameworkRedistListPath(NuGetFramework targetFramework) { var information = _cache.GetOrAdd(targetFramework, GetFrameworkInformation); if (information == null || !information.Exists) { return null; } return information.RedistListPath; } public string GetFriendlyFrameworkName(NuGetFramework targetFramework) { var frameworkName = new FrameworkName(targetFramework.DotNetFrameworkName); // We don't have a friendly name for this anywhere on the machine so hard code it if (string.Equals(frameworkName.Identifier, VersionUtility.DnxCoreFrameworkIdentifier, StringComparison.OrdinalIgnoreCase)) { return "DNX Core 5.0"; } else if (string.Equals(frameworkName.Identifier, VersionUtility.DnxFrameworkIdentifier, StringComparison.OrdinalIgnoreCase)) { return "DNX " + targetFramework.Version.ToString(); } else if (string.Equals(frameworkName.Identifier, VersionUtility.NetPlatformFrameworkIdentifier, StringComparison.OrdinalIgnoreCase)) { var version = targetFramework.Version > Constants.Version50 ? (" " + targetFramework.Version.ToString()) : string.Empty; return ".NET Platform" + version; } var information = _cache.GetOrAdd(targetFramework, GetFrameworkInformation); if (information == null) { return SynthesizeFrameworkFriendlyName(targetFramework); } return information.Name; } private FrameworkInformation GetFrameworkInformation(NuGetFramework targetFramework) { string referenceAssembliesPath = ReferenceAssembliesPath; if (string.IsNullOrEmpty(referenceAssembliesPath)) { return null; } NuGetFramework[] candidates; if (_aliases.TryGetValue(targetFramework, out candidates)) { foreach (var framework in candidates) { var information = GetFrameworkInformation(framework); if (information != null) { return information; } } return null; } else { return GetFrameworkInformation(targetFramework, referenceAssembliesPath); } } private static FrameworkInformation GetFrameworkInformation(NuGetFramework targetFramework, string referenceAssembliesPath) { // Check for legacy frameworks if (RuntimeEnvironment.OperatingSystemPlatform == Platform.Windows && targetFramework.IsDesktop() && targetFramework.Version <= new Version(3, 5, 0, 0)) { return GetLegacyFrameworkInformation(targetFramework, referenceAssembliesPath); } var basePath = Path.Combine(referenceAssembliesPath, targetFramework.Framework, "v" + GetDisplayVersion(targetFramework)); if (!string.IsNullOrEmpty(targetFramework.Profile)) { basePath = Path.Combine(basePath, "Profile", targetFramework.Profile); } var version = new DirectoryInfo(basePath); if (!version.Exists) { return null; } return GetFrameworkInformation(version, targetFramework, referenceAssembliesPath); } private static FrameworkInformation GetLegacyFrameworkInformation(NuGetFramework targetFramework, string referenceAssembliesPath) { var frameworkInfo = new FrameworkInformation(); // Always grab .NET 2.0 data var searchPaths = new List<string>(); var net20Dir = Path.Combine(Environment.GetEnvironmentVariable("WINDIR"), "Microsoft.NET", "Framework", "v2.0.50727"); if (!Directory.Exists(net20Dir)) { return null; } // Grab reference assemblies first, if present for this framework if (targetFramework.Version.Major == 3) { // Most specific first (i.e. 3.5) if (targetFramework.Version.Minor == 5) { var refAsms35Dir = Path.Combine(referenceAssembliesPath, "v3.5"); if (!string.IsNullOrEmpty(targetFramework.Profile)) { // The 3.5 Client Profile assemblies ARE in .NETFramework... it's weird. refAsms35Dir = Path.Combine(referenceAssembliesPath, ".NETFramework", "v3.5", "Profile", targetFramework.Profile); } if (Directory.Exists(refAsms35Dir)) { searchPaths.Add(refAsms35Dir); } } // Always search the 3.0 reference assemblies if (string.IsNullOrEmpty(targetFramework.Profile)) { // a) 3.0 didn't have profiles // b) When using a profile, we don't want to fall back to 3.0 or 2.0 var refAsms30Dir = Path.Combine(referenceAssembliesPath, "v3.0"); if (Directory.Exists(refAsms30Dir)) { searchPaths.Add(refAsms30Dir); } } } // .NET 2.0 reference assemblies go last (but only if there's no profile in the TFM) if (string.IsNullOrEmpty(targetFramework.Profile)) { searchPaths.Add(net20Dir); } frameworkInfo.Exists = true; frameworkInfo.Path = searchPaths.First(); frameworkInfo.SearchPaths = searchPaths; // Load the redist list in reverse order (most general -> most specific) for (int i = searchPaths.Count - 1; i >= 0; i--) { var dir = new DirectoryInfo(searchPaths[i]); if (dir.Exists) { PopulateFromRedistList(dir, targetFramework, referenceAssembliesPath, frameworkInfo); } } if (string.IsNullOrEmpty(frameworkInfo.Name)) { frameworkInfo.Name = SynthesizeFrameworkFriendlyName(targetFramework); } return frameworkInfo; } private static string SynthesizeFrameworkFriendlyName(NuGetFramework targetFramework) { // Names are not present in the RedistList.xml file for older frameworks or on Mono // We do some custom version string rendering to match how net40 is rendered (.NET Framework 4) if (targetFramework.Framework.Equals(FrameworkConstants.FrameworkIdentifiers.Net)) { string versionString = targetFramework.Version.Minor == 0 ? targetFramework.Version.Major.ToString() : GetDisplayVersion(targetFramework).ToString(); string profileString = string.IsNullOrEmpty(targetFramework.Profile) ? string.Empty : $" {targetFramework.Profile} Profile"; return ".NET Framework " + versionString + profileString; } return targetFramework.ToString(); } private static FrameworkInformation GetFrameworkInformation(DirectoryInfo directory, NuGetFramework targetFramework, string referenceAssembliesPath) { var frameworkInfo = new FrameworkInformation(); frameworkInfo.Exists = true; frameworkInfo.Path = directory.FullName; frameworkInfo.SearchPaths = new[] { frameworkInfo.Path, Path.Combine(frameworkInfo.Path, "Facades") }; PopulateFromRedistList(directory, targetFramework, referenceAssembliesPath, frameworkInfo); if (string.IsNullOrEmpty(frameworkInfo.Name)) { frameworkInfo.Name = SynthesizeFrameworkFriendlyName(targetFramework); } return frameworkInfo; } private static void PopulateFromRedistList(DirectoryInfo directory, NuGetFramework targetFramework, string referenceAssembliesPath, FrameworkInformation frameworkInfo) { // The redist list contains the list of assemblies for this target framework string redistList = Path.Combine(directory.FullName, "RedistList", "FrameworkList.xml"); if (File.Exists(redistList)) { frameworkInfo.RedistListPath = redistList; using (var stream = File.OpenRead(redistList)) { var frameworkList = XDocument.Load(stream); // Remember the original search paths, because we might need them later var originalSearchPaths = frameworkInfo.SearchPaths; // There are some frameworks, that "inherit" from a base framework, like // e.g. .NET 4.0.3, and MonoAndroid. var includeFrameworkVersion = frameworkList.Root.Attribute("IncludeFramework")?.Value; if (includeFrameworkVersion != null) { // Get the NuGetFramework identifier for the framework to include var includeFramework = NuGetFramework.Parse($"{targetFramework.Framework}, Version={includeFrameworkVersion}"); // Recursively call the code to get the framework information var includeFrameworkInfo = GetFrameworkInformation(includeFramework, referenceAssembliesPath); // Append the search paths of the included framework frameworkInfo.SearchPaths = frameworkInfo.SearchPaths.Concat(includeFrameworkInfo.SearchPaths).ToArray(); // Add the assemblies of the included framework foreach (var assemblyEntry in includeFrameworkInfo.Assemblies) { frameworkInfo.Assemblies[assemblyEntry.Key] = assemblyEntry.Value; } } // On mono, the RedistList.xml has an entry pointing to the TargetFrameworkDirectory // It basically uses the GAC as the reference assemblies for all .NET framework // profiles var targetFrameworkDirectory = frameworkList.Root.Attribute("TargetFrameworkDirectory")?.Value; IEnumerable<string> populateFromPaths; if (!string.IsNullOrEmpty(targetFrameworkDirectory)) { // For some odd reason, the paths are actually listed as \ so normalize them here targetFrameworkDirectory = targetFrameworkDirectory.Replace('\\', Path.DirectorySeparatorChar); // The specified path is the relative path from the RedistList.xml itself var resovledPath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(redistList), targetFrameworkDirectory)); // Update the path to the framework frameworkInfo.Path = resovledPath; populateFromPaths = new List<string> { resovledPath, Path.Combine(resovledPath, "Facades") }; } else { var emptyFileElements = true; foreach (var e in frameworkList.Root.Elements()) { // Remember that we had at least one framework assembly emptyFileElements = false; var assemblyName = e.Attribute("AssemblyName").Value; var version = e.Attribute("Version")?.Value; var entry = new AssemblyEntry(); entry.Version = version != null ? Version.Parse(version) : null; frameworkInfo.Assemblies[assemblyName] = entry; } if (emptyFileElements) { // When we haven't found any file elements, we probably processed a // Mono/Xamarin FrameworkList.xml. That means, that we have to // populate the assembly list from the files. populateFromPaths = originalSearchPaths; } else { populateFromPaths = null; } } // Do we need to populate from search paths? if (populateFromPaths != null) { foreach (var populateFromPath in populateFromPaths) { PopulateAssemblies(frameworkInfo.Assemblies, populateFromPath); } } var nameAttribute = frameworkList.Root.Attribute("Name"); frameworkInfo.Name = nameAttribute == null ? null : nameAttribute.Value; } } } private static void PopulateAssemblies(IDictionary<string, AssemblyEntry> assemblies, string path) { if (!Directory.Exists(path)) { return; } foreach (var assemblyPath in Directory.GetFiles(path, "*.dll")) { var name = Path.GetFileNameWithoutExtension(assemblyPath); var entry = new AssemblyEntry(); entry.Path = assemblyPath; assemblies[name] = entry; } } private static string GetAssemblyPath(IEnumerable<string> basePaths, string assemblyName) { foreach (var basePath in basePaths) { var assemblyPath = Path.Combine(basePath, assemblyName + ".dll"); if (File.Exists(assemblyPath)) { return assemblyPath; } } return null; } private static Version GetDisplayVersion(NuGetFramework framework) { // Fix the target framework version due to https://github.com/NuGet/Home/issues/1600, this is relevant // when looking up in the reference assembly folder return new FrameworkName(framework.DotNetFrameworkName).Version; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Web.UI; using Juice.Framework; using Juice.Framework.TypeConverters; namespace Juice { [ParseChildren(typeof(TabPage), DefaultProperty = "TabPages", ChildrenAsProperties = true)] [WidgetEvent("beforeLoad")] [WidgetEvent("create")] [WidgetEvent("beforeActivate")] [WidgetEvent("load")] public class Tabs : JuiceScriptControl, IAutoPostBackWidget { private List<TabPage> _tabPages; public Tabs() : base("tabs") { _tabPages = new List<TabPage>(); } [PersistenceMode(PersistenceMode.InnerProperty)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] [TemplateContainer(typeof(TabPage))] public List<TabPage> TabPages { get { return this._tabPages; } } #region Widget Options /// <summary> /// Set to true to allow an already selected tab to become unselected again upon reselection. /// Reference: http://api.jqueryui.com/tabs/#option-collapsible /// </summary> [WidgetOption("collapsible", false)] [Category("Behavior")] [DefaultValue(false)] [Description("Set to true to allow an already selected tab to become unselected again upon reselection.")] public bool Collapsible { get; set; } /// <summary> /// OBSOLETE. Store the latest selected tab in a cookie. The cookie is then used to determine the initially selected tab if the selected option is not defined. Requires cookie plugin, which can also be found in the development-bundle>external folder from the download builder. The object needs to have key/value pairs of the form the cookie plugin expects as options. Available options (example): { expires: 7, path: '/', domain: 'jquery.com', secure: true }. Since jQuery UI 1.7 it is also possible to define the cookie name being used via name property. /// Reference: http://api.jqueryui.com/tabs/#option-cookie /// </summary> [Obsolete("This option will be removed in jQuery UI 1.10.")] public string Cookie { get; set; } /// <summary> /// Disables (true) or enables (false) the widget. /// - OR - /// An array containing the position of the tabs (zero-based index) that should be disabled on initialization. /// Reference: http://api.jqueryui.com/tabs/#option-disabled /// </summary> /* * This is really a one-time case specifically for the tabs widget. No other jQuery UI widgets double up on the disabled option. */ [WidgetOption("disabled", false)] [TypeConverter(typeof(BooleanInt32ArrayConverter))] [Category("Appearance")] [DefaultValue(null)] [Description("Disables (true) or enables (false) the widget. - OR - An array containing the position of the tabs (zero-based index) that should be disabled on initialization.")] public new dynamic Disabled { get; set; } /// <summary> /// The type of event to be used for selecting a tab. /// Reference: http://api.jqueryui.com/tabs/#option-event /// </summary> [WidgetOption("event", "click")] [Category("Behavior")] [DefaultValue("click")] [Description("The type of event to be used for selecting a tab.")] public string Event { get; set; } /// <summary> /// Controls the height of the accordion and each panel. Possible values: /// "auto": All panels will be set to the height of the tallest panel. /// "fill": Expand to the available height based on the accordion's parent height. /// "content": Each panel will be only as tall as its content. /// Reference: http://api.jqueryui.com/tabs/#option-heightstyle /// </summary> [WidgetOption("heightStyle", "{}", Eval = true)] [TypeConverter(typeof(Framework.TypeConverters.JsonObjectConverter))] [Category("Appearance")] [DefaultValue("{}")] [Description(@"Controls the height of the tabs and each panel. Possible values: ""auto"": All panels will be set to the height of the tallest panel. ""fill"": Expand to the available height based on the tabs' parent height. ""content"": Each panel will be only as tall as its content.")] public string HeightStyle { get; set; } /// <summary> /// Specifies if and how to animate the hiding of the panel. /// Reference: http://api.jqueryui.com/tabs/#option-hide /// </summary> [WidgetOption("hide", null)] [TypeConverter(typeof(StringToObjectConverter))] [Category("Behavior")] [DefaultValue(null)] [Description("Specifies if and how to animate the hiding of the panel.")] public dynamic Hide { get; set; } /// <summary> /// Specifies if and how to animate the showing of the panel. /// Reference: http://api.jqueryui.com/tabs/#option-hide /// </summary> [WidgetOption("show", null)] [TypeConverter(typeof(StringToObjectConverter))] [Category("Behavior")] [DefaultValue(null)] [Description("Specifies if and how to animate the showing of the panel.")] public dynamic Show { get; set; } /// <summary> /// OBSOLETE. If the remote tab, its anchor element that is, has no title attribute to generate an id from, an id/fragment identifier is created from this prefix and a unique id returned by $.data(el), for example "ui-tabs-54". /// Reference: http://api.jqueryui.com/tabs/#option-idPrefix /// </summary> [Obsolete("This option will be removed in jQuery UI 1.10.")] public string IdPrefix { get; set; } /// <summary> /// OBSOLETE. HTML template from which a new tab panel is created in case of adding a tab with the add method or when creating a panel for a remote tab on the fly. /// Reference: http://api.jqueryui.com/tabs/#option-panelTemplate /// </summary> [Obsolete("This option will be removed in jQuery UI 1.10.")] public string PanelTemplate { get; set; } /// <summary> /// Zero-based index of the tab to be selected on initialization. To set all tabs to unselected pass -1 as value. /// Reference: http://api.jqueryui.com/tabs/#option-selected /// </summary> [WidgetOption("active", 0)] [Category("Behavior")] [DefaultValue(0)] [Description("Zero-based index of the tab to be selected on initialization. To set all tabs to unselected pass -1 as value.")] public int Active { get; set; } /// <summary> /// OBSOLETE. The HTML content of this string is shown in a tab title while remote content is loading. Pass in empty string to deactivate that behavior. An span element must be present in the A tag of the title, for the spinner content to be visible. /// Reference: http://api.jqueryui.com/tabs/#option-spinner /// </summary> [Obsolete("This option will be removed in jQuery UI 1.10.")] public string Spinner { get; set; } /// <summary> /// OBSOLETE. HTML template from which a new tab is created and added. The placeholders #{href} and #{label} are replaced with the url and tab label that are passed as arguments to the add method. /// Reference: http://api.jqueryui.com/tabs/#option-tabTemplate /// </summary> [Obsolete("This option will be removed in jQuery UI 1.10.")] public string TabTemplate { get; set; } #endregion #region Obsolete Widget Options [Obsolete("This property has been deprecated in jQuery UI 1.9. Use Active instead.", true)] public int Selected { get; set; } [Obsolete("This property has been deprecated in jQuery UI 1.9. Use beforeLoad instead. See: http://stage.jqueryui.com/upgrade-guide/1.9/#deprecated-ajaxoptions-and-cache-options-added-beforeload-event", true)] public string AjaxOptions { get; set; } [Obsolete("This property has been deprecated in jQuery UI 1.9. Use beforeLoad instead. See: http://stage.jqueryui.com/upgrade-guide/1.9/#deprecated-ajaxoptions-and-cache-options-added-beforeload-event", true)] public bool Cache { get; set; } [Obsolete("This property has been deprecated in jQuery UI 1.9. Use Hide or Show instead.", true)] public string Fx { get; set; } #endregion #region Widget Events /// <summary> /// This event is triggered when clicking a tab. /// Reference: http://api.jqueryui.com/tabs/#event-select /// </summary> [WidgetEvent("activate", AutoPostBack = true)] [Category("Action")] [Description("This event is triggered when clicking a tab.")] public event EventHandler ActiveTabChanged; [Obsolete("This event has been deprecated in jQuery UI 1.9. Use ActiveTabChanged instead.", true)] public event EventHandler SelectedTabChanged; #endregion protected override HtmlTextWriterTag TagKey { get { return HtmlTextWriterTag.Div; } } public override ControlCollection Controls { get { this.EnsureChildControls(); return base.Controls; } } protected override void OnPreRender(EventArgs e) { this.Controls.Clear(); if(TabPages != null) { foreach(TabPage page in TabPages) { this.Controls.Add(page); } } base.OnPreRender(e); } protected override void Render(HtmlTextWriter writer) { this.RenderBeginTag(writer); writer.WriteBeginTag("ul"); writer.Write(HtmlTextWriter.TagRightChar); if(TabPages != null) { foreach(TabPage page in TabPages) { writer.WriteFullBeginTag("li"); writer.WriteBeginTag("a"); writer.WriteAttribute("href", "#" + page.ClientID); writer.Write(HtmlTextWriter.TagRightChar); writer.Write(page.Title); writer.WriteEndTag("a"); writer.WriteEndTag("li"); } } writer.WriteEndTag("ul"); this.RenderChildren(writer); this.RenderEndTag(writer); } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski 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. // namespace NLog.UnitTests.Targets.Wrappers { using System; using System.Threading; using NUnit.Framework; #if !NUNIT using SetUp = Microsoft.VisualStudio.TestTools.UnitTesting.TestInitializeAttribute; using TestFixture = Microsoft.VisualStudio.TestTools.UnitTesting.TestClassAttribute; using Test = Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute; using TearDown = Microsoft.VisualStudio.TestTools.UnitTesting.TestCleanupAttribute; #endif using NLog.Common; using NLog.Internal; using NLog.Targets; using NLog.Targets.Wrappers; [TestFixture] public class BufferingTargetWrapperTests : NLogTestBase { [Test] public void BufferingTargetWrapperSyncTest1() { var myTarget = new MyTarget(); var targetWrapper = new BufferingTargetWrapper { WrappedTarget = myTarget, BufferSize = 10, }; myTarget.Initialize(null); targetWrapper.Initialize(null); int totalEvents = 100; var continuationHit = new bool[totalEvents]; var lastException = new Exception[totalEvents]; var continuationThread = new Thread[totalEvents]; int hitCount = 0; CreateContinuationFunc createAsyncContinuation = eventNumber => ex => { lastException[eventNumber] = ex; continuationThread[eventNumber] = Thread.CurrentThread; continuationHit[eventNumber] = true; Interlocked.Increment(ref hitCount); }; // write 9 events - they will all be buffered and no final continuation will be reached int eventCounter = 0; for (int i = 0; i < 9; ++i) { targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); } Assert.AreEqual(0, hitCount); Assert.AreEqual(0, myTarget.WriteCount); // write one more event - everything will be flushed targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); Assert.AreEqual(10, hitCount); Assert.AreEqual(1, myTarget.BufferedWriteCount); Assert.AreEqual(10, myTarget.BufferedTotalEvents); Assert.AreEqual(10, myTarget.WriteCount); for (int i = 0; i < hitCount; ++i) { Assert.AreSame(Thread.CurrentThread, continuationThread[i]); Assert.IsNull(lastException[i]); } // write 9 more events - they will all be buffered and no final continuation will be reached for (int i = 0; i < 9; ++i) { targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); } // no change Assert.AreEqual(10, hitCount); Assert.AreEqual(1, myTarget.BufferedWriteCount); Assert.AreEqual(10, myTarget.BufferedTotalEvents); Assert.AreEqual(10, myTarget.WriteCount); Exception flushException = null; var flushHit = new ManualResetEvent(false); targetWrapper.Flush( ex => { flushException = ex; flushHit.Set(); }); Thread.Sleep(1000); flushHit.WaitOne(); Assert.IsNull(flushException); // make sure remaining events were written Assert.AreEqual(19, hitCount); Assert.AreEqual(2, myTarget.BufferedWriteCount); Assert.AreEqual(19, myTarget.BufferedTotalEvents); Assert.AreEqual(19, myTarget.WriteCount); Assert.AreEqual(1, myTarget.FlushCount); // flushes happen on the same thread for (int i = 10; i < hitCount; ++i) { Assert.IsNotNull(continuationThread[i]); Assert.AreSame(Thread.CurrentThread, continuationThread[i], "Invalid thread #" + i); Assert.IsNull(lastException[i]); } // flush again - should just invoke Flush() on the wrapped target flushHit.Reset(); targetWrapper.Flush( ex => { flushException = ex; flushHit.Set(); }); flushHit.WaitOne(); Assert.AreEqual(19, hitCount); Assert.AreEqual(2, myTarget.BufferedWriteCount); Assert.AreEqual(19, myTarget.BufferedTotalEvents); Assert.AreEqual(19, myTarget.WriteCount); Assert.AreEqual(2, myTarget.FlushCount); targetWrapper.Close(); myTarget.Close(); } [Test] public void BufferingTargetWrapperSyncWithTimedFlushTest() { var myTarget = new MyTarget(); var targetWrapper = new BufferingTargetWrapper { WrappedTarget = myTarget, BufferSize = 10, FlushTimeout = 1000, }; myTarget.Initialize(null); targetWrapper.Initialize(null); int totalEvents = 100; var continuationHit = new bool[totalEvents]; var lastException = new Exception[totalEvents]; var continuationThread = new Thread[totalEvents]; int hitCount = 0; CreateContinuationFunc createAsyncContinuation = eventNumber => ex => { lastException[eventNumber] = ex; continuationThread[eventNumber] = Thread.CurrentThread; continuationHit[eventNumber] = true; Interlocked.Increment(ref hitCount); }; // write 9 events - they will all be buffered and no final continuation will be reached int eventCounter = 0; for (int i = 0; i < 9; ++i) { targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); } Assert.AreEqual(0, hitCount); Assert.AreEqual(0, myTarget.WriteCount); // sleep 2 seconds, this will trigger the timer and flush all events Thread.Sleep(4000); Assert.AreEqual(9, hitCount); Assert.AreEqual(1, myTarget.BufferedWriteCount); Assert.AreEqual(9, myTarget.BufferedTotalEvents); Assert.AreEqual(9, myTarget.WriteCount); for (int i = 0; i < hitCount; ++i) { Assert.AreNotSame(Thread.CurrentThread, continuationThread[i]); Assert.IsNull(lastException[i]); } // write 11 more events, 10 will be hit immediately because the buffer will fill up // 1 will be pending for (int i = 0; i < 11; ++i) { targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); } Assert.AreEqual(19, hitCount); Assert.AreEqual(2, myTarget.BufferedWriteCount); Assert.AreEqual(19, myTarget.BufferedTotalEvents); Assert.AreEqual(19, myTarget.WriteCount); // sleep 2 seonds and the last remaining one will be flushed Thread.Sleep(2000); Assert.AreEqual(20, hitCount); Assert.AreEqual(3, myTarget.BufferedWriteCount); Assert.AreEqual(20, myTarget.BufferedTotalEvents); Assert.AreEqual(20, myTarget.WriteCount); } [Test] public void BufferingTargetWrapperAsyncTest1() { var myTarget = new MyAsyncTarget(); var targetWrapper = new BufferingTargetWrapper { WrappedTarget = myTarget, BufferSize = 10, }; myTarget.Initialize(null); targetWrapper.Initialize(null); int totalEvents = 100; var continuationHit = new bool[totalEvents]; var lastException = new Exception[totalEvents]; var continuationThread = new Thread[totalEvents]; int hitCount = 0; CreateContinuationFunc createAsyncContinuation = eventNumber => ex => { lastException[eventNumber] = ex; continuationThread[eventNumber] = Thread.CurrentThread; continuationHit[eventNumber] = true; Interlocked.Increment(ref hitCount); }; // write 9 events - they will all be buffered and no final continuation will be reached int eventCounter = 0; for (int i = 0; i < 9; ++i) { targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); } Assert.AreEqual(0, hitCount); // write one more event - everything will be flushed targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); while (hitCount < 10) { Thread.Sleep(10); } Assert.AreEqual(10, hitCount); Assert.AreEqual(1, myTarget.BufferedWriteCount); Assert.AreEqual(10, myTarget.BufferedTotalEvents); for (int i = 0; i < hitCount; ++i) { Assert.AreNotSame(Thread.CurrentThread, continuationThread[i]); Assert.IsNull(lastException[i]); } // write 9 more events - they will all be buffered and no final continuation will be reached for (int i = 0; i < 9; ++i) { targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); } // no change Assert.AreEqual(10, hitCount); Assert.AreEqual(1, myTarget.BufferedWriteCount); Assert.AreEqual(10, myTarget.BufferedTotalEvents); Exception flushException = null; var flushHit = new ManualResetEvent(false); targetWrapper.Flush( ex => { flushException = ex; flushHit.Set(); }); Thread.Sleep(1000); flushHit.WaitOne(); Assert.IsNull(flushException); // make sure remaining events were written Assert.AreEqual(19, hitCount); Assert.AreEqual(2, myTarget.BufferedWriteCount); Assert.AreEqual(19, myTarget.BufferedTotalEvents); // flushes happen on another thread for (int i = 10; i < hitCount; ++i) { Assert.IsNotNull(continuationThread[i]); Assert.AreNotSame(Thread.CurrentThread, continuationThread[i], "Invalid thread #" + i); Assert.IsNull(lastException[i]); } // flush again - should not do anything flushHit.Reset(); targetWrapper.Flush( ex => { flushException = ex; flushHit.Set(); }); flushHit.WaitOne(); Assert.AreEqual(19, hitCount); Assert.AreEqual(2, myTarget.BufferedWriteCount); Assert.AreEqual(19, myTarget.BufferedTotalEvents); targetWrapper.Close(); myTarget.Close(); } [Test] public void BufferingTargetWrapperSyncWithTimedFlushNonSlidingTest() { var myTarget = new MyTarget(); var targetWrapper = new BufferingTargetWrapper { WrappedTarget = myTarget, BufferSize = 10, FlushTimeout = 400, SlidingTimeout = false, }; myTarget.Initialize(null); targetWrapper.Initialize(null); int totalEvents = 100; var continuationHit = new bool[totalEvents]; var lastException = new Exception[totalEvents]; var continuationThread = new Thread[totalEvents]; int hitCount = 0; CreateContinuationFunc createAsyncContinuation = eventNumber => ex => { lastException[eventNumber] = ex; continuationThread[eventNumber] = Thread.CurrentThread; continuationHit[eventNumber] = true; Interlocked.Increment(ref hitCount); }; int eventCounter = 0; targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); Thread.Sleep(300); Assert.AreEqual(0, hitCount); Assert.AreEqual(0, myTarget.WriteCount); targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); Thread.Sleep(300); Assert.AreEqual(2, hitCount); Assert.AreEqual(2, myTarget.WriteCount); } [Test] public void BufferingTargetWrapperSyncWithTimedFlushSlidingTest() { var myTarget = new MyTarget(); var targetWrapper = new BufferingTargetWrapper { WrappedTarget = myTarget, BufferSize = 10, FlushTimeout = 400, }; myTarget.Initialize(null); targetWrapper.Initialize(null); int totalEvents = 100; var continuationHit = new bool[totalEvents]; var lastException = new Exception[totalEvents]; var continuationThread = new Thread[totalEvents]; int hitCount = 0; CreateContinuationFunc createAsyncContinuation = eventNumber => ex => { lastException[eventNumber] = ex; continuationThread[eventNumber] = Thread.CurrentThread; continuationHit[eventNumber] = true; Interlocked.Increment(ref hitCount); }; int eventCounter = 0; targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); Thread.Sleep(300); Assert.AreEqual(0, hitCount); Assert.AreEqual(0, myTarget.WriteCount); targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++))); Thread.Sleep(300); Assert.AreEqual(0, hitCount); Assert.AreEqual(0, myTarget.WriteCount); Thread.Sleep(200); Assert.AreEqual(2, hitCount); Assert.AreEqual(2, myTarget.WriteCount); } class MyAsyncTarget : Target { public int BufferedWriteCount { get; set; } public int BufferedTotalEvents { get; set; } protected override void Write(LogEventInfo logEvent) { throw new NotSupportedException(); } protected override void Write(AsyncLogEventInfo[] logEvents) { this.BufferedWriteCount++; this.BufferedTotalEvents += logEvents.Length; for (int i = 0; i < logEvents.Length; ++i) { var logEvent = logEvents[i]; ThreadPool.QueueUserWorkItem( s => { if (this.ThrowExceptions) { logEvent.Continuation(new InvalidOperationException("Some problem!")); logEvent.Continuation(new InvalidOperationException("Some problem!")); } else { logEvent.Continuation(null); logEvent.Continuation(null); } }); } } protected override void FlushAsync(AsyncContinuation asyncContinuation) { ThreadPool.QueueUserWorkItem( s => asyncContinuation(null)); } public bool ThrowExceptions { get; set; } } class MyTarget : Target { public int FlushCount { get; set; } public int WriteCount { get; set; } public int BufferedWriteCount { get; set; } public int BufferedTotalEvents { get; set; } protected override void Write(AsyncLogEventInfo[] logEvents) { this.BufferedWriteCount++; this.BufferedTotalEvents += logEvents.Length; base.Write(logEvents); } protected override void Write(LogEventInfo logEvent) { Assert.IsTrue(this.FlushCount <= this.WriteCount); this.WriteCount++; } protected override void FlushAsync(AsyncContinuation asyncContinuation) { this.FlushCount++; asyncContinuation(null); } } private delegate AsyncContinuation CreateContinuationFunc(int eventNumber); } }
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using BenderProxy; using BenderProxy.Writers; using NUnit.Framework; using OpenQA.Selenium.Environment; using OpenQA.Selenium.IE; namespace OpenQA.Selenium { [TestFixture] public class ProxySettingTest : DriverTestFixture { private IWebDriver localDriver; private ProxyServer proxyServer; [SetUp] public void RestartOriginalDriver() { driver = EnvironmentManager.Instance.GetCurrentDriver(); proxyServer = new ProxyServer(); EnvironmentManager.Instance.DriverStarting += EnvironmentManagerDriverStarting; } [TearDown] public void QuitAdditionalDriver() { if (localDriver != null) { localDriver.Quit(); localDriver = null; } if (proxyServer != null) { proxyServer.Quit(); proxyServer = null; } EnvironmentManager.Instance.DriverStarting -= EnvironmentManagerDriverStarting; } [Test] [IgnoreBrowser(Browser.Safari, "SafariDriver does not support setting proxy")] [IgnoreBrowser(Browser.Edge, "EdgeDriver does not support setting proxy")] public void CanConfigureManualHttpProxy() { proxyServer.EnableLogResourcesOnResponse(); Proxy proxyToUse = proxyServer.AsProxy(); InitLocalDriver(proxyToUse); localDriver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("simpleTest.html"); Assert.That(proxyServer.HasBeenCalled("simpleTest.html"), Is.True); } [Test] [IgnoreBrowser(Browser.Safari, "SafariDriver does not support setting proxy")] [IgnoreBrowser(Browser.Edge, "EdgeDriver does not support setting proxy")] public void CanConfigureNoProxy() { proxyServer.EnableLogResourcesOnResponse(); Proxy proxyToUse = proxyServer.AsProxy(); proxyToUse.AddBypassAddresses(EnvironmentManager.Instance.UrlBuilder.HostName); if (TestUtilities.IsInternetExplorer(driver)) { proxyToUse.AddBypassAddress("<-localhost>"); } InitLocalDriver(proxyToUse); localDriver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("simpleTest.html"); Assert.That(proxyServer.HasBeenCalled("simpleTest.html"), Is.False); localDriver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIsViaNonLoopbackAddress("simpleTest.html"); Assert.That(proxyServer.HasBeenCalled("simpleTest.html"), Is.True); } [Test] [IgnoreBrowser(Browser.Safari, "SafariDriver does not support setting proxy")] [IgnoreBrowser(Browser.Edge, "EdgeDriver does not support setting proxy")] public void CanConfigureProxyThroughAutoConfigFile() { StringBuilder pacFileContentBuilder = new StringBuilder(); pacFileContentBuilder.AppendLine("function FindProxyForURL(url, host) {"); pacFileContentBuilder.AppendFormat(" return 'PROXY {0}';\n", proxyServer.BaseUrl); pacFileContentBuilder.AppendLine("}"); string pacFileContent = pacFileContentBuilder.ToString(); using (ProxyAutoConfigServer pacServer = new ProxyAutoConfigServer(pacFileContent)) { proxyServer.EnableContentOverwriteOnRequest(); Proxy proxyToUse = new Proxy(); proxyToUse.ProxyAutoConfigUrl = string.Format("http://{0}:{1}/proxy.pac", pacServer.HostName, pacServer.Port); InitLocalDriver(proxyToUse); localDriver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("simpleTest.html"); Assert.That(localDriver.FindElement(By.TagName("h3")).Text, Is.EqualTo("Hello, world!")); } } [Test] [IgnoreBrowser(Browser.Safari, "SafariDriver does not support setting proxy")] [IgnoreBrowser(Browser.Edge, "EdgeDriver does not support setting proxy")] public void CanUseAutoConfigFileThatOnlyProxiesCertainHosts() { StringBuilder pacFileContentBuilder = new StringBuilder(); pacFileContentBuilder.AppendLine("function FindProxyForURL(url, host) {"); pacFileContentBuilder.AppendFormat(" if (url.indexOf('{0}') != -1) {{\n", EnvironmentManager.Instance.UrlBuilder.HostName); pacFileContentBuilder.AppendFormat(" return 'PROXY {0}';\n", proxyServer.BaseUrl); pacFileContentBuilder.AppendLine(" }"); pacFileContentBuilder.AppendLine(" return 'DIRECT';"); pacFileContentBuilder.AppendLine("}"); string pacFileContent = pacFileContentBuilder.ToString(); using (ProxyAutoConfigServer pacServer = new ProxyAutoConfigServer(pacFileContent)) { proxyServer.EnableContentOverwriteOnRequest(); Proxy proxyToUse = new Proxy(); proxyToUse.ProxyAutoConfigUrl = string.Format("http://{0}:{1}/proxy.pac", pacServer.HostName, pacServer.Port); InitLocalDriver(proxyToUse); localDriver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("simpleTest.html"); Assert.That(localDriver.FindElement(By.TagName("h3")).Text, Is.EqualTo("Hello, world!")); localDriver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIsViaNonLoopbackAddress("simpleTest.html"); Assert.That(localDriver.FindElement(By.TagName("h1")).Text, Is.EqualTo("Heading")); } } private void EnvironmentManagerDriverStarting(object sender, DriverStartingEventArgs e) { InternetExplorerOptions ieOptions = e.Options as InternetExplorerOptions; if (ieOptions != null) { ieOptions.EnsureCleanSession = true; } } private void InitLocalDriver(Proxy proxy) { EnvironmentManager.Instance.CloseCurrentDriver(); if (localDriver != null) { localDriver.Quit(); } ProxyOptions options = new ProxyOptions(); options.Proxy = proxy; localDriver = EnvironmentManager.Instance.CreateDriverInstance(options); } private class ProxyOptions : DriverOptions { [Obsolete] public override void AddAdditionalCapability(string capabilityName, object capabilityValue) { } public override ICapabilities ToCapabilities() { return null; } } private class ProxyAutoConfigServer : IDisposable { private int listenerPort; private string hostName; private string pacFileContent; private bool disposedValue = false; // To detect redundant calls private bool keepRunning = true; private HttpListener listener; private Thread listenerThread; public ProxyAutoConfigServer(string pacFileContent) : this(pacFileContent, "localhost") { } public ProxyAutoConfigServer(string pacFileContent, string hostName) { this.pacFileContent = pacFileContent; this.hostName = hostName; //get an empty port TcpListener l = new TcpListener(IPAddress.Loopback, 0); l.Start(); this.listenerPort = ((IPEndPoint)l.LocalEndpoint).Port; l.Stop(); this.listenerThread = new Thread(this.Listen); this.listenerThread.Start(); } public string HostName { get { return hostName; } } public int Port { get { return listenerPort; } } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { this.keepRunning = false; this.listenerThread.Join(TimeSpan.FromSeconds(5)); this.listener.Stop(); } disposedValue = true; } } private void ProcessContext(HttpListenerContext context) { if (context.Request.Url.AbsoluteUri.ToLowerInvariant().Contains("proxy.pac")) { byte[] pacFileBuffer = Encoding.ASCII.GetBytes(this.pacFileContent); context.Response.ContentType = "application/x-javascript-config"; context.Response.ContentLength64 = pacFileBuffer.LongLength; context.Response.ContentEncoding = Encoding.ASCII; context.Response.StatusCode = 200; context.Response.OutputStream.Write(pacFileBuffer, 0, pacFileBuffer.Length); context.Response.OutputStream.Flush(); } } private void Listen() { listener = new HttpListener(); listener.Prefixes.Add("http://" + this.HostName + ":" + this.listenerPort.ToString() + "/"); listener.Start(); while (this.keepRunning) { try { HttpListenerContext context = listener.GetContext(); this.ProcessContext(context); } catch (HttpListenerException) { } } } } private class ProxyServer { private HttpProxyServer server; private List<string> uris = new List<string>(); int port; string hostName = string.Empty; public ProxyServer() : this("127.0.0.1") { } public ProxyServer(string hostName) { this.hostName = hostName; this.server = new HttpProxyServer(this.hostName, new HttpProxy()); this.server.Start().WaitOne(); this.port = this.server.ProxyEndPoint.Port; // this.server.Log += OnServerLog; } public string BaseUrl { get { return string.Format("{0}:{1}", this.hostName, this.port); } } public HttpProxyServer Server { get { return this.server; } } public string HostName { get { return hostName; } } public int Port { get { return port; } } public void EnableLogResourcesOnResponse() { this.server.Proxy.OnResponseSent = this.LogRequestedResources; } public void DisableLogResourcesOnResponse() { this.server.Proxy.OnResponseSent = null; } public void EnableContentOverwriteOnRequest() { this.server.Proxy.OnRequestReceived = this.OverwriteRequestedContent; } public void DisableContentOverwriteOnRequest() { this.server.Proxy.OnRequestReceived = null; } public bool HasBeenCalled(string resourceName) { return this.uris.Contains(resourceName); } public void Quit() { this.server.Proxy.OnResponseSent = null; this.server.Stop(); } public Proxy AsProxy() { Proxy proxy = new Proxy(); proxy.HttpProxy = this.BaseUrl; return proxy; } private void OnServerLog(object sender, BenderProxy.Logging.LogEventArgs e) { Console.WriteLine(e.LogMessage); } private void LogRequestedResources(ProcessingContext context) { string[] parts = context.RequestHeader.RequestURI.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 0) { string finalPart = parts[parts.Length - 1]; uris.Add(finalPart); } } private void OverwriteRequestedContent(ProcessingContext context) { StringBuilder pageContentBuilder = new StringBuilder("<!DOCTYPE html>"); pageContentBuilder.AppendLine("<html>"); pageContentBuilder.AppendLine("<head>"); pageContentBuilder.AppendLine(" <title>Hello</title>"); pageContentBuilder.AppendLine("</head>"); pageContentBuilder.AppendLine("<body>"); pageContentBuilder.AppendLine(" <h3>Hello, world!</h3>"); pageContentBuilder.AppendLine("</body>"); pageContentBuilder.AppendLine("</html>"); string pageContent = pageContentBuilder.ToString(); context.StopProcessing(); MemoryStream responseStream = new MemoryStream(Encoding.UTF8.GetBytes(pageContent)); var responseHeader = new BenderProxy.Headers.HttpResponseHeader(200, "OK", "1.1"); responseHeader.EntityHeaders.ContentType = "text/html"; responseHeader.EntityHeaders.ContentEncoding = "utf-8"; responseHeader.EntityHeaders.ContentLength = responseStream.Length; new HttpResponseWriter(context.ClientStream).Write(responseHeader, responseStream, responseStream.Length); } } } }
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 T with 3 columns and 3 rows. /// </summary> [Serializable] [DataContract(Namespace = "mat")] [StructLayout(LayoutKind.Sequential)] public struct gmat3<T> : IReadOnlyList<T>, IEquatable<gmat3<T>> { #region Fields /// <summary> /// Column 0, Rows 0 /// </summary> [DataMember] public T m00; /// <summary> /// Column 0, Rows 1 /// </summary> [DataMember] public T m01; /// <summary> /// Column 0, Rows 2 /// </summary> [DataMember] public T m02; /// <summary> /// Column 1, Rows 0 /// </summary> [DataMember] public T m10; /// <summary> /// Column 1, Rows 1 /// </summary> [DataMember] public T m11; /// <summary> /// Column 1, Rows 2 /// </summary> [DataMember] public T m12; /// <summary> /// Column 2, Rows 0 /// </summary> [DataMember] public T m20; /// <summary> /// Column 2, Rows 1 /// </summary> [DataMember] public T m21; /// <summary> /// Column 2, Rows 2 /// </summary> [DataMember] public T m22; #endregion #region Constructors /// <summary> /// Component-wise constructor /// </summary> public gmat3(T m00, T m01, T m02, T m10, T m11, T m12, T m20, T m21, T m22) { this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m20 = m20; this.m21 = m21; this.m22 = m22; } /// <summary> /// Constructs this matrix from a gmat2. Non-overwritten fields are from an Identity matrix. /// </summary> public gmat3(gmat2<T> m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = default(T); this.m10 = m.m10; this.m11 = m.m11; this.m12 = default(T); this.m20 = default(T); this.m21 = default(T); this.m22 = default(T); } /// <summary> /// Constructs this matrix from a gmat3x2. Non-overwritten fields are from an Identity matrix. /// </summary> public gmat3(gmat3x2<T> m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = default(T); this.m10 = m.m10; this.m11 = m.m11; this.m12 = default(T); this.m20 = m.m20; this.m21 = m.m21; this.m22 = default(T); } /// <summary> /// Constructs this matrix from a gmat4x2. Non-overwritten fields are from an Identity matrix. /// </summary> public gmat3(gmat4x2<T> m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = default(T); this.m10 = m.m10; this.m11 = m.m11; this.m12 = default(T); this.m20 = m.m20; this.m21 = m.m21; this.m22 = default(T); } /// <summary> /// Constructs this matrix from a gmat2x3. Non-overwritten fields are from an Identity matrix. /// </summary> public gmat3(gmat2x3<T> m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m20 = default(T); this.m21 = default(T); this.m22 = default(T); } /// <summary> /// Constructs this matrix from a gmat3. Non-overwritten fields are from an Identity matrix. /// </summary> public gmat3(gmat3<T> m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m20 = m.m20; this.m21 = m.m21; this.m22 = m.m22; } /// <summary> /// Constructs this matrix from a gmat4x3. Non-overwritten fields are from an Identity matrix. /// </summary> public gmat3(gmat4x3<T> m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m20 = m.m20; this.m21 = m.m21; this.m22 = m.m22; } /// <summary> /// Constructs this matrix from a gmat2x4. Non-overwritten fields are from an Identity matrix. /// </summary> public gmat3(gmat2x4<T> m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m20 = default(T); this.m21 = default(T); this.m22 = default(T); } /// <summary> /// Constructs this matrix from a gmat3x4. Non-overwritten fields are from an Identity matrix. /// </summary> public gmat3(gmat3x4<T> m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m20 = m.m20; this.m21 = m.m21; this.m22 = m.m22; } /// <summary> /// Constructs this matrix from a gmat4. Non-overwritten fields are from an Identity matrix. /// </summary> public gmat3(gmat4<T> m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m20 = m.m20; this.m21 = m.m21; this.m22 = m.m22; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public gmat3(gvec2<T> c0, gvec2<T> c1) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = default(T); this.m10 = c1.x; this.m11 = c1.y; this.m12 = default(T); this.m20 = default(T); this.m21 = default(T); this.m22 = default(T); } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public gmat3(gvec2<T> c0, gvec2<T> c1, gvec2<T> c2) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = default(T); this.m10 = c1.x; this.m11 = c1.y; this.m12 = default(T); this.m20 = c2.x; this.m21 = c2.y; this.m22 = default(T); } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public gmat3(gvec3<T> c0, gvec3<T> c1) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = c0.z; this.m10 = c1.x; this.m11 = c1.y; this.m12 = c1.z; this.m20 = default(T); this.m21 = default(T); this.m22 = default(T); } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public gmat3(gvec3<T> c0, gvec3<T> c1, gvec3<T> c2) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = c0.z; this.m10 = c1.x; this.m11 = c1.y; this.m12 = c1.z; this.m20 = c2.x; this.m21 = c2.y; this.m22 = c2.z; } #endregion #region Properties /// <summary> /// Creates a 2D array with all values (address: Values[x, y]) /// </summary> public T[,] Values => new[,] { { m00, m01, m02 }, { m10, m11, m12 }, { m20, m21, m22 } }; /// <summary> /// Creates a 1D array with all values (internal order) /// </summary> public T[] Values1D => new[] { m00, m01, m02, m10, m11, m12, m20, m21, m22 }; /// <summary> /// Gets or sets the column nr 0 /// </summary> public gvec3<T> Column0 { get { return new gvec3<T>(m00, m01, m02); } set { m00 = value.x; m01 = value.y; m02 = value.z; } } /// <summary> /// Gets or sets the column nr 1 /// </summary> public gvec3<T> Column1 { get { return new gvec3<T>(m10, m11, m12); } set { m10 = value.x; m11 = value.y; m12 = value.z; } } /// <summary> /// Gets or sets the column nr 2 /// </summary> public gvec3<T> Column2 { get { return new gvec3<T>(m20, m21, m22); } set { m20 = value.x; m21 = value.y; m22 = value.z; } } /// <summary> /// Gets or sets the row nr 0 /// </summary> public gvec3<T> Row0 { get { return new gvec3<T>(m00, m10, m20); } set { m00 = value.x; m10 = value.y; m20 = value.z; } } /// <summary> /// Gets or sets the row nr 1 /// </summary> public gvec3<T> Row1 { get { return new gvec3<T>(m01, m11, m21); } set { m01 = value.x; m11 = value.y; m21 = value.z; } } /// <summary> /// Gets or sets the row nr 2 /// </summary> public gvec3<T> Row2 { get { return new gvec3<T>(m02, m12, m22); } set { m02 = value.x; m12 = value.y; m22 = value.z; } } #endregion #region Static Properties /// <summary> /// Predefined all-zero matrix /// </summary> public static gmat3<T> Zero { get; } = new gmat3<T>(default(T), default(T), default(T), default(T), default(T), default(T), default(T), default(T), default(T)); #endregion #region Functions /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> public IEnumerator<T> GetEnumerator() { yield return m00; yield return m01; yield return m02; yield return m10; yield return m11; yield return m12; yield return m20; yield return m21; yield return m22; } /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); #endregion /// <summary> /// Returns the number of Fields (3 x 3 = 9). /// </summary> public int Count => 9; /// <summary> /// Gets/Sets a specific indexed component (a bit slower than direct access). /// </summary> public T this[int fieldIndex] { get { switch (fieldIndex) { case 0: return m00; case 1: return m01; case 2: return m02; case 3: return m10; case 4: return m11; case 5: return m12; case 6: return m20; case 7: return m21; case 8: return m22; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } set { switch (fieldIndex) { case 0: this.m00 = value; break; case 1: this.m01 = value; break; case 2: this.m02 = value; break; case 3: this.m10 = value; break; case 4: this.m11 = value; break; case 5: this.m12 = value; break; case 6: this.m20 = value; break; case 7: this.m21 = value; break; case 8: this.m22 = value; break; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } } /// <summary> /// Gets/Sets a specific 2D-indexed component (a bit slower than direct access). /// </summary> public T this[int col, int row] { get { return this[col * 3 + row]; } set { this[col * 3 + row] = value; } } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public bool Equals(gmat3<T> rhs) => ((((EqualityComparer<T>.Default.Equals(m00, rhs.m00) && EqualityComparer<T>.Default.Equals(m01, rhs.m01)) && EqualityComparer<T>.Default.Equals(m02, rhs.m02)) && (EqualityComparer<T>.Default.Equals(m10, rhs.m10) && EqualityComparer<T>.Default.Equals(m11, rhs.m11))) && ((EqualityComparer<T>.Default.Equals(m12, rhs.m12) && EqualityComparer<T>.Default.Equals(m20, rhs.m20)) && (EqualityComparer<T>.Default.Equals(m21, rhs.m21) && EqualityComparer<T>.Default.Equals(m22, rhs.m22)))); /// <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 gmat3<T> && Equals((gmat3<T>) obj); } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool operator ==(gmat3<T> lhs, gmat3<T> rhs) => lhs.Equals(rhs); /// <summary> /// Returns true iff this does not equal rhs (component-wise). /// </summary> public static bool operator !=(gmat3<T> lhs, gmat3<T> rhs) => !lhs.Equals(rhs); /// <summary> /// Returns a hash code for this instance. /// </summary> public override int GetHashCode() { unchecked { return ((((((((((((((((EqualityComparer<T>.Default.GetHashCode(m00)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(m01)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(m02)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(m10)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(m11)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(m12)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(m20)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(m21)) * 397) ^ EqualityComparer<T>.Default.GetHashCode(m22); } } /// <summary> /// Returns a transposed version of this matrix. /// </summary> public gmat3<T> Transposed => new gmat3<T>(m00, m10, m20, m01, m11, m21, m02, m12, m22); } }
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD. // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. using System; using System.Linq.Expressions; using Xunit; namespace Moq.Tests { public class ActionObserverFixture { public class Reconstructibility { // NOTE: These tests might look pointless at first glance, until you notice // the signature of `AssertReconstructable`: delegates are being compared to // LINQ expression trees for equality. [Fact] public void Void_method_call() { AssertReconstructable( x => x.Void(), x => x.Void()); } [Fact] public void Void_method_call_with_arg() { AssertReconstructable( x => x.VoidWithInt(42), x => x.VoidWithInt(42)); } [Fact] public void Void_method_call_with_coerced_arg() { AssertReconstructable( x => x.VoidWithLong(42), x => x.VoidWithLong(42)); } [Fact] public void Void_method_call_with_coerced_nullable_arg() { AssertReconstructable( "x => x.VoidWithNullableInt(42)", x => x.VoidWithNullableInt(42)); } [Fact] public void Void_method_call_with_cast_arg() { AssertReconstructable( x => x.VoidWithInt((int)42L), x => x.VoidWithInt((int)42L)); } [Fact] public void Void_method_call_with_arg_evaluated() { int arg = 42; AssertReconstructable( x => x.VoidWithInt(42), x => x.VoidWithInt(arg)); } [Fact] public void Void_method_call_on_sub_object() { AssertReconstructable( x => x.GetY().Z.Void(), x => x.GetY().Z.Void()); } [Fact] public void Void_method_call_on_sub_with_several_args() { AssertReconstructable( x => x.GetY(1).Z.VoidWithIntInt(2, 3), x => x.GetY(1).Z.VoidWithIntInt(2, 3)); } [Fact] public void Void_method_call_with_matcher() { AssertReconstructable( x => x.VoidWithInt(It.IsAny<int>()), x => x.VoidWithInt(It.IsAny<int>())); } [Fact] public void Void_method_call_with_matcher_of_assignment_compatible_type() { AssertReconstructable( x => x.VoidWithObject(It.IsAny<int>()), x => x.VoidWithObject(It.IsAny<int>())); } [Fact] public void Void_method_call_with_matcher_in_first_of_three_invocations() { AssertReconstructable( x => x.GetY(It.IsAny<int>()).Z.VoidWithIntInt(0, 0), x => x.GetY(It.IsAny<int>()).Z.VoidWithIntInt(0, 0)); } [Fact] public void Void_method_call_with_matcher_in_third_of_three_invocations_1() { AssertReconstructable( x => x.GetY(0).Z.VoidWithIntInt(1, It.IsAny<int>()), x => x.GetY(0).Z.VoidWithIntInt(1, It.IsAny<int>())); } [Fact] public void Void_method_call_with_matcher_in_third_of_three_invocations_2() { AssertReconstructable( x => x.GetY(0).Z.VoidWithIntInt(It.IsAny<int>(), 2), x => x.GetY(0).Z.VoidWithIntInt(It.IsAny<int>(), 2)); } [Fact] public void Void_method_call_with_matcher_in_first_and_third_of_three_invocations() { AssertReconstructable( "x => x.GetY(It.Is<int>(i => i % 2 == 0)).Z.VoidWithIntInt(It.IsAny<int>(), 2)", x => x.GetY(It.Is<int>(i => i % 2 == 0)).Z.VoidWithIntInt(It.IsAny<int>(), 2)); } [Fact] public void Method_with_matchers_after_default_arg() { // This demonstrates that even though the first argument has a default value, // the matcher isn't placed there, because it has a type (string) that won't fit (int). AssertReconstructable( x => x.VoidWithIntString(0, It.IsAny<string>()), x => x.VoidWithIntString(0, It.IsAny<string>())); } [Fact] public void Assignment() { AssertReconstructable( "x => x.GetY().Z.Property = \"value\"", x => x.GetY().Z.Property = "value" ); } [Fact] public void Assignment_with_captured_var_on_rhs() { var arg = "value"; AssertReconstructable( "x => x.GetY().Z.Property = \"value\"", x => x.GetY().Z.Property = arg); } [Fact] public void Assignment_with_matcher_on_rhs() { AssertReconstructable( "x => x.GetY().Z.Property = It.IsAny<string>()", x => x.GetY().Z.Property = It.IsAny<string>()); } [Fact] public void Indexer_assignment_with_arg() { AssertReconstructable( "x => x[1] = null", x => x[1] = null); } [Fact] public void Indexer_assignment_with_matcher_on_lhs_1() { AssertReconstructable( "x => x[It.IsAny<int>()] = null", x => x[It.IsAny<int>()] = null); } [Fact] public void Indexer_assignment_with_matcher_on_lhs_2() { AssertReconstructable( "x => x[1, It.IsAny<int>()] = 0", x => x[1, It.IsAny<int>()] = 0); } [Fact] public void Indexer_assignment_with_matcher_on_rhs() { AssertReconstructable( "x => x[1] = It.IsAny<ActionObserverFixture.Reconstructibility.IY>()", x => x[1] = It.IsAny<ActionObserverFixture.Reconstructibility.IY>()); } [Fact] public void Indexer_assignment_with_matchers_everywhere() { AssertReconstructable( "x => x[It.Is<int>(i => i == 0), It.Is<int>(i => i == 2)] = It.Is<int>(i => i == 3)", x => x[It.Is<int>(i => i == 0), It.Is<int>(i => i == 2)] = It.Is<int>(i => i == 3)); } [Fact] public void Widening_and_narrowing_and_enum_convertions() { ushort arg = 123; AssertReconstructable( "x => x.VoidWithShort(123)", x => x.VoidWithShort((short)arg)); AssertReconstructable( "x => x.VoidWithInt(123)", x => x.VoidWithInt(arg)); AssertReconstructable( "x => x.VoidWithLong(123)", x => x.VoidWithLong(arg)); long longArg = 654L; AssertReconstructable( "x => x.VoidWithShort(654)", x => x.VoidWithShort((short)longArg)); AssertReconstructable( "x => x.VoidWithObject(ActionObserverFixture.Reconstructibility.Color.Green)", x => x.VoidWithObject(Color.Green)); AssertReconstructable( "x => x.VoidWithEnum(ActionObserverFixture.Reconstructibility.Color.Green)", x => x.VoidWithEnum(Color.Green)); AssertReconstructable( "x => x.VoidWithNullableEnum(ActionObserverFixture.Reconstructibility.Color.Green)", x => x.VoidWithNullableEnum(Color.Green)); } [Fact] public void It_IsAny_enum_converted_and_assigned_to_int_parameter() { AssertReconstructable( x => x.VoidWithInt((int)It.IsAny<Color>()), x => x.VoidWithInt((int)It.IsAny<Color>())); } [Fact] public void It_IsAny_short_widened_to_int_parameter() { AssertReconstructable( x => x.VoidWithInt(It.IsAny<short>()), x => x.VoidWithInt(It.IsAny<short>())); } private void AssertReconstructable(string expected, Action<IX> action) { Expression actual = ActionObserver.Instance.ReconstructExpression(action); actual = PrepareForComparison.Instance.Visit(actual); Assert.Equal(expected, actual.ToStringFixed()); } private void AssertReconstructable(Expression<Action<IX>> expected, Action<IX> action) { Expression actual = ActionObserver.Instance.ReconstructExpression(action); expected = (Expression<Action<IX>>)PrepareForComparison.Instance.Visit(expected); actual = PrepareForComparison.Instance.Visit(actual); Assert.Equal(expected, actual, ExpressionComparer.Default); } public interface IX { IY this[int index] { get; set; } int this[int index1, int index2] { get; set; } IY GetY(); IY GetY(int arg); void Void(); void VoidWithShort(short arg); void VoidWithInt(int arg); void VoidWithLong(long arg); void VoidWithNullableInt(int? arg); void VoidWithIntString(int arg1, string arg2); void VoidWithObject(object arg); void VoidWithEnum(Color arg); void VoidWithNullableEnum(Color? arg); } public interface IY { IZ Z { get; } } public interface IZ { object Property { get; set; } void Void(); void VoidWithIntInt(int arg1, int arg2); } public enum Color { Red, Green, Blue, Yellow, } } public class Error_detection { [Fact] public void Stops_before_non_interceptable_method() { AssertFailsAfter<X>("x => x...", x => x.NonVirtual()); } [Fact] public void Stops_before_non_interceptable_property() { AssertFailsAfter<X>("x => x...", x => x.NonVirtualProperty = It.IsAny<IY>()); } [Fact] public void Stops_after_non_interceptable_return_type() { AssertFailsAfter<IX>("x => x.SealedY...", x => x.SealedY.Method()); } private void AssertFailsAfter<TRoot>(string expectedPartial, Action<TRoot> action) { var error = Assert.Throws<ArgumentException>(() => ActionObserver.Instance.ReconstructExpression(action)); Assert.Contains($": {expectedPartial}", error.Message); } public interface IX { IY Y { get; } SealedY SealedY { get; } } public class X { public IY NonVirtualProperty { get; set; } public void NonVirtual() { } } public interface IY { void Method(int arg1, int arg2); } public sealed class SealedY { public void Method() { } } } // These tests document limitations of the current implementation. public class Limitations { [Fact] public void Method_with_matchers_after_default_arg() { // This is because parameters with default values are filled from left to right. AssertIncorrectlyReconstructsAs( x => x.Method(It.IsAny<int>(), 0 ), x => x.Method(0 , It.IsAny<int>())); } [Fact] public void Indexer_with_default_value_on_lfs_and_matcher_on_rhs_both_having_same_types() { // Same as above, since LHS and RHS are actually both part of a single parameter list of a method call `get_Item(...lhs, rhs). AssertIncorrectlyReconstructsAs( "x => x[It.IsAny<int>()] = 0", x => x[0 ] = It.IsAny<int>()); } private void AssertIncorrectlyReconstructsAs(string expected, Action<IX> action) { Expression actual = ActionObserver.Instance.ReconstructExpression(action); actual = PrepareForComparison.Instance.Visit(actual); Assert.Equal(expected, actual.ToStringFixed()); } private void AssertIncorrectlyReconstructsAs(Expression<Action<IX>> expected, Action<IX> action) { Expression actual = ActionObserver.Instance.ReconstructExpression(action); expected = (Expression<Action<IX>>)PrepareForComparison.Instance.Visit(expected); actual = PrepareForComparison.Instance.Visit(actual); Assert.Equal(expected, actual, ExpressionComparer.Default); } public interface IX { int this[int index] { get; set; } void Method(int arg1, int arg2); } } // The expression trees reconstructed by `ActionObserver` may differ from those // produced by the Roslyn compilers in some minor regards that shouldn't actually // matter to program execution; however `ExpressionComparer` will notice the // differences, making above tests fail. Because of this, we try to "equalize" // expressions created by the Roslyn compilers (`expected`) and those produced // by `ActionObserver` (`actual`) using this expression visitor: private sealed class PrepareForComparison : ExpressionVisitor { public static readonly PrepareForComparison Instance = new PrepareForComparison(); protected override Expression VisitExtension(Expression node) { if (node is MatchExpression me) { // Resolve `MatchExpression`s to their matcher's `RenderExpression`: return me.Match.RenderExpression; } else { return base.VisitExtension(node); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json; using Pulsar4X.Entities; using Pulsar4X.Helpers.GameMath; using Pulsar4X.Helpers; using System.ComponentModel; namespace Pulsar4X.Entities { /// <summary> /// Calculates and handles orbits for bodies. /// All angles stored in Degrees, but calculated in Radians. /// </summary> public class Orbit { #region Properties /// <summary> /// Mass in KG of this entity. /// </summary> public double Mass { get { return m_mass; } } private double m_mass; /// <summary> /// Mass in Earth Masses of this entity. /// </summary> public double MassRelativeToEarth { get { return m_mass / Constants.Units.EarthMassInKG; } } /// <summary> /// Mass in Solar Masses of this entity. /// </summary> public double MassRelativeToSol { get { return m_mass / Constants.Units.SolarMassInKG; } } /// <summary> /// Mass in KG of parent (object this orbit orbits) /// </summary> public double ParentMass { get { return m_parentMass; } } private double m_parentMass; /// <summary> /// Semimajor Axis of orbit stored in AU. /// Average distance of orbit from center. /// </summary> public double SemiMajorAxis { get; set; } /// <summary> /// Eccentricity of orbit. /// Shape of the orbit. 0 = perfectly circular, 1 = parabolic. /// </summary> public double Eccentricity { get; set; } /// <summary> /// Angle between the orbit and the flat referance plane. /// Stored in degrees. /// </summary> public double Inclination { get; set; } /// <summary> /// Horizontal orientation of the point where the orbit crosses /// the referance frame stored in degrees. /// </summary> public double LongitudeOfAscendingNode { get; set; } /// <summary> /// Angle from the Ascending Node to the Periapsis stored in degrees. /// </summary> public double ArgumentOfPeriapsis { get; set; } /// <summary> /// Definition of the position of the body in the orbit at the referance time /// epoch. Mathematically convienant angle does not correspond to a real angle. /// Stored in degrees. /// </summary> public double MeanAnomaly { get; set; } /// <summary> /// Referance time. Orbital parameters are stored relative to this referance. /// </summary> public DateTime Epoch { get; set; } /// <summary> /// 2-Body gravitational parameter of system. /// </summary> public double GravitationalParameter { get { return m_gravitationalParameter; } } private double m_gravitationalParameter; /// <summary> /// Orbital Period of orbit. /// </summary> public TimeSpan OrbitalPeriod { get { return m_orbitalPeriod; } } private TimeSpan m_orbitalPeriod; /// <summary> /// Mean Motion of orbit. Stored as Degrees/Sec. /// </summary> public double MeanMotion { get { return m_meanMotion; } } private double m_meanMotion; /// <summary> /// Point in orbit furthest from the ParentBody. Measured in AU. /// </summary> public double Apoapsis { get { return (1 + Eccentricity) * SemiMajorAxis; } } /// <summary> /// Point in orbit closest to the ParentBody. Measured in AU. /// </summary> public double Periapsis { get { return (1 - Eccentricity) * SemiMajorAxis; } } /// <summary> /// Stationary orbits don't have all of the data to update. They always return (0, 0). /// </summary> private bool m_isStationary; #endregion #region Orbit Construction Interface /// <summary> /// Returns an orbit representing the defined parameters. /// </summary> /// <param name="mass">Mass of this object in KG.</param> /// <param name="parentMass">Mass of parent object in KG.</param> /// <param name="semiMajorAxis">SemiMajorAxis of orbit in AU.</param> /// <param name="eccentricity">Eccentricity of orbit.</param> /// <param name="inclination">Inclination of orbit in degrees.</param> /// <param name="longitudeOfAscendingNode">Longitude of ascending node in degrees.</param> /// <param name="longitudeOfPeriapsis">Longitude of periapsis in degrees.</param> /// <param name="meanLongitude">Longitude of object at epoch in degrees.</param> /// <param name="epoch">Referance time for these orbital elements.</param> public static Orbit FromMajorPlanetFormat(double mass, double parentMass, double semiMajorAxis, double eccentricity, double inclination, double longitudeOfAscendingNode, double longitudeOfPeriapsis, double meanLongitude, DateTime epoch) { // http://en.wikipedia.org/wiki/Longitude_of_the_periapsis double argumentOfPeriapsis = longitudeOfPeriapsis - longitudeOfAscendingNode; // http://en.wikipedia.org/wiki/Mean_longitude double meanAnomaly = meanLongitude - (longitudeOfAscendingNode + argumentOfPeriapsis); return new Orbit(mass, parentMass, semiMajorAxis, eccentricity, inclination, longitudeOfAscendingNode, argumentOfPeriapsis, meanAnomaly, epoch); } /// <summary> /// Returns an orbit representing the defined parameters. /// </summary> /// <param name="mass">Mass of this object in KG.</param> /// <param name="parentMass">Mass of parent object in KG.</param> /// <param name="semiMajorAxis">SemiMajorAxis of orbit in AU.</param> /// <param name="eccentricity">Eccentricity of orbit.</param> /// <param name="inclination">Inclination of orbit in degrees.</param> /// <param name="longitudeOfAscendingNode">Longitude of ascending node in degrees.</param> /// <param name="argumentOfPeriapsis">Argument of periapsis in degrees.</param> /// <param name="meanAnomaly">Mean Anomaly in degrees.</param> /// <param name="epoch">Referance time for these orbital elements.</param> public static Orbit FromAsteroidFormat(double mass, double parentMass, double semiMajorAxis, double eccentricity, double inclination, double longitudeOfAscendingNode, double argumentOfPeriapsis, double meanAnomaly, DateTime epoch) { return new Orbit(mass, parentMass, semiMajorAxis, eccentricity, inclination, longitudeOfAscendingNode, argumentOfPeriapsis, meanAnomaly, epoch); } /// <summary> /// Creates an orbit that never moves. /// </summary> public static Orbit FromStationary(double mass) { return new Orbit(mass); } /// <summary> /// Constructor for stationary orbits. /// </summary> private Orbit(double mass) { m_mass = mass; SemiMajorAxis = 0; Eccentricity = 0; m_isStationary = true; } /// <summary> /// Constructor for the orbit. /// Calculates commonly-used parameters for future use. /// </summary> private Orbit(double mass, double parentMass, double semiMajorAxis, double eccentricity, double inclination, double longitudeOfAscendingNode, double argumentOfPeriapsis, double meanAnomaly, DateTime epoch) { m_mass = mass; m_parentMass = parentMass; SemiMajorAxis = semiMajorAxis; Eccentricity = Math.Min(eccentricity, 0.8D); // Max eccentricity is 0.8 Orbit code has issues at higher eccentricity. (Note: If restriction lifed, fix code in GetEccentricAnomaly) Inclination = inclination; LongitudeOfAscendingNode = longitudeOfAscendingNode; ArgumentOfPeriapsis = argumentOfPeriapsis; MeanAnomaly = meanAnomaly; Epoch = epoch; m_isStationary = false; // Calculate extended parameters. // http://en.wikipedia.org/wiki/Standard_gravitational_parameter#Two_bodies_orbiting_each_other m_gravitationalParameter = Constants.Science.GravitationalConstant * (ParentMass + Mass) / (1000 * 1000 * 1000); // Normalize GravitationalParameter from m^3/s^2 to km^3/s^2 // http://en.wikipedia.org/wiki/Orbital_period#Two_bodies_orbiting_each_other double orbitalPeriod = 2 * Math.PI * Math.Sqrt(Math.Pow(Distance.ToKm(SemiMajorAxis), 3) / (GravitationalParameter)); if (orbitalPeriod * 10000000 > Int64.MaxValue) { m_orbitalPeriod = TimeSpan.MaxValue; } else { m_orbitalPeriod = TimeSpan.FromSeconds(orbitalPeriod); } // http://en.wikipedia.org/wiki/Mean_motion m_meanMotion = Math.Sqrt(GravitationalParameter / Math.Pow(Distance.ToKm(SemiMajorAxis), 3)); // Calculated in radians. m_meanMotion = Angle.ToDegrees(m_meanMotion); // Stored in degrees. } #endregion #region Orbit Position Calculations /// <summary> /// Calculates the parent-relative cartesian coordinate of an orbit for a given time. /// </summary> public void GetPosition(DateTime time, out double x, out double y) { if (m_isStationary) { x = 0; y = 0; return; } TimeSpan timeSinceEpoch = time - Epoch; while (timeSinceEpoch > m_orbitalPeriod) { // Don't attempt to calculate large timeframes. timeSinceEpoch -= m_orbitalPeriod; Epoch += m_orbitalPeriod; } // http://en.wikipedia.org/wiki/Mean_anomaly (M = M0 + nT) // Convert MeanAnomaly to radians. double currentMeanAnomaly = Angle.ToRadians(MeanAnomaly); // Add nT currentMeanAnomaly += Angle.ToRadians(MeanMotion) * timeSinceEpoch.TotalSeconds; double EccentricAnomaly = GetEccentricAnomaly(currentMeanAnomaly); // http://en.wikipedia.org/wiki/True_anomaly#From_the_eccentric_anomaly double TrueAnomaly = Math.Atan2(Math.Sqrt(1 - Eccentricity * Eccentricity) * Math.Sin(EccentricAnomaly), Math.Cos(EccentricAnomaly) - Eccentricity); GetPosition(TrueAnomaly, out x, out y); } /// <summary> /// Calculates the cartesian coordinates (relative to it's parent) of an orbit for a given angle. /// </summary> /// <param name="TrueAnomaly">Angle in Radians.</param> public void GetPosition(double TrueAnomaly, out double x, out double y) { if (m_isStationary) { x = 0; y = 0; return; } // http://en.wikipedia.org/wiki/True_anomaly#Radius_from_true_anomaly double radius = Distance.ToKm(SemiMajorAxis) * (1 - Eccentricity * Eccentricity) / (1 + Eccentricity * Math.Cos(TrueAnomaly)); // Adjust TrueAnomaly by the Argument of Periapsis (converted to radians) TrueAnomaly += Angle.ToRadians(ArgumentOfPeriapsis); // Convert KM to AU radius = Distance.ToAU(radius); // Polar to Cartesian conversion. x = radius * Math.Cos(TrueAnomaly); y = radius * Math.Sin(TrueAnomaly); } /// <summary> /// Calculates the current Eccentric Anomaly given certain orbital parameters. /// </summary> private double GetEccentricAnomaly(double currentMeanAnomaly) { //Kepler's Equation List<double> E = new List<double>(); double Epsilon = 1E-12; // Plenty of accuracy. /* Eccentricity is currently clamped @ 0.8 if (Eccentricity > 0.8) { E.Add(Math.PI); } else */ { E.Add(currentMeanAnomaly); } int i = 0; do { // Newton's Method. /* E(n) - e sin(E(n)) - M(t) * E(n+1) = E(n) - ( ------------------------- ) * 1 - e cos(E(n) * * E == EccentricAnomaly, e == Eccentricity, M == MeanAnomaly. * http://en.wikipedia.org/wiki/Eccentric_anomaly#From_the_mean_anomaly */ E.Add(E[i] - ((E[i] - Eccentricity * Math.Sin(E[i]) - currentMeanAnomaly) / (1 - Eccentricity * Math.Cos(E[i])))); i++; } while (Math.Abs(E[i] - E[i - 1]) > Epsilon && i < 1000); if (i > 1000) { // <? todo: Flag an error about non-convergence of Newton's method. } double eccentricAnomaly = E[i - 1]; return E[i - 1]; } #endregion } #region Data Binding /// <summary> /// Used for databinding, see here: http://blogs.msdn.com/b/msdnts/archive/2007/01/19/how-to-bind-a-datagridview-column-to-a-second-level-property-of-a-data-source.aspx /// </summary> public class OrbitTypeDescriptor : CustomTypeDescriptor { public OrbitTypeDescriptor(ICustomTypeDescriptor parent) : base(parent) { } public override PropertyDescriptorCollection GetProperties() { PropertyDescriptorCollection cols = base.GetProperties(); PropertyDescriptor addressPD = cols["Orbit"]; PropertyDescriptorCollection Orbit_child = addressPD.GetChildProperties(); PropertyDescriptor[] array = new PropertyDescriptor[cols.Count + 5]; cols.CopyTo(array, 0); array[cols.Count] = new SubPropertyDescriptor(addressPD, Orbit_child["Mass"], "Orbit_Mass"); array[cols.Count + 1] = new SubPropertyDescriptor(addressPD, Orbit_child["MassRelativeToEarth"], "Orbit_MassRelativeToEarth"); array[cols.Count + 2] = new SubPropertyDescriptor(addressPD, Orbit_child["MassRelativeToSol"], "Orbit_MassRelativeToSol"); array[cols.Count + 3] = new SubPropertyDescriptor(addressPD, Orbit_child["SemiMajorAxis"], "Orbit_SemiMajorAxis"); array[cols.Count + 4] = new SubPropertyDescriptor(addressPD, Orbit_child["OrbitalPeriod"], "Orbit_OrbitalPeriod"); PropertyDescriptorCollection newcols = new PropertyDescriptorCollection(array); return newcols; } public override PropertyDescriptorCollection GetProperties(Attribute[] attributes) { PropertyDescriptorCollection cols = base.GetProperties(attributes); PropertyDescriptor addressPD = cols["Orbit"]; PropertyDescriptorCollection Orbit_child = addressPD.GetChildProperties(); PropertyDescriptor[] array = new PropertyDescriptor[cols.Count + 5]; cols.CopyTo(array, 0); array[cols.Count] = new SubPropertyDescriptor(addressPD, Orbit_child["Mass"], "Orbit_Mass"); array[cols.Count + 1] = new SubPropertyDescriptor(addressPD, Orbit_child["MassRelativeToEarth"], "Orbit_MassRelativeToEarth"); array[cols.Count + 2] = new SubPropertyDescriptor(addressPD, Orbit_child["MassRelativeToSol"], "Orbit_MassRelativeToSol"); array[cols.Count + 3] = new SubPropertyDescriptor(addressPD, Orbit_child["SemiMajorAxis"], "Orbit_SemiMajorAxis"); array[cols.Count + 4] = new SubPropertyDescriptor(addressPD, Orbit_child["OrbitalPeriod"], "Orbit_OrbitalPeriod"); PropertyDescriptorCollection newcols = new PropertyDescriptorCollection(array); return newcols; } } #endregion }
// Copyright (c) 2015 Alachisoft // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.IO; using System.Text; using System.Collections; using System.Net; using System.Configuration; using Alachisoft.NCache.Config; using Alachisoft.NCache.Caching; using Alachisoft.NCache.Runtime.Exceptions; namespace Alachisoft.NCache.Config { /// <summary> /// /// </summary> internal class ChannelConfigBuilder { /// <summary> /// /// </summary> /// <param name="properties"></param> /// <returns></returns> public static string BuildTCPConfiguration(IDictionary properties,long opTimeout) { StringBuilder b = new StringBuilder(2048); b.Append(BuildTCP(properties["tcp"] as IDictionary)).Append(":"); b.Append(BuildTCPPING(properties["tcpping"] as IDictionary)).Append(":"); b.Append(BuildQueue(properties["queue"] as IDictionary)).Append(":"); b.Append(Buildpbcast_GMS(properties["pbcast.gms"] as IDictionary,false)).Append(":"); b.Append(BuildTOTAL(properties["total"] as IDictionary,opTimeout)).Append(":"); b.Append(BuildVIEW_ENFORCER(properties["view-enforcer"] as IDictionary)); return b.ToString(); } public static string BuildTCPConfiguration(IDictionary properties, long opTimeout,bool isPor) { StringBuilder b = new StringBuilder(2048); b.Append(BuildTCP(properties["tcp"] as IDictionary)).Append(":"); b.Append(BuildTCPPING(properties["tcpping"] as IDictionary)).Append(":"); b.Append(BuildQueue(properties["queue"] as IDictionary)).Append(":"); b.Append(Buildpbcast_GMS(properties["pbcast.gms"] as IDictionary,isPor)).Append(":"); b.Append(BuildTOTAL(properties["total"] as IDictionary, opTimeout)).Append(":"); b.Append(BuildVIEW_ENFORCER(properties["view-enforcer"] as IDictionary)); return b.ToString(); } /// <summary> /// /// </summary> /// <param name="properties"></param> /// <returns></returns> public static string BuildUDPConfiguration(IDictionary properties) { StringBuilder b = new StringBuilder(2048); b.Append(BuildUDP(properties["udp"] as IDictionary)).Append(":"); b.Append(BuildPING(properties["ping"] as IDictionary)).Append(":"); b.Append(BuildMERGEFAST(properties["mergefast"] as IDictionary)).Append(":"); b.Append(BuildFD_SOCK(properties["fd-sock"] as IDictionary)).Append(":"); b.Append(BuildVERIFY_SUSPECT(properties["verify-suspect"] as IDictionary)).Append(":"); b.Append(BuildFRAG(properties["frag"] as IDictionary)).Append(":"); b.Append(BuildUNICAST(properties["unicast"] as IDictionary)).Append(":"); b.Append(BuildQueue(properties["queue"] as IDictionary)).Append(":"); b.Append(Buildpbcast_NAKACK(properties["pbcast.nakack"] as IDictionary)).Append(":"); b.Append(Buildpbcast_STABLE(properties["pbcast.stable"] as IDictionary)).Append(":"); b.Append(Buildpbcast_GMS(properties["pbcast.gms"] as IDictionary,false)).Append(":"); b.Append(BuildTOTAL(properties["total"] as IDictionary,5000)).Append(":"); b.Append(BuildVIEW_ENFORCER(properties["view-enforcer"] as IDictionary)); return b.ToString(); } private static string BuildUDP(IDictionary properties) { StringBuilder b = new StringBuilder(256); b.Append("UDP(") .Append(ConfigHelper.SafeGetPair(properties,"mcast_addr", "239.0.1.10")) .Append(ConfigHelper.SafeGetPair(properties,"mcast_port", 10001)) .Append(ConfigHelper.SafeGetPair(properties,"bind_addr", null)) .Append(ConfigHelper.SafeGetPair(properties,"bind_port", null)) .Append(ConfigHelper.SafeGetPair(properties,"port_range", 256)) .Append(ConfigHelper.SafeGetPair(properties,"ip_mcast", null)) //"false" .Append(ConfigHelper.SafeGetPair(properties,"mcast_send_buf_size", null)) //32000 .Append(ConfigHelper.SafeGetPair(properties,"mcast_recv_buf_size", null)) //64000 .Append(ConfigHelper.SafeGetPair(properties,"ucast_send_buf_size", null)) //32000 .Append(ConfigHelper.SafeGetPair(properties,"ucast_recv_buf_size", null)) //64000 .Append(ConfigHelper.SafeGetPair(properties,"max_bundle_size", null)) //32000 .Append(ConfigHelper.SafeGetPair(properties,"max_bundle_timeout", null)) //20 .Append(ConfigHelper.SafeGetPair(properties,"enable_bundling", null)) //"false" .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"use_incoming_packet_handler", null)) .Append(ConfigHelper.SafeGetPair(properties,"use_outgoing_packet_handler", null)) .Append("ip_ttl=32;") .Append(")"); return b.ToString(); } private static string BuildPING(IDictionary properties) { StringBuilder b = new StringBuilder(256); b.Append("PING(") .Append(ConfigHelper.SafeGetPair(properties,"timeout", null)) //2000 .Append(ConfigHelper.SafeGetPair(properties,"num_initial_members", null)) //2 .Append(ConfigHelper.SafeGetPair(properties,"port_range", null)) //1 .Append(ConfigHelper.SafeGetPair(properties,"initial_hosts", null)) .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(")"); return b.ToString(); } private static string BuildMERGEFAST(IDictionary properties) { StringBuilder b = new StringBuilder(16); b.Append("MERGEFAST(") .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(")"); return b.ToString(); } private static string BuildFD_SOCK(IDictionary properties) { StringBuilder b = new StringBuilder(64); b.Append("FD_SOCK(") .Append(ConfigHelper.SafeGetPair(properties,"get_cache_timeout", null)) //3000 .Append(ConfigHelper.SafeGetPair(properties,"start_port", null)) //49152 .Append(ConfigHelper.SafeGetPair(properties,"num_tries", null)) //3 .Append(ConfigHelper.SafeGetPair(properties,"suspect_msg_interval", null)) //5000 .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(")"); return b.ToString(); } private static string BuildVERIFY_SUSPECT(IDictionary properties) { StringBuilder b = new StringBuilder(32); b.Append("VERIFY_SUSPECT(") .Append(ConfigHelper.SafeGetPair(properties,"timeout", 1500)) .Append(ConfigHelper.SafeGetPair(properties,"num_msgs", null)) // null .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(")"); return b.ToString(); } private static string BuildQueue(IDictionary properties) { StringBuilder b = new StringBuilder(32); b.Append("QUEUE(") .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(")"); return b.ToString(); } private static string Buildpbcast_NAKACK(IDictionary properties) { StringBuilder b = new StringBuilder(128); b.Append("pbcast.NAKACK(") .Append(ConfigHelper.SafeGetPair(properties,"retransmit_timeout", null)) //"600,1200,2400,4800" .Append(ConfigHelper.SafeGetPair(properties,"gc_lag", 40)) .Append(ConfigHelper.SafeGetPair(properties,"max_xmit_size", null)) // 8192 .Append(ConfigHelper.SafeGetPair(properties,"use_mcast_xmit", null)) // "false" .Append(ConfigHelper.SafeGetPair(properties,"discard_delivered_msgs", null)) // "true" .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(")"); return b.ToString(); } private static string BuildUNICAST(IDictionary properties) { StringBuilder b = new StringBuilder(64); b.Append("UNICAST(") .Append(ConfigHelper.SafeGetPair(properties,"timeout", null)) // "800,1600,3200,6400" .Append(ConfigHelper.SafeGetPair(properties,"window_size", null)) // -1 .Append(ConfigHelper.SafeGetPair(properties,"min_threshold", null)) // -1 //.Append(ConfigHelper.SafeGetPair(properties,"use_gms", null)) // "true" .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(")"); return b.ToString(); } private static string Buildpbcast_STABLE(IDictionary properties) { StringBuilder b = new StringBuilder(256); b.Append("pbcast.STABLE(") .Append(ConfigHelper.SafeGetPair(properties,"digest_timeout", null)) // 60000 .Append(ConfigHelper.SafeGetPair(properties,"desired_avg_gossip", null)) // 20000 .Append(ConfigHelper.SafeGetPair(properties,"stability_delay", null)) // 6000 .Append(ConfigHelper.SafeGetPair(properties,"max_gossip_runs", null)) // 3 .Append(ConfigHelper.SafeGetPair(properties,"max_bytes", null)) // 0 .Append(ConfigHelper.SafeGetPair(properties,"max_suspend_time", null)) // 600000 .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(")"); return b.ToString(); } private static string BuildFRAG(IDictionary properties) { StringBuilder b = new StringBuilder(32); b.Append("FRAG(") .Append(ConfigHelper.SafeGetPair(properties,"frag_size", null)) .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(")"); return b.ToString(); } private static string Buildpbcast_GMS(IDictionary properties,bool isPor) { StringBuilder b = new StringBuilder(256); if (isPor) { if (properties == null) properties = new Hashtable(); properties["is_part_replica"]= "true"; } b.Append("pbcast.GMS(") .Append(ConfigHelper.SafeGetPair(properties,"shun", null)) // "true" .Append(ConfigHelper.SafeGetPair(properties,"join_timeout", null)) // 5000 .Append(ConfigHelper.SafeGetPair(properties,"join_retry_timeout", null)) // 2000 .Append(ConfigHelper.SafeGetPair(properties, "join_retry_count", null)) // 3 .Append(ConfigHelper.SafeGetPair(properties,"leave_timeout", null)) // 5000 .Append(ConfigHelper.SafeGetPair(properties,"merge_timeout", null)) // 10000 .Append(ConfigHelper.SafeGetPair(properties,"digest_timeout", null)) // 5000 .Append(ConfigHelper.SafeGetPair(properties,"disable_initial_coord", null)) // false .Append(ConfigHelper.SafeGetPair(properties,"num_prev_mbrs", null)) // 50 .Append(ConfigHelper.SafeGetPair(properties,"print_local_addr", null)) // false .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(ConfigHelper.SafeGetPair(properties, "is_part_replica", null)) .Append(")"); return b.ToString(); } private static string BuildTOTAL(IDictionary properties,long opTimeout) { StringBuilder b = new StringBuilder(8); b.Append("TOTAL(") .Append(ConfigHelper.SafeGetPair(properties,"timeout", null)) //"600,1200,2400,4800" .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(ConfigHelper.SafeGetPair(properties, "op_timeout", opTimeout)) .Append(")"); return b.ToString(); } private static string BuildVIEW_ENFORCER(IDictionary properties) { StringBuilder b = new StringBuilder(16); b.Append("VIEW_ENFORCER(") .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(")"); return b.ToString(); } private static string BuildTCPPING(IDictionary properties) { StringBuilder b = new StringBuilder(256); b.Append("TCPPING(") .Append(ConfigHelper.SafeGetPair(properties,"timeout", null)) //3000 .Append(ConfigHelper.SafeGetPair(properties,"port_range", null)) //5 .Append(ConfigHelper.SafeGetPair(properties,"static", null)) //false .Append(ConfigHelper.SafeGetPair(properties,"num_initial_members", null)) //2 .Append(ConfigHelper.SafeGetPair(properties,"initial_hosts", null)) .Append(ConfigHelper.SafeGetPair(properties,"discovery_addr", "228.8.8.8")) //228.8.8.8 .Append(ConfigHelper.SafeGetPair(properties,"discovery_port", 7700)) //7700 .Append(ConfigHelper.SafeGetPair(properties,"down_thread", null)) .Append(ConfigHelper.SafeGetPair(properties,"up_thread", null)) .Append(")"); return b.ToString(); } private static string BuildTCP(IDictionary properties) { string bindIP = ConfigurationSettings.AppSettings["NCacheServer.BindToIP"]; StringBuilder b = new StringBuilder(256); b.Append("TCP(") .Append(ConfigHelper.SafeGetPair(properties, "connection_retries", 0)) .Append(ConfigHelper.SafeGetPair(properties, "connection_retry_interval", 0)) .Append(ConfigHelper.SafeGetPair(properties, "bind_addr", bindIP)) .Append(ConfigHelper.SafeGetPair(properties, "start_port", null)) .Append(ConfigHelper.SafeGetPair(properties, "port_range", null)) .Append(ConfigHelper.SafeGetPair(properties, "send_buf_size", null)) //32000 .Append(ConfigHelper.SafeGetPair(properties, "recv_buf_size", null)) //64000 .Append(ConfigHelper.SafeGetPair(properties, "reaper_interval", null)) //0 .Append(ConfigHelper.SafeGetPair(properties, "conn_expire_time", null)) //0 .Append(ConfigHelper.SafeGetPair(properties, "skip_suspected_members", null)) //true .Append(ConfigHelper.SafeGetPair(properties, "down_thread", true)) .Append(ConfigHelper.SafeGetPair(properties, "up_thread", true)) .Append(ConfigHelper.SafeGetPair(properties, "use_heart_beat", true)) .Append(ConfigHelper.SafeGetPair(properties, "heart_beat_interval", null)) .Append(")"); return b.ToString(); } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type ContactFolderContactsCollectionRequest. /// </summary> public partial class ContactFolderContactsCollectionRequest : BaseRequest, IContactFolderContactsCollectionRequest { /// <summary> /// Constructs a new ContactFolderContactsCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public ContactFolderContactsCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified Contact to the collection via POST. /// </summary> /// <param name="contact">The Contact to add.</param> /// <returns>The created Contact.</returns> public System.Threading.Tasks.Task<Contact> AddAsync(Contact contact) { return this.AddAsync(contact, CancellationToken.None); } /// <summary> /// Adds the specified Contact to the collection via POST. /// </summary> /// <param name="contact">The Contact to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Contact.</returns> public System.Threading.Tasks.Task<Contact> AddAsync(Contact contact, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<Contact>(contact, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IContactFolderContactsCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IContactFolderContactsCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<ContactFolderContactsCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IContactFolderContactsCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IContactFolderContactsCollectionRequest Expand(Expression<Func<Contact, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IContactFolderContactsCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IContactFolderContactsCollectionRequest Select(Expression<Func<Contact, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IContactFolderContactsCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IContactFolderContactsCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IContactFolderContactsCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IContactFolderContactsCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return 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 System.Threading; namespace System.Runtime { // AsyncResult starts acquired; Complete releases. [Fx.Tag.SynchronizationPrimitive(Fx.Tag.BlocksUsing.ManualResetEvent, SupportsAsync = true, ReleaseMethod = "Complete")] internal abstract class AsyncResult : IAsyncResult { private static AsyncCallback s_asyncCompletionWrapperCallback; private AsyncCallback _callback; private bool _endCalled; private Exception _exception; private AsyncCompletion _nextAsyncCompletion; private Action _beforePrepareAsyncCompletionAction; private Func<IAsyncResult, bool> _checkSyncValidationFunc; [Fx.Tag.SynchronizationObject] private ManualResetEvent _manualResetEvent; [Fx.Tag.SynchronizationObject(Blocking = false)] private object _thisLock; protected AsyncResult(AsyncCallback callback, object state) { _callback = callback; AsyncState = state; _thisLock = new object(); } public object AsyncState { get; } public WaitHandle AsyncWaitHandle { get { if (_manualResetEvent != null) { return _manualResetEvent; } lock (ThisLock) { if (_manualResetEvent == null) { _manualResetEvent = new ManualResetEvent(IsCompleted); } } return _manualResetEvent; } } public bool CompletedSynchronously { get; private set; } public bool HasCallback { get { return _callback != null; } } public bool IsCompleted { get; private set; } // used in conjunction with PrepareAsyncCompletion to allow for finally blocks protected Action<AsyncResult, Exception> OnCompleting { get; set; } private object ThisLock { get { return _thisLock; } } // subclasses like TraceAsyncResult can use this to wrap the callback functionality in a scope protected Action<AsyncCallback, IAsyncResult> VirtualCallback { get; set; } protected void Complete(bool completedSynchronously) { if (IsCompleted) { throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.AsyncResultCompletedTwice(GetType()))); } CompletedSynchronously = completedSynchronously; if (OnCompleting != null) { // Allow exception replacement, like a catch/throw pattern. try { OnCompleting(this, _exception); } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } _exception = exception; } } if (completedSynchronously) { // If we completedSynchronously, then there's no chance that the manualResetEvent was created so // we don't need to worry about a race condition. Fx.Assert(_manualResetEvent == null, "No ManualResetEvent should be created for a synchronous AsyncResult."); IsCompleted = true; } else { lock (ThisLock) { IsCompleted = true; if (_manualResetEvent != null) { _manualResetEvent.Set(); } } } if (_callback != null) { try { if (VirtualCallback != null) { VirtualCallback(_callback, this); } else { _callback(this); } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } throw Fx.Exception.AsError(new CallbackException(InternalSR.AsyncCallbackThrewException, e)); } } } protected void Complete(bool completedSynchronously, Exception exception) { _exception = exception; Complete(completedSynchronously); } private static void AsyncCompletionWrapperCallback(IAsyncResult result) { if (result == null) { throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.InvalidNullAsyncResult)); } if (result.CompletedSynchronously) { return; } AsyncResult thisPtr = (AsyncResult)result.AsyncState; if (!thisPtr.OnContinueAsyncCompletion(result)) { return; } AsyncCompletion callback = thisPtr.GetNextCompletion(); if (callback == null) { ThrowInvalidAsyncResult(result); } bool completeSelf = false; Exception completionException = null; try { completeSelf = callback(result); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } completeSelf = true; completionException = e; } if (completeSelf) { thisPtr.Complete(false, completionException); } } // Note: this should be only derived by the TransactedAsyncResult protected virtual bool OnContinueAsyncCompletion(IAsyncResult result) { return true; } // Note: this should be used only by the TransactedAsyncResult protected void SetBeforePrepareAsyncCompletionAction(Action beforePrepareAsyncCompletionAction) { _beforePrepareAsyncCompletionAction = beforePrepareAsyncCompletionAction; } // Note: this should be used only by the TransactedAsyncResult protected void SetCheckSyncValidationFunc(Func<IAsyncResult, bool> checkSyncValidationFunc) { _checkSyncValidationFunc = checkSyncValidationFunc; } protected AsyncCallback PrepareAsyncCompletion(AsyncCompletion callback) { if (_beforePrepareAsyncCompletionAction != null) { _beforePrepareAsyncCompletionAction(); } _nextAsyncCompletion = callback; if (AsyncResult.s_asyncCompletionWrapperCallback == null) { AsyncResult.s_asyncCompletionWrapperCallback = Fx.ThunkCallback(new AsyncCallback(AsyncCompletionWrapperCallback)); } return AsyncResult.s_asyncCompletionWrapperCallback; } protected bool CheckSyncContinue(IAsyncResult result) { AsyncCompletion dummy; return TryContinueHelper(result, out dummy); } protected bool SyncContinue(IAsyncResult result) { AsyncCompletion callback; if (TryContinueHelper(result, out callback)) { return callback(result); } else { return false; } } private bool TryContinueHelper(IAsyncResult result, out AsyncCompletion callback) { if (result == null) { throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.InvalidNullAsyncResult)); } callback = null; if (_checkSyncValidationFunc != null) { if (!_checkSyncValidationFunc(result)) { return false; } } else if (!result.CompletedSynchronously) { return false; } callback = GetNextCompletion(); if (callback == null) { ThrowInvalidAsyncResult("Only call Check/SyncContinue once per async operation (once per PrepareAsyncCompletion)."); } return true; } private AsyncCompletion GetNextCompletion() { AsyncCompletion result = _nextAsyncCompletion; _nextAsyncCompletion = null; return result; } protected static void ThrowInvalidAsyncResult(IAsyncResult result) { throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.InvalidAsyncResultImplementation(result.GetType()))); } protected static void ThrowInvalidAsyncResult(string debugText) { string message = InternalSR.InvalidAsyncResultImplementationGeneric; if (debugText != null) { #if DEBUG message += " " + debugText; #endif } throw Fx.Exception.AsError(new InvalidOperationException(message)); } [Fx.Tag.Blocking(Conditional = "!asyncResult.isCompleted")] protected static TAsyncResult End<TAsyncResult>(IAsyncResult result) where TAsyncResult : AsyncResult { if (result == null) { throw Fx.Exception.ArgumentNull("result"); } TAsyncResult asyncResult = result as TAsyncResult; if (asyncResult == null) { throw Fx.Exception.Argument("result", InternalSR.InvalidAsyncResult); } if (asyncResult._endCalled) { throw Fx.Exception.AsError(new InvalidOperationException(InternalSR.AsyncResultAlreadyEnded)); } asyncResult._endCalled = true; if (!asyncResult.IsCompleted) { asyncResult.AsyncWaitHandle.WaitOne(); } if (asyncResult._manualResetEvent != null) { asyncResult._manualResetEvent.Dispose(); } if (asyncResult._exception != null) { throw Fx.Exception.AsError(asyncResult._exception); } return asyncResult; } // can be utilized by subclasses to write core completion code for both the sync and async paths // in one location, signalling chainable synchronous completion with the boolean result, // and leveraging PrepareAsyncCompletion for conversion to an AsyncCallback. // NOTE: requires that "this" is passed in as the state object to the asynchronous sub-call being used with a completion routine. protected delegate bool AsyncCompletion(IAsyncResult result); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Binary { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Common; /// <summary> /// Write delegate. /// </summary> /// <param name="writer">Write context.</param> /// <param name="obj">Object to write.</param> internal delegate void BinarySystemWriteDelegate(BinaryWriter writer, object obj); /** * <summary>Collection of predefined handlers for various system types.</summary> */ internal static class BinarySystemHandlers { /** Write handlers. */ private static volatile Dictionary<Type, BinarySystemWriteDelegate> _writeHandlers = new Dictionary<Type, BinarySystemWriteDelegate>(); /** Mutex for write handlers update. */ private static readonly object WriteHandlersMux = new object(); /** Read handlers. */ private static readonly IBinarySystemReader[] ReadHandlers = new IBinarySystemReader[255]; /** Type ids. */ private static readonly Dictionary<Type, byte> TypeIds = new Dictionary<Type, byte> { {typeof (bool), BinaryUtils.TypeBool}, {typeof (byte), BinaryUtils.TypeByte}, {typeof (sbyte), BinaryUtils.TypeByte}, {typeof (short), BinaryUtils.TypeShort}, {typeof (ushort), BinaryUtils.TypeShort}, {typeof (char), BinaryUtils.TypeChar}, {typeof (int), BinaryUtils.TypeInt}, {typeof (uint), BinaryUtils.TypeInt}, {typeof (long), BinaryUtils.TypeLong}, {typeof (ulong), BinaryUtils.TypeLong}, {typeof (float), BinaryUtils.TypeFloat}, {typeof (double), BinaryUtils.TypeDouble}, {typeof (string), BinaryUtils.TypeString}, {typeof (decimal), BinaryUtils.TypeDecimal}, {typeof (Guid), BinaryUtils.TypeGuid}, {typeof (Guid?), BinaryUtils.TypeGuid}, {typeof (ArrayList), BinaryUtils.TypeCollection}, {typeof (Hashtable), BinaryUtils.TypeDictionary}, {typeof (DictionaryEntry), BinaryUtils.TypeMapEntry}, {typeof (bool[]), BinaryUtils.TypeArrayBool}, {typeof (byte[]), BinaryUtils.TypeArrayByte}, {typeof (sbyte[]), BinaryUtils.TypeArrayByte}, {typeof (short[]), BinaryUtils.TypeArrayShort}, {typeof (ushort[]), BinaryUtils.TypeArrayShort}, {typeof (char[]), BinaryUtils.TypeArrayChar}, {typeof (int[]), BinaryUtils.TypeArrayInt}, {typeof (uint[]), BinaryUtils.TypeArrayInt}, {typeof (long[]), BinaryUtils.TypeArrayLong}, {typeof (ulong[]), BinaryUtils.TypeArrayLong}, {typeof (float[]), BinaryUtils.TypeArrayFloat}, {typeof (double[]), BinaryUtils.TypeArrayDouble}, {typeof (string[]), BinaryUtils.TypeArrayString}, {typeof (decimal?[]), BinaryUtils.TypeArrayDecimal}, {typeof (Guid?[]), BinaryUtils.TypeArrayGuid}, {typeof (object[]), BinaryUtils.TypeArray} }; /// <summary> /// Initializes the <see cref="BinarySystemHandlers"/> class. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Readability.")] static BinarySystemHandlers() { // 1. Primitives. ReadHandlers[BinaryUtils.TypeBool] = new BinarySystemReader<bool>(s => s.ReadBool()); ReadHandlers[BinaryUtils.TypeByte] = new BinarySystemReader<byte>(s => s.ReadByte()); ReadHandlers[BinaryUtils.TypeShort] = new BinarySystemReader<short>(s => s.ReadShort()); ReadHandlers[BinaryUtils.TypeChar] = new BinarySystemReader<char>(s => s.ReadChar()); ReadHandlers[BinaryUtils.TypeInt] = new BinarySystemReader<int>(s => s.ReadInt()); ReadHandlers[BinaryUtils.TypeLong] = new BinarySystemReader<long>(s => s.ReadLong()); ReadHandlers[BinaryUtils.TypeFloat] = new BinarySystemReader<float>(s => s.ReadFloat()); ReadHandlers[BinaryUtils.TypeDouble] = new BinarySystemReader<double>(s => s.ReadDouble()); ReadHandlers[BinaryUtils.TypeDecimal] = new BinarySystemReader<decimal?>(BinaryUtils.ReadDecimal); // 2. Date. ReadHandlers[BinaryUtils.TypeTimestamp] = new BinarySystemReader<DateTime?>(BinaryUtils.ReadTimestamp); // 3. String. ReadHandlers[BinaryUtils.TypeString] = new BinarySystemReader<string>(BinaryUtils.ReadString); // 4. Guid. ReadHandlers[BinaryUtils.TypeGuid] = new BinarySystemReader<Guid?>(BinaryUtils.ReadGuid); // 5. Primitive arrays. ReadHandlers[BinaryUtils.TypeArrayBool] = new BinarySystemReader<bool[]>(BinaryUtils.ReadBooleanArray); ReadHandlers[BinaryUtils.TypeArrayByte] = new BinarySystemDualReader<byte[], sbyte[]>(BinaryUtils.ReadByteArray, BinaryUtils.ReadSbyteArray); ReadHandlers[BinaryUtils.TypeArrayShort] = new BinarySystemDualReader<short[], ushort[]>(BinaryUtils.ReadShortArray, BinaryUtils.ReadUshortArray); ReadHandlers[BinaryUtils.TypeArrayChar] = new BinarySystemReader<char[]>(BinaryUtils.ReadCharArray); ReadHandlers[BinaryUtils.TypeArrayInt] = new BinarySystemDualReader<int[], uint[]>(BinaryUtils.ReadIntArray, BinaryUtils.ReadUintArray); ReadHandlers[BinaryUtils.TypeArrayLong] = new BinarySystemDualReader<long[], ulong[]>(BinaryUtils.ReadLongArray, BinaryUtils.ReadUlongArray); ReadHandlers[BinaryUtils.TypeArrayFloat] = new BinarySystemReader<float[]>(BinaryUtils.ReadFloatArray); ReadHandlers[BinaryUtils.TypeArrayDouble] = new BinarySystemReader<double[]>(BinaryUtils.ReadDoubleArray); ReadHandlers[BinaryUtils.TypeArrayDecimal] = new BinarySystemReader<decimal?[]>(BinaryUtils.ReadDecimalArray); // 6. Date array. ReadHandlers[BinaryUtils.TypeArrayTimestamp] = new BinarySystemReader<DateTime?[]>(BinaryUtils.ReadTimestampArray); // 7. String array. ReadHandlers[BinaryUtils.TypeArrayString] = new BinarySystemTypedArrayReader<string>(); // 8. Guid array. ReadHandlers[BinaryUtils.TypeArrayGuid] = new BinarySystemTypedArrayReader<Guid?>(); // 9. Array. ReadHandlers[BinaryUtils.TypeArray] = new BinarySystemReader(ReadArray); // 11. Arbitrary collection. ReadHandlers[BinaryUtils.TypeCollection] = new BinarySystemReader(ReadCollection); // 13. Arbitrary dictionary. ReadHandlers[BinaryUtils.TypeDictionary] = new BinarySystemReader(ReadDictionary); // 15. Map entry. ReadHandlers[BinaryUtils.TypeMapEntry] = new BinarySystemReader(ReadMapEntry); // 16. Enum. ReadHandlers[BinaryUtils.TypeArrayEnum] = new BinarySystemReader(ReadEnumArray); } /// <summary> /// Try getting write handler for type. /// </summary> /// <param name="type"></param> /// <returns></returns> public static BinarySystemWriteDelegate GetWriteHandler(Type type) { BinarySystemWriteDelegate res; var writeHandlers0 = _writeHandlers; // Have we ever met this type? if (writeHandlers0 != null && writeHandlers0.TryGetValue(type, out res)) return res; // Determine write handler for type and add it. res = FindWriteHandler(type); if (res != null) AddWriteHandler(type, res); return res; } /// <summary> /// Find write handler for type. /// </summary> /// <param name="type">Type.</param> /// <returns>Write handler or NULL.</returns> private static BinarySystemWriteDelegate FindWriteHandler(Type type) { // 1. Well-known types. if (type == typeof(string)) return WriteString; if (type == typeof(decimal)) return WriteDecimal; if (type == typeof(DateTime)) return WriteDate; if (type == typeof(Guid)) return WriteGuid; if (type == typeof (BinaryObject)) return WriteBinary; if (type == typeof (BinaryEnum)) return WriteBinaryEnum; if (type == typeof (ArrayList)) return WriteArrayList; if (type == typeof(Hashtable)) return WriteHashtable; if (type == typeof(DictionaryEntry)) return WriteMapEntry; if (type.IsArray) { // We know how to write any array type. Type elemType = type.GetElementType(); // Primitives. if (elemType == typeof (bool)) return WriteBoolArray; if (elemType == typeof(byte)) return WriteByteArray; if (elemType == typeof(short)) return WriteShortArray; if (elemType == typeof(char)) return WriteCharArray; if (elemType == typeof(int)) return WriteIntArray; if (elemType == typeof(long)) return WriteLongArray; if (elemType == typeof(float)) return WriteFloatArray; if (elemType == typeof(double)) return WriteDoubleArray; // Non-CLS primitives. if (elemType == typeof(sbyte)) return WriteSbyteArray; if (elemType == typeof(ushort)) return WriteUshortArray; if (elemType == typeof(uint)) return WriteUintArray; if (elemType == typeof(ulong)) return WriteUlongArray; // Special types. if (elemType == typeof (decimal?)) return WriteDecimalArray; if (elemType == typeof(string)) return WriteStringArray; if (elemType == typeof(Guid?)) return WriteGuidArray; // Enums. if (elemType.IsEnum || elemType == typeof(BinaryEnum)) return WriteEnumArray; // Object array. if (elemType == typeof (object) || elemType == typeof(IBinaryObject) || elemType == typeof(BinaryObject)) return WriteArray; } if (type.IsEnum) // We know how to write enums. return WriteEnum; if (type.IsSerializable) return WriteSerializable; return null; } /// <summary> /// Find write handler for type. /// </summary> /// <param name="type">Type.</param> /// <returns>Write handler or NULL.</returns> public static byte GetTypeId(Type type) { byte res; if (TypeIds.TryGetValue(type, out res)) return res; if (type.IsEnum) return BinaryUtils.TypeEnum; if (type.IsArray && type.GetElementType().IsEnum) return BinaryUtils.TypeArrayEnum; return BinaryUtils.TypeObject; } /// <summary> /// Add write handler for type. /// </summary> /// <param name="type"></param> /// <param name="handler"></param> private static void AddWriteHandler(Type type, BinarySystemWriteDelegate handler) { lock (WriteHandlersMux) { if (_writeHandlers == null) { Dictionary<Type, BinarySystemWriteDelegate> writeHandlers0 = new Dictionary<Type, BinarySystemWriteDelegate>(); writeHandlers0[type] = handler; _writeHandlers = writeHandlers0; } else if (!_writeHandlers.ContainsKey(type)) { Dictionary<Type, BinarySystemWriteDelegate> writeHandlers0 = new Dictionary<Type, BinarySystemWriteDelegate>(_writeHandlers); writeHandlers0[type] = handler; _writeHandlers = writeHandlers0; } } } /// <summary> /// Reads an object of predefined type. /// </summary> public static bool TryReadSystemType<T>(byte typeId, BinaryReader ctx, out T res) { var handler = ReadHandlers[typeId]; if (handler == null) { res = default(T); return false; } res = handler.Read<T>(ctx); return true; } /// <summary> /// Write decimal. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteDecimal(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeDecimal); BinaryUtils.WriteDecimal((decimal)obj, ctx.Stream); } /// <summary> /// Write date. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteDate(BinaryWriter ctx, object obj) { ctx.Write(new DateTimeHolder((DateTime) obj)); } /// <summary> /// Write string. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Object.</param> private static void WriteString(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeString); BinaryUtils.WriteString((string)obj, ctx.Stream); } /// <summary> /// Write Guid. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteGuid(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeGuid); BinaryUtils.WriteGuid((Guid)obj, ctx.Stream); } /// <summary> /// Write boolaen array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteBoolArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayBool); BinaryUtils.WriteBooleanArray((bool[])obj, ctx.Stream); } /// <summary> /// Write byte array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteByteArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayByte); BinaryUtils.WriteByteArray((byte[])obj, ctx.Stream); } /// <summary> /// Write sbyte array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteSbyteArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayByte); BinaryUtils.WriteByteArray((byte[])(Array)obj, ctx.Stream); } /// <summary> /// Write short array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteShortArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayShort); BinaryUtils.WriteShortArray((short[])obj, ctx.Stream); } /// <summary> /// Write ushort array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteUshortArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayShort); BinaryUtils.WriteShortArray((short[])(Array)obj, ctx.Stream); } /// <summary> /// Write char array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteCharArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayChar); BinaryUtils.WriteCharArray((char[])obj, ctx.Stream); } /// <summary> /// Write int array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteIntArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayInt); BinaryUtils.WriteIntArray((int[])obj, ctx.Stream); } /// <summary> /// Write uint array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteUintArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayInt); BinaryUtils.WriteIntArray((int[])(Array)obj, ctx.Stream); } /// <summary> /// Write long array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteLongArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayLong); BinaryUtils.WriteLongArray((long[])obj, ctx.Stream); } /// <summary> /// Write ulong array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteUlongArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayLong); BinaryUtils.WriteLongArray((long[])(Array)obj, ctx.Stream); } /// <summary> /// Write float array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteFloatArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayFloat); BinaryUtils.WriteFloatArray((float[])obj, ctx.Stream); } /// <summary> /// Write double array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteDoubleArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayDouble); BinaryUtils.WriteDoubleArray((double[])obj, ctx.Stream); } /// <summary> /// Write decimal array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteDecimalArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayDecimal); BinaryUtils.WriteDecimalArray((decimal?[])obj, ctx.Stream); } /// <summary> /// Write string array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteStringArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayString); BinaryUtils.WriteStringArray((string[])obj, ctx.Stream); } /// <summary> /// Write nullable GUID array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteGuidArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayGuid); BinaryUtils.WriteGuidArray((Guid?[])obj, ctx.Stream); } /** * <summary>Write enum array.</summary> */ private static void WriteEnumArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayEnum); BinaryUtils.WriteArray((Array)obj, ctx); } /** * <summary>Write array.</summary> */ private static void WriteArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArray); BinaryUtils.WriteArray((Array)obj, ctx); } /** * <summary>Write ArrayList.</summary> */ private static void WriteArrayList(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeCollection); BinaryUtils.WriteCollection((ICollection)obj, ctx, BinaryUtils.CollectionArrayList); } /** * <summary>Write Hashtable.</summary> */ private static void WriteHashtable(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeDictionary); BinaryUtils.WriteDictionary((IDictionary)obj, ctx, BinaryUtils.MapHashMap); } /** * <summary>Write map entry.</summary> */ private static void WriteMapEntry(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeMapEntry); BinaryUtils.WriteMapEntry(ctx, (DictionaryEntry)obj); } /** * <summary>Write binary object.</summary> */ private static void WriteBinary(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeBinary); BinaryUtils.WriteBinary(ctx.Stream, (BinaryObject)obj); } /// <summary> /// Write enum. /// </summary> private static void WriteEnum(BinaryWriter ctx, object obj) { ctx.WriteEnum(obj); } /// <summary> /// Write enum. /// </summary> private static void WriteBinaryEnum(BinaryWriter ctx, object obj) { var binEnum = (BinaryEnum) obj; ctx.Stream.WriteByte(BinaryUtils.TypeEnum); ctx.WriteInt(binEnum.TypeId); ctx.WriteInt(binEnum.EnumValue); } /// <summary> /// Writes serializable. /// </summary> /// <param name="writer">The writer.</param> /// <param name="o">The object.</param> private static void WriteSerializable(BinaryWriter writer, object o) { writer.Write(new SerializableObjectHolder(o)); } /** * <summary>Read enum array.</summary> */ private static object ReadEnumArray(BinaryReader ctx, Type type) { return BinaryUtils.ReadTypedArray(ctx, true, type.GetElementType()); } /** * <summary>Read array.</summary> */ private static object ReadArray(BinaryReader ctx, Type type) { var elemType = type.IsArray ? type.GetElementType() : typeof(object); return BinaryUtils.ReadTypedArray(ctx, true, elemType); } /** * <summary>Read collection.</summary> */ private static object ReadCollection(BinaryReader ctx, Type type) { return BinaryUtils.ReadCollection(ctx, null, null); } /** * <summary>Read dictionary.</summary> */ private static object ReadDictionary(BinaryReader ctx, Type type) { return BinaryUtils.ReadDictionary(ctx, null); } /** * <summary>Read map entry.</summary> */ private static object ReadMapEntry(BinaryReader ctx, Type type) { return BinaryUtils.ReadMapEntry(ctx); } /** * <summary>Add element to array list.</summary> * <param name="col">Array list.</param> * <param name="elem">Element.</param> */ /** * <summary>Read delegate.</summary> * <param name="ctx">Read context.</param> * <param name="type">Type.</param> */ private delegate object BinarySystemReadDelegate(BinaryReader ctx, Type type); /// <summary> /// System type reader. /// </summary> private interface IBinarySystemReader { /// <summary> /// Reads a value of specified type from reader. /// </summary> T Read<T>(BinaryReader ctx); } /// <summary> /// System type generic reader. /// </summary> private interface IBinarySystemReader<out T> { /// <summary> /// Reads a value of specified type from reader. /// </summary> T Read(BinaryReader ctx); } /// <summary> /// Default reader with boxing. /// </summary> private class BinarySystemReader : IBinarySystemReader { /** */ private readonly BinarySystemReadDelegate _readDelegate; /// <summary> /// Initializes a new instance of the <see cref="BinarySystemReader"/> class. /// </summary> /// <param name="readDelegate">The read delegate.</param> public BinarySystemReader(BinarySystemReadDelegate readDelegate) { Debug.Assert(readDelegate != null); _readDelegate = readDelegate; } /** <inheritdoc /> */ public T Read<T>(BinaryReader ctx) { return (T)_readDelegate(ctx, typeof(T)); } } /// <summary> /// Reader without boxing. /// </summary> private class BinarySystemReader<T> : IBinarySystemReader { /** */ private readonly Func<IBinaryStream, T> _readDelegate; /// <summary> /// Initializes a new instance of the <see cref="BinarySystemReader{T}"/> class. /// </summary> /// <param name="readDelegate">The read delegate.</param> public BinarySystemReader(Func<IBinaryStream, T> readDelegate) { Debug.Assert(readDelegate != null); _readDelegate = readDelegate; } /** <inheritdoc /> */ public TResult Read<TResult>(BinaryReader ctx) { return TypeCaster<TResult>.Cast(_readDelegate(ctx.Stream)); } } /// <summary> /// Reader without boxing. /// </summary> private class BinarySystemTypedArrayReader<T> : IBinarySystemReader { public TResult Read<TResult>(BinaryReader ctx) { return TypeCaster<TResult>.Cast(BinaryUtils.ReadArray<T>(ctx, false)); } } /// <summary> /// Reader with selection based on requested type. /// </summary> private class BinarySystemDualReader<T1, T2> : IBinarySystemReader, IBinarySystemReader<T2> { /** */ private readonly Func<IBinaryStream, T1> _readDelegate1; /** */ private readonly Func<IBinaryStream, T2> _readDelegate2; /// <summary> /// Initializes a new instance of the <see cref="BinarySystemDualReader{T1,T2}"/> class. /// </summary> /// <param name="readDelegate1">The read delegate1.</param> /// <param name="readDelegate2">The read delegate2.</param> public BinarySystemDualReader(Func<IBinaryStream, T1> readDelegate1, Func<IBinaryStream, T2> readDelegate2) { Debug.Assert(readDelegate1 != null); Debug.Assert(readDelegate2 != null); _readDelegate1 = readDelegate1; _readDelegate2 = readDelegate2; } /** <inheritdoc /> */ T2 IBinarySystemReader<T2>.Read(BinaryReader ctx) { return _readDelegate2(ctx.Stream); } /** <inheritdoc /> */ public T Read<T>(BinaryReader ctx) { // Can't use "as" because of variance. // For example, IBinarySystemReader<byte[]> can be cast to IBinarySystemReader<sbyte[]>, which // will cause incorrect behavior. if (typeof (T) == typeof (T2)) return ((IBinarySystemReader<T>) this).Read(ctx); return TypeCaster<T>.Cast(_readDelegate1(ctx.Stream)); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Text; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.Build.Framework; using Microsoft.Build.Logging; using Shouldly; using Xunit.Abstractions; namespace Microsoft.Build.UnitTests { /*************************************************************************** * * Class: MockEngine * * In order to execute tasks, we have to pass in an Engine object, so the * task can log events. It doesn't have to be the real Engine object, just * something that implements the IBuildEngine4 interface. So, we mock up * a fake engine object here, so we're able to execute tasks from the unit tests. * * The unit tests could have instantiated the real Engine object, but then * we would have had to take a reference onto the Microsoft.Build.Engine assembly, which * is somewhat of a no-no for task assemblies. * **************************************************************************/ internal sealed class MockEngine : IBuildEngine7 { private readonly object _lockObj = new object(); // Protects _log, _output private readonly ITestOutputHelper _output; private readonly StringBuilder _log = new StringBuilder(); private readonly ProjectCollection _projectCollection = new ProjectCollection(); private readonly bool _logToConsole; private readonly ConcurrentDictionary<object, object> _objectCache = new ConcurrentDictionary<object, object>(); private readonly ConcurrentQueue<BuildErrorEventArgs> _errorEvents = new ConcurrentQueue<BuildErrorEventArgs>(); internal MockEngine() : this(false) { } internal int Messages { get; set; } internal int Warnings { get; set; } internal int Errors { get; set; } public bool AllowFailureWithoutError { get; set; } = false; public BuildErrorEventArgs[] ErrorEvents => _errorEvents.ToArray(); public Dictionary<string, string> GlobalProperties { get; set; } = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); internal MockLogger MockLogger { get; } public MockEngine(bool logToConsole) { MockLogger = new MockLogger(); _logToConsole = logToConsole; } public MockEngine(ITestOutputHelper output) { _output = output; MockLogger = new MockLogger(output); _logToConsole = false; // We have a better place to put it. } public void LogErrorEvent(BuildErrorEventArgs eventArgs) { _errorEvents.Enqueue(eventArgs); string message = string.Empty; if (!string.IsNullOrEmpty(eventArgs.File)) { message += $"{eventArgs.File}({eventArgs.LineNumber},{eventArgs.ColumnNumber}): "; } message += "ERROR " + eventArgs.Code + ": "; ++Errors; message += eventArgs.Message; lock (_lockObj) { if (_logToConsole) { Console.WriteLine(message); } _output?.WriteLine(message); _log.AppendLine(message); } } public void LogWarningEvent(BuildWarningEventArgs eventArgs) { lock (_lockObj) { string message = string.Empty; if (!string.IsNullOrEmpty(eventArgs.File)) { message += $"{eventArgs.File}({eventArgs.LineNumber},{eventArgs.ColumnNumber}): "; } message += "WARNING " + eventArgs.Code + ": "; ++Warnings; message += eventArgs.Message; if (_logToConsole) { Console.WriteLine(message); } _output?.WriteLine(message); _log.AppendLine(message); } } public void LogCustomEvent(CustomBuildEventArgs eventArgs) { lock (_lockObj) { if (_logToConsole) { Console.WriteLine(eventArgs.Message); } _output?.WriteLine(eventArgs.Message); _log.AppendLine(eventArgs.Message); } } public void LogMessageEvent(BuildMessageEventArgs eventArgs) { lock (_lockObj) { if (_logToConsole) { Console.WriteLine(eventArgs.Message); } _output?.WriteLine(eventArgs.Message); _log.AppendLine(eventArgs.Message); ++Messages; } } public void LogTelemetry(string eventName, IDictionary<string, string> properties) { string message = $"Received telemetry event '{eventName}'{Environment.NewLine}"; foreach (string key in properties?.Keys) { message += $" Property '{key}' = '{properties[key]}'{Environment.NewLine}"; } lock (_lockObj) { if (_logToConsole) { Console.WriteLine(message); } _output?.WriteLine(message); _log.AppendLine(message); } } public IReadOnlyDictionary<string, string> GetGlobalProperties() { return GlobalProperties; } public bool ContinueOnError => false; public string ProjectFileOfTaskNode => String.Empty; public int LineNumberOfTaskNode => 0; public int ColumnNumberOfTaskNode => 0; internal string Log { get { lock (_lockObj) { return _log.ToString(); } } set { if (!string.IsNullOrEmpty(value)) { throw new ArgumentException("Expected log setter to be used only to reset the log to empty."); } lock (_lockObj) { _log.Clear(); } } } public bool IsRunningMultipleNodes { get; set; } public bool BuildProjectFile ( string projectFileName, string[] targetNames, IDictionary globalPropertiesPassedIntoTask, IDictionary targetOutputs ) { return BuildProjectFile(projectFileName, targetNames, globalPropertiesPassedIntoTask, targetOutputs, null); } public bool BuildProjectFile ( string projectFileName, string[] targetNames, IDictionary globalPropertiesPassedIntoTask, IDictionary targetOutputs, string toolsVersion ) { var finalGlobalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); // Finally, whatever global properties were passed into the task ... those are the final winners. if (globalPropertiesPassedIntoTask != null) { foreach (DictionaryEntry newGlobalProperty in globalPropertiesPassedIntoTask) { finalGlobalProperties[(string)newGlobalProperty.Key] = (string)newGlobalProperty.Value; } } Project project = _projectCollection.LoadProject(projectFileName, finalGlobalProperties, toolsVersion); ILogger[] loggers = { MockLogger, new ConsoleLogger() }; return project.Build(targetNames, loggers); } public bool BuildProjectFilesInParallel ( string[] projectFileNames, string[] targetNames, IDictionary[] globalProperties, IDictionary[] targetOutputsPerProject, string[] toolsVersion, bool useResultsCache, bool unloadProjectsOnCompletion ) { bool includeTargetOutputs = targetOutputsPerProject != null; BuildEngineResult result = BuildProjectFilesInParallel(projectFileNames, targetNames, globalProperties, new List<String>[projectFileNames.Length], toolsVersion, includeTargetOutputs); if (includeTargetOutputs) { for (int i = 0; i < targetOutputsPerProject.Length; i++) { if (targetOutputsPerProject[i] != null) { foreach (KeyValuePair<string, ITaskItem[]> output in result.TargetOutputsPerProject[i]) { targetOutputsPerProject[i].Add(output.Key, output.Value); } } } } return result.Result; } public BuildEngineResult BuildProjectFilesInParallel ( string[] projectFileNames, string[] targetNames, IDictionary[] globalProperties, IList<string>[] undefineProperties, string[] toolsVersion, bool returnTargetOutputs ) { List<IDictionary<string, ITaskItem[]>> targetOutputsPerProject = null; ILogger[] loggers = { MockLogger, new ConsoleLogger() }; bool allSucceeded = true; if (returnTargetOutputs) { targetOutputsPerProject = new List<IDictionary<string, ITaskItem[]>>(); } for (int i = 0; i < projectFileNames.Length; i++) { Dictionary<string, string> finalGlobalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); if (globalProperties[i] != null) { foreach (DictionaryEntry newGlobalProperty in globalProperties[i]) { finalGlobalProperties[(string)newGlobalProperty.Key] = (string)newGlobalProperty.Value; } } ProjectInstance instance = _projectCollection.LoadProject(projectFileNames[i], finalGlobalProperties, null).CreateProjectInstance(); bool success = instance.Build(targetNames, loggers, out IDictionary<string, TargetResult> targetOutputs); if (targetOutputsPerProject != null) { targetOutputsPerProject.Add(new Dictionary<string, ITaskItem[]>(StringComparer.OrdinalIgnoreCase)); foreach (KeyValuePair<string, TargetResult> resultEntry in targetOutputs) { targetOutputsPerProject[i][resultEntry.Key] = resultEntry.Value.Items; } } allSucceeded = allSucceeded && success; } return new BuildEngineResult(allSucceeded, targetOutputsPerProject); } public void Yield() { } public void Reacquire() { } public bool BuildProjectFile ( string projectFileName ) { return (_projectCollection.LoadProject(projectFileName)).Build(); } public bool BuildProjectFile ( string projectFileName, string[] targetNames ) { return (_projectCollection.LoadProject(projectFileName)).Build(targetNames); } public bool BuildProjectFile ( string projectFileName, string targetName ) { return (_projectCollection.LoadProject(projectFileName)).Build(targetName); } public void UnregisterAllLoggers ( ) { _projectCollection.UnregisterAllLoggers(); } public void UnloadAllProjects ( ) { _projectCollection.UnloadAllProjects(); } /// <summary> /// Assert that the mock log in the engine doesn't contain a certain message based on a resource string and some parameters /// </summary> internal void AssertLogDoesntContainMessageFromResource(GetStringDelegate getString, string resourceName, params string[] parameters) { string resource = getString(resourceName); string stringToSearchFor = String.Format(resource, parameters); AssertLogDoesntContain(stringToSearchFor); } /// <summary> /// Assert that the mock log in the engine contains a certain message based on a resource string and some parameters /// </summary> internal void AssertLogContainsMessageFromResource(GetStringDelegate getString, string resourceName, params string[] parameters) { string resource = getString(resourceName); string stringToSearchFor = String.Format(resource, parameters); AssertLogContains(stringToSearchFor); } /// <summary> /// Assert that the log file contains the given string. /// Case insensitive. /// First check if the string is in the log string. If not /// than make sure it is also check the MockLogger /// </summary> internal void AssertLogContains(string contains) { // If we do not contain this string than pass it to // MockLogger. Since MockLogger is also registered as // a logger it may have this string. string logText; lock (_lockObj) { logText = _log.ToString(); } if (logText.IndexOf(contains, StringComparison.OrdinalIgnoreCase) == -1) { if (_output == null) { Console.WriteLine(logText); } else { _output.WriteLine(logText); } MockLogger.AssertLogContains(contains); } } /// <summary> /// Assert that the log doesn't contain the given string. /// First check if the string is in the log string. If not /// than make sure it is also not in the MockLogger /// </summary> internal void AssertLogDoesntContain(string contains) { string logText; lock (_lockObj) { logText = _log.ToString(); } if (_output == null) { Console.WriteLine(logText); } else { _output.WriteLine(logText); } logText.ShouldNotContain(contains, Case.Insensitive); // If we do not contain this string than pass it to // MockLogger. Since MockLogger is also registered as // a logger it may have this string. MockLogger.AssertLogDoesntContain(contains); } /// <summary> /// Delegate which will get the resource from the correct resource manager /// </summary> public delegate string GetStringDelegate(string resourceName); public object GetRegisteredTaskObject(object key, RegisteredTaskObjectLifetime lifetime) { _objectCache.TryGetValue(key, out object obj); return obj; } public void RegisterTaskObject(object key, object obj, RegisteredTaskObjectLifetime lifetime, bool allowEarlyCollection) { _objectCache[key] = obj; } public object UnregisterTaskObject(object key, RegisteredTaskObjectLifetime lifetime) { _objectCache.TryRemove(key, out object obj); return obj; } } }
// Copyright (C) 2012-2017 Luca Piccioni // // 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. // ReSharper disable InconsistentNaming using System; namespace OpenGL.Objects { /// <summary> /// The type of the data collected in OpenGL array buffers. /// </summary> public enum ArrayBufferItemType { #region Single-Precision Floating-Point Types /// <summary> /// A single single-precision floating-point value. /// </summary> Float, /// <summary> /// A vector of two single-precision floating-point values. /// </summary> Float2, /// <summary> /// A vector of three single-precision floating-point values. /// </summary> Float3, /// <summary> /// A vector of four single-precision floating-point values. /// </summary> Float4, #endregion #region Half-Precision Floating-Point Types /// <summary> /// A single half-precision floating-point value. /// </summary> Half, /// <summary> /// A vector of two half-precision floating-point values. /// </summary> Half2, /// <summary> /// A vector of three half-precision floating-point values. /// </summary> Half3, /// <summary> /// A vector of four half-precision floating-point values. /// </summary> Half4, #endregion #region Double-Precision Floating-Point Types /// <summary> /// A single double-precision floating-point value. /// </summary> Double, /// <summary> /// A vector of two double-precision floating-point values. /// </summary> Double2, /// <summary> /// A vector of three double-precision floating-point values. /// </summary> Double3, /// <summary> /// A vector of four double-precision floating-point values. /// </summary> Double4, #endregion #region Signed Integer Types /// <summary> /// A single signed byte value. /// </summary> Byte, /// <summary> /// A vector of two signed byte values. /// </summary> Byte2, /// <summary> /// A vector of three signed byte values. /// </summary> Byte3, /// <summary> /// A vector of four signed byte values. /// </summary> Byte4, /// <summary> /// A single signed short integer value. /// </summary> Short, /// <summary> /// A vector of two signed short integer values. /// </summary> Short2, /// <summary> /// A vector of three signed short integer values. /// </summary> Short3, /// <summary> /// A vector of four signed short integer values. /// </summary> Short4, /// <summary> /// A single signed integer value. /// </summary> Int, /// <summary> /// A vector of two signed integer values. /// </summary> Int2, /// <summary> /// A vector of three signed integer values. /// </summary> Int3, /// <summary> /// A vector of four signed integer values. /// </summary> Int4, #endregion #region Unsigned Integer Types /// <summary> /// A single unsigned byte value. /// </summary> UByte, /// <summary> /// A vector of two unsigned byte values. /// </summary> UByte2, /// <summary> /// A vector of three unsigned byte values. /// </summary> UByte3, /// <summary> /// A vector of four unsigned byte values. /// </summary> UByte4, /// <summary> /// A single unsigned short integer value. /// </summary> UShort, /// <summary> /// A vector of two unsigned short integer values. /// </summary> UShort2, /// <summary> /// A vector of three unsigned short integer values. /// </summary> UShort3, /// <summary> /// A vector of four unsigned short integer values. /// </summary> UShort4, /// <summary> /// A single unsigned integer value. /// </summary> UInt, /// <summary> /// A vector of two unsigned integer values. /// </summary> UInt2, /// <summary> /// A vector of three unsigned integer values. /// </summary> UInt3, /// <summary> /// A vector of four unsigned integer values. /// </summary> UInt4, #endregion #region Single-Precision Floating-Point Matrix Types /// <summary> /// A single-precision floating-point matrix of 2 columns and 2 rows. /// </summary> Float2x2, /// <summary> /// A single-precision floating-point matrix of 2 columns and 3 rows. /// </summary> Float2x3, /// <summary> /// A single-precision floating-point matrix of 2 columns and 4 rows. /// </summary> Float2x4, /// <summary> /// A single-precision floating-point matrix of 3 columns and 2 rows. /// </summary> Float3x2, /// <summary> /// A single-precision floating-point matrix of 3 columns and 3 rows. /// </summary> Float3x3, /// <summary> /// A single-precision floating-point matrix of 3 columns and 4 rows. /// </summary> Float3x4, /// <summary> /// A single-precision floating-point matrix of 4 columns and 2 rows. /// </summary> Float4x2, /// <summary> /// A single-precision floating-point matrix of 4 columns and 3 rows. /// </summary> Float4x3, /// <summary> /// A single-precision floating-point matrix of 4 columns and 4 rows. /// </summary> Float4x4, #endregion #region Double-Precision Floating-Point Matrix Types /// <summary> /// A double-precision floating-point matrix of 2 columns and 2 rows. /// </summary> Double2x2, /// <summary> /// A double-precision floating-point matrix of 2 columns and 3 rows. /// </summary> Double2x3, /// <summary> /// A double-precision floating-point matrix of 2 columns and 4 rows. /// </summary> Double2x4, /// <summary> /// A double-precision floating-point matrix of 3 columns and 2 rows. /// </summary> Double3x2, /// <summary> /// A double-precision floating-point matrix of 3 columns and 3 rows. /// </summary> Double3x3, /// <summary> /// A double-precision floating-point matrix of 3 columns and 4 rows. /// </summary> Double3x4, /// <summary> /// A double-precision floating-point matrix of 4 columns and 2 rows. /// </summary> Double4x2, /// <summary> /// A double-precision floating-point matrix of 4 columns and 3 rows. /// </summary> Double4x3, /// <summary> /// A double-precision floating-point matrix of 4 columns and 4 rows. /// </summary> Double4x4, #endregion } /// <summary> /// Extension methods for <see cref="ArrayBufferItemType"/> enumeration. /// </summary> public static class ArrayBufferItemTypeExtensions { #region Base Type /// <summary> /// Get the array components base type of the vertex array buffer item. /// </summary> /// <param name="vertexArrayType"> /// A <see cref="ArrayBufferItemType"/> that describe the vertex array buffer item. /// </param> /// <returns> /// It returns a <see cref="VertexBaseType"/> indicating the type of the components of /// the vertex array buffer item. /// </returns> public static VertexBaseType GetVertexBaseType(this ArrayBufferItemType vertexArrayType) { switch (vertexArrayType) { case ArrayBufferItemType.Byte: case ArrayBufferItemType.Byte2: case ArrayBufferItemType.Byte3: case ArrayBufferItemType.Byte4: return VertexBaseType.Byte; case ArrayBufferItemType.UByte: case ArrayBufferItemType.UByte2: case ArrayBufferItemType.UByte3: case ArrayBufferItemType.UByte4: return VertexBaseType.UByte; case ArrayBufferItemType.Short: case ArrayBufferItemType.Short2: case ArrayBufferItemType.Short3: case ArrayBufferItemType.Short4: return VertexBaseType.Short; case ArrayBufferItemType.UShort: case ArrayBufferItemType.UShort2: case ArrayBufferItemType.UShort3: case ArrayBufferItemType.UShort4: return VertexBaseType.UShort; case ArrayBufferItemType.Int: case ArrayBufferItemType.Int2: case ArrayBufferItemType.Int3: case ArrayBufferItemType.Int4: return VertexBaseType.Int; case ArrayBufferItemType.UInt: case ArrayBufferItemType.UInt2: case ArrayBufferItemType.UInt3: case ArrayBufferItemType.UInt4: return VertexBaseType.UInt; case ArrayBufferItemType.Float: case ArrayBufferItemType.Float2: case ArrayBufferItemType.Float3: case ArrayBufferItemType.Float4: case ArrayBufferItemType.Float2x2: case ArrayBufferItemType.Float2x3: case ArrayBufferItemType.Float2x4: case ArrayBufferItemType.Float3x2: case ArrayBufferItemType.Float3x3: case ArrayBufferItemType.Float3x4: case ArrayBufferItemType.Float4x2: case ArrayBufferItemType.Float4x3: case ArrayBufferItemType.Float4x4: return VertexBaseType.Float; #if !MONODROID case ArrayBufferItemType.Double: case ArrayBufferItemType.Double2: case ArrayBufferItemType.Double3: case ArrayBufferItemType.Double4: case ArrayBufferItemType.Double2x2: case ArrayBufferItemType.Double2x3: case ArrayBufferItemType.Double2x4: case ArrayBufferItemType.Double3x2: case ArrayBufferItemType.Double3x3: case ArrayBufferItemType.Double3x4: case ArrayBufferItemType.Double4x2: case ArrayBufferItemType.Double4x3: case ArrayBufferItemType.Double4x4: return VertexBaseType.Double; #endif case ArrayBufferItemType.Half: case ArrayBufferItemType.Half2: case ArrayBufferItemType.Half3: case ArrayBufferItemType.Half4: return VertexBaseType.Half; default: throw new NotSupportedException("unsupported vertex array base type of " + vertexArrayType); } } /// <summary> /// Determine whether a vertex array type is composed by floating-point value(s). /// </summary> public static bool IsFloatBaseType(this ArrayBufferItemType vertexArrayType) { return vertexArrayType.GetVertexBaseType().IsFloatBaseType(); } /// <summary> /// Get the size of a vertex array buffer item, in bytes. /// </summary> /// <param name="vertexArrayType"> /// A <see cref="ArrayBufferItemType"/> that describe the vertex array buffer item. /// </param> /// <returns> /// It returns the size of the vertex array buffer type having the type <paramref name="vertexArrayType"/>, in bytes. /// </returns> public static uint GetItemSize(this ArrayBufferItemType vertexArrayType) { uint baseTypeSize = vertexArrayType.GetVertexBaseType().GetSize(); uint length = vertexArrayType.GetArrayLength(); uint rank = vertexArrayType.GetArrayRank(); return baseTypeSize * length * rank; } #endregion #region Length & Rank /// <summary> /// Get the number of components of the vertex array buffer item. /// </summary> /// <param name="vertexArrayType"> /// A <see cref="ArrayBufferItemType"/> that describe the vertex array buffer item. /// </param> /// <returns> /// It returns the count of the components of the vertex array buffer item. It will be a value /// from 1 (inclusive) to 4 (inclusive). For matrices, this value indicates the matrix height (column-major order). /// </returns> public static uint GetArrayLength(this ArrayBufferItemType vertexArrayType) { switch (vertexArrayType) { case ArrayBufferItemType.Byte: case ArrayBufferItemType.UByte: case ArrayBufferItemType.Short: case ArrayBufferItemType.UShort: case ArrayBufferItemType.Int: case ArrayBufferItemType.UInt: case ArrayBufferItemType.Float: case ArrayBufferItemType.Double: case ArrayBufferItemType.Half: return 1; case ArrayBufferItemType.Byte2: case ArrayBufferItemType.UByte2: case ArrayBufferItemType.Short2: case ArrayBufferItemType.UShort2: case ArrayBufferItemType.Int2: case ArrayBufferItemType.UInt2: case ArrayBufferItemType.Float2: case ArrayBufferItemType.Double2: case ArrayBufferItemType.Half2: case ArrayBufferItemType.Float2x2: case ArrayBufferItemType.Float2x3: case ArrayBufferItemType.Float2x4: case ArrayBufferItemType.Double2x2: case ArrayBufferItemType.Double2x3: case ArrayBufferItemType.Double2x4: return 2; case ArrayBufferItemType.Byte3: case ArrayBufferItemType.UByte3: case ArrayBufferItemType.Short3: case ArrayBufferItemType.UShort3: case ArrayBufferItemType.Int3: case ArrayBufferItemType.UInt3: case ArrayBufferItemType.Float3: case ArrayBufferItemType.Double3: case ArrayBufferItemType.Half3: case ArrayBufferItemType.Float3x2: case ArrayBufferItemType.Float3x3: case ArrayBufferItemType.Float3x4: case ArrayBufferItemType.Double3x2: case ArrayBufferItemType.Double3x3: case ArrayBufferItemType.Double3x4: return 3; case ArrayBufferItemType.Byte4: case ArrayBufferItemType.UByte4: case ArrayBufferItemType.Short4: case ArrayBufferItemType.UShort4: case ArrayBufferItemType.Int4: case ArrayBufferItemType.UInt4: case ArrayBufferItemType.Float4: case ArrayBufferItemType.Double4: case ArrayBufferItemType.Half4: case ArrayBufferItemType.Float4x2: case ArrayBufferItemType.Float4x3: case ArrayBufferItemType.Float4x4: case ArrayBufferItemType.Double4x2: case ArrayBufferItemType.Double4x3: case ArrayBufferItemType.Double4x4: return 4; default: throw new NotSupportedException("unsupported vertex array length of " + vertexArrayType); } } /// <summary> /// Get the rank of the vertex array buffer item (that is, the number of <i>vec4</i> attributes requires). /// </summary> /// <param name="vertexArrayType"> /// A <see cref="ArrayBufferItemType"/> that describe the vertex array buffer item. /// </param> /// <returns> /// It returns the rank of the vertex array buffer item. It will be a value /// from 1 (inclusive) to 4 (inclusive). For matrices, this value indicates the matrix width (column-major order), /// while for simpler types the value will be 1. /// </returns> public static uint GetArrayRank(this ArrayBufferItemType vertexArrayType) { switch (vertexArrayType) { case ArrayBufferItemType.Float2x2: case ArrayBufferItemType.Float3x2: case ArrayBufferItemType.Float4x2: case ArrayBufferItemType.Double2x2: case ArrayBufferItemType.Double3x2: case ArrayBufferItemType.Double4x2: return 2; case ArrayBufferItemType.Float2x3: case ArrayBufferItemType.Float3x3: case ArrayBufferItemType.Float4x3: case ArrayBufferItemType.Double2x3: case ArrayBufferItemType.Double3x3: case ArrayBufferItemType.Double4x3: return 3; case ArrayBufferItemType.Float2x4: case ArrayBufferItemType.Float3x4: case ArrayBufferItemType.Float4x4: case ArrayBufferItemType.Double2x4: case ArrayBufferItemType.Double3x4: case ArrayBufferItemType.Double4x4: return 4; case ArrayBufferItemType.Byte: case ArrayBufferItemType.UByte: case ArrayBufferItemType.Short: case ArrayBufferItemType.UShort: case ArrayBufferItemType.Int: case ArrayBufferItemType.UInt: case ArrayBufferItemType.Float: case ArrayBufferItemType.Double: case ArrayBufferItemType.Half: case ArrayBufferItemType.Byte2: case ArrayBufferItemType.UByte2: case ArrayBufferItemType.Short2: case ArrayBufferItemType.UShort2: case ArrayBufferItemType.Int2: case ArrayBufferItemType.UInt2: case ArrayBufferItemType.Float2: case ArrayBufferItemType.Double2: case ArrayBufferItemType.Half2: case ArrayBufferItemType.Byte3: case ArrayBufferItemType.UByte3: case ArrayBufferItemType.Short3: case ArrayBufferItemType.UShort3: case ArrayBufferItemType.Int3: case ArrayBufferItemType.UInt3: case ArrayBufferItemType.Float3: case ArrayBufferItemType.Double3: case ArrayBufferItemType.Half3: case ArrayBufferItemType.Byte4: case ArrayBufferItemType.UByte4: case ArrayBufferItemType.Short4: case ArrayBufferItemType.UShort4: case ArrayBufferItemType.Int4: case ArrayBufferItemType.UInt4: case ArrayBufferItemType.Float4: case ArrayBufferItemType.Double4: case ArrayBufferItemType.Half4: return 1; default: throw new NotSupportedException("unsupported vertex array rank of " + vertexArrayType); } } /// <summary> /// Get whether a <see cref="ArrayBufferItemType"/> is a simple type (float, int, ...). /// </summary> /// <param name="vertexArrayType"> /// A <see cref="ArrayBufferItemType"/> that describe the vertex array buffer item. /// </param> /// <returns> /// It returns a boolean value indicating whether <paramref name="vertexArrayType"/> is a simple type. /// </returns> public static bool IsArraySimpleType(this ArrayBufferItemType vertexArrayType) { return vertexArrayType.GetArrayLength() == 1 && vertexArrayType.GetArrayRank() == 1; } /// <summary> /// Get whether a <see cref="ArrayBufferItemType"/> is a vector type (vec2, vec3, ...). /// </summary> /// <param name="vertexArrayType"> /// A <see cref="ArrayBufferItemType"/> that describe the vertex array buffer item. /// </param> /// <returns> /// It returns a boolean value indicating whether <paramref name="vertexArrayType"/> is a vector type. /// </returns> public static bool IsArrayVectorType(this ArrayBufferItemType vertexArrayType) { return vertexArrayType.GetArrayLength() > 1 && vertexArrayType.GetArrayRank() == 1; } /// <summary> /// Get whether a <see cref="ArrayBufferItemType"/> is a matrix type (mat2, mat4, ...). /// </summary> /// <param name="vertexArrayType"> /// A <see cref="ArrayBufferItemType"/> that describe the vertex array buffer item. /// </param> /// <returns> /// It returns a boolean value indicating whether <paramref name="vertexArrayType"/> is a matrix type. /// </returns> public static bool IsArrayMatrixType(this ArrayBufferItemType vertexArrayType) { return GetArrayRank(vertexArrayType) > 1; } /// <summary> /// Get the correponding type for the column of the matrix type. /// </summary> /// <param name="vertexArrayType"> /// A <see cref="ArrayBufferItemType"/> that describe the vertex array buffer item. /// </param> /// <returns> /// It returns a boolean value indicating whether <paramref name="vertexArrayType"/> is a matrix type. /// </returns> public static ArrayBufferItemType GetMatrixColumnType(this ArrayBufferItemType vertexArrayType) { switch (vertexArrayType) { case ArrayBufferItemType.Float2x2: case ArrayBufferItemType.Float2x3: case ArrayBufferItemType.Float2x4: return ArrayBufferItemType.Float2; case ArrayBufferItemType.Float3x2: case ArrayBufferItemType.Float3x3: case ArrayBufferItemType.Float3x4: return ArrayBufferItemType.Float3; case ArrayBufferItemType.Float4x2: case ArrayBufferItemType.Float4x3: case ArrayBufferItemType.Float4x4: return ArrayBufferItemType.Float4; case ArrayBufferItemType.Double2x2: case ArrayBufferItemType.Double2x3: case ArrayBufferItemType.Double2x4: return ArrayBufferItemType.Double2; case ArrayBufferItemType.Double3x2: case ArrayBufferItemType.Double3x3: case ArrayBufferItemType.Double3x4: return ArrayBufferItemType.Double3; case ArrayBufferItemType.Double4x2: case ArrayBufferItemType.Double4x3: case ArrayBufferItemType.Double4x4: return ArrayBufferItemType.Double4; default: throw new NotImplementedException(); } } #endregion #region Fixed Pipeline Array Base Type /// <summary> /// Get the array components base type of the vertex array attribute item type. /// </summary> /// <param name="vertexArrayType"> /// A <see cref="ArrayBufferItemType"/> that describe the vertex array attribute item type. /// </param> /// <returns> /// It returns a <see cref="VertexBaseType"/> indicating the type of the components of /// the vertex array buffer item. /// </returns> public static VertexPointerType GetVertexPointerType(this ArrayBufferItemType vertexArrayType) { switch (vertexArrayType.GetVertexBaseType()) { case VertexBaseType.Short: return VertexPointerType.Short; case VertexBaseType.Int: return VertexPointerType.Int; case VertexBaseType.Float: return VertexPointerType.Float; #if !MONODROID case VertexBaseType.Double: return VertexPointerType.Double; #endif default: throw new NotSupportedException($"vertex pointer of type {vertexArrayType} not supported"); } } /// <summary> /// Get the array components base type of the vertex array attribute item type. /// </summary> /// <param name="vertexArrayType"> /// A <see cref="ArrayBufferItemType"/> that describe the vertex array attribute item type. /// </param> /// <returns> /// It returns a <see cref="VertexBaseType"/> indicating the type of the components of /// the vertex array buffer item. /// </returns> public static ColorPointerType GetColorPointerType(this ArrayBufferItemType vertexArrayType) { switch (vertexArrayType.GetVertexBaseType()) { case VertexBaseType.Byte: return ColorPointerType.Byte; case VertexBaseType.UByte: return ColorPointerType.UnsignedByte; case VertexBaseType.Short: return ColorPointerType.Short; case VertexBaseType.UShort: return ColorPointerType.UnsignedShort; case VertexBaseType.Int: return ColorPointerType.Int; case VertexBaseType.UInt: return ColorPointerType.UnsignedInt; case VertexBaseType.Float: return ColorPointerType.Float; #if !MONODROID case VertexBaseType.Double: return ColorPointerType.Double; #endif default: throw new NotSupportedException($"color pointer of type {vertexArrayType} not supported"); } } /// <summary> /// Get the array components base type of the vertex array attribute item type. /// </summary> /// <param name="vertexArrayType"> /// A <see cref="ArrayBufferItemType"/> that describe the vertex array attribute item type. /// </param> /// <returns> /// It returns a <see cref="VertexBaseType"/> indicating the type of the components of /// the vertex array buffer item. /// </returns> public static NormalPointerType GetNormalPointerType(this ArrayBufferItemType vertexArrayType) { switch (vertexArrayType.GetVertexBaseType()) { case VertexBaseType.Byte: return NormalPointerType.Byte; case VertexBaseType.Short: return NormalPointerType.Short; case VertexBaseType.Int: return NormalPointerType.Int; case VertexBaseType.Float: return NormalPointerType.Float; #if !MONODROID case VertexBaseType.Double: return NormalPointerType.Double; #endif default: throw new NotSupportedException($"normal pointer of type {vertexArrayType} not supported"); } } /// <summary> /// Get the array components base type of the vertex array attribute item type. /// </summary> /// <param name="vertexArrayType"> /// A <see cref="ArrayBufferItemType"/> that describe the vertex array attribute item type. /// </param> /// <returns> /// It returns a <see cref="VertexBaseType"/> indicating the type of the components of /// the vertex array buffer item. /// </returns> public static TexCoordPointerType GetTexCoordPointerType(this ArrayBufferItemType vertexArrayType) { switch (vertexArrayType.GetVertexBaseType()) { case VertexBaseType.Short: return TexCoordPointerType.Short; case VertexBaseType.Int: return TexCoordPointerType.Int; case VertexBaseType.Float: return TexCoordPointerType.Float; #if !MONODROID case VertexBaseType.Double: return TexCoordPointerType.Double; #endif default: throw new NotSupportedException($"vertex pointer of type {vertexArrayType} not supported"); } } #endregion } }
//#define ASTARDEBUG //"BBTree Debug" If enables, some queries to the tree will show debug lines. Turn off multithreading when using this since DrawLine calls cannot be called from a different thread using System; using UnityEngine; using Pathfinding; using System.Collections.Generic; namespace Pathfinding { /** Axis Aligned Bounding Box Tree. * Holds a bounding box tree of triangles.\n * \b Performance: Insertion - Practically O(1) - About 0.003 ms * \astarpro */ public class BBTree { /** Holds an Axis Aligned Bounding Box Tree used for faster node lookups. * \astarpro */ public BBTreeBox root; public INavmesh graph; public BBTree (INavmesh graph) { this.graph = graph; } public NNInfo Query (Vector3 p, NNConstraint constraint) { BBTreeBox c = root; if (c == null) { return new NNInfo(); } NNInfo nnInfo = new NNInfo (); SearchBox (c,p, constraint, ref nnInfo); nnInfo.UpdateInfo (); return nnInfo; } /** Queries the tree for the best node, searching within a circle around \a p with the specified radius */ public NNInfo QueryCircle (Vector3 p, float radius, NNConstraint constraint) { BBTreeBox c = root; if (c == null) { return new NNInfo(); } #if ASTARDEBUG Vector3 prev = new Vector3 (1,0,0)*radius+p; for (double i=0;i< Math.PI*2; i += Math.PI/50.0) { Vector3 cpos = new Vector3 ((float)Math.Cos (i),0,(float)Math.Sin (i))*radius+p; Debug.DrawLine (prev,cpos,Color.yellow); prev = cpos; } #endif NNInfo nnInfo = new NNInfo (null); SearchBoxCircle (c,p, radius, constraint, ref nnInfo); nnInfo.UpdateInfo (); return nnInfo; } public void SearchBoxCircle (BBTreeBox box, Vector3 p, float radius, NNConstraint constraint, ref NNInfo nnInfo) {//, int intendentLevel = 0) { if (box.node != null) { //Leaf node if (NodeIntersectsCircle (box.node,p,radius)) { //Update the NNInfo #if ASTARDEBUG Debug.DrawLine ((Vector3)graph.vertices[box.node[0]],(Vector3)graph.vertices[box.node[1]],Color.red); Debug.DrawLine ((Vector3)graph.vertices[box.node[1]],(Vector3)graph.vertices[box.node[2]],Color.red); Debug.DrawLine ((Vector3)graph.vertices[box.node[2]],(Vector3)graph.vertices[box.node[0]],Color.red); #endif Vector3 closest = NavMeshGraph.ClosestPointOnNode (box.node,graph.vertices,p); float dist = (closest-p).sqrMagnitude; if (nnInfo.node == null) { nnInfo.node = box.node; nnInfo.clampedPosition = closest; } else if (dist < (nnInfo.clampedPosition - p).sqrMagnitude) { nnInfo.node = box.node; nnInfo.clampedPosition = closest; } if (constraint.Suitable (box.node)) { if (nnInfo.constrainedNode == null) { nnInfo.constrainedNode = box.node; nnInfo.constClampedPosition = closest; } else if (dist < (nnInfo.constClampedPosition - p).sqrMagnitude) { nnInfo.constrainedNode = box.node; nnInfo.constClampedPosition = closest; } } } else { #if ASTARDEBUG Debug.DrawLine ((Vector3)graph.vertices[box.node[0]],(Vector3)graph.vertices[box.node[1]],Color.blue); Debug.DrawLine ((Vector3)graph.vertices[box.node[1]],(Vector3)graph.vertices[box.node[2]],Color.blue); Debug.DrawLine ((Vector3)graph.vertices[box.node[2]],(Vector3)graph.vertices[box.node[0]],Color.blue); #endif } return; } #if ASTARDEBUG Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMin),new Vector3 (box.rect.xMax,0,box.rect.yMin),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMax),new Vector3 (box.rect.xMax,0,box.rect.yMax),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMin,0,box.rect.yMin),new Vector3 (box.rect.xMin,0,box.rect.yMax),Color.white); Debug.DrawLine (new Vector3 (box.rect.xMax,0,box.rect.yMin),new Vector3 (box.rect.xMax,0,box.rect.yMax),Color.white); #endif //Search children if (RectIntersectsCircle (box.c1.rect,p,radius)) { SearchBoxCircle (box.c1,p, radius, constraint, ref nnInfo); } if (RectIntersectsCircle (box.c2.rect,p,radius)) { SearchBoxCircle (box.c2,p, radius, constraint, ref nnInfo); } } public void SearchBox (BBTreeBox box, Vector3 p, NNConstraint constraint, ref NNInfo nnInfo) {//, int intendentLevel = 0) { if (box.node != null) { //Leaf node if (NavMeshGraph.ContainsPoint (box.node,p,graph.vertices)) { //Update the NNInfo if (nnInfo.node == null) { nnInfo.node = box.node; } else if (Mathf.Abs(((Vector3)box.node.position).y - p.y) < Mathf.Abs (((Vector3)nnInfo.node.position).y - p.y)) { nnInfo.node = box.node; } if (constraint.Suitable (box.node)) { if (nnInfo.constrainedNode == null) { nnInfo.constrainedNode = box.node; } else if (Mathf.Abs(box.node.position.y - p.y) < Mathf.Abs (nnInfo.constrainedNode.position.y - p.y)) { nnInfo.constrainedNode = box.node; } } } return; } //Search children if (RectContains (box.c1.rect,p)) { SearchBox (box.c1,p, constraint, ref nnInfo); } if (RectContains (box.c2.rect,p)) { SearchBox (box.c2,p, constraint, ref nnInfo); } } public void Insert (MeshNode node) { BBTreeBox box = new BBTreeBox (this,node); if (root == null) { root = box; return; } BBTreeBox c = root; while (true) { c.rect = ExpandToContain (c.rect,box.rect); if (c.node != null) { //Is Leaf c.c1 = box; BBTreeBox box2 = new BBTreeBox (this,c.node); //Console.WriteLine ("Inserted "+box.node+", rect "+box.rect.ToString ()); c.c2 = box2; c.node = null; //c.rect = c.rect. return; } else { float e1 = ExpansionRequired (c.c1.rect,box.rect); float e2 = ExpansionRequired (c.c2.rect,box.rect); //Choose the rect requiring the least expansion to contain box.rect if (e1 < e2) { c = c.c1; } else if (e2 < e1) { c = c.c2; } else { //Equal, Choose the one with the smallest area c = RectArea (c.c1.rect) < RectArea (c.c2.rect) ? c.c1 : c.c2; } } } } public void OnDrawGizmos () { //Gizmos.color = new Color (1,1,1,0.01F); //OnDrawGizmos (root); } public void OnDrawGizmos (BBTreeBox box) { if (box == null) { return; } Vector3 min = new Vector3 (box.rect.xMin,0,box.rect.yMin); Vector3 max = new Vector3 (box.rect.xMax,0,box.rect.yMax); Vector3 center = (min+max)*0.5F; Vector3 size = (max-center)*2; Gizmos.DrawCube (center,size); OnDrawGizmos (box.c1); OnDrawGizmos (box.c2); } public void TestIntersections (Vector3 p, float radius) { BBTreeBox box = root; TestIntersections (box,p,radius); } public void TestIntersections (BBTreeBox box, Vector3 p, float radius) { if (box == null) { return; } RectIntersectsCircle (box.rect,p,radius); TestIntersections (box.c1,p,radius); TestIntersections (box.c2,p,radius); } public bool NodeIntersectsCircle (MeshNode node, Vector3 p, float radius) { if (NavMeshGraph.ContainsPoint (node,p,graph.vertices)) { return true; } Int3[] vertices = graph.vertices; Vector3 p1 = (Vector3)vertices[node[0]], p2 = (Vector3)vertices[node[1]], p3 = (Vector3)vertices[node[2]]; float r2 = radius*radius; p1.y = p.y; p2.y = p.y; p3.y = p.y; return Mathfx.DistancePointSegmentStrict (p1,p2,p) < r2 || Mathfx.DistancePointSegmentStrict (p2,p3,p) < r2 || Mathfx.DistancePointSegmentStrict (p3,p1,p) < r2; } public bool RectIntersectsCircle (Rect r, Vector3 p, float radius) { if (RectContains (r,p)) { return true; } return XIntersectsCircle (r.xMin,r.xMax,r.yMin,p,radius) || XIntersectsCircle (r.xMin,r.xMax,r.yMax,p,radius) || ZIntersectsCircle (r.yMin,r.yMax,r.xMin,p,radius) || ZIntersectsCircle (r.yMin,r.yMax,r.xMax,p,radius); } /** Returns if a rect contains the 3D point in XZ space */ public bool RectContains (Rect r, Vector3 p) { return p.x >= r.xMin && p.x <= r.xMax && p.z >= r.yMin && p.z <= r.yMax; } public bool ZIntersectsCircle (float z1, float z2, float xpos, Vector3 circle, float radius) { double f = Math.Abs (xpos-circle.x)/radius; if (f > 1.0 || f < -1.0) { return false; } double s = Math.Acos (f); float s1 = (float)Math.Sin (s)*radius; float s2 = circle.z - s1; s1 += circle.z; float min = Math.Min (s1,s2); float max = Math.Max (s1,s2); min = Mathf.Max (z1,min); max = Mathf.Min (z2,max); return max > min; } public bool XIntersectsCircle (float x1, float x2, float zpos, Vector3 circle, float radius) { double f = Math.Abs (zpos-circle.z)/radius; if (f > 1.0 || f < -1.0) { return false; } double s = Math.Asin (f); float s1 = (float)Math.Cos (s)*radius; float s2 = circle.x - s1; s1 += circle.x; float min = Math.Min (s1,s2); float max = Math.Max (s1,s2); min = Mathf.Max (x1,min); max = Mathf.Min (x2,max); return max > min; } /** Returns the difference in area between \a r and \a r expanded to contain \a r2 */ public float ExpansionRequired (Rect r, Rect r2) { float xMin = Mathf.Min (r.xMin,r2.xMin); float xMax = Mathf.Max (r.xMax,r2.xMax); float yMin = Mathf.Min (r.yMin,r2.yMin); float yMax = Mathf.Max (r.yMax,r2.yMax); return (xMax-xMin)*(yMax-yMin)-RectArea (r); } /** Returns a new rect which contains both \a r and \a r2 */ public Rect ExpandToContain (Rect r, Rect r2) { float xMin = Mathf.Min (r.xMin,r2.xMin); float xMax = Mathf.Max (r.xMax,r2.xMax); float yMin = Mathf.Min (r.yMin,r2.yMin); float yMax = Mathf.Max (r.yMax,r2.yMax); return Rect.MinMaxRect (xMin,yMin,xMax,yMax); } /** Returns the area of a rect */ public float RectArea (Rect r) { return r.width*r.height; } public new void ToString () { Console.WriteLine ("Root "+(root.node != null ? root.node.ToString () : "")); BBTreeBox c = root; Stack<BBTreeBox> stack = new Stack<BBTreeBox>(); stack.Push (c); c.WriteChildren (0); } } public class BBTreeBox { public Rect rect; public MeshNode node; public BBTreeBox c1; public BBTreeBox c2; public BBTreeBox (BBTree tree, MeshNode node) { this.node = node; Vector3 first = (Vector3)tree.graph.vertices[node[0]]; Vector2 min = new Vector2(first.x,first.z); Vector2 max = min; for (int i=1;i<3;i++) { Vector3 p = (Vector3)tree.graph.vertices[node[i]]; min.x = Mathf.Min (min.x,p.x); min.y = Mathf.Min (min.y,p.z); max.x = Mathf.Max (max.x,p.x); max.y = Mathf.Max (max.y,p.z); } rect = Rect.MinMaxRect (min.x,min.y,max.x,max.y); } public bool Contains (Vector3 p) { return rect.Contains (p); } public void WriteChildren (int level) { for (int i=0;i<level;i++) { Console.Write (" "); } if (node != null) { Console.WriteLine ("Leaf ");//+triangle.ToString ()); } else { Console.WriteLine ("Box ");//+rect.ToString ()); c1.WriteChildren (level+1); c2.WriteChildren (level+1); } } } }
using System; using System.Collections.Generic; using System.Text; using FlatRedBall.Gui; using FlatRedBall.Graphics.Particle; namespace EditorObjects.Gui { public class EmitterPropertyGrid : PropertyGrid<Emitter> { SpritePropertyGrid mSpritePropertyGrid; #region Properties public override Emitter SelectedObject { get { return base.SelectedObject; } set { base.SelectedObject = value; if (SelectedObject != null) { this.mSpritePropertyGrid.SelectedObject = SelectedObject.ParticleBlueprint; this.SelectCategory(this.SelectedCategory); } this.Visible = SelectedObject != null; } } #endregion #region Event Methods private void ScaleEmitterClick(Window callingWindow) { TextInputWindow tiw = GuiManager.ShowTextInputWindow( "Enter amount to scale by", "Scale Emitter"); tiw.Format = TextBox.FormatTypes.Decimal; tiw.OkClick += ScaleEmitterOk; } private void ScaleEmitterOk(Window callingWindow) { TextInputWindow tiw = (TextInputWindow)callingWindow; try { float scaleAmount = float.Parse(tiw.Text); ScaleEmitter(scaleAmount); } catch { GuiManager.ShowMessageBox("Invalid scaling value", "Error"); } } #endregion #region Methods #region Constructor public EmitterPropertyGrid(Cursor cursor) : base(cursor) { #region Set "this" properties MinimumScaleY = 10; this.Name = "Emitter Properties"; SelectedObject = null; Visible = false; #endregion ExcludeAllMembers(); #region Simple includes and categories IncludeMember("ParentVelocityChangesEmissionVelocity", "Attachment"); IncludeMember("ParentRotationChangesPosition", "Attachment"); IncludeMember("RelativeX", "Attachment"); IncludeMember("RelativeY", "Attachment"); IncludeMember("RelativeZ", "Attachment"); IncludeMember("RelativeRotationX", "Attachment"); IncludeMember("RelativeRotationY", "Attachment"); IncludeMember("RelativeRotationZ", "Attachment"); IncludeMember("X", "Basic"); IncludeMember("Y", "Basic"); IncludeMember("Z", "Basic"); IncludeMember("RotationX", "Basic"); IncludeMember("RotationY", "Basic"); IncludeMember("RotationZ", "Basic"); IncludeMember("Name", "Basic"); IncludeMember("RotationChangesParticleRotation", "Basic"); IncludeMember("RotationChangesParticleAcceleration", "Basic"); IncludeMember("EmissionSettings", "Basic"); IncludeMember("Texture", "Texture"); IncludeMember("RemovalEvent", "Removal"); IncludeMember("SecondsLasting", "Removal"); IncludeMember("AreaEmission", "Emission Area"); IncludeMember("ScaleX", "Emission Area"); IncludeMember("ScaleY", "Emission Area"); IncludeMember("ScaleZ", "Emission Area"); IncludeMember("SecondFrequency", "Frequency"); IncludeMember("NumberPerEmission", "Frequency"); IncludeMember("TimedEmission", "Frequency"); IncludeMember("BoundedEmission", "Boundary"); #endregion #region Set value minimums and maximums UpDown upDown = GetUIElementForMember("ScaleX") as UpDown; upDown.MinValue = 0; upDown = GetUIElementForMember("ScaleY") as UpDown; upDown.MinValue = 0; upDown = GetUIElementForMember("ScaleZ") as UpDown; upDown.MinValue = 0; #endregion #region Create the AreaEmissionType ComboBox ComboBox emissionComboBox = new ComboBox(GuiManager.Cursor); emissionComboBox.AddItem("Point"); emissionComboBox.AddItem("Rectangle"); emissionComboBox.AddItem("Cube"); emissionComboBox.ScaleX = 4; ReplaceMemberUIElement("AreaEmissionType", emissionComboBox); #endregion #region Create the ScaleEmitter ComboBox Button scaleEmitterButton = new Button(this.mCursor); scaleEmitterButton.Text = "Scale Emitter"; scaleEmitterButton.ScaleX = 6; scaleEmitterButton.ScaleY = 1.5f; scaleEmitterButton.Click += ScaleEmitterClick; this.AddWindow(scaleEmitterButton, "Actions"); #endregion mSpritePropertyGrid = new SpritePropertyGrid(cursor); mSpritePropertyGrid.HasMoveBar = false; mSpritePropertyGrid.MakeVisibleOnSpriteSet = false; this.AddWindow(mSpritePropertyGrid, "Blueprint"); mSpritePropertyGrid.Visible = false; RemoveCategory("Uncategorized"); SelectCategory("Basic"); KeepInScreen(); // This needs to be last X = 20.4f; Y = 15.7f; this.MinimumScaleY = 12; PropertyGrid.SetPropertyGridTypeAssociation(typeof(EmissionSettings), typeof(EmissionSettingsPropertyGrid)); } #endregion #region Private Methods private void ScaleEmitter(float scaleAmount) { // scale all of the values: Emitter e = SelectedObject; if (e.EmissionBoundary != null) { e.EmissionBoundary.ScaleBy(scaleAmount); } e.ScaleX *= scaleAmount; e.ScaleY *= scaleAmount; e.ScaleZ *= scaleAmount; e.EmissionSettings.RadialVelocity *= scaleAmount; e.EmissionSettings.RadialVelocityRange *= scaleAmount; e.EmissionSettings.ScaleX *= scaleAmount; e.EmissionSettings.ScaleXRange *= scaleAmount; e.EmissionSettings.ScaleXVelocity *= scaleAmount; e.EmissionSettings.ScaleXVelocityRange *= scaleAmount; e.EmissionSettings.ScaleY *= scaleAmount; e.EmissionSettings.ScaleYRange *= scaleAmount; e.EmissionSettings.ScaleYVelocity *= scaleAmount; e.EmissionSettings.ScaleYVelocityRange *= scaleAmount; // do we scale acceleration by the same amount? e.EmissionSettings.XAcceleration *= scaleAmount; e.EmissionSettings.XAccelerationRange *= scaleAmount; e.EmissionSettings.XVelocity *= scaleAmount; e.EmissionSettings.XVelocityRange *= scaleAmount; e.EmissionSettings.YAcceleration *= scaleAmount; e.EmissionSettings.YAccelerationRange *= scaleAmount; e.EmissionSettings.YVelocity *= scaleAmount; e.EmissionSettings.YVelocityRange *= scaleAmount; e.EmissionSettings.ZAcceleration *= scaleAmount; e.EmissionSettings.ZAccelerationRange *= scaleAmount; e.EmissionSettings.ZVelocity *= scaleAmount; e.EmissionSettings.ZVelocityRange *= scaleAmount; } #endregion #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Reflection; using System.Collections.Generic; using Microsoft.Build.Framework; namespace Microsoft.Build.BuildEngine.Shared { /// <summary> /// This class packages information about a type loaded from an assembly: for example, /// the GenerateResource task class type or the ConsoleLogger logger class type. /// </summary> /// <owner>SumedhK</owner> internal sealed class LoadedType { #region Constructors /// <summary> /// Creates an instance of this class for the given type. /// </summary> /// <owner>SumedhK</owner> /// <param name="type"></param> /// <param name="assembly"></param> internal LoadedType(Type type, AssemblyLoadInfo assembly) { ErrorUtilities.VerifyThrow(type != null, "We must have the type."); ErrorUtilities.VerifyThrow(assembly != null, "We must have the assembly the type was loaded from."); this.type = type; this.assembly = assembly; } #endregion #region Methods /// <summary> /// Gets the list of names of public instance properties that have the required attribute applied. /// Caches the result - since it can't change during the build. /// </summary> /// <returns></returns> public Dictionary<string, string> GetNamesOfPropertiesWithRequiredAttribute() { if (propertyInfoCache == null) { PopulatePropertyInfoCache(); } return namesOfPropertiesWithRequiredAttribute; } /// <summary> /// Gets the list of names of public instance properties that have the output attribute applied. /// Caches the result - since it can't change during the build. /// </summary> /// <returns></returns> public Dictionary<string, string> GetNamesOfPropertiesWithOutputAttribute() { if (propertyInfoCache == null) { PopulatePropertyInfoCache(); } return namesOfPropertiesWithOutputAttribute; } /// <summary> /// Get the cached propertyinfo of the given name /// </summary> /// <param name="propertyName">property name</param> /// <returns>PropertyInfo</returns> public PropertyInfo GetProperty(string propertyName) { if (propertyInfoCache == null) { PopulatePropertyInfoCache(); } PropertyInfo propertyInfo; if (!propertyInfoCache.TryGetValue(propertyName, out propertyInfo)) { return null; } else { if (namesOfPropertiesWithAmbiguousMatches.ContainsKey(propertyName)) { // See comment in PopulatePropertyInfoCache throw new AmbiguousMatchException(); } return propertyInfo; } } /// <summary> /// Populate the cache of PropertyInfos for this type /// </summary> private void PopulatePropertyInfoCache() { if (propertyInfoCache == null) { propertyInfoCache = new Dictionary<string, PropertyInfo>(StringComparer.OrdinalIgnoreCase); namesOfPropertiesWithRequiredAttribute = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); namesOfPropertiesWithOutputAttribute = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); namesOfPropertiesWithAmbiguousMatches = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); PropertyInfo[] propertyInfos = this.Type.GetProperties(BindingFlags.Instance | BindingFlags.Public); for (int i = 0; i < propertyInfos.Length; i++) { try { propertyInfoCache.Add(propertyInfos[i].Name, propertyInfos[i]); } catch (ArgumentException) { // We have encountered a duplicate entry in our hashtable; if we had used BindingFlags.IgnoreCase this // would have produced an AmbiguousMatchException. In the old code, before this cache existed, // that wouldn't have been thrown unless and until the project actually tried to set this ambiguous parameter. // So rather than fail here, we store a list of ambiguous names and throw later, when one of them // is requested. namesOfPropertiesWithAmbiguousMatches[propertyInfos[i].Name] = String.Empty; } if (propertyInfos[i].IsDefined(typeof(RequiredAttribute), false /* uninherited */)) { // we have a require attribute defined, keep a record of that namesOfPropertiesWithRequiredAttribute[propertyInfos[i].Name] = String.Empty; } if (propertyInfos[i].IsDefined(typeof(OutputAttribute), false /* uninherited */)) { // we have a output attribute defined, keep a record of that namesOfPropertiesWithOutputAttribute[propertyInfos[i].Name] = String.Empty; } } } } /// <summary> /// Gets whether there's a LoadInSeparateAppDomain attribute on this type. /// Caches the result - since it can't change during the build. /// </summary> /// <returns></returns> public bool HasLoadInSeparateAppDomainAttribute() { if (hasLoadInSeparateAppDomainAttribute == null) { hasLoadInSeparateAppDomainAttribute = this.Type.IsDefined(typeof(LoadInSeparateAppDomainAttribute), true /* inherited */); } return (bool)hasLoadInSeparateAppDomainAttribute; } #endregion #region Properties /// <summary> /// Gets the type that was loaded from an assembly. /// </summary> /// <owner>SumedhK</owner> /// <value>The loaded type.</value> internal Type Type { get { return type; } } /// <summary> /// Gets the assembly the type was loaded from. /// </summary> /// <owner>SumedhK</owner> /// <value>The assembly info for the loaded type.</value> internal AssemblyLoadInfo Assembly { get { return assembly; } } #endregion // the type that was loaded private Type type; // the assembly the type was loaded from private AssemblyLoadInfo assembly; // cache of names of required properties on this type private Dictionary<string, string> namesOfPropertiesWithRequiredAttribute; // cache of names of output properties on this type private Dictionary<string, string> namesOfPropertiesWithOutputAttribute; // cache of names of properties on this type whose names are ambiguous private Dictionary<string, string> namesOfPropertiesWithAmbiguousMatches; // cache of PropertyInfos for this type private Dictionary<string, PropertyInfo> propertyInfoCache; // whether the loadinseparateappdomain attribute is applied to this type private bool? hasLoadInSeparateAppDomainAttribute; } }
// 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.Diagnostics; using System.Reflection.Internal; using System.Reflection.Metadata; namespace System.Reflection.PortableExecutable { /// <summary> /// Managed .text PE section. /// </summary> /// <remarks> /// Contains in the following order: /// - Import Address Table /// - COR Header /// - IL /// - Metadata /// - Managed Resource Data /// - Strong Name Signature /// - Debug Data (directory and extra info) /// - Import Table /// - Name Table /// - Runtime Startup Stub /// - Mapped Field Data /// </remarks> internal sealed class ManagedTextSection { public Characteristics ImageCharacteristics { get; } public Machine Machine { get; } /// <summary> /// The size of IL stream (unaligned). /// </summary> public int ILStreamSize { get; } /// <summary> /// Total size of metadata (header and all streams). /// </summary> public int MetadataSize { get; } /// <summary> /// The size of managed resource data stream. /// Aligned to <see cref="ManagedResourcesDataAlignment"/>. /// </summary> public int ResourceDataSize { get; } /// <summary> /// Size of strong name hash. /// </summary> public int StrongNameSignatureSize { get; } /// <summary> /// Size of Debug data. /// </summary> public int DebugDataSize { get; } /// <summary> /// The size of mapped field data stream. /// Aligned to <see cref="MappedFieldDataAlignment"/>. /// </summary> public int MappedFieldDataSize { get; } public ManagedTextSection( Characteristics imageCharacteristics, Machine machine, int ilStreamSize, int metadataSize, int resourceDataSize, int strongNameSignatureSize, int debugDataSize, int mappedFieldDataSize) { MetadataSize = metadataSize; ResourceDataSize = resourceDataSize; ILStreamSize = ilStreamSize; MappedFieldDataSize = mappedFieldDataSize; StrongNameSignatureSize = strongNameSignatureSize; ImageCharacteristics = imageCharacteristics; Machine = machine; DebugDataSize = debugDataSize; } /// <summary> /// If set, the module must include a machine code stub that transfers control to the virtual execution system. /// </summary> internal bool RequiresStartupStub => Machine == Machine.I386 || Machine == 0; /// <summary> /// If set, the module contains instructions that assume a 64 bit instruction set. For example it may depend on an address being 64 bits. /// This may be true even if the module contains only IL instructions because of PlatformInvoke and COM interop. /// </summary> internal bool Requires64bits => Machine == Machine.Amd64 || Machine == Machine.IA64; public bool Is32Bit => !Requires64bits; public const int ManagedResourcesDataAlignment = 8; private const string CorEntryPointDll = "mscoree.dll"; private string CorEntryPointName => (ImageCharacteristics & Characteristics.Dll) != 0 ? "_CorDllMain" : "_CorExeMain"; private int SizeOfImportAddressTable => RequiresStartupStub ? (Is32Bit ? 2 * sizeof(uint) : 2 * sizeof(ulong)) : 0; // (_is32bit ? 66 : 70); private int SizeOfImportTable => sizeof(uint) + // RVA sizeof(uint) + // 0 sizeof(uint) + // 0 sizeof(uint) + // name RVA sizeof(uint) + // import address table RVA 20 + // ? (Is32Bit ? 3 * sizeof(uint) : 2 * sizeof(ulong)) + // import lookup table sizeof(ushort) + // hint CorEntryPointName.Length + 1; // NUL private static int SizeOfNameTable => CorEntryPointDll.Length + 1 + sizeof(ushort); private int SizeOfRuntimeStartupStub => Is32Bit ? 8 : 16; public const int MappedFieldDataAlignment = 8; public int CalculateOffsetToMappedFieldDataStream() { int result = ComputeOffsetToImportTable(); if (RequiresStartupStub) { result += SizeOfImportTable + SizeOfNameTable; result = BitArithmetic.Align(result, Is32Bit ? 4 : 8); //optional padding to make startup stub's target address align on word or double word boundary result += SizeOfRuntimeStartupStub; } return result; } internal int ComputeOffsetToDebugDirectory() { Debug.Assert(MetadataSize % 4 == 0); Debug.Assert(ResourceDataSize % 4 == 0); return ComputeOffsetToMetadata() + MetadataSize + ResourceDataSize + StrongNameSignatureSize; } private int ComputeOffsetToImportTable() { return ComputeOffsetToDebugDirectory() + DebugDataSize; } private const int CorHeaderSize = sizeof(int) + // header size sizeof(short) + // major runtime version sizeof(short) + // minor runtime version sizeof(long) + // metadata directory sizeof(int) + // COR flags sizeof(int) + // entry point sizeof(long) + // resources directory sizeof(long) + // strong name signature directory sizeof(long) + // code manager table directory sizeof(long) + // vtable fixups directory sizeof(long) + // export address table jumps directory sizeof(long); // managed-native header directory public int OffsetToILStream => SizeOfImportAddressTable + CorHeaderSize; private int ComputeOffsetToMetadata() { return OffsetToILStream + BitArithmetic.Align(ILStreamSize, 4); } public int ComputeSizeOfTextSection() { Debug.Assert(MappedFieldDataSize % MappedFieldDataAlignment == 0); return CalculateOffsetToMappedFieldDataStream() + MappedFieldDataSize; } public int GetEntryPointAddress(int rva) { // TODO: constants return RequiresStartupStub ? rva + CalculateOffsetToMappedFieldDataStream() - (Is32Bit ? 6 : 10) : 0; } public DirectoryEntry GetImportAddressTableDirectoryEntry(int rva) { return RequiresStartupStub ? new DirectoryEntry(rva, SizeOfImportAddressTable) : default(DirectoryEntry); } public DirectoryEntry GetImportTableDirectoryEntry(int rva) { // TODO: constants return RequiresStartupStub ? new DirectoryEntry(rva + ComputeOffsetToImportTable(), (Is32Bit ? 66 : 70) + 13) : default(DirectoryEntry); } public DirectoryEntry GetCorHeaderDirectoryEntry(int rva) { return new DirectoryEntry(rva + SizeOfImportAddressTable, CorHeaderSize); } #region Serialization /// <summary> /// Serializes .text section data into a specified <paramref name="builder"/>. /// </summary> /// <param name="builder">An empty builder to serialize section data to.</param> /// <param name="relativeVirtualAddess">Relative virtual address of the section within the containing PE file.</param> /// <param name="entryPointTokenOrRelativeVirtualAddress">Entry point token or RVA (<see cref="CorHeader.EntryPointTokenOrRelativeVirtualAddress"/>)</param> /// <param name="corFlags">COR Flags (<see cref="CorHeader.Flags"/>).</param> /// <param name="baseAddress">Base address of the PE image.</param> /// <param name="metadataBuilder"><see cref="BlobBuilder"/> containing metadata. Must be populated with data. Linked into the <paramref name="builder"/> and can't be expanded afterwards.</param> /// <param name="ilBuilder"><see cref="BlobBuilder"/> containing IL stream. Must be populated with data. Linked into the <paramref name="builder"/> and can't be expanded afterwards.</param> /// <param name="mappedFieldDataBuilderOpt"><see cref="BlobBuilder"/> containing mapped field data. Must be populated with data. Linked into the <paramref name="builder"/> and can't be expanded afterwards.</param> /// <param name="resourceBuilderOpt"><see cref="BlobBuilder"/> containing managed resource data. Must be populated with data. Linked into the <paramref name="builder"/> and can't be expanded afterwards.</param> /// <param name="debugDataBuilderOpt"><see cref="BlobBuilder"/> containing PE debug table and data. Must be populated with data. Linked into the <paramref name="builder"/> and can't be expanded afterwards.</param> /// <param name="strongNameSignature">Blob reserved in the <paramref name="builder"/> for strong name signature.</param> public void Serialize( BlobBuilder builder, int relativeVirtualAddess, int entryPointTokenOrRelativeVirtualAddress, CorFlags corFlags, ulong baseAddress, BlobBuilder metadataBuilder, BlobBuilder ilBuilder, BlobBuilder mappedFieldDataBuilderOpt, BlobBuilder resourceBuilderOpt, BlobBuilder debugDataBuilderOpt, out Blob strongNameSignature) { Debug.Assert(builder.Count == 0); Debug.Assert(metadataBuilder.Count == MetadataSize); Debug.Assert(metadataBuilder.Count % 4 == 0); Debug.Assert(ilBuilder.Count == ILStreamSize); Debug.Assert((mappedFieldDataBuilderOpt?.Count ?? 0) == MappedFieldDataSize); Debug.Assert((resourceBuilderOpt?.Count ?? 0) == ResourceDataSize); Debug.Assert((resourceBuilderOpt?.Count ?? 0) % 4 == 0); // TODO: avoid recalculation int importTableRva = GetImportTableDirectoryEntry(relativeVirtualAddess).RelativeVirtualAddress; int importAddressTableRva = GetImportAddressTableDirectoryEntry(relativeVirtualAddess).RelativeVirtualAddress; if (RequiresStartupStub) { WriteImportAddressTable(builder, importTableRva); } WriteCorHeader(builder, relativeVirtualAddess, entryPointTokenOrRelativeVirtualAddress, corFlags); // IL: ilBuilder.Align(4); builder.LinkSuffix(ilBuilder); // metadata: builder.LinkSuffix(metadataBuilder); // managed resources: if (resourceBuilderOpt != null) { builder.LinkSuffix(resourceBuilderOpt); } // strong name signature: strongNameSignature = builder.ReserveBytes(StrongNameSignatureSize); // The bytes are required to be 0 for the purpose of calculating hash of the PE content // when strong name signing. new BlobWriter(strongNameSignature).WriteBytes(0, StrongNameSignatureSize); // debug directory and data: if (debugDataBuilderOpt != null) { builder.LinkSuffix(debugDataBuilderOpt); } if (RequiresStartupStub) { WriteImportTable(builder, importTableRva, importAddressTableRva); WriteNameTable(builder); WriteRuntimeStartupStub(builder, importAddressTableRva, baseAddress); } // mapped field data: if (mappedFieldDataBuilderOpt != null) { builder.LinkSuffix(mappedFieldDataBuilderOpt); } Debug.Assert(builder.Count == ComputeSizeOfTextSection()); } private void WriteImportAddressTable(BlobBuilder builder, int importTableRva) { int start = builder.Count; int ilRva = importTableRva + 40; int hintRva = ilRva + (Is32Bit ? 12 : 16); // Import Address Table if (Is32Bit) { builder.WriteUInt32((uint)hintRva); // 4 builder.WriteUInt32(0); // 8 } else { builder.WriteUInt64((uint)hintRva); // 8 builder.WriteUInt64(0); // 16 } Debug.Assert(builder.Count - start == SizeOfImportAddressTable); } private void WriteImportTable(BlobBuilder builder, int importTableRva, int importAddressTableRva) { int start = builder.Count; int ilRVA = importTableRva + 40; int hintRva = ilRVA + (Is32Bit ? 12 : 16); int nameRva = hintRva + 12 + 2; // Import table builder.WriteUInt32((uint)ilRVA); // 4 builder.WriteUInt32(0); // 8 builder.WriteUInt32(0); // 12 builder.WriteUInt32((uint)nameRva); // 16 builder.WriteUInt32((uint)importAddressTableRva); // 20 builder.WriteBytes(0, 20); // 40 // Import Lookup table if (Is32Bit) { builder.WriteUInt32((uint)hintRva); // 44 builder.WriteUInt32(0); // 48 builder.WriteUInt32(0); // 52 } else { builder.WriteUInt64((uint)hintRva); // 48 builder.WriteUInt64(0); // 56 } // Hint table builder.WriteUInt16(0); // Hint 54|58 foreach (char ch in CorEntryPointName) { builder.WriteByte((byte)ch); // 65|69 } builder.WriteByte(0); // 66|70 Debug.Assert(builder.Count - start == SizeOfImportTable); } private static void WriteNameTable(BlobBuilder builder) { int start = builder.Count; foreach (char ch in CorEntryPointDll) { builder.WriteByte((byte)ch); } builder.WriteByte(0); builder.WriteUInt16(0); Debug.Assert(builder.Count - start == SizeOfNameTable); } private void WriteCorHeader(BlobBuilder builder, int textSectionRva, int entryPointTokenOrRva, CorFlags corFlags) { const ushort majorRuntimeVersion = 2; const ushort minorRuntimeVersion = 5; int metadataRva = textSectionRva + ComputeOffsetToMetadata(); int resourcesRva = metadataRva + MetadataSize; int signatureRva = resourcesRva + ResourceDataSize; int start = builder.Count; // Size: builder.WriteUInt32(CorHeaderSize); // Version: builder.WriteUInt16(majorRuntimeVersion); builder.WriteUInt16(minorRuntimeVersion); // MetadataDirectory: builder.WriteUInt32((uint)metadataRva); builder.WriteUInt32((uint)MetadataSize); // COR Flags: builder.WriteUInt32((uint)corFlags); // EntryPoint: builder.WriteUInt32((uint)entryPointTokenOrRva); // ResourcesDirectory: builder.WriteUInt32((uint)(ResourceDataSize == 0 ? 0 : resourcesRva)); // 28 builder.WriteUInt32((uint)ResourceDataSize); // StrongNameSignatureDirectory: builder.WriteUInt32((uint)(StrongNameSignatureSize == 0 ? 0 : signatureRva)); // 36 builder.WriteUInt32((uint)StrongNameSignatureSize); // CodeManagerTableDirectory (not supported): builder.WriteUInt32(0); builder.WriteUInt32(0); // VtableFixupsDirectory (not supported): builder.WriteUInt32(0); builder.WriteUInt32(0); // ExportAddressTableJumpsDirectory (not supported): builder.WriteUInt32(0); builder.WriteUInt32(0); // ManagedNativeHeaderDirectory (not supported): builder.WriteUInt32(0); builder.WriteUInt32(0); Debug.Assert(builder.Count - start == CorHeaderSize); Debug.Assert(builder.Count % 4 == 0); } private void WriteRuntimeStartupStub(BlobBuilder sectionBuilder, int importAddressTableRva, ulong baseAddress) { // entry point code, consisting of a jump indirect to _CorXXXMain if (Is32Bit) { // Write zeros (nops) to pad the entry point code so that the target address is aligned on a 4 byte boundary. // Note that the section is aligned to FileAlignment, which is at least 512, so we can align relatively to the start of the section. sectionBuilder.Align(4); sectionBuilder.WriteUInt16(0); sectionBuilder.WriteByte(0xff); sectionBuilder.WriteByte(0x25); //4 sectionBuilder.WriteUInt32((uint)importAddressTableRva + (uint)baseAddress); //8 } else { // Write zeros (nops) to pad the entry point code so that the target address is aligned on a 8 byte boundary. // Note that the section is aligned to FileAlignment, which is at least 512, so we can align relatively to the start of the section. sectionBuilder.Align(8); sectionBuilder.WriteUInt32(0); sectionBuilder.WriteUInt16(0); sectionBuilder.WriteByte(0xff); sectionBuilder.WriteByte(0x25); //8 sectionBuilder.WriteUInt64((ulong)importAddressTableRva + baseAddress); //16 } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #define ENABLE #define MINBUFFERS using System; #if !FEATURE_CORECLR using System.Diagnostics.Tracing; #endif using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; using System.Collections.Generic; using System.Collections.Concurrent; using System.Threading; using System.Runtime.CompilerServices; using System.Diagnostics; using System.Security.Permissions; #if PINNABLEBUFFERCACHE_MSCORLIB namespace System.Threading #else namespace System #endif { internal sealed class PinnableBufferCache { /// <summary> /// Create a new cache for pinned byte[] buffers /// </summary> /// <param name="cacheName">A name used in diagnostic messages</param> /// <param name="numberOfElements">The size of byte[] buffers in the cache (they are all the same size)</param> public PinnableBufferCache(string cacheName, int numberOfElements) : this(cacheName, () => new byte[numberOfElements]) { } /// <summary> /// Get a buffer from the buffer manager. If no buffers exist, allocate a new one. /// </summary> public byte[] AllocateBuffer() { return (byte[])Allocate(); } /// <summary> /// Return a buffer back to the buffer manager. /// </summary> public void FreeBuffer(byte[] buffer) { Free(buffer); } /// <summary> /// Create a PinnableBufferCache that works on any object (it is intended for OverlappedData) /// This is only used in mscorlib. /// </summary> #if (ENABLE || MINBUFFERS) #pragma warning disable 618 [EnvironmentPermission(SecurityAction.Assert, Unrestricted = true)] #pragma warning restore 618 [System.Security.SecuritySafeCritical] #endif internal PinnableBufferCache(string cacheName, Func<object> factory) { m_NotGen2 = new List<object>(DefaultNumberOfBuffers); m_factory = factory; #if ENABLE // Check to see if we should disable the cache. string envVarName = "PinnableBufferCache_" + cacheName + "_Disabled"; try { string envVar = Environment.GetEnvironmentVariable(envVarName); if (envVar != null) { PinnableBufferCacheEventSource.Log.DebugMessage("Creating " + cacheName + " PinnableBufferCacheDisabled=" + envVar); int index = envVar.IndexOf(cacheName, StringComparison.OrdinalIgnoreCase); if (0 <= index) { // The cache is disabled because we haven't set the cache name. PinnableBufferCacheEventSource.Log.DebugMessage("Disabling " + cacheName); return; } } } catch { // Ignore failures when reading the environment variable. } #endif #if MINBUFFERS // Allow the environment to specify a minimum buffer count. string minEnvVarName = "PinnableBufferCache_" + cacheName + "_MinCount"; try { string minEnvVar = Environment.GetEnvironmentVariable(minEnvVarName); if (minEnvVar != null) { if (int.TryParse(minEnvVar, out m_minBufferCount)) CreateNewBuffers(); } } catch { // Ignore failures when reading the environment variable. } #endif PinnableBufferCacheEventSource.Log.Create(cacheName); m_CacheName = cacheName; } /// <summary> /// Get a object from the buffer manager. If no buffers exist, allocate a new one. /// </summary> [System.Security.SecuritySafeCritical] internal object Allocate() { #if ENABLE // Check to see whether or not the cache is disabled. if (m_CacheName == null) return m_factory(); #endif // Fast path, get it from our Gen2 aged m_FreeList. object returnBuffer; if (!m_FreeList.TryPop(out returnBuffer)) Restock(out returnBuffer); // Computing free count is expensive enough that we don't want to compute it unless logging is on. if (PinnableBufferCacheEventSource.Log.IsEnabled()) { int numAllocCalls = Interlocked.Increment(ref m_numAllocCalls); if (numAllocCalls >= 1024) { lock (this) { int previousNumAllocCalls = Interlocked.Exchange(ref m_numAllocCalls, 0); if (previousNumAllocCalls >= 1024) { int nonGen2Count = 0; foreach (object o in m_FreeList) { if (GC.GetGeneration(o) < GC.MaxGeneration) { nonGen2Count++; } } PinnableBufferCacheEventSource.Log.WalkFreeListResult(m_CacheName, m_FreeList.Count, nonGen2Count); } } } PinnableBufferCacheEventSource.Log.AllocateBuffer(m_CacheName, PinnableBufferCacheEventSource.AddressOf(returnBuffer), returnBuffer.GetHashCode(), GC.GetGeneration(returnBuffer), m_FreeList.Count); } return returnBuffer; } /// <summary> /// Return a buffer back to the buffer manager. /// </summary> [System.Security.SecuritySafeCritical] internal void Free(object buffer) { #if ENABLE // Check to see whether or not the cache is disabled. if (m_CacheName == null) return; #endif if (PinnableBufferCacheEventSource.Log.IsEnabled()) PinnableBufferCacheEventSource.Log.FreeBuffer(m_CacheName, PinnableBufferCacheEventSource.AddressOf(buffer), buffer.GetHashCode(), m_FreeList.Count); // After we've done 3 gen1 GCs, assume that all buffers have aged into gen2 on the free path. if ((m_gen1CountAtLastRestock + 3) > GC.CollectionCount(GC.MaxGeneration - 1)) { lock (this) { if (GC.GetGeneration(buffer) < GC.MaxGeneration) { // The buffer is not aged, so put it in the non-aged free list. m_moreThanFreeListNeeded = true; PinnableBufferCacheEventSource.Log.FreeBufferStillTooYoung(m_CacheName, m_NotGen2.Count); m_NotGen2.Add(buffer); m_gen1CountAtLastRestock = GC.CollectionCount(GC.MaxGeneration - 1); return; } } } // If we discovered that it is indeed Gen2, great, put it in the Gen2 list. m_FreeList.Push(buffer); } #region Private /// <summary> /// Called when we don't have any buffers in our free list to give out. /// </summary> /// <returns></returns> [System.Security.SecuritySafeCritical] private void Restock(out object returnBuffer) { lock (this) { // Try again after getting the lock as another thread could have just filled the free list. If we don't check // then we unnecessarily grab a new set of buffers because we think we are out. if (m_FreeList.TryPop(out returnBuffer)) return; // Lazy init, Ask that TrimFreeListIfNeeded be called on every Gen 2 GC. if (m_restockSize == 0) Gen2GcCallback.Register(Gen2GcCallbackFunc, this); // Indicate to the trimming policy that the free list is insufficent. m_moreThanFreeListNeeded = true; PinnableBufferCacheEventSource.Log.AllocateBufferFreeListEmpty(m_CacheName, m_NotGen2.Count); // Get more buffers if needed. if (m_NotGen2.Count == 0) CreateNewBuffers(); // We have no buffers in the aged freelist, so get one from the newer list. Try to pick the best one. // Debug.Assert(m_NotGen2.Count != 0); int idx = m_NotGen2.Count - 1; if (GC.GetGeneration(m_NotGen2[idx]) < GC.MaxGeneration && GC.GetGeneration(m_NotGen2[0]) == GC.MaxGeneration) idx = 0; returnBuffer = m_NotGen2[idx]; m_NotGen2.RemoveAt(idx); // Remember any sub-optimial buffer so we don't put it on the free list when it gets freed. if (PinnableBufferCacheEventSource.Log.IsEnabled() && GC.GetGeneration(returnBuffer) < GC.MaxGeneration) { PinnableBufferCacheEventSource.Log.AllocateBufferFromNotGen2(m_CacheName, m_NotGen2.Count); } // If we have a Gen1 collection, then everything on m_NotGen2 should have aged. Move them to the m_Free list. if (!AgePendingBuffers()) { // Before we could age at set of buffers, we have handed out half of them. // This implies we should be proactive about allocating more (since we will trim them if we over-allocate). if (m_NotGen2.Count == m_restockSize / 2) { PinnableBufferCacheEventSource.Log.DebugMessage("Proactively adding more buffers to aging pool"); CreateNewBuffers(); } } } } /// <summary> /// See if we can promote the buffers to the free list. Returns true if sucessful. /// </summary> [System.Security.SecuritySafeCritical] private bool AgePendingBuffers() { if (m_gen1CountAtLastRestock < GC.CollectionCount(GC.MaxGeneration - 1)) { // Allocate a temp list of buffers that are not actually in gen2, and swap it in once // we're done scanning all buffers. int promotedCount = 0; List<object> notInGen2 = new List<object>(); PinnableBufferCacheEventSource.Log.AllocateBufferAged(m_CacheName, m_NotGen2.Count); for (int i = 0; i < m_NotGen2.Count; i++) { // We actually check every object to ensure that we aren't putting non-aged buffers into the free list. object currentBuffer = m_NotGen2[i]; if (GC.GetGeneration(currentBuffer) >= GC.MaxGeneration) { m_FreeList.Push(currentBuffer); promotedCount++; } else { notInGen2.Add(currentBuffer); } } PinnableBufferCacheEventSource.Log.AgePendingBuffersResults(m_CacheName, promotedCount, notInGen2.Count); m_NotGen2 = notInGen2; return true; } return false; } /// <summary> /// Generates some buffers to age into Gen2. /// </summary> private void CreateNewBuffers() { // We choose a very modest number of buffers initially because for the client case. This is often enough. if (m_restockSize == 0) m_restockSize = 4; else if (m_restockSize < DefaultNumberOfBuffers) m_restockSize = DefaultNumberOfBuffers; else if (m_restockSize < 256) m_restockSize = m_restockSize * 2; // Grow quickly at small sizes else if (m_restockSize < 4096) m_restockSize = m_restockSize * 3 / 2; // Less agressively at large ones else m_restockSize = 4096; // Cap how agressive we are // Ensure we hit our minimums if (m_minBufferCount > m_buffersUnderManagement) m_restockSize = Math.Max(m_restockSize, m_minBufferCount - m_buffersUnderManagement); PinnableBufferCacheEventSource.Log.AllocateBufferCreatingNewBuffers(m_CacheName, m_buffersUnderManagement, m_restockSize); for (int i = 0; i < m_restockSize; i++) { // Make a new buffer. object newBuffer = m_factory(); // Create space between the objects. We do this because otherwise it forms a single plug (group of objects) // and the GC pins the entire plug making them NOT move to Gen1 and Gen2. by putting space between them // we ensure that object get a chance to move independently (even if some are pinned). var dummyObject = new object(); m_NotGen2.Add(newBuffer); } m_buffersUnderManagement += m_restockSize; m_gen1CountAtLastRestock = GC.CollectionCount(GC.MaxGeneration - 1); } /// <summary> /// This is the static function that is called from the gen2 GC callback. /// The input object is the cache itself. /// NOTE: The reason that we make this functionstatic and take the cache as a parameter is that /// otherwise, we root the cache to the Gen2GcCallback object, and leak the cache even when /// the application no longer needs it. /// </summary> [System.Security.SecuritySafeCritical] private static bool Gen2GcCallbackFunc(object targetObj) { return ((PinnableBufferCache)(targetObj)).TrimFreeListIfNeeded(); } /// <summary> /// This is called on every gen2 GC to see if we need to trim the free list. /// NOTE: DO NOT CALL THIS DIRECTLY FROM THE GEN2GCCALLBACK. INSTEAD CALL IT VIA A STATIC FUNCTION (SEE ABOVE). /// If you register a non-static function as a callback, then this object will be leaked. /// </summary> [System.Security.SecuritySafeCritical] private bool TrimFreeListIfNeeded() { int curMSec = Environment.TickCount; int deltaMSec = curMSec - m_msecNoUseBeyondFreeListSinceThisTime; PinnableBufferCacheEventSource.Log.TrimCheck(m_CacheName, m_buffersUnderManagement, m_moreThanFreeListNeeded, deltaMSec); // If we needed more than just the set of aged buffers since the last time we were called, // we obviously should not be trimming any memory, so do nothing except reset the flag if (m_moreThanFreeListNeeded) { m_moreThanFreeListNeeded = false; m_trimmingExperimentInProgress = false; m_msecNoUseBeyondFreeListSinceThisTime = curMSec; return true; } // We require a minimum amount of clock time to pass (10 seconds) before we trim. Ideally this time // is larger than the typical buffer hold time. if (0 <= deltaMSec && deltaMSec < 10000) return true; // If we got here we have spend the last few second without needing to lengthen the free list. Thus // we have 'enough' buffers, but maybe we have too many. // See if we can trim lock (this) { // Hit a race, try again later. if (m_moreThanFreeListNeeded) { m_moreThanFreeListNeeded = false; m_trimmingExperimentInProgress = false; m_msecNoUseBeyondFreeListSinceThisTime = curMSec; return true; } var freeCount = m_FreeList.Count; // This is expensive to fetch, do it once. // If there is something in m_NotGen2 it was not used for the last few seconds, it is trimable. if (m_NotGen2.Count > 0) { // If we are not performing an experiment and we have stuff that is waiting to go into the // free list but has not made it there, it could be becasue the 'slow path' of restocking // has not happened, so force this (which should flush the list) and start over. if (!m_trimmingExperimentInProgress) { PinnableBufferCacheEventSource.Log.TrimFlush(m_CacheName, m_buffersUnderManagement, freeCount, m_NotGen2.Count); AgePendingBuffers(); m_trimmingExperimentInProgress = true; return true; } PinnableBufferCacheEventSource.Log.TrimFree(m_CacheName, m_buffersUnderManagement, freeCount, m_NotGen2.Count); m_buffersUnderManagement -= m_NotGen2.Count; // Possibly revise the restocking down. We don't want to grow agressively if we are trimming. var newRestockSize = m_buffersUnderManagement / 4; if (newRestockSize < m_restockSize) m_restockSize = Math.Max(newRestockSize, DefaultNumberOfBuffers); m_NotGen2.Clear(); m_trimmingExperimentInProgress = false; return true; } // Set up an experiment where we use 25% less buffers in our free list. We put them in // m_NotGen2, and if they are needed they will be put back in the free list again. var trimSize = freeCount / 4 + 1; // We are OK with a 15% overhead, do nothing in that case. if (freeCount * 15 <= m_buffersUnderManagement || m_buffersUnderManagement - trimSize <= m_minBufferCount) { PinnableBufferCacheEventSource.Log.TrimFreeSizeOK(m_CacheName, m_buffersUnderManagement, freeCount); return true; } // Move buffers from the free list back to the non-aged list. If we don't use them by next time, then we'll consider trimming them. PinnableBufferCacheEventSource.Log.TrimExperiment(m_CacheName, m_buffersUnderManagement, freeCount, trimSize); object buffer; for (int i = 0; i < trimSize; i++) { if (m_FreeList.TryPop(out buffer)) m_NotGen2.Add(buffer); } m_msecNoUseBeyondFreeListSinceThisTime = curMSec; m_trimmingExperimentInProgress = true; } // Indicate that we want to be called back on the next Gen 2 GC. return true; } private const int DefaultNumberOfBuffers = 16; private string m_CacheName; private Func<object> m_factory; /// <summary> /// Contains 'good' buffers to reuse. They are guarenteed to be Gen 2 ENFORCED! /// </summary> private ConcurrentStack<object> m_FreeList = new ConcurrentStack<object>(); /// <summary> /// Contains buffers that are not gen 2 and thus we do not wish to give out unless we have to. /// To implement trimming we sometimes put aged buffers in here as a place to 'park' them /// before true deletion. /// </summary> private List<object> m_NotGen2; /// <summary> /// What whas the gen 1 count the last time re restocked? If it is now greater, then /// we know that all objects are in Gen 2 so we don't have to check. Should be updated /// every time something gets added to the m_NotGen2 list. /// </summary> private int m_gen1CountAtLastRestock; /// <summary> /// Used to ensure we have a minimum time between trimmings. /// </summary> private int m_msecNoUseBeyondFreeListSinceThisTime; /// <summary> /// To trim, we remove things from the free list (which is Gen 2) and see if we 'hit bottom' /// This flag indicates that we hit bottom (we really needed a bigger free list). /// </summary> private bool m_moreThanFreeListNeeded; /// <summary> /// The total number of buffers that this cache has ever allocated. /// Used in trimming heuristics. /// </summary> private int m_buffersUnderManagement; /// <summary> /// The number of buffers we added the last time we restocked. /// </summary> private int m_restockSize; /// <summary> /// Did we put some buffers into m_NotGen2 to see if we can trim? /// </summary> private bool m_trimmingExperimentInProgress; /// <summary> /// A forced minimum number of buffers. /// </summary> private int m_minBufferCount; /// <summary> /// The number of calls to Allocate. /// </summary> private int m_numAllocCalls; #endregion } /// <summary> /// Schedules a callback roughly every gen 2 GC (you may see a Gen 0 an Gen 1 but only once) /// (We can fix this by capturing the Gen 2 count at startup and testing, but I mostly don't care) /// </summary> internal sealed class Gen2GcCallback : CriticalFinalizerObject { [System.Security.SecuritySafeCritical] public Gen2GcCallback() : base() { } /// <summary> /// Schedule 'callback' to be called in the next GC. If the callback returns true it is /// rescheduled for the next Gen 2 GC. Otherwise the callbacks stop. /// /// NOTE: This callback will be kept alive until either the callback function returns false, /// or the target object dies. /// </summary> public static void Register(Func<object, bool> callback, object targetObj) { // Create a unreachable object that remembers the callback function and target object. Gen2GcCallback gcCallback = new Gen2GcCallback(); gcCallback.Setup(callback, targetObj); } #region Private private Func<object, bool> m_callback; private GCHandle m_weakTargetObj; [System.Security.SecuritySafeCritical] private void Setup(Func<object, bool> callback, object targetObj) { m_callback = callback; m_weakTargetObj = GCHandle.Alloc(targetObj, GCHandleType.Weak); } [System.Security.SecuritySafeCritical] ~Gen2GcCallback() { // Check to see if the target object is still alive. object targetObj = m_weakTargetObj.Target; if (targetObj == null) { // The target object is dead, so this callback object is no longer needed. m_weakTargetObj.Free(); return; } // Execute the callback method. try { if (!m_callback(targetObj)) { // If the callback returns false, this callback object is no longer needed. return; } } catch { // Ensure that we still get a chance to resurrect this object, even if the callback throws an exception. } // Resurrect ourselves by re-registering for finalization. if (!Environment.HasShutdownStarted && !AppDomain.CurrentDomain.IsFinalizingForUnload()) { GC.ReRegisterForFinalize(this); } } #endregion } #if FEATURE_CORECLR internal sealed class PinnableBufferCacheEventSource { public static readonly PinnableBufferCacheEventSource Log = new PinnableBufferCacheEventSource(); public bool IsEnabled() { return false; } public void DebugMessage(string message) {} public void DebugMessage1(string message, long value) {} public void DebugMessage2(string message, long value1, long value2) {} public void DebugMessage3(string message, long value1, long value2, long value3) {} public void Create(string cacheName) {} public void AllocateBuffer(string cacheName, ulong objectId, int objectHash, int objectGen, int freeCountAfter) {} public void AllocateBufferFromNotGen2(string cacheName, int notGen2CountAfter) {} public void AllocateBufferCreatingNewBuffers(string cacheName, int totalBuffsBefore, int objectCount) {} public void AllocateBufferAged(string cacheName, int agedCount) {} public void AllocateBufferFreeListEmpty(string cacheName, int notGen2CountBefore) {} public void FreeBuffer(string cacheName, ulong objectId, int objectHash, int freeCountBefore) {} public void FreeBufferStillTooYoung(string cacheName, int notGen2CountBefore) {} public void TrimCheck(string cacheName, int totalBuffs, bool neededMoreThanFreeList, int deltaMSec) {} public void TrimFree(string cacheName, int totalBuffs, int freeListCount, int toBeFreed) {} public void TrimExperiment(string cacheName, int totalBuffs, int freeListCount, int numTrimTrial) {} public void TrimFreeSizeOK(string cacheName, int totalBuffs, int freeListCount) {} public void TrimFlush(string cacheName, int totalBuffs, int freeListCount, int notGen2CountBefore) {} public void AgePendingBuffersResults(string cacheName, int promotedToFreeListCount, int heldBackCount) {} public void WalkFreeListResult(string cacheName, int freeListCount, int gen0BuffersInFreeList) {} static internal ulong AddressOf(object obj) { return 0; } [System.Security.SecuritySafeCritical] static internal unsafe long AddressOfObject(byte[] array) { return 0; } } #else /// <summary> /// PinnableBufferCacheEventSource is a private eventSource that we are using to /// debug and monitor the effectiveness of PinnableBufferCache /// </summary> #if PINNABLEBUFFERCACHE_MSCORLIB [EventSource(Name = "Microsoft-DotNETRuntime-PinnableBufferCache")] #else [EventSource(Name = "Microsoft-DotNETRuntime-PinnableBufferCache-System")] #endif internal sealed class PinnableBufferCacheEventSource : EventSource { public static readonly PinnableBufferCacheEventSource Log = new PinnableBufferCacheEventSource(); [Event(1, Level = EventLevel.Verbose)] public void DebugMessage(string message) { if (IsEnabled()) WriteEvent(1, message); } [Event(2, Level = EventLevel.Verbose)] public void DebugMessage1(string message, long value) { if (IsEnabled()) WriteEvent(2, message, value); } [Event(3, Level = EventLevel.Verbose)] public void DebugMessage2(string message, long value1, long value2) { if (IsEnabled()) WriteEvent(3, message, value1, value2); } [Event(18, Level = EventLevel.Verbose)] public void DebugMessage3(string message, long value1, long value2, long value3) { if (IsEnabled()) WriteEvent(18, message, value1, value2, value3); } [Event(4)] public void Create(string cacheName) { if (IsEnabled()) WriteEvent(4, cacheName); } [Event(5, Level = EventLevel.Verbose)] public void AllocateBuffer(string cacheName, ulong objectId, int objectHash, int objectGen, int freeCountAfter) { if (IsEnabled()) WriteEvent(5, cacheName, objectId, objectHash, objectGen, freeCountAfter); } [Event(6)] public void AllocateBufferFromNotGen2(string cacheName, int notGen2CountAfter) { if (IsEnabled()) WriteEvent(6, cacheName, notGen2CountAfter); } [Event(7)] public void AllocateBufferCreatingNewBuffers(string cacheName, int totalBuffsBefore, int objectCount) { if (IsEnabled()) WriteEvent(7, cacheName, totalBuffsBefore, objectCount); } [Event(8)] public void AllocateBufferAged(string cacheName, int agedCount) { if (IsEnabled()) WriteEvent(8, cacheName, agedCount); } [Event(9)] public void AllocateBufferFreeListEmpty(string cacheName, int notGen2CountBefore) { if (IsEnabled()) WriteEvent(9, cacheName, notGen2CountBefore); } [Event(10, Level = EventLevel.Verbose)] public void FreeBuffer(string cacheName, ulong objectId, int objectHash, int freeCountBefore) { if (IsEnabled()) WriteEvent(10, cacheName, objectId, objectHash, freeCountBefore); } [Event(11)] public void FreeBufferStillTooYoung(string cacheName, int notGen2CountBefore) { if (IsEnabled()) WriteEvent(11, cacheName, notGen2CountBefore); } [Event(13)] public void TrimCheck(string cacheName, int totalBuffs, bool neededMoreThanFreeList, int deltaMSec) { if (IsEnabled()) WriteEvent(13, cacheName, totalBuffs, neededMoreThanFreeList, deltaMSec); } [Event(14)] public void TrimFree(string cacheName, int totalBuffs, int freeListCount, int toBeFreed) { if (IsEnabled()) WriteEvent(14, cacheName, totalBuffs, freeListCount, toBeFreed); } [Event(15)] public void TrimExperiment(string cacheName, int totalBuffs, int freeListCount, int numTrimTrial) { if (IsEnabled()) WriteEvent(15, cacheName, totalBuffs, freeListCount, numTrimTrial); } [Event(16)] public void TrimFreeSizeOK(string cacheName, int totalBuffs, int freeListCount) { if (IsEnabled()) WriteEvent(16, cacheName, totalBuffs, freeListCount); } [Event(17)] public void TrimFlush(string cacheName, int totalBuffs, int freeListCount, int notGen2CountBefore) { if (IsEnabled()) WriteEvent(17, cacheName, totalBuffs, freeListCount, notGen2CountBefore); } [Event(20)] public void AgePendingBuffersResults(string cacheName, int promotedToFreeListCount, int heldBackCount) { if (IsEnabled()) WriteEvent(20, cacheName, promotedToFreeListCount, heldBackCount); } [Event(21)] public void WalkFreeListResult(string cacheName, int freeListCount, int gen0BuffersInFreeList) { if (IsEnabled()) WriteEvent(21, cacheName, freeListCount, gen0BuffersInFreeList); } static internal ulong AddressOf(object obj) { var asByteArray = obj as byte[]; if (asByteArray != null) return (ulong)AddressOfByteArray(asByteArray); return 0; } [System.Security.SecuritySafeCritical] static internal unsafe long AddressOfByteArray(byte[] array) { if (array == null) return 0; fixed (byte* ptr = array) return (long)(ptr - 2 * sizeof(void*)); } } #endif }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Sql; using Microsoft.Azure.Management.Sql.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Sql { /// <summary> /// Represents all the operations for operating on Azure SQL Server /// communication links. Contains operations to: Create, Retrieve, /// Update, and Delete. /// </summary> internal partial class ServerCommunicationLinkOperations : IServiceOperations<SqlManagementClient>, IServerCommunicationLinkOperations { /// <summary> /// Initializes a new instance of the ServerCommunicationLinkOperations /// class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ServerCommunicationLinkOperations(SqlManagementClient client) { this._client = client; } private SqlManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Sql.SqlManagementClient. /// </summary> public SqlManagementClient Client { get { return this._client; } } /// <summary> /// Begins creating a new or updating an existing Azure SQL Server /// communication. To determine the status of the operation call /// GetServerCommunicationLinkOperationStatus. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server. /// </param> /// <param name='communicationLinkName'> /// Required. The name of the Azure SQL Server communication link to be /// operated on (Updated or created). /// </param> /// <param name='parameters'> /// Required. The required parameters for creating or updating a Server /// communication link. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for long running Azure Sql server communication link /// operation. /// </returns> public async Task<ServerCommunicationLinkCreateOrUpdateResponse> BeginCreateOrUpdateAsync(string resourceGroupName, string serverName, string communicationLinkName, ServerCommunicationLinkCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (communicationLinkName == null) { throw new ArgumentNullException("communicationLinkName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Location == null) { throw new ArgumentNullException("parameters.Location"); } if (parameters.Properties == null) { throw new ArgumentNullException("parameters.Properties"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("communicationLinkName", communicationLinkName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginCreateOrUpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/communicationLinks/"; url = url + Uri.EscapeDataString(communicationLinkName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject serverCommunicationLinkCreateOrUpdateParametersValue = new JObject(); requestDoc = serverCommunicationLinkCreateOrUpdateParametersValue; JObject propertiesValue = new JObject(); serverCommunicationLinkCreateOrUpdateParametersValue["properties"] = propertiesValue; if (parameters.Properties.PartnerServer != null) { propertiesValue["partnerServer"] = parameters.Properties.PartnerServer; } serverCommunicationLinkCreateOrUpdateParametersValue["location"] = parameters.Location; if (parameters.Tags != null) { JObject tagsDictionary = new JObject(); foreach (KeyValuePair<string, string> pair in parameters.Tags) { string tagsKey = pair.Key; string tagsValue = pair.Value; tagsDictionary[tagsKey] = tagsValue; } serverCommunicationLinkCreateOrUpdateParametersValue["tags"] = tagsDictionary; } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServerCommunicationLinkCreateOrUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServerCommunicationLinkCreateOrUpdateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ErrorResponse errorInstance = new ErrorResponse(); result.Error = errorInstance; JToken codeValue = responseDoc["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = responseDoc["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken targetValue = responseDoc["target"]; if (targetValue != null && targetValue.Type != JTokenType.Null) { string targetInstance = ((string)targetValue); errorInstance.Target = targetInstance; } ServerCommunicationLink serverCommunicationLinkInstance = new ServerCommunicationLink(); result.ServerCommunicationLink = serverCommunicationLinkInstance; JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { ServerCommunicationLinkProperties propertiesInstance = new ServerCommunicationLinkProperties(); serverCommunicationLinkInstance.Properties = propertiesInstance; JToken stateValue = propertiesValue2["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { string stateInstance = ((string)stateValue); propertiesInstance.State = stateInstance; } JToken partnerServerValue = propertiesValue2["partnerServer"]; if (partnerServerValue != null && partnerServerValue.Type != JTokenType.Null) { string partnerServerInstance = ((string)partnerServerValue); propertiesInstance.PartnerServer = partnerServerInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); serverCommunicationLinkInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); serverCommunicationLinkInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); serverCommunicationLinkInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); serverCommunicationLinkInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey2 = ((string)property.Name); string tagsValue2 = ((string)property.Value); serverCommunicationLinkInstance.Tags.Add(tagsKey2, tagsValue2); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Location")) { result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.Created) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Creates a new or updates an existing Azure SQL Server communication /// link. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Database Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server. /// </param> /// <param name='communicationLinkName'> /// Required. The name of the Azure SQL Server communication link to be /// operated on (Updated or created). /// </param> /// <param name='parameters'> /// Required. The required parameters for creating or updating a Server /// communication link. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for long running Azure Sql server communication link /// operation. /// </returns> public async Task<ServerCommunicationLinkCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string serverName, string communicationLinkName, ServerCommunicationLinkCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { SqlManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("communicationLinkName", communicationLinkName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); ServerCommunicationLinkCreateOrUpdateResponse response = await client.CommunicationLinks.BeginCreateOrUpdateAsync(resourceGroupName, serverName, communicationLinkName, parameters, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); ServerCommunicationLinkCreateOrUpdateResponse result = await client.CommunicationLinks.GetServerCommunicationLinkOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 30; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.CommunicationLinks.GetServerCommunicationLinkOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 15; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// Deletes the Azure SQL server communication link with the given name. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server. /// </param> /// <param name='communicationLinkName'> /// Required. The name of the Azure SQL server communication link to be /// retrieved. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string serverName, string communicationLinkName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (communicationLinkName == null) { throw new ArgumentNullException("communicationLinkName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("communicationLinkName", communicationLinkName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/communicationLinks/"; url = url + Uri.EscapeDataString(communicationLinkName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Returns information about an Azure SQL Server communication links. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server. /// </param> /// <param name='communicationLinkName'> /// Required. The name of the Azure SQL server communication link to be /// retrieved. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a get server communication link request. /// </returns> public async Task<ServerCommunicationLinkGetResponse> GetAsync(string resourceGroupName, string serverName, string communicationLinkName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } if (communicationLinkName == null) { throw new ArgumentNullException("communicationLinkName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("communicationLinkName", communicationLinkName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/communicationLinks/"; url = url + Uri.EscapeDataString(communicationLinkName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServerCommunicationLinkGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServerCommunicationLinkGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ServerCommunicationLink serverCommunicationLinkInstance = new ServerCommunicationLink(); result.ServerCommunicationLink = serverCommunicationLinkInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ServerCommunicationLinkProperties propertiesInstance = new ServerCommunicationLinkProperties(); serverCommunicationLinkInstance.Properties = propertiesInstance; JToken stateValue = propertiesValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { string stateInstance = ((string)stateValue); propertiesInstance.State = stateInstance; } JToken partnerServerValue = propertiesValue["partnerServer"]; if (partnerServerValue != null && partnerServerValue.Type != JTokenType.Null) { string partnerServerInstance = ((string)partnerServerValue); propertiesInstance.PartnerServer = partnerServerInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); serverCommunicationLinkInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); serverCommunicationLinkInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); serverCommunicationLinkInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); serverCommunicationLinkInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); serverCommunicationLinkInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the status of an Azure Sql Server communication link create or /// update operation. /// </summary> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Response for long running Azure Sql server communication link /// operation. /// </returns> public async Task<ServerCommunicationLinkCreateOrUpdateResponse> GetServerCommunicationLinkOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken) { // Validate if (operationStatusLink == null) { throw new ArgumentNullException("operationStatusLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("operationStatusLink", operationStatusLink); TracingAdapter.Enter(invocationId, this, "GetServerCommunicationLinkOperationStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + operationStatusLink; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServerCommunicationLinkCreateOrUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServerCommunicationLinkCreateOrUpdateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ErrorResponse errorInstance = new ErrorResponse(); result.Error = errorInstance; JToken codeValue = responseDoc["code"]; if (codeValue != null && codeValue.Type != JTokenType.Null) { string codeInstance = ((string)codeValue); errorInstance.Code = codeInstance; } JToken messageValue = responseDoc["message"]; if (messageValue != null && messageValue.Type != JTokenType.Null) { string messageInstance = ((string)messageValue); errorInstance.Message = messageInstance; } JToken targetValue = responseDoc["target"]; if (targetValue != null && targetValue.Type != JTokenType.Null) { string targetInstance = ((string)targetValue); errorInstance.Target = targetInstance; } ServerCommunicationLink serverCommunicationLinkInstance = new ServerCommunicationLink(); result.ServerCommunicationLink = serverCommunicationLinkInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ServerCommunicationLinkProperties propertiesInstance = new ServerCommunicationLinkProperties(); serverCommunicationLinkInstance.Properties = propertiesInstance; JToken stateValue = propertiesValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { string stateInstance = ((string)stateValue); propertiesInstance.State = stateInstance; } JToken partnerServerValue = propertiesValue["partnerServer"]; if (partnerServerValue != null && partnerServerValue.Type != JTokenType.Null) { string partnerServerInstance = ((string)partnerServerValue); propertiesInstance.PartnerServer = partnerServerInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); serverCommunicationLinkInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); serverCommunicationLinkInstance.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); serverCommunicationLinkInstance.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); serverCommunicationLinkInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); serverCommunicationLinkInstance.Tags.Add(tagsKey, tagsValue); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.Created) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Returns information about Azure SQL Server communication links. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the Azure SQL /// Server belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Server. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Represents the response to a List Azure Sql Server communication /// link request. /// </returns> public async Task<ServerCommunicationLinkListResponse> ListAsync(string resourceGroupName, string serverName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serverName == null) { throw new ArgumentNullException("serverName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.Sql"; url = url + "/servers/"; url = url + Uri.EscapeDataString(serverName); url = url + "/communicationLinks"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-04-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServerCommunicationLinkListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServerCommunicationLinkListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { ServerCommunicationLink serverCommunicationLinkInstance = new ServerCommunicationLink(); result.ServerCommunicationLinks.Add(serverCommunicationLinkInstance); JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ServerCommunicationLinkProperties propertiesInstance = new ServerCommunicationLinkProperties(); serverCommunicationLinkInstance.Properties = propertiesInstance; JToken stateValue = propertiesValue["state"]; if (stateValue != null && stateValue.Type != JTokenType.Null) { string stateInstance = ((string)stateValue); propertiesInstance.State = stateInstance; } JToken partnerServerValue = propertiesValue["partnerServer"]; if (partnerServerValue != null && partnerServerValue.Type != JTokenType.Null) { string partnerServerInstance = ((string)partnerServerValue); propertiesInstance.PartnerServer = partnerServerInstance; } } JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); serverCommunicationLinkInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); serverCommunicationLinkInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); serverCommunicationLinkInstance.Type = typeInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); serverCommunicationLinkInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); serverCommunicationLinkInstance.Tags.Add(tagsKey, tagsValue); } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
/* * Copyright (c) 2008, Anthony James McCreath * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1 Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2 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. * 3 Neither the name of the 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 Anthony James McCreath "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 Anthony James McCreath 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.Text; using System.IO; using System.Security; using System.Runtime.InteropServices; using System.Diagnostics; namespace ClockWork.ScriptBuilder { /// <summary> /// A writer that adds the following to the normal TextWriter /// Indentation Control - tracks and adds indentation while writing /// Accepts objects and formats then based on a format provider (default is ScriptFormatProvider) /// Supports IScriptItem based classes and their self rendering ability /// /// </summary> public class ScriptWriter : IScriptWriter { #region Constructors /// <summary> /// Create a Script Writer that writes to a specific TextWriter /// </summary> /// <param name="writer"></param> public ScriptWriter(TextWriter writer) { if (writer == null) throw new Exception("ScriptWriter does not like null TextWriters"); Writer = writer; } /// <summary> /// Create a Script Writer that writes to a Stream /// </summary> /// <param name="stream"></param> public ScriptWriter(Stream stream) { if (stream == null) throw new Exception("ScriptWriter does not like null Streams"); Writer = new StreamWriter(stream); } /// <summary> /// Create a Script Writer that writes to a specific TextWriter using a particular format provider /// </summary> /// <param name="writer"></param> /// <param name="formatProvider"></param> public ScriptWriter(TextWriter writer, IFormatProvider formatProvider) { if (writer == null) throw new Exception("ScriptWriter does not like null TextWriters"); _FormatProvider = formatProvider; Writer = writer; } /// <summary> /// Create a Script Writer that writes to a Stream using a particular format provider /// </summary> /// <param name="stream"></param> /// <param name="formatProvider"></param> public ScriptWriter(Stream stream, IFormatProvider formatProvider) { if (stream == null) throw new Exception("ScriptWriter does not like null Streams"); _FormatProvider = formatProvider; Writer = new StreamWriter(stream); } /// <summary> /// Create a Script Writer that writes to a specific TextWriter based on another ScriptWriters settings /// </summary> /// <param name="writer"></param> /// <param name="scriptWriter"></param> public ScriptWriter(TextWriter writer, IScriptWriter scriptWriter) { if (writer == null) throw new Exception("ScriptWriter does not like null TextWriters"); Writer = writer; this.CopySettings(scriptWriter); } /// <summary> /// Create a Script Writer that writes to a Stream using a particular format provider /// </summary> /// <param name="stream"></param> /// <param name="scriptWriter"></param> public ScriptWriter(Stream stream, IScriptWriter scriptWriter) { if (stream == null) throw new Exception("ScriptWriter does not like null Streams"); Writer = new StreamWriter(stream); this.CopySettings(scriptWriter); } /// <summary> /// Copies settings from the provided writer so that this writer will write in the same way /// </summary> /// <param name="scriptWriter"></param> protected void CopySettings(IScriptWriter scriptWriter) { this._FormatProvider = scriptWriter.FormatProvider; if (scriptWriter is ScriptWriter) { ScriptWriter sw = (ScriptWriter)scriptWriter; this.IncludeIndentation = sw.IncludeIndentation; this.IndentText = sw.IndentText; this.NewLine = sw.NewLine; this.Compress = sw.Compress; } } #endregion #region Data /// <summary> /// The underlying writer /// </summary> private TextWriter Writer = null; #endregion #region Writers /// <summary> /// Write an object /// If its a IScriptItem then use its Render method /// First formats the object using the Format method /// </summary> /// <param name="o">object to write to the undelying TextWriter</param> public virtual void Write(object o) { if (Sb.HasRenderContent(o)) { if (o is IScriptItem) ((IScriptItem)o).Render(this); else { string formatted = Format(o); // Debug.Write(formatted); Writer.Write(formatted); } IsStartOfLine = false; // do before as could end up being reset while writing object } } /// <summary> /// Start a new line and indent to the required position /// Prefered way to move to the next line /// </summary> /// <param name="unlessAtStartOfLine">If true don't do anything if currently at the start of a line</param> public virtual void WriteNewLineAndIndent(bool unlessAtStartOfLine) { if (!unlessAtStartOfLine || !IsStartOfLine) { WriteNewLine(); WriteIndent(); IsStartOfLine = true; } } /// <summary> /// Start a new line and indent to the required position /// Prefered way to move to the next line /// Does nothing if currently at the start of a line /// </summary> public virtual void WriteNewLineAndIndent() { WriteNewLineAndIndent(true); } /// <summary> /// Starts a new line. /// Should generaly be folled by a WriteIndent() so following text is in the correct position /// WriteNewLineAndIndent() may be preferable. /// </summary> public virtual void WriteNewLine() { this.Write(this.NewLine); indentsOnOneLine = 0; } /// <summary> /// Adds the indent string /// Should always be after a newline to make sense /// WriteNewLineAndIndent() may be preferable. /// </summary> public virtual void WriteIndent() { this.Write(this.IndentString); } #endregion #region Formatting private IFormatProvider _FormatProvider = null; /// <summary> /// The format provider to use when formatting /// </summary> public IFormatProvider FormatProvider { get { if (_FormatProvider == null) _FormatProvider = new ScriptFormatProvider(); return _FormatProvider; } //set //{ // _FormatProvider = value; //} } /// <summary> /// Formats the object using the current FormatProvider /// </summary> /// <param name="o">object to format</param> /// <returns>string representation of the object</returns> public string Format(object o) { if (o == null) return String.Empty; return this.Format("{0}", o); } /// <summary> /// Formats the object using the current FormatProvider /// </summary> /// <param name="format">format string to use</param> /// <param name="o">object to format</param> /// <returns>string representation of the object</returns> public string Format(string format, object o) { return String.Format(this.FormatProvider, format, o); } private bool _Compress; /// <summary> /// writer requests that compressed content is provided when writing /// </summary> public bool Compress { get { return _Compress; } set { _Compress = value; } } #endregion #region Indentation /// <summary> /// Increase the indentation level by one /// BeginIndent() and EndIndent() should be used in pairs /// Preferably using a try finally pattern so as to avoid messed up formatting on errors /// </summary> public void BeginIndent() { BeginIndent(1); } /// <summary> /// Increase the indentation level by the supplied amount /// BeginIndent() and EndIndent() should be used in pairs /// Preferably using a try finally pattern so as to avoid messed up formatting on errors /// </summary> /// <param name="levels">How many indentations to add</param> public void BeginIndent(int levels) { CurrentIndentLevel += levels; indentsOnOneLine += levels; // Writer.Write("+" + levels + "=" + this.CurrentIndentLevel +"#"+indentsOnOneLine + "+"); } private int indentsOnOneLine = 0; // experimental idea to handle pre-un-indentingy type thing /// <summary> /// Decrease the indentation level by one /// BeginIndent() and EndIndent() should be used in pairs /// Preferably using a try finally pattern so as to avoid messed up formatting on errors /// </summary> public void EndIndent() { EndIndent(1); } /// <summary> /// Decrease the indentation level by the supplied amount /// BeginIndent() and EndIndent() should be used in pairs /// Preferably using a try finally pattern so as to avoid messed up formatting on errors /// </summary> /// <param name="levels">How many indentations to remove</param> public void EndIndent(int levels) { if (CurrentIndentLevel >= levels) { CurrentIndentLevel -= levels; indentsOnOneLine -= levels; } else CurrentIndentLevel = 0; // Writer.Write("-" + levels + "=" + this.CurrentIndentLevel+"#"+indentsOnOneLine + "-"); } private Int32 _CurrentIndentLevel; /// <summary> /// Tracks how many indentations we are currently at /// Increased by BeginIndent() /// Reduced by EndIndent() /// </summary> public Int32 CurrentIndentLevel { get { return _CurrentIndentLevel; } set { _CurrentIndentLevel = value; } } private string _IndentText = "\t"; /// <summary> /// The string to use for each indentation /// Repeated fore each IndentLevel /// Default: tab /// </summary> public string IndentText { get { return _IndentText; } set { _IndentText = value; } } private bool _IncludeIndentation = true; /// <summary> /// If we should Include indents when writing /// If false then IndentString is always empty /// </summary> public bool IncludeIndentation { get { return _IncludeIndentation; } set { _IncludeIndentation = value; } } /// <summary> /// The current string to use for indentation /// Empty if IncludeIndents is false /// otherwise IndentationLevel * IndentText /// </summary> public virtual string IndentString { get { if (IncludeIndentation) { if (Indents.ContainsKey(CurrentIndentLevel)) return Indents[CurrentIndentLevel]; string indent = String.Empty; for (int i = 0; i < CurrentIndentLevel; i++) indent += IndentText; Indents[CurrentIndentLevel] = indent; return indent; } else return String.Empty; } } private Dictionary<int, string> _Indents = null; /// <summary> /// Cache of indent levels already created /// </summary> protected Dictionary<int, string> Indents { get { if (_Indents==null) _Indents = new Dictionary<int, string>(); return _Indents; } } #endregion #region NewLines private bool _IsStartOfLine = true; /// <summary> /// Used to stop repeated WriteNewLineAndIndent /// </summary> public bool IsStartOfLine { get { return _IsStartOfLine; } set { _IsStartOfLine = value; } } private string _NewLine = Environment.NewLine; /// <summary> /// What to use for a new line /// </summary> public string NewLine { get { return _NewLine; } set { _NewLine = value; } } #endregion #region Stream Handing /// <summary> /// Closes the underlying writer/stream /// </summary> public void Close() { this.Writer.Close(); } /// <summary> /// Flush the underying writer/stream /// </summary> public void Flush() { this.Writer.Flush(); } #endregion #region ToString /// <summary> /// Adds current indent and position information /// </summary> /// <returns></returns> public override string ToString() { return base.ToString() + (this.IsStartOfLine ? " at start of line " : " writing line ") + this.CurrentIndentLevel; } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using WebApiSoup.Areas.HelpPage.Models; namespace WebApiSoup.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: TextReader ** ** <OWNER>Microsoft</OWNER> ** ** ** Purpose: Abstract base class for all Text-only Readers. ** Subclasses will include StreamReader & StringReader. ** ** ===========================================================*/ /* * https://github.com/Microsoft/referencesource/blob/master/mscorlib/system/io/textreader.cs */ using System; using System.Text; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Reflection; using System.Security.Permissions; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Threading.Tasks; namespace System.IO { // This abstract base class represents a reader that can read a sequential // stream of characters. This is not intended for reading bytes - // there are methods on the Stream class to read bytes. // A subclass must minimally implement the Peek() and Read() methods. // // This class is intended for character input, not bytes. // There are methods on the Stream class for reading bytes. public abstract class TextReader : IDisposable { public static readonly TextReader Null = new NullTextReader(); protected TextReader() { } // Closes this TextReader and releases any system resources associated with the // TextReader. Following a call to Close, any operations on the TextReader // may raise exceptions. // // This default method is empty, but descendant classes can override the // method to provide the appropriate functionality. public virtual void Close() { Dispose(true); } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { } // Returns the next available character without actually reading it from // the input stream. The current position of the TextReader is not changed by // this operation. The returned value is -1 if no further characters are // available. // // This default method simply returns -1. // [Pure] public virtual int Peek() { Contract.Ensures(Contract.Result<int>() >= -1); return -1; } // Reads the next character from the input stream. The returned value is // -1 if no further characters are available. // // This default method simply returns -1. // public virtual int Read() { Contract.Ensures(Contract.Result<int>() >= -1); return -1; } // Reads a block of characters. This method will read up to // count characters from this TextReader into the // buffer character array starting at position // index. Returns the actual number of characters read. // public virtual int Read([In, Out] char[] buffer, int index, int count) { if (buffer == null) throw new ArgumentNullException("buffer"); if (index < 0) throw new ArgumentOutOfRangeException("index"); if (count < 0) throw new ArgumentOutOfRangeException("count"); if (buffer.Length - index < count) throw new ArgumentException(); Contract.Ensures(Contract.Result<int>() >= 0); Contract.Ensures(Contract.Result<int>() <= Contract.OldValue(count)); Contract.EndContractBlock(); int n = 0; do { int ch = Read(); if (ch == -1) break; buffer[index + n++] = (char)ch; } while (n < count); return n; } public virtual Task<String> ReadToEndAsync() { return Task.FromResult(ReadToEnd()); } // Reads all characters from the current position to the end of the // TextReader, and returns them as one string. public virtual String ReadToEnd() { Contract.Ensures(Contract.Result<String>() != null); char[] chars = new char[4096]; int len; StringBuilder sb = new StringBuilder(4096); while ((len = Read(chars, 0, chars.Length)) != 0) { sb.Append(new string(chars, 0, len)); } return sb.ToString(); } // Blocking version of read. Returns only when count // characters have been read or the end of the file was reached. // public virtual int ReadBlock([In, Out] char[] buffer, int index, int count) { Contract.Ensures(Contract.Result<int>() >= 0); Contract.Ensures(Contract.Result<int>() <= count); int i, n = 0; do { n += (i = Read(buffer, index + n, count - n)); } while (i > 0 && n < count); return n; } // Reads a line. A line is defined as a sequence of characters followed by // a carriage return ('\r'), a line feed ('\n'), or a carriage return // immediately followed by a line feed. The resulting string does not // contain the terminating carriage return and/or line feed. The returned // value is null if the end of the input stream has been reached. // public virtual String ReadLine() { StringBuilder sb = new StringBuilder(); while (true) { int ch = Read(); if (ch == -1) break; if (ch == '\r' || ch == '\n') { if (ch == '\r' && Peek() == '\n') Read(); return sb.ToString(); } sb.Append((char)ch); } if (sb.Length > 0) return sb.ToString(); return null; } public static TextReader Synchronized(TextReader reader) { if (reader == null) throw new ArgumentNullException("reader"); Contract.Ensures(Contract.Result<TextReader>() != null); Contract.EndContractBlock(); return reader; } [Serializable] private sealed class NullTextReader : TextReader { public NullTextReader() { } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. public override int Read(char[] buffer, int index, int count) { return 0; } public override String ReadLine() { return null; } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure.Management.Storage; using Microsoft.Azure.Management.Storage.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.Storage { /// <summary> /// Operations for listing usage. /// </summary> internal partial class UsageOperations : IServiceOperations<StorageManagementClient>, IUsageOperations { /// <summary> /// Initializes a new instance of the UsageOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal UsageOperations(StorageManagementClient client) { this._client = client; } private StorageManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.Storage.StorageManagementClient. /// </summary> public StorageManagementClient Client { get { return this._client; } } /// <summary> /// Gets the current usage count and the limit for the resources under /// the subscription. /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Usages operation response. /// </returns> public async Task<UsageListResponse> ListAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/providers/Microsoft.Storage/usages"; List<string> queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); } if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result UsageListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new UsageListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Usage usageInstance = new Usage(); result.Usages.Add(usageInstance); JToken unitValue = valueValue["unit"]; if (unitValue != null && unitValue.Type != JTokenType.Null) { UsageUnit unitInstance = ((UsageUnit)Enum.Parse(typeof(UsageUnit), ((string)unitValue), true)); usageInstance.Unit = unitInstance; } JToken currentValueValue = valueValue["currentValue"]; if (currentValueValue != null && currentValueValue.Type != JTokenType.Null) { int currentValueInstance = ((int)currentValueValue); usageInstance.CurrentValue = currentValueInstance; } JToken limitValue = valueValue["limit"]; if (limitValue != null && limitValue.Type != JTokenType.Null) { int limitInstance = ((int)limitValue); usageInstance.Limit = limitInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { UsageName nameInstance = new UsageName(); usageInstance.Name = nameInstance; JToken valueValue2 = nameValue["value"]; if (valueValue2 != null && valueValue2.Type != JTokenType.Null) { string valueInstance = ((string)valueValue2); nameInstance.Value = valueInstance; } JToken localizedValueValue = nameValue["localizedValue"]; if (localizedValueValue != null && localizedValueValue.Type != JTokenType.Null) { string localizedValueInstance = ((string)localizedValueValue); nameInstance.LocalizedValue = localizedValueInstance; } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// 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; namespace System.Globalization { /* ** Calendar support range: ** Calendar Minimum Maximum ** ========== ========== ========== ** Gregorian 1912/02/18 2051/02/10 ** TaiwanLunisolar 1912/01/01 2050/13/29 */ public class TaiwanLunisolarCalendar : EastAsianLunisolarCalendar { // Since // Gregorian Year = Era Year + yearOffset // When Gregorian Year 1912 is year 1, so that // 1912 = 1 + yearOffset // So yearOffset = 1911 //m_EraInfo[0] = new EraInfo(1, new DateTime(1912, 1, 1).Ticks, 1911, 1, GregorianCalendar.MaxYear - 1911); // Initialize our era info. internal static EraInfo[] taiwanLunisolarEraInfo = new EraInfo[] { new EraInfo( 1, 1912, 1, 1, 1911, 1, GregorianCalendar.MaxYear - 1911) // era #, start year/month/day, yearOffset, minEraYear }; internal GregorianCalendarHelper helper; internal const int MIN_LUNISOLAR_YEAR = 1912; internal const int MAX_LUNISOLAR_YEAR = 2050; internal const int MIN_GREGORIAN_YEAR = 1912; internal const int MIN_GREGORIAN_MONTH = 2; internal const int MIN_GREGORIAN_DAY = 18; internal const int MAX_GREGORIAN_YEAR = 2051; internal const int MAX_GREGORIAN_MONTH = 2; internal const int MAX_GREGORIAN_DAY = 10; internal static DateTime minDate = new DateTime(MIN_GREGORIAN_YEAR, MIN_GREGORIAN_MONTH, MIN_GREGORIAN_DAY); internal static DateTime maxDate = new DateTime((new DateTime(MAX_GREGORIAN_YEAR, MAX_GREGORIAN_MONTH, MAX_GREGORIAN_DAY, 23, 59, 59, 999)).Ticks + 9999); public override DateTime MinSupportedDateTime { get { return (minDate); } } public override DateTime MaxSupportedDateTime { get { return (maxDate); } } protected override int DaysInYearBeforeMinSupportedYear { get { // 1911 from ChineseLunisolarCalendar return 384; } } private static readonly int[,] s_yinfo = { /*Y LM Lmon Lday DaysPerMonth D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 #Days 1912 */ { 0 , 2 , 18 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 1913 */{ 0 , 2 , 6 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 1914 */{ 5 , 1 , 26 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384 1915 */{ 0 , 2 , 14 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354 1916 */{ 0 , 2 , 3 , 54944 },/* 30 30 29 30 29 30 30 29 30 29 30 29 0 355 1917 */{ 2 , 1 , 23 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384 1918 */{ 0 , 2 , 11 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355 1919 */{ 7 , 2 , 1 , 18872 },/* 29 30 29 29 30 29 29 30 30 29 30 30 30 384 1920 */{ 0 , 2 , 20 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 1921 */{ 0 , 2 , 8 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 1922 */{ 5 , 1 , 28 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384 1923 */{ 0 , 2 , 16 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354 1924 */{ 0 , 2 , 5 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354 1925 */{ 4 , 1 , 24 , 44456 },/* 30 29 30 29 30 30 29 30 30 29 30 29 30 385 1926 */{ 0 , 2 , 13 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354 1927 */{ 0 , 2 , 2 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 0 355 1928 */{ 2 , 1 , 23 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384 1929 */{ 0 , 2 , 10 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 1930 */{ 6 , 1 , 30 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 29 383 1931 */{ 0 , 2 , 17 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 1932 */{ 0 , 2 , 6 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355 1933 */{ 5 , 1 , 26 , 27976 },/* 29 30 30 29 30 30 29 30 29 30 29 29 30 384 1934 */{ 0 , 2 , 14 , 23248 },/* 29 30 29 30 30 29 30 29 30 30 29 30 0 355 1935 */{ 0 , 2 , 4 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354 1936 */{ 3 , 1 , 24 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 29 384 1937 */{ 0 , 2 , 11 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354 1938 */{ 7 , 1 , 31 , 51560 },/* 30 30 29 29 30 29 29 30 29 30 30 29 30 384 1939 */{ 0 , 2 , 19 , 51536 },/* 30 30 29 29 30 29 29 30 29 30 29 30 0 354 1940 */{ 0 , 2 , 8 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 1941 */{ 6 , 1 , 27 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 29 384 1942 */{ 0 , 2 , 15 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355 1943 */{ 0 , 2 , 5 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 1944 */{ 4 , 1 , 25 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385 1945 */{ 0 , 2 , 13 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354 1946 */{ 0 , 2 , 2 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354 1947 */{ 2 , 1 , 22 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384 1948 */{ 0 , 2 , 10 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354 1949 */{ 7 , 1 , 29 , 46248 },/* 30 29 30 30 29 30 29 29 30 29 30 29 30 384 1950 */{ 0 , 2 , 17 , 27808 },/* 29 30 30 29 30 30 29 29 30 29 30 29 0 354 1951 */{ 0 , 2 , 6 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355 1952 */{ 5 , 1 , 27 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 1953 */{ 0 , 2 , 14 , 19872 },/* 29 30 29 29 30 30 29 30 30 29 30 29 0 354 1954 */{ 0 , 2 , 3 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355 1955 */{ 3 , 1 , 24 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384 1956 */{ 0 , 2 , 12 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354 1957 */{ 8 , 1 , 31 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 29 383 1958 */{ 0 , 2 , 18 , 59728 },/* 30 30 30 29 30 29 29 30 29 30 29 30 0 355 1959 */{ 0 , 2 , 8 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354 1960 */{ 6 , 1 , 28 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384 1961 */{ 0 , 2 , 15 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355 1962 */{ 0 , 2 , 5 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354 1963 */{ 4 , 1 , 25 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 1964 */{ 0 , 2 , 13 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355 1965 */{ 0 , 2 , 2 , 21088 },/* 29 30 29 30 29 29 30 29 29 30 30 29 0 353 1966 */{ 3 , 1 , 21 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384 1967 */{ 0 , 2 , 9 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 0 355 1968 */{ 7 , 1 , 30 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384 1969 */{ 0 , 2 , 17 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 1970 */{ 0 , 2 , 6 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355 1971 */{ 5 , 1 , 27 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 1972 */{ 0 , 2 , 15 , 19152 },/* 29 30 29 29 30 29 30 29 30 30 29 30 0 354 1973 */{ 0 , 2 , 3 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 1974 */{ 4 , 1 , 23 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384 1975 */{ 0 , 2 , 11 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 1976 */{ 8 , 1 , 31 , 54568 },/* 30 30 29 30 29 30 29 30 29 29 30 29 30 384 1977 */{ 0 , 2 , 18 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354 1978 */{ 0 , 2 , 7 , 46752 },/* 30 29 30 30 29 30 30 29 30 29 30 29 0 355 1979 */{ 6 , 1 , 28 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384 1980 */{ 0 , 2 , 16 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355 1981 */{ 0 , 2 , 5 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354 1982 */{ 4 , 1 , 25 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384 1983 */{ 0 , 2 , 13 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 1984 */{ 10 , 2 , 2 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384 1985 */{ 0 , 2 , 20 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354 1986 */{ 0 , 2 , 9 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354 1987 */{ 6 , 1 , 29 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 29 384 1988 */{ 0 , 2 , 17 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355 1989 */{ 0 , 2 , 6 , 38256 },/* 30 29 29 30 29 30 29 30 29 30 30 30 0 355 1990 */{ 5 , 1 , 27 , 18808 },/* 29 30 29 29 30 29 29 30 29 30 30 30 30 384 1991 */{ 0 , 2 , 15 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 1992 */{ 0 , 2 , 4 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354 1993 */{ 3 , 1 , 23 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383 1994 */{ 0 , 2 , 10 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355 1995 */{ 8 , 1 , 31 , 27432 },/* 29 30 30 29 30 29 30 30 29 29 30 29 30 384 1996 */{ 0 , 2 , 19 , 23232 },/* 29 30 29 30 30 29 30 29 30 30 29 29 0 354 1997 */{ 0 , 2 , 7 , 43872 },/* 30 29 30 29 30 29 30 30 29 30 30 29 0 355 1998 */{ 5 , 1 , 28 , 37736 },/* 30 29 29 30 29 29 30 30 29 30 30 29 30 384 1999 */{ 0 , 2 , 16 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354 2000 */{ 0 , 2 , 5 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354 2001 */{ 4 , 1 , 24 , 54440 },/* 30 30 29 30 29 30 29 29 30 29 30 29 30 384 2002 */{ 0 , 2 , 12 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 2003 */{ 0 , 2 , 1 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355 2004 */{ 2 , 1 , 22 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384 2005 */{ 0 , 2 , 9 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 2006 */{ 7 , 1 , 29 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385 2007 */{ 0 , 2 , 18 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354 2008 */{ 0 , 2 , 7 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354 2009 */{ 5 , 1 , 26 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384 2010 */{ 0 , 2 , 14 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354 2011 */{ 0 , 2 , 3 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354 2012 */{ 4 , 1 , 23 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 29 384 2013 */{ 0 , 2 , 10 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355 2014 */{ 9 , 1 , 31 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 2015 */{ 0 , 2 , 19 , 19360 },/* 29 30 29 29 30 29 30 30 30 29 30 29 0 354 2016 */{ 0 , 2 , 8 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355 2017 */{ 6 , 1 , 28 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384 2018 */{ 0 , 2 , 16 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354 2019 */{ 0 , 2 , 5 , 43312 },/* 30 29 30 29 30 29 29 30 29 29 30 30 0 354 2020 */{ 4 , 1 , 25 , 29864 },/* 29 30 30 30 29 30 29 29 30 29 30 29 30 384 2021 */{ 0 , 2 , 12 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354 2022 */{ 0 , 2 , 1 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355 2023 */{ 2 , 1 , 22 , 19880 },/* 29 30 29 29 30 30 29 30 30 29 30 29 30 384 2024 */{ 0 , 2 , 10 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354 2025 */{ 6 , 1 , 29 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 2026 */{ 0 , 2 , 17 , 42208 },/* 30 29 30 29 29 30 29 29 30 30 30 29 0 354 2027 */{ 0 , 2 , 6 , 53856 },/* 30 30 29 30 29 29 30 29 29 30 30 29 0 354 2028 */{ 5 , 1 , 26 , 59696 },/* 30 30 30 29 30 29 29 30 29 29 30 30 29 384 2029 */{ 0 , 2 , 13 , 54576 },/* 30 30 29 30 29 30 29 30 29 29 30 30 0 355 2030 */{ 0 , 2 , 3 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354 2031 */{ 3 , 1 , 23 , 27472 },/* 29 30 30 29 30 29 30 30 29 30 29 30 29 384 2032 */{ 0 , 2 , 11 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355 2033 */{ 11 , 1 , 31 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 2034 */{ 0 , 2 , 19 , 19152 },/* 29 30 29 29 30 29 30 29 30 30 29 30 0 354 2035 */{ 0 , 2 , 8 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 2036 */{ 6 , 1 , 28 , 53848 },/* 30 30 29 30 29 29 30 29 29 30 29 30 30 384 2037 */{ 0 , 2 , 15 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 2038 */{ 0 , 2 , 4 , 54560 },/* 30 30 29 30 29 30 29 30 29 29 30 29 0 354 2039 */{ 5 , 1 , 24 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 29 384 2040 */{ 0 , 2 , 12 , 46496 },/* 30 29 30 30 29 30 29 30 30 29 30 29 0 355 2041 */{ 0 , 2 , 1 , 22224 },/* 29 30 29 30 29 30 30 29 30 30 29 30 0 355 2042 */{ 2 , 1 , 22 , 19160 },/* 29 30 29 29 30 29 30 29 30 30 29 30 30 384 2043 */{ 0 , 2 , 10 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354 2044 */{ 7 , 1 , 30 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384 2045 */{ 0 , 2 , 17 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 2046 */{ 0 , 2 , 6 , 43600 },/* 30 29 30 29 30 29 30 29 29 30 29 30 0 354 2047 */{ 5 , 1 , 26 , 46376 },/* 30 29 30 30 29 30 29 30 29 29 30 29 30 384 2048 */{ 0 , 2 , 14 , 27936 },/* 29 30 30 29 30 30 29 30 29 29 30 29 0 354 2049 */{ 0 , 2 , 2 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 0 355 2050 */{ 3 , 1 , 23 , 21936 },/* 29 30 29 30 29 30 29 30 30 29 30 30 29 384 */}; internal override int MinCalendarYear { get { return (MIN_LUNISOLAR_YEAR); } } internal override int MaxCalendarYear { get { return (MAX_LUNISOLAR_YEAR); } } internal override DateTime MinDate { get { return (minDate); } } internal override DateTime MaxDate { get { return (maxDate); } } internal override EraInfo[] CalEraInfo { get { return (taiwanLunisolarEraInfo); } } internal override int GetYearInfo(int lunarYear, int index) { if ((lunarYear < MIN_LUNISOLAR_YEAR) || (lunarYear > MAX_LUNISOLAR_YEAR)) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR)); } return s_yinfo[lunarYear - MIN_LUNISOLAR_YEAR, index]; } internal override int GetYear(int year, DateTime time) { return helper.GetYear(year, time); } internal override int GetGregorianYear(int year, int era) { return helper.GetGregorianYear(year, era); } public TaiwanLunisolarCalendar() { helper = new GregorianCalendarHelper(this, taiwanLunisolarEraInfo); } public override int GetEra(DateTime time) { return (helper.GetEra(time)); } internal override CalendarId BaseCalendarID { get { return (CalendarId.TAIWAN); } } internal override CalendarId ID { get { return (CalendarId.TAIWANLUNISOLAR); } } public override int[] Eras { get { return (helper.Eras); } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// Provides base functionality to handle textures with multiple image frames. /// </summary> [ExecuteInEditMode] public class OTContainer : MonoBehaviour { public string _name = ""; bool registered = false; public Vector2 _sheetSize = Vector2.zero; /// <summary> /// Spritesheet's texture /// </summary> public Texture texture; public OTContainerSizeTexture[] sizeTextures; protected bool dirtyContainer = true; protected string _name_ = ""; Vector2 _sheetSize_ = Vector2.zero; protected Texture _texture = null; /// <summary> /// Original sheet size /// </summary> /// <remarks> /// This setting is optional and only used in combination with frameSize when /// the frames do not exactly fill up the texture horizontally and/or vertically. /// <br></br><br></br> /// Sometimes a sheet has some left over space to the right or bottom of the /// texture that was used. By setting the original sheetSize and the frameSize, /// the empty left-over space can be calculated and taken into account when /// setting the texture scaling and frame texture offsetting. /// </remarks> public Vector2 sheetSize { get { return _sheetSize; } set { _sheetSize = value; dirtyContainer = true; } } /// <summary> /// Stores texture data of a specific container frame. /// </summary> public struct Frame { /// <summary> /// This frame's name /// </summary> public string name; /// <summary> /// This frame's image scale modifier /// </summary> public Vector2 size; /// <summary> /// This frame's original image size /// </summary> public Vector2 imageSize; /// <summary> /// This frame's world position offset modifier /// </summary> public Vector2 offset; /// <summary> /// This frame's world rotation modifier /// </summary> public float rotation; /// <summary> /// Texture UV coordinates (x/y). /// </summary> public Vector2[] uv; /// <summary> /// Mesh vertices used when OffsetSizing = false (Atlas) /// </summary> public Vector3[] vertices; /// <summary> /// The index of the frame /// </summary> public int index; } Frame[] frames = { }; /// <summary> /// Name of the container /// </summary> new public string name { get { return _name; } set { string old = _name; _name = value; gameObject.name = _name; if (OT.isValid) { _name_ = _name; OT.RegisterContainerLookup(this, old); } } } /// <summary> /// Container ready indicator. /// </summary> /// <remarks> /// Container frame data or container texture can only be accessed when a container is ready. /// Be sure to check this when retrieving data programmaticly. /// </remarks> public bool isReady { get { return frames.Length > 0; } } /// <summary> /// Number of frames in this container. /// </summary> public int frameCount { get { return frames.Length; } } public Texture GetTexture() { return texture; } Texture _defaultTexture; void CheckSizeFactor() { if (OT.sizeFactor!=1) { for (int i=0; i<sizeTextures.Length; i++) { if (sizeTextures[i].sizeFactor == OT.sizeFactor) { if (_defaultTexture==null) _defaultTexture = texture; texture = sizeTextures[i].texture; } } } else { if (_defaultTexture!=null) texture = _defaultTexture; } } /// <summary> /// Overridable virtal method to provide the container's frames /// </summary> /// <returns>Container's array of frames</returns> protected virtual Frame[] GetFrames() { return new Frame[] { }; } /// <summary> /// Return the frame number by its name or -1 if it doesn't exist. /// </summary> public virtual int GetFrameIndex(string inName) { Frame frame = FrameByName(inName); if (frame.name==inName) return frame.index; else return -1; } protected void Awake() { #if UNITY_EDITOR if (!Application.isPlaying) UnityEditor.PrefabUtility.RecordPrefabInstancePropertyModifications(this); #endif } // Use this for initialization protected void Start() { // initialize attributes // initialize attributes _name_ = name; _sheetSize_ = sheetSize; _texture = texture; if (name == "") { name = "Container (id=" + this.gameObject.GetInstanceID() + ")"; #if UNITY_EDITOR if (!Application.isPlaying) UnityEditor.PrefabUtility.RecordPrefabInstancePropertyModifications(this); #endif } } /// <summary> /// Retrieve a specific container frame. /// </summary> /// <remarks> /// The container frame contains data about each frame's texture offset and UV coordinates. The texture offset and scale /// is used when this frame is mapped onto a single sprite. The UV coordinates are used when this images has to be mapped onto /// a multi sprite mesh ( a SpriteBatch for example ). /// <br></br><br></br> /// When the index is out of bounce, an IndexOutOfRangeException will be raised. /// </remarks> /// <param name="index">Index of container frame to retrieve. (starting at 0)</param> /// <returns>Retrieved container frame.</returns> public Frame GetFrame(int index) { if (frames.Length > index) return frames[index]; else { throw new System.IndexOutOfRangeException("Frame index out of bounds ["+index+"]"); } } void RegisterContainer() { if (OT.ContainerByName(name) == null) { OT.RegisterContainer(this); gameObject.name = name; registered = true; } if (_name_ != name) { OT.RegisterContainerLookup(this, _name_); _name_ = name; gameObject.name = name; } if (name != gameObject.name) { name = gameObject.name; OT.RegisterContainerLookup(this, _name_); _name_ = name; #if UNITY_EDITOR if (!Application.isPlaying) UnityEditor.PrefabUtility.RecordPrefabInstancePropertyModifications(this); #endif } } Dictionary<string, Frame> frameByName = new Dictionary<string, Frame>(); public Frame FrameByName(string frameName) { if (frameByName.ContainsKey(frameName)) return frameByName[frameName]; if (frameByName.ContainsKey(frameName+".png")) return frameByName[frameName+".png"]; if (frameByName.ContainsKey(frameName+".gif")) return frameByName[frameName+".gif"]; if (frameByName.ContainsKey(frameName+".jpg")) return frameByName[frameName+".jpg"]; return new Frame(); } // Update is called once per frame protected void Update() { if (!OT.isValid) return; if (!registered || !Application.isPlaying) RegisterContainer(); if (frames.Length == 0 && !dirtyContainer) dirtyContainer = true; if (!Vector2.Equals(_sheetSize, _sheetSize_)) { _sheetSize_ = _sheetSize; dirtyContainer = true; } if (_texture != texture) { _texture = texture; dirtyContainer = true; } if (dirtyContainer || !isReady) { frames = GetFrames(); frameByName.Clear(); for (int f=0; f<frames.Length; f++) { frames[f].index = f; if (!frameByName.ContainsKey(frames[f].name)) frameByName.Add(frames[f].name,frames[f]); } // remove all cached materials for this container OT.ClearMaterials("spc:"+name.ToLower()+":"); List<OTSprite> sprites = OT.ContainerSprites(this); for (int s=0; s<sprites.Count; s++) sprites[s].GetMat(); if (Application.isPlaying) CheckSizeFactor(); dirtyContainer = false; } } void OnDestroy() { if (OT.isValid) OT.RemoveContainer(this); } public virtual void Reset() { dirtyContainer = true; Update(); } } [System.Serializable] public class OTContainerSizeTexture { public float sizeFactor; public Texture texture; }
/* Usage: just add/link this file to your NUnit test project. * Class and method attributes are: * * [TestClass] * public class MyFixture * { * [TestMethod] * public void ShouldWork() * { * // arrange * // act * // assert * result.ShouldNotBeNull(); * } * } * * "Dotting" on the results you want to verify, * you'll get the ShouldXXX assertions to use. * Don't add a "using NUnit.Framework;" import * at the top of the file. It's not needed and * will limit portability of your tests in the * future. * * To port the tests to a different test framework, simply replace * the corresponding CoreTDD file. * * Report issues and suggestions to http://code.google.com/p/coretdd. * * Daniel Cazzulino - http://clariusconsulting.net/kzu */ #region New BSD License //Copyright (c) 2007, CoreTDD Team //http://code.google.com/p/coretdd/ //All rights reserved. //Redistribution and use in source and binary forms, //with or without modification, are permitted provided //that the following conditions are met: // * Redistributions of source code must retain the // above copyright notice, this list of conditions and // the following disclaimer. // * Redistributions in binary form must reproduce // the above copyright notice, this list of conditions // and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of the CoreTDD Team 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. //[This is the BSD license, see // http://www.opensource.org/licenses/bsd-license.php] #endregion using System; using System.Linq; using System.Collections; using NUnit.Framework; /// <summary> /// Marks a class that contains tests. /// </summary> [AttributeUsage(AttributeTargets.Class)] public class TestClassAttribute : TestFixtureAttribute { } /// <summary> /// Marks a test method. /// </summary> public class TestMethodAttribute : TestAttribute { } public static class TestExtensions { /// <summary> /// Asserts that the given object satisfies the condition. /// </summary> /// <typeparam name="T">Type of the object, omitted as it can be inferred from the value.</typeparam> /// <param name="object">The object to test with the condition.</param> /// <param name="condition">The condition expresion.</param> /// <example> /// <code> /// Order order = repository.CreateOrder(...); /// /// order.ShouldSatisfy(o =&gt; o.Created >= now); /// </code> /// </example> public static T ShouldSatisfy<T>(this T @object, Predicate<T> condition) { Assert.IsTrue(condition(@object)); return @object; } /// <summary> /// Asserts that the given object satisfies the condition. /// </summary> /// <typeparam name="T">Type of the object, omitted as it can be inferred from the value.</typeparam> /// <param name="object">The object to test with the condition.</param> /// <param name="condition">The condition expresion.</param> /// <param name="failMessage">Message to show if the assertion fails.</param> /// <example> /// <code> /// Order order = repository.CreateOrder(...); /// /// order.ShouldSatisfy(o =&gt; o.Created >= now, "Creation date should be equal or greater than now!"); /// </code> /// </example> public static T ShouldSatisfy<T>(this T @object, Predicate<T> condition, string failMessage) { Assert.IsTrue(condition(@object), failMessage); return @object; } /// <summary> /// Asserts that the given condition is false. /// </summary> /// <example> /// <code> /// bool result = service.Execute(); /// result.ShouldBeFalse(); /// </code> /// </example> public static void ShouldBeFalse(this bool condition) { Assert.IsFalse(condition); } /// <summary> /// Asserts that the given condition is true. /// </summary> /// <example> /// <code> /// bool result = service.Execute(); /// result.ShouldBeTrue(); /// </code> /// </example> public static void ShouldBeTrue(this bool condition) { Assert.IsTrue(condition); } /// <summary> /// Asserts that the actual object equals the given value. /// </summary> /// <example> /// <code> /// var order = repository.CreateOrder(...); /// /// order.GrandTotal.ShouldEqual(expectedSum); /// </code> /// </example> public static T ShouldEqual<T>(this T actual, object expected) { Assert.AreEqual(expected, actual); return actual; } /// <summary> /// Asserts that the actual object does not equal the given value. /// </summary> /// <example> /// <code> /// var order = repository.CreateOrder(...); /// /// order.GrandTotal.ShouldNotEqual(sumItemsWithoutStock); /// </code> /// </example> public static T ShouldNotEqual<T>(this T actual, object expected) { Assert.AreNotEqual(expected, actual); return actual; } /// <summary> /// Asserts that the value is null. /// </summary> /// <example> /// <code> /// var order = repository.Find(nonExistentId); /// /// order.ShouldBeNull(); /// </code> /// </example> public static void ShouldBeNull(this object @object) { Assert.IsNull(@object); } /// <summary> /// Asserts that the value is not null. /// </summary> /// <example> /// <code> /// var order = repository.Find(existentId); /// /// order.ShouldNotBeNull(); /// </code> /// </example> public static T ShouldNotBeNull<T>(this T @object) { Assert.IsNotNull(@object); return @object; } /// <summary> /// Asserts that the value is the same as the given one. /// </summary> /// <example> /// <code> /// var order = repository.CreateOrder(...); /// /// order.Customer.ShouldBeSameAs(customer); /// </code> /// </example> public static T ShouldBeSameAs<T>(this T actual, object expected) { Assert.AreSame(expected, actual); return actual; } /// <summary> /// Asserts that the value is not the same as the given one. /// </summary> /// <example> /// <code> /// var order = repository.CreateOrder(...); /// /// order.Customer.ShouldNotBeSameAs(customer); /// </code> /// </example> public static T ShouldNotBeSameAs<T>(this T actual, object expected) { Assert.AreNotSame(expected, actual); return actual; } /// <summary> /// Asserts that the value is of the given type, inherits or implements it. /// </summary> /// <example> /// <code> /// IPrincipal principal = factory.CreateGroupPrincipal("foo"); /// /// principal.ShouldBeOfType(typeof(GroupPrincipal)); /// </code> /// </example> public static object ShouldBeOfType(this object actual, Type expected) { Assert.IsAssignableFrom(expected, actual); return actual; } /// <summary> /// Asserts that the value is of the given type, inherits or implements it. /// </summary> /// <example> /// <code> /// IPrincipal principal = factory.CreateGroupPrincipal("foo"); /// /// principal.ShouldBeOfType&lt;GroupPrincipal&gt;(); /// </code> /// </example> public static TExpected ShouldBeOfType<TExpected>(this object actual) { Assert.IsAssignableFrom(typeof(TExpected), actual); return (TExpected)actual; } /// <summary> /// Asserts that the value is of the given type (not a descendant). /// </summary> /// <example> /// <code> /// IPrincipal principal = factory.CreateGroupPrincipal("foo"); /// /// principal.ShouldBeOfExactType&lt;GroupPrincipal&gt;(); /// </code> /// </example> public static object ShouldBeOfExactType(this object actual, Type expected) { ShouldNotBeNull(actual); Assert.AreEqual(expected, actual.GetType()); return actual; } /// <summary> /// Asserts that the value is of the given type (not a descendant). /// </summary> /// <example> /// <code> /// IPrincipal principal = factory.CreateGroupPrincipal("foo"); /// /// principal.ShouldBeOfExactType&lt;GroupPrincipal&gt;(); /// </code> /// </example> public static TExpected ShouldBeOfExactType<TExpected>(this object actual) { return (TExpected)ShouldBeOfExactType(actual, typeof(TExpected)); } /// <summary> /// Asserts that the value is not of the given type, or inherits or implements it. /// </summary> /// <example> /// <code> /// IPrincipal principal = factory.CreatePrincipal("foo"); /// /// principal.ShouldNotBeOfType(typeof(GroupPrincipal)); /// </code> /// </example> public static object ShouldNotBeOfType(this object actual, Type expected) { Assert.IsNotAssignableFrom(expected, actual); return actual; } /// <summary> /// Asserts that the value is not of the given type, or inherits or implements it. /// </summary> /// <example> /// <code> /// IPrincipal principal = factory.CreatePrincipal("foo"); /// /// principal.ShouldNotBeOfType&lt;GroupPrincipal&gt;(); /// </code> /// </example> public static object ShouldNotBeOfType<TExpected>(this object actual) { Assert.IsNotAssignableFrom(typeof(TExpected), actual); return actual; } /// <summary> /// Asserts that the given collection contains the value. /// </summary> /// <example> /// <code> /// var order = repository.CreateOrder(...); /// /// repository.GetOrders().ShouldContain(order); /// </code> /// </example> public static IEnumerable ShouldContain(this IEnumerable collection, object expected) { Assert.Contains(expected, collection.Cast<object>().ToList()); return collection; } /// <summary> /// Asserts that the given collection does not contains the value. /// </summary> /// <example> /// <code> /// var order = repository.CreateOrder(.../* IsPending = true */); /// /// repository.GetOrders().ShouldNotContain(order); /// </code> /// </example> public static IEnumerable ShouldNotContain(this IEnumerable collection, object expected) { Assert.IsFalse(collection.Cast<object>().Contains(expected), "Collection contains the value."); return collection; } /// <summary> /// Asserts that the given string is empty. /// </summary> /// <example> /// <code> /// string id = repository.FindId(noMatchCriteria); /// /// id.ShouldBeEmpty(); /// </code> /// </example> public static void ShouldBeEmpty(this string @string) { Assert.IsEmpty(@string); } /// <summary> /// Asserts that the given string is not empty. /// </summary> /// <example> /// <code> /// string id = repository.FindId(matchCriteria); /// /// id.ShouldNotBeEmpty(); /// </code> /// </example> public static string ShouldNotBeEmpty(this string @string) { Assert.IsNotEmpty(@string); return @string; } /// <summary> /// Asserts that the given collection is empty. /// </summary> /// <example> /// <code> /// repository.Clear(); /// /// repository.GetOrders().ShouldBeEmpty(); /// </code> /// </example> public static void ShouldBeEmpty(this IEnumerable collection) { Assert.IsEmpty(collection.Cast<object>().ToList()); } /// <summary> /// Asserts that the given collection is not empty. /// </summary> /// <example> /// <code> /// var order = repository.CreateOrder(...); /// /// repository.GetOrders().ShouldNotBeEmpty(); /// </code> /// </example> public static IEnumerable ShouldNotBeEmpty(this IEnumerable collection) { Assert.IsNotEmpty(collection.Cast<object>().ToList()); return collection; } /// <summary> /// Asserts that the value contains the expected substring. /// </summary> /// <example> /// <code> /// string message = messaging.GetWelcomeMessage(); /// /// message.ShouldContain("Joe"); /// </code> /// </example> public static void ShouldContain(this string actual, string expected) { Assert.IsTrue(actual.Contains(expected), String.Format("\"{0}\" does not contain \"{1}\".", actual, expected)); } /// <summary> /// Asserts that the value does not contains the expected substring. /// </summary> /// <example> /// <code> /// string message = messaging.GetWelcomeMessage(); /// /// message.ShouldNotContain("Mary"); /// </code> /// </example> public static void ShouldNotContain(this string actual, string expected) { Assert.IsFalse(actual.Contains(expected), String.Format("\"{0}\" contains \"{1}\".", actual, expected)); } /// <summary> /// Asserts that the exception contains the given string. /// </summary> /// <example> /// <code> /// try /// { /// repository.CreateOrder(...); /// } /// catch (Exception ex) /// { /// ex.ShouldContainErrorMessage("invalid CustomerId"); /// } /// </code> /// </example> public static void ShouldContainErrorMessage(this Exception exception, string expected) { ShouldContain(exception.Message, expected); } /// <summary> /// Asserts that the given exception type was thrown by the action. /// </summary> /// <example> /// <code> /// typeof(RepositoryException).ShouldBeThrownBy(() => repository.CreateOrder(...)); /// </code> /// </example> public static Exception ShouldBeThrownBy(this Type exceptionType, Action actionThatThrows) { Exception exception = actionThatThrows.GetException(); Assert.IsNotNull(exception); Assert.AreEqual(exceptionType, exception.GetType()); return exception; } /// <summary> /// Asserts that the given exception type was thrown by the action, and that /// the exception satisfies the condition. /// </summary> /// <example> /// <code> /// typeof(RepositoryException) /// .ShouldBeThrownBy( /// () => repository.CreateOrder(...), /// e => e.Reason == Reason.InvalidData); /// </code> /// </example> public static Exception ShouldBeThrownBy(this Type exceptionType, Action actionThatThrows, Predicate<Exception> exceptionCondition) { Exception exception = actionThatThrows.GetException(); Assert.IsNotNull(exception); Assert.AreEqual(exceptionType, exception.GetType()); if (!exceptionCondition(exception)) throw new ArgumentException("Exception throw did not satisfy the condition."); return exception; } /// <summary> /// Retrieves the exception throw by the action, or <see langword="null"/>. /// </summary> public static Exception GetException(this Action actionThatThrows) { Exception exception = null; try { actionThatThrows(); } catch (Exception e) { exception = e; } return exception; } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel.Design; using System.IO; using System.Linq; using System.Resources; namespace ResxTranslator.Common { /// <summary> /// Represents text strings that are localized in a number of resx files. /// The files comprise the so-called Localization Group. /// </summary> public class LocalizationGroup { // <key, <culture, LocalizedValue>> private readonly Dictionary<string, Dictionary<string, LocalizedValue>> _contents = new Dictionary<string, Dictionary<string, LocalizedValue>>(); private readonly List<string> _cultures = new List<string>(); private KeyList _keys; /// <summary> /// Creates an instance of this class. /// </summary> public LocalizationGroup() { _keys = new KeyList(this); IsNew = true; } internal LocalizationGroup(string path, string baseTitle, string[] cultures, bool[] load) { if (path == null) { throw new ArgumentNullException("path"); } if (path.Trim().Length <= 0) { throw new ArgumentException("path"); } if (baseTitle == null) { throw new ArgumentNullException("baseTitle"); } if (baseTitle.Trim().Length <= 0) { throw new ArgumentException("baseTitle"); } if (cultures == null || cultures.Length <= 0) { throw new ArgumentException("cultures"); } if (cultures.Any(culture => culture == null)) { throw new ArgumentException("null culture"); } if (cultures.Distinct().Count() != cultures.Length) { throw new ArgumentException("Duplicate culture"); } if (cultures.Length != load.Length) { throw new ArgumentException("load"); } Path = path; BaseTitle = baseTitle; _cultures.AddRange(cultures); Dictionary<string, Dictionary<string, LocalizedValue>> tempContents = new Dictionary<string, Dictionary<string, LocalizedValue>>(); List<string> tempKeys = new List<string>(); for (int i = 0; i < load.Length; i++) { if (load[i]) { DoAddFile(_cultures[i], tempContents, tempKeys); } } tempKeys.Sort(); _contents = tempContents; _keys = new KeyList(this, tempKeys); KeysDirty = false; // reset it after loading files } /// <summary> /// Gets or sets a value indicating whether this is a new, unpersisted localization group. /// </summary> public bool IsNew { get; set; } public string Path { get; private set; } public string BaseTitle { get; private set; } public LocalizedValue this[string key, string culture] { get { return EnsureLocalizedValue(key, culture); } } public string this[int row, int col] { get { if (col == 0) { return _keys[row]; } else { int cultureIndex = (col - 1) / 2; string culture = _cultures[cultureIndex]; LocalizedValue localizedValue = this[_keys[row], culture]; return col % 2 == 0 ? localizedValue.Comment : localizedValue.Value; } } set { string oldKey = Keys[row]; if (col == 0) { Keys[row] = value; } else { int cultureIndex = (col - 1) / 2; string culture = _cultures[cultureIndex]; LocalizedValue localizedValue = this[oldKey, culture]; if (col % 2 == 0) { localizedValue.Comment = value; } else { localizedValue.Value = value; } } } } public IKeyList Keys { get { return _keys; } } public IList<string> Cultures { get { return _cultures; } } public bool KeysDirty { get; private set; } /// <summary> /// Adds a culture to the group, loading it from disk. /// </summary> /// <param name="culture">The culture code.</param> public void LoadCulture(string culture) { Cultures.Add(culture); // TODO: Don't use instance variable here List<string> tempKeys = new List<string>(_keys); DoAddFile(culture, _contents, tempKeys); tempKeys.Sort(); _keys = new KeyList(this, tempKeys); } public void SaveAll(string path, string baseFileName) { SaveAllAs(path, baseFileName); IsNew = false; Path = path; BaseTitle = baseFileName; } public void SaveAll() { if (IsNew) { throw new InvalidOperationException("No path specified"); } SaveAllAs(Path, BaseTitle); } internal LocalizedValue EnsureLocalizedValue(string key, string culture) { if (!_keys.Contains(key)) { throw new ArgumentOutOfRangeException("Key not found"); } if (!_cultures.Contains(culture)) { throw new ArgumentOutOfRangeException("Culture not found"); } Dictionary<string, LocalizedValue> values; if (_contents.ContainsKey(key)) { values = _contents[key]; } else { values = new Dictionary<string, LocalizedValue>(); _contents.Add(key, values); } LocalizedValue lv; if (values.ContainsKey(culture)) { lv = values[culture]; } else { lv = new LocalizedValue(); values.Add(culture, lv); } return lv; } internal void KeyRenamed(string oldKey, string newKey) { if (_contents.ContainsKey(oldKey)) { _contents.Add(newKey, _contents[oldKey]); _contents.Remove(oldKey); } KeysDirty = true; } internal void KeyRemoved(string key) { if (_contents.ContainsKey(key)) { _contents.Remove(key); } KeysDirty = true; } internal void KeyAdded(string item) { KeysDirty = true; } private IEnumerable<LocalizedValue> LocalizedValuesOfCulture(string culture) { foreach (string key in _contents.Keys) { Dictionary<string, LocalizedValue> translationsOfKey = _contents[key]; if (translationsOfKey.ContainsKey(culture)) { LocalizedValue localizedValue = translationsOfKey[culture]; yield return localizedValue; } } } private void DoAddFile(string culture, Dictionary<string, Dictionary<string, LocalizedValue>> contents, IList<string> keys) { string file = FilenameUtils.ToFilename(culture, Path, BaseTitle); foreach (KeyValuePair<string, LocalizedValue> entry in Read(file)) { Dictionary<string, LocalizedValue> translations; if (contents.ContainsKey(entry.Key)) { translations = contents[entry.Key]; } else { translations = new Dictionary<string, LocalizedValue>(); contents.Add(entry.Key, translations); keys.Add(entry.Key); } translations[culture] = entry.Value; } } private void SaveAllAs(string path, string baseTitle) { if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException("path"); } if (string.IsNullOrEmpty(baseTitle)) { throw new ArgumentException("baseTitle"); } if (_cultures == null || _cultures.Count <= 0) { throw new InvalidOperationException("No cultures to be saved"); } if (Keys == null || Keys.Count <= 0) { throw new InvalidOperationException("No keys to be saved"); } foreach (string culture in _cultures) { SaveFileAs(culture, path, baseTitle); } KeysDirty = false; } private IEnumerable<KeyValuePair<string, LocalizedValue>> GetNonEmptyKeys(string culture) { if (culture == null) { throw new ArgumentNullException("culture"); } if (_keys == null || _keys.Count <= 0 || _cultures == null || !_cultures.Contains(culture) || _contents == null || _contents.Count <= 0) { yield break; } foreach (string key in Keys) { Dictionary<string, LocalizedValue> map = null; if (_contents.ContainsKey(key)) { map = _contents[key]; } LocalizedValue localizedValue = null; if (map != null && map.ContainsKey(culture)) { localizedValue = map[culture]; } if (!LocalizedValue.IsNullOrEmpty(localizedValue)) { yield return new KeyValuePair<string, LocalizedValue>(key, localizedValue); } } } private void SaveFileAs(string culture, string path, string baseTitle) { var nonEmptyKeys = GetNonEmptyKeys(culture); string filename = FilenameUtils.ToFilename(culture, path, baseTitle); using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.ReadWrite)) { if (nonEmptyKeys.Any()) { using (ResXResourceWriter writer = new ResXResourceWriter(fs)) { foreach (KeyValuePair<string, LocalizedValue> kv in nonEmptyKeys) { LocalizedValue translation = kv.Value; ResXDataNode n = new ResXDataNode(kv.Key, translation.Value); n.Comment = translation.Comment; writer.AddResource(n); translation.IsDirty = false; } writer.Generate(); writer.Close(); } } else { // write zero byte file fs.Flush(); } } } private IEnumerable<KeyValuePair<string, LocalizedValue>> Read(string file) { // Use a null type resolver. ITypeResolutionService typeres = null; using (ResXResourceReader reader = new ResXResourceReader(file)) { reader.UseResXDataNodes = true; foreach (DictionaryEntry o in reader) { string key = o.Key.ToString(); ResXDataNode node = (ResXDataNode)o.Value; string value = node.GetValue(typeres).ToString(); string comment = node.Comment; yield return new KeyValuePair<string, LocalizedValue>(key, new LocalizedValue(value, comment)); } } } } }
using AbcSharp.ABC; using AbcSharp.SWF; using Microsoft.Win32; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Runtime.ExceptionServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Web.Script.Serialization; using System.Windows; using System.Windows.Controls; using System.Windows.Threading; namespace LESs { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public static string selected_version; private const string VersionURL = "http://da.viddiaz.com/LESs/version.php?v="; private List<int> _supportedVersions = new List<int>(); private JavaScriptSerializer serializer = new JavaScriptSerializer(); private readonly BackgroundWorker _worker = new BackgroundWorker(); private ErrorLevel _errorLevel = ErrorLevel.NoError; private Dictionary<CheckBox, LessMod> _lessMods = new Dictionary<CheckBox, LessMod>(); private Stopwatch timer; private ServerType type; private string BackupVersion; private string _modsDirectory = "mods"; public MainWindow() { InitializeComponent(); } /// <summary> /// Called when the program encounters any unhandled exception. Displays a message box to the user alerting them to the error. /// </summary> private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { MessageBox.Show(e.ExceptionObject.ToString()); } /// <summary> /// Called on the initial loading of Lol Enhancement Suite. /// </summary> private async void MainGrid_Loaded(object sender, RoutedEventArgs e) { string AssemblyVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); LeagueVersionLabel.Content = AssemblyVersion; BackupVersion = AssemblyVersion; WebSiteButton.IsEnabled = true; //Set the events for the worker when the patching starts. _worker.DoWork += worker_DoWork; _worker.RunWorkerCompleted += worker_RunWorkerCompleted; //Enable exception logging if the debugger ISNT attached. if (!Debugger.IsAttached) AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; //Try to find the mods in the base directory of the solution when the debugger is attached if (Debugger.IsAttached && !Directory.Exists(_modsDirectory) && Directory.Exists("../../../mods")) { _modsDirectory = "../../../mods"; } //Add a reload button if we are debugging #if DEBUG ReloadButton.Visibility = Visibility.Visible; #endif //Make sure that the mods exist in the directory. Warn the user if they dont. if (!Directory.Exists(_modsDirectory)) { MessageBox.Show("Missing mods directory. Ensure that all files were extracted properly.", "Missing files"); Environment.Exit(0); } LoadMods(); try { using (WebClient c = new WebClient()) { _supportedVersions = serializer.Deserialize<List<int>>(await c.DownloadStringTaskAsync($"{VersionURL}{AssemblyVersion}")); } } catch //Couldn't load versions... { } } private void LoadMods() { ModsListBox.Items.Clear(); _lessMods.Clear(); //Get all mods within the mod directory var modList = Directory.GetDirectories(_modsDirectory); //Add each mod to the mod list. foreach (string mod in modList) { string modJsonFile = Path.Combine(mod, "mod.json"); if (File.Exists(modJsonFile)) { LessMod lessMod = serializer.Deserialize<LessMod>(File.ReadAllText(modJsonFile)); lessMod.Directory = mod; CheckBox ModCheckBox = new CheckBox() { IsChecked = !lessMod.DisabledByDefault && !lessMod.PermaDisable, //Don't automatically check disabled by default mods IsEnabled = !lessMod.PermaDisable, Content = lessMod.Name }; ModsListBox.Items.Add(ModCheckBox); _lessMods.Add(ModCheckBox, lessMod); } } } /// <summary> /// Change the label & description when the mod is hovered over. /// </summary> private void ModsListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { CheckBox box = (CheckBox)ModsListBox.SelectedItem; if (box == null) return; LessMod lessMod = _lessMods[box]; ModNameLabel.Content = lessMod.Name; ModDescriptionBox.Text = lessMod.Description; //see if our mod has an author and display it if (!string.IsNullOrEmpty(lessMod.Author)) ModAuthorLabel.Content = "Author: " + lessMod.Author; else ModAuthorLabel.Content = "Author: Anonymous"; } /// <summary> /// Called when the user looks for their League of Legends installation /// </summary> private void FindButton_Click(object sender, RoutedEventArgs e) { //Disable patching if the user selects another league installation. PatchButton.IsEnabled = false; RemoveButton.IsEnabled = false; //Create a file dialog for the user to locate their league of legends installation. OpenFileDialog findLeagueDialog = new OpenFileDialog(); findLeagueDialog.DefaultExt = ".exe"; findLeagueDialog.Filter = "League of Legends Launcher|lol.launcher*.exe|Garena Launcher|lol.exe"; //Only show the league of legends executables string RiotPath = Path.Combine(Path.GetPathRoot(Environment.SystemDirectory), "Riot Games", "League of Legends"); string GarenaPath = Path.Combine(Path.GetPathRoot(Environment.SystemDirectory), "Program Files (x86)", "GarenaLoL", "GameData", "Apps", "LoL"); //If they don't have League of Legends in the default path, look for Garena. if (!Directory.Exists(RiotPath)) findLeagueDialog.InitialDirectory = Path.GetFullPath(GarenaPath); else findLeagueDialog.InitialDirectory = Path.GetFullPath(RiotPath); bool? selectedExectuable = findLeagueDialog.ShowDialog(); if (selectedExectuable == false || selectedExectuable == null) return; //Remove the executable from the location Uri Location = new Uri(findLeagueDialog.FileName); string SelectedLocation = Location.LocalPath.Replace(Location.Segments.Last(), string.Empty); //Get the executable name to check for Garena string LastSegment = Location.Segments.Last(); //If the file name is lol.exe, then it's garena if (!LastSegment.StartsWith("lol.launcher")) { type = ServerType.GARENA; RemoveButton.IsEnabled = true; PatchButton.IsEnabled = true; LocationTextbox.Text = Path.Combine(SelectedLocation, "Air"); } else { //Check each RADS installation to find the latest installation string radsLocation = Path.Combine(SelectedLocation, "RADS", "projects", "lol_air_client", "releases"); //Compare the version text with format x.x.x.x to get the largest directory var versionDirectories = Directory.GetDirectories(radsLocation); string finalDirectory = ""; int BiggestVersion = 0; //Get the biggest version in the directory foreach (string x in versionDirectories) { string CurrentVersion = new Uri(x).Segments.Last(); string[] VersionNumbers = CurrentVersion.Split('.'); for (int i = 0; i < VersionNumbers.Length; i++) { //Ensure that numbers like 0.0.2.1 are larger than 0.0.1.999 VersionNumbers[i] = VersionNumbers[i].PadLeft(3, '0'); } int Version = Convert.ToInt32(string.Join("", VersionNumbers)); if (Version > BiggestVersion) { BiggestVersion = Version; finalDirectory = x; } } BackupVersion = BiggestVersion.ToString(); //If the version isn't the intended version, show a message to the user. This is just a warning and probably can be ignored if (!_supportedVersions.Contains(BiggestVersion) && !Debugger.IsAttached) { string Message = "This version of LESs may not support your version of League of Legends. Continue? This could harm your installation."; MessageBoxResult versionMismatchResult = MessageBox.Show(Message, "Invalid Version", MessageBoxButton.YesNo); if (versionMismatchResult == MessageBoxResult.No) return; } type = ServerType.NORMAL; PatchButton.IsEnabled = true; RemoveButton.IsEnabled = true; LocationTextbox.Text = Path.Combine(finalDirectory, "deploy"); } //Create the LESsBackup directory to allow the user to uninstall if they wish to later on. Directory.CreateDirectory(Path.Combine(LocationTextbox.Text, "LESsBackup")); Directory.CreateDirectory(Path.Combine(LocationTextbox.Text, "LESsBackup", BackupVersion)); } /// <summary> /// Called when the user tries to patch their League of Legends installation. /// </summary> private void PatchButton_Click(object sender, RoutedEventArgs e) { PatchButton.IsEnabled = false; ReloadButton.IsEnabled = false; _worker.RunWorkerAsync(); } /// <summary> /// Called when the user wants to remove LESs from their League of Legends installation. /// </summary> private void RemoveButton_Click(object sender, RoutedEventArgs e) { new RemovePopup(type, LocationTextbox.Text).Show(); } /// <summary> /// Called when the user wants to check the League# forum topic. /// </summary> private void WebSiteButton_Click(object sender, RoutedEventArgs e) { Process.Start("https://www.joduska.me/forum/topic/77640-519league-enhancement-suite/"); } /// <summary> /// Gets all the mods and patches them. /// </summary> private void worker_DoWork(object sender, DoWorkEventArgs e) { _errorLevel = ErrorLevel.NoError; //Gets the list of mods ItemCollection modCollection = null; string lolLocation = null; //Get the data from the UI thread Dispatcher.Invoke(DispatcherPriority.Input, new ThreadStart(() => { modCollection = ModsListBox.Items; lolLocation = LocationTextbox.Text; })); SetStatusLabelAsync("Gathering mods..."); //Gets the list of mods that have been checked. List<LessMod> modsToPatch = new List<LessMod>(); foreach (var x in modCollection) { CheckBox box = (CheckBox)x; bool isBoxChecked = false; Dispatcher.Invoke(DispatcherPriority.Input, new ThreadStart(() => { isBoxChecked = box.IsChecked ?? false; })); if (isBoxChecked) { modsToPatch.Add(_lessMods[box]); } } //Create a new dictionary to hold the SWF definitions in. This stops opening and closing the same SWF file if it's going to be modified more than once. Dictionary<string, SwfFile> swfs = new Dictionary<string, SwfFile>(); //Start the stopwatch to see how long it took to patch (aiming for ~5 sec or less on test machine) timer = Stopwatch.StartNew(); //Go through each modification foreach (var lessMod in modsToPatch) { SetStatusLabelAsync("Patching mod: " + lessMod.Name); //Go through each patch within the mod foreach (var patch in lessMod.Patches) { //If the swf hasn't been loaded, load it into the dictionary. if (!swfs.ContainsKey(patch.Swf)) { string fullPath = Path.Combine(lolLocation, patch.Swf); //Backup the SWF string CurrentLocation = ""; string[] FileLocation = patch.Swf.Split('/', '\\'); foreach (string s in FileLocation.Take(FileLocation.Length - 1)) { CurrentLocation = Path.Combine(CurrentLocation, s); if (!Directory.Exists(Path.Combine(lolLocation, "LESsBackup", BackupVersion, CurrentLocation))) { Directory.CreateDirectory(Path.Combine(lolLocation, "LESsBackup", BackupVersion, CurrentLocation)); } } if (!File.Exists(Path.Combine(lolLocation, "LESsBackup", BackupVersion, patch.Swf))) { File.Copy(Path.Combine(lolLocation, patch.Swf), Path.Combine(lolLocation, "LESsBackup", BackupVersion, patch.Swf)); } swfs.Add(patch.Swf, SwfFile.ReadFile(fullPath)); } //Get the SWF file that is being modified SwfFile swf = swfs[patch.Swf]; if (patch.Action == "replace_swf_character")// replace an swf-character (buttons, sprites, fonts etc.) { ushort charId; if (ushort.TryParse(patch.Class, out charId) && swf.CharacterTags.ContainsKey(charId)) { swf.CharacterTags[charId].SetData(File.ReadAllBytes(Path.Combine(lessMod.Directory, patch.Code))); } else { _errorLevel = ErrorLevel.UnableToPatch; throw new TraitNotFoundException($"<{patch.Class}> is not a valid Character ID."); } } else { //Get the ABC tags (containing the code) from the swf file. List<DoAbcTag> tags = swf.GetDoAbcTags(); bool classFound = false; foreach (var tag in tags) { //check if this tag contains our script ScriptInfo si = tag.GetScriptByClassName(patch.Class); //check next tag if it doesn't if (si == null) continue; ClassInfo cls = si.FindClass(patch.Class); classFound = true; Assembler asm; //Perform the action based on what the patch defines switch (patch.Action) { case "replace_trait": //replace trait (method) //Load the code from the patch and assemble it to be inserted into the code asm = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code))); TraitInfo newTrait = asm.Assemble() as TraitInfo; int traitIndex = cls.GetTraitIndexByTypeAndName(newTrait.Type, newTrait.Name.Name, Scope.Instance); bool classTrait = false; if (traitIndex < 0) { traitIndex = cls.GetTraitIndexByTypeAndName(newTrait.Type, newTrait.Name.Name, Scope.Class); classTrait = true; } if (traitIndex < 0) { throw new TraitNotFoundException(String.Format("Can't find trait \"{0}\" in class \"{1}\"", newTrait.Name.Name, patch.Class)); } //Modified the found trait if (classTrait) { cls.ClassTraits[traitIndex] = newTrait; } else { cls.InstanceTraits[traitIndex] = newTrait; } break; case "replace_cinit"://replace class constructor //Load the code from the patch and assemble it to be inserted into the code asm = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code))); cls.ClassInit = asm.Assemble() as MethodInfo; break; case "replace_iinit"://replace instance constructor //Load the code from the patch and assemble it to be inserted into the code asm = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code))); cls.InstanceInit = asm.Assemble() as MethodInfo; break; case "add_class_trait": //add new class trait (method) //Load the code from the patch and assemble it to be inserted into the code asm = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code))); newTrait = asm.Assemble() as TraitInfo; traitIndex = cls.GetTraitIndexByTypeAndName(newTrait.Type, newTrait.Name.Name, Scope.Class); if (traitIndex < 0) { cls.ClassTraits.Add(newTrait); } else { cls.ClassTraits[traitIndex] = newTrait; } break; case "add_instance_trait": //add new instance trait (method) //Load the code from the patch and assemble it to be inserted into the code asm = new Assembler(File.ReadAllText(Path.Combine(lessMod.Directory, patch.Code))); newTrait = asm.Assemble() as TraitInfo; traitIndex = cls.GetTraitIndexByTypeAndName(newTrait.Type, newTrait.Name.Name, Scope.Instance); if (traitIndex < 0) { cls.InstanceTraits.Add(newTrait); } else { cls.InstanceTraits[traitIndex] = newTrait; } break; case "remove_class_trait": throw new NotImplementedException(); case "remove_instance_trait": throw new NotImplementedException(); default: throw new NotSupportedException($"Unknown Action \"{patch.Action}\" in mod {lessMod.Name}"); } } if (!classFound) { _errorLevel = ErrorLevel.UnableToPatch; throw new ClassNotFoundException($"Class {patch.Class} not found in file {patch.Swf}"); } } } } //Save the modified SWFS to their original location foreach (var patchedSwf in swfs) { try { SetStatusLabelAsync("Applying mods: " + patchedSwf.Key); string swfLoc = Path.Combine(lolLocation, patchedSwf.Key); SwfFile.WriteFile(patchedSwf.Value, swfLoc); } catch { _errorLevel = ErrorLevel.GoodJobYourInstallationIsProbablyCorruptedNow; if (Debugger.IsAttached) throw; } } timer.Stop(); } /// <summary> /// Called once LESs has been successfully patched into the client. /// </summary> private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { switch (_errorLevel) { case ErrorLevel.NoError: StatusLabel.Content = "Done patching!"; MessageBox.Show("LESs has been successfully patched into League of Legends!\n(In " + timer.ElapsedMilliseconds + "ms)"); break; case ErrorLevel.UnableToPatch: SetStatusLabelAsync("[Error] Please check debug.log for more information."); MessageBox.Show("LESs encountered errors during patching. No mods have been applied."); break; case ErrorLevel.GoodJobYourInstallationIsProbablyCorruptedNow: SetStatusLabelAsync("[Critical Error] Please check debug.log for more information."); MessageBox.Show("LESs encountered errors during patching.\nIt is possible your client is corrupted.\nPlease repair before trying again."); break; } PatchButton.IsEnabled = true; ReloadButton.IsEnabled = true; } /// <summary> /// Sets the text of the status label /// </summary> private void SetStatusLabelAsync(string text) { Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() => { StatusLabel.Content = text; })); } /// <summary> /// Reloads all mods /// </summary> private void ReloadButton_Click(object sender, RoutedEventArgs e) { LoadMods(); } } }
using System; using System.Runtime.InteropServices; using System.Collections; using UnityEngine; /* * please don't use this code for sell a asset * user for free * developed by Poya @ http://gamesforsoul.com/ * BLOB support by Jonathan Derrough @ http://jderrough.blogspot.com/ * Modify and structure by Santiago Bustamante @ busta117@gmail.com * Android compatibility by Thomas Olsen @ olsen.thomas@gmail.com * * */ using Logger = June.DebugLogger; namespace SQLiteUnityKit { /// <summary> /// Sqlite exception. /// </summary> public class SqliteException : Exception { /// <summary> /// Initializes a new instance of the <see cref="SQLiteUnityKit.SqliteException"/> class. /// </summary> /// <param name="message">Message.</param> public SqliteException (string message) : base(message) { } } /// <summary> /// Sqlite database. /// </summary> public class SqliteDatabase : IDisposable { private bool CanExQuery = true; const int SQLITE_OK = 0; const int SQLITE_ROW = 100; const int SQLITE_DONE = 101; const int SQLITE_INTEGER = 1; const int SQLITE_FLOAT = 2; const int SQLITE_TEXT = 3; const int SQLITE_BLOB = 4; const int SQLITE_NULL = 5; [DllImport("sqlite3", EntryPoint = "sqlite3_open")] private static extern int sqlite3_open (string filename, out IntPtr db); [DllImport("sqlite3", EntryPoint = "sqlite3_close")] private static extern int sqlite3_close (IntPtr db); [DllImport("sqlite3", EntryPoint = "sqlite3_prepare_v2")] private static extern int sqlite3_prepare_v2 (IntPtr db, string zSql, int nByte, out IntPtr ppStmpt, IntPtr pzTail); [DllImport("sqlite3", EntryPoint = "sqlite3_step")] private static extern int sqlite3_step (IntPtr stmHandle); [DllImport("sqlite3", EntryPoint = "sqlite3_finalize")] private static extern int sqlite3_finalize (IntPtr stmHandle); [DllImport("sqlite3", EntryPoint = "sqlite3_exec")] private static extern int sqlite3_exec (IntPtr db, string zSql, IntPtr callback, IntPtr firstArg, out IntPtr ErrorWrapper); [DllImport("sqlite3", EntryPoint = "sqlite3_errmsg")] private static extern IntPtr sqlite3_errmsg (IntPtr db); [DllImport("sqlite3", EntryPoint = "sqlite3_total_changes")] private static extern int sqlite3_total_changes (IntPtr db); [DllImport("sqlite3", EntryPoint = "sqlite3_changes")] private static extern int sqlite3_changes (IntPtr db); [DllImport("sqlite3", EntryPoint = "sqlite3_column_count")] private static extern int sqlite3_column_count (IntPtr stmHandle); [DllImport("sqlite3", EntryPoint = "sqlite3_column_name")] private static extern IntPtr sqlite3_column_name (IntPtr stmHandle, int iCol); [DllImport("sqlite3", EntryPoint = "sqlite3_column_type")] private static extern int sqlite3_column_type (IntPtr stmHandle, int iCol); [DllImport("sqlite3", EntryPoint = "sqlite3_column_int")] private static extern int sqlite3_column_int (IntPtr stmHandle, int iCol); [DllImport("sqlite3", EntryPoint = "sqlite3_column_text")] private static extern IntPtr sqlite3_column_text (IntPtr stmHandle, int iCol); [DllImport("sqlite3", EntryPoint = "sqlite3_column_double")] private static extern double sqlite3_column_double (IntPtr stmHandle, int iCol); [DllImport("sqlite3", EntryPoint = "sqlite3_column_blob")] private static extern IntPtr sqlite3_column_blob (IntPtr stmHandle, int iCol); [DllImport("sqlite3", EntryPoint = "sqlite3_column_bytes")] private static extern int sqlite3_column_bytes (IntPtr stmHandle, int iCol); private IntPtr _connection; /// <summary> /// Gets a value indicating whether this instance is connection open. /// </summary> /// <value><c>true</c> if this instance is connection open; otherwise, <c>false</c>.</value> public bool IsConnectionOpen { get { return CanExQuery; } } /// <summary> /// Gets the connection string. /// </summary> /// <value>The connection string.</value> public string ConnectionString { get { return pathDB; } } private string pathDB; #region Public Methods /// <summary> /// Initializes a new instance of the <see cref="SqliteDatabase"/> class. /// </summary> /// <param name='dbName'> /// Data Base name. (the file needs exist in the streamingAssets folder) /// </param> public SqliteDatabase (string dbName) { this.pathDB = dbName; this.CanExQuery = false; } /// <summary> /// Open this instance. /// </summary> public void Open () { this.Open (pathDB); } /// <summary> /// Open the specified path. /// </summary> /// <param name="path">Path.</param> public void Open (string path) { if (IsConnectionOpen) { throw new SqliteException ("There is already an open connection"); } if (sqlite3_open (path, out _connection) != SQLITE_OK) { throw new SqliteException ("Could not open database file: " + path); } this.CanExQuery = true; } /// <summary> /// Close this instance. /// </summary> public void Close () { if (IsConnectionOpen) { sqlite3_close (_connection); } this.CanExQuery = false; } /// <summary> /// Executes a Update, Delete, etc query. /// </summary> /// <param name='query'> /// Query. /// </param> /// <exception cref='SqliteException'> /// Is thrown when the sqlite exception. /// </exception> public int ExecuteNonQuery (string query) { int changes = 0; if (!CanExQuery) { Logger.Log ("ERROR: Can't execute the query, verify DB origin file"); return 0; } if(!IsConnectionOpen) { this.Open (); } if (!IsConnectionOpen) { throw new SqliteException ("SQLite database is not open."); } IntPtr stmHandle = Prepare (query); if (sqlite3_step (stmHandle) != SQLITE_DONE) { throw new SqliteException ("Could not execute SQL statement."); } changes = sqlite3_changes(_connection); Finalize (stmHandle); this.Close (); return changes; } /// <summary> /// Executes a query that requires a response (SELECT, etc). /// </summary> /// <returns> /// Dictionary with the response data /// </returns> /// <param name='query'> /// Query. /// </param> /// <exception cref='SqliteException'> /// Is thrown when the sqlite exception. /// </exception> public DataTable ExecuteQuery (string query) { if (!CanExQuery) { Logger.Log ("ERROR: Can't execute the query, verify DB origin file"); return null; } if(!IsConnectionOpen) { this.Open (); } if (!IsConnectionOpen) { throw new SqliteException ("SQLite database is not open."); } IntPtr stmHandle = Prepare (query); int columnCount = sqlite3_column_count (stmHandle); var dataTable = new DataTable (); for (int i = 0; i < columnCount; i++) { string columnName = Marshal.PtrToStringAnsi (sqlite3_column_name (stmHandle, i)); dataTable.Columns.Add (columnName); } //populate datatable while (sqlite3_step(stmHandle) == SQLITE_ROW) { object[] row = new object[columnCount]; for (int i = 0; i < columnCount; i++) { switch (sqlite3_column_type (stmHandle, i)) { case SQLITE_INTEGER: row [i] = sqlite3_column_int (stmHandle, i); break; case SQLITE_TEXT: IntPtr text = sqlite3_column_text (stmHandle, i); row [i] = Marshal.PtrToStringAnsi (text); break; case SQLITE_FLOAT: row [i] = sqlite3_column_double (stmHandle, i); break; case SQLITE_BLOB: IntPtr blob = sqlite3_column_blob (stmHandle, i); int size = sqlite3_column_bytes (stmHandle, i); byte[] data = new byte[size]; Marshal.Copy (blob, data, 0, size); row [i] = data; break; case SQLITE_NULL: row [i] = null; break; } } dataTable.AddRow (row); } Finalize (stmHandle); this.Close (); return dataTable; } public int ExecuteScript (string script) { int changes = 0; try { if (!CanExQuery) { Logger.Log ("ERROR: Can't execute the query, verify DB origin file"); return 0; } if(!IsConnectionOpen) { this.Open (); } if (!IsConnectionOpen) { throw new SqliteException ("SQLite database is not open."); } IntPtr hError; int result = sqlite3_exec(_connection, script, IntPtr.Zero, IntPtr.Zero, out hError); if (result != SQLITE_OK || result != SQLITE_DONE) { throw new SqliteException ("Could not execute SQL script."); } changes = sqlite3_changes(_connection); this.Close(); } catch(Exception ex) { Logger.Log(ex); } return changes; } #endregion #region Private Methods private IntPtr Prepare (string query) { IntPtr stmHandle; if (sqlite3_prepare_v2 (_connection, query, query.Length, out stmHandle, IntPtr.Zero) != SQLITE_OK) { IntPtr errorMsg = sqlite3_errmsg (_connection); throw new SqliteException (Marshal.PtrToStringAnsi (errorMsg)); } return stmHandle; } private void Finalize (IntPtr stmHandle) { if (sqlite3_finalize (stmHandle) != SQLITE_OK) { throw new SqliteException ("Could not finalize SQL statement."); } } #endregion #region IDisposable implementation /// <summary> /// Releases all resource used by the <see cref="SQLiteUnityKit.SqliteDatabase"/> object. /// </summary> /// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="SQLiteUnityKit.SqliteDatabase"/>. The /// <see cref="Dispose"/> method leaves the <see cref="SQLiteUnityKit.SqliteDatabase"/> in an unusable state. After /// calling <see cref="Dispose"/>, you must release all references to the <see cref="SQLiteUnityKit.SqliteDatabase"/> /// so the garbage collector can reclaim the memory that the <see cref="SQLiteUnityKit.SqliteDatabase"/> was occupying.</remarks> public void Dispose () { if(IsConnectionOpen) { Close(); } } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Timers; using OpenMetaverse.Packets; using OpenSim.Framework; using OpenSim.Framework.Monitoring; using OpenSim.Region.Framework.Interfaces; namespace OpenSim.Region.Framework.Scenes { /// <summary> /// Collect statistics from the scene to send to the client and for access by other monitoring tools. /// </summary> /// <remarks> /// FIXME: This should be a monitoring region module /// </remarks> public class SimStatsReporter { private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public const string LastReportedObjectUpdateStatName = "LastReportedObjectUpdates"; public const string SlowFramesStatName = "SlowFrames"; public delegate void SendStatResult(SimStats stats); public delegate void YourStatsAreWrong(); public delegate void SendAgentStat(string name, string ipAddress, string timestamp); public event SendStatResult OnSendStatsResult; public event YourStatsAreWrong OnStatsIncorrect; private SendStatResult handlerSendStatResult; private YourStatsAreWrong handlerStatsIncorrect; // Determines the size of the array that is used to collect StatBlocks // for sending to the SimStats and SimExtraStatsCollector private const int m_statisticArraySize = 32; // Holds the names of the users that are currently attempting to login // to the server private ArrayList m_usersLoggingIn; /// <summary> /// These are the IDs of stats sent in the StatsPacket to the viewer. /// </summary> /// <remarks> /// Some of these are not relevant to OpenSimulator since it is architected differently to other simulators /// (e.g. script instructions aren't executed as part of the frame loop so 'script time' is tricky). /// </remarks> public enum Stats : uint { TimeDilation = 0, SimFPS = 1, PhysicsFPS = 2, AgentUpdates = 3, FrameMS = 4, NetMS = 5, OtherMS = 6, PhysicsMS = 7, AgentMS = 8, ImageMS = 9, ScriptMS = 10, TotalPrim = 11, ActivePrim = 12, Agents = 13, ChildAgents = 14, ActiveScripts = 15, ScriptLinesPerSecond = 16, InPacketsPerSecond = 17, OutPacketsPerSecond = 18, PendingDownloads = 19, PendingUploads = 20, VirtualSizeKb = 21, ResidentSizeKb = 22, PendingLocalUploads = 23, UnAckedBytes = 24, PhysicsPinnedTasks = 25, PhysicsLodTasks = 26, SimPhysicsStepMs = 27, SimPhysicsShapeMs = 28, SimPhysicsOtherMs = 29, SimPhysicsMemory = 30, ScriptEps = 31, SimSpareMs = 32, SimSleepMs = 33, SimIoPumpTime = 34, FrameDilation = 35, UsersLoggingIn = 36, TotalGeoPrim = 37, TotalMesh = 38, ThreadCount = 39, UDPInRate = 40, UDPOutRate = 41, UDPErrorRate = 42, NetworkQueueSize = 43, ClientPingAvg = 44 } /// <summary> /// This is for llGetRegionFPS /// </summary> public float LastReportedSimFPS { get { return lastReportedSimFPS; } } /// <summary> /// Number of object updates performed in the last stats cycle /// </summary> /// <remarks> /// This isn't sent out to the client but it is very useful data to detect whether viewers are being sent a /// large number of object updates. /// </remarks> public float LastReportedObjectUpdates { get; private set; } public float[] LastReportedSimStats { get { return lastReportedSimStats; } } /// <summary> /// Number of frames that have taken longer to process than Scene.MIN_FRAME_TIME /// </summary> public Stat SlowFramesStat { get; private set; } /// <summary> /// The threshold at which we log a slow frame. /// </summary> public int SlowFramesStatReportThreshold { get; private set; } /// <summary> /// Extra sim statistics that are used by monitors but not sent to the client. /// </summary> /// <value> /// The keys are the stat names. /// </value> private Dictionary<string, float> m_lastReportedExtraSimStats = new Dictionary<string, float>(); // Sending a stats update every 3 seconds- private int m_statsUpdatesEveryMS = 3000; private float m_statsUpdateFactor; private float m_timeDilation; private int m_fps; /// <summary> /// Number of the last frame on which we processed a stats udpate. /// </summary> private uint m_lastUpdateFrame; /// <summary> /// Our nominal fps target, as expected in fps stats when a sim is running normally. /// </summary> private float m_nominalReportedFps = 55; /// <summary> /// Parameter to adjust reported scene fps /// </summary> /// <remarks> /// Our scene loop runs slower than other server implementations, apparantly because we work somewhat differently. /// However, we will still report an FPS that's closer to what people are used to seeing. A lower FPS might /// affect clients and monitoring scripts/software. /// </remarks> private float m_reportedFpsCorrectionFactor = 5; // saved last reported value so there is something available for llGetRegionFPS private float lastReportedSimFPS; private float[] lastReportedSimStats = new float[m_statisticArraySize]; private float m_pfps; /// <summary> /// Number of agent updates requested in this stats cycle /// </summary> private int m_agentUpdates; /// <summary> /// Number of object updates requested in this stats cycle /// </summary> private int m_objectUpdates; private int m_frameMS; private int m_spareMS; private int m_netMS; private int m_agentMS; private int m_physicsMS; private int m_imageMS; private int m_otherMS; //Ckrinke: (3-21-08) Comment out to remove a compiler warning. Bring back into play when needed. //Ckrinke private int m_scriptMS = 0; private int m_rootAgents; private int m_childAgents; private int m_numPrim; private int m_numGeoPrim; private int m_numMesh; private double m_inPacketsPerSecond; private double m_outPacketsPerSecond; private int m_activePrim; private int m_unAckedBytes; private int m_pendingDownloads; private int m_pendingUploads = 0; // FIXME: Not currently filled in private int m_activeScripts; private int m_scriptLinesPerSecond; private int m_objectCapacity = 45000; // This is the number of frames that will be stored and then averaged for // the Total, Simulation, Physics, and Network Frame Time; It is set to // 10 by default but can be changed by the OpenSim.ini configuration file // NumberOfFrames parameter private int m_numberFramesStored = Scene.m_defaultNumberFramesStored; // The arrays that will hold the time it took to run the past N frames, // where N is the num_frames_to_average given by the configuration file private double[] m_totalFrameTimeMilliseconds; private double[] m_simulationFrameTimeMilliseconds; private double[] m_physicsFrameTimeMilliseconds; private double[] m_networkFrameTimeMilliseconds; private int[] m_networkQueueSize; // The location of the next time in milliseconds that will be // (over)written when the next frame completes private int m_nextLocation = 0; private int m_netLocation = 0; // The correct number of frames that have completed since the last stats // update for physics private int m_numberPhysicsFrames; // The last reported value of threads from the SmartThreadPool inside of // XEngine private int m_inUseThreads; // These variables record the most recent snapshot of the UDP network // by holding values for the bytes per second in and out, and the number // of packets ignored per second private double m_inByteRate = 0.0; private double m_outByteRate = 0.0; private double m_errorPacketRate = 0.0; // Average ping between the server and a subset of connected users private double m_clientPing = 0.0; // Keeps track of the total ping time, and the number, of all connected clients pinged private double m_totalPingTime = 0; private int m_clientPingCount = 0; private Scene m_scene; private RegionInfo ReportingRegion; private Timer m_report = new Timer(); private IEstateModule estateModule; public SimStatsReporter(Scene scene) { // Initialize the different frame time arrays to the correct sizes m_totalFrameTimeMilliseconds = new double[m_numberFramesStored]; m_simulationFrameTimeMilliseconds = new double[m_numberFramesStored]; m_physicsFrameTimeMilliseconds = new double[m_numberFramesStored]; m_networkFrameTimeMilliseconds = new double[m_numberFramesStored]; m_networkQueueSize = new int[m_numberFramesStored]; // Initialize the array to hold the names of the users currently // attempting to login to the server m_usersLoggingIn = new ArrayList(); m_scene = scene; m_reportedFpsCorrectionFactor = scene.MinFrameSeconds * m_nominalReportedFps; m_statsUpdateFactor = (float)(m_statsUpdatesEveryMS / 1000); ReportingRegion = scene.RegionInfo; m_objectCapacity = scene.RegionInfo.ObjectCapacity; m_report.AutoReset = true; m_report.Interval = m_statsUpdatesEveryMS; m_report.Elapsed += TriggerStatsHeartbeat; m_report.Enabled = true; if (StatsManager.SimExtraStats != null) { OnSendStatsResult += StatsManager.SimExtraStats.ReceiveClassicSimStatsPacket; } /// At the moment, we'll only report if a frame is over 120% of target, since commonly frames are a bit /// longer than ideal (which in itself is a concern). SlowFramesStatReportThreshold = (int)Math.Ceiling(scene.MinFrameTicks * 1.2); SlowFramesStat = new Stat( "SlowFrames", "Slow Frames", "Number of frames where frame time has been significantly longer than the desired frame time.", " frames", "scene", m_scene.Name, StatType.Push, null, StatVerbosity.Info); StatsManager.RegisterStat(SlowFramesStat); } public SimStatsReporter(Scene scene, int numberOfFrames) : this (scene) { // Store the number of frames from the OpenSim.ini configuration file m_numberFramesStored = numberOfFrames; } public void Close() { m_report.Elapsed -= TriggerStatsHeartbeat; m_report.Close(); } /// <summary> /// Sets the number of milliseconds between stat updates. /// </summary> /// <param name='ms'></param> public void SetUpdateMS(int ms) { m_statsUpdatesEveryMS = ms; m_statsUpdateFactor = (float)(m_statsUpdatesEveryMS / 1000); m_report.Interval = m_statsUpdatesEveryMS; } private void TriggerStatsHeartbeat(object sender, EventArgs args) { try { statsHeartBeat(sender, args); } catch (Exception e) { m_log.Warn(string.Format( "[SIM STATS REPORTER] Update for {0} failed with exception ", m_scene.RegionInfo.RegionName), e); } } private void statsHeartBeat(object sender, EventArgs e) { double totalSumFrameTime; double simulationSumFrameTime; double physicsSumFrameTime; double networkSumFrameTime; double networkSumQueueSize; float frameDilation; int currentFrame; if (!m_scene.Active) return; // Create arrays to hold the statistics for this current scene, // these will be passed to the SimExtraStatsCollector, they are also // sent to the SimStats class SimStatsPacket.StatBlock[] sb = new SimStatsPacket.StatBlock[m_statisticArraySize]; SimStatsPacket.RegionBlock rb = new SimStatsPacket.RegionBlock(); // Know what's not thread safe in Mono... modifying timers. // m_log.Debug("Firing Stats Heart Beat"); lock (m_report) { uint regionFlags = 0; try { if (estateModule == null) estateModule = m_scene.RequestModuleInterface<IEstateModule>(); regionFlags = estateModule != null ? estateModule.GetRegionFlags() : (uint) 0; } catch (Exception) { // leave region flags at 0 } #region various statistic googly moogly // ORIGINAL code commented out until we have time to add our own // statistics to the statistics window, this will be done as a // new section given the title of our current project // We're going to lie about the FPS because we've been lying since 2008. The actual FPS is currently // locked at a maximum of 11. Maybe at some point this can change so that we're not lying. //int reportedFPS = (int)(m_fps * m_reportedFpsCorrectionFactor); int reportedFPS = m_fps; // save the reported value so there is something available for llGetRegionFPS lastReportedSimFPS = reportedFPS / m_statsUpdateFactor; // ORIGINAL code commented out until we have time to add our own // statistics to the statistics window //float physfps = ((m_pfps / 1000)); float physfps = m_numberPhysicsFrames; //if (physfps > 600) //physfps = physfps - (physfps - 600); if (physfps < 0) physfps = 0; #endregion m_rootAgents = m_scene.SceneGraph.GetRootAgentCount(); m_childAgents = m_scene.SceneGraph.GetChildAgentCount(); m_numPrim = m_scene.SceneGraph.GetTotalObjectsCount(); m_numGeoPrim = m_scene.SceneGraph.GetTotalPrimObjectsCount(); m_numMesh = m_scene.SceneGraph.GetTotalMeshObjectsCount(); m_activePrim = m_scene.SceneGraph.GetActiveObjectsCount(); m_activeScripts = m_scene.SceneGraph.GetActiveScriptsCount(); // FIXME: Checking for stat sanity is a complex approach. What we really need to do is fix the code // so that stat numbers are always consistent. CheckStatSanity(); //Our time dilation is 0.91 when we're running a full speed, // therefore to make sure we get an appropriate range, // we have to factor in our error. (0.10f * statsUpdateFactor) // multiplies the fix for the error times the amount of times it'll occur a second // / 10 divides the value by the number of times the sim heartbeat runs (10fps) // Then we divide the whole amount by the amount of seconds pass in between stats updates. // 'statsUpdateFactor' is how often stats packets are sent in seconds. Used below to change // values to X-per-second values. uint thisFrame = m_scene.Frame; float framesUpdated = (float)(thisFrame - m_lastUpdateFrame) * m_reportedFpsCorrectionFactor; m_lastUpdateFrame = thisFrame; // Avoid div-by-zero if somehow we've not updated any frames. if (framesUpdated == 0) framesUpdated = 1; for (int i = 0; i < m_statisticArraySize; i++) { sb[i] = new SimStatsPacket.StatBlock(); } // Resetting the sums of the frame times to prevent any errors // in calculating the moving average for frame time totalSumFrameTime = 0; simulationSumFrameTime = 0; physicsSumFrameTime = 0; networkSumFrameTime = 0; networkSumQueueSize = 0; // Loop through all the frames that were stored for the current // heartbeat to process the moving average of frame times for (int i = 0; i < m_numberFramesStored; i++) { // Sum up each frame time in order to calculate the moving // average of frame time totalSumFrameTime += m_totalFrameTimeMilliseconds[i]; simulationSumFrameTime += m_simulationFrameTimeMilliseconds[i]; physicsSumFrameTime += m_physicsFrameTimeMilliseconds[i]; networkSumFrameTime += m_networkFrameTimeMilliseconds[i]; networkSumQueueSize += m_networkQueueSize[i]; } // Get the index that represents the current frame based on the next one known; go back // to the last index if next one is stated to restart at 0 if (m_nextLocation == 0) currentFrame = m_numberFramesStored - 1; else currentFrame = m_nextLocation - 1; // Calculate the frame dilation; which is currently based on the ratio between the sum of the // physics and simulation rate, and the set minimum time to run a scene's frame frameDilation = (float)(m_simulationFrameTimeMilliseconds[currentFrame] + m_physicsFrameTimeMilliseconds[currentFrame]) / m_scene.MinFrameTicks; // ORIGINAL code commented out until we have time to add our own sb[0].StatID = (uint) Stats.TimeDilation; sb[0].StatValue = (Single.IsNaN(m_timeDilation)) ? 0.1f : m_timeDilation ; //((((m_timeDilation + (0.10f * statsUpdateFactor)) /10) / statsUpdateFactor)); sb[1].StatID = (uint) Stats.SimFPS; sb[1].StatValue = reportedFPS / m_statsUpdateFactor; sb[2].StatID = (uint) Stats.PhysicsFPS; sb[2].StatValue = physfps / m_statsUpdateFactor; sb[3].StatID = (uint) Stats.AgentUpdates; sb[3].StatValue = (m_agentUpdates / m_statsUpdateFactor); sb[4].StatID = (uint) Stats.Agents; sb[4].StatValue = m_rootAgents; sb[5].StatID = (uint) Stats.ChildAgents; sb[5].StatValue = m_childAgents; sb[6].StatID = (uint) Stats.TotalPrim; sb[6].StatValue = m_numPrim; sb[7].StatID = (uint) Stats.ActivePrim; sb[7].StatValue = m_activePrim; // ORIGINAL code commented out until we have time to add our own // statistics to the statistics window sb[8].StatID = (uint)Stats.FrameMS; //sb[8].StatValue = m_frameMS / framesUpdated; sb[8].StatValue = (float) totalSumFrameTime / m_numberFramesStored; sb[9].StatID = (uint)Stats.NetMS; //sb[9].StatValue = m_netMS / framesUpdated; sb[9].StatValue = (float) networkSumFrameTime / m_numberFramesStored; sb[10].StatID = (uint)Stats.PhysicsMS; //sb[10].StatValue = m_physicsMS / framesUpdated; sb[10].StatValue = (float) physicsSumFrameTime / m_numberFramesStored; sb[11].StatID = (uint)Stats.ImageMS ; sb[11].StatValue = m_imageMS / framesUpdated; sb[12].StatID = (uint)Stats.OtherMS; //sb[12].StatValue = m_otherMS / framesUpdated; sb[12].StatValue = (float) simulationSumFrameTime / m_numberFramesStored; sb[13].StatID = (uint)Stats.InPacketsPerSecond; sb[13].StatValue = (float) m_inPacketsPerSecond; sb[14].StatID = (uint)Stats.OutPacketsPerSecond; sb[14].StatValue = (float) m_outPacketsPerSecond; sb[15].StatID = (uint)Stats.UnAckedBytes; sb[15].StatValue = m_unAckedBytes; sb[16].StatID = (uint)Stats.AgentMS; sb[16].StatValue = m_agentMS / framesUpdated; sb[17].StatID = (uint)Stats.PendingDownloads; sb[17].StatValue = m_pendingDownloads; sb[18].StatID = (uint)Stats.PendingUploads; sb[18].StatValue = m_pendingUploads; sb[19].StatID = (uint)Stats.ActiveScripts; sb[19].StatValue = m_activeScripts; sb[20].StatID = (uint)Stats.ScriptLinesPerSecond; sb[20].StatValue = m_scriptLinesPerSecond / m_statsUpdateFactor; sb[21].StatID = (uint)Stats.SimSpareMs; sb[21].StatValue = m_spareMS / framesUpdated; // Current ratio between the sum of physics and sim rate, and the // minimum time to run a scene's frame sb[22].StatID = (uint)Stats.FrameDilation; sb[22].StatValue = frameDilation; // Current number of users currently attemptint to login to region sb[23].StatID = (uint)Stats.UsersLoggingIn; sb[23].StatValue = m_usersLoggingIn.Count; // Total number of geometric primitives in the scene sb[24].StatID = (uint)Stats.TotalGeoPrim; sb[24].StatValue = m_numGeoPrim; // Total number of mesh objects in the scene sb[25].StatID = (uint)Stats.TotalMesh; sb[25].StatValue = m_numMesh; // Current number of threads that XEngine is using sb[26].StatID = (uint)Stats.ThreadCount; sb[26].StatValue = m_inUseThreads; // Tracks the number of bytes that are received by the server's // UDP network handler sb[27].StatID = (uint)Stats.UDPInRate; sb[27].StatValue = (float) m_inByteRate; // Tracks the number of bytes that are sent by the server's UDP // network handler sb[28].StatID = (uint)Stats.UDPOutRate; sb[28].StatValue = (float) m_outByteRate; // Tracks the number of packets that were received by the // server's UDP network handler, that were unable to be processed sb[29].StatID = (uint)Stats.UDPErrorRate; sb[29].StatValue = (float) m_errorPacketRate; // Track the queue size of the network as a moving average sb[30].StatID = (uint)Stats.NetworkQueueSize; sb[30].StatValue = (float) networkSumQueueSize / m_numberFramesStored; // Current average ping between the server and a subset of its conneced users sb[31].StatID = (uint)Stats.ClientPingAvg; sb[31].StatValue = (float) m_clientPing; for (int i = 0; i < m_statisticArraySize; i++) { lastReportedSimStats[i] = sb[i].StatValue; } SimStats simStats = new SimStats( ReportingRegion.RegionLocX, ReportingRegion.RegionLocY, regionFlags, (uint)m_objectCapacity, rb, sb, m_scene.RegionInfo.originRegionID); handlerSendStatResult = OnSendStatsResult; if (handlerSendStatResult != null) { handlerSendStatResult(simStats); } // Extra statistics that aren't currently sent to clients lock (m_lastReportedExtraSimStats) { m_lastReportedExtraSimStats[LastReportedObjectUpdateStatName] = m_objectUpdates / m_statsUpdateFactor; m_lastReportedExtraSimStats[SlowFramesStat.ShortName] = (float)SlowFramesStat.Value; Dictionary<string, float> physicsStats = m_scene.PhysicsScene.GetStats(); if (physicsStats != null) { foreach (KeyValuePair<string, float> tuple in physicsStats) { // FIXME: An extremely dirty hack to divide MS stats per frame rather than per second // Need to change things so that stats source can indicate whether they are per second or // per frame. if (tuple.Key.EndsWith("MS")) m_lastReportedExtraSimStats[tuple.Key] = tuple.Value / framesUpdated; else m_lastReportedExtraSimStats[tuple.Key] = tuple.Value / m_statsUpdateFactor; } } } ResetValues(); } } private void ResetValues() { // Reset the number of frames that the physics library has // processed since the last stats report m_numberPhysicsFrames = 0; m_timeDilation = 0; m_fps = 0; m_pfps = 0; m_agentUpdates = 0; m_objectUpdates = 0; //m_inPacketsPerSecond = 0; //m_outPacketsPerSecond = 0; m_unAckedBytes = 0; m_scriptLinesPerSecond = 0; m_frameMS = 0; m_agentMS = 0; m_netMS = 0; m_physicsMS = 0; m_imageMS = 0; m_otherMS = 0; m_spareMS = 0; //Ckrinke This variable is not used, so comment to remove compiler warning until it is used. //Ckrinke m_scriptMS = 0; } # region methods called from Scene // The majority of these functions are additive // so that you can easily change the amount of // seconds in between sim stats updates public void AddTimeDilation(float td) { //float tdsetting = td; //if (tdsetting > 1.0f) //tdsetting = (tdsetting - (tdsetting - 0.91f)); //if (tdsetting < 0) //tdsetting = 0.0f; m_timeDilation = td; } internal void CheckStatSanity() { if (m_rootAgents < 0 || m_childAgents < 0) { handlerStatsIncorrect = OnStatsIncorrect; if (handlerStatsIncorrect != null) { handlerStatsIncorrect(); } } if (m_rootAgents == 0 && m_childAgents == 0) { m_unAckedBytes = 0; } } public void AddFPS(int frames) { m_fps += frames; } public void AddPhysicsFPS(float frames) { m_pfps += frames; } public void AddObjectUpdates(int numUpdates) { m_objectUpdates += numUpdates; } public void AddAgentUpdates(int numUpdates) { m_agentUpdates += numUpdates; } public void AddInPackets(int numPackets) { m_inPacketsPerSecond = numPackets; } public void AddOutPackets(int numPackets) { m_outPacketsPerSecond = numPackets; } public void AddunAckedBytes(int numBytes) { m_unAckedBytes += numBytes; if (m_unAckedBytes < 0) m_unAckedBytes = 0; } public void addFrameMS(int ms) { m_frameMS += ms; // At the moment, we'll only report if a frame is over 120% of target, since commonly frames are a bit // longer than ideal due to the inaccuracy of the Sleep in Scene.Update() (which in itself is a concern). if (ms > SlowFramesStatReportThreshold) SlowFramesStat.Value++; } public void AddSpareMS(int ms) { m_spareMS += ms; } public void addNetMS(int ms) { m_netMS += ms; } public void addAgentMS(int ms) { m_agentMS += ms; } public void addPhysicsMS(int ms) { m_physicsMS += ms; } public void addImageMS(int ms) { m_imageMS += ms; } public void addOtherMS(int ms) { m_otherMS += ms; } public void addPhysicsFrame(int frames) { // Add the number of physics frames to the correct total physics // frames m_numberPhysicsFrames += frames; } public void addFrameTimeMilliseconds(double total, double simulation, double physics) { // Save the frame times from the current frame into the appropriate // arrays m_totalFrameTimeMilliseconds[m_nextLocation] = total; m_simulationFrameTimeMilliseconds[m_nextLocation] = simulation; m_physicsFrameTimeMilliseconds[m_nextLocation] = physics; // Update to the next location in the list m_nextLocation++; // Since the list will begin to overwrite the oldest frame values // first, the next location needs to loop back to the beginning of the // list whenever it reaches the end m_nextLocation = m_nextLocation % m_numberFramesStored; } public void AddPendingDownloads(int count) { m_pendingDownloads += count; if (m_pendingDownloads < 0) m_pendingDownloads = 0; //m_log.InfoFormat("[stats]: Adding {0} to pending downloads to make {1}", count, m_pendingDownloads); } public void addScriptLines(int count) { m_scriptLinesPerSecond += count; } public void AddPacketsStats(double inPacketRate, double outPacketRate, int unAckedBytes, double inByteRate, double outByteRate, double errorPacketRate) { m_inPacketsPerSecond = inPacketRate; m_outPacketsPerSecond = outPacketRate; AddunAckedBytes(unAckedBytes); m_inByteRate = inByteRate; m_outByteRate = outByteRate; m_errorPacketRate = errorPacketRate; } public void AddPacketProcessStats(double processTime, int queueSize) { // Store the time that it took to process the most recent UDP // message and the size of the UDP network in queue m_networkFrameTimeMilliseconds[m_netLocation] = processTime; m_networkQueueSize[m_netLocation] = queueSize; m_netLocation++; // Since the list will begin to overwrite the oldest frame values // first, the network location needs to loop back to the beginning // of the list whenever it reaches the end m_netLocation = m_netLocation % m_numberFramesStored; } public void AddUserLoggingIn(string name) { // Check that the name does not exist in the list of users logging // in, this prevents the case of the user disconnecting while // logging in and reconnecting from adding multiple instances of // the user if (!m_usersLoggingIn.Contains(name)) { // Add the name of the user attempting to connect to the server // to our list, this will allow tracking of which users have // succesfully updated the texture of their avatar m_usersLoggingIn.Add(name); } } public void RemoveUserLoggingIn(string name) { // Remove the user that has finished logging into the server, if // the name doesn't exist no change to the array list occurs m_usersLoggingIn.Remove(name); } public void SetThreadCount(int inUseThreads) { // Save the new number of threads to our member variable to send to // the extra stats collector m_inUseThreads = inUseThreads; } public void AddClientPingTime(double pingTime, int subset) { // Keep track of the total ping time from various clients m_totalPingTime += pingTime; // Increment the number of clients pinged and check to see if we've reached // the desired number of clients m_clientPingCount++; if (m_clientPingCount >= subset) { // Calculate the ping average between the server and its connected clients m_clientPing = m_totalPingTime / (double)m_clientPingCount; // Reset the client count and the total ping time m_clientPingCount = 0; m_totalPingTime = 0; } } public void AddNewAgent(string name, string ipAddress, string timestamp) { // Report the new agent being added to the additional stats collector, // if the extra stats collector exists if (StatsManager.SimExtraStats != null) StatsManager.SimExtraStats.AddAgent(name, ipAddress, timestamp); } public void RemoveAgent(string name) { // Report the agent being removed to the additional stats collector, // if the extra stats collector exists if (StatsManager.SimExtraStats != null) StatsManager.SimExtraStats.RemoveAgent(name); } #endregion public Dictionary<string, float> GetExtraSimStats() { lock (m_lastReportedExtraSimStats) return new Dictionary<string, float>(m_lastReportedExtraSimStats); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Microsoft.VisualBasic.CompilerServices; using Xunit; namespace Microsoft.VisualBasic.CompilerServices.Tests { public class OperatorsTests { public static IEnumerable<object[]> AddObject_Idempotent_TestData() { // byte + primitives. yield return new object[] { (byte)1, (byte)2, (byte)3 }; yield return new object[] { (byte)2, (sbyte)2, (short)4 }; yield return new object[] { (byte)3, (ushort)2, (ushort)5 }; yield return new object[] { (byte)4, (short)2, (short)6 }; yield return new object[] { (byte)5, (uint)2, (uint)7 }; yield return new object[] { (byte)6, 2, 8 }; yield return new object[] { (byte)7, (long)2, (long)9 }; yield return new object[] { (byte)8, (ulong)2, (ulong)10 }; yield return new object[] { (byte)9, (float)2, (float)11 }; yield return new object[] { (byte)10, (double)2, (double)12 }; yield return new object[] { (byte)11, (decimal)2, (decimal)13 }; yield return new object[] { (byte)12, "2", (double)14 }; yield return new object[] { (byte)13, true, (short)12 }; yield return new object[] { (byte)14, null, (byte)14 }; yield return new object[] { (byte)15, byte.MaxValue, (short)270 }; // sbyte + primitives. yield return new object[] { (sbyte)1, (sbyte)2, (sbyte)3 }; yield return new object[] { (sbyte)3, (ushort)2, 5 }; yield return new object[] { (sbyte)4, (short)2, (short)6 }; yield return new object[] { (sbyte)5, (uint)2, (long)7 }; yield return new object[] { (sbyte)6, 2, 8 }; yield return new object[] { (sbyte)7, (long)2, (long)9 }; yield return new object[] { (sbyte)9, (float)2, (float)11 }; yield return new object[] { (sbyte)8, (ulong)2, (decimal)10 }; yield return new object[] { (sbyte)10, (double)2, (double)12 }; yield return new object[] { (sbyte)11, (decimal)2, (decimal)13 }; yield return new object[] { (sbyte)12, "2", (double)14 }; yield return new object[] { (sbyte)13, true, (sbyte)12 }; yield return new object[] { (sbyte)14, null, (sbyte)14 }; yield return new object[] { (sbyte)15, sbyte.MaxValue, (short)142 }; // ushort + primitives. yield return new object[] { (ushort)3, (ushort)2, (ushort)5 }; yield return new object[] { (ushort)4, (short)2, 6 }; yield return new object[] { (ushort)5, (uint)2, (uint)7 }; yield return new object[] { (ushort)6, 2, 8 }; yield return new object[] { (ushort)7, (long)2, (long)9 }; yield return new object[] { (ushort)8, (ulong)2, (ulong)10 }; yield return new object[] { (ushort)9, (float)2, (float)11 }; yield return new object[] { (ushort)10, (double)2, (double)12 }; yield return new object[] { (ushort)11, (decimal)2, (decimal)13 }; yield return new object[] { (ushort)12, "2", (double)14 }; yield return new object[] { (ushort)13, true, 12 }; yield return new object[] { (ushort)14, null, (ushort)14 }; yield return new object[] { (ushort)15, ushort.MaxValue, 65550 }; // short + primitives. yield return new object[] { (short)4, (short)2, (short)6 }; yield return new object[] { (short)5, (uint)2, (long)7 }; yield return new object[] { (short)6, 2, 8 }; yield return new object[] { (short)7, (long)2, (long)9 }; yield return new object[] { (short)8, (ulong)2, (decimal)10 }; yield return new object[] { (short)9, (float)2, (float)11 }; yield return new object[] { (short)10, (double)2, (double)12 }; yield return new object[] { (short)11, (decimal)2, (decimal)13 }; yield return new object[] { (short)12, "2", (double)14 }; yield return new object[] { (short)13, true, (short)12 }; yield return new object[] { (short)14, null, (short)14 }; yield return new object[] { (short)15, short.MaxValue, 32782 }; // uint + primitives. yield return new object[] { (uint)4, (short)2, (long)6 }; yield return new object[] { (uint)5, (uint)2, (uint)7 }; yield return new object[] { (uint)6, 2, (long)8 }; yield return new object[] { (uint)7, (ulong)2, (ulong)9 }; yield return new object[] { (uint)8, (long)2, (long)10 }; yield return new object[] { (uint)9, (float)2, (float)11 }; yield return new object[] { (uint)10, (double)2, (double)12 }; yield return new object[] { (uint)11, (decimal)2, (decimal)13 }; yield return new object[] { (uint)12, "2", (double)14 }; yield return new object[] { (uint)13, true, (long)12 }; yield return new object[] { (uint)14, null, (uint)14 }; yield return new object[] { (uint)15, uint.MaxValue, 4294967310 }; // int + primitives. yield return new object[] { 6, 2, 8 }; yield return new object[] { 7, (ulong)2, (decimal)9 }; yield return new object[] { 8, (long)2, (long)10 }; yield return new object[] { 9, (float)2, (float)11 }; yield return new object[] { 10, (double)2, (double)12 }; yield return new object[] { 11, (decimal)2, (decimal)13 }; yield return new object[] { 12, "2", (double)14 }; yield return new object[] { 13, true, 12 }; yield return new object[] { 14, null, 14 }; yield return new object[] { 15, int.MaxValue, (long)2147483662 }; // ulong + primitives. yield return new object[] { (ulong)7, (ulong)2, (ulong)9 }; yield return new object[] { (ulong)8, (long)2, (decimal)10 }; yield return new object[] { (ulong)9, (float)2, (float)11 }; yield return new object[] { (ulong)10, (double)2, (double)12 }; yield return new object[] { (ulong)11, (decimal)2, (decimal)13 }; yield return new object[] { (ulong)12, "2", (double)14 }; yield return new object[] { (ulong)13, true, (decimal)12 }; yield return new object[] { (ulong)14, null, (ulong)14 }; yield return new object[] { (ulong)15, ulong.MaxValue, decimal.Parse("18446744073709551630") }; // long + primitives. yield return new object[] { (long)8, (long)2, (long)10 }; yield return new object[] { (long)9, (float)2, (float)11 }; yield return new object[] { (long)10, (double)2, (double)12 }; yield return new object[] { (long)11, (decimal)2, (decimal)13 }; yield return new object[] { (long)12, "2", (double)14 }; yield return new object[] { (long)13, true, (long)12 }; yield return new object[] { (long)14, null, (long)14 }; yield return new object[] { (long)15, long.MaxValue, decimal.Parse("9223372036854775822") }; // float + primitives yield return new object[] { (float)9, (float)2, (float)11 }; yield return new object[] { (float)10, (double)2, (double)12 }; yield return new object[] { (float)11, (decimal)2, (float)13 }; yield return new object[] { (float)12, "2", (double)14 }; yield return new object[] { (float)13, true, (float)12 }; yield return new object[] { (float)14, null, (float)14 }; yield return new object[] { (float)15, float.PositiveInfinity, float.PositiveInfinity }; // double + primitives yield return new object[] { (double)10, (double)2, (double)12 }; yield return new object[] { (double)11, (decimal)2, (double)13 }; yield return new object[] { (double)12, "2", (double)14 }; yield return new object[] { (double)13, true, (double)12 }; yield return new object[] { (double)14, null, (double)14 }; yield return new object[] { (double)15, double.PositiveInfinity, double.PositiveInfinity }; // decimal + primitives yield return new object[] { (decimal)11, (decimal)2, (decimal)13 }; yield return new object[] { (decimal)12, "2", (double)14 }; yield return new object[] { (decimal)13, true, (decimal)12 }; yield return new object[] { (decimal)14, null, (decimal)14 }; // string + primitives yield return new object[] { "1", "2", "12" }; yield return new object[] { "2", '2', "22" }; yield return new object[] { "3", true, (double)2 }; yield return new object[] { "5", null, "5" }; // bool + primitives yield return new object[] { true, "2", (double)1 }; yield return new object[] { true, true, (short)-2 }; yield return new object[] { true, false, (short)-1 }; yield return new object[] { true, null, (short)-1 }; // char + primitives yield return new object[] { 'a', null, "a\0" }; // null + null yield return new object[] { null, null, 0 }; } [Theory] [MemberData(nameof(AddObject_Idempotent_TestData))] [ActiveIssue(21682, TargetFrameworkMonikers.UapAot)] public void AddObject_Convertible_ReturnsExpected(object left, object right, object expected) { Assert.Equal(expected, Operators.AddObject(left, right)); if (expected is string expectedString) { string reversed = new string(expectedString.Reverse().ToArray()); Assert.Equal(reversed, Operators.AddObject(right, left)); } else { Assert.Equal(expected, Operators.AddObject(right, left)); } } [Fact] public void AddObject_DateString_ReturnsExpected() { string expected = Assert.IsType<string>(Operators.AddObject("String", new DateTime(2017, 10, 10))); Assert.StartsWith("String", expected); Assert.Contains("17", expected); } [Fact] public void AddObject_DateDate_ReturnsExpected() { string expected = Assert.IsType<string>(Operators.AddObject(new DateTime(2018, 10, 10), new DateTime(2017, 10, 10))); Assert.Contains("17", expected); Assert.Contains("18", expected); } [Fact] public void AddObject_DateNull_ReturnsExpected() { string expected = Assert.IsType<string>(Operators.AddObject(new DateTime(2018, 10, 10), null)); Assert.Contains("18", expected); } [Fact] public void AddObject_NullDate_ReturnsExpected() { string expected = Assert.IsType<string>(Operators.AddObject(null, new DateTime(2018, 10, 10))); Assert.Contains("18", expected); } [Fact] public void AddObject_StringDate_ReturnsExpected() { string expected = Assert.IsType<string>(Operators.AddObject(new DateTime(2017, 10, 10), "String")); Assert.EndsWith("String", expected); Assert.Contains("17", expected); } [Fact] public void AddObject_FloatDoubleDecimalOverflow_ReturnsMax() { Assert.Equal(float.MaxValue, Operators.AddObject((float)15, float.MaxValue)); Assert.Equal(double.MaxValue, Operators.AddObject((double)15, double.MaxValue)); Assert.NotEqual(decimal.MaxValue, Operators.AddObject((decimal)15, decimal.MaxValue)); } public static IEnumerable<object[]> IncompatibleAddObject_TestData() { yield return new object[] { 1, '2' }; yield return new object[] { 2, DBNull.Value }; yield return new object[] { '3', new object() }; } [Theory] [MemberData(nameof(IncompatibleAddObject_TestData))] [ActiveIssue(21682, TargetFrameworkMonikers.UapAot)] public void AddObject_Incompatible_ThrowsInvalidCastException(object left, object right) { Assert.Throws<InvalidCastException>(() => Operators.AddObject(left, right)); Assert.Throws<InvalidCastException>(() => Operators.AddObject(right, left)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Net.Security; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; namespace System.Net.Http { internal sealed class ManagedHandler : HttpMessageHandler { // Configuration settings private bool _useCookies = HttpHandlerDefaults.DefaultUseCookies; private CookieContainer _cookieContainer; private ClientCertificateOption _clientCertificateOptions = HttpHandlerDefaults.DefaultClientCertificateOption; private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression; private bool _useProxy = HttpHandlerDefaults.DefaultUseProxy; private IWebProxy _proxy; private ICredentials _defaultProxyCredentials; private bool _preAuthenticate = HttpHandlerDefaults.DefaultPreAuthenticate; private bool _useDefaultCredentials = HttpHandlerDefaults.DefaultUseDefaultCredentials; private ICredentials _credentials; private bool _allowAutoRedirect = HttpHandlerDefaults.DefaultAutomaticRedirection; private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections; private int _maxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeadersLength; private int _maxConnectionsPerServer = HttpHandlerDefaults.DefaultMaxConnectionsPerServer; private X509CertificateCollection _clientCertificates; private Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> _serverCertificateCustomValidationCallback; private bool _checkCertificateRevocationList = false; private SslProtocols _sslProtocols = SslProtocols.None; private IDictionary<string, object> _properties; private HttpMessageHandler _handler; private bool _disposed; private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(nameof(ManagedHandler)); } } private void CheckDisposedOrStarted() { CheckDisposed(); if (_handler != null) { throw new InvalidOperationException(SR.net_http_operation_started); } } public bool SupportsAutomaticDecompression => true; public bool SupportsProxy => true; public bool SupportsRedirectConfiguration => true; public bool UseCookies { get => _useCookies; set { CheckDisposedOrStarted(); _useCookies = value; } } public CookieContainer CookieContainer { get => _cookieContainer ?? (_cookieContainer = new CookieContainer()); set { CheckDisposedOrStarted(); _cookieContainer = value; } } public ClientCertificateOption ClientCertificateOptions { get => _clientCertificateOptions; set { if (value != ClientCertificateOption.Manual && value != ClientCertificateOption.Automatic) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _clientCertificateOptions = value; } } public DecompressionMethods AutomaticDecompression { get => _automaticDecompression; set { CheckDisposedOrStarted(); _automaticDecompression = value; } } public bool UseProxy { get => _useProxy; set { CheckDisposedOrStarted(); _useProxy = value; } } public IWebProxy Proxy { get => _proxy; set { CheckDisposedOrStarted(); _proxy = value; } } public ICredentials DefaultProxyCredentials { get => _defaultProxyCredentials; set { CheckDisposedOrStarted(); _defaultProxyCredentials = value; } } public bool PreAuthenticate { get => _preAuthenticate; set { CheckDisposedOrStarted(); _preAuthenticate = value; } } public bool UseDefaultCredentials { get => _useDefaultCredentials; set { CheckDisposedOrStarted(); _useDefaultCredentials = value; } } public ICredentials Credentials { get => _credentials; set { CheckDisposedOrStarted(); _credentials = value; } } public bool AllowAutoRedirect { get => _allowAutoRedirect; set { CheckDisposedOrStarted(); _allowAutoRedirect = value; } } public int MaxAutomaticRedirections { get => _maxAutomaticRedirections; set { if (value < 1) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxAutomaticRedirections = value; } } public int MaxConnectionsPerServer { get => _maxConnectionsPerServer; set { if (value < 1) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxConnectionsPerServer = value; } } public int MaxResponseHeadersLength { get => _maxResponseHeadersLength; set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxResponseHeadersLength = value; } } public X509CertificateCollection ClientCertificates { get { if (_clientCertificateOptions != ClientCertificateOption.Manual) { throw new InvalidOperationException(SR.Format(SR.net_http_invalid_enable_first, nameof(ClientCertificateOptions), nameof(ClientCertificateOption.Manual))); } return _clientCertificates ?? (_clientCertificates = new X509Certificate2Collection()); } } public Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ServerCertificateCustomValidationCallback { get => _serverCertificateCustomValidationCallback; set { CheckDisposedOrStarted(); _serverCertificateCustomValidationCallback = value; } } public bool CheckCertificateRevocationList { get => _checkCertificateRevocationList; set { CheckDisposedOrStarted(); _checkCertificateRevocationList = value; } } public SslProtocols SslProtocols { get => _sslProtocols; set { SecurityProtocol.ThrowOnNotAllowed(value, allowNone: true); CheckDisposedOrStarted(); _sslProtocols = value; } } public IDictionary<string, object> Properties => _properties ?? (_properties = new Dictionary<string, object>()); protected override void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; _handler?.Dispose(); } base.Dispose(disposing); } private HttpMessageHandler SetupHandlerChain() { HttpMessageHandler handler = new HttpConnectionHandler( _clientCertificates, _serverCertificateCustomValidationCallback, _checkCertificateRevocationList, _sslProtocols); if (_useProxy && _proxy != null) { handler = new HttpProxyConnectionHandler(_proxy, handler); } if (_credentials != null) { handler = new AuthenticationHandler(_preAuthenticate, _credentials, handler); } if (_useCookies) { handler = new CookieHandler(CookieContainer, handler); } if (_allowAutoRedirect) { handler = new AutoRedirectHandler(_maxAutomaticRedirections, handler); } if (_automaticDecompression != DecompressionMethods.None) { handler = new DecompressionHandler(_automaticDecompression, handler); } if (Interlocked.CompareExchange(ref _handler, handler, null) == null) { return handler; } else { handler.Dispose(); return _handler; } } protected internal override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { CheckDisposed(); HttpMessageHandler handler = _handler ?? SetupHandlerChain(); return handler.SendAsync(request, cancellationToken); } } }
using System; using System.Drawing; using System.IO; using Xunit; using Medo.Drawing; using System.Reflection; namespace Tests.Medo.Drawing { public class SimplePngImageTests { [Fact(DisplayName = "SimplePngImage: Color Basic")] public void ColorBasic() { var bmp = new SimplePngImage(2, 3); Assert.Equal(2, bmp.Width); Assert.Equal(3, bmp.Height); bmp.SetPixel(0, 0, Color.Red); bmp.SetPixel(0, 1, Color.Green); bmp.SetPixel(0, 2, Color.Blue); bmp.SetPixel(1, 0, Color.White); bmp.SetPixel(1, 1, Color.Black); bmp.SetPixel(1, 2, Color.Purple); Assert.Equal(Color.Red, bmp.GetPixel(0, 0)); Assert.Equal(Color.Green, bmp.GetPixel(0, 1)); Assert.Equal(Color.Blue, bmp.GetPixel(0, 2)); Assert.Equal(Color.White, bmp.GetPixel(1, 0)); Assert.Equal(Color.Black, bmp.GetPixel(1, 1)); Assert.Equal(Color.Purple, bmp.GetPixel(1, 2)); //bmp.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "png-color-basic.png")); var memStream = new MemoryStream(); bmp.Save(memStream); Assert.Equal(76, memStream.Length); Assert.Equal("89504E470D0A1A0A0000000D4948445200000002000000030802000000368849D60000001349444154789C63F8CFC0F0FF3F9068608080FF0D0C0D00D6C212940000000049454E44AE426082", BitConverter.ToString(memStream.ToArray()).Replace("-", "")); } [Fact(DisplayName = "SimplePngImage: Color Transparency")] public void ColorAlpha() { var bmp = new SimplePngImage(2, 3); Assert.Equal(2, bmp.Width); Assert.Equal(3, bmp.Height); bmp.SetPixel(0, 0, Color.Red); bmp.SetPixel(0, 1, Color.Green); bmp.SetPixel(0, 2, Color.Blue); bmp.SetPixel(1, 0, Color.White); bmp.SetPixel(1, 1, Color.Black); bmp.SetPixel(1, 2, Color.FromArgb(128, Color.Purple)); Assert.Equal(Color.Red, bmp.GetPixel(0, 0)); Assert.Equal(Color.Green, bmp.GetPixel(0, 1)); Assert.Equal(Color.Blue, bmp.GetPixel(0, 2)); Assert.Equal(Color.White, bmp.GetPixel(1, 0)); Assert.Equal(Color.Black, bmp.GetPixel(1, 1)); Assert.Equal(Color.FromArgb(128, Color.Purple), bmp.GetPixel(1, 2)); //bmp.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "png-color-transparency.png")); var memStream = new MemoryStream(); bmp.Save(memStream); Assert.Equal(80, memStream.Length); Assert.Equal("89504E470D0A1A0A0000000D4948445200000002000000030806000000B9EADE810000001749444154789C63F8CFC0F01F0418181A18800404FF6F6068680000700275140000000049454E44AE426082", BitConverter.ToString(memStream.ToArray()).Replace("-", "")); } [Fact(DisplayName = "SimplePngImage: Mono Basic")] public void MonoBasic() { var bmp = new SimplePngImage(2, 2); Assert.Equal(2, bmp.Width); Assert.Equal(2, bmp.Height); bmp.SetPixel(0, 0, Color.Black); bmp.SetPixel(0, 1, Color.DarkGray); bmp.SetPixel(1, 0, Color.Gray); bmp.SetPixel(1, 1, Color.White); Assert.Equal(Color.Black, bmp.GetPixel(0, 0)); Assert.Equal(Color.DarkGray, bmp.GetPixel(0, 1)); Assert.Equal(Color.Gray, bmp.GetPixel(1, 0)); Assert.Equal(Color.White, bmp.GetPixel(1, 1)); //bmp.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "png-mono-basic.png")); var memStream = new MemoryStream(); bmp.Save(memStream); Assert.Equal(67, memStream.Length); Assert.Equal("89504E470D0A1A0A0000000D494844520000000200000002080000000057DD52F80000000A49444154789C6360686058F91F00384FDB7F0000000049454E44AE426082", BitConverter.ToString(memStream.ToArray()).Replace("-", "")); } [Fact(DisplayName = "SimplePngImage: Mono Transparency")] public void MonoAlpha() { var bmp = new SimplePngImage(2, 2); Assert.Equal(2, bmp.Width); Assert.Equal(2, bmp.Height); bmp.SetPixel(0, 0, Color.Black); bmp.SetPixel(0, 1, Color.DarkGray); bmp.SetPixel(1, 0, Color.Gray); bmp.SetPixel(1, 1, Color.FromArgb(192, Color.White)); Assert.Equal(Color.Black, bmp.GetPixel(0, 0)); Assert.Equal(Color.DarkGray, bmp.GetPixel(0, 1)); Assert.Equal(Color.Gray, bmp.GetPixel(1, 0)); Assert.Equal(Color.FromArgb(192, Color.White), bmp.GetPixel(1, 1)); //bmp.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "png-mono-transparency.png")); var memStream = new MemoryStream(); bmp.Save(memStream); Assert.Equal(71, memStream.Length); Assert.Equal("89504E470D0A1A0A0000000D4948445200000002000000020804000000D8BFC5AF0000000E49444154789C6360F8DFF09F61E5FFFF0700F55FDCD50000000049454E44AE426082", BitConverter.ToString(memStream.ToArray()).Replace("-", "")); } [Fact(DisplayName = "SimplePngImage: Clone")] public void Clone() { var original = new SimplePngImage(2, 3); original.SetPixel(0, 0, Color.Red); original.SetPixel(0, 1, Color.Green); original.SetPixel(0, 2, Color.Blue); original.SetPixel(1, 0, Color.White); original.SetPixel(1, 1, Color.Black); original.SetPixel(1, 2, Color.Purple); var bmp = original.Clone(); original.SetPixel(1, 2, Color.Cyan); Assert.Equal(Color.Red, bmp.GetPixel(0, 0)); Assert.Equal(Color.Green, bmp.GetPixel(0, 1)); Assert.Equal(Color.Blue, bmp.GetPixel(0, 2)); Assert.Equal(Color.White, bmp.GetPixel(1, 0)); Assert.Equal(Color.Black, bmp.GetPixel(1, 1)); Assert.Equal(Color.Purple, bmp.GetPixel(1, 2)); //bmp.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "png-clone.png")); var memStream = new MemoryStream(); bmp.Save(memStream); Assert.Equal(76, memStream.Length); Assert.Equal("89504E470D0A1A0A0000000D4948445200000002000000030802000000368849D60000001349444154789C63F8CFC0F0FF3F9068608080FF0D0C0D00D6C212940000000049454E44AE426082", BitConverter.ToString(memStream.ToArray()).Replace("-", "")); } [Fact(DisplayName = "SimplePngImage: Save/Open 24-bit")] public void SaveOpen24() { var bmp = new SimplePngImage(2, 3); bmp.SetPixel(0, 0, Color.Red); bmp.SetPixel(0, 1, Color.Green); bmp.SetPixel(0, 2, Color.Blue); bmp.SetPixel(1, 0, Color.White); bmp.SetPixel(1, 1, Color.Black); bmp.SetPixel(1, 2, Color.Purple); var memStream = new MemoryStream(); bmp.Save(memStream); memStream.Position = 0; var bmp2 = new SimplePngImage(memStream); Assert.Equal(Color.Red.ToArgb(), bmp2.GetPixel(0, 0).ToArgb()); Assert.Equal(Color.Green.ToArgb(), bmp2.GetPixel(0, 1).ToArgb()); Assert.Equal(Color.Blue.ToArgb(), bmp2.GetPixel(0, 2).ToArgb()); Assert.Equal(Color.White.ToArgb(), bmp2.GetPixel(1, 0).ToArgb()); Assert.Equal(Color.Black.ToArgb(), bmp2.GetPixel(1, 1).ToArgb()); Assert.Equal(Color.Purple.ToArgb(), bmp2.GetPixel(1, 2).ToArgb()); } [Fact(DisplayName = "SimplePngImage: Save/Open 32-bit")] public void SaveOpen32() { var bmp = new SimplePngImage(2, 3); bmp.SetPixel(0, 0, Color.Red); bmp.SetPixel(0, 1, Color.Green); bmp.SetPixel(0, 2, Color.Blue); bmp.SetPixel(1, 0, Color.White); bmp.SetPixel(1, 1, Color.Black); bmp.SetPixel(1, 2, Color.FromArgb(128, Color.Purple)); var memStream = new MemoryStream(); bmp.Save(memStream); memStream.Position = 0; var bmp2 = new SimplePngImage(memStream); Assert.Equal(Color.Red.ToArgb(), bmp2.GetPixel(0, 0).ToArgb()); Assert.Equal(Color.Green.ToArgb(), bmp2.GetPixel(0, 1).ToArgb()); Assert.Equal(Color.Blue.ToArgb(), bmp2.GetPixel(0, 2).ToArgb()); Assert.Equal(Color.White.ToArgb(), bmp2.GetPixel(1, 0).ToArgb()); Assert.Equal(Color.Black.ToArgb(), bmp2.GetPixel(1, 1).ToArgb()); Assert.Equal(Color.FromArgb(128, Color.Purple).ToArgb(), bmp2.GetPixel(1, 2).ToArgb()); } [Theory(DisplayName = "SimplePngImage: Validate Colors 2")] [InlineData("Example2-Color32.png")] [InlineData("Example2-Color24.png")] [InlineData("Example2-Color8.png")] [InlineData("Example2-Color4.png")] [InlineData("Example2-Color2.png")] [InlineData("Example2-Color1.png")] public void ValidateColor2(string fileName) { var bmpOriginal = GetExampleImageColor2(); var bmp = new SimplePngImage(GetResourceStreamBytes(fileName)); //bmp.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "png-" + fileName)); Assert.True(AreImagesSame(bmp, bmpOriginal)); } [Theory(DisplayName = "SimplePngImage: Validate Colors 4")] [InlineData("Example4-Color32.png")] [InlineData("Example4-Color24.png")] [InlineData("Example4-Color8.png")] [InlineData("Example4-Color4.png")] [InlineData("Example4-Color2.png")] public void ValidateColor4(string fileName) { var bmpOriginal = GetExampleImageColor4(); var bmp = new SimplePngImage(GetResourceStreamBytes(fileName)); //bmp.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "png-" + fileName)); Assert.True(AreImagesSame(bmp, bmpOriginal)); } [Theory(DisplayName = "SimplePngImage: Validate Colors 16")] [InlineData("Example16-Color32.png")] [InlineData("Example16-Color24.png")] [InlineData("Example16-Color8.png")] [InlineData("Example16-Color4.png")] public void ValidateColor16(string fileName) { var bmpOriginal = GetExampleImageColor16(); var bmp = new SimplePngImage(GetResourceStreamBytes(fileName)); //bmp.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "png-" + fileName)); Assert.True(AreImagesSame(bmp, bmpOriginal)); } [Theory(DisplayName = "SimplePngImage: Validate Colors 64")] [InlineData("Example64-Color32.png")] [InlineData("Example64-Color24.png")] [InlineData("Example64-Color8.png")] public void ValidateColor64(string fileName) { var bmpOriginal = GetExampleImageColor64(); var bmp = new SimplePngImage(GetResourceStreamBytes(fileName)); //bmp.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "png-" + fileName)); Assert.True(AreImagesSame(bmp, bmpOriginal)); } [Theory(DisplayName = "SimplePngImage: Validate Colors 256")] [InlineData("Example256-Color32.png")] [InlineData("Example256-Color24.png")] [InlineData("Example256-Color8.png")] public void ValidateColor256(string fileName) { var bmpOriginal = GetExampleImageColor256(); var bmp = new SimplePngImage(GetResourceStreamBytes(fileName)); //bmp.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "png-" + fileName)); Assert.True(AreImagesSame(bmp, bmpOriginal)); } [Theory(DisplayName = "SimplePngImage: Validate Monochrome 256")] [InlineData("Example256-Mono32.png")] [InlineData("Example256-Mono24.png")] [InlineData("Example256-Mono8.png")] public void ValidateMono256(string fileName) { var bmpOriginal = GetExampleImageMonochrome256(); var bmp = new SimplePngImage(GetResourceStreamBytes(fileName)); //bmp.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "png-" + fileName)); Assert.True(AreImagesSame(bmp, bmpOriginal)); } #region Helper private static Stream GetResourceStreamBytes(string fileName) { return Assembly.GetExecutingAssembly().GetManifestResourceStream("Tests.Medo._Resources.Drawing.SimplePngImage." + fileName); } private static bool AreImagesSame(SimplePngImage image1, SimplePngImage image2) { if (image1.Width != image2.Width) { return false; } if (image1.Height != image2.Height) { return false; } for (var x = 0; x < image1.Width; x++) { for (var y = 0; y < image1.Height; y++) { if (image1.GetPixel(x, y).ToArgb() != image2.GetPixel(x, y).ToArgb()) { return false; } } } return true; } private static SimplePngImage GetExampleImageColor2() { var bmp = new SimplePngImage(8, 8); for (var x = 0; x < 8; x++) { for (var y = 0; y < 8; y++) { bmp.SetPixel(x, y, (x % 2 == y % 2) ? Color.Red : Color.Blue); } } //bmp.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "png-color-2.png")); return bmp; } private static SimplePngImage GetExampleImageColor4() { var bmp = new SimplePngImage(8, 8); for (var x = 0; x < 2; x++) { for (var y = 0; y < 2; y++) { var r = (byte)((7 - x) * 129); var g = (byte)(y * 128); var b = (byte)(((x * 128) & 0xF0) | ((y * 128) >> 4)); for (var i = 0; i < 4; i++) { for (var j = 0; j < 4; j++) { bmp.SetPixel(x * 4 + i, y * 4 + j, Color.FromArgb(r, g, b)); } } } } //bmp.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "png-color-4.png")); return bmp; } private static SimplePngImage GetExampleImageColor16() { var bmp = new SimplePngImage(8, 8); for (var x = 0; x < 4; x++) { for (var y = 0; y < 4; y++) { var r = (byte)((7 - x) * 64); var g = (byte)(y * 64); var b = (byte)(((x * 64) & 0xF0) | ((y * 64) >> 4)); bmp.SetPixel(x * 2 + 0, y * 2 + 0, Color.FromArgb(r, g, b)); bmp.SetPixel(x * 2 + 0, y * 2 + 1, Color.FromArgb(r, g, b)); bmp.SetPixel(x * 2 + 1, y * 2 + 0, Color.FromArgb(r, g, b)); bmp.SetPixel(x * 2 + 1, y * 2 + 1, Color.FromArgb(r, g, b)); } } //bmp.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "png-color-16.png")); return bmp; } private static SimplePngImage GetExampleImageColor64() { var bmp = new SimplePngImage(8, 8); for (var x = 0; x < 8; x++) { for (var y = 0; y < 8; y++) { var r = (byte)((7 - x) * 32); var g = (byte)(y * 32); var b = (byte)(((x * 32) & 0xF0) | ((y * 32) >> 4)); bmp.SetPixel(x, y, Color.FromArgb(r, g, b)); } } //bmp.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "png-color-64.png")); return bmp; } private static SimplePngImage GetExampleImageColor256() { var bmp = new SimplePngImage(16, 16); for (var x = 0; x < 16; x++) { for (var y = 0; y < 16; y++) { var r = (byte)((15 - x) * 16); var g = (byte)(y * 16); var b = (byte)(((x * 16) & 0xF0) | ((y * 16) >> 4)); bmp.SetPixel(x, y, Color.FromArgb(r, g, b)); } } //bmp.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "png-color-256.png")); return bmp; } private static SimplePngImage GetExampleImageMonochrome256() { var bmp = new SimplePngImage(16, 16); for (var x = 0; x < 16; x++) { for (var y = 0; y < 16; y++) { var m = x << 4 | y; bmp.SetPixel(x, y, Color.FromArgb(m, m, m)); } } //bmp.Save(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "png-mono-256.png")); return bmp; } #endregion Helper } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; namespace Astrid.LibGdx { /// <summary> /// Provides TextureAtlasGDX with the ability to read texture atlas files in /// libGDX's format. This is not meant for everyday use. /// </summary> /// <see cref="TextureAtlas" /> internal class GdxTextureAtlasData { private GdxTextureAtlasData(string name) { Name = name;; } public string Name { get; private set; } public static GdxTextureAtlasData Load(string name, Stream stream, string imageFolder, bool flip) { var data = new GdxTextureAtlasData(name); using (var reader = new StreamReader(stream)) { try { Page pageImage = null; while (!reader.EndOfStream) { var line = reader.ReadLine(); if (line == null) break; if (line.Trim().Length == 0) pageImage = null; else if (pageImage == null) { // TODO: This code might not work on all platforms if (!string.IsNullOrEmpty(imageFolder) && !imageFolder.EndsWith("/")) imageFolder += "/"; var textureHandle = imageFolder + line; var width = 0f; var height = 0f; if (ReadTuple(reader) == 2) { // size is only optional for an atlas packed with an old TexturePacker. width = int.Parse(_tuple[0]); height = int.Parse(_tuple[1]); ReadTuple(reader); } ReadTuple(reader); //TextureFilter min = TextureFilter.valueOf(tuple[0]); //TextureFilter max = TextureFilter.valueOf(tuple[1]); String direction = ReadValue(reader); //TextureWrap repeatX = ClampToEdge; //TextureWrap repeatY = ClampToEdge; /* switch(direction) { case "xy": repeatX = Repeat; repeatY = Repeat; break; case "x": repeatX = Repeat; break; case "y": repeatY = Repeat; break; }*/ pageImage = new Page(textureHandle, width, height, false); data._pages.Add(pageImage); } else { var rotate = bool.Parse(ReadValue(reader)); ReadTuple(reader); var left = int.Parse(_tuple[0]); var top = int.Parse(_tuple[1]); ReadTuple(reader); var width = int.Parse(_tuple[0]); var height = int.Parse(_tuple[1]); var region = new Region { Page = pageImage, Left = left, Top = top, Width = width, Height = height, Name = line, Rotate = rotate }; if (ReadTuple(reader) == 4) { // split is optional region.Splits = new[] { int.Parse(_tuple[0]), int.Parse(_tuple[1]), int.Parse(_tuple[2]), int.Parse(_tuple[3]) }; if (ReadTuple(reader) == 4) { // pad is optional, but only present with splits region.Pads = new[] { int.Parse(_tuple[0]), int.Parse(_tuple[1]), int.Parse(_tuple[2]), int.Parse(_tuple[3]) }; ReadTuple(reader); } } region.OriginalWidth = int.Parse(_tuple[0]); region.OriginalHeight = int.Parse(_tuple[1]); ReadTuple(reader); region.OffsetX = int.Parse(_tuple[0]); region.OffsetY = int.Parse(_tuple[1]); region.Index = int.Parse(ReadValue(reader)); if (flip) region.Flip = true; data._regions.Add(region); } } } catch (Exception ex) { throw new FormatException("Error reading pack file: " + stream, ex); } } data._regions.Sort(); return data; } private static readonly string[] _tuple = new string[4]; private static string ReadValue(StreamReader reader) { var line = reader.ReadLine(); var colon = line.IndexOf(':'); if (colon == -1) throw new FormatException("Invalid line: " + line); return line.Substring(colon + 1).Trim(); } /// <summary> /// Reads a a group of strings separated by commas after a colon. /// What precedes the colon is ignored. /// </summary> /// <param name="reader"></param> /// <returns>The number of tuple values read (1, 2 or 4).</returns> private static int ReadTuple(StreamReader reader) { var line = reader.ReadLine(); Debug.Assert(line != null, "line != null"); var colon = line.IndexOf(':'); if (colon == -1) throw new FormatException("Invalid line: " + line); int i, lastMatch = colon + 1; for (i = 0; i < 3; i++) { int comma = line.IndexOf(',', lastMatch); if (comma < 0) break; _tuple[i] = line.Substring(lastMatch, comma - lastMatch).Trim(); lastMatch = comma + 1; } _tuple[i] = line.Substring(lastMatch).Trim(); return i + 1; } /// <summary> /// A texture page that may contain multiple Regions. This is not meant for everyday use. /// </summary> /// <see cref="TextureAtlas" /> public class Page { public readonly string TextureHandle; public readonly float Width, Height; public readonly bool UseMipMaps; public Page(string textureHandle, float width, float height, bool useMipMaps) { Width = width; Height = height; TextureHandle = textureHandle; UseMipMaps = useMipMaps; } } /// <summary> /// An internally-used class that keeps information about a portion of a Page. /// This is not meant for everyday use. /// </summary> /// <see cref="TextureAtlas" /> public class Region : IComparable<Region> { public Page Page; public int Index; public String Name; public float OffsetX; public float OffsetY; public int OriginalWidth; public int OriginalHeight; public bool Rotate; public int Left; public int Top; public int Width; public int Height; public bool Flip; public int[] Splits; public int[] Pads; public int CompareTo(Region other) { int i1 = Index; if (i1 == -1) i1 = int.MaxValue; int i2 = other.Index; if (i2 == -1) i2 = int.MaxValue; return i1 - i2; } public override string ToString() { return string.Format("Region: {0} Index: {1}", Name, Index); } } private readonly List<Page> _pages = new List<Page>(); public List<Page> Pages { get { return _pages; } } private readonly List<Region> _regions = new List<Region>(); public List<Region> Regions { get { return _regions; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using LavaLeak.Diplomata.Dictionaries; using LavaLeak.Diplomata.Helpers; using LavaLeak.Diplomata.Models.Submodels; using LavaLeak.Diplomata.Persistence; using LavaLeak.Diplomata.Persistence.Models; using UnityEngine; namespace LavaLeak.Diplomata.Models { /// <summary> /// Class of quest that can have multiples states. /// </summary> [Serializable] public class Quest : Data { [SerializeField] private string uniqueId; private bool finished; // The null value is necessary for database serialization. private string currentStateId = null; public LanguageDictionary[] Name; public QuestState[] questStates; public bool Initialized { get; private set; } /// <summary> /// Basic constructor, it sets the id and create the default "In progress" state. /// </summary> public Quest() { uniqueId = Guid.NewGuid().ToString(); Name = new LanguageDictionary[0]; questStates = new QuestState[0]; } /// <summary> /// Get the quest id private field. /// </summary> /// <returns>The id (a guid string).</returns> public string GetId() { return uniqueId; } /// <summary> /// Get if the quest is active. /// </summary> /// <returns>Return true if is active or false.</returns> public bool IsActive() { return Initialized && !finished; } /// <summary> /// Get if the quest is complete. /// </summary> /// <returns>Return true if is complete or false.</returns> public bool IsComplete() { return Initialized && finished; } /// <summary> /// Add a state to the states list. /// </summary> /// <param name="questState">The state name.</param> public void AddState(string questState, string longDescription) { if (!finished) questStates = ArrayHelper.Add(questStates, new QuestState()); } /// <summary> /// Get the index of the current state of the quest in questStates array. /// </summary> /// <returns>Return the index or -1 if don't have a current state.</returns> public int GetStateIndex() { var index = -1; if (string.IsNullOrEmpty(currentStateId) || !Initialized || finished) return index; for (var i = 0; i < questStates.Length; i++) { if (questStates[i].GetId() != currentStateId) continue; index = i; break; } return index; } /// <summary> /// Remove a state from states list if the quest has not initialized. /// </summary> /// <param name="questState">The state to remove.</param> public void RemoveState(QuestState questState) { if (Initialized) return; if (ArrayHelper.Contains(questStates, questState)) questStates = ArrayHelper.Remove(questStates, questState); } /// <summary> /// Initialize a quest setting the state to the first one. /// </summary> public void Initialize() { if (!finished && !Initialized) { Initialized = true; currentStateId = questStates[0].GetId(); DiplomataManager.EventController.SendQuestStart(this); } } /// <summary> /// Get the current quest name. /// </summary> /// <returns>Return the current quest name, if don't have one return null.</returns> public string GetCurrentState(string language = "") { var index = GetStateIndex(); return index != -1 ? questStates[index].GetShortDescription(language) : null; } public string GetCurrentStateID() { var index = GetStateIndex(); return index != -1 ? questStates[index].GetId() : null; } /// <summary> /// Get a state from id. /// </summary> /// <param name="id">The id to find.</param> /// <returns>The state object.</returns> public QuestState GetState(string id) { foreach (var state in questStates) { if (state.GetId() == id) return state; } return null; } /// <summary> /// Go to the next state, if don't have one finish the quest. /// </summary> /// <returns>A dictionary with all the quest states.</returns> public Dictionary<string, bool> NextState() { if (!finished) { int index = GetStateIndex(); if (index != -1) { if (index == questStates.Length - 1) { Finish(); } else { currentStateId = questStates[index + 1].GetId(); DiplomataManager.EventController.SendQuestStateChange(this); } } } return GetQuestLog(); } /// <summary> /// Force a quest state. /// </summary> /// <param name="stateId">The id (a string guid) of the quest state to force.</param> /// <returns>A dictionary with all the quest states.</returns> public Dictionary<string, bool> SetState(string stateId) { if (!finished) { Initialized = true; if (ArrayHelper.Contains(QuestState.GetIDs(questStates), stateId)) { currentStateId = stateId; DiplomataManager.EventController.SendQuestStateChange(this); } } else { Debug.Log(string.Format("Quest {0} already finished.", Name)); } return GetQuestLog(); } /// <summary> /// Return a dictionary with all the quest states names and if it is complete or don't. /// </summary> /// <returns>A dictionary with all the quest states names.</returns> public Dictionary<string, bool> GetQuestLog(string language = "") { var questLog = new Dictionary<string, bool>(); var currentStateIndex = GetStateIndex(); for (var i = 0; i < questStates.Length; i++) { var completed = true; if (!Initialized) completed = false; else if (!finished) completed = currentStateIndex > i && currentStateIndex > -1; var questStateName = questStates[i].GetShortDescription(language); if (questStateName != null) questLog.Add(questStateName, completed); } return questLog; } /// <summary> /// Return a dictionary with all the quest states and if it is complete or don't. /// </summary> /// <returns>A dictionary with all the quest states.</returns> public Dictionary<QuestState, bool> GetQuestStates() { var questLog = new Dictionary<QuestState, bool>(); var currentStateIndex = GetStateIndex(); for (var i = 0; i < questStates.Length; i++) { var completed = true; if (!Initialized) completed = false; else if (!finished) completed = currentStateIndex > i && currentStateIndex > -1; questLog.Add(questStates[i], completed); } return questLog; } /// <summary> /// Return the first QuestState that is incomplete. /// </summary> /// <returns>QuestState</returns> public QuestState GetFirstIncomplete() { var currentQuestStateId = GetStateIndex(); // If don't have quest states. if (questStates.Length < 0) return null; // If can't return current quest state. if (currentQuestStateId < 0) return questStates[0]; return questStates[currentQuestStateId]; } /// <summary> /// Checks if the QuestState with the required ID is complete. /// </summary> /// <param name="id">Unique ID of the QuestState.</param> /// <returns>A bool that indicates if the quest state is complete or not.</returns> public bool IsQuestStateCompleteById(string id) { var allQuestStates = GetQuestStates(); for (int i = 0; i < allQuestStates.Count; i++) { //TODO: Change this LINQ if (allQuestStates.Keys.ElementAt(i).GetId() == id) { if (allQuestStates.Values.ElementAt(i)) return true; } } return false; } /// <summary> /// Get the quest name in the setted language. /// </summary> /// <param name="language">The language or the current if don't exists.</param> /// <returns>The name as string.</returns> public string GetName(string language = "") { language = string.IsNullOrEmpty(language) ? DiplomataManager.Data.options.currentLanguage : language; var name = DictionariesHelper.ContainsKey(Name, language); return name != null ? name.value : string.Empty; } /// <summary> /// Get the quest name in the current language. /// </summary> /// <param name="options">The options to get current language.</param> /// <returns>The name as string.</returns> public string GetName(Options options) { return GetName(options.currentLanguage); } /// <summary> /// Get a list of the names of the quests of a array. /// </summary> /// <param name="quests">The quests array.</param> /// <param name="language">The language to get names.</param> /// <returns>A array of names as strings.</returns> public static string[] GetNames(Quest[] quests, string language = "") { string[] questsReturn = quests == null ? new string[0] : new string[quests.Length]; if (quests != null) { for (var i = 0; i < quests.Length; i++) { questsReturn[i] = quests[i].GetName(language); } } return questsReturn; } /// <summary> /// Get a list of the names of the quests of a array. /// </summary> /// <param name="quests">The quests array.</param> /// <param name="options">The options to get current language.</param> /// <returns></returns> public static string[] GetNames(Quest[] quests, Options options) { return GetNames(quests, options.currentLanguage); } /// <summary> /// Get a list of the ids of the quests of a array. /// </summary> /// <param name="quests">The quests array.</param> /// <returns>A array of ids as strings.</returns> public static string[] GetIDs(Quest[] quests) { string[] questsReturn = quests == null ? new string[0] : new string[quests.Length]; if (quests != null) { for (var i = 0; i < quests.Length; i++) { questsReturn[i] = quests[i].GetId(); } } return questsReturn; } /// <summary> /// Finish the quest and set the state to empty. /// </summary> public void Finish() { if (Initialized) { finished = true; currentStateId = null; DiplomataManager.EventController.SendQuestEnd(this); } } /// <summary> /// Find a quest from a array. /// </summary> /// <param name="quests">A array of quests.</param> /// <param name="value">The quest id (a string guid) or name.</param> /// <returns>The quest if found, or null.</returns> public static Quest Find(Quest[] quests, string value) { var quest = (Quest) Helpers.Find.In(quests).Where("uniqueId", value).Result; if (quest != null) return quest; foreach (var _quest in quests) { if (_quest.Name.Any(lang => lang.value.Equals(value))) { quest = _quest; } } return quest; } /// <summary> /// The string return. /// </summary> /// <returns></returns> public override string ToString() { var questString = new StringBuilder(); questString.Append(string.Format("{0}: ", Name)); foreach (KeyValuePair<string, bool> state in GetQuestLog()) { questString.Append(string.Format("{0}:{1}; ", state.Key, state.Value)); } return questString.ToString(); } /// <summary> /// Find a state by it index order. /// </summary> /// <param name="index">The index of the state in the quest.</param> /// <param name="language">The language to return the content.</param> /// <returns>The quest state short description as string.</returns> public string GetStateByIndex(int index, string language = "") { return index < questStates.Length ? questStates[index].GetShortDescription(language) : string.Empty; } /// <summary> /// Return the index of the quest state by it short description. /// </summary> /// <param name="shortDescription">The short description text.</param> /// <param name="language">A specific language or use the currentLanguage.</param> /// <returns></returns> public int GetIndexByStateName(string shortDescription, string language = "") { for (var i = 0; i < questStates.Length; i++) { if (questStates[i].GetShortDescription(language) == shortDescription) { return i; } } return -1; } /// <summary> /// Return the data of the object to save in a persistent object. /// </summary> /// <returns>A persistent object.</returns> public override Persistent GetData() { var quest = new QuestPersistent(); quest.id = uniqueId; quest.currentStateId = currentStateId; quest.initialized = Initialized; quest.finished = finished; return quest; } /// <summary> /// Store in a object data from persistent object. /// </summary> /// <param name="persistentData">The persistent data object.</param> public override void SetData(Persistent persistentData) { var questPersistentData = (QuestPersistent) persistentData; uniqueId = questPersistentData.id; currentStateId = questPersistentData.currentStateId; Initialized = questPersistentData.initialized; finished = questPersistentData.finished; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Net; using System.Net.Http.Headers; using System.Net.Security; using System.Runtime.ExceptionServices; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.InteropServices.WindowsRuntime; using System.Security.Authentication; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using RTApiInformation = Windows.Foundation.Metadata.ApiInformation; using RTHttpBaseProtocolFilter = Windows.Web.Http.Filters.HttpBaseProtocolFilter; using RTHttpCacheReadBehavior = Windows.Web.Http.Filters.HttpCacheReadBehavior; using RTHttpCacheWriteBehavior = Windows.Web.Http.Filters.HttpCacheWriteBehavior; using RTHttpCookieUsageBehavior = Windows.Web.Http.Filters.HttpCookieUsageBehavior; using RTHttpRequestMessage = Windows.Web.Http.HttpRequestMessage; using RTPasswordCredential = Windows.Security.Credentials.PasswordCredential; using RTCertificate = Windows.Security.Cryptography.Certificates.Certificate; using RTChainValidationResult = Windows.Security.Cryptography.Certificates.ChainValidationResult; using RTHttpServerCustomValidationRequestedEventArgs = Windows.Web.Http.Filters.HttpServerCustomValidationRequestedEventArgs; namespace System.Net.Http { public partial class HttpClientHandler : HttpMessageHandler { private const string RequestMessageLookupKey = "System.Net.Http.HttpRequestMessage"; private const string SavedExceptionDispatchInfoLookupKey = "System.Runtime.ExceptionServices.ExceptionDispatchInfo"; private const string ClientAuthenticationOID = "1.3.6.1.5.5.7.3.2"; private static Oid s_serverAuthOid = new Oid("1.3.6.1.5.5.7.3.1", "1.3.6.1.5.5.7.3.1"); private static readonly Lazy<bool> s_RTCookieUsageBehaviorSupported = new Lazy<bool>(InitRTCookieUsageBehaviorSupported); internal static bool RTCookieUsageBehaviorSupported => s_RTCookieUsageBehaviorSupported.Value; private static readonly Lazy<bool> s_RTNoCacheSupported = new Lazy<bool>(InitRTNoCacheSupported); private static bool RTNoCacheSupported => s_RTNoCacheSupported.Value; private static readonly Lazy<bool> s_RTServerCustomValidationRequestedSupported = new Lazy<bool>(InitRTServerCustomValidationRequestedSupported); private static bool RTServerCustomValidationRequestedSupported => s_RTServerCustomValidationRequestedSupported.Value; #region Fields private readonly HttpHandlerToFilter _handlerToFilter; private readonly HttpMessageHandler _diagnosticsPipeline; private RTHttpBaseProtocolFilter _rtFilter; private ClientCertificateOption _clientCertificateOptions; private CookieContainer _cookieContainer; private bool _useCookies; private DecompressionMethods _automaticDecompression; private bool _allowAutoRedirect; private int _maxAutomaticRedirections; private ICredentials _defaultProxyCredentials; private ICredentials _credentials; private IWebProxy _proxy; private X509Certificate2Collection _clientCertificates; private IDictionary<string, object> _properties; // Only create dictionary when required. private Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> _serverCertificateCustomValidationCallback; #endregion Fields #region Properties public virtual bool SupportsAutomaticDecompression { get { return true; } } public virtual bool SupportsProxy { get { return false; } } public virtual bool SupportsRedirectConfiguration { get { return false; } } public bool UseCookies { get { return _useCookies; } set { CheckDisposedOrStarted(); _useCookies = value; } } public CookieContainer CookieContainer { get { return _cookieContainer; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (!UseCookies) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, SR.net_http_invalid_enable_first, nameof(UseCookies), "true")); } CheckDisposedOrStarted(); _cookieContainer = value; } } public ClientCertificateOption ClientCertificateOptions { get { return _clientCertificateOptions; } set { if (value != ClientCertificateOption.Manual && value != ClientCertificateOption.Automatic) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _clientCertificateOptions = value; } } public DecompressionMethods AutomaticDecompression { get { return _automaticDecompression; } set { CheckDisposedOrStarted(); // Automatic decompression is implemented downstack. // HBPF will decompress both gzip and deflate, we will set // accept-encoding for one, the other, or both passed in here. _rtFilter.AutomaticDecompression = (value != DecompressionMethods.None); _automaticDecompression = value; } } public bool UseProxy { get { return _rtFilter.UseProxy; } set { CheckDisposedOrStarted(); _rtFilter.UseProxy = value; } } public IWebProxy Proxy { // We don't actually support setting a different proxy because our Http stack in NETNative // layers on top of the WinRT HttpClient which uses Wininet. And that API layer simply // uses the proxy information in the registry (and the same that Internet Explorer uses). // However, we can't throw PlatformNotSupportedException because the .NET Desktop stack // does support this and doing so would break apps. So, we'll just let this get/set work // even though we ignore it. The majority of apps actually use the default proxy anyways // so setting it here would be a no-op. get { return _proxy; } set { CheckDisposedOrStarted(); _proxy = value; } } public bool PreAuthenticate { get { return true; } set { CheckDisposedOrStarted(); } } public bool UseDefaultCredentials { get { return false; } set { CheckDisposedOrStarted(); } } public ICredentials Credentials { get { return _credentials; } set { CheckDisposedOrStarted(); if (value != null && value != CredentialCache.DefaultCredentials && !(value is NetworkCredential)) { throw new PlatformNotSupportedException(string.Format(CultureInfo.InvariantCulture, SR.net_http_value_not_supported, value, nameof(Credentials))); } _credentials = value; } } public ICredentials DefaultProxyCredentials { get { return _defaultProxyCredentials; } set { CheckDisposedOrStarted(); if (value != null && value != CredentialCache.DefaultCredentials && !(value is NetworkCredential)) { throw new PlatformNotSupportedException(string.Format(CultureInfo.InvariantCulture, SR.net_http_value_not_supported, value, nameof(DefaultProxyCredentials))); } _defaultProxyCredentials = value;; } } public bool AllowAutoRedirect { get { return _allowAutoRedirect; } set { CheckDisposedOrStarted(); _allowAutoRedirect = value; } } public int MaxAutomaticRedirections { get { return _maxAutomaticRedirections; } set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); } } public int MaxConnectionsPerServer { get { return (int)_rtFilter.MaxConnectionsPerServer; } set { CheckDisposedOrStarted(); _rtFilter.MaxConnectionsPerServer = (uint)value; } } public int MaxResponseHeadersLength { // Windows.Web.Http is built on WinINet. There is no maximum limit (except for out of memory) // for received response headers. So, returning -1 (indicating no limit) is appropriate. get { return -1; } set { CheckDisposedOrStarted(); } } public X509CertificateCollection ClientCertificates { get { if (_clientCertificateOptions != ClientCertificateOption.Manual) { throw new InvalidOperationException(SR.Format( SR.net_http_invalid_enable_first, nameof(ClientCertificateOptions), nameof(ClientCertificateOption.Manual))); } if (_clientCertificates == null) { _clientCertificates = new X509Certificate2Collection(); } return _clientCertificates; } } public Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ServerCertificateCustomValidationCallback { get { return _serverCertificateCustomValidationCallback; } set { CheckDisposedOrStarted(); if (value != null) { if (!RTServerCustomValidationRequestedSupported) { throw new PlatformNotSupportedException(string.Format(CultureInfo.InvariantCulture, SR.net_http_feature_requires_Windows10Version1607)); } } _serverCertificateCustomValidationCallback = value; } } public bool CheckCertificateRevocationList { // The WinRT API always checks for certificate revocation. If the revocation status is indeterminate // (such as revocation server is offline), then the WinRT API will indicate "success" and not fail // the request. get { return true; } set { CheckDisposedOrStarted(); } } public SslProtocols SslProtocols { // The WinRT API does not expose a property to control this. It always uses the system default. get { return SslProtocols.None; } set { CheckDisposedOrStarted(); } } public IDictionary<string, object> Properties { get { if (_properties == null) { _properties = new Dictionary<string, object>(); } return _properties; } } #endregion Properties #region De/Constructors public HttpClientHandler() { _rtFilter = CreateFilter(); _handlerToFilter = new HttpHandlerToFilter(_rtFilter, this); _handlerToFilter.RequestMessageLookupKey = RequestMessageLookupKey; _handlerToFilter.SavedExceptionDispatchInfoLookupKey = SavedExceptionDispatchInfoLookupKey; _diagnosticsPipeline = new DiagnosticsHandler(_handlerToFilter); _clientCertificateOptions = ClientCertificateOption.Manual; _useCookies = true; // deal with cookies by default. _cookieContainer = new CookieContainer(); // default container used for dealing with auto-cookies. _allowAutoRedirect = true; _maxAutomaticRedirections = 50; _automaticDecompression = DecompressionMethods.None; } private RTHttpBaseProtocolFilter CreateFilter() { var filter = new RTHttpBaseProtocolFilter(); // Always turn off WinRT cookie processing if the WinRT API supports turning it off. // Use .NET CookieContainer handling only. if (RTCookieUsageBehaviorSupported) { filter.CookieUsageBehavior = RTHttpCookieUsageBehavior.NoCookies; } // Handle redirections at the .NET layer so that we can see cookies on redirect responses // and have control of the number of redirections allowed. filter.AllowAutoRedirect = false; filter.AutomaticDecompression = false; // We don't support using the UI model in HttpBaseProtocolFilter() especially for auto-handling 401 responses. filter.AllowUI = false; // The .NET Desktop System.Net Http APIs (based on HttpWebRequest/HttpClient) uses no caching by default. // To preserve app-compat, we turn off caching in the WinRT HttpClient APIs. filter.CacheControl.ReadBehavior = RTNoCacheSupported ? RTHttpCacheReadBehavior.NoCache : RTHttpCacheReadBehavior.MostRecent; filter.CacheControl.WriteBehavior = RTHttpCacheWriteBehavior.NoCache; return filter; } protected override void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; try { _rtFilter.Dispose(); } catch (InvalidComObjectException) { // We'll ignore this error since it can happen when Dispose() is called from an object's finalizer // and the WinRT object (rtFilter) has already been disposed by the .NET Native runtime. } } base.Dispose(disposing); } #endregion De/Constructors #region Request Setup private async Task ConfigureRequest(HttpRequestMessage request) { ApplyDecompressionSettings(request); await ApplyClientCertificateSettings().ConfigureAwait(false); } private void ApplyDecompressionSettings(HttpRequestMessage request) { // Decompression: Add the Gzip and Deflate headers if not already present. ApplyDecompressionSetting(request, DecompressionMethods.GZip, "gzip"); ApplyDecompressionSetting(request, DecompressionMethods.Deflate, "deflate"); } private void ApplyDecompressionSetting(HttpRequestMessage request, DecompressionMethods method, string methodName) { if ((AutomaticDecompression & method) == method) { bool found = false; foreach (StringWithQualityHeaderValue encoding in request.Headers.AcceptEncoding) { if (methodName.Equals(encoding.Value, StringComparison.OrdinalIgnoreCase)) { found = true; break; } } if (!found) { request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue(methodName)); } } } private async Task ApplyClientCertificateSettings() { if (ClientCertificateOptions == ClientCertificateOption.Manual) { if (_clientCertificates != null && _clientCertificates.Count > 0) { X509Certificate2 clientCert = CertificateHelper.GetEligibleClientCertificate(_clientCertificates); if (clientCert == null) { return; } RTCertificate rtClientCert = await CertificateHelper.ConvertDotNetClientCertToWinRtClientCertAsync(clientCert).ConfigureAwait(false); if (rtClientCert == null) { throw new PlatformNotSupportedException(string.Format(CultureInfo.InvariantCulture, SR.net_http_feature_UWPClientCertSupportRequiresCertInPersonalCertificateStore)); } _rtFilter.ClientCertificate = rtClientCert; } return; } else { X509Certificate2 clientCert = CertificateHelper.GetEligibleClientCertificate(); if (clientCert == null) { return; } // Unlike in the .Manual case above, the conversion to WinRT Certificate should always work; // so we just use an Assert. All the possible client certs were enumerated from that store and // filtered down to a single client cert. RTCertificate rtClientCert = await CertificateHelper.ConvertDotNetClientCertToWinRtClientCertAsync(clientCert).ConfigureAwait(false); Debug.Assert(rtClientCert != null); _rtFilter.ClientCertificate = rtClientCert; } } private RTPasswordCredential RTPasswordCredentialFromICredentials(ICredentials creds) { // The WinRT PasswordCredential object does not have a special credentials value for "default credentials". // In general, the UWP HTTP platform automatically manages sending default credentials, if no explicit // credential was specified, based on if the app has EnterpriseAuthentication capability and if the endpoint // is listed in an intranet zone. // // A WinRT PasswordCredential object that is either null or created with the default constructor (i.e. with // empty values for username and password) indicates that there is no explicit credential. And that means // that the default logged-on credentials might be sent to the endpoint. // // There is currently no WinRT API to turn off sending default credentials other than the capability // and intranet zone checks described above. In general, the UWP HTTP model for specifying default // credentials is orthogonal to how the .NET System.Net APIs have been designed. if (creds == null || creds == CredentialCache.DefaultCredentials) { return null; } else { Debug.Assert(creds is NetworkCredential); NetworkCredential networkCred = (NetworkCredential)creds; // Creating a new WinRT PasswordCredential object with the default constructor ends up // with empty strings for username and password inside the object. However, one can't assign // empty strings to those properties; otherwise, it will throw an error. RTPasswordCredential rtCreds = new RTPasswordCredential(); if (!string.IsNullOrEmpty(networkCred.UserName)) { if (!string.IsNullOrEmpty(networkCred.Domain)) { rtCreds.UserName = networkCred.Domain + "\\" + networkCred.UserName; } else { rtCreds.UserName = networkCred.UserName; } } if (!string.IsNullOrEmpty(networkCred.Password)) { rtCreds.Password = networkCred.Password; } return rtCreds; } } private void SetFilterProxyCredential() { // We don't support changing the proxy settings in the UAP version of HttpClient since it's layered on // WinRT HttpClient. But we do support passing in explicit proxy credentials, if specified, which we can // get from the specified or default proxy. ICredentials proxyCredentials = null; if (UseProxy) { if (_proxy != null) { proxyCredentials = _proxy.Credentials; } else { proxyCredentials = _defaultProxyCredentials; } } _rtFilter.ProxyCredential = RTPasswordCredentialFromICredentials(proxyCredentials); } private void SetFilterServerCredential() { _rtFilter.ServerCredential = RTPasswordCredentialFromICredentials(_credentials); } #endregion Request Setup #region Request Execution protected internal override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { CheckDisposed(); SetOperationStarted(); HttpResponseMessage response; try { if (string.Equals(request.Method.Method, HttpMethod.Trace.Method, StringComparison.OrdinalIgnoreCase)) { // https://github.com/dotnet/corefx/issues/22161 throw new PlatformNotSupportedException(string.Format(CultureInfo.InvariantCulture, SR.net_http_httpmethod_notsupported_error, request.Method.Method)); } await ConfigureRequest(request).ConfigureAwait(false); Task<HttpResponseMessage> responseTask = DiagnosticsHandler.IsEnabled() ? _diagnosticsPipeline.SendAsync(request, cancellationToken) : _handlerToFilter.SendAsync(request, cancellationToken); response = await responseTask.ConfigureAwait(false); } catch (OperationCanceledException) { throw; } catch (Exception ex) { // Convert back to the expected exception type. throw new HttpRequestException(SR.net_http_client_execution_error, ex); } return response; } #endregion Request Execution #region Helpers private void SetOperationStarted() { if (!_operationStarted) { // Since this is the first operation, we set all the necessary WinRT filter properties. SetFilterProxyCredential(); SetFilterServerCredential(); if (_serverCertificateCustomValidationCallback != null) { Debug.Assert(RTServerCustomValidationRequestedSupported); // The WinRT layer uses a different model for the certificate callback. The callback is // considered "extra" validation. We need to explicitly ignore errors so that the callback // will get called. // // In addition, the WinRT layer restricts some errors so that they cannot be ignored, such // as "Revoked". This will result in behavior differences between UWP and other platforms. // The following errors cannot be ignored right now in the WinRT layer: // // ChainValidationResult.BasicConstraintsError // ChainValidationResult.InvalidCertificateAuthorityPolicy // ChainValidationResult.InvalidSignature // ChainValidationResult.OtherErrors // ChainValidationResult.Revoked // ChainValidationResult.UnknownCriticalExtension _rtFilter.IgnorableServerCertificateErrors.Add(RTChainValidationResult.Expired); _rtFilter.IgnorableServerCertificateErrors.Add(RTChainValidationResult.IncompleteChain); _rtFilter.IgnorableServerCertificateErrors.Add(RTChainValidationResult.InvalidName); _rtFilter.IgnorableServerCertificateErrors.Add(RTChainValidationResult.RevocationFailure); _rtFilter.IgnorableServerCertificateErrors.Add(RTChainValidationResult.RevocationInformationMissing); _rtFilter.IgnorableServerCertificateErrors.Add(RTChainValidationResult.Untrusted); _rtFilter.IgnorableServerCertificateErrors.Add(RTChainValidationResult.WrongUsage); _rtFilter.ServerCustomValidationRequested += RTServerCertificateCallback; } _operationStarted = true; } } private static bool InitRTCookieUsageBehaviorSupported() { return RTApiInformation.IsPropertyPresent( "Windows.Web.Http.Filters.HttpBaseProtocolFilter", "CookieUsageBehavior"); } private static bool InitRTNoCacheSupported() { return RTApiInformation.IsEnumNamedValuePresent( "Windows.Web.Http.Filters.HttpCacheReadBehavior", "NoCache"); } private static bool InitRTServerCustomValidationRequestedSupported() { return RTApiInformation.IsEventPresent( "Windows.Web.Http.Filters.HttpBaseProtocolFilter", "ServerCustomValidationRequested"); } internal void RTServerCertificateCallback(RTHttpBaseProtocolFilter sender, RTHttpServerCustomValidationRequestedEventArgs args) { bool success = RTServerCertificateCallbackHelper( args.RequestMessage, args.ServerCertificate, args.ServerIntermediateCertificates, args.ServerCertificateErrors); if (!success) { args.Reject(); } } private bool RTServerCertificateCallbackHelper( RTHttpRequestMessage requestMessage, RTCertificate cert, IReadOnlyList<RTCertificate> intermediateCerts, IReadOnlyList<RTChainValidationResult> certErrors) { // Convert WinRT certificate to .NET certificate. X509Certificate2 serverCert = CertificateHelper.ConvertPublicKeyCertificate(cert); // Create .NET X509Chain from the WinRT information. We need to rebuild the chain since WinRT only // gives us an array of intermediate certificates and not a X509Chain object. var serverChain = new X509Chain(); SslPolicyErrors sslPolicyErrors = SslPolicyErrors.None; foreach (RTCertificate intermediateCert in intermediateCerts) { serverChain.ChainPolicy.ExtraStore.Add(CertificateHelper.ConvertPublicKeyCertificate(cert)); } serverChain.ChainPolicy.RevocationMode = X509RevocationMode.Online; // WinRT always checks revocation. serverChain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot; // Authenticate the remote party: (e.g. when operating in client mode, authenticate the server). serverChain.ChainPolicy.ApplicationPolicy.Add(s_serverAuthOid); if (!serverChain.Build(serverCert)) { sslPolicyErrors |= SslPolicyErrors.RemoteCertificateChainErrors; } // Determine name-mismatch error from the existing WinRT information since .NET X509Chain.Build does not // return that in the X509Chain.ChainStatus fields. foreach (RTChainValidationResult result in certErrors) { if (result == RTChainValidationResult.InvalidName) { sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNameMismatch; break; } } // Get the .NET HttpRequestMessage we saved in the property bag of the WinRT HttpRequestMessage. HttpRequestMessage request = (HttpRequestMessage)requestMessage.Properties[RequestMessageLookupKey]; // Call the .NET callback. bool success = false; try { success = _serverCertificateCustomValidationCallback(request, serverCert, serverChain, sslPolicyErrors); } catch (Exception ex) { // Save the exception info. We will return it later via the SendAsync response processing. requestMessage.Properties.Add( SavedExceptionDispatchInfoLookupKey, ExceptionDispatchInfo.Capture(ex)); } finally { serverChain.Dispose(); serverCert.Dispose(); } return success; } #endregion Helpers } }
using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.IO; using System.Timers; using System.Threading; namespace Zegeger.Diagnostics { public enum TraceLevel { Off, Fatal, Error, Warning, Info, Verbose, Noise } public static class TraceLogger { private static System.Timers.Timer logFlusher; private static TraceLevel loggingLevel = TraceLevel.Verbose; private static string pathBase; private static string path; private static int logRollOverByteSize = 20 * 1024 * 1024; private static int maxLogCount = 50; private static int logNumber = 1; private static bool autoFlush = false; private static StreamWriter fileStream; public static TraceLevel LoggingLevel { get { return loggingLevel; } set { loggingLevel = value; } } public static int LogRollOverByteSize { get { return logRollOverByteSize; } set { logRollOverByteSize = value; } } public static int MaxLogCount { get { return maxLogCount; } set { maxLogCount = value; } } public static double FlushInterval { get { return logFlusher.Interval; } set { logFlusher.Interval = value; } } public static bool AutoFlush { get { return autoFlush; } set { autoFlush = value; fileStream.AutoFlush = value; } } public static void StartUp(string folderPath) { try { string datetime = DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss"); pathBase = Path.Combine(folderPath, "TraceLog_" + datetime); path = pathBase + "_" + logNumber + ".txt"; logFlusher = new System.Timers.Timer(10000); logFlusher.AutoReset = true; logFlusher.Elapsed += new ElapsedEventHandler(logFlusher_Elapsed); logFlusher.Start(); Start(); ThreadPool.QueueUserWorkItem(CleanUp); } catch (Exception ex) { Write(ex); } } private static void logFlusher_Elapsed(object sender, ElapsedEventArgs e) { try { ThreadPool.QueueUserWorkItem(Flush); } catch (Exception ex) { Write(ex); } } private static void Start() { fileStream = new StreamWriter(path); fileStream.AutoFlush = AutoFlush; fileStream.WriteLine("TraceStart"); fileStream.Flush(); } private static void End() { fileStream.WriteLine("TraceEnd"); fileStream.Close(); } private static void Flush(object state) { try { fileStream.Flush(); FileInfo logInfo = new FileInfo(path); Write("File Size: " + logInfo.Length + " > " + logRollOverByteSize, TraceLevel.Verbose); if (logInfo.Length > logRollOverByteSize) { Write("Rolling over...", TraceLevel.Info); RollOver(); } } catch (Exception ex) { Write(ex); } } private static void RollOver() { try { logNumber++; path = pathBase + "_" + logNumber + ".txt"; lock (fileStream) { End(); Start(); } ThreadPool.QueueUserWorkItem(CleanUp); } catch (Exception ex) { Write(ex); } } private static void CleanUp(object state) { try { Write("Enter", TraceLevel.Verbose); string folder = Path.GetDirectoryName(pathBase); Write("Cleaning up folder " + folder, TraceLevel.Info); DirectoryInfo di = new DirectoryInfo(folder); SortedDictionary<DateTime, FileInfo> sortedFiles = new SortedDictionary<DateTime, FileInfo>(); foreach (FileInfo fi in di.GetFiles("*.txt")) { Write("Found file " + fi.Name, TraceLevel.Verbose); sortedFiles.Add(fi.CreationTime, fi); } if (sortedFiles.Count > 0) { FileInfo[] sortedFI = new FileInfo[sortedFiles.Count]; sortedFiles.Values.CopyTo(sortedFI, 0); for (int i = sortedFI.Length - 1; i >= 0; i--) { if (i < sortedFI.Length - maxLogCount) { Write("Deleting file " + sortedFI[i].Name, TraceLevel.Info); sortedFI[i].Delete(); } } } } catch (Exception ex) { Write(ex); } Write("Exit"); } public static void ShutDown() { try { loggingLevel = TraceLevel.Off; End(); logFlusher.Elapsed -= new ElapsedEventHandler(logFlusher_Elapsed); logFlusher.Stop(); } catch { } } public static void Write(Exception ex, TraceLevel level = TraceLevel.Error) { try { StringWriter sw = new StringWriter(); sw.WriteLine(""); sw.WriteLine("Begin Exception ============================================================"); sw.WriteLine("Message: " + ex.Message); sw.WriteLine("Source: " + ex.Source); sw.WriteLine("Stack: " + ex.StackTrace); if (ex.InnerException != null) { sw.WriteLine("Inner: " + ex.InnerException.Message); sw.WriteLine("Inner Stack: " + ex.InnerException.StackTrace); } sw.WriteLine("End Exception =============================================================="); Write(sw.ToString(), level); //PluginCore.WriteToChat(sw.ToString()); sw.Close(); } catch { //PluginCore.WriteToChat(ex2.ToString()); //Write(ex2.ToString()); } } public static void Write(string text, TraceLevel level = TraceLevel.Info) { try { if (level == TraceLevel.Off) return; if (level > loggingLevel) return; StackFrame sf = new StackFrame(1, true); string output = ""; switch (level) { case TraceLevel.Fatal: output = "FATAL "; break; case TraceLevel.Error: output = "ERROR "; break; case TraceLevel.Warning: output = "WARN "; break; case TraceLevel.Info: output = "INFO "; break; case TraceLevel.Verbose: output = "VERBOSE "; break; case TraceLevel.Noise: output = "NOISE "; break; } output += DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss:fff") + " "; output += "[ " + Path.GetFileName(sf.GetFileName()) + "(" + sf.GetFileLineNumber() + ") " + sf.GetMethod() + " ] "; output += text; fileStream.WriteLine(output); //PluginCore.WriteToChat(output); } catch { //Write(ex); } } public static void Write(string format, TraceLevel level, params object[] args) { Write(String.Format(format, args), level); } } }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System; using System.Collections.Generic; using System.Web; using Sitecore.Data; using Sitecore.Data.Items; namespace Glass.Mapper.Sc { /// <summary> /// Class SitecoreContext /// </summary> public abstract class AbstractSitecoreContext : SitecoreService, ISitecoreContext { /// <summary> /// Initializes a new instance of the <see cref="SitecoreContext"/> class. /// </summary> protected AbstractSitecoreContext(Database database, Context context) : base(database, context) { } protected AbstractSitecoreContext(Database database, string contextName) : base(database, contextName) { } public static string GetContextFromSite() { if (Sitecore.Context.Site == null) return Context.DefaultContextName; return Sitecore.Context.Site.Properties["glassContext"] ?? Context.DefaultContextName; } #region AbstractSitecoreContext Members /// <summary> /// Gets the home item. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="isLazy">if set to <c>true</c> [is lazy].</param> /// <param name="inferType">if set to <c>true</c> [infer type].</param> /// <returns>``0.</returns> public T GetHomeItem<T>(bool isLazy = false, bool inferType = false) where T : class { return GetItem<T>(Sitecore.Context.Site.StartPath, isLazy, inferType); } /// <summary> /// Performs a query relative to the current item /// </summary> /// <typeparam name="T">The type to cast classes to</typeparam> /// <param name="query">The query.</param> /// <param name="isLazy">if set to <c>true</c> [is lazy].</param> /// <param name="inferType">if set to <c>true</c> [infer type].</param> /// <returns>IEnumerable{``0}.</returns> public IEnumerable<T> QueryRelative<T>(string query, bool isLazy = false, bool inferType = false) where T : class { Item item = Sitecore.Context.Item; var results = item.Axes.SelectItems(query); return CreateTypes(typeof(T), () => { return results; }, isLazy, inferType) as IEnumerable<T>; } /// <summary> /// Performs a query relative to the current item /// </summary> /// <typeparam name="T">The type to cast classes to</typeparam> /// <param name="query">The query.</param> /// <param name="isLazy">if set to <c>true</c> [is lazy].</param> /// <param name="inferType">if set to <c>true</c> [infer type].</param> /// <returns>``0.</returns> public T QuerySingleRelative<T>(string query, bool isLazy = false, bool inferType = false) where T : class { Item item = Sitecore.Context.Item; var result = item.Axes.SelectSingleItem(query); return CreateType<T>(result, isLazy, inferType); } /// <summary> /// Retrieves the current item as the specified type /// </summary> /// <returns> /// The current item as the specified type /// </returns> public dynamic GetCurrentDynamicItem() { return GetDynamicItem(Sitecore.Context.Item); } /// <summary> /// Retrieves the current item as the specified type /// </summary> /// <param name="type">The type to return.</param> /// <param name="isLazy">if set to <c>true</c> [is lazy].</param> /// <param name="inferType">if set to <c>true</c> [infer type].</param> /// <returns>The current item as the specified type</returns> public object GetCurrentItem(Type type, bool isLazy = false, bool inferType = false) { return CreateType(type, Sitecore.Context.Item, isLazy, inferType, null); } /// <summary> /// Retrieves the current item as the specified type /// </summary> /// <typeparam name="T">The type to return.</typeparam> /// <param name="isLazy">if set to <c>true</c> [is lazy].</param> /// <param name="inferType">if set to <c>true</c> [infer type].</param> /// <returns>The current item as the specified type</returns> public T GetCurrentItem<T>(bool isLazy = false, bool inferType = false) where T : class { return CreateType<T>(Sitecore.Context.Item, isLazy, inferType); } /// <summary> /// Retrieves the current item as the specified type /// </summary> /// <typeparam name="T">The type to return the Sitecore item as</typeparam> /// <typeparam name="TK">The type of the first constructor parameter</typeparam> /// <param name="param1">The value of the first parameter of the constructor</param> /// <param name="isLazy">if set to <c>true</c> [is lazy].</param> /// <param name="inferType">if set to <c>true</c> [infer type].</param> /// <returns>The Sitecore item as the specified type</returns> public T GetCurrentItem<T, TK>(TK param1, bool isLazy = false, bool inferType = false) where T : class { return CreateType<T, TK>(Sitecore.Context.Item, param1, isLazy, inferType); } /// <summary> /// Retrieves the current item as the specified type /// </summary> /// <typeparam name="T">The type to return the Sitecore item as</typeparam> /// <typeparam name="TK">The type of the first constructor parameter</typeparam> /// <typeparam name="TL">The type of the second constructor parameter</typeparam> /// <param name="param1">The value of the first parameter of the constructor</param> /// <param name="param2">The value of the second parameter of the constructor</param> /// <param name="isLazy">if set to <c>true</c> [is lazy].</param> /// <param name="inferType">if set to <c>true</c> [infer type].</param> /// <returns>The Sitecore item as the specified type</returns> public T GetCurrentItem<T, TK, TL>(TK param1, TL param2, bool isLazy = false, bool inferType = false) where T : class { return CreateType<T, TK, TL>(Sitecore.Context.Item, param1, param2, isLazy, inferType); } /// <summary> /// Retrieves the current item as the specified type /// </summary> /// <typeparam name="T">The type to return the Sitecore item as</typeparam> /// <typeparam name="TK">The type of the first constructor parameter</typeparam> /// <typeparam name="TL">The type of the second constructor parameter</typeparam> /// <typeparam name="TM">The type of the third constructor parameter</typeparam> /// <param name="param1">The value of the first parameter of the constructor</param> /// <param name="param2">The value of the second parameter of the constructor</param> /// <param name="param3">The value of the third parameter of the constructor</param> /// <param name="isLazy">if set to <c>true</c> [is lazy].</param> /// <param name="inferType">if set to <c>true</c> [infer type].</param> /// <returns>The Sitecore item as the specified type</returns> public T GetCurrentItem<T, TK, TL, TM>(TK param1, TL param2, TM param3, bool isLazy = false, bool inferType = false) where T : class { return CreateType<T, TK, TL, TM>(Sitecore.Context.Item, param1, param2, param3, isLazy, inferType); } /// <summary> /// Retrieves the current item as the specified type /// </summary> /// <typeparam name="T">The type to return the Sitecore item as</typeparam> /// <typeparam name="TK">The type of the first constructor parameter</typeparam> /// <typeparam name="TL">The type of the second constructor parameter</typeparam> /// <typeparam name="TM">The type of the third constructor parameter</typeparam> /// <typeparam name="TN">The type of the fourth constructor parameter</typeparam> /// <param name="param1">The value of the first parameter of the constructor</param> /// <param name="param2">The value of the second parameter of the constructor</param> /// <param name="param3">The value of the third parameter of the constructor</param> /// <param name="param4">The value of the fourth parameter of the constructor</param> /// <param name="isLazy">if set to <c>true</c> [is lazy].</param> /// <param name="inferType">if set to <c>true</c> [infer type].</param> /// <returns>The Sitecore item as the specified type</returns> public T GetCurrentItem<T, TK, TL, TM, TN>(TK param1, TL param2, TM param3, TN param4, bool isLazy = false, bool inferType = false) where T : class { return CreateType<T, TK, TL, TM, TN>(Sitecore.Context.Item, param1, param2, param3, param4, isLazy, inferType); } #endregion } }
using Lucene.Net.Store; using Lucene.Net.Util; using System; using System.Diagnostics; namespace Lucene.Net.Codecs { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Utility class for reading and writing versioned headers. /// <p> /// Writing codec headers is useful to ensure that a file is in /// the format you think it is. /// /// @lucene.experimental /// </summary> public sealed class CodecUtil { private CodecUtil() // no instance { } /// <summary> /// Constant to identify the start of a codec header. /// </summary> public const int CODEC_MAGIC = 0x3fd76c17; /// <summary> /// Constant to identify the start of a codec footer. /// </summary> public static readonly int FOOTER_MAGIC = ~CODEC_MAGIC; /// <summary> /// Writes a codec header, which records both a string to /// identify the file and a version number. this header can /// be parsed and validated with /// <seealso cref="#checkHeader(DataInput, String, int, int) checkHeader()"/>. /// <p> /// CodecHeader --&gt; Magic,CodecName,Version /// <ul> /// <li>Magic --&gt; <seealso cref="DataOutput#writeInt Uint32"/>. this /// identifies the start of the header. It is always {@value #CODEC_MAGIC}. /// <li>CodecName --&gt; <seealso cref="DataOutput#writeString String"/>. this /// is a string to identify this file. /// <li>Version --&gt; <seealso cref="DataOutput#writeInt Uint32"/>. Records /// the version of the file. /// </ul> /// <p> /// Note that the length of a codec header depends only upon the /// name of the codec, so this length can be computed at any time /// with <seealso cref="#headerLength(String)"/>. /// </summary> /// <param name="out"> Output stream </param> /// <param name="codec"> String to identify this file. It should be simple ASCII, /// less than 128 characters in length. </param> /// <param name="version"> Version number </param> /// <exception cref="IOException"> If there is an I/O error writing to the underlying medium. </exception> public static void WriteHeader(DataOutput @out, string codec, int version) { BytesRef bytes = new BytesRef(codec); if (bytes.Length != codec.Length || bytes.Length >= 128) { throw new System.ArgumentException("codec must be simple ASCII, less than 128 characters in length [got " + codec + "]"); } @out.WriteInt(CODEC_MAGIC); @out.WriteString(codec); @out.WriteInt(version); } /// <summary> /// Computes the length of a codec header. /// </summary> /// <param name="codec"> Codec name. </param> /// <returns> length of the entire codec header. </returns> /// <seealso cref= #writeHeader(DataOutput, String, int) </seealso> public static int HeaderLength(string codec) { return 9 + codec.Length; } /// <summary> /// Reads and validates a header previously written with /// <seealso cref="#writeHeader(DataOutput, String, int)"/>. /// <p> /// When reading a file, supply the expected <code>codec</code> and /// an expected version range (<code>minVersion to maxVersion</code>). /// </summary> /// <param name="in"> Input stream, positioned at the point where the /// header was previously written. Typically this is located /// at the beginning of the file. </param> /// <param name="codec"> The expected codec name. </param> /// <param name="minVersion"> The minimum supported expected version number. </param> /// <param name="maxVersion"> The maximum supported expected version number. </param> /// <returns> The actual version found, when a valid header is found /// that matches <code>codec</code>, with an actual version /// where <code>minVersion <= actual <= maxVersion</code>. /// Otherwise an exception is thrown. </returns> /// <exception cref="CorruptIndexException"> If the first four bytes are not /// <seealso cref="#CODEC_MAGIC"/>, or if the actual codec found is /// not <code>codec</code>. </exception> /// <exception cref="IndexFormatTooOldException"> If the actual version is less /// than <code>minVersion</code>. </exception> /// <exception cref="IndexFormatTooNewException"> If the actual version is greater /// than <code>maxVersion</code>. </exception> /// <exception cref="IOException"> If there is an I/O error reading from the underlying medium. </exception> /// <seealso cref= #writeHeader(DataOutput, String, int) </seealso> public static int CheckHeader(DataInput @in, string codec, int minVersion, int maxVersion) { // Safety to guard against reading a bogus string: int actualHeader = @in.ReadInt(); if (actualHeader != CODEC_MAGIC) { throw new System.IO.IOException("codec header mismatch: actual header=" + actualHeader + " vs expected header=" + CODEC_MAGIC + " (resource: " + @in + ")"); } return CheckHeaderNoMagic(@in, codec, minVersion, maxVersion); } /// <summary> /// Like {@link /// #checkHeader(DataInput,String,int,int)} except this /// version assumes the first int has already been read /// and validated from the input. /// </summary> public static int CheckHeaderNoMagic(DataInput @in, string codec, int minVersion, int maxVersion) { string actualCodec = @in.ReadString(); if (!actualCodec.Equals(codec)) { throw new System.IO.IOException("codec mismatch: actual codec=" + actualCodec + " vs expected codec=" + codec + " (resource: " + @in + ")"); } int actualVersion = @in.ReadInt(); if (actualVersion < minVersion) { throw new System.IO.IOException("Version: " + actualVersion + " is not supported. Minimum Version number is " + minVersion + "."); } if (actualVersion > maxVersion) { throw new System.IO.IOException("Version: " + actualVersion + " is not supported. Maximum Version number is " + maxVersion + "."); } return actualVersion; } /// <summary> /// Writes a codec footer, which records both a checksum /// algorithm ID and a checksum. this footer can /// be parsed and validated with /// <seealso cref="#checkFooter(ChecksumIndexInput) checkFooter()"/>. /// <p> /// CodecFooter --&gt; Magic,AlgorithmID,Checksum /// <ul> /// <li>Magic --&gt; <seealso cref="DataOutput#writeInt Uint32"/>. this /// identifies the start of the footer. It is always {@value #FOOTER_MAGIC}. /// <li>AlgorithmID --&gt; <seealso cref="DataOutput#writeInt Uint32"/>. this /// indicates the checksum algorithm used. Currently this is always 0, /// for zlib-crc32. /// <li>Checksum --&gt; <seealso cref="DataOutput#writeLong Uint32"/>. The /// actual checksum value for all previous bytes in the stream, including /// the bytes from Magic and AlgorithmID. /// </ul> /// </summary> /// <param name="out"> Output stream </param> /// <exception cref="IOException"> If there is an I/O error writing to the underlying medium. </exception> public static void WriteFooter(IndexOutput @out) { @out.WriteInt(FOOTER_MAGIC); @out.WriteInt(0); @out.WriteLong(@out.Checksum); } /// <summary> /// Computes the length of a codec footer. /// </summary> /// <returns> length of the entire codec footer. </returns> /// <seealso cref= #writeFooter(IndexOutput) </seealso> public static int FooterLength() { return 16; } /// <summary> /// Validates the codec footer previously written by <seealso cref="#writeFooter"/>. </summary> /// <returns> actual checksum value </returns> /// <exception cref="IOException"> if the footer is invalid, if the checksum does not match, /// or if {@code in} is not properly positioned before the footer /// at the end of the stream. </exception> public static long CheckFooter(ChecksumIndexInput @in) { ValidateFooter(@in); long actualChecksum = @in.Checksum; long expectedChecksum = @in.ReadLong(); if (expectedChecksum != actualChecksum) { throw new System.IO.IOException("checksum failed (hardware problem?) : expected=" + expectedChecksum.ToString("x") + " actual=" + actualChecksum.ToString("x") + " (resource=" + @in + ")"); } if (@in.FilePointer != @in.Length()) { throw new System.IO.IOException("did not read all bytes from file: read " + @in.FilePointer + " vs size " + @in.Length() + " (resource: " + @in + ")"); } return actualChecksum; } /// <summary> /// Returns (but does not validate) the checksum previously written by <seealso cref="#checkFooter"/>. </summary> /// <returns> actual checksum value </returns> /// <exception cref="IOException"> if the footer is invalid </exception> public static long RetrieveChecksum(IndexInput @in) { @in.Seek(@in.Length() - FooterLength()); ValidateFooter(@in); return @in.ReadLong(); } private static void ValidateFooter(IndexInput @in) { int magic = @in.ReadInt(); if (magic != FOOTER_MAGIC) { throw new System.IO.IOException("codec footer mismatch: actual footer=" + magic + " vs expected footer=" + FOOTER_MAGIC + " (resource: " + @in + ")"); } int algorithmID = @in.ReadInt(); if (algorithmID != 0) { throw new System.IO.IOException("codec footer mismatch: unknown algorithmID: " + algorithmID); } } /// <summary> /// Checks that the stream is positioned at the end, and throws exception /// if it is not. </summary> /// @deprecated Use <seealso cref="#checkFooter"/> instead, this should only used for files without checksums public static void CheckEOF(IndexInput @in) { if (@in.FilePointer != @in.Length()) { throw new System.IO.IOException("did not read all bytes from file: read " + @in.FilePointer + " vs size " + @in.Length() + " (resource: " + @in + ")"); } } /// <summary> /// Clones the provided input, reads all bytes from the file, and calls <seealso cref="#checkFooter"/> /// <p> /// Note that this method may be slow, as it must process the entire file. /// If you just need to extract the checksum value, call <seealso cref="#retrieveChecksum"/>. /// </summary> public static long ChecksumEntireFile(IndexInput input) { IndexInput clone = (IndexInput)input.Clone(); clone.Seek(0); ChecksumIndexInput @in = new BufferedChecksumIndexInput(clone); Debug.Assert(@in.FilePointer == 0); @in.Seek(@in.Length() - FooterLength()); return CheckFooter(@in); } } }
#region License //----------------------------------------------------------------------- // <copyright> // The MIT License (MIT) // // Copyright (c) 2014 Kirk S Woll // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // </copyright> //----------------------------------------------------------------------- #endregion namespace WootzJs.Compiler.JsAst { public class JsWalker : IJsVisitor { public virtual void DefaultVisit(JsNode node) { } public virtual void Visit(JsCompilationUnit node) { DefaultVisit(node); node.Body.Accept(this); } public virtual void Visit(JsBlockStatement node) { DefaultVisit(node); foreach (var statement in node.Statements) { statement.Accept(this); } } public virtual void Visit(JsExpressionStatement node) { DefaultVisit(node); node.Expression.Accept(this); } private void VisitDeclaration(IJsDeclaration declaration) { if (declaration is JsParameter) ((JsParameter)declaration).Accept(this); else if (declaration is JsVariableDeclarator) ((JsVariableDeclarator)declaration).Accept(this); } public virtual void Visit(JsFunction node) { DefaultVisit(node); foreach (var parameter in node.Parameters) { VisitDeclaration(parameter); } node.Body.Accept(this); } public virtual void Visit(JsMemberReferenceExpression node) { DefaultVisit(node); node.Target.Accept(this); } public virtual void Visit(JsObjectExpression node) { DefaultVisit(node); foreach (var item in node.Items) { item.Accept(this); } } public virtual void Visit(JsParentheticalExpression node) { DefaultVisit(node); node.Expression.Accept(this); } public virtual void Visit(JsReturnStatement node) { DefaultVisit(node); node.Expression.Accept(this); } public virtual void Visit(JsVariableDeclarator node) { DefaultVisit(node); if (node.Initializer != null) node.Initializer.Accept(this); } public virtual void Visit(JsVariableDeclaration node) { DefaultVisit(node); foreach (var declaration in node.Declarations) { declaration.Accept(this); } } public virtual void Visit(JsVariableReferenceExpression node) { DefaultVisit(node); } public virtual void Visit(JsObjectItem node) { DefaultVisit(node); node.Value.Accept(this); } public virtual void Visit(JsInvocationExpression node) { DefaultVisit(node); node.Target.Accept(this); foreach (var item in node.Arguments) { item.Accept(this); } } public virtual void Visit(JsParameter node) { DefaultVisit(node); } public virtual void Visit(JsFunctionDeclaration node) { DefaultVisit(node); node.Function.Accept(this); } public virtual void Visit(JsPrimitiveExpression node) { DefaultVisit(node); } public virtual void Visit(JsThisExpression node) { DefaultVisit(node); } public virtual void Visit(JsNewExpression node) { DefaultVisit(node); node.Expression.Accept(this); } public virtual void Visit(JsIfStatement node) { DefaultVisit(node); node.Condition.Accept(this); node.IfTrue.Accept(this); if (node.IfFalse != null) node.IfFalse.Accept(this); } public virtual void Visit(JsBinaryExpression node) { DefaultVisit(node); node.Left.Accept(this); node.Right.Accept(this); } public virtual void Visit(JsUnaryExpression node) { DefaultVisit(node); node.Operand.Accept(this); } public virtual void Visit(JsNativeStatement node) { DefaultVisit(node); } public virtual void Visit(JsNativeExpression node) { DefaultVisit(node); } public virtual void Visit(JsNewArrayExpression node) { DefaultVisit(node); if (node.Size != null) node.Size.Accept(this); } public virtual void Visit(JsForStatement node) { DefaultVisit(node); if (node.Declaration != null) node.Declaration.Accept(this); if (node.Condition != null) node.Condition.Accept(this); foreach (var incrementor in node.Incrementors) incrementor.Accept(this); } public virtual void Visit(JsIndexExpression node) { DefaultVisit(node); node.Target.Accept(this); node.Index.Accept(this); } public virtual void Visit(JsLocalVariableDeclaration node) { DefaultVisit(node); node.Declaration.Accept(this); } public virtual void Visit(JsRegexExpression node) { DefaultVisit(node); } public virtual void Visit(JsArrayExpression node) { DefaultVisit(node); foreach (var item in node.Elements) { item.Accept(this); } } public virtual void Visit(JsThrowStatement node) { DefaultVisit(node); node.Expression.Accept(this); } public virtual void Visit(JsSwitchSection node) { DefaultVisit(node); foreach (var label in node.Labels) { label.Accept(this); } foreach (var statement in node.Statements) { statement.Accept(this); } } public virtual void Visit(JsSwitchStatement node) { DefaultVisit(node); node.Expression.Accept(this); foreach (var section in node.Sections) { section.Accept(this); } } public virtual void Visit(JsSwitchLabel node) { DefaultVisit(node); if (node.Value != null) node.Value.Accept(this); } public virtual void Visit(JsWhileStatement node) { DefaultVisit(node); node.Condition.Accept(this); node.Body.Accept(this); } public virtual void Visit(JsBreakStatement node) { DefaultVisit(node); } public virtual void Visit(JsEmptyStatement node) { DefaultVisit(node); } public virtual void Visit(JsCatchClause node) { DefaultVisit(node); node.Declaration.Accept(this); node.Body.Accept(this); } public virtual void Visit(JsTryStatement node) { DefaultVisit(node); node.Body.Accept(this); if (node.Catch != null) node.Catch.Accept(this); if (node.Finally != null) node.Finally.Accept(this); } public virtual void Visit(JsConditionalExpression node) { DefaultVisit(node); node.Condition.Accept(this); node.IfTrue.Accept(this); node.IfFalse.Accept(this); } public virtual void Visit(JsDeleteExpression node) { DefaultVisit(node); node.Target.Accept(this); } public virtual void Visit(JsForInStatement node) { DefaultVisit(node); node.Declaration.Accept(this); node.Target.Accept(this); node.Body.Accept(this); } public virtual void Visit(JsTypeOfExpression node) { DefaultVisit(node); node.Target.Accept(this); } public virtual void Visit(JsContinueStatement node) { DefaultVisit(node); } public virtual void Visit(JsDeclarationReferenceExpression node) { DefaultVisit(node); VisitDeclaration(node.Declaration); } public virtual void Visit(JsLabeledStatement node) { DefaultVisit(node); node.Statement.Accept(this); } public virtual void Visit(JsDoWhileStatement node) { DefaultVisit(node); node.Body.Accept(this); node.Condition.Accept(this); } public virtual void Visit(JsInstanceOfExpression node) { DefaultVisit(node); node.Expression.Accept(this); node.Type.Accept(this); } public void Visit(JsInExpression node) { DefaultVisit(node); node.Object.Accept(this); } public void Visit(JsSnippetExpression node) { DefaultVisit(node); foreach (var part in node.Parts) { part.Accept(this); } } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1) Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace XenAPI { /// <summary> /// A virtual TPM device /// First published in XenServer 4.0. /// </summary> public partial class VTPM : XenObject<VTPM> { public VTPM() { } public VTPM(string uuid, XenRef<VM> VM, XenRef<VM> backend) { this.uuid = uuid; this.VM = VM; this.backend = backend; } /// <summary> /// Creates a new VTPM from a Proxy_VTPM. /// </summary> /// <param name="proxy"></param> public VTPM(Proxy_VTPM proxy) { this.UpdateFromProxy(proxy); } /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given VTPM. /// </summary> public override void UpdateFrom(VTPM update) { uuid = update.uuid; VM = update.VM; backend = update.backend; } internal void UpdateFromProxy(Proxy_VTPM proxy) { uuid = proxy.uuid == null ? null : (string)proxy.uuid; VM = proxy.VM == null ? null : XenRef<VM>.Create(proxy.VM); backend = proxy.backend == null ? null : XenRef<VM>.Create(proxy.backend); } public Proxy_VTPM ToProxy() { Proxy_VTPM result_ = new Proxy_VTPM(); result_.uuid = uuid ?? ""; result_.VM = VM ?? ""; result_.backend = backend ?? ""; return result_; } /// <summary> /// Creates a new VTPM from a Hashtable. /// Note that the fields not contained in the Hashtable /// will be created with their default values. /// </summary> /// <param name="table"></param> public VTPM(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this VTPM /// with the values listed in the Hashtable. Note that only the fields contained /// in the Hashtable will be updated and the rest will remain the same. /// </summary> /// <param name="table"></param> public void UpdateFrom(Hashtable table) { if (table.ContainsKey("uuid")) uuid = Marshalling.ParseString(table, "uuid"); if (table.ContainsKey("VM")) VM = Marshalling.ParseRef<VM>(table, "VM"); if (table.ContainsKey("backend")) backend = Marshalling.ParseRef<VM>(table, "backend"); } public bool DeepEquals(VTPM other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._VM, other._VM) && Helper.AreEqual2(this._backend, other._backend); } internal static List<VTPM> ProxyArrayToObjectList(Proxy_VTPM[] input) { var result = new List<VTPM>(); foreach (var item in input) result.Add(new VTPM(item)); return result; } public override string SaveChanges(Session session, string opaqueRef, VTPM server) { if (opaqueRef == null) { var reference = create(session, this); return reference == null ? null : reference.opaque_ref; } else { throw new InvalidOperationException("This type has no read/write properties"); } } /// <summary> /// Get a record containing the current state of the given VTPM. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vtpm">The opaque_ref of the given vtpm</param> public static VTPM get_record(Session session, string _vtpm) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vtpm_get_record(session.opaque_ref, _vtpm); else return new VTPM((Proxy_VTPM)session.proxy.vtpm_get_record(session.opaque_ref, _vtpm ?? "").parse()); } /// <summary> /// Get a reference to the VTPM instance with the specified UUID. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<VTPM> get_by_uuid(Session session, string _uuid) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vtpm_get_by_uuid(session.opaque_ref, _uuid); else return XenRef<VTPM>.Create(session.proxy.vtpm_get_by_uuid(session.opaque_ref, _uuid ?? "").parse()); } /// <summary> /// Create a new VTPM instance, and return its handle. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_record">All constructor arguments</param> public static XenRef<VTPM> create(Session session, VTPM _record) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vtpm_create(session.opaque_ref, _record); else return XenRef<VTPM>.Create(session.proxy.vtpm_create(session.opaque_ref, _record.ToProxy()).parse()); } /// <summary> /// Create a new VTPM instance, and return its handle. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_record">All constructor arguments</param> public static XenRef<Task> async_create(Session session, VTPM _record) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_vtpm_create(session.opaque_ref, _record); else return XenRef<Task>.Create(session.proxy.async_vtpm_create(session.opaque_ref, _record.ToProxy()).parse()); } /// <summary> /// Destroy the specified VTPM instance. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vtpm">The opaque_ref of the given vtpm</param> public static void destroy(Session session, string _vtpm) { if (session.JsonRpcClient != null) session.JsonRpcClient.vtpm_destroy(session.opaque_ref, _vtpm); else session.proxy.vtpm_destroy(session.opaque_ref, _vtpm ?? "").parse(); } /// <summary> /// Destroy the specified VTPM instance. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vtpm">The opaque_ref of the given vtpm</param> public static XenRef<Task> async_destroy(Session session, string _vtpm) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_vtpm_destroy(session.opaque_ref, _vtpm); else return XenRef<Task>.Create(session.proxy.async_vtpm_destroy(session.opaque_ref, _vtpm ?? "").parse()); } /// <summary> /// Get the uuid field of the given VTPM. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vtpm">The opaque_ref of the given vtpm</param> public static string get_uuid(Session session, string _vtpm) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vtpm_get_uuid(session.opaque_ref, _vtpm); else return (string)session.proxy.vtpm_get_uuid(session.opaque_ref, _vtpm ?? "").parse(); } /// <summary> /// Get the VM field of the given VTPM. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vtpm">The opaque_ref of the given vtpm</param> public static XenRef<VM> get_VM(Session session, string _vtpm) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vtpm_get_vm(session.opaque_ref, _vtpm); else return XenRef<VM>.Create(session.proxy.vtpm_get_vm(session.opaque_ref, _vtpm ?? "").parse()); } /// <summary> /// Get the backend field of the given VTPM. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_vtpm">The opaque_ref of the given vtpm</param> public static XenRef<VM> get_backend(Session session, string _vtpm) { if (session.JsonRpcClient != null) return session.JsonRpcClient.vtpm_get_backend(session.opaque_ref, _vtpm); else return XenRef<VM>.Create(session.proxy.vtpm_get_backend(session.opaque_ref, _vtpm ?? "").parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid = ""; /// <summary> /// the virtual machine /// </summary> [JsonConverter(typeof(XenRefConverter<VM>))] public virtual XenRef<VM> VM { get { return _VM; } set { if (!Helper.AreEqual(value, _VM)) { _VM = value; Changed = true; NotifyPropertyChanged("VM"); } } } private XenRef<VM> _VM = new XenRef<VM>(Helper.NullOpaqueRef); /// <summary> /// the domain where the backend is located /// </summary> [JsonConverter(typeof(XenRefConverter<VM>))] public virtual XenRef<VM> backend { get { return _backend; } set { if (!Helper.AreEqual(value, _backend)) { _backend = value; Changed = true; NotifyPropertyChanged("backend"); } } } private XenRef<VM> _backend = new XenRef<VM>(Helper.NullOpaqueRef); } }
// ----------------------------------------------------------------------- // <copyright file="Rect.cs" company="Steven Kirk"> // Copyright 2013 MIT Licence. See licence.md for more information. // </copyright> // ----------------------------------------------------------------------- namespace Avalonia { using System; using System.Globalization; using Avalonia.Media; public struct Rect : IFormattable { private double x; private double y; private double width; private double height; public Rect(Size size) { this.x = this.y = 0.0; this.width = size.Width; this.height = size.Height; } public Rect(Point point, Vector vector) : this(point, Point.Add(point, vector)) { } public Rect(Point point1, Point point2) { if (point1.X < point2.X) { this.x = point1.X; this.width = point2.X - point1.X; } else { this.x = point2.X; this.width = point1.X - point2.X; } if (point1.Y < point2.Y) { this.y = point1.Y; this.height = point2.Y - point1.Y; } else { this.y = point2.Y; this.height = point1.Y - point2.Y; } } public Rect(double x, double y, double width, double height) { if (width < 0 || height < 0) { throw new ArgumentException("width and height must be non-negative."); } this.x = x; this.y = y; this.width = width; this.height = height; } public Rect(Point location, Size size) { this.x = location.X; this.y = location.Y; this.width = size.Width; this.height = size.Height; } public static Rect Empty { get { Rect r = new Rect(); r.x = r.y = double.PositiveInfinity; r.width = r.height = double.NegativeInfinity; return r; } } public bool IsEmpty { get { return this.x == double.PositiveInfinity && this.y == double.PositiveInfinity && this.width == double.NegativeInfinity && this.height == double.NegativeInfinity; } } public Point Location { get { return new Point(this.x, this.y); } set { if (this.IsEmpty) { throw new InvalidOperationException("Cannot modify this property on the Empty Rect."); } this.x = value.X; this.y = value.Y; } } public Size Size { get { if (this.IsEmpty) { return Size.Empty; } return new Size(this.width, this.height); } set { if (this.IsEmpty) { throw new InvalidOperationException("Cannot modify this property on the Empty Rect."); } this.width = value.Width; this.height = value.Height; } } public double X { get { return this.x; } set { if (this.IsEmpty) { throw new InvalidOperationException("Cannot modify this property on the Empty Rect."); } this.x = value; } } public double Y { get { return this.y; } set { if (this.IsEmpty) { throw new InvalidOperationException("Cannot modify this property on the Empty Rect."); } this.y = value; } } public double Width { get { return this.width; } set { if (this.IsEmpty) { throw new InvalidOperationException("Cannot modify this property on the Empty Rect."); } if (value < 0) { throw new ArgumentException("width must be non-negative."); } this.width = value; } } public double Height { get { return this.height; } set { if (this.IsEmpty) { throw new InvalidOperationException("Cannot modify this property on the Empty Rect."); } if (value < 0) { throw new ArgumentException("height must be non-negative."); } this.height = value; } } public double Left { get { return this.x; } } public double Top { get { return this.y; } } public double Right { get { return this.x + this.width; } } public double Bottom { get { return this.y + this.height; } } public Point TopLeft { get { return new Point(this.Left, this.Top); } } public Point TopRight { get { return new Point(this.Right, this.Top); } } public Point BottomLeft { get { return new Point(this.Left, this.Bottom); } } public Point BottomRight { get { return new Point(this.Right, this.Bottom); } } public static bool Equals(Rect rect1, Rect rect2) { return rect1.Equals(rect2); } public static Rect Inflate(Rect rect, double width, double height) { if (width < rect.Width * -2) { return Rect.Empty; } if (height < rect.Height * -2) { return Rect.Empty; } Rect result = rect; result.Inflate(width, height); return result; } public static Rect Inflate(Rect rect, Size size) { return Rect.Inflate(rect, size.Width, size.Height); } public static Rect Intersect(Rect rect1, Rect rect2) { Rect result = rect1; result.Intersect(rect2); return result; } public static Rect Offset(Rect rect, double offsetX, double offsetY) { Rect result = rect; result.Offset(offsetX, offsetY); return result; } public static Rect Offset(Rect rect, Vector offsetVector) { Rect result = rect; result.Offset(offsetVector); return result; } public static Rect Transform(Rect rect, Matrix matrix) { Rect result = rect; result.Transform(matrix); return result; } public static Rect Union(Rect rect1, Rect rect2) { Rect result = rect1; result.Union(rect2); return result; } public static Rect Union(Rect rect, Point point) { Rect result = rect; result.Union(point); return result; } public static Rect Parse(string source) { throw new NotImplementedException(); } public static bool operator !=(Rect rect1, Rect rect2) { return !(rect1.Location == rect2.Location && rect1.Size == rect2.Size); } public static bool operator ==(Rect rect1, Rect rect2) { return rect1.Location == rect2.Location && rect1.Size == rect2.Size; } [AvaloniaSpecific] public static Rect operator -(Rect rect, Thickness thickness) { return new Rect( rect.Left + thickness.Left, rect.Top + thickness.Top, Math.Max(0.0, rect.Width - thickness.Left - thickness.Right), Math.Max(0.0, rect.Height - thickness.Top - thickness.Bottom)); } public void Union(Point point) { this.Union(new Rect(point, point)); } public bool Equals(Rect value) { return this.x == value.X && this.y == value.Y && this.width == value.Width && this.height == value.Height; } public override bool Equals(object o) { if (!(o is Rect)) { return false; } return this.Equals((Rect)o); } public override int GetHashCode() { throw new NotImplementedException(); } public bool Contains(Rect rect) { if (rect.Left < this.Left || rect.Right > this.Right) { return false; } if (rect.Top < this.Top || rect.Bottom > this.Bottom) { return false; } return true; } public bool Contains(double x, double y) { if (x < this.Left || x > this.Right) { return false; } if (y < this.Top || y > this.Bottom) { return false; } return true; } public bool Contains(Point point) { return this.Contains(point.X, point.Y); } public void Intersect(Rect rect) { double x = Math.Max(this.x, rect.x); double y = Math.Max(this.y, rect.y); double width = Math.Min(this.Right, rect.Right) - x; double height = Math.Min(this.Bottom, rect.Bottom) - y; if (width < 0 || height < 0) { this.x = this.y = double.PositiveInfinity; this.width = this.height = double.NegativeInfinity; } else { this.x = x; this.y = y; this.width = width; this.height = height; } } public void Inflate(double width, double height) { // XXX any error checking like in the static case? this.x -= width; this.y -= height; this.width += 2 * width; this.height += 2 * height; } public void Inflate(Size size) { this.Inflate(size.Width, size.Height); } public bool IntersectsWith(Rect rect) { return !((this.Left >= rect.Right) || (this.Right <= rect.Left) || (this.Top >= rect.Bottom) || (this.Bottom <= rect.Top)); } public void Offset(double offsetX, double offsetY) { this.x += offsetX; this.y += offsetY; } public void Offset(Vector offsetVector) { this.x += offsetVector.X; this.y += offsetVector.Y; } public void Scale(double scaleX, double scaleY) { this.x *= scaleX; this.y *= scaleY; this.width *= scaleX; this.height *= scaleY; } public void Transform(Matrix matrix) { throw new NotImplementedException(); } public void Union(Rect rect) { var left = Math.Min(this.Left, rect.Left); var top = Math.Min(this.Top, rect.Top); var right = Math.Max(this.Right, rect.Right); var bottom = Math.Max(this.Bottom, rect.Bottom); this.x = left; this.y = top; this.width = right - left; this.height = bottom - top; } public override string ToString() { return this.ToString(null); } public string ToString(IFormatProvider provider) { return this.ToString(null, provider); } string IFormattable.ToString(string format, IFormatProvider provider) { return this.ToString(format, provider); } private string ToString(string format, IFormatProvider provider) { if (this.IsEmpty) { return "Empty"; } if (provider == null) { provider = CultureInfo.CurrentCulture; } if (format == null) { format = string.Empty; } string separator = ","; NumberFormatInfo numberFormat = provider.GetFormat(typeof(NumberFormatInfo)) as NumberFormatInfo; if (numberFormat != null && numberFormat.NumberDecimalSeparator == separator) { separator = ";"; } string rectFormat = string.Format( "{{0:{0}}}{1}{{1:{0}}}{1}{{2:{0}}}{1}{{3:{0}}}", format, separator); return string.Format(provider, rectFormat, this.x, this.y, this.width, this.height); } } }
// 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.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; namespace System.Collections.Immutable { /// <summary> /// An immutable sorted set implementation. /// </summary> /// <typeparam name="T">The type of elements in the set.</typeparam> /// <devremarks> /// We implement <see cref="IReadOnlyList{T}"/> because it adds an ordinal indexer. /// We implement <see cref="IList{T}"/> because it gives us <see cref="IList{T}.IndexOf"/>, which is important for some folks. /// </devremarks> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableEnumerableDebuggerProxy<>))] public sealed partial class ImmutableSortedSet<T> : IImmutableSet<T>, ISortKeyCollection<T>, IReadOnlyList<T>, IList<T>, ISet<T>, IList, IStrongEnumerable<T, ImmutableSortedSet<T>.Enumerator> { /// <summary> /// This is the factor between the small collection's size and the large collection's size in a bulk operation, /// under which recreating the entire collection using a fast method rather than some incremental update /// (that requires tree rebalancing) is preferable. /// </summary> private const float RefillOverIncrementalThreshold = 0.15f; /// <summary> /// An empty sorted set with the default sort comparer. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly ImmutableSortedSet<T> Empty = new ImmutableSortedSet<T>(); /// <summary> /// The root node of the AVL tree that stores this set. /// </summary> private readonly Node _root; /// <summary> /// The comparer used to sort elements in this set. /// </summary> private readonly IComparer<T> _comparer; /// <summary> /// Initializes a new instance of the <see cref="ImmutableSortedSet{T}"/> class. /// </summary> /// <param name="comparer">The comparer.</param> internal ImmutableSortedSet(IComparer<T> comparer = null) { _root = Node.EmptyNode; _comparer = comparer ?? Comparer<T>.Default; } /// <summary> /// Initializes a new instance of the <see cref="ImmutableSortedSet{T}"/> class. /// </summary> /// <param name="root">The root of the AVL tree with the contents of this set.</param> /// <param name="comparer">The comparer.</param> private ImmutableSortedSet(Node root, IComparer<T> comparer) { Requires.NotNull(root, nameof(root)); Requires.NotNull(comparer, nameof(comparer)); root.Freeze(); _root = root; _comparer = comparer; } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> public ImmutableSortedSet<T> Clear() { return _root.IsEmpty ? this : Empty.WithComparer(_comparer); } /// <summary> /// Gets the maximum value in the collection, as defined by the comparer. /// </summary> /// <value>The maximum value in the set.</value> public T Max { get { return _root.Max; } } /// <summary> /// Gets the minimum value in the collection, as defined by the comparer. /// </summary> /// <value>The minimum value in the set.</value> public T Min { get { return _root.Min; } } #region IImmutableSet<T> Properties /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> public bool IsEmpty { get { return _root.IsEmpty; } } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> public int Count { get { return _root.Count; } } #endregion #region ISortKeyCollection<T> Properties /// <summary> /// See the <see cref="ISortKeyCollection{T}"/> interface. /// </summary> public IComparer<T> KeyComparer { get { return _comparer; } } #endregion /// <summary> /// Gets the root node (for testing purposes). /// </summary> internal IBinaryTree Root { get { return _root; } } #region IReadOnlyList<T> Indexers /// <summary> /// Gets the element of the set at the given index. /// </summary> /// <param name="index">The 0-based index of the element in the set to return.</param> /// <returns>The element at the given position.</returns> public T this[int index] { get { #if !NETSTANDARD1_0 return _root.ItemRef(index); #else return _root[index]; #endif } } #if !NETSTANDARD1_0 /// <summary> /// Gets a read-only reference of the element of the set at the given index. /// </summary> /// <param name="index">The 0-based index of the element in the set to return.</param> /// <returns>A read-only reference of the element at the given position.</returns> public ref readonly T ItemRef(int index) { return ref _root.ItemRef(index); } #endif #endregion #region Public methods /// <summary> /// Creates a collection with the same contents as this collection that /// can be efficiently mutated across multiple operations using standard /// mutable interfaces. /// </summary> /// <remarks> /// This is an O(1) operation and results in only a single (small) memory allocation. /// The mutable collection that is returned is *not* thread-safe. /// </remarks> [Pure] public Builder ToBuilder() { // We must not cache the instance created here and return it to various callers. // Those who request a mutable collection must get references to the collection // that version independently of each other. return new Builder(this); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [Pure] public ImmutableSortedSet<T> Add(T value) { bool mutated; return this.Wrap(_root.Add(value, _comparer, out mutated)); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [Pure] public ImmutableSortedSet<T> Remove(T value) { bool mutated; return this.Wrap(_root.Remove(value, _comparer, out mutated)); } /// <summary> /// Searches the set for a given value and returns the equal value it finds, if any. /// </summary> /// <param name="equalValue">The value to search for.</param> /// <param name="actualValue">The value from the set that the search found, or the original value if the search yielded no match.</param> /// <returns>A value indicating whether the search was successful.</returns> /// <remarks> /// This can be useful when you want to reuse a previously stored reference instead of /// a newly constructed one (so that more sharing of references can occur) or to look up /// a value that has more complete data than the value you currently have, although their /// comparer functions indicate they are equal. /// </remarks> [Pure] public bool TryGetValue(T equalValue, out T actualValue) { Node searchResult = _root.Search(equalValue, _comparer); if (searchResult.IsEmpty) { actualValue = equalValue; return false; } else { actualValue = searchResult.Key; return true; } } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [Pure] public ImmutableSortedSet<T> Intersect(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); var newSet = this.Clear(); foreach (var item in other.GetEnumerableDisposable<T, Enumerator>()) { if (this.Contains(item)) { newSet = newSet.Add(item); } } Debug.Assert(newSet != null); return newSet; } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [Pure] public ImmutableSortedSet<T> Except(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); var result = _root; foreach (T item in other.GetEnumerableDisposable<T, Enumerator>()) { bool mutated; result = result.Remove(item, _comparer, out mutated); } return this.Wrap(result); } /// <summary> /// Produces a set that contains elements either in this set or a given sequence, but not both. /// </summary> /// <param name="other">The other sequence of items.</param> /// <returns>The new set.</returns> [Pure] public ImmutableSortedSet<T> SymmetricExcept(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); var otherAsSet = ImmutableSortedSet.CreateRange(_comparer, other); var result = this.Clear(); foreach (T item in this) { if (!otherAsSet.Contains(item)) { result = result.Add(item); } } foreach (T item in otherAsSet) { if (!this.Contains(item)) { result = result.Add(item); } } return result; } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [Pure] public ImmutableSortedSet<T> Union(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); ImmutableSortedSet<T> immutableSortedSet; if (TryCastToImmutableSortedSet(other, out immutableSortedSet) && immutableSortedSet.KeyComparer == this.KeyComparer) // argument is a compatible immutable sorted set { if (immutableSortedSet.IsEmpty) { return this; } else if (this.IsEmpty) { // Adding the argument to this collection is equivalent to returning the argument. return immutableSortedSet; } else if (immutableSortedSet.Count > this.Count) { // We're adding a larger set to a smaller set, so it would be faster to simply // add the smaller set to the larger set. return immutableSortedSet.Union(this); } } int count; if (this.IsEmpty || (other.TryGetCount(out count) && (this.Count + count) * RefillOverIncrementalThreshold > this.Count)) { // The payload being added is so large compared to this collection's current size // that we likely won't see much memory reuse in the node tree by performing an // incremental update. So just recreate the entire node tree since that will // likely be faster. return this.LeafToRootRefill(other); } return this.UnionIncremental(other); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [Pure] public ImmutableSortedSet<T> WithComparer(IComparer<T> comparer) { if (comparer == null) { comparer = Comparer<T>.Default; } if (comparer == _comparer) { return this; } else { var result = new ImmutableSortedSet<T>(Node.EmptyNode, comparer); result = result.Union(this); Debug.Assert(result != null); return result; } } /// <summary> /// Checks whether a given sequence of items entirely describe the contents of this set. /// </summary> /// <param name="other">The sequence of items to check against this set.</param> /// <returns>A value indicating whether the sets are equal.</returns> [Pure] public bool SetEquals(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); if (object.ReferenceEquals(this, other)) { return true; } var otherSet = new SortedSet<T>(other, this.KeyComparer); if (this.Count != otherSet.Count) { return false; } int matches = 0; foreach (T item in otherSet) { if (!this.Contains(item)) { return false; } matches++; } return matches == this.Count; } /// <summary> /// Determines whether the current set is a property (strict) subset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a correct subset of other; otherwise, false.</returns> [Pure] public bool IsProperSubsetOf(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); if (this.IsEmpty) { return other.Any(); } // To determine whether everything we have is also in another sequence, // we enumerate the sequence and "tag" whether it's in this collection, // then consider whether every element in this collection was tagged. // Since this collection is immutable we cannot directly tag. So instead // we simply count how many "hits" we have and ensure it's equal to the // size of this collection. Of course for this to work we need to ensure // the uniqueness of items in the given sequence, so we create a set based // on the sequence first. var otherSet = new SortedSet<T>(other, this.KeyComparer); if (this.Count >= otherSet.Count) { return false; } int matches = 0; bool extraFound = false; foreach (T item in otherSet) { if (this.Contains(item)) { matches++; } else { extraFound = true; } if (matches == this.Count && extraFound) { return true; } } return false; } /// <summary> /// Determines whether the current set is a correct superset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a correct superset of other; otherwise, false.</returns> [Pure] public bool IsProperSupersetOf(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); if (this.IsEmpty) { return false; } int count = 0; foreach (T item in other.GetEnumerableDisposable<T, Enumerator>()) { count++; if (!this.Contains(item)) { return false; } } return this.Count > count; } /// <summary> /// Determines whether a set is a subset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a subset of other; otherwise, false.</returns> [Pure] public bool IsSubsetOf(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); if (this.IsEmpty) { return true; } // To determine whether everything we have is also in another sequence, // we enumerate the sequence and "tag" whether it's in this collection, // then consider whether every element in this collection was tagged. // Since this collection is immutable we cannot directly tag. So instead // we simply count how many "hits" we have and ensure it's equal to the // size of this collection. Of course for this to work we need to ensure // the uniqueness of items in the given sequence, so we create a set based // on the sequence first. var otherSet = new SortedSet<T>(other, this.KeyComparer); int matches = 0; foreach (T item in otherSet) { if (this.Contains(item)) { matches++; } } return matches == this.Count; } /// <summary> /// Determines whether the current set is a superset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a superset of other; otherwise, false.</returns> [Pure] public bool IsSupersetOf(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); foreach (T item in other.GetEnumerableDisposable<T, Enumerator>()) { if (!this.Contains(item)) { return false; } } return true; } /// <summary> /// Determines whether the current set overlaps with the specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set and other share at least one common element; otherwise, false.</returns> [Pure] public bool Overlaps(IEnumerable<T> other) { Requires.NotNull(other, nameof(other)); if (this.IsEmpty) { return false; } foreach (T item in other.GetEnumerableDisposable<T, Enumerator>()) { if (this.Contains(item)) { return true; } } return false; } /// <summary> /// Returns an <see cref="IEnumerable{T}"/> that iterates over this /// collection in reverse order. /// </summary> /// <returns> /// An enumerator that iterates over the <see cref="ImmutableSortedSet{T}"/> /// in reverse order. /// </returns> [Pure] public IEnumerable<T> Reverse() { return new ReverseEnumerable(_root); } /// <summary> /// Gets the position within this set that the specified value does or would appear. /// </summary> /// <param name="item">The value whose position is being sought.</param> /// <returns> /// The index of the specified <paramref name="item"/> in the sorted set, /// if <paramref name="item"/> is found. If <paramref name="item"/> is not /// found and <paramref name="item"/> is less than one or more elements in this set, /// a negative number which is the bitwise complement of the index of the first /// element that is larger than value. If <paramref name="item"/> is not found /// and <paramref name="item"/> is greater than any of the elements in the set, /// a negative number which is the bitwise complement of (the index of the last /// element plus 1). /// </returns> public int IndexOf(T item) { return _root.IndexOf(item, _comparer); } #endregion #region IImmutableSet<T> Members /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> public bool Contains(T value) { return _root.Contains(value, _comparer); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Clear() { return this.Clear(); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Add(T value) { return this.Add(value); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Remove(T value) { return this.Remove(value); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Intersect(IEnumerable<T> other) { return this.Intersect(other); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Except(IEnumerable<T> other) { return this.Except(other); } /// <summary> /// Produces a set that contains elements either in this set or a given sequence, but not both. /// </summary> /// <param name="other">The other sequence of items.</param> /// <returns>The new set.</returns> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.SymmetricExcept(IEnumerable<T> other) { return this.SymmetricExcept(other); } /// <summary> /// See the <see cref="IImmutableSet{T}"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Union(IEnumerable<T> other) { return this.Union(other); } #endregion #region ISet<T> Members /// <summary> /// See <see cref="ISet{T}"/> /// </summary> bool ISet<T>.Add(T item) { throw new NotSupportedException(); } /// <summary> /// See <see cref="ISet{T}"/> /// </summary> void ISet<T>.ExceptWith(IEnumerable<T> other) { throw new NotSupportedException(); } /// <summary> /// See <see cref="ISet{T}"/> /// </summary> void ISet<T>.IntersectWith(IEnumerable<T> other) { throw new NotSupportedException(); } /// <summary> /// See <see cref="ISet{T}"/> /// </summary> void ISet<T>.SymmetricExceptWith(IEnumerable<T> other) { throw new NotSupportedException(); } /// <summary> /// See <see cref="ISet{T}"/> /// </summary> void ISet<T>.UnionWith(IEnumerable<T> other) { throw new NotSupportedException(); } #endregion #region ICollection<T> members /// <summary> /// See the <see cref="ICollection{T}"/> interface. /// </summary> bool ICollection<T>.IsReadOnly { get { return true; } } /// <summary> /// See the <see cref="ICollection{T}"/> interface. /// </summary> void ICollection<T>.CopyTo(T[] array, int arrayIndex) { _root.CopyTo(array, arrayIndex); } /// <summary> /// See the <see cref="IList{T}"/> interface. /// </summary> void ICollection<T>.Add(T item) { throw new NotSupportedException(); } /// <summary> /// See the <see cref="ICollection{T}"/> interface. /// </summary> void ICollection<T>.Clear() { throw new NotSupportedException(); } /// <summary> /// See the <see cref="IList{T}"/> interface. /// </summary> bool ICollection<T>.Remove(T item) { throw new NotSupportedException(); } #endregion #region IList<T> methods /// <summary> /// See the <see cref="IList{T}"/> interface. /// </summary> T IList<T>.this[int index] { get { return this[index]; } set { throw new NotSupportedException(); } } /// <summary> /// See the <see cref="IList{T}"/> interface. /// </summary> void IList<T>.Insert(int index, T item) { throw new NotSupportedException(); } /// <summary> /// See the <see cref="IList{T}"/> interface. /// </summary> void IList<T>.RemoveAt(int index) { throw new NotSupportedException(); } #endregion #region IList properties /// <summary> /// Gets a value indicating whether the <see cref="IList"/> has a fixed size. /// </summary> /// <returns>true if the <see cref="IList"/> has a fixed size; otherwise, false.</returns> bool IList.IsFixedSize { get { return true; } } /// <summary> /// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only. /// </summary> /// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false. /// </returns> bool IList.IsReadOnly { get { return true; } } #endregion #region ICollection Properties /// <summary> /// See <see cref="ICollection"/>. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] object ICollection.SyncRoot { get { return this; } } /// <summary> /// See the <see cref="ICollection"/> interface. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection.IsSynchronized { get { // This is immutable, so it is always thread-safe. return true; } } #endregion #region IList methods /// <summary> /// Adds an item to the <see cref="IList"/>. /// </summary> /// <param name="value">The object to add to the <see cref="IList"/>.</param> /// <returns> /// The position into which the new element was inserted, or -1 to indicate that the item was not inserted into the collection, /// </returns> /// <exception cref="System.NotSupportedException"></exception> int IList.Add(object value) { throw new NotSupportedException(); } /// <summary> /// Clears this instance. /// </summary> /// <exception cref="System.NotSupportedException"></exception> void IList.Clear() { throw new NotSupportedException(); } /// <summary> /// Determines whether the <see cref="IList"/> contains a specific value. /// </summary> /// <param name="value">The object to locate in the <see cref="IList"/>.</param> /// <returns> /// true if the <see cref="object"/> is found in the <see cref="IList"/>; otherwise, false. /// </returns> bool IList.Contains(object value) { return this.Contains((T)value); } /// <summary> /// Determines the index of a specific item in the <see cref="IList"/>. /// </summary> /// <param name="value">The object to locate in the <see cref="IList"/>.</param> /// <returns> /// The index of <paramref name="value"/> if found in the list; otherwise, -1. /// </returns> int IList.IndexOf(object value) { return this.IndexOf((T)value); } /// <summary> /// Inserts an item to the <see cref="IList"/> at the specified index. /// </summary> /// <param name="index">The zero-based index at which <paramref name="value"/> should be inserted.</param> /// <param name="value">The object to insert into the <see cref="IList"/>.</param> /// <exception cref="System.NotSupportedException"></exception> void IList.Insert(int index, object value) { throw new NotSupportedException(); } /// <summary> /// Removes the first occurrence of a specific object from the <see cref="IList"/>. /// </summary> /// <param name="value">The object to remove from the <see cref="IList"/>.</param> /// <exception cref="System.NotSupportedException"></exception> void IList.Remove(object value) { throw new NotSupportedException(); } /// <summary> /// Removes at. /// </summary> /// <param name="index">The index.</param> /// <exception cref="System.NotSupportedException"></exception> void IList.RemoveAt(int index) { throw new NotSupportedException(); } /// <summary> /// Gets or sets the <see cref="object"/> at the specified index. /// </summary> /// <value> /// The <see cref="object"/>. /// </value> /// <param name="index">The index.</param> /// <exception cref="System.NotSupportedException"></exception> object IList.this[int index] { get { return this[index]; } set { throw new NotSupportedException(); } } #endregion #region ICollection Methods /// <summary> /// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param> void ICollection.CopyTo(Array array, int index) { _root.CopyTo(array, index); } #endregion #region IEnumerable<T> Members /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> [ExcludeFromCodeCoverage] IEnumerator<T> IEnumerable<T>.GetEnumerator() { return this.IsEmpty ? Enumerable.Empty<T>().GetEnumerator() : this.GetEnumerator(); } #endregion #region IEnumerable Members /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="IEnumerator"/> object that can be used to iterate through the collection. /// </returns> [ExcludeFromCodeCoverage] System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> /// <remarks> /// CAUTION: when this enumerator is actually used as a valuetype (not boxed) do NOT copy it by assigning to a second variable /// or by passing it to another method. When this enumerator is disposed of it returns a mutable reference type stack to a resource pool, /// and if the value type enumerator is copied (which can easily happen unintentionally if you pass the value around) there is a risk /// that a stack that has already been returned to the resource pool may still be in use by one of the enumerator copies, leading to data /// corruption and/or exceptions. /// </remarks> public Enumerator GetEnumerator() { return _root.GetEnumerator(); } /// <summary> /// Discovers an immutable sorted set for a given value, if possible. /// </summary> private static bool TryCastToImmutableSortedSet(IEnumerable<T> sequence, out ImmutableSortedSet<T> other) { other = sequence as ImmutableSortedSet<T>; if (other != null) { return true; } var builder = sequence as Builder; if (builder != null) { other = builder.ToImmutable(); return true; } return false; } /// <summary> /// Creates a new sorted set wrapper for a node tree. /// </summary> /// <param name="root">The root of the collection.</param> /// <param name="comparer">The comparer used to build the tree.</param> /// <returns>The immutable sorted set instance.</returns> [Pure] private static ImmutableSortedSet<T> Wrap(Node root, IComparer<T> comparer) { return root.IsEmpty ? ImmutableSortedSet<T>.Empty.WithComparer(comparer) : new ImmutableSortedSet<T>(root, comparer); } /// <summary> /// Adds items to this collection using the standard spine rewrite and tree rebalance technique. /// </summary> /// <param name="items">The items to add.</param> /// <returns>The new collection.</returns> /// <remarks> /// This method is least demanding on memory, providing the great chance of memory reuse /// and does not require allocating memory large enough to store all items contiguously. /// It's performance is optimal for additions that do not significantly dwarf the existing /// size of this collection. /// </remarks> [Pure] private ImmutableSortedSet<T> UnionIncremental(IEnumerable<T> items) { Requires.NotNull(items, nameof(items)); // Let's not implement in terms of ImmutableSortedSet.Add so that we're // not unnecessarily generating a new wrapping set object for each item. var result = _root; foreach (var item in items.GetEnumerableDisposable<T, Enumerator>()) { bool mutated; result = result.Add(item, _comparer, out mutated); } return this.Wrap(result); } /// <summary> /// Creates a wrapping collection type around a root node. /// </summary> /// <param name="root">The root node to wrap.</param> /// <returns>A wrapping collection type for the new tree.</returns> [Pure] private ImmutableSortedSet<T> Wrap(Node root) { if (root != _root) { return root.IsEmpty ? this.Clear() : new ImmutableSortedSet<T>(root, _comparer); } else { return this; } } /// <summary> /// Creates an immutable sorted set with the contents from this collection and a sequence of elements. /// </summary> /// <param name="addedItems">The sequence of elements to add to this set.</param> /// <returns>The immutable sorted set.</returns> [Pure] private ImmutableSortedSet<T> LeafToRootRefill(IEnumerable<T> addedItems) { Requires.NotNull(addedItems, nameof(addedItems)); // Rather than build up the immutable structure in the incremental way, // build it in such a way as to generate minimal garbage, by assembling // the immutable binary tree from leaf to root. This requires // that we know the length of the item sequence in advance, sort it, // and can index into that sequence like a list, so the limited // garbage produced is a temporary mutable data structure we use // as a reference when creating the immutable one. // Produce the initial list containing all elements, including any duplicates. List<T> list; if (this.IsEmpty) { // If the additional items enumerable list is known to be empty, too, // then just return this empty instance. int count; if (addedItems.TryGetCount(out count) && count == 0) { return this; } // Otherwise, construct a list from the items. The Count could still // be zero, in which case, again, just return this empty instance. list = new List<T>(addedItems); if (list.Count == 0) { return this; } } else { // Build the list from this set and then add the additional items. // Even if the additional items is empty, this set isn't, so we know // the resulting list will not be empty. list = new List<T>(this); list.AddRange(addedItems); } Debug.Assert(list.Count > 0); // Sort the list and remove duplicate entries. IComparer<T> comparer = this.KeyComparer; list.Sort(comparer); int index = 1; for (int i = 1; i < list.Count; i++) { if (comparer.Compare(list[i], list[i - 1]) != 0) { list[index++] = list[i]; } } list.RemoveRange(index, list.Count - index); // Use the now sorted list of unique items to construct a new sorted set. Node root = Node.NodeTreeFromList(list.AsOrderedCollection(), 0, list.Count); return this.Wrap(root); } /// <summary> /// An reverse enumerable of a sorted set. /// </summary> private class ReverseEnumerable : IEnumerable<T> { /// <summary> /// The root node to enumerate. /// </summary> private readonly Node _root; /// <summary> /// Initializes a new instance of the <see cref="ImmutableSortedSet{T}.ReverseEnumerable"/> class. /// </summary> /// <param name="root">The root of the data structure to reverse enumerate.</param> internal ReverseEnumerable(Node root) { Requires.NotNull(root, nameof(root)); _root = root; } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> public IEnumerator<T> GetEnumerator() { return _root.Reverse(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // System.Drawing.Imaging.Metafile.cs // // Authors: // Christian Meyer, eMail: Christian.Meyer@cs.tum.edu // Dennis Hayes (dennish@raytek.com) // Sebastien Pouliot <sebastien@ximian.com> // // (C) 2002 Ximian, Inc. http://www.ximian.com // Copyright (C) 2004,2006-2007 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.IO; using System.Reflection; using System.ComponentModel; using System.Runtime.InteropServices; using Gdip = System.Drawing.SafeNativeMethods.Gdip; using System.Runtime.Serialization; namespace System.Drawing.Imaging { public sealed partial class Metafile : Image { // Usually called when cloning images that need to have // not only the handle saved, but also the underlying stream // (when using MS GDI+ and IStream we must ensure the stream stays alive for all the life of the Image) internal Metafile(IntPtr ptr, Stream stream) => SetNativeImage(ptr); public Metafile(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); // With libgdiplus we use a custom API for this, because there's no easy way // to get the Stream down to libgdiplus. So, we wrap the stream with a set of delegates. GdiPlusStreamHelper sh = new GdiPlusStreamHelper(stream, false); int status = Gdip.GdipCreateMetafileFromDelegate_linux(sh.GetHeaderDelegate, sh.GetBytesDelegate, sh.PutBytesDelegate, sh.SeekDelegate, sh.CloseDelegate, sh.SizeDelegate, out nativeImage); // Since we're just passing to native code the delegates inside the wrapper, we need to keep sh alive // to avoid the object being collected and therefore the delegates would be collected as well. GC.KeepAlive(sh); Gdip.CheckStatus(status); } public Metafile(IntPtr hmetafile, WmfPlaceableFileHeader wmfHeader) { int status = Gdip.GdipCreateMetafileFromEmf(hmetafile, false, out nativeImage); Gdip.CheckStatus(status); } public Metafile(IntPtr referenceHdc, EmfType emfType, string description) : this(referenceHdc, new RectangleF(), MetafileFrameUnit.GdiCompatible, emfType, description) { } public Metafile(Stream stream, IntPtr referenceHdc, EmfType type, string description) : this(stream, referenceHdc, new RectangleF(), MetafileFrameUnit.GdiCompatible, type, description) { } public Metafile(string fileName, IntPtr referenceHdc, EmfType type, string description) : this(fileName, referenceHdc, new RectangleF(), MetafileFrameUnit.GdiCompatible, type, description) { } public Metafile(IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type, string desc) { int status = Gdip.GdipRecordMetafileI(referenceHdc, type, ref frameRect, frameUnit, desc, out nativeImage); Gdip.CheckStatus(status); } public Metafile(Stream stream, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type, string description) { if (stream == null) throw new NullReferenceException(nameof(stream)); // With libgdiplus we use a custom API for this, because there's no easy way // to get the Stream down to libgdiplus. So, we wrap the stream with a set of delegates. GdiPlusStreamHelper sh = new GdiPlusStreamHelper(stream, false); int status = Gdip.GdipRecordMetafileFromDelegateI_linux(sh.GetHeaderDelegate, sh.GetBytesDelegate, sh.PutBytesDelegate, sh.SeekDelegate, sh.CloseDelegate, sh.SizeDelegate, referenceHdc, type, ref frameRect, frameUnit, description, out nativeImage); // Since we're just passing to native code the delegates inside the wrapper, we need to keep sh alive // to avoid the object being collected and therefore the delegates would be collected as well. GC.KeepAlive(sh); Gdip.CheckStatus(status); } public Metafile(Stream stream, IntPtr referenceHdc, RectangleF frameRect, MetafileFrameUnit frameUnit, EmfType type, string description) { if (stream == null) throw new NullReferenceException(nameof(stream)); // With libgdiplus we use a custom API for this, because there's no easy way // to get the Stream down to libgdiplus. So, we wrap the stream with a set of delegates. GdiPlusStreamHelper sh = new GdiPlusStreamHelper(stream, false); int status = Gdip.GdipRecordMetafileFromDelegate_linux(sh.GetHeaderDelegate, sh.GetBytesDelegate, sh.PutBytesDelegate, sh.SeekDelegate, sh.CloseDelegate, sh.SizeDelegate, referenceHdc, type, ref frameRect, frameUnit, description, out nativeImage); // Since we're just passing to native code the delegates inside the wrapper, we need to keep sh alive // to avoid the object being collected and therefore the delegates would be collected as well. GC.KeepAlive(sh); Gdip.CheckStatus(status); } public Metafile(string fileName, IntPtr referenceHdc, Rectangle frameRect, MetafileFrameUnit frameUnit, EmfType type, string description) { // Called in order to emulate exception behavior from netfx related to invalid file paths. Path.GetFullPath(fileName); int status = Gdip.GdipRecordMetafileFileNameI(fileName, referenceHdc, type, ref frameRect, frameUnit, description, out nativeImage); Gdip.CheckStatus(status); } // methods public IntPtr GetHenhmetafile() { return nativeImage; } public MetafileHeader GetMetafileHeader() { IntPtr header = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeader))); try { int status = Gdip.GdipGetMetafileHeaderFromMetafile(nativeImage, header); Gdip.CheckStatus(status); return new MetafileHeader(header); } finally { Marshal.FreeHGlobal(header); } } public static MetafileHeader GetMetafileHeader(IntPtr henhmetafile) { IntPtr header = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeader))); try { int status = Gdip.GdipGetMetafileHeaderFromEmf(henhmetafile, header); Gdip.CheckStatus(status); return new MetafileHeader(header); } finally { Marshal.FreeHGlobal(header); } } public static MetafileHeader GetMetafileHeader(Stream stream) { if (stream == null) throw new NullReferenceException(nameof(stream)); IntPtr header = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeader))); try { // With libgdiplus we use a custom API for this, because there's no easy way // to get the Stream down to libgdiplus. So, we wrap the stream with a set of delegates. GdiPlusStreamHelper sh = new GdiPlusStreamHelper(stream, false); int status = Gdip.GdipGetMetafileHeaderFromDelegate_linux(sh.GetHeaderDelegate, sh.GetBytesDelegate, sh.PutBytesDelegate, sh.SeekDelegate, sh.CloseDelegate, sh.SizeDelegate, header); // Since we're just passing to native code the delegates inside the wrapper, we need to keep sh alive // to avoid the object being collected and therefore the delegates would be collected as well. GC.KeepAlive(sh); Gdip.CheckStatus(status); return new MetafileHeader(header); } finally { Marshal.FreeHGlobal(header); } } public static MetafileHeader GetMetafileHeader(string fileName) { // Called in order to emulate exception behavior from netfx related to invalid file paths. Path.GetFullPath(fileName); IntPtr header = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeader))); try { int status = Gdip.GdipGetMetafileHeaderFromFile(fileName, header); Gdip.CheckStatus(status); return new MetafileHeader(header); } finally { Marshal.FreeHGlobal(header); } } public static MetafileHeader GetMetafileHeader(IntPtr hmetafile, WmfPlaceableFileHeader wmfHeader) { IntPtr header = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(MetafileHeader))); try { int status = Gdip.GdipGetMetafileHeaderFromEmf(hmetafile, header); Gdip.CheckStatus(status); return new MetafileHeader(header); } finally { Marshal.FreeHGlobal(header); } } } }
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Windows.Documents.Serialization; using System.Windows.Documents; using System.Windows.Markup; using System.Windows.Media; using System.Printing; using System.Windows; using System.Xml; namespace DocumentSerialization { class XamlSerializerWriter:SerializerWriter { public XamlSerializerWriter(Stream stream) { _stream = stream; } /// <summary> /// Write a single Visual and close package /// </summary> public override void Write(Visual visual) { Write(visual, null); } /// <summary> /// Write a single Visual and close package /// </summary> public override void Write(Visual visual, PrintTicket printTicket) { SerializeObjectTree(visual); } /// <summary> /// Asynchronous Write a single Visual and close package /// </summary> public override void WriteAsync(Visual visual) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single Visual and close package /// </summary> public override void WriteAsync(Visual visual, object userState) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single Visual and close package /// </summary> public override void WriteAsync(Visual visual, PrintTicket printTicket) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single Visual and close package /// </summary> public override void WriteAsync(Visual visual, PrintTicket printTicket, object userState) { throw new NotSupportedException(); } /// <summary> /// Write a single DocumentPaginator and close package /// </summary> public override void Write(DocumentPaginator documentPaginator) { Write(documentPaginator, null); } /// <summary> /// Write a single DocumentPaginator and close package /// </summary> public override void Write(DocumentPaginator documentPaginator, PrintTicket printTicket) { SerializeObjectTree(documentPaginator.Source); } /// <summary> /// Asynchronous Write a single DocumentPaginator and close package /// </summary> public override void WriteAsync(DocumentPaginator documentPaginator) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single DocumentPaginator and close package /// </summary> public override void WriteAsync(DocumentPaginator documentPaginator, PrintTicket printTicket) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single DocumentPaginator and close package /// </summary> public override void WriteAsync(DocumentPaginator documentPaginator, object userState) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single DocumentPaginator and close package /// </summary> public override void WriteAsync(DocumentPaginator documentPaginator, PrintTicket printTicket, object userState) { throw new NotSupportedException(); } /// <summary> /// Write a single FixedPage and close package /// </summary> public override void Write(FixedPage fixedPage) { Write(fixedPage, null); } /// <summary> /// Write a single FixedPage and close package /// </summary> public override void Write(FixedPage fixedPage, PrintTicket printTicket) { SerializeObjectTree(fixedPage); } /// <summary> /// Asynchronous Write a single FixedPage and close package /// </summary> public override void WriteAsync(FixedPage fixedPage) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single FixedPage and close package /// </summary> public override void WriteAsync(FixedPage fixedPage, PrintTicket printTicket) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single FixedPage and close package /// </summary> public override void WriteAsync(FixedPage fixedPage, object userState) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single FixedPage and close package /// </summary> public override void WriteAsync(FixedPage fixedPage, PrintTicket printTicket, object userState) { throw new NotSupportedException(); } /// <summary> /// Write a single FixedDocument and close package /// </summary> public override void Write(FixedDocument fixedDocument) { Write(fixedDocument, null); } /// <summary> /// Write a single FixedDocument and close package /// </summary> public override void Write(FixedDocument fixedDocument, PrintTicket printTicket) { SerializeObjectTree(fixedDocument); } /// <summary> /// Asynchronous Write a single FixedDocument and close package /// </summary> public override void WriteAsync(FixedDocument fixedDocument) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single FixedDocument and close package /// </summary> public override void WriteAsync(FixedDocument fixedDocument, PrintTicket printTicket) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single FixedDocument and close package /// </summary> public override void WriteAsync(FixedDocument fixedDocument, object userState) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single FixedDocument and close package /// </summary> public override void WriteAsync(FixedDocument fixedDocument, PrintTicket printTicket, object userState) { throw new NotSupportedException(); } /// <summary> /// Write a single FixedDocumentSequence and close package /// </summary> public override void Write(FixedDocumentSequence fixedDocumentSequence) { Write(fixedDocumentSequence, null); } /// <summary> /// Write a single FixedDocumentSequence and close package /// </summary> public override void Write(FixedDocumentSequence fixedDocumentSequence, PrintTicket printTicket) { SerializeObjectTree(fixedDocumentSequence); } /// <summary> /// Asynchronous Write a single FixedDocumentSequence and close package /// </summary> public override void WriteAsync(FixedDocumentSequence fixedDocumentSequence) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single FixedDocumentSequence and close package /// </summary> public override void WriteAsync(FixedDocumentSequence fixedDocumentSequence, PrintTicket printTicket) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single FixedDocumentSequence and close package /// </summary> public override void WriteAsync(FixedDocumentSequence fixedDocumentSequence, object userState) { throw new NotSupportedException(); } /// <summary> /// Asynchronous Write a single FixedDocumentSequence and close package /// </summary> public override void WriteAsync(FixedDocumentSequence fixedDocumentSequence, PrintTicket printTicket, object userState) { throw new NotSupportedException(); } /// <summary> /// Cancel Asynchronous Write /// </summary> public override void CancelAsync() { throw new NotSupportedException(); } /// <summary> /// Create a SerializerWriterCollator to gobble up multiple Visuals /// </summary> public override SerializerWriterCollator CreateVisualsCollator() { throw new NotSupportedException(); } /// <summary> /// Create a SerializerWriterCollator to gobble up multiple Visuals /// </summary> public override SerializerWriterCollator CreateVisualsCollator(PrintTicket documentSequencePT, PrintTicket documentPT) { throw new NotSupportedException(); } #pragma warning disable 0067 /// <summary> /// This event will be invoked if the writer wants a PrintTicker /// </summary> public override event WritingPrintTicketRequiredEventHandler WritingPrintTicketRequired; /// <summary> /// This event will be invoked if the writer progress changes /// </summary> public override event WritingProgressChangedEventHandler WritingProgressChanged; /// <summary> /// This event will be invoked if the writer is done /// </summary> public override event WritingCompletedEventHandler WritingCompleted; /// <summary> /// This event will be invoked if the writer has been cancelled /// </summary> public override event WritingCancelledEventHandler WritingCancelled; #pragma warning restore 0067 private void SerializeObjectTree(object objectTree) { TextWriter writer = new StreamWriter(_stream); XmlTextWriter xmlWriter = null; try { // Create XmlTextWriter xmlWriter = new XmlTextWriter(writer); // Set serialization mode XamlDesignerSerializationManager manager = new XamlDesignerSerializationManager(xmlWriter); // Serialize System.Windows.Markup.XamlWriter.Save(objectTree, manager); } finally { if (xmlWriter != null) xmlWriter.Close(); } } private Stream _stream; } }
#region License // Copyright (c) K2 Workflow (SourceCode Technology Holdings Inc.). All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. #endregion using System; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq.Expressions; using System.Reflection; namespace SourceCode.Clay { /// <summary> /// Allows the conversion of enum values to integral values. /// </summary> public static class EnumConvert { private sealed class Checked { } private sealed class Unchecked { } private static class Converter<TEnum, TInteger, TChecked> where TEnum : struct, Enum where TInteger : unmanaged, IComparable, IConvertible, IFormattable { #pragma warning disable CA1000 // Do not declare static members on generic types private static readonly bool s_isChecked = typeof(TChecked) == typeof(Checked); public static Func<TEnum, TInteger> ConvertTo { get; } public static Func<TInteger, TEnum> ConvertFrom { get; } #pragma warning restore CA1000 // Do not declare static members on generic types static Converter() { Type @enum = typeof(TEnum); Type integer = typeof(TInteger); try { ParameterExpression enumParam = Expression.Parameter(@enum, "value"); ParameterExpression integerParam = Expression.Parameter(integer, "value"); Type underlying = @enum.GetEnumUnderlyingType(); var enumConv = (Expression)Expression.Convert(enumParam, underlying); if (underlying != integer) enumConv = Convert(enumConv, integer); Expression integerConv = underlying == integer ? integerParam : Convert(integerParam, underlying); integerConv = Expression.Convert(integerConv, @enum); ConvertTo = Expression.Lambda<Func<TEnum, TInteger>>(enumConv, enumParam).Compile(); ConvertFrom = Expression.Lambda<Func<TInteger, TEnum>>(integerConv, integerParam).Compile(); } #pragma warning disable CA1031 // Do not catch general exception types #pragma warning disable CA1065 // Do not raise exceptions in unexpected locations // Exception forwarding // Exceptions are not raised in this method. catch (Exception e) { ConvertTo = _ => throw e; ConvertFrom = _ => throw e; } #pragma warning restore CA1065 // Do not raise exceptions in unexpected locations #pragma warning restore CA1031 // Do not catch general exception types } private static Expression Convert(in Expression value, in Type type) => s_isChecked ? Expression.ConvertChecked(value, type) : Expression.Convert(value, type); } private static class ValueCache<TEnum> where TEnum : struct, Enum { internal static readonly Func<int> Length = () => { Type @enum = typeof(TEnum); ulong[] values = (ulong[])typeof(Enum) .GetMethod("InternalGetValues", BindingFlags.Static | BindingFlags.NonPublic) // Also see InternalGetNames .Invoke(null, new[] { typeof(TEnum) }); return values.Length; }; }; /// <summary> /// Converts the specified <typeparamref name="TEnum"/> into /// a <see cref="ulong"/>. /// </summary> /// <remarks> /// This method will fail if <typeparamref name="TEnum"/> /// is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The enum value to convert.</param> /// <returns>The <see cref="ulong"/>.</returns> public static ulong ToUInt64<TEnum>(TEnum value) where TEnum : struct, Enum => Converter<TEnum, ulong, Unchecked>.ConvertTo(value); /// <summary> /// Converts the specified <see cref="ulong"/> into /// a <typeparamref name="TEnum"/>. /// </summary> /// <remarks> /// This method will fail if <typeparamref name="TEnum"/> /// is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The <see cref="ulong"/> to convert.</param> /// <returns>The <typeparamref name="TEnum"/>.</returns> public static TEnum ToEnum<TEnum>(ulong value) where TEnum : struct, Enum => Converter<TEnum, ulong, Unchecked>.ConvertFrom(value); /// <summary> /// Converts the specified <typeparamref name="TEnum"/> into /// a <see cref="long"/>. /// </summary> /// <remarks> /// This method will fail if <typeparamref name="TEnum"/> /// is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The enum value to convert.</param> /// <returns>The <see cref="long"/>.</returns> public static long ToInt64<TEnum>(TEnum value) where TEnum : struct, Enum => Converter<TEnum, long, Unchecked>.ConvertTo(value); /// <summary> /// Converts the specified <see cref="long"/> into /// a <typeparamref name="TEnum"/>. /// </summary> /// <remarks> /// This method will fail if <typeparamref name="TEnum"/> /// is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The <see cref="long"/> to convert.</param> /// <returns>The <typeparamref name="TEnum"/>.</returns> public static TEnum ToEnum<TEnum>(long value) where TEnum : struct, Enum => Converter<TEnum, long, Unchecked>.ConvertFrom(value); /// <summary> /// Converts the specified <typeparamref name="TEnum"/> into /// a <see cref="uint"/>. /// </summary> /// <remarks> /// This method will fail if <typeparamref name="TEnum"/> /// is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The enum value to convert.</param> /// <returns>The <see cref="uint"/>.</returns> public static uint ToUInt32<TEnum>(TEnum value) where TEnum : struct, Enum => Converter<TEnum, uint, Unchecked>.ConvertTo(value); /// <summary> /// Converts the specified <see cref="uint"/> into /// a <typeparamref name="TEnum"/>. /// </summary> /// <remarks> /// This method will fail if <typeparamref name="TEnum"/> /// is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The <see cref="uint"/> to convert.</param> /// <returns>The <typeparamref name="TEnum"/>.</returns> public static TEnum ToEnum<TEnum>(uint value) where TEnum : struct, Enum => Converter<TEnum, uint, Unchecked>.ConvertFrom(value); /// <summary> /// Converts the specified <typeparamref name="TEnum"/> into /// a <see cref="int"/>. /// </summary> /// <remarks> /// This method will fail if <typeparamref name="TEnum"/> /// is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The enum value to convert.</param> /// <returns>The <see cref="int"/>.</returns> public static int ToInt32<TEnum>(TEnum value) where TEnum : struct, Enum => Converter<TEnum, int, Unchecked>.ConvertTo(value); /// <summary> /// Converts the specified <see cref="int"/> into /// a <typeparamref name="TEnum"/>. /// </summary> /// <remarks> /// This method will fail if <typeparamref name="TEnum"/> /// is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The <see cref="int"/> to convert.</param> /// <returns>The <typeparamref name="TEnum"/>.</returns> public static TEnum ToEnum<TEnum>(int value) where TEnum : struct, Enum => Converter<TEnum, int, Unchecked>.ConvertFrom(value); /// <summary> /// Converts the specified <typeparamref name="TEnum"/> into /// a <see cref="ushort"/>. /// </summary> /// <remarks> /// This method will fail if <typeparamref name="TEnum"/> /// is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The enum value to convert.</param> /// <returns>The <see cref="ushort"/>.</returns> public static ushort ToUInt16<TEnum>(TEnum value) where TEnum : struct, Enum => Converter<TEnum, ushort, Unchecked>.ConvertTo(value); /// <summary> /// Converts the specified <see cref="ushort"/> into /// a <typeparamref name="TEnum"/>. /// </summary> /// <remarks> /// This method will fail if <typeparamref name="TEnum"/> /// is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The <see cref="ushort"/> to convert.</param> /// <returns>The <typeparamref name="TEnum"/>.</returns> public static TEnum ToEnum<TEnum>(ushort value) where TEnum : struct, Enum => Converter<TEnum, ushort, Unchecked>.ConvertFrom(value); /// <summary> /// Converts the specified <typeparamref name="TEnum"/> into /// a <see cref="short"/>. /// </summary> /// <remarks> /// This method will fail if <typeparamref name="TEnum"/> /// is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The enum value to convert.</param> /// <returns>The <see cref="short"/>.</returns> public static short ToInt16<TEnum>(TEnum value) where TEnum : struct, Enum => Converter<TEnum, short, Unchecked>.ConvertTo(value); /// <summary> /// Converts the specified <see cref="short"/> into /// a <typeparamref name="TEnum"/>. /// </summary> /// <remarks> /// This method will fail if <typeparamref name="TEnum"/> /// is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The <see cref="short"/> to convert.</param> /// <returns>The <typeparamref name="TEnum"/>.</returns> public static TEnum ToEnum<TEnum>(short value) where TEnum : struct, Enum => Converter<TEnum, short, Unchecked>.ConvertFrom(value); /// <summary> /// Converts the specified <typeparamref name="TEnum"/> into /// a <see cref="byte"/>. /// </summary> /// <remarks> /// This method will fail if <typeparamref name="TEnum"/> /// is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The enum value to convert.</param> /// <returns>The <see cref="byte"/>.</returns> public static byte ToByte<TEnum>(TEnum value) where TEnum : struct, Enum => Converter<TEnum, byte, Unchecked>.ConvertTo(value); /// <summary> /// Converts the specified <see cref="byte"/> into /// a <typeparamref name="TEnum"/>. /// </summary> /// <remarks> /// This method will fail if <typeparamref name="TEnum"/> /// is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The <see cref="byte"/> to convert.</param> /// <returns>The <typeparamref name="TEnum"/>.</returns> public static TEnum ToEnum<TEnum>(byte value) where TEnum : struct, Enum => Converter<TEnum, byte, Unchecked>.ConvertFrom(value); /// <summary> /// Converts the specified <typeparamref name="TEnum"/> into /// a <see cref="sbyte"/>. /// </summary> /// <remarks> /// This method will fail if <typeparamref name="TEnum"/> /// is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The enum value to convert.</param> /// <returns>The <see cref="sbyte"/>.</returns> public static sbyte ToSByte<TEnum>(TEnum value) where TEnum : struct, Enum => Converter<TEnum, sbyte, Unchecked>.ConvertTo(value); /// <summary> /// Converts the specified <see cref="sbyte"/> into /// a <typeparamref name="TEnum"/>. /// </summary> /// <remarks> /// This method will fail if <typeparamref name="TEnum"/> /// is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The <see cref="sbyte"/> to convert.</param> /// <returns>The <typeparamref name="TEnum"/>.</returns> public static TEnum ToEnum<TEnum>(sbyte value) where TEnum : struct, Enum => Converter<TEnum, sbyte, Unchecked>.ConvertFrom(value); /// <summary> /// Converts the specified <typeparamref name="TEnum"/> into /// a <see cref="ulong"/>. /// </summary> /// <remarks> /// This method will fail if the enum value is less than /// <see cref="ulong.MinValue"/>, or if <typeparamref name="TEnum"/> /// is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The enum value to convert.</param> /// <returns>The <see cref="ulong"/>.</returns> public static ulong ToUInt64Checked<TEnum>(TEnum value) where TEnum : struct, Enum => Converter<TEnum, ulong, Checked>.ConvertTo(value); /// <summary> /// Converts the specified <see cref="ulong"/> into /// a <typeparamref name="TEnum"/>. /// </summary> /// <remarks> /// This method will fail if the <paramref name="value"/> is outside /// the range of valid values for the underlying type of /// <typeparamref name="TEnum"/>, or if <typeparamref name="TEnum"/> /// is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The <see cref="ulong"/> to convert.</param> /// <returns>The <typeparamref name="TEnum"/>.</returns> public static TEnum ToEnumChecked<TEnum>(ulong value) where TEnum : struct, Enum => Converter<TEnum, ulong, Checked>.ConvertFrom(value); /// <summary> /// Converts the specified <typeparamref name="TEnum"/> into /// a <see cref="long"/>. /// </summary> /// <remarks> /// This method will fail if the enum value is larger than /// <see cref="long.MaxValue"/>, or if <typeparamref name="TEnum"/> is /// not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The enum value to convert.</param> /// <returns>The <see cref="long"/>.</returns> public static long ToInt64Checked<TEnum>(TEnum value) where TEnum : struct, Enum => Converter<TEnum, long, Checked>.ConvertTo(value); /// <summary> /// Converts the specified <see cref="long"/> into /// a <typeparamref name="TEnum"/>. /// </summary> /// <remarks> /// This method will fail if the <paramref name="value"/> is outside /// the range of valid values for the underlying type of /// <typeparamref name="TEnum"/>, or if <typeparamref name="TEnum"/> /// is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The <see cref="long"/> to convert.</param> /// <returns>The <typeparamref name="TEnum"/>.</returns> public static TEnum ToEnumChecked<TEnum>(long value) where TEnum : struct, Enum => Converter<TEnum, long, Checked>.ConvertFrom(value); /// <summary> /// Converts the specified <typeparamref name="TEnum"/> into /// a <see cref="uint"/>. /// </summary> /// <remarks> /// This method will fail if the enum value is less than /// <see cref="uint.MinValue"/> or larger than <see cref="uint.MaxValue"/>, /// or if <typeparamref name="TEnum"/> is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The enum value to convert.</param> /// <returns>The <see cref="uint"/>.</returns> public static uint ToUInt32Checked<TEnum>(TEnum value) where TEnum : struct, Enum => Converter<TEnum, uint, Checked>.ConvertTo(value); /// <summary> /// Converts the specified <see cref="uint"/> into /// a <typeparamref name="TEnum"/>. /// </summary> /// <remarks> /// This method will fail if the <paramref name="value"/> is outside /// the range of valid values for the underlying type of /// <typeparamref name="TEnum"/>, or if <typeparamref name="TEnum"/> /// is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The <see cref="uint"/> to convert.</param> /// <returns>The <typeparamref name="TEnum"/>.</returns> public static TEnum ToEnumChecked<TEnum>(uint value) where TEnum : struct, Enum => Converter<TEnum, uint, Checked>.ConvertFrom(value); /// <summary> /// Converts the specified <typeparamref name="TEnum"/> into /// a <see cref="int"/>. /// </summary> /// <remarks> /// This method will fail if the enum value is less than /// <see cref="int.MinValue"/> or larger than <see cref="int.MaxValue"/>, /// or if <typeparamref name="TEnum"/> is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The enum value to convert.</param> /// <returns>The <see cref="int"/>.</returns> public static int ToInt32Checked<TEnum>(TEnum value) where TEnum : struct, Enum => Converter<TEnum, int, Checked>.ConvertTo(value); /// <summary> /// Converts the specified <see cref="int"/> into /// a <typeparamref name="TEnum"/>. /// </summary> /// <remarks> /// This method will fail if the <paramref name="value"/> is outside /// the range of valid values for the underlying type of /// <typeparamref name="TEnum"/>, or if <typeparamref name="TEnum"/> /// is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The <see cref="int"/> to convert.</param> /// <returns>The <typeparamref name="TEnum"/>.</returns> public static TEnum ToEnumChecked<TEnum>(int value) where TEnum : struct, Enum => Converter<TEnum, int, Checked>.ConvertFrom(value); /// <summary> /// Converts the specified <typeparamref name="TEnum"/> into /// a <see cref="ushort"/>. /// </summary> /// <remarks> /// This method will fail if the enum value is less than /// <see cref="ushort.MinValue"/> or larger than <see cref="ushort.MaxValue"/>, /// or if <typeparamref name="TEnum"/> is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The enum value to convert.</param> /// <returns>The <see cref="ushort"/>.</returns> public static ushort ToUInt16Checked<TEnum>(TEnum value) where TEnum : struct, Enum => Converter<TEnum, ushort, Checked>.ConvertTo(value); /// <summary> /// Converts the specified <see cref="ushort"/> into /// a <typeparamref name="TEnum"/>. /// </summary> /// <remarks> /// This method will fail if the <paramref name="value"/> is outside /// the range of valid values for the underlying type of /// <typeparamref name="TEnum"/>, or if <typeparamref name="TEnum"/> /// is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The <see cref="ushort"/> to convert.</param> /// <returns>The <typeparamref name="TEnum"/>.</returns> public static TEnum ConvertToEnumChecked<TEnum>(ushort value) where TEnum : struct, Enum => Converter<TEnum, ushort, Checked>.ConvertFrom(value); /// <summary> /// Converts the specified <typeparamref name="TEnum"/> into /// a <see cref="short"/>. /// </summary> /// <remarks> /// This method will fail if the enum value is less than /// <see cref="short.MinValue"/> or larger than <see cref="ushort.MaxValue"/>, /// or if <typeparamref name="TEnum"/> is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The enum value to convert.</param> /// <returns>The <see cref="short"/>.</returns> public static short ToInt16Checked<TEnum>(TEnum value) where TEnum : struct, Enum => Converter<TEnum, short, Checked>.ConvertTo(value); /// <summary> /// Converts the specified <see cref="short"/> into /// a <typeparamref name="TEnum"/>. /// </summary> /// <remarks> /// This method will fail if the <paramref name="value"/> is outside /// the range of valid values for the underlying type of /// <typeparamref name="TEnum"/>, or if <typeparamref name="TEnum"/> /// is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The <see cref="short"/> to convert.</param> /// <returns>The <typeparamref name="TEnum"/>.</returns> public static TEnum ToEnumChecked<TEnum>(short value) where TEnum : struct, Enum => Converter<TEnum, short, Checked>.ConvertFrom(value); /// <summary> /// Converts the specified <typeparamref name="TEnum"/> into /// a <see cref="byte"/>. /// </summary> /// <remarks> /// This method will fail if the enum value is less than /// <see cref="byte.MinValue"/> or larger than <see cref="byte.MaxValue"/>, /// or if <typeparamref name="TEnum"/> is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The enum value to convert.</param> /// <returns>The <see cref="byte"/>.</returns> public static byte ToByteChecked<TEnum>(TEnum value) where TEnum : struct, Enum => Converter<TEnum, byte, Checked>.ConvertTo(value); /// <summary> /// Converts the specified <see cref="byte"/> into /// a <typeparamref name="TEnum"/>. /// </summary> /// <remarks> /// This method will fail if the <paramref name="value"/> is outside /// the range of valid values for the underlying type of /// <typeparamref name="TEnum"/>, or if <typeparamref name="TEnum"/> /// is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The <see cref="byte"/> to convert.</param> /// <returns>The <typeparamref name="TEnum"/>.</returns> public static TEnum ToEnumChecked<TEnum>(byte value) where TEnum : struct, Enum => Converter<TEnum, byte, Checked>.ConvertFrom(value); /// <summary> /// Converts the specified <typeparamref name="TEnum"/> into /// a <see cref="sbyte"/>. /// </summary> /// <remarks> /// This method will fail if the enum value is less than /// <see cref="sbyte.MinValue"/> or larger than <see cref="sbyte.MaxValue"/>, /// or if <typeparamref name="TEnum"/> is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The enum value to convert.</param> /// <returns>The <see cref="sbyte"/>.</returns> public static sbyte ToSByteChecked<TEnum>(TEnum value) where TEnum : struct, Enum => Converter<TEnum, sbyte, Checked>.ConvertTo(value); /// <summary> /// Converts the specified <see cref="sbyte"/> into /// a <typeparamref name="TEnum"/>. /// </summary> /// <remarks> /// This method will fail if the <paramref name="value"/> is outside /// the range of valid values for the underlying type of /// <typeparamref name="TEnum"/>, or if <typeparamref name="TEnum"/> /// is not an enum. /// </remarks> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <param name="value">The <see cref="sbyte"/> to convert.</param> /// <returns>The <typeparamref name="TEnum"/>.</returns> public static TEnum ToEnumChecked<TEnum>(sbyte value) where TEnum : struct, Enum => Converter<TEnum, sbyte, Checked>.ConvertFrom(value); /// <summary> /// Gets the number of items in the specified <see cref="Enum"/>. /// </summary> /// <typeparam name="TEnum">The type of the enum.</typeparam> /// <returns>The member count.</returns> public static int Length<TEnum>() where TEnum : struct, Enum => ValueCache<TEnum>.Length(); private static readonly Dictionary<RuntimeTypeHandle, StringDictionary> s_enumDesc = new Dictionary<RuntimeTypeHandle, StringDictionary>(); public static string GetEnumDescription<TEnum>(this TEnum value) where TEnum : struct, Enum { Type typ = typeof(TEnum); if (!s_enumDesc.TryGetValue(typ.TypeHandle, out StringDictionary dict)) { lock (((System.Collections.ICollection)s_enumDesc).SyncRoot) { if (!s_enumDesc.TryGetValue(typ.TypeHandle, out dict)) { dict = new StringDictionary(); foreach (string name in Enum.GetNames(typ)) { // Try to get [Description] attribute FieldInfo field = typ.GetField(name); DescriptionAttribute attr = field.GetCustomAttribute<DescriptionAttribute>(false); // Populate dictionary dict[name] = attr == null ? name : attr.Description; } s_enumDesc[typ.TypeHandle] = dict; } } } return dict[value.ToString()]; } } }
using System; using CookComputing.XmlRpc; namespace Drupal7.Services { public interface IServiceSystem : IXmlRpcProxy { #region AddressField [XmlRpcMethod("services_addressfield.country_get_list")] XmlRpcStruct AddressFieldCountryGetList(); [XmlRpcMethod("services_addressfield.get_address_format")] XmlRpcStruct AddressFieldGetAddressFormat(string country_code); [XmlRpcMethod("services_addressfield.get_administrative_areas")] XmlRpcStruct AddressFieldGetAdministrativeAreas(string country_code); [XmlRpcMethod("services_addressfield.get_address_format_and_administrative_areas")] XmlRpcStruct AddressFieldGetAddressFormatAndAdministrativeAreas(string country_code); #endregion #region Comment [XmlRpcMethod("comment.create")] DrupalCommentCid CommentCreate(object comment); [XmlRpcBegin("comment.create")] IAsyncResult BeginCommentCreate(object comment, AsyncCallback callback, object asyncState); [XmlRpcEnd("comment.create")] DrupalCommentCid EndCommentCreate(IAsyncResult asyncResult); [XmlRpcMethod("comment.retrieve")] object CommentRetrieve(int cid); [XmlRpcMethod("comment.retrieve")] DrupalComment CommentRetrieve2(int cid); [XmlRpcBegin("comment.retrieve")] IAsyncResult BeginCommentRetrieve(int cid, AsyncCallback callback, object asyncState); [XmlRpcEnd("comment.retrieve")] object EndCommentRetrieve(IAsyncResult asyncResult); [XmlRpcMethod("comment.update")] object CommentUpdate(int cid, object comment); [XmlRpcBegin("comment.update")] IAsyncResult BeginCommentUpdate(int cid, object comment, AsyncCallback callback, object asyncState); [XmlRpcEnd("comment.update")] object EndCommentUpdate(IAsyncResult asyncResult); [XmlRpcMethod("comment.delete")] bool CommentDelete(int cid); [XmlRpcBegin("comment.delete")] IAsyncResult BeginCommentDelete(int cid, AsyncCallback callback, object asyncState); [XmlRpcEnd("comment.delete")] bool EndCommentDelete(IAsyncResult asyncResult); [XmlRpcMethod("comment.index")] XmlRpcStruct[] CommentIndex(int page, string fields, object parameters, int page_size); [XmlRpcBegin("comment.index")] IAsyncResult BeginCommentIndex(int page, string fields, object parameters, int page_size, AsyncCallback callback, object asyncState); [XmlRpcEnd("comment.index")] XmlRpcStruct[] EndCommentIndex(IAsyncResult asyncResult); [XmlRpcMethod("comment.countAll")] int CommentCountAll(int nid); [XmlRpcBegin("comment.countAll")] IAsyncResult BeginCommentCountAll(int nid, AsyncCallback callback, object asyncState); [XmlRpcEnd("comment.countAll")] int EndCommentCountAll(IAsyncResult asyncResult); [XmlRpcMethod("comment.countNew")] int CommentCountNew(int nid, int timestamp); [XmlRpcBegin("comment.countNew")] IAsyncResult BeginCommentCountNew(int nid, int timestamp, AsyncCallback callback, object asyncState); [XmlRpcEnd("comment.countNew")] int EndCommentCountNew(IAsyncResult asyncResult); #endregion #region Contact [XmlRpcMethod("contact.index")] DrupalContact[] ContactIndex(); [XmlRpcBegin("contact.index")] IAsyncResult BeginContactIndex(AsyncCallback callback, object asyncState); [XmlRpcEnd("contact.index")] DrupalContact[] EndContactIndex(IAsyncResult asyncResult); [XmlRpcMethod("contact.site")] bool ContactSite(string name, string mail, string subject, int cid, string message, bool copy); [XmlRpcBegin("contact.site")] IAsyncResult BeginContactSite(string name, string mail, string subject, int cid, string message, bool copy, AsyncCallback callback, object asyncState); [XmlRpcEnd("contact.site")] bool EndContactSite(IAsyncResult asyncResult); [XmlRpcMethod("contact.personal")] bool ContactPersonal(string name, string mail, string to, string subject, string message, bool copy); [XmlRpcBegin("contact.personal")] IAsyncResult BeginContactPersonal(string name, string mail, string to, string subject, string message, bool copy, AsyncCallback callback, object asyncState); [XmlRpcEnd("contact.personal")] bool EndContactPersonal(IAsyncResult asyncResult); #endregion #region Definition [XmlRpcMethod("definition.index")] XmlRpcStruct DefinitionIndex(); [XmlRpcBegin("definition.index")] IAsyncResult BeginDefinitionIndex(AsyncCallback callback, object asyncState); [XmlRpcEnd("definition.index")] XmlRpcStruct EndDefinitionIndex(IAsyncResult asyncResult); #endregion #region EntityComment [XmlRpcMethod("entity_comment.create")] object EntityCommentCreate(string method, string entity_type, object values); [XmlRpcMethod("entity_comment.retrieve")] XmlRpcStruct EntityCommentRetrieve(string method, string entity_type, int comment_id, string fields = "*"); [XmlRpcMethod("entity_comment.retrieve")] XmlRpcStruct EntityCommentRetrieve(string method, string entity_type, int comment_id, string fields, int revision); [XmlRpcMethod("entity_comment.update")] object EntityCommentUpdate(string method, string entity_type, int comment_id, object values); [XmlRpcMethod("entity_comment.delete")] void EntityCommentDelete(string method, string entity_type, int comment_id); [XmlRpcMethod("entity_comment.index")] XmlRpcStruct[] EntityCommentIndex(string method = "index", string entity_type = "comment", string fields = "*", object parameters = null, int page = 0, int pagesize = 20, string sort = "", string direction = "ASC"); [XmlRpcMethod("entity_comment.countAll")] string EntityCommentCountAll(int nid); [XmlRpcMethod("entity_comment.countNew")] string EntityCommentCountNew(int nid, int since = 0); #endregion #region EntityFile [XmlRpcMethod("entity_file.retrieve")] XmlRpcStruct EntityFileRetrieve(string method, string entity_type, int file_id, string fields = "*"); [XmlRpcMethod("entity_file.retrieve")] XmlRpcStruct EntityFileRetrieve(string method, string entity_type, int file_id, string fields, int revision); [XmlRpcMethod("entity_file.update")] object EntityFileUpdate(string method, string entity_type, int file_id, object values); [XmlRpcMethod("entity_file.delete")] void EntityFileDelete(string method, string entity_type, int file_id); [XmlRpcMethod("entity_file.index")] XmlRpcStruct[] EntityFileIndex(string method = "index", string entity_type = "file", string fields = "*", object parameters = null, int page = 0, int pagesize = 20, string sort = "", string direction = "ASC"); [XmlRpcMethod("entity_file.create")] object EntityFileCreate(string method, string entity_type, object values); [XmlRpcMethod("entity_file.create_raw")] object EntityFileCreateRaw(); #endregion #region EntityNode // TODO: Finish EntityNode. [XmlRpcMethod("entity_node.index")] XmlRpcStruct[] EntityNodeIndex(string method = "index", string entity_type = "node", string fields = "*", object parameters = null, int page = 0, int pagesize = 20, string sort = "", string direction = "ASC"); #endregion #region EntityPrivateMsgMessage // TODO: EntityPrivateMsgMessage #endregion #region EntityTaxonomyTerm // TODO: EntityTaxonomyTerm #endregion #region EntityTaxonomyVocabulary // TODO: EntityTaxonomyVocabulary #endregion #region EntityUser // TODO: EntityUser #endregion #region File [XmlRpcMethod("file.create")] DrupalFile FileCreate(DrupalFile file); [XmlRpcBegin("file.create")] IAsyncResult BeginFileCreate(DrupalFile file, AsyncCallback callback, object asyncState); [XmlRpcEnd("file.create")] DrupalFile EndFileCreate(IAsyncResult asyncResult); [XmlRpcMethod("file.retrieve")] DrupalFile FileRetrieve(int fid, bool include_file_contents, bool get_image_style); [XmlRpcBegin("file.retrieve")] IAsyncResult BeginFileRetrieve(int fid, bool include_file_contents, bool get_image_style, AsyncCallback callback, object asyncState); [XmlRpcEnd("file.retrieve")] DrupalFile EndFileRetrieve(IAsyncResult asyncResult); [XmlRpcMethod("file.delete")] bool FileDelete(int fid); [XmlRpcBegin("file.delete")] IAsyncResult BeginFileDelete(int fid, AsyncCallback callback, object asyncState); [XmlRpcEnd("file.delete")] bool EndFileDelete(IAsyncResult asyncResult); [XmlRpcMethod("file.index")] DrupalFile[] FileIndex(int page, string fields, XmlRpcStruct parameters, int page_size); [XmlRpcBegin("file.index")] IAsyncResult BeginFileIndex(int page, string fields, XmlRpcStruct parameters, int page_size, AsyncCallback callback, object asyncState); [XmlRpcEnd("file.index")] DrupalFile[] EndFileIndex(IAsyncResult asyncResult); [XmlRpcMethod("file.create_raw")] DrupalFile[] FileCreateRaw(); [XmlRpcBegin("file.create_raw")] IAsyncResult BeginFileCreateRaw(AsyncCallback callback, object asyncState); [XmlRpcEnd("file.create_raw")] DrupalFile[] EndFileCreateRaw(IAsyncResult asyncResult); #endregion #region Flag [XmlRpcMethod("flag.is_flagged")] bool FlagIsFlagged(string flag_name, int content_id, int uid); [XmlRpcBegin("flag.is_flagged")] IAsyncResult BeginFlagIsFlagged(string flag_name, int content_id, int uid, AsyncCallback callback, object asyncState); [XmlRpcMethod("flag.is_flagged")] bool FlagIsFlagged(string flag_name, int content_id); [XmlRpcBegin("flag.is_flagged")] IAsyncResult BeginFlagIsFlagged(string flag_name, int content_id, AsyncCallback callback, object asyncState); [XmlRpcEnd("flag.is_flagged")] bool EndFlagIsFlagged(IAsyncResult asyncResult); [XmlRpcMethod("flag.flag")] bool FlagFlag(string flag_name, int content_id, string action, int uid, bool skip_permission_check); [XmlRpcBegin("flag.flag")] IAsyncResult BeginFlagFlag(string flag_name, int content_id, string action, int uid, bool skip_permission_check, AsyncCallback callback, object asyncState); [XmlRpcMethod("flag.flag")] bool FlagFlag(string flag_name, int content_id, string action, bool skip_permission_check); [XmlRpcBegin("flag.flag")] IAsyncResult BeginFlagFlag(string flag_name, int content_id, string action, bool skip_permission_check, AsyncCallback callback, object asyncState); [XmlRpcEnd("flag.flag")] bool EndFlagFlag(IAsyncResult asyncResult); [XmlRpcMethod("flag.countall")] XmlRpcStruct FlagCountAll(string flag_name, int content_id); [XmlRpcBegin("flag.countall")] XmlRpcStruct BeginFlagCountAll(string flag_name, int content_id, AsyncCallback callback, object asyncState); [XmlRpcEnd("flag.countall")] XmlRpcStruct EndFlagCountAll(IAsyncResult asyncResult); #endregion #region Geocoder [XmlRpcMethod("geocoder.retrieve")] string GeocoderRetrieve(string handler, string data, string output); [XmlRpcBegin("geocoder.retrieve")] IAsyncResult BeginGeocoderRetrieve(string handler, string data, string output, AsyncCallback callback, object asyncState); [XmlRpcEnd("geocoder.retrieve")] string EndGeocoderRetrieve(IAsyncResult asyncResult); [XmlRpcMethod("geocoder.index")] XmlRpcStruct GeocoderIndex(); [XmlRpcBegin("geocoder.index")] IAsyncResult BeginGeocoderIndex(AsyncCallback callback, object asyncState); [XmlRpcEnd("geocoder.index")] XmlRpcStruct EndGeocoderIndex(IAsyncResult asyncResult); #endregion #region Menu [XmlRpcMethod("menu.retrieve")] object MenuRetrieve(string menu_name); [XmlRpcBegin("menu.retrieve")] IAsyncResult BeginMenuRetrieve(string menu_name, AsyncCallback callback, object asyncState); [XmlRpcEnd("menu.retrieve")] object EndMenuRetrieve(IAsyncResult asyncResult); #endregion #region Node [XmlRpcMethod("node.retrieve")] XmlRpcStruct NodeRetrieve(int nid); [XmlRpcBegin("node.retrieve")] IAsyncResult BeginNodeRetrieve(int nid, AsyncCallback callback, object asyncState); [XmlRpcEnd("node.retrieve")] XmlRpcStruct EndNodeRetrieve(IAsyncResult asyncResult); [XmlRpcMethod("node.create")] XmlRpcStruct NodeCreate(object node); [XmlRpcBegin("node.create")] IAsyncResult BeginNodeCreate(object node, AsyncCallback callback, object asyncState); [XmlRpcEnd("node.create")] XmlRpcStruct EndNodeCreate(IAsyncResult asyncResult); [XmlRpcMethod("node.update")] XmlRpcStruct NodeUpdate(int nid, object node); [XmlRpcBegin("node.update")] IAsyncResult BeginNodeUpdate(int nid, object node, AsyncCallback callback, object asyncState); [XmlRpcEnd("node.update")] XmlRpcStruct EndNodeUpdate(IAsyncResult asyncResult); [XmlRpcMethod("node.delete")] bool NodeDelete(int nid); [XmlRpcBegin("node.delete")] IAsyncResult BeginNodeDelete(int nid, AsyncCallback callback, object asyncState); [XmlRpcEnd("node.delete")] bool EndNodeDelete(IAsyncResult asyncResult); [XmlRpcMethod("node.index")] XmlRpcStruct[] NodeIndex(int page, string fields, XmlRpcStruct parameters, int page_size); [XmlRpcBegin("node.index")] IAsyncResult BeginNodeIndex(int page, string fields, XmlRpcStruct parameters, int page_size, AsyncCallback callback, object asyncState); [XmlRpcEnd("node.index")] XmlRpcStruct[] EndNodeIndex(IAsyncResult asyncResult); [XmlRpcMethod("node.files")] DrupalFile[] NodeFiles(int nid, bool include_file_contents, bool get_image_style); [XmlRpcBegin("node.files")] IAsyncResult BeginNodeFiles(int nid, bool include_file_contents, bool get_image_style, AsyncCallback callback, object asyncState); [XmlRpcEnd("node.files")] DrupalFile[] EndNodeFiles(IAsyncResult asyncResult); #endregion #region SearchNode [XmlRpcMethod("search_node.retrieve")] XmlRpcStruct[] SearchNodeRetrieve(object op, string keys, bool simple, string[] fields); [XmlRpcBegin("search_node.retrieve")] IAsyncResult BeginSearchNodeRetrieve(object op, string keys, bool simple, string[] fields, AsyncCallback callback, object asyncState); [XmlRpcEnd("search_node.retrieve")] XmlRpcStruct[] EndSearchNodeRetrieve(IAsyncResult asyncResult); #endregion #region SearchUser [XmlRpcMethod("search_user.retrieve")] DrupalUserSearchResult[] SearchUserRetrieve(object op, string keys); [XmlRpcBegin("search_user.retrieve")] IAsyncResult BeginSearchUserRetrieve(object op, string keys, AsyncCallback callback, object asyncState); [XmlRpcEnd("search_user.retrieve")] DrupalUserSearchResult[] EndSearchUserRetrieve(IAsyncResult asyncResult); #endregion #region System [XmlRpcMethod("system.connect")] DrupalSessionObject SystemConnect(); [XmlRpcBegin("system.connect")] IAsyncResult BeginSystemConnect(AsyncCallback callback, object asyncState); [XmlRpcEnd("system.connect")] DrupalSessionObject EndSystemConnect(IAsyncResult asyncResult); [XmlRpcMethod("system.get_variable")] object SystemGetVariable(string name, object @default); [XmlRpcBegin("system.get_variable")] IAsyncResult BeginSystemGetVariable(string name, object @default, AsyncCallback callback, object asyncState); [XmlRpcEnd("system.get_variable")] object EndSystemGetVariable(IAsyncResult asyncResult); [XmlRpcMethod("system.set_variable")] void SystemSetVariable(string name, object @value); [XmlRpcBegin("system.set_variable")] IAsyncResult BeginSystemSetVariable(string name, object @value, AsyncCallback callback, object asyncState); [XmlRpcEnd("system.set_variable")] void EndSystemSetVariable(IAsyncResult asyncResult); [XmlRpcMethod("system.del_variable")] void SystemDelVariable(string name); [XmlRpcBegin("system.del_variable")] IAsyncResult BeginSystemDelVariable(string name, AsyncCallback callback, object asyncState); [XmlRpcEnd("system.del_variable")] void EndSystemDelVariable(IAsyncResult asyncResult); #endregion #region TaxonomyTerm [XmlRpcMethod("taxonomy_term.retrieve")] object TaxonomyTermRetrieve(int tid); [XmlRpcBegin("taxonomy_term.retrieve")] IAsyncResult BeginTaxonomyTermRetrieve(int tid, AsyncCallback callback, object asyncState); [XmlRpcEnd("taxonomy_term.retrieve")] object EndTaxonomyTermRetrieve(IAsyncResult asyncResult); [XmlRpcMethod("taxonomy_term.create")] int TaxonomyTermCreate(XmlRpcStruct term); [XmlRpcBegin("taxonomy_term.create")] IAsyncResult BeginTaxonomyTermCreate(XmlRpcStruct term, AsyncCallback callback, object asyncState); [XmlRpcEnd("taxonomy_term.create")] int EndTaxonomyTermCreate(IAsyncResult asyncResult); [XmlRpcMethod("taxonomy_term.update")] int TaxonomyTermUpdate(int tid, XmlRpcStruct term); [XmlRpcBegin("taxonomy_term.update")] IAsyncResult BeginTaxonomyTermUpdate(int tid, XmlRpcStruct term, AsyncCallback callback, object asyncState); [XmlRpcEnd("taxonomy_term.update")] int EndTaxonomyTermUpdate(IAsyncResult asyncResult); [XmlRpcMethod("taxonomy_term.delete")] int TaxonomyTermDelete(int tid); [XmlRpcBegin("taxonomy_term.delete")] IAsyncResult BeginTaxonomyTermDelete(int tid, AsyncCallback callback, object asyncState); [XmlRpcEnd("taxonomy_term.delete")] int EndTaxonomyTermDelete(IAsyncResult asyncResult); [XmlRpcMethod("taxonomy_term.index")] XmlRpcStruct[] TaxonomyTermIndex(int page, string fields, XmlRpcStruct parameters, int page_size); [XmlRpcBegin("taxonomy_term.index")] IAsyncResult BeginTaxonomyTermIndex(int page, string fields, XmlRpcStruct parameters, int page_size, AsyncCallback callback, object asyncState); [XmlRpcEnd("taxonomy_term.index")] XmlRpcStruct[] EndTaxonomyTermIndex(IAsyncResult asyncResult); [XmlRpcMethod("taxonomy_term.selectNodes")] XmlRpcStruct[] TaxonomyTermSelectNodes(int tid, bool pager, int limit, object order); [XmlRpcBegin("taxonomy_term.selectNodes")] IAsyncResult BeginTaxonomyTermSelectNodes(int tid, bool pager, int limit, object order, AsyncCallback callback, object asyncState); [XmlRpcEnd("taxonomy_term.selectNodes")] XmlRpcStruct[] EndTaxonomyTermSelectNodes(IAsyncResult asyncResult); #endregion #region TaxonomyVocabulary [XmlRpcMethod("taxonomy_vocabulary.retrieve")] XmlRpcStruct TaxonomyVocabularyRetrieve(int vid); [XmlRpcBegin("taxonomy_vocabulary.retrieve")] IAsyncResult BeginTaxonomyVocabularyRetrieve(int vid, AsyncCallback callback, object asyncState); [XmlRpcEnd("taxonomy_vocabulary.retrieve")] XmlRpcStruct EndTaxonomyVocabularyRetrieve(IAsyncResult asyncResult); [XmlRpcMethod("taxonomy_vocabulary.create")] int TaxonomyVocabularyCreate(XmlRpcStruct vocabulary); [XmlRpcBegin("taxonomy_vocabulary.create")] IAsyncResult BeginTaxonomyVocabularyCreate(XmlRpcStruct vocabulary, AsyncCallback callback, object asyncState); [XmlRpcEnd("taxonomy_vocabulary.create")] int EndTaxonomyVocabularyCreate(IAsyncResult asyncResult); [XmlRpcMethod("taxonomy_vocabulary.update")] int TaxonomyVocabularyUpdate(int vid, XmlRpcStruct vocabulary); [XmlRpcBegin("taxonomy_vocabulary.update")] IAsyncResult BeginTaxonomyVocabularyUpdate(int vid, XmlRpcStruct vocabulary, AsyncCallback callback, object asyncState); [XmlRpcEnd("taxonomy_vocabulary.update")] int EndTaxonomyVocabularyUpdate(IAsyncResult asyncResult); [XmlRpcMethod("taxonomy_vocabulary.delete")] int TaxonomyVocabularyDelete(int vid); [XmlRpcBegin("taxonomy_vocabulary.delete")] IAsyncResult BeginTaxonomyVocabularyDelete(int vid, AsyncCallback callback, object asyncState); [XmlRpcEnd("taxonomy_vocabulary.delete")] int EndTaxonomyVocabularyDelete(IAsyncResult asyncResult); [XmlRpcMethod("taxonomy_vocabulary.index")] XmlRpcStruct[] TaxonomyVocabularyIndex(int page, string fields, XmlRpcStruct parameters, int page_size); [XmlRpcBegin("taxonomy_vocabulary.index")] IAsyncResult BeginTaxonomyVocabularyIndex(int page, string fields, XmlRpcStruct parameters, int page_size, AsyncCallback callback, object asyncState); [XmlRpcEnd("taxonomy_vocabulary.index")] XmlRpcStruct[] EndTaxonomyVocabularyIndex(IAsyncResult asyncResult); [XmlRpcMethod("taxonomy_vocabulary.getTree")] XmlRpcStruct[] TaxonomyVocabularyGetTree(int vid, int parent, int max_depth); [XmlRpcBegin("taxonomy_vocabulary.getTree")] IAsyncResult BeginTaxonomyVocabularyGetTree(int vid, int parent, int max_depth, AsyncCallback callback, object asyncState); [XmlRpcEnd("taxonomy_vocabulary.getTree")] XmlRpcStruct[] EndTaxonomyVocabularyGetTree(IAsyncResult asyncResult); #endregion #region User [XmlRpcMethod("user.retrieve")] XmlRpcStruct UserRetrieve(int uid); [XmlRpcBegin("user.retrieve")] IAsyncResult BeginUserRetrieve(int uid, AsyncCallback callback, object asyncState); [XmlRpcEnd("user.retrieve")] XmlRpcStruct EndUserRetrieve(IAsyncResult asyncResult); [XmlRpcMethod("user.create")] DrupalUser UserCreate(XmlRpcStruct account); [XmlRpcBegin("user.create")] IAsyncResult BeginUserCreate(XmlRpcStruct account, AsyncCallback callback, object asyncState); [XmlRpcEnd("user.create")] DrupalUser EndUserCreate(IAsyncResult asyncResult); [XmlRpcMethod("user.update")] DrupalUser UserUpdate(int uid, XmlRpcStruct account); [XmlRpcBegin("user.update")] IAsyncResult BeginUserUpdate(int uid, XmlRpcStruct account, AsyncCallback callback, object asyncState); [XmlRpcEnd("user.update")] DrupalUser EndUserUpdate(IAsyncResult asyncResult); [XmlRpcMethod("user.delete")] bool UserDelete(int uid); [XmlRpcBegin("user.delete")] IAsyncResult BeginUserDelete(int uid, AsyncCallback callback, object asyncState); [XmlRpcEnd("user.delete")] bool EndUserDelete(IAsyncResult asyncResult); [XmlRpcMethod("user.index")] XmlRpcStruct[] UserIndex(int page, string fields, XmlRpcStruct parameters, int page_size); [XmlRpcBegin("user.index")] IAsyncResult BeginUserIndex(int page, string fields, XmlRpcStruct parameters, int page_size, AsyncCallback callback, object asyncState); [XmlRpcEnd("user.index")] XmlRpcStruct[] EndUserIndex(IAsyncResult asyncResult); [XmlRpcMethod("user.login")] DrupalSessionObject UserLogin(string username, string password); [XmlRpcBegin("user.login")] IAsyncResult BeginUserLogin(string username, string password, AsyncCallback callback, object asyncState); [XmlRpcEnd("user.login")] DrupalSessionObject EndUserLogin(IAsyncResult asyncResult); [XmlRpcMethod("user.logout")] bool UserLogout(); [XmlRpcBegin("user.logout")] IAsyncResult BeginUserLogout(AsyncCallback callback, object asyncState); [XmlRpcEnd("user.logout")] bool EndUserLogout(IAsyncResult asyncResult); [XmlRpcMethod("user.register")] DrupalUser UserRegister(XmlRpcStruct account); [XmlRpcBegin("user.register")] IAsyncResult BeginUserRegister(XmlRpcStruct account, AsyncCallback callback, object asyncState); [XmlRpcEnd("user.register")] DrupalUser EndUserRegister(IAsyncResult asyncResult); [XmlRpcMethod("user.token")] DrupalUserToken UserToken(); [XmlRpcBegin("user.token")] IAsyncResult BeginUserToken(AsyncCallback callback, object asyncState); [XmlRpcEnd("user.token")] DrupalUserToken EndUserToken(IAsyncResult asyncResult); #endregion #region Views [XmlRpcMethod("views.retrieve")] XmlRpcStruct ViewsRetrieve(string view_name, string display_id, XmlRpcStruct args, int offset, int limit, object return_type, XmlRpcStruct filters); [XmlRpcBegin("views.retrieve")] IAsyncResult BeginViewsRetrieve(string view_name, string display_id, XmlRpcStruct args, int offset, int limit, object return_type, XmlRpcStruct filters, AsyncCallback callback, object asyncState); [XmlRpcEnd("views.retrieve")] XmlRpcStruct EndViewsRetrieve(IAsyncResult asyncResult); #endregion } }
/// <license> /// This is a port of the SciMark2a Java Benchmark to C# by /// Chris Re (cmr28@cornell.edu) and Werner Vogels (vogels@cs.cornell.edu) /// /// For details on the original authors see http://math.nist.gov/scimark2 /// /// This software is likely to burn your processor, bitflip your memory chips /// anihilate your screen and corrupt all your disks, so you it at your /// own risk. /// </license> using Microsoft.Xunit.Performance; using System; namespace SciMark2 { public static class kernel { [Benchmark] public static void benchFFT() { SciMark2.Random R = new SciMark2.Random(Constants.RANDOM_SEED); int N = Constants.FFT_SIZE; long Iterations = 20000; double[] x = RandomVector(2 * N, R); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { innerFFT(x, Iterations); } } validateFFT(N, x); } private static void innerFFT(double[] x, long Iterations) { for (int i = 0; i < Iterations; i++) { FFT.transform(x); // forward transform FFT.inverse(x); // backward transform } } private static void validateFFT(int N, double[] x) { const double EPS = 1.0e-10; if (FFT.test(x) / N > EPS) { throw new Exception("FFT failed to validate"); } } public static double measureFFT(int N, double mintime, Random R) { // initialize FFT data as complex (N real/img pairs) double[] x = RandomVector(2 * N, R); long cycles = 1; Stopwatch Q = new Stopwatch(); while (true) { Q.start(); innerFFT(x, cycles); Q.stop(); if (Q.read() >= mintime) break; cycles *= 2; } validateFFT(N, x); // approx Mflops return FFT.num_flops(N) * cycles / Q.read() * 1.0e-6; } [Benchmark] public static void benchSOR() { int N = Constants.SOR_SIZE; SciMark2.Random R = new SciMark2.Random(Constants.RANDOM_SEED); int Iterations = 20000; double[][] G = RandomMatrix(N, N, R); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { SOR.execute(1.25, G, Iterations); } } } public static double measureSOR(int N, double min_time, Random R) { double[][] G = RandomMatrix(N, N, R); Stopwatch Q = new Stopwatch(); int cycles = 1; while (true) { Q.start(); SOR.execute(1.25, G, cycles); Q.stop(); if (Q.read() >= min_time) break; cycles *= 2; } // approx Mflops return SOR.num_flops(N, N, cycles) / Q.read() * 1.0e-6; } [Benchmark] public static void benchMonteCarlo() { SciMark2.Random R = new SciMark2.Random(Constants.RANDOM_SEED); int Iterations = 40000000; foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { MonteCarlo.integrate(Iterations); } } } public static double measureMonteCarlo(double min_time, Random R) { Stopwatch Q = new Stopwatch(); int cycles = 1; while (true) { Q.start(); MonteCarlo.integrate(cycles); Q.stop(); if (Q.read() >= min_time) break; cycles *= 2; } // approx Mflops return MonteCarlo.num_flops(cycles) / Q.read() * 1.0e-6; } [Benchmark] public static void benchSparseMult() { int N = Constants.SPARSE_SIZE_M; int nz = Constants.SPARSE_SIZE_nz; int Iterations = 100000; SciMark2.Random R = new SciMark2.Random(Constants.RANDOM_SEED); double[] x = RandomVector(N, R); double[] y = new double[N]; int nr = nz / N; // average number of nonzeros per row int anz = nr * N; // _actual_ number of nonzeros double[] val = RandomVector(anz, R); int[] col = new int[anz]; int[] row = new int[N + 1]; row[0] = 0; for (int r = 0; r < N; r++) { // initialize elements for row r int rowr = row[r]; row[r + 1] = rowr + nr; int step = r / nr; if (step < 1) step = 1; // take at least unit steps for (int i = 0; i < nr; i++) col[rowr + i] = i * step; } foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { SparseCompRow.matmult(y, val, row, col, x, Iterations); } } } public static double measureSparseMatmult(int N, int nz, double min_time, Random R) { // initialize vector multipliers and storage for result // y = A*y; double[] x = RandomVector(N, R); double[] y = new double[N]; // initialize square sparse matrix // // for this test, we create a sparse matrix wit M/nz nonzeros // per row, with spaced-out evenly between the begining of the // row to the main diagonal. Thus, the resulting pattern looks // like // +-----------------+ // +* + // +*** + // +* * * + // +** * * + // +** * * + // +* * * * + // +* * * * + // +* * * * + // +-----------------+ // // (as best reproducible with integer artihmetic) // Note that the first nr rows will have elements past // the diagonal. int nr = nz / N; // average number of nonzeros per row int anz = nr * N; // _actual_ number of nonzeros double[] val = RandomVector(anz, R); int[] col = new int[anz]; int[] row = new int[N + 1]; row[0] = 0; for (int r = 0; r < N; r++) { // initialize elements for row r int rowr = row[r]; row[r + 1] = rowr + nr; int step = r / nr; if (step < 1) step = 1; // take at least unit steps for (int i = 0; i < nr; i++) col[rowr + i] = i * step; } Stopwatch Q = new Stopwatch(); int cycles = 1; while (true) { Q.start(); SparseCompRow.matmult(y, val, row, col, x, cycles); Q.stop(); if (Q.read() >= min_time) break; cycles *= 2; } // approx Mflops return SparseCompRow.num_flops(N, nz, cycles) / Q.read() * 1.0e-6; } [Benchmark] public static void benchmarkLU() { int N = Constants.LU_SIZE; SciMark2.Random R = new SciMark2.Random(Constants.RANDOM_SEED); int Iterations = 2000; double[][] A = RandomMatrix(N, N, R); double[][] lu = new double[N][]; for (int i = 0; i < N; i++) { lu[i] = new double[N]; } int[] pivot = new int[N]; foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Iterations; i++) { CopyMatrix(lu, A); LU.factor(lu, pivot); } } } validateLU(N, R, lu, A, pivot); } public static void validateLU(int N, SciMark2.Random R, double[][] lu, double[][] A, int[] pivot) { // verify that LU is correct double[] b = RandomVector(N, R); double[] x = NewVectorCopy(b); LU.solve(lu, pivot, x); const double EPS = 1.0e-12; if (normabs(b, matvec(A, x)) / N > EPS) { throw new Exception("LU failed to validate"); } } public static double measureLU(int N, double min_time, Random R) { // compute approx Mlfops, or O if LU yields large errors double[][] A = RandomMatrix(N, N, R); double[][] lu = new double[N][]; for (int i = 0; i < N; i++) { lu[i] = new double[N]; } int[] pivot = new int[N]; Stopwatch Q = new Stopwatch(); int cycles = 1; while (true) { Q.start(); for (int i = 0; i < cycles; i++) { CopyMatrix(lu, A); LU.factor(lu, pivot); } Q.stop(); if (Q.read() >= min_time) break; cycles *= 2; } validateLU(N, R, lu, A, pivot); return LU.num_flops(N) * cycles / Q.read() * 1.0e-6; } private static double[] NewVectorCopy(double[] x) { int N = x.Length; double[] y = new double[N]; for (int i = 0; i < N; i++) y[i] = x[i]; return y; } private static void CopyVector(double[] B, double[] A) { int N = A.Length; for (int i = 0; i < N; i++) B[i] = A[i]; } private static double normabs(double[] x, double[] y) { int N = x.Length; double sum = 0.0; for (int i = 0; i < N; i++) sum += System.Math.Abs(x[i] - y[i]); return sum; } private static void CopyMatrix(double[][] B, double[][] A) { int M = A.Length; int N = A[0].Length; int remainder = N & 3; // N mod 4; for (int i = 0; i < M; i++) { double[] Bi = B[i]; double[] Ai = A[i]; for (int j = 0; j < remainder; j++) Bi[j] = Ai[j]; for (int j = remainder; j < N; j += 4) { Bi[j] = Ai[j]; Bi[j + 1] = Ai[j + 1]; Bi[j + 2] = Ai[j + 2]; Bi[j + 3] = Ai[j + 3]; } } } private static double[][] RandomMatrix(int M, int N, Random R) { double[][] A = new double[M][]; for (int i = 0; i < M; i++) { A[i] = new double[N]; } for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) A[i][j] = R.nextDouble(); return A; } private static double[] RandomVector(int N, Random R) { double[] A = new double[N]; for (int i = 0; i < N; i++) A[i] = R.nextDouble(); return A; } private static double[] matvec(double[][] A, double[] x) { int N = x.Length; double[] y = new double[N]; matvec(A, x, y); return y; } private static void matvec(double[][] A, double[] x, double[] y) { int M = A.Length; int N = A[0].Length; for (int i = 0; i < M; i++) { double sum = 0.0; double[] Ai = A[i]; for (int j = 0; j < N; j++) sum += Ai[j] * x[j]; y[i] = sum; } } } }
using System; using System.ComponentModel; using UIKit; using Xamarin.Forms.PlatformConfiguration.iOSSpecific; namespace Xamarin.Forms.Platform.iOS { internal class ChildViewController : UIViewController { public override void ViewDidLayoutSubviews() { foreach (var vc in ChildViewControllers) vc.View.Frame = View.Bounds; } } internal class EventedViewController : ChildViewController { public override void ViewWillAppear(bool animated) { base.ViewWillAppear(animated); var eh = WillAppear; if (eh != null) eh(this, EventArgs.Empty); } public override void ViewWillDisappear(bool animated) { base.ViewWillDisappear(animated); var eh = WillDisappear; if (eh != null) eh(this, EventArgs.Empty); } public event EventHandler WillAppear; public event EventHandler WillDisappear; } public class TabletMasterDetailRenderer : UISplitViewController, IVisualElementRenderer, IEffectControlProvider { UIViewController _detailController; bool _disposed; EventTracker _events; InnerDelegate _innerDelegate; EventedViewController _masterController; MasterDetailPage _masterDetailPage; bool _masterVisible; VisualElementTracker _tracker; IPageController PageController => Element as IPageController; IElementController ElementController => Element as IElementController; protected MasterDetailPage MasterDetailPage => _masterDetailPage ?? (_masterDetailPage = (MasterDetailPage)Element); IMasterDetailPageController MasterDetailPageController => MasterDetailPage as IMasterDetailPageController; UIBarButtonItem PresentButton { get { return _innerDelegate == null ? null : _innerDelegate.PresentButton; } } protected override void Dispose(bool disposing) { if (_disposed) { return; } _disposed = true; if (disposing) { if (Element != null) { PageController.SendDisappearing(); Element.PropertyChanged -= HandlePropertyChanged; if (MasterDetailPage?.Master != null) { MasterDetailPage.Master.PropertyChanged -= HandleMasterPropertyChanged; } Element = null; } if (_tracker != null) { _tracker.Dispose(); _tracker = null; } if (_events != null) { _events.Dispose(); _events = null; } if (_masterController != null) { _masterController.WillAppear -= MasterControllerWillAppear; _masterController.WillDisappear -= MasterControllerWillDisappear; } ClearControllers(); } base.Dispose(disposing); } public VisualElement Element { get; private set; } public event EventHandler<VisualElementChangedEventArgs> ElementChanged; public SizeRequest GetDesiredSize(double widthConstraint, double heightConstraint) { return NativeView.GetSizeRequest(widthConstraint, heightConstraint); } public UIView NativeView { get { return View; } } public void SetElement(VisualElement element) { var oldElement = Element; Element = element; ViewControllers = new[] { _masterController = new EventedViewController(), _detailController = new ChildViewController() }; Delegate = _innerDelegate = new InnerDelegate(MasterDetailPage.MasterBehavior); UpdateControllers(); _masterController.WillAppear += MasterControllerWillAppear; _masterController.WillDisappear += MasterControllerWillDisappear; PresentsWithGesture = MasterDetailPage.IsGestureEnabled; OnElementChanged(new VisualElementChangedEventArgs(oldElement, element)); EffectUtilities.RegisterEffectControlProvider(this, oldElement, element); if (element != null) element.SendViewInitialized(NativeView); } public void SetElementSize(Size size) { Element.Layout(new Rectangle(Element.X, Element.Width, size.Width, size.Height)); } public UIViewController ViewController { get { return this; } } public override void ViewDidAppear(bool animated) { PageController.SendAppearing(); base.ViewDidAppear(animated); ToggleMaster(); } public override void ViewDidDisappear(bool animated) { base.ViewDidDisappear(animated); PageController?.SendDisappearing(); } public override void ViewDidLayoutSubviews() { base.ViewDidLayoutSubviews(); if (View.Subviews.Length < 2) return; var detailsBounds = _detailController.View.Frame; var masterBounds = _masterController.View.Frame; if (!masterBounds.IsEmpty) MasterDetailPageController.MasterBounds = new Rectangle(0, 0, masterBounds.Width, masterBounds.Height); if (!detailsBounds.IsEmpty) MasterDetailPageController.DetailBounds = new Rectangle(0, 0, detailsBounds.Width, detailsBounds.Height); } public override void ViewDidLoad() { base.ViewDidLoad(); UpdateBackground(); _tracker = new VisualElementTracker(this); _events = new EventTracker(this); _events.LoadEvents(NativeView); } public override void ViewWillDisappear(bool animated) { if (_masterVisible) PerformButtonSelector(); base.ViewWillDisappear(animated); } public override void ViewWillLayoutSubviews() { base.ViewWillLayoutSubviews(); _masterController.View.BackgroundColor = UIColor.White; } public override void WillRotate(UIInterfaceOrientation toInterfaceOrientation, double duration) { // On IOS8 the MasterViewController ViewAppear/Disappear weren't being called correctly after rotation // We now close the Master by using the new SplitView API, basicly we set it to hidden and right back to the Normal/AutomaticMode if (!MasterDetailPageController.ShouldShowSplitMode && _masterVisible) { MasterDetailPageController.CanChangeIsPresented = true; PreferredDisplayMode = UISplitViewControllerDisplayMode.PrimaryHidden; PreferredDisplayMode = UISplitViewControllerDisplayMode.Automatic; } MasterDetailPageController.UpdateMasterBehavior(); MessagingCenter.Send<IVisualElementRenderer>(this, NavigationRenderer.UpdateToolbarButtons); base.WillRotate(toInterfaceOrientation, duration); } public override UIViewController ChildViewControllerForStatusBarHidden() { if (((MasterDetailPage)Element).Detail != null) return (UIViewController)Platform.GetRenderer(((MasterDetailPage)Element).Detail); else return base.ChildViewControllerForStatusBarHidden(); } protected virtual void OnElementChanged(VisualElementChangedEventArgs e) { if (e.OldElement != null) e.OldElement.PropertyChanged -= HandlePropertyChanged; if (e.NewElement != null) e.NewElement.PropertyChanged += HandlePropertyChanged; var changed = ElementChanged; if (changed != null) changed(this, e); } void ClearControllers() { foreach (var controller in _masterController.ChildViewControllers) { controller.View.RemoveFromSuperview(); controller.RemoveFromParentViewController(); } foreach (var controller in _detailController.ChildViewControllers) { controller.View.RemoveFromSuperview(); controller.RemoveFromParentViewController(); } } void HandleMasterPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == Page.IconProperty.PropertyName || e.PropertyName == Page.TitleProperty.PropertyName) MessagingCenter.Send<IVisualElementRenderer>(this, NavigationRenderer.UpdateToolbarButtons); } void HandlePropertyChanged(object sender, PropertyChangedEventArgs e) { if (_tracker == null) return; if (e.PropertyName == "Master" || e.PropertyName == "Detail") UpdateControllers(); else if (e.PropertyName == MasterDetailPage.IsPresentedProperty.PropertyName) ToggleMaster(); else if (e.PropertyName == MasterDetailPage.IsGestureEnabledProperty.PropertyName) PresentsWithGesture = MasterDetailPage.IsGestureEnabled; MessagingCenter.Send<IVisualElementRenderer>(this, NavigationRenderer.UpdateToolbarButtons); } void MasterControllerWillAppear(object sender, EventArgs e) { _masterVisible = true; if (MasterDetailPageController.CanChangeIsPresented) ElementController.SetValueFromRenderer(MasterDetailPage.IsPresentedProperty, true); } void MasterControllerWillDisappear(object sender, EventArgs e) { _masterVisible = false; if (MasterDetailPageController.CanChangeIsPresented) ElementController.SetValueFromRenderer(MasterDetailPage.IsPresentedProperty, false); } void PerformButtonSelector() { DisplayModeButtonItem.Target.PerformSelector(DisplayModeButtonItem.Action, DisplayModeButtonItem, 0); } void ToggleMaster() { if (_masterVisible == MasterDetailPage.IsPresented || MasterDetailPageController.ShouldShowSplitMode) return; PerformButtonSelector(); } void UpdateBackground() { if (!string.IsNullOrEmpty(((Page)Element).BackgroundImage)) View.BackgroundColor = UIColor.FromPatternImage(UIImage.FromBundle(((Page)Element).BackgroundImage)); else if (Element.BackgroundColor == Color.Default) View.BackgroundColor = UIColor.White; else View.BackgroundColor = Element.BackgroundColor.ToUIColor(); } void UpdateControllers() { MasterDetailPage.Master.PropertyChanged -= HandleMasterPropertyChanged; if (Platform.GetRenderer(MasterDetailPage.Master) == null) Platform.SetRenderer(MasterDetailPage.Master, Platform.CreateRenderer(MasterDetailPage.Master)); if (Platform.GetRenderer(MasterDetailPage.Detail) == null) Platform.SetRenderer(MasterDetailPage.Detail, Platform.CreateRenderer(MasterDetailPage.Detail)); ClearControllers(); MasterDetailPage.Master.PropertyChanged += HandleMasterPropertyChanged; var master = Platform.GetRenderer(MasterDetailPage.Master).ViewController; var detail = Platform.GetRenderer(MasterDetailPage.Detail).ViewController; _masterController.View.AddSubview(master.View); _masterController.AddChildViewController(master); _detailController.View.AddSubview(detail.View); _detailController.AddChildViewController(detail); } class InnerDelegate : UISplitViewControllerDelegate { readonly MasterBehavior _masterPresentedDefaultState; public InnerDelegate(MasterBehavior masterPresentedDefaultState) { _masterPresentedDefaultState = masterPresentedDefaultState; } public UIBarButtonItem PresentButton { get; set; } public override bool ShouldHideViewController(UISplitViewController svc, UIViewController viewController, UIInterfaceOrientation inOrientation) { bool willHideViewController; switch (_masterPresentedDefaultState) { case MasterBehavior.Split: willHideViewController = false; break; case MasterBehavior.Popover: willHideViewController = true; break; case MasterBehavior.SplitOnPortrait: willHideViewController = !(inOrientation == UIInterfaceOrientation.Portrait || inOrientation == UIInterfaceOrientation.PortraitUpsideDown); break; default: willHideViewController = inOrientation == UIInterfaceOrientation.Portrait || inOrientation == UIInterfaceOrientation.PortraitUpsideDown; break; } return willHideViewController; } public override void WillHideViewController(UISplitViewController svc, UIViewController aViewController, UIBarButtonItem barButtonItem, UIPopoverController pc) { PresentButton = barButtonItem; } } void IEffectControlProvider.RegisterEffect(Effect effect) { VisualElementRenderer<VisualElement>.RegisterEffect(effect, View); } } }
using System; using GraphQL.Types; using Shouldly; using Xunit; namespace GraphQL.Tests.Initialization { public class SchemaInitializationTests : SchemaInitializationTestBase { [Fact] public void EmptyQuerySchema_Should_Throw() { ShouldThrow<EmptyQuerySchema, InvalidOperationException>("An Object type 'Empty' must define one or more fields."); } [Fact] public void SchemaWithDuplicateFields_Should_Throw() { ShouldThrow<SchemaWithDuplicateFields, InvalidOperationException>("The field 'field' must have a unique name within Object type 'Dup'; no two fields may share the same name."); } [Fact] public void SchemaWithDuplicateArguments_Should_Throw() { ShouldThrow<SchemaWithDuplicateArguments, InvalidOperationException>("The argument 'arg' must have a unique name within field 'Dup.field'; no two field arguments may share the same name."); } [Fact] public void SchemaWithDuplicateArgumentsInDirective_Should_Throw() { ShouldThrow<SchemaWithDuplicateArgumentsInDirective, InvalidOperationException>("The argument 'arg' must have a unique name within directive 'my'; no two directive arguments may share the same name."); } [Fact] public void EmptyInterfaceSchema_Should_Throw() { ShouldThrow<EmptyInterfaceSchema, InvalidOperationException>("An Interface type 'Empty' must define one or more fields."); } [Fact] public void SchemaWithDuplicateInterfaceFields_Should_Throw() { ShouldThrow<SchemaWithDuplicateInterfaceFields, InvalidOperationException>("The field 'field' must have a unique name within Interface type 'Dup'; no two fields may share the same name."); } [Fact] public void SchemaWithDeprecatedAppliedDirective_Should_Not_Throw() { ShouldNotThrow<SchemaWithDeprecatedAppliedDirective>(); } [Fact] public void SchemaWithNullDirectiveArgumentWhenShouldBeNonNull_Should_Throw() { ShouldThrow<SchemaWithNullDirectiveArgumentWhenShouldBeNonNull, InvalidOperationException>("Directive 'test' applied to field 'MyQuery.field' explicitly specifies 'null' value for required argument 'arg'. The value must be non-null."); } [Fact] public void SchemaWithArgumentsOnInputField_Should_Throw() { ShouldThrow<SchemaWithArgumentsOnInputField, InvalidOperationException>("The field 'id' of an Input Object type 'MyInput' must not have any arguments specified."); } [Fact] public void SchemaWithNotFullSpecifiedResolvedType_Should_Throw() { ShouldThrow<SchemaWithNotFullSpecifiedResolvedType, InvalidOperationException>("The field 'in' of an Input Object type 'InputString' must have non-null 'ResolvedType' property for all types in the chain."); } } public class EmptyQuerySchema : Schema { public EmptyQuerySchema() { Query = new ObjectGraphType { Name = "Empty" }; } } public class SchemaWithDuplicateArgumentsInDirective : Schema { public SchemaWithDuplicateArgumentsInDirective() { Query = new ObjectGraphType { Name = "q" }; Query.Fields.Add(new FieldType { Name = "f", ResolvedType = new StringGraphType() }); Directives.Register(new MyDirective()); } public class MyDirective : DirectiveGraphType { public MyDirective() : base("my", DirectiveLocation.Field) { Arguments = new QueryArguments( new QueryArgument<BooleanGraphType> { Name = "arg" }, new QueryArgument<BooleanGraphType> { Name = "arg" } ); } } } public class SchemaWithDuplicateFields : Schema { public SchemaWithDuplicateFields() { Query = new ObjectGraphType { Name = "Dup" }; Query.AddField(new FieldType { Name = "field", ResolvedType = new StringGraphType() }); Query.AddField(new FieldType { Name = "field_2", ResolvedType = new StringGraphType() }); // bypass HasField check Query.Fields.List[1].Name = "field"; } } public class SchemaWithDuplicateArguments : Schema { public SchemaWithDuplicateArguments() { Query = new ObjectGraphType { Name = "Dup" }; Query.Field( "field", new StringGraphType(), arguments: new QueryArguments( new QueryArgument<StringGraphType> { Name = "arg" }, new QueryArgument<StringGraphType> { Name = "arg" } )); } } public class EmptyInterfaceSchema : Schema { public EmptyInterfaceSchema() { Query = new ObjectGraphType { Name = "Query" }; Query.AddField(new FieldType { Name = "field", ResolvedType = new StringGraphType() }); var iface = new InterfaceGraphType { Name = "Empty", ResolveType = _ => null }; RegisterType(iface); Query.ResolvedInterfaces.Add(iface); } } public class SchemaWithDuplicateInterfaceFields : Schema { public SchemaWithDuplicateInterfaceFields() { Query = new ObjectGraphType { Name = "Query" }; var iface = new InterfaceGraphType { Name = "Dup", ResolveType = _ => null }; iface.AddField(new FieldType { Name = "field", ResolvedType = new StringGraphType() }); iface.AddField(new FieldType { Name = "field_2", ResolvedType = new StringGraphType() }); // bypass HasField check iface.Fields.List[1].Name = "field"; Query.AddField(new FieldType { Name = "field", ResolvedType = new StringGraphType() }); RegisterType(iface); Query.ResolvedInterfaces.Add(iface); } } public class SchemaWithDeprecatedAppliedDirective : Schema { public SchemaWithDeprecatedAppliedDirective() { Query = new ObjectGraphType { Name = "Query" }; var f = Query.AddField(new FieldType { Name = "field1", ResolvedType = new StringGraphType() }).ApplyDirective("deprecated", "reason", "aaa"); f.DeprecationReason.ShouldBe("aaa"); f.DeprecationReason = "bbb"; f.FindAppliedDirective("deprecated").FindArgument("reason").Value.ShouldBe("bbb"); } } public class SchemaWithNullDirectiveArgumentWhenShouldBeNonNull : Schema { public class TestDirective : DirectiveGraphType { public TestDirective() : base("test", DirectiveLocation.Schema, DirectiveLocation.FieldDefinition) { Arguments = new QueryArguments(new QueryArgument<NonNullGraphType<StringGraphType>> { Name = "arg" }); } } public SchemaWithNullDirectiveArgumentWhenShouldBeNonNull() { Query = new ObjectGraphType { Name = "MyQuery" }; Query.AddField(new FieldType { Name = "field", ResolvedType = new StringGraphType() }).ApplyDirective("test", "arg", null); Directives.Register(new TestDirective()); } } public class SchemaWithArgumentsOnInputField : Schema { public class MyInputGraphType : InputObjectGraphType { public MyInputGraphType() { Field<NonNullGraphType<StringGraphType>>("id", arguments: new QueryArguments(new QueryArgument<StringGraphType> { Name = "x" })); } } public SchemaWithArgumentsOnInputField() { Query = new ObjectGraphType { Name = "MyQuery" }; Query.AddField(new FieldType { Name = "field", ResolvedType = new StringGraphType(), Arguments = new QueryArguments(new QueryArgument<MyInputGraphType> { Name = "arg" }) }); } } // https://github.com/graphql-dotnet/graphql-dotnet/issues/2675 public class SchemaWithNotFullSpecifiedResolvedType : Schema { public SchemaWithNotFullSpecifiedResolvedType() { var stringFilterInputType = new InputObjectGraphType { Name = "InputString" }; stringFilterInputType.AddField(new FieldType { Name = "eq", ResolvedType = new StringGraphType() }); stringFilterInputType.AddField(new FieldType { Name = "in", ResolvedType = new ListGraphType<StringGraphType>() }); stringFilterInputType.AddField(new FieldType { Name = "not", ResolvedType = new NonNullGraphType<StringGraphType>() }); Query = new ObjectGraphType(); Query.Field( "test", new StringGraphType(), arguments: new QueryArguments(new QueryArgument(stringFilterInputType) { Name = "a" }), resolve: context => "ok"); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DotNetty.Handlers.Tls { using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.IO; using System.Net.Security; using System.Runtime.ExceptionServices; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using DotNetty.Buffers; using DotNetty.Codecs; using DotNetty.Common.Concurrency; using DotNetty.Common.Utilities; using DotNetty.Transport.Channels; public sealed class TlsHandler : ByteToMessageDecoder { const int ReadBufferSize = 4 * 1024; // todo: research perfect size static readonly Exception ChannelClosedException = new IOException("Channel is closed"); static readonly Action<Task, object> AuthenticationCompletionCallback = new Action<Task, object>(HandleAuthenticationCompleted); static readonly AsyncCallback SslStreamReadCallback = new AsyncCallback(HandleSslStreamRead); readonly SslStream sslStream; State state; readonly MediationStream mediationStream; IByteBuffer sslStreamReadBuffer; volatile IChannelHandlerContext capturedContext; PendingWriteQueue pendingUnencryptedWrites; Task lastContextWriteTask; TaskCompletionSource closeFuture; readonly bool isServer; readonly X509Certificate2 certificate; readonly string targetHost; TlsHandler(bool isServer, X509Certificate2 certificate, string targetHost, RemoteCertificateValidationCallback certificateValidationCallback) { Contract.Requires(!isServer || certificate != null); Contract.Requires(isServer || !string.IsNullOrEmpty(targetHost)); this.closeFuture = new TaskCompletionSource(); this.isServer = isServer; this.certificate = certificate; this.targetHost = targetHost; this.mediationStream = new MediationStream(this); this.sslStream = new SslStream(this.mediationStream, true, certificateValidationCallback); } public static TlsHandler Client(string targetHost) { return new TlsHandler(false, null, targetHost, null); } public static TlsHandler Client(string targetHost, X509Certificate2 certificate) { return new TlsHandler(false, certificate, targetHost, null); } public static TlsHandler Client(string targetHost, X509Certificate2 certificate, RemoteCertificateValidationCallback certificateValidationCallback) { return new TlsHandler(false, certificate, targetHost, certificateValidationCallback); } public static TlsHandler Server(X509Certificate2 certificate) { return new TlsHandler(true, certificate, null, null); } public X509Certificate LocalCertificate { get { return this.sslStream.LocalCertificate; } } public X509Certificate RemoteCertificate { get { return this.sslStream.RemoteCertificate; } } public void Dispose() { if (this.sslStream != null) { this.sslStream.Dispose(); } } public override void ChannelActive(IChannelHandlerContext context) { base.ChannelActive(context); if (!this.isServer) { this.EnsureAuthenticated(); } } public override void ChannelInactive(IChannelHandlerContext context) { // Make sure to release SslStream, // and notify the handshake future if the connection has been closed during handshake. this.HandleFailure(ChannelClosedException); base.ChannelInactive(context); } public override void ExceptionCaught(IChannelHandlerContext context, Exception exception) { if (IgnoreException(exception)) { // Close the connection explicitly just in case the transport // did not close the connection automatically. if (context.Channel.Active) { context.CloseAsync(); } } else { base.ExceptionCaught(context, exception); } } bool IgnoreException(Exception t) { if (t is ObjectDisposedException && this.closeFuture.Task.IsCompleted) { return true; } return false; } static void HandleAuthenticationCompleted(Task task, object state) { var self = (TlsHandler)state; switch (task.Status) { case TaskStatus.RanToCompletion: { State oldState = self.state; if ((oldState & State.AuthenticationCompleted) == 0) { self.state = (oldState | State.Authenticated) & ~(State.Authenticating | State.FlushedBeforeHandshake); self.capturedContext.FireUserEventTriggered(TlsHandshakeCompletionEvent.Success); if ((oldState & State.ReadRequestedBeforeAuthenticated) == State.ReadRequestedBeforeAuthenticated && !self.capturedContext.Channel.Configuration.AutoRead) { self.capturedContext.Read(); } if ((oldState & State.FlushedBeforeHandshake) != 0) { self.Wrap(self.capturedContext); self.capturedContext.Flush(); } } break; } case TaskStatus.Canceled: case TaskStatus.Faulted: { // ReSharper disable once AssignNullToNotNullAttribute -- task.Exception will be present as task is faulted State oldState = self.state; if ((oldState & State.AuthenticationCompleted) == 0) { self.state = (oldState | State.FailedAuthentication) & ~State.Authenticating; } self.HandleFailure(task.Exception); break; } default: throw new ArgumentOutOfRangeException("task", "Unexpected task status: " + task.Status); } } public override void HandlerAdded(IChannelHandlerContext context) { base.HandlerAdded(context); this.capturedContext = context; this.pendingUnencryptedWrites = new PendingWriteQueue(context); if (context.Channel.Active && !this.isServer) { // todo: support delayed initialization on an existing/active channel if in client mode this.EnsureAuthenticated(); } } protected override void HandlerRemovedInternal(IChannelHandlerContext context) { if (!this.pendingUnencryptedWrites.IsEmpty) { // Check if queue is not empty first because create a new ChannelException is expensive this.pendingUnencryptedWrites.RemoveAndFailAll(new ChannelException("Write has failed due to TlsHandler being removed from channel pipeline.")); } } protected override void Decode(IChannelHandlerContext context, IByteBuffer input, List<object> output) { // pass bytes to SslStream through input -> trigger HandleSslStreamRead. After this call sslStreamReadBuffer may or may not have bytes to read this.mediationStream.AcceptBytes(input); if (!this.EnsureAuthenticated()) { return; } IByteBuffer readBuffer = this.sslStreamReadBuffer; if (readBuffer == null) { this.sslStreamReadBuffer = readBuffer = context.Channel.Allocator.Buffer(ReadBufferSize); this.ScheduleSslStreamRead(); } if (readBuffer.IsReadable()) { // SslStream parsed at least one full frame and completed read request // Pass the buffer to a next handler in pipeline output.Add(readBuffer); this.sslStreamReadBuffer = null; } } public override void Read(IChannelHandlerContext context) { State oldState = this.state; if ((oldState & State.AuthenticationCompleted) == 0) { this.state = oldState | State.ReadRequestedBeforeAuthenticated; } context.Read(); } bool EnsureAuthenticated() { State oldState = this.state; if ((oldState & State.AuthenticationStarted) == 0) { this.state = oldState | State.Authenticating; if (this.isServer) { this.sslStream.AuthenticateAsServerAsync(this.certificate) // todo: change to begin/end .ContinueWith(AuthenticationCompletionCallback, this, TaskContinuationOptions.ExecuteSynchronously); } else { var certificateCollection = new X509Certificate2Collection(); if (this.certificate != null) { certificateCollection.Add(this.certificate); } this.sslStream.AuthenticateAsClientAsync(this.targetHost, certificateCollection, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false) // todo: change to begin/end .ContinueWith(AuthenticationCompletionCallback, this, TaskContinuationOptions.ExecuteSynchronously); } return false; } return (oldState & State.Authenticated) == State.Authenticated; } void ScheduleSslStreamRead() { try { IByteBuffer buf = this.sslStreamReadBuffer; this.sslStream.BeginRead(buf.Array, buf.ArrayOffset + buf.WriterIndex, buf.WritableBytes, SslStreamReadCallback, this); } catch (Exception ex) { this.HandleFailure(ex); throw; } } static void HandleSslStreamRead(IAsyncResult ar) { var self = (TlsHandler)ar.AsyncState; int length = self.sslStream.EndRead(ar); self.sslStreamReadBuffer.SetWriterIndex(self.sslStreamReadBuffer.ReaderIndex + length); // adjust byte buffer's writer index to reflect read progress } public override Task WriteAsync(IChannelHandlerContext context, object message) { if (!(message is IByteBuffer)) { return TaskEx.FromException(new UnsupportedMessageTypeException(message, typeof(IByteBuffer))); } return this.pendingUnencryptedWrites.Add(message); } public override void Flush(IChannelHandlerContext context) { if (this.pendingUnencryptedWrites.IsEmpty) { this.pendingUnencryptedWrites.Add(Unpooled.Empty); } if (!this.EnsureAuthenticated()) { this.state |= State.FlushedBeforeHandshake; return; } this.Wrap(context); context.Flush(); } void Wrap(IChannelHandlerContext context) { Contract.Assert(context == this.capturedContext); while (true) { object msg = this.pendingUnencryptedWrites.Current; if (msg == null) { break; } var buf = (IByteBuffer)msg; buf.ReadBytes(this.sslStream, buf.ReadableBytes); // this leads to FinishWrap being called 0+ times TaskCompletionSource promise = this.pendingUnencryptedWrites.Remove(); Task task = this.lastContextWriteTask; if (task != null) { task.LinkOutcome(promise); this.lastContextWriteTask = null; } else { promise.TryComplete(); } } } void FinishWrap(byte[] buffer, int offset, int count) { IByteBuffer output = this.capturedContext.Allocator.Buffer(count); output.WriteBytes(buffer, offset, count); if (!output.IsReadable()) { output.Release(); output = Unpooled.Empty; } this.lastContextWriteTask = this.capturedContext.WriteAsync(output); } public override Task CloseAsync(IChannelHandlerContext context) { this.sslStream.Close(); this.closeFuture.TryComplete(); return base.CloseAsync(context); } void HandleFailure(Exception cause) { // Release all resources such as internal buffers that SSLEngine // is managing. try { this.sslStream.Close(); } catch (Exception ex) { // todo: evaluate following: // only log in debug mode as it most likely harmless and latest chrome still trigger // this all the time. // // See https://github.com/netty/netty/issues/1340 //string msg = ex.Message; //if (msg == null || !msg.contains("possible truncation attack")) //{ // logger.debug("{} SSLEngine.closeInbound() raised an exception.", ctx.channel(), e); //} } this.NotifyHandshakeFailure(cause); this.pendingUnencryptedWrites.RemoveAndFailAll(cause); } void NotifyHandshakeFailure(Exception cause) { if ((this.state & State.AuthenticationCompleted) == 0) { // handshake was not completed yet => TlsHandler react to failure by closing the channel this.state = (this.state | State.FailedAuthentication) & ~State.Authenticating; this.capturedContext.FireUserEventTriggered(new TlsHandshakeCompletionEvent(cause)); this.capturedContext.CloseAsync(); } } [Flags] enum State { Authenticating = 1, Authenticated = 1 << 1, FailedAuthentication = 1 << 2, ReadRequestedBeforeAuthenticated = 1 << 3, FlushedBeforeHandshake = 1 << 4, AuthenticationStarted = Authenticating | Authenticated | FailedAuthentication, AuthenticationCompleted = Authenticated | FailedAuthentication } sealed class MediationStream : Stream { static readonly Action<Task, object> WriteCompleteCallback = HandleChannelWriteComplete; readonly TlsHandler owner; IByteBuffer pendingReadBuffer; readonly SynchronousAsyncResult<int> syncReadResult; TaskCompletionSource<int> readCompletionSource; AsyncCallback readCallback; ArraySegment<byte> sslOwnedBuffer; TaskCompletionSource writeCompletion; AsyncCallback writeCallback; public MediationStream(TlsHandler owner) { this.syncReadResult = new SynchronousAsyncResult<int>(); this.owner = owner; } public void AcceptBytes(IByteBuffer input) { TaskCompletionSource<int> tcs = this.readCompletionSource; if (tcs == null) { // there is no pending read operation - keep for future this.pendingReadBuffer = input; return; } ArraySegment<byte> sslBuffer = this.sslOwnedBuffer; Contract.Assert(sslBuffer.Array != null); int readableBytes = input.ReadableBytes; int length = Math.Min(sslBuffer.Count, readableBytes); input.ReadBytes(sslBuffer.Array, sslBuffer.Offset, length); tcs.TrySetResult(length); if (length < readableBytes) { // set buffer for consecutive read to use this.pendingReadBuffer = input; } AsyncCallback callback = this.readCallback; if (callback != null) { callback(tcs.Task); } } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { IByteBuffer pendingBuf = this.pendingReadBuffer; if (pendingBuf != null) { // we have the bytes available upfront - write out synchronously int readableBytes = pendingBuf.ReadableBytes; int length = Math.Min(count, readableBytes); pendingBuf.ReadBytes(buffer, offset, length); if (length == readableBytes) { // buffer has been read out to the end this.pendingReadBuffer = null; } return this.PrepareSyncReadResult(length, state); } // take note of buffer - we will pass bytes in here this.sslOwnedBuffer = new ArraySegment<byte>(buffer, offset, count); this.readCompletionSource = new TaskCompletionSource<int>(state); this.readCallback = callback; return this.readCompletionSource.Task; } public override int EndRead(IAsyncResult asyncResult) { SynchronousAsyncResult<int> syncResult = this.syncReadResult; if (ReferenceEquals(asyncResult, syncResult)) { return syncResult.Result; } Contract.Assert(!((Task<int>)asyncResult).IsCanceled); try { return ((Task<int>)asyncResult).Result; } catch (AggregateException ex) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); throw; // unreachable } finally { this.readCompletionSource = null; this.readCallback = null; this.sslOwnedBuffer = default(ArraySegment<byte>); } } public override void Write(byte[] buffer, int offset, int count) { this.owner.FinishWrap(buffer, offset, count); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { Task task = this.owner.capturedContext.WriteAndFlushAsync(Unpooled.WrappedBuffer(buffer, offset, count)); switch (task.Status) { case TaskStatus.RanToCompletion: // write+flush completed synchronously (and successfully) var result = new SynchronousAsyncResult<int>(); result.AsyncState = state; callback(result); return result; default: this.writeCallback = callback; var tcs = new TaskCompletionSource(state); this.writeCompletion = tcs; task.ContinueWith(WriteCompleteCallback, this, TaskContinuationOptions.ExecuteSynchronously); return tcs.Task; } } static void HandleChannelWriteComplete(Task writeTask, object state) { var self = (MediationStream)state; switch (writeTask.Status) { case TaskStatus.RanToCompletion: self.writeCompletion.TryComplete(); break; case TaskStatus.Canceled: self.writeCompletion.TrySetCanceled(); break; case TaskStatus.Faulted: self.writeCompletion.TrySetException(writeTask.Exception); break; default: throw new ArgumentOutOfRangeException("Unexpected task status: " + writeTask.Status); } if (self.writeCallback != null) { self.writeCallback(self.writeCompletion.Task); } } public override void EndWrite(IAsyncResult asyncResult) { this.writeCallback = null; this.writeCompletion = null; if (asyncResult is SynchronousAsyncResult<int>) { return; } try { ((Task<int>)asyncResult).Wait(); } catch (AggregateException ex) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); throw; } } IAsyncResult PrepareSyncReadResult(int readBytes, object state) { // it is safe to reuse sync result object as it can't lead to leak (no way to attach to it via handle) SynchronousAsyncResult<int> result = this.syncReadResult; result.Result = readBytes; result.AsyncState = state; return result; } public override void Flush() { // NOOP: called on SslStream.Close } #region plumbing public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return true; } } public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } #endregion #region sync result sealed class SynchronousAsyncResult<T> : IAsyncResult { public T Result { get; set; } public bool IsCompleted { get { return true; } } public WaitHandle AsyncWaitHandle { get { throw new InvalidOperationException("Cannot wait on a synchronous result."); } } public object AsyncState { get; set; } public bool CompletedSynchronously { get { return true; } } } #endregion } } }
using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; /* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Simulation { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LocalSimulationConnectorModule")] public class LocalSimulationConnectorModule : ISharedRegionModule, ISimulationService { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Is this module enabled? /// </summary> private bool m_ModuleEnabled = false; /// <summary> /// Map region ID to scene. /// </summary> private Dictionary<UUID, Scene> m_scenes = new Dictionary<UUID, Scene>(); /// <summary> /// Version of this service. /// </summary> /// <remarks> /// Currently valid versions are "SIMULATION/0.1" and "SIMULATION/0.2" /// </remarks> public string ServiceVersion { get; set; } #region Region Module interface public string Name { get { return "LocalSimulationConnectorModule"; } } public Type ReplaceableInterface { get { return null; } } public void AddRegion(Scene scene) { if (!m_ModuleEnabled) return; Init(scene); scene.RegisterModuleInterface<ISimulationService>(this); } public void Close() { } /// <summary> /// Can be called from other modules. /// </summary> /// <param name="scene"></param> public void Init(Scene scene) { lock (m_scenes) { if (!m_scenes.ContainsKey(scene.RegionInfo.RegionID)) m_scenes[scene.RegionInfo.RegionID] = scene; else m_log.WarnFormat( "[LOCAL SIMULATION CONNECTOR]: Tried to add region {0} but it is already present", scene.RegionInfo.RegionName); } } public void Initialise(IConfigSource configSource) { IConfig moduleConfig = configSource.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("SimulationServices", ""); if (name == Name) { InitialiseService(configSource); m_ModuleEnabled = true; m_log.Info("[LOCAL SIMULATION CONNECTOR]: Local simulation enabled."); } } } public void InitialiseService(IConfigSource configSource) { ServiceVersion = "SIMULATION/0.2"; IConfig config = configSource.Configs["SimulationService"]; if (config != null) { ServiceVersion = config.GetString("ConnectorProtocolVersion", ServiceVersion); if (ServiceVersion != "SIMULATION/0.1" && ServiceVersion != "SIMULATION/0.2") throw new Exception(string.Format("Invalid ConnectorProtocolVersion {0}", ServiceVersion)); m_log.InfoFormat( "[LOCAL SIMULATION CONNECTOR]: Initialized with connector protocol version {0}", ServiceVersion); } } public void PostInitialise() { } public void RegionLoaded(Scene scene) { } public void RemoveRegion(Scene scene) { if (!m_ModuleEnabled) return; RemoveScene(scene); scene.UnregisterModuleInterface<ISimulationService>(this); } /// <summary> /// Can be called from other modules. /// </summary> /// <param name="scene"></param> public void RemoveScene(Scene scene) { lock (m_scenes) { if (m_scenes.ContainsKey(scene.RegionInfo.RegionID)) m_scenes.Remove(scene.RegionInfo.RegionID); else m_log.WarnFormat( "[LOCAL SIMULATION CONNECTOR]: Tried to remove region {0} but it was not present", scene.RegionInfo.RegionName); } } #endregion Region Module interface #region ISimulationService public bool CloseAgent(GridRegion destination, UUID id, string auth_token) { if (destination == null) return false; if (m_scenes.ContainsKey(destination.RegionID)) { // m_log.DebugFormat( // "[LOCAL SIMULATION CONNECTOR]: Found region {0} {1} to send AgentUpdate", // s.RegionInfo.RegionName, destination.RegionHandle); m_scenes[destination.RegionID].CloseAgent(id, false, auth_token); return true; } //m_log.Debug("[LOCAL COMMS]: region not found in SendCloseAgent"); return false; } public bool CreateAgent(GridRegion source, GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, out string reason) { if (destination == null) { reason = "Given destination was null"; m_log.DebugFormat("[LOCAL SIMULATION CONNECTOR]: CreateAgent was given a null destination"); return false; } if (m_scenes.ContainsKey(destination.RegionID)) { // m_log.DebugFormat("[LOCAL SIMULATION CONNECTOR]: Found region {0} to send SendCreateChildAgent", destination.RegionName); return m_scenes[destination.RegionID].NewUserConnection(aCircuit, teleportFlags, source, out reason); } reason = "Did not find region " + destination.RegionName; return false; } public bool CreateObject(GridRegion destination, Vector3 newPosition, ISceneObject sog, bool isLocalCall) { if (destination == null) return false; if (m_scenes.ContainsKey(destination.RegionID)) { // m_log.DebugFormat( // "[LOCAL SIMULATION CONNECTOR]: Found region {0} {1} to send AgentUpdate", // s.RegionInfo.RegionName, destination.RegionHandle); Scene s = m_scenes[destination.RegionID]; if (isLocalCall) { // We need to make a local copy of the object ISceneObject sogClone = sog.CloneForNewScene(); sogClone.SetState(sog.GetStateSnapshot(), s); return s.IncomingCreateObject(newPosition, sogClone); } else { // Use the object as it came through the wire return s.IncomingCreateObject(newPosition, sog); } } return false; } public ISimulationService GetInnerService() { return this; } public IScene GetScene(UUID regionId) { if (m_scenes.ContainsKey(regionId)) { return m_scenes[regionId]; } else { // FIXME: This was pre-existing behaviour but possibly not a good idea, since it hides an error rather // than making it obvious and fixable. Need to see if the error message comes up in practice. Scene s = m_scenes.Values.ToArray()[0]; m_log.ErrorFormat( "[LOCAL SIMULATION CONNECTOR]: Region with id {0} not found. Returning {1} {2} instead", regionId, s.RegionInfo.RegionName, s.RegionInfo.RegionID); return s; } } /** * Agent-related communications */ public bool QueryAccess(GridRegion destination, UUID agentID, string agentHomeURI, Vector3 position, out string version, out string reason) { reason = "Communications failure"; version = ServiceVersion; if (destination == null) return false; if (m_scenes.ContainsKey(destination.RegionID)) { // m_log.DebugFormat( // "[LOCAL SIMULATION CONNECTOR]: Found region {0} {1} to send AgentUpdate", // s.RegionInfo.RegionName, destination.RegionHandle); return m_scenes[destination.RegionID].QueryAccess(agentID, agentHomeURI, position, out reason); } //m_log.Debug("[LOCAL COMMS]: region not found for QueryAccess"); return false; } public bool ReleaseAgent(UUID originId, UUID agentId, string uri) { if (m_scenes.ContainsKey(originId)) { // m_log.DebugFormat( // "[LOCAL SIMULATION CONNECTOR]: Found region {0} {1} to send AgentUpdate", // s.RegionInfo.RegionName, destination.RegionHandle); m_scenes[originId].EntityTransferModule.AgentArrivedAtDestination(agentId); return true; } //m_log.Debug("[LOCAL COMMS]: region not found in SendReleaseAgent " + origin); return false; } public bool UpdateAgent(GridRegion destination, AgentData cAgentData) { if (destination == null) return false; if (m_scenes.ContainsKey(destination.RegionID)) { // m_log.DebugFormat( // "[LOCAL SIMULATION CONNECTOR]: Found region {0} {1} to send AgentUpdate", // destination.RegionName, destination.RegionID); return m_scenes[destination.RegionID].IncomingUpdateChildAgent(cAgentData); } // m_log.DebugFormat( // "[LOCAL COMMS]: Did not find region {0} {1} for ChildAgentUpdate", // destination.RegionName, destination.RegionID); return false; } public bool UpdateAgent(GridRegion destination, AgentPosition agentPosition) { if (destination == null) return false; // We limit the number of messages sent for a position change to just one per // simulator so when we receive the update we need to hand it to each of the // scenes; scenes each check to see if the is a scene presence for the avatar // note that we really don't need the GridRegion for this call foreach (Scene s in m_scenes.Values) { // m_log.Debug("[LOCAL COMMS]: Found region to send ChildAgentUpdate"); s.IncomingUpdateChildAgent(agentPosition); } //m_log.Debug("[LOCAL COMMS]: region not found for ChildAgentUpdate"); return true; } /** * Object-related communications */ #endregion ISimulationService #region Misc public bool IsLocalRegion(ulong regionhandle) { foreach (Scene s in m_scenes.Values) if (s.RegionInfo.RegionHandle == regionhandle) return true; return false; } public bool IsLocalRegion(UUID id) { return m_scenes.ContainsKey(id); } #endregion Misc } }
/* * 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; using System.Collections.Generic; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Data; using System.Reflection; using log4net; using RegionFlags = OpenSim.Framework.RegionFlags; namespace OpenSim.Data.Null { public class NullRegionData : IRegionData { private static NullRegionData Instance = null; /// <summary> /// Should we use the static instance for all invocations? /// </summary> private bool m_useStaticInstance = true; // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); Dictionary<UUID, RegionData> m_regionData = new Dictionary<UUID, RegionData>(); public NullRegionData(string connectionString, string realm) { // m_log.DebugFormat( // "[NULL REGION DATA]: Constructor got connectionString {0}, realm {1}", connectionString, realm); // The !static connection string is a hack so that regression tests can use this module without a high degree of fragility // in having to deal with the static reference in the once-loaded NullRegionData class. // // In standalone operation, we have to use only one instance of this class since the login service and // simulator have no other way of using a common data store. if (connectionString == "!static") m_useStaticInstance = false; else if (Instance == null) Instance = this; } private delegate bool Matcher(string value); public List<RegionData> Get(string regionName, UUID scopeID) { if (m_useStaticInstance && Instance != this) return Instance.Get(regionName, scopeID); // m_log.DebugFormat("[NULL REGION DATA]: Getting region {0}, scope {1}", regionName, scopeID); string cleanName = regionName.ToLower(); // Handle SQL wildcards const string wildcard = "%"; bool wildcardPrefix = false; bool wildcardSuffix = false; if (cleanName.Equals(wildcard)) { wildcardPrefix = wildcardSuffix = true; cleanName = string.Empty; } else { if (cleanName.StartsWith(wildcard)) { wildcardPrefix = true; cleanName = cleanName.Substring(1); } if (regionName.EndsWith(wildcard)) { wildcardSuffix = true; cleanName = cleanName.Remove(cleanName.Length - 1); } } Matcher queryMatch; if (wildcardPrefix && wildcardSuffix) queryMatch = delegate(string s) { return s.Contains(cleanName); }; else if (wildcardSuffix) queryMatch = delegate(string s) { return s.StartsWith(cleanName); }; else if (wildcardPrefix) queryMatch = delegate(string s) { return s.EndsWith(cleanName); }; else queryMatch = delegate(string s) { return s.Equals(cleanName); }; // Find region data List<RegionData> ret = new List<RegionData>(); lock (m_regionData) { foreach (RegionData r in m_regionData.Values) { // m_log.DebugFormat("[NULL REGION DATA]: comparing {0} to {1}", cleanName, r.RegionName.ToLower()); if (queryMatch(r.RegionName.ToLower())) ret.Add(r); } } if (ret.Count > 0) return ret; return null; } public RegionData Get(int posX, int posY, UUID scopeID) { if (m_useStaticInstance && Instance != this) return Instance.Get(posX, posY, scopeID); RegionData ret = null; lock (m_regionData) { foreach (RegionData r in m_regionData.Values) { if (posX >= r.posX && posX < r.posX + r.sizeX && posY >= r.posY && posY < r.posY + r.sizeY) { ret = r; break; } } } return ret; } public RegionData Get(UUID regionID, UUID scopeID) { if (m_useStaticInstance && Instance != this) return Instance.Get(regionID, scopeID); lock (m_regionData) { if (m_regionData.ContainsKey(regionID)) return m_regionData[regionID]; } return null; } public List<RegionData> Get(int startX, int startY, int endX, int endY, UUID scopeID) { if (m_useStaticInstance && Instance != this) return Instance.Get(startX, startY, endX, endY, scopeID); List<RegionData> ret = new List<RegionData>(); lock (m_regionData) { foreach (RegionData r in m_regionData.Values) { if (r.posX + r.sizeX > startX && r.posX <= endX && r.posY + r.sizeX > startY && r.posY <= endY) ret.Add(r); } } return ret; } public bool Store(RegionData data) { if (m_useStaticInstance && Instance != this) return Instance.Store(data); // m_log.DebugFormat( // "[NULL REGION DATA]: Storing region {0} {1}, scope {2}", data.RegionName, data.RegionID, data.ScopeID); lock (m_regionData) { m_regionData[data.RegionID] = data; } return true; } public bool SetDataItem(UUID regionID, string item, string value) { if (m_useStaticInstance && Instance != this) return Instance.SetDataItem(regionID, item, value); lock (m_regionData) { if (!m_regionData.ContainsKey(regionID)) return false; m_regionData[regionID].Data[item] = value; } return true; } public bool Delete(UUID regionID) { if (m_useStaticInstance && Instance != this) return Instance.Delete(regionID); // m_log.DebugFormat("[NULL REGION DATA]: Deleting region {0}", regionID); lock (m_regionData) { if (!m_regionData.ContainsKey(regionID)) return false; m_regionData.Remove(regionID); } return true; } public List<RegionData> GetDefaultRegions(UUID scopeID) { return Get((int)RegionFlags.DefaultRegion, scopeID); } public List<RegionData> GetDefaultHypergridRegions(UUID scopeID) { return Get((int)RegionFlags.DefaultHGRegion, scopeID); } public List<RegionData> GetFallbackRegions(UUID scopeID, int x, int y) { List<RegionData> regions = Get((int)RegionFlags.FallbackRegion, scopeID); RegionDataDistanceCompare distanceComparer = new RegionDataDistanceCompare(x, y); regions.Sort(distanceComparer); return regions; } public List<RegionData> GetHyperlinks(UUID scopeID) { return Get((int)RegionFlags.Hyperlink, scopeID); } private List<RegionData> Get(int regionFlags, UUID scopeID) { if (Instance != this) return Instance.Get(regionFlags, scopeID); List<RegionData> ret = new List<RegionData>(); lock (m_regionData) { foreach (RegionData r in m_regionData.Values) { if ((Convert.ToInt32(r.Data["flags"]) & regionFlags) != 0) ret.Add(r); } } return ret; } } }
using System; using System.Collections.Generic; using LiteNetLib.Utils; //Some code parts taked from lidgren-network-gen3 namespace LiteNetLib { public interface INatPunchListener { void OnNatIntroductionRequest(NetEndPoint localEndPoint, NetEndPoint remoteEndPoint, string token); void OnNatIntroductionSuccess(NetEndPoint targetEndPoint, string token); } public class EventBasedNatPunchListener : INatPunchListener { public delegate void OnNatIntroductionRequest(NetEndPoint localEndPoint, NetEndPoint remoteEndPoint, string token); public delegate void OnNatIntroductionSuccess(NetEndPoint targetEndPoint, string token); public event OnNatIntroductionRequest NatIntroductionRequest; public event OnNatIntroductionSuccess NatIntroductionSuccess; void INatPunchListener.OnNatIntroductionRequest(NetEndPoint localEndPoint, NetEndPoint remoteEndPoint, string token) { if(NatIntroductionRequest != null) NatIntroductionRequest(localEndPoint, remoteEndPoint, token); } void INatPunchListener.OnNatIntroductionSuccess(NetEndPoint targetEndPoint, string token) { if (NatIntroductionSuccess != null) NatIntroductionSuccess(targetEndPoint, token); } } public sealed class NatPunchModule { struct RequestEventData { public NetEndPoint LocalEndPoint; public NetEndPoint RemoteEndPoint; public string Token; } struct SuccessEventData { public NetEndPoint TargetEndPoint; public string Token; } private readonly NetManager _netBase; private readonly Queue<RequestEventData> _requestEvents; private readonly Queue<SuccessEventData> _successEvents; private const byte HostByte = 1; private const byte ClientByte = 0; public const int MaxTokenLength = 256; private INatPunchListener _natPunchListener; internal NatPunchModule(NetManager netBase, NetSocket socket) { _netBase = netBase; _requestEvents = new Queue<RequestEventData>(); _successEvents = new Queue<SuccessEventData>(); } public void Init(INatPunchListener listener) { _natPunchListener = listener; } public void NatIntroduce( NetEndPoint hostInternal, NetEndPoint hostExternal, NetEndPoint clientInternal, NetEndPoint clientExternal, string additionalInfo) { NetDataWriter dw = new NetDataWriter(); //First packet (server) //send to client dw.Put(ClientByte); dw.Put(hostInternal); dw.Put(hostExternal); dw.Put(additionalInfo, MaxTokenLength); _netBase.SendRaw(NetPacket.CreateRawPacket(PacketProperty.NatIntroduction, dw), clientExternal); //Second packet (client) //send to server dw.Reset(); dw.Put(HostByte); dw.Put(clientInternal); dw.Put(clientExternal); dw.Put(additionalInfo, MaxTokenLength); _netBase.SendRaw(NetPacket.CreateRawPacket(PacketProperty.NatIntroduction, dw), hostExternal); } public void PollEvents() { if (_natPunchListener == null) return; lock (_successEvents) { while (_successEvents.Count > 0) { var evt = _successEvents.Dequeue(); _natPunchListener.OnNatIntroductionSuccess(evt.TargetEndPoint, evt.Token); } } lock (_requestEvents) { while (_requestEvents.Count > 0) { var evt = _requestEvents.Dequeue(); _natPunchListener.OnNatIntroductionRequest(evt.LocalEndPoint, evt.RemoteEndPoint, evt.Token); } } } public void SendNatIntroduceRequest(NetEndPoint masterServerEndPoint, string additionalInfo) { if (!_netBase.IsRunning) return; //prepare outgoing data NetDataWriter dw = new NetDataWriter(); string networkIp = NetUtils.GetLocalIp(true); int networkPort = _netBase.LocalEndPoint.Port; NetEndPoint localEndPoint = new NetEndPoint(networkIp, networkPort); dw.Put(localEndPoint); dw.Put(additionalInfo, MaxTokenLength); //prepare packet _netBase.SendRaw(NetPacket.CreateRawPacket(PacketProperty.NatIntroductionRequest, dw), masterServerEndPoint); } private void HandleNatPunch(NetEndPoint senderEndPoint, NetDataReader dr) { byte fromHostByte = dr.GetByte(); if (fromHostByte != HostByte && fromHostByte != ClientByte) { //garbage return; } //Read info string additionalInfo = dr.GetString(MaxTokenLength); NetUtils.DebugWrite(ConsoleColor.Green, "[NAT] punch received from {0} - additional info: {1}", senderEndPoint, additionalInfo); //Release punch success to client; enabling him to Connect() to msg.Sender if token is ok lock (_successEvents) { _successEvents.Enqueue(new SuccessEventData { TargetEndPoint = senderEndPoint, Token = additionalInfo }); } } private void HandleNatIntroduction(NetDataReader dr) { // read intro byte hostByte = dr.GetByte(); NetEndPoint remoteInternal = dr.GetNetEndPoint(); NetEndPoint remoteExternal = dr.GetNetEndPoint(); string token = dr.GetString(MaxTokenLength); NetUtils.DebugWrite(ConsoleColor.Cyan, "[NAT] introduction received; we are designated " + (hostByte == HostByte ? "host" : "client")); NetDataWriter writer = new NetDataWriter(); // send internal punch writer.Put(hostByte); writer.Put(token); _netBase.SendRaw(NetPacket.CreateRawPacket(PacketProperty.NatPunchMessage, writer), remoteInternal); NetUtils.DebugWrite(ConsoleColor.Cyan, "[NAT] internal punch sent to " + remoteInternal); // send external punch writer.Reset(); writer.Put(hostByte); writer.Put(token); _netBase.SendRaw(NetPacket.CreateRawPacket(PacketProperty.NatPunchMessage, writer), remoteExternal); NetUtils.DebugWrite(ConsoleColor.Cyan, "[NAT] external punch sent to " + remoteExternal); } private void HandleNatIntroductionRequest(NetEndPoint senderEndPoint, NetDataReader dr) { NetEndPoint localEp = dr.GetNetEndPoint(); string token = dr.GetString(MaxTokenLength); lock (_requestEvents) { _requestEvents.Enqueue(new RequestEventData { LocalEndPoint = localEp, RemoteEndPoint = senderEndPoint, Token = token }); } } internal void ProcessMessage(NetEndPoint senderEndPoint, PacketProperty property, byte[] data) { NetDataReader dr = new NetDataReader(data); switch (property) { case PacketProperty.NatIntroductionRequest: //We got request and must introduce HandleNatIntroductionRequest(senderEndPoint, dr); break; case PacketProperty.NatIntroduction: //We got introduce and must punch HandleNatIntroduction(dr); break; case PacketProperty.NatPunchMessage: //We got punch and can connect HandleNatPunch(senderEndPoint, dr); break; } } } }
/*************************************************************************** copyright : (C) 2005 by Brian Nickel : (C) 2006 Novell, Inc. email : brian.nickel@gmail.com : Aaron Bockover <abockover@novell.com> based on : tbytevector.cpp from TagLib ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License version * * 2.1 as published by the Free Software Foundation. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * * USA * ***************************************************************************/ using System.Collections; using System.Collections.Generic; using System; namespace TagLib { public enum StringType { Latin1 = 0, UTF16 = 1, UTF16BE = 2, UTF8 = 3, UTF16LE = 4 } public class ByteVector : IList<byte>, IComparable<ByteVector> { private List<byte> data = new List<byte>(); private static uint [] crc_table = new uint[256] { 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75, 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd, 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, 0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d, 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95, 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, 0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072, 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca, 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba, 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692, 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a, 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e, 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a, 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb, 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53, 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b, 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, 0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b, 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3, 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, 0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3, 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c, 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec, 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654, 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c, 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18, 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c, 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4 }; #region Constructors public ByteVector() { } public ByteVector(int size, byte value) { if(size > 0) { byte [] data = new byte[size]; for(int i = 0; i < size; i ++) { data[i] = value; } SetData(data); } } public ByteVector(int size) : this(size, 0) { } public ByteVector(ByteVector vector) { Add(vector); } public ByteVector(byte value) : this(1, value) { } public ByteVector (byte [] data, int length) { SetData(data, length); } public ByteVector(byte [] data) { SetData(data); } #endregion #region Properties public byte [] Data { get { return data.ToArray(); } } public bool IsEmpty { get { return Count == 0; } } public uint CheckSum { get { uint sum = 0; foreach(byte b in this) { sum = (sum << 8) ^ crc_table[((sum >> 24) & 0xFF) ^ b]; } return sum; } } #endregion #region Methods public void SetData(byte [] value, int length) { if(length >= value.Length) { SetData(value); } else { byte [] array = new byte[length]; for(int i = 0; i < length; i++) { array[i] = value[i]; } SetData(array); } } public void SetData(byte [] value) { Clear(); Add(value); } public ByteVector Mid(int index, int length) { if(length == Int32.MaxValue || index + length > Count) { length = Count - index; } ByteVector vector = new ByteVector(length); for(int i = 0; i < length; i ++) { vector[i] = this[i + index]; } return vector; } public ByteVector Mid(int index) { return Mid(index, Int32.MaxValue); } public int Find (ByteVector pattern, int offset, int byte_align) { if (pattern.Count > Count || offset >= Count - 1) return -1; // Let's go ahead and special case a pattern of size one since that's common // and easy to make fast. if (pattern.Count == 1) { byte p = pattern [0]; for (int i = offset; i < Count; i += byte_align) if (this [i] == p) return i; return -1; } int [] last_occurrence = new int [256]; for (int i = 0; i < 256; ++i) last_occurrence [i] = pattern.Count; for (int i = 0; i < pattern.Count - 1; ++i) last_occurrence [pattern [i]] = pattern.Count - i - 1; for (int i = pattern.Count - 1 + offset; i < Count; i += last_occurrence [this [i]]) { int iBuffer = i; int iPattern = pattern.Count - 1; while(iPattern >= 0 && this [iBuffer] == pattern [iPattern]) { --iBuffer; --iPattern; } if(-1 == iPattern && (iBuffer + 1) % byte_align == 0) return iBuffer + 1; } return -1; } public int Find(ByteVector pattern, int offset) { return Find(pattern, offset, 1); } public int Find(ByteVector pattern) { return Find(pattern, 0, 1); } public int RFind (ByteVector pattern, int offset, int byte_align) { if (pattern.Count == 0 || pattern.Count > Count || Count - pattern.Count - offset < 0) return -1; // Let's go ahead and special case a pattern of size one since that's common // and easy to make fast. if (pattern.Count == 1) { byte p = pattern [0]; for (int i = Count - offset - 1; i >= 0; i -= byte_align) if (this [i] == p) return i; return -1; } int [] first_occurrence = new int [256]; for (int i = 0; i < 256; ++i) first_occurrence [i] = pattern.Count; for (int i = pattern.Count - 1; i > 0; --i) first_occurrence [pattern [i]] = i; for (int i = Count - offset - pattern.Count; i >= 0; i -= first_occurrence [this [i]]) if (ContainsAt (pattern, i)) return i; return -1; } public int RFind(ByteVector pattern, int offset) { return RFind(pattern, offset, 1); } public int RFind(ByteVector pattern) { return RFind(pattern, 0, 1); } public bool ContainsAt(ByteVector pattern, int offset, int patternOffset, int patternLength) { if(pattern.Count < patternLength) { patternLength = pattern.Count; } // do some sanity checking -- all of these things are // needed for the search to be valid if(patternLength > Count || offset >= Count || patternOffset >= pattern.Count || patternLength == 0) { return false; } // loop through looking for a mismatch for(int i = 0; i < patternLength - patternOffset; i++) { if(this[i + offset] != pattern[i + patternOffset]) { return false; } } return true; } public bool ContainsAt(ByteVector pattern, int offset, int pattern_offset) { return ContainsAt(pattern, offset, pattern_offset, Int32.MaxValue); } public bool ContainsAt(ByteVector pattern, int offset) { return ContainsAt(pattern, offset, 0); } public bool StartsWith(ByteVector pattern) { return ContainsAt(pattern, 0); } public bool EndsWith(ByteVector pattern) { return ContainsAt(pattern, Count - pattern.Count); } public int EndsWithPartialMatch(ByteVector pattern) { if(pattern.Count > Count) { return -1; } int start_index = Count - pattern.Count; // try to match the last n-1 bytes from the vector (where n is // the pattern size) -- continue trying to match n-2, n-3...1 bytes for(int i = 1; i < pattern.Count; i++) { if(ContainsAt(pattern, start_index + i, 0, pattern.Count - i)) { return start_index + i; } } return -1; } public void Add(ByteVector vector) { if(vector != null) { data.AddRange(vector); } } public void Add(byte [] vector) { if(vector != null) { data.AddRange(vector); } } public void Insert (int index, ByteVector vector) { if(vector != null) { data.InsertRange (index, vector); } } public void Insert (int index, byte [] vector) { if(vector != null) { data.InsertRange (index, vector); } } public ByteVector Resize(int size, byte padding) { if(Count > size) { data.RemoveRange(size, Count - size); } while(Count < size) { Add(0); } return this; } public ByteVector Resize(int size) { return Resize(size, 0); } #endregion #region Conversions public uint ToUInt(bool msbFirst) { uint sum = 0; for(int i = 0, last = Count > 4 ? 3 : Count - 1; i <= last; i++) { sum |= (uint)this[i] << ((msbFirst ? last - i : i) * 8); } return sum; } public uint ToUInt() { return ToUInt(true); } public short ToShort(bool msbFirst) { short sum = 0; for(int i = 0, last = Count > 2 ? 1 : Count - 1; i <= last; i++) { sum |= (short)(this[i] << ((msbFirst ? last - i : i) * 8)); } return sum; } public short ToShort() { return ToShort(true); } public long ToLong(bool msbFirst) { long sum = 0; for(int i = 0, last = Count > 8 ? 7 : Count - 1; i <= last; i++) { sum |= (long)this [i] << ((msbFirst ? last - i : i) * 8); } return sum; } public long ToLong() { return ToLong(true); } public string ToString(StringType type, int offset) { ByteVector bom = type == StringType.UTF16 ? Mid(offset, 2) : null; string s = StringTypeToEncoding(type, bom).GetString(Data, offset, Count - offset); if(s.Length != 0 && (s[0] == 0xfffe || s[0] == 0xfeff)) { // UTF16 BOM return s.Substring(1); } return s; } public string ToString(StringType type) { return ToString (type, 0); } public override string ToString() { return ToString(StringType.UTF8); } #endregion #region Operators public static bool operator==(ByteVector a, ByteVector b) { if((object) a == null && (object) b == null) { return true; } else if((object) a == null || (object) b == null) { return false; } return a.Count == b.Count && a.StartsWith(b); } public static bool operator!=(ByteVector a, ByteVector b) { return !(a == b); } public static bool operator<(ByteVector a, ByteVector b) { for(int i = 0; i < a.Count && i < b.Count; i ++) { if(a[i] < b[i]) { return true; } } return a.Count < b.Count; } public static bool operator<=(ByteVector a, ByteVector b) { return a < b || a == b; } public static bool operator>(ByteVector a, ByteVector b) { for(int i = 0; i < a.Count && i < b.Count; i ++) { if(a[i] > b[i]) { return true; } } return a.Count > b.Count; } public static bool operator>=(ByteVector a, ByteVector b) { return a > b || a == b; } public static ByteVector operator+(ByteVector a, ByteVector b) { ByteVector sum = new ByteVector(a); sum.Add(b); return sum; } public static implicit operator ByteVector(byte c) { return new ByteVector(c); } public static implicit operator ByteVector(byte [] b) { return new ByteVector(b); } public static implicit operator ByteVector(string s) { return ByteVector.FromString(s); } #endregion #region Static Conversions public static ByteVector FromUInt(uint value, bool msbFirst) { ByteVector vector = new ByteVector(); for(int i = 0; i < 4; i++) { vector.Add((byte)(value >> ((msbFirst ? 3 - i : i) * 8) & 0xFF)); } return vector; } public static ByteVector FromUInt(uint value) { return FromUInt(value, true); } public static ByteVector FromShort(short value, bool msbFirst) { ByteVector vector = new ByteVector(); for(int i = 0; i < 2; i++) { vector.Add((byte)(value >> ((msbFirst ? 1 - i : i) * 8) & 0xFF)); } return vector; } public static ByteVector FromShort(short value) { return FromShort(value, true); } public static ByteVector FromLong(long value, bool msbFirst) { ByteVector vector = new ByteVector(); for(int i = 0; i < 8; i++) { vector.Add((byte)(value >> ((msbFirst ? 7 - i : i) * 8) & 0xFF)); } return vector; } public static ByteVector FromLong(long value) { return FromLong(value, true); } public static ByteVector FromString(string s, StringType type, int length) { if(s == null || s.Length == 0) { return new ByteVector(); } if(s.Length > length) { s = s.Substring(0, length); } byte [] data = StringTypeToEncoding(type, null).GetBytes(s); if(type != StringType.UTF16) { return new ByteVector(data); } byte [] ordered_data = new byte[data.Length + 2]; ordered_data[0] = 0xff; ordered_data[1] = 0xfe; data.CopyTo(ordered_data, 2); return new ByteVector(ordered_data); } public static ByteVector FromString(string s, StringType type) { return FromString(s, type, Int32.MaxValue); } public static ByteVector FromString(string s, int length) { return FromString(s, StringType.UTF8, length); } public static ByteVector FromString(string s) { return FromString (s, StringType.UTF8); } public static ByteVector FromUri(string uri) { byte [] tmp_out; return FromUri(uri, out tmp_out, false); } internal static ByteVector FromUri(string uri, out byte [] firstChunk, bool copyFirstChunk) { File.FileAbstractionCreator creator = File.GetFileAbstractionCreator(); File.IFileAbstraction abstraction = creator(uri); using(System.IO.Stream stream = abstraction.ReadStream) { return FromStream(stream, out firstChunk, copyFirstChunk); } } public static ByteVector FromStream(System.IO.Stream stream) { byte [] tmp_out; return FromStream(stream, out tmp_out, false); } internal static ByteVector FromStream(System.IO.Stream stream, out byte [] firstChunk, bool copyFirstChunk) { ByteVector vector = new ByteVector(); byte [] bytes = new byte[4096]; int read_size = bytes.Length; int bytes_read = 0; bool set_first_chunk = false; firstChunk = null; while(true) { Array.Clear(bytes, 0, bytes.Length); int n = stream.Read(bytes, 0, read_size); vector.Add(bytes); bytes_read += n; if(!set_first_chunk) { if(copyFirstChunk) { if(firstChunk == null || firstChunk.Length != read_size) { firstChunk = new byte[read_size]; } Array.Copy(bytes, 0, firstChunk, 0, n); } set_first_chunk = true; } if((bytes_read == stream.Length && stream.Length > 0) || (n < read_size && stream.Length <= 0)) { break; } } if(stream.Length > 0 && vector.Count != stream.Length) { vector.Resize((int)stream.Length); } return vector; } #endregion #region Utilities private static System.Text.Encoding StringTypeToEncoding(StringType type, ByteVector bom) { switch(type) { case StringType.UTF16: return (bom == null || (bom [0] == 0xFF && bom [1] == 0xFE)) ? System.Text.Encoding.Unicode : System.Text.Encoding.BigEndianUnicode; case StringType.UTF16BE: return System.Text.Encoding.BigEndianUnicode; case StringType.UTF8: return System.Text.Encoding.UTF8; case StringType.UTF16LE: return System.Text.Encoding.Unicode; } try { // The right format but not ECMA. return System.Text.Encoding.GetEncoding("latin1"); } catch { return System.Text.Encoding.UTF8; } } #endregion #region System.Object public override bool Equals(object o) { ByteVector vector = (ByteVector)o; return vector != null && vector == this; } public override int GetHashCode () { return Count; } #endregion #region IComparable<T> public int CompareTo(ByteVector vector) { if(this == vector) { return 0; } else if(this < vector) { return -1; } else { return 1; } } #endregion #region IEnumerable<T> public IEnumerator<byte> GetEnumerator() { return data.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return data.GetEnumerator(); } #endregion #region ICollection<T> public void Clear() { data.Clear(); } public void Add(byte value) { data.Add(value); } public bool Remove(byte value) { return data.Remove(value); } public void CopyTo(byte [] array, int index) { data.CopyTo(array, index); } public bool Contains(byte value) { return data.Contains(value); } public int Count { get { return data.Count; } } public bool IsSynchronized { get { return false; } } public object SyncRoot { get { return this; } } #endregion #region IList<T> public void RemoveAt(int index) { data.RemoveAt(index); } public void Insert(int index, byte value) { data.Insert(index, value); } public int IndexOf(byte value) { return data.IndexOf(value); } public bool IsReadOnly { get { return false; } } public bool IsFixedSize { get { return false; } } public byte this[int index] { get { return data[index]; } set { data[index] = value; } } #endregion } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V10.Services { /// <summary>Settings for <see cref="AdGroupBidModifierServiceClient"/> instances.</summary> public sealed partial class AdGroupBidModifierServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="AdGroupBidModifierServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="AdGroupBidModifierServiceSettings"/>.</returns> public static AdGroupBidModifierServiceSettings GetDefault() => new AdGroupBidModifierServiceSettings(); /// <summary> /// Constructs a new <see cref="AdGroupBidModifierServiceSettings"/> object with default settings. /// </summary> public AdGroupBidModifierServiceSettings() { } private AdGroupBidModifierServiceSettings(AdGroupBidModifierServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); MutateAdGroupBidModifiersSettings = existing.MutateAdGroupBidModifiersSettings; OnCopy(existing); } partial void OnCopy(AdGroupBidModifierServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AdGroupBidModifierServiceClient.MutateAdGroupBidModifiers</c> and /// <c>AdGroupBidModifierServiceClient.MutateAdGroupBidModifiersAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateAdGroupBidModifiersSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="AdGroupBidModifierServiceSettings"/> object.</returns> public AdGroupBidModifierServiceSettings Clone() => new AdGroupBidModifierServiceSettings(this); } /// <summary> /// Builder class for <see cref="AdGroupBidModifierServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class AdGroupBidModifierServiceClientBuilder : gaxgrpc::ClientBuilderBase<AdGroupBidModifierServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public AdGroupBidModifierServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public AdGroupBidModifierServiceClientBuilder() { UseJwtAccessWithScopes = AdGroupBidModifierServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref AdGroupBidModifierServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AdGroupBidModifierServiceClient> task); /// <summary>Builds the resulting client.</summary> public override AdGroupBidModifierServiceClient Build() { AdGroupBidModifierServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<AdGroupBidModifierServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<AdGroupBidModifierServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private AdGroupBidModifierServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return AdGroupBidModifierServiceClient.Create(callInvoker, Settings); } private async stt::Task<AdGroupBidModifierServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return AdGroupBidModifierServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => AdGroupBidModifierServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => AdGroupBidModifierServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => AdGroupBidModifierServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>AdGroupBidModifierService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage ad group bid modifiers. /// </remarks> public abstract partial class AdGroupBidModifierServiceClient { /// <summary> /// The default endpoint for the AdGroupBidModifierService service, which is a host of /// "googleads.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default AdGroupBidModifierService scopes.</summary> /// <remarks> /// The default AdGroupBidModifierService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="AdGroupBidModifierServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="AdGroupBidModifierServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="AdGroupBidModifierServiceClient"/>.</returns> public static stt::Task<AdGroupBidModifierServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new AdGroupBidModifierServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="AdGroupBidModifierServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="AdGroupBidModifierServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="AdGroupBidModifierServiceClient"/>.</returns> public static AdGroupBidModifierServiceClient Create() => new AdGroupBidModifierServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="AdGroupBidModifierServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="AdGroupBidModifierServiceSettings"/>.</param> /// <returns>The created <see cref="AdGroupBidModifierServiceClient"/>.</returns> internal static AdGroupBidModifierServiceClient Create(grpccore::CallInvoker callInvoker, AdGroupBidModifierServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } AdGroupBidModifierService.AdGroupBidModifierServiceClient grpcClient = new AdGroupBidModifierService.AdGroupBidModifierServiceClient(callInvoker); return new AdGroupBidModifierServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC AdGroupBidModifierService client</summary> public virtual AdGroupBidModifierService.AdGroupBidModifierServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes ad group bid modifiers. /// Operation statuses are returned. /// /// List of thrown errors: /// [AdGroupBidModifierError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateAdGroupBidModifiersResponse MutateAdGroupBidModifiers(MutateAdGroupBidModifiersRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes ad group bid modifiers. /// Operation statuses are returned. /// /// List of thrown errors: /// [AdGroupBidModifierError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdGroupBidModifiersResponse> MutateAdGroupBidModifiersAsync(MutateAdGroupBidModifiersRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes ad group bid modifiers. /// Operation statuses are returned. /// /// List of thrown errors: /// [AdGroupBidModifierError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdGroupBidModifiersResponse> MutateAdGroupBidModifiersAsync(MutateAdGroupBidModifiersRequest request, st::CancellationToken cancellationToken) => MutateAdGroupBidModifiersAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes ad group bid modifiers. /// Operation statuses are returned. /// /// List of thrown errors: /// [AdGroupBidModifierError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. ID of the customer whose ad group bid modifiers are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ad group bid modifiers. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateAdGroupBidModifiersResponse MutateAdGroupBidModifiers(string customerId, scg::IEnumerable<AdGroupBidModifierOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateAdGroupBidModifiers(new MutateAdGroupBidModifiersRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes ad group bid modifiers. /// Operation statuses are returned. /// /// List of thrown errors: /// [AdGroupBidModifierError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. ID of the customer whose ad group bid modifiers are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ad group bid modifiers. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdGroupBidModifiersResponse> MutateAdGroupBidModifiersAsync(string customerId, scg::IEnumerable<AdGroupBidModifierOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateAdGroupBidModifiersAsync(new MutateAdGroupBidModifiersRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes ad group bid modifiers. /// Operation statuses are returned. /// /// List of thrown errors: /// [AdGroupBidModifierError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. ID of the customer whose ad group bid modifiers are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual ad group bid modifiers. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateAdGroupBidModifiersResponse> MutateAdGroupBidModifiersAsync(string customerId, scg::IEnumerable<AdGroupBidModifierOperation> operations, st::CancellationToken cancellationToken) => MutateAdGroupBidModifiersAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>AdGroupBidModifierService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage ad group bid modifiers. /// </remarks> public sealed partial class AdGroupBidModifierServiceClientImpl : AdGroupBidModifierServiceClient { private readonly gaxgrpc::ApiCall<MutateAdGroupBidModifiersRequest, MutateAdGroupBidModifiersResponse> _callMutateAdGroupBidModifiers; /// <summary> /// Constructs a client wrapper for the AdGroupBidModifierService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="AdGroupBidModifierServiceSettings"/> used within this client. /// </param> public AdGroupBidModifierServiceClientImpl(AdGroupBidModifierService.AdGroupBidModifierServiceClient grpcClient, AdGroupBidModifierServiceSettings settings) { GrpcClient = grpcClient; AdGroupBidModifierServiceSettings effectiveSettings = settings ?? AdGroupBidModifierServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callMutateAdGroupBidModifiers = clientHelper.BuildApiCall<MutateAdGroupBidModifiersRequest, MutateAdGroupBidModifiersResponse>(grpcClient.MutateAdGroupBidModifiersAsync, grpcClient.MutateAdGroupBidModifiers, effectiveSettings.MutateAdGroupBidModifiersSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateAdGroupBidModifiers); Modify_MutateAdGroupBidModifiersApiCall(ref _callMutateAdGroupBidModifiers); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_MutateAdGroupBidModifiersApiCall(ref gaxgrpc::ApiCall<MutateAdGroupBidModifiersRequest, MutateAdGroupBidModifiersResponse> call); partial void OnConstruction(AdGroupBidModifierService.AdGroupBidModifierServiceClient grpcClient, AdGroupBidModifierServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC AdGroupBidModifierService client</summary> public override AdGroupBidModifierService.AdGroupBidModifierServiceClient GrpcClient { get; } partial void Modify_MutateAdGroupBidModifiersRequest(ref MutateAdGroupBidModifiersRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Creates, updates, or removes ad group bid modifiers. /// Operation statuses are returned. /// /// List of thrown errors: /// [AdGroupBidModifierError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateAdGroupBidModifiersResponse MutateAdGroupBidModifiers(MutateAdGroupBidModifiersRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateAdGroupBidModifiersRequest(ref request, ref callSettings); return _callMutateAdGroupBidModifiers.Sync(request, callSettings); } /// <summary> /// Creates, updates, or removes ad group bid modifiers. /// Operation statuses are returned. /// /// List of thrown errors: /// [AdGroupBidModifierError]() /// [AuthenticationError]() /// [AuthorizationError]() /// [ContextError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateAdGroupBidModifiersResponse> MutateAdGroupBidModifiersAsync(MutateAdGroupBidModifiersRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateAdGroupBidModifiersRequest(ref request, ref callSettings); return _callMutateAdGroupBidModifiers.Async(request, callSettings); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcdv = Google.Cloud.Dataplex.V1; using sys = System; namespace Google.Cloud.Dataplex.V1 { /// <summary>Resource name for the <c>Environment</c> resource.</summary> public sealed partial class EnvironmentName : gax::IResourceName, sys::IEquatable<EnvironmentName> { /// <summary>The possible contents of <see cref="EnvironmentName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/lakes/{lake}/environments/{environment}</c>. /// </summary> ProjectLocationLakeEnvironment = 1, } private static gax::PathTemplate s_projectLocationLakeEnvironment = new gax::PathTemplate("projects/{project}/locations/{location}/lakes/{lake}/environments/{environment}"); /// <summary>Creates a <see cref="EnvironmentName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="EnvironmentName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static EnvironmentName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new EnvironmentName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="EnvironmentName"/> with the pattern /// <c>projects/{project}/locations/{location}/lakes/{lake}/environments/{environment}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="lakeId">The <c>Lake</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="EnvironmentName"/> constructed from the provided ids.</returns> public static EnvironmentName FromProjectLocationLakeEnvironment(string projectId, string locationId, string lakeId, string environmentId) => new EnvironmentName(ResourceNameType.ProjectLocationLakeEnvironment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), lakeId: gax::GaxPreconditions.CheckNotNullOrEmpty(lakeId, nameof(lakeId)), environmentId: gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="EnvironmentName"/> with pattern /// <c>projects/{project}/locations/{location}/lakes/{lake}/environments/{environment}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="lakeId">The <c>Lake</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="EnvironmentName"/> with pattern /// <c>projects/{project}/locations/{location}/lakes/{lake}/environments/{environment}</c>. /// </returns> public static string Format(string projectId, string locationId, string lakeId, string environmentId) => FormatProjectLocationLakeEnvironment(projectId, locationId, lakeId, environmentId); /// <summary> /// Formats the IDs into the string representation of this <see cref="EnvironmentName"/> with pattern /// <c>projects/{project}/locations/{location}/lakes/{lake}/environments/{environment}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="lakeId">The <c>Lake</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="EnvironmentName"/> with pattern /// <c>projects/{project}/locations/{location}/lakes/{lake}/environments/{environment}</c>. /// </returns> public static string FormatProjectLocationLakeEnvironment(string projectId, string locationId, string lakeId, string environmentId) => s_projectLocationLakeEnvironment.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(lakeId, nameof(lakeId)), gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId))); /// <summary>Parses the given resource name string into a new <see cref="EnvironmentName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/lakes/{lake}/environments/{environment}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="environmentName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="EnvironmentName"/> if successful.</returns> public static EnvironmentName Parse(string environmentName) => Parse(environmentName, false); /// <summary> /// Parses the given resource name string into a new <see cref="EnvironmentName"/> instance; optionally allowing /// an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/lakes/{lake}/environments/{environment}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="environmentName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="EnvironmentName"/> if successful.</returns> public static EnvironmentName Parse(string environmentName, bool allowUnparsed) => TryParse(environmentName, allowUnparsed, out EnvironmentName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="EnvironmentName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/lakes/{lake}/environments/{environment}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="environmentName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="EnvironmentName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string environmentName, out EnvironmentName result) => TryParse(environmentName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="EnvironmentName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/lakes/{lake}/environments/{environment}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="environmentName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="EnvironmentName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string environmentName, bool allowUnparsed, out EnvironmentName result) { gax::GaxPreconditions.CheckNotNull(environmentName, nameof(environmentName)); gax::TemplatedResourceName resourceName; if (s_projectLocationLakeEnvironment.TryParseName(environmentName, out resourceName)) { result = FromProjectLocationLakeEnvironment(resourceName[0], resourceName[1], resourceName[2], resourceName[3]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(environmentName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private EnvironmentName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string environmentId = null, string lakeId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; EnvironmentId = environmentId; LakeId = lakeId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="EnvironmentName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/lakes/{lake}/environments/{environment}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="lakeId">The <c>Lake</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param> public EnvironmentName(string projectId, string locationId, string lakeId, string environmentId) : this(ResourceNameType.ProjectLocationLakeEnvironment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), lakeId: gax::GaxPreconditions.CheckNotNullOrEmpty(lakeId, nameof(lakeId)), environmentId: gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Environment</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string EnvironmentId { get; } /// <summary> /// The <c>Lake</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LakeId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationLakeEnvironment: return s_projectLocationLakeEnvironment.Expand(ProjectId, LocationId, LakeId, EnvironmentId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as EnvironmentName); /// <inheritdoc/> public bool Equals(EnvironmentName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(EnvironmentName a, EnvironmentName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(EnvironmentName a, EnvironmentName b) => !(a == b); } /// <summary>Resource name for the <c>Content</c> resource.</summary> public sealed partial class ContentName : gax::IResourceName, sys::IEquatable<ContentName> { /// <summary>The possible contents of <see cref="ContentName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/lakes/{lake}/content/{content}</c> /// . /// </summary> ProjectLocationLakeContent = 1, } private static gax::PathTemplate s_projectLocationLakeContent = new gax::PathTemplate("projects/{project}/locations/{location}/lakes/{lake}/content/{content}"); /// <summary>Creates a <see cref="ContentName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="ContentName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static ContentName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ContentName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ContentName"/> with the pattern /// <c>projects/{project}/locations/{location}/lakes/{lake}/content/{content}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="lakeId">The <c>Lake</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="contentId">The <c>Content</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ContentName"/> constructed from the provided ids.</returns> public static ContentName FromProjectLocationLakeContent(string projectId, string locationId, string lakeId, string contentId) => new ContentName(ResourceNameType.ProjectLocationLakeContent, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), lakeId: gax::GaxPreconditions.CheckNotNullOrEmpty(lakeId, nameof(lakeId)), contentId: gax::GaxPreconditions.CheckNotNullOrEmpty(contentId, nameof(contentId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ContentName"/> with pattern /// <c>projects/{project}/locations/{location}/lakes/{lake}/content/{content}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="lakeId">The <c>Lake</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="contentId">The <c>Content</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ContentName"/> with pattern /// <c>projects/{project}/locations/{location}/lakes/{lake}/content/{content}</c>. /// </returns> public static string Format(string projectId, string locationId, string lakeId, string contentId) => FormatProjectLocationLakeContent(projectId, locationId, lakeId, contentId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ContentName"/> with pattern /// <c>projects/{project}/locations/{location}/lakes/{lake}/content/{content}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="lakeId">The <c>Lake</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="contentId">The <c>Content</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ContentName"/> with pattern /// <c>projects/{project}/locations/{location}/lakes/{lake}/content/{content}</c>. /// </returns> public static string FormatProjectLocationLakeContent(string projectId, string locationId, string lakeId, string contentId) => s_projectLocationLakeContent.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(lakeId, nameof(lakeId)), gax::GaxPreconditions.CheckNotNullOrEmpty(contentId, nameof(contentId))); /// <summary>Parses the given resource name string into a new <see cref="ContentName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/lakes/{lake}/content/{content}</c></description> /// </item> /// </list> /// </remarks> /// <param name="contentName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ContentName"/> if successful.</returns> public static ContentName Parse(string contentName) => Parse(contentName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ContentName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/lakes/{lake}/content/{content}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="contentName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="ContentName"/> if successful.</returns> public static ContentName Parse(string contentName, bool allowUnparsed) => TryParse(contentName, allowUnparsed, out ContentName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ContentName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/lakes/{lake}/content/{content}</c></description> /// </item> /// </list> /// </remarks> /// <param name="contentName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="ContentName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string contentName, out ContentName result) => TryParse(contentName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ContentName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>projects/{project}/locations/{location}/lakes/{lake}/content/{content}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="contentName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="ContentName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string contentName, bool allowUnparsed, out ContentName result) { gax::GaxPreconditions.CheckNotNull(contentName, nameof(contentName)); gax::TemplatedResourceName resourceName; if (s_projectLocationLakeContent.TryParseName(contentName, out resourceName)) { result = FromProjectLocationLakeContent(resourceName[0], resourceName[1], resourceName[2], resourceName[3]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(contentName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private ContentName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string contentId = null, string lakeId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; ContentId = contentId; LakeId = lakeId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="ContentName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/lakes/{lake}/content/{content}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="lakeId">The <c>Lake</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="contentId">The <c>Content</c> ID. Must not be <c>null</c> or empty.</param> public ContentName(string projectId, string locationId, string lakeId, string contentId) : this(ResourceNameType.ProjectLocationLakeContent, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), lakeId: gax::GaxPreconditions.CheckNotNullOrEmpty(lakeId, nameof(lakeId)), contentId: gax::GaxPreconditions.CheckNotNullOrEmpty(contentId, nameof(contentId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Content</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ContentId { get; } /// <summary> /// The <c>Lake</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LakeId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationLakeContent: return s_projectLocationLakeContent.Expand(ProjectId, LocationId, LakeId, ContentId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as ContentName); /// <inheritdoc/> public bool Equals(ContentName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ContentName a, ContentName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ContentName a, ContentName b) => !(a == b); } /// <summary>Resource name for the <c>Session</c> resource.</summary> public sealed partial class SessionName : gax::IResourceName, sys::IEquatable<SessionName> { /// <summary>The possible contents of <see cref="SessionName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/lakes/{lake}/environments/{environment}/sessions/{session}</c> /// . /// </summary> ProjectLocationLakeEnvironmentSession = 1, } private static gax::PathTemplate s_projectLocationLakeEnvironmentSession = new gax::PathTemplate("projects/{project}/locations/{location}/lakes/{lake}/environments/{environment}/sessions/{session}"); /// <summary>Creates a <see cref="SessionName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="SessionName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static SessionName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new SessionName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="SessionName"/> with the pattern /// <c>projects/{project}/locations/{location}/lakes/{lake}/environments/{environment}/sessions/{session}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="lakeId">The <c>Lake</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="SessionName"/> constructed from the provided ids.</returns> public static SessionName FromProjectLocationLakeEnvironmentSession(string projectId, string locationId, string lakeId, string environmentId, string sessionId) => new SessionName(ResourceNameType.ProjectLocationLakeEnvironmentSession, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), lakeId: gax::GaxPreconditions.CheckNotNullOrEmpty(lakeId, nameof(lakeId)), environmentId: gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="SessionName"/> with pattern /// <c>projects/{project}/locations/{location}/lakes/{lake}/environments/{environment}/sessions/{session}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="lakeId">The <c>Lake</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SessionName"/> with pattern /// <c>projects/{project}/locations/{location}/lakes/{lake}/environments/{environment}/sessions/{session}</c>. /// </returns> public static string Format(string projectId, string locationId, string lakeId, string environmentId, string sessionId) => FormatProjectLocationLakeEnvironmentSession(projectId, locationId, lakeId, environmentId, sessionId); /// <summary> /// Formats the IDs into the string representation of this <see cref="SessionName"/> with pattern /// <c>projects/{project}/locations/{location}/lakes/{lake}/environments/{environment}/sessions/{session}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="lakeId">The <c>Lake</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="SessionName"/> with pattern /// <c>projects/{project}/locations/{location}/lakes/{lake}/environments/{environment}/sessions/{session}</c>. /// </returns> public static string FormatProjectLocationLakeEnvironmentSession(string projectId, string locationId, string lakeId, string environmentId, string sessionId) => s_projectLocationLakeEnvironmentSession.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(lakeId, nameof(lakeId)), gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId))); /// <summary>Parses the given resource name string into a new <see cref="SessionName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/lakes/{lake}/environments/{environment}/sessions/{session}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="sessionName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="SessionName"/> if successful.</returns> public static SessionName Parse(string sessionName) => Parse(sessionName, false); /// <summary> /// Parses the given resource name string into a new <see cref="SessionName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/lakes/{lake}/environments/{environment}/sessions/{session}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="sessionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="SessionName"/> if successful.</returns> public static SessionName Parse(string sessionName, bool allowUnparsed) => TryParse(sessionName, allowUnparsed, out SessionName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="SessionName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/lakes/{lake}/environments/{environment}/sessions/{session}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="sessionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="SessionName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string sessionName, out SessionName result) => TryParse(sessionName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="SessionName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>projects/{project}/locations/{location}/lakes/{lake}/environments/{environment}/sessions/{session}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="sessionName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="SessionName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string sessionName, bool allowUnparsed, out SessionName result) { gax::GaxPreconditions.CheckNotNull(sessionName, nameof(sessionName)); gax::TemplatedResourceName resourceName; if (s_projectLocationLakeEnvironmentSession.TryParseName(sessionName, out resourceName)) { result = FromProjectLocationLakeEnvironmentSession(resourceName[0], resourceName[1], resourceName[2], resourceName[3], resourceName[4]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(sessionName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private SessionName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string environmentId = null, string lakeId = null, string locationId = null, string projectId = null, string sessionId = null) { Type = type; UnparsedResource = unparsedResourceName; EnvironmentId = environmentId; LakeId = lakeId; LocationId = locationId; ProjectId = projectId; SessionId = sessionId; } /// <summary> /// Constructs a new instance of a <see cref="SessionName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/lakes/{lake}/environments/{environment}/sessions/{session}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="lakeId">The <c>Lake</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="environmentId">The <c>Environment</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="sessionId">The <c>Session</c> ID. Must not be <c>null</c> or empty.</param> public SessionName(string projectId, string locationId, string lakeId, string environmentId, string sessionId) : this(ResourceNameType.ProjectLocationLakeEnvironmentSession, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), lakeId: gax::GaxPreconditions.CheckNotNullOrEmpty(lakeId, nameof(lakeId)), environmentId: gax::GaxPreconditions.CheckNotNullOrEmpty(environmentId, nameof(environmentId)), sessionId: gax::GaxPreconditions.CheckNotNullOrEmpty(sessionId, nameof(sessionId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Environment</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string EnvironmentId { get; } /// <summary> /// The <c>Lake</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LakeId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Session</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string SessionId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationLakeEnvironmentSession: return s_projectLocationLakeEnvironmentSession.Expand(ProjectId, LocationId, LakeId, EnvironmentId, SessionId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as SessionName); /// <inheritdoc/> public bool Equals(SessionName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(SessionName a, SessionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(SessionName a, SessionName b) => !(a == b); } public partial class Environment { /// <summary> /// <see cref="gcdv::EnvironmentName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::EnvironmentName EnvironmentName { get => string.IsNullOrEmpty(Name) ? null : gcdv::EnvironmentName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class Content { /// <summary> /// <see cref="gcdv::ContentName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::ContentName ContentName { get => string.IsNullOrEmpty(Name) ? null : gcdv::ContentName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class Session { /// <summary> /// <see cref="gcdv::SessionName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::SessionName SessionName { get => string.IsNullOrEmpty(Name) ? null : gcdv::SessionName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
//--------------------------------------------------------------------- // <copyright file="ColumnEnums.cs" company="Microsoft Corporation"> // Copyright (c) 1999, Microsoft Corporation. All rights reserved. // </copyright> // <summary> // Part of the Deployment Tools Foundation project. // </summary> //--------------------------------------------------------------------- namespace Microsoft.PackageManagement.Msi.Internal.Deployment.WindowsInstaller { using System; using System.Diagnostics.CodeAnalysis; // Enumerations are in alphabetical order. /// <summary> /// Available values for the Attributes column of the Component table. /// </summary> [Flags] public enum ComponentAttributes : int { /// <summary> /// Local only - Component cannot be run from source. /// </summary> /// <remarks><p> /// Set this value for all components belonging to a feature to prevent the feature from being run-from-network or /// run-from-source. Note that if a feature has no components, the feature always shows run-from-source and /// run-from-my-computer as valid options. /// </p></remarks> None = 0x0000, /// <summary> /// Component can only be run from source. /// </summary> /// <remarks><p> /// Set this bit for all components belonging to a feature to prevent the feature from being run-from-my-computer. /// Note that if a feature has no components, the feature always shows run-from-source and run-from-my-computer /// as valid options. /// </p></remarks> SourceOnly = 0x0001, /// <summary> /// Component can run locally or from source. /// </summary> Optional = 0x0002, /// <summary> /// If this bit is set, the value in the KeyPath column is used as a key into the Registry table. /// </summary> /// <remarks><p> /// If the Value field of the corresponding record in the Registry table is null, the Name field in that record /// must not contain "+", "-", or "*". For more information, see the description of the Name field in Registry /// table. /// <p>Setting this bit is recommended for registry entries written to the HKCU hive. This ensures the installer /// writes the necessary HKCU registry entries when there are multiple users on the same machine.</p> /// </p></remarks> RegistryKeyPath = 0x0004, /// <summary> /// If this bit is set, the installer increments the reference count in the shared DLL registry of the component's /// key file. If this bit is not set, the installer increments the reference count only if the reference count /// already exists. /// </summary> SharedDllRefCount = 0x0008, /// <summary> /// If this bit is set, the installer does not remove the component during an uninstall. The installer registers /// an extra system client for the component in the Windows Installer registry settings. /// </summary> Permanent = 0x0010, /// <summary> /// If this bit is set, the value in the KeyPath column is a key into the ODBCDataSource table. /// </summary> OdbcDataSource = 0x0020, /// <summary> /// If this bit is set, the installer reevaluates the value of the statement in the Condition column upon a reinstall. /// If the value was previously False and has changed to true, the installer installs the component. If the value /// was previously true and has changed to false, the installer removes the component even if the component has /// other products as clients. /// </summary> Transitive = 0x0040, /// <summary> /// If this bit is set, the installer does not install or reinstall the component if a key path file or a key path /// registry entry for the component already exists. The application does register itself as a client of the component. /// </summary> /// <remarks><p> /// Use this flag only for components that are being registered by the Registry table. Do not use this flag for /// components registered by the AppId, Class, Extension, ProgId, MIME, and Verb tables. /// </p></remarks> NeverOverwrite = 0x0080, /// <summary> /// Set this bit to mark this as a 64-bit component. This attribute facilitates the installation of packages that /// include both 32-bit and 64-bit components. If this bit is not set, the component is registered as a 32-bit component. /// </summary> /// <remarks><p> /// If this is a 64-bit component replacing a 32-bit component, set this bit and assign a new GUID in the /// ComponentId column. /// </p></remarks> SixtyFourBit = 0x0100, /// <summary> /// Set this bit to disable registry reflection on all existing and new registry keys affected by this component. /// </summary> /// <remarks><p> /// If this bit is set, the Windows Installer calls the RegDisableReflectionKey on each key being accessed by the component. /// This bit is available with Windows Installer version 4.0 and is ignored on 32-bit systems. /// </p></remarks> DisableRegistryReflection = 0x0200, /// <summary> /// [MSI 4.5] Set this bit for a component in a patch package to prevent leaving orphan components on the computer. /// </summary> /// <remarks><p> /// If a subsequent patch is installed, marked with the SupersedeEarlier flag in its MsiPatchSequence /// table to supersede the first patch, Windows Installer 4.5 can unregister and uninstall components marked with the /// UninstallOnSupersedence value. If the component is not marked with this bit, installation of a superseding patch can leave /// behind an unused component on the computer. /// </p></remarks> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Supersedence")] UninstallOnSupersedence = 0x0400, /// <summary> /// [MSI 4.5] If a component is marked with this attribute value in at least one package installed on the system, /// the installer treats the component as marked in all packages. If a package that shares the marked component /// is uninstalled, Windows Installer 4.5 can continue to share the highest version of the component on the system, /// even if that highest version was installed by the package that is being uninstalled. /// </summary> Shared = 0x0800, } /// <summary> /// Defines flags for the Attributes column of the Control table. /// </summary> [Flags] public enum ControlAttributes : int { /// <summary>If this bit is set, the control is visible on the dialog box.</summary> Visible = 0x00000001, /// <summary>specifies if the given control is enabled or disabled. Most controls appear gray when disabled.</summary> Enabled = 0x00000002, /// <summary>If this bit is set, the control is displayed with a sunken, three dimensional look.</summary> Sunken = 0x00000004, /// <summary>The Indirect control attribute specifies whether the value displayed or changed by this control is referenced indirectly.</summary> Indirect = 0x00000008, /// <summary>If this bit is set on a control, the associated property specified in the Property column of the Control table is an integer.</summary> Integer = 0x00000010, /// <summary>If this bit is set the text in the control is displayed in a right-to-left reading order.</summary> RightToLeftReadingOrder = 0x00000020, /// <summary>If this style bit is set, text in the control is aligned to the right.</summary> RightAligned = 0x00000040, /// <summary>If this bit is set, the scroll bar is located on the left side of the control, otherwise it is on the right.</summary> LeftScroll = 0x00000080, /// <summary>This is a combination of the RightToLeftReadingOrder, RightAligned, and LeftScroll attributes.</summary> Bidirectional = RightToLeftReadingOrder | RightAligned | LeftScroll, /// <summary>If this bit is set on a text control, the control is displayed transparently with the background showing through the control where there are no characters.</summary> Transparent = 0x00010000, /// <summary>If this bit is set on a text control, the occurrence of the character "&amp;" in a text string is displayed as itself.</summary> NoPrefix = 0x00020000, /// <summary>If this bit is set the text in the control is displayed on a single line.</summary> NoWrap = 0x00040000, /// <summary>If this bit is set for a text control, the control will automatically attempt to format the displayed text as a number representing a count of bytes.</summary> FormatSize = 0x00080000, /// <summary>If this bit is set, fonts are created using the user's default UI code page. Otherwise it is created using the database code page.</summary> UsersLanguage = 0x00100000, /// <summary>If this bit is set on an Edit control, the installer creates a multiple line edit control with a vertical scroll bar.</summary> Multiline = 0x00010000, /// <summary>This attribute creates an edit control for entering passwords. The control displays each character as an asterisk (*) as they are typed into the control.</summary> PasswordInput = 0x00200000, /// <summary>If this bit is set on a ProgressBar control, the bar is drawn as a series of small rectangles in Microsoft Windows 95-style. Otherwise it is drawn as a single continuous rectangle.</summary> Progress95 = 0x00010000, /// <summary>If this bit is set, the control shows removable volumes.</summary> RemovableVolume = 0x00010000, /// <summary>If this bit is set, the control shows fixed internal hard drives.</summary> FixedVolume = 0x00020000, /// <summary>If this bit is set, the control shows remote volumes.</summary> RemoteVolume = 0x00040000, /// <summary>If this bit is set, the control shows CD-ROM volumes.</summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cdrom")] CdromVolume = 0x00080000, /// <summary>If this bit is set, the control shows RAM disk volumes.</summary> RamDiskVolume = 0x00100000, /// <summary>If this bit is set, the control shows floppy volumes.</summary> FloppyVolume = 0x00200000, /// <summary>Specifies whether or not the rollback backup files are included in the costs displayed by the VolumeCostList control.</summary> ShowRollbackCost = 0x00400000, /// <summary>If this bit is set, the items listed in the control are displayed in a specified order. Otherwise, items are displayed in alphabetical order.</summary> Sorted = 0x00010000, /// <summary>If this bit is set on a combo box, the edit field is replaced by a static text field. This prevents a user from entering a new value and requires the user to choose only one of the predefined values.</summary> ComboList = 0x00020000, //ImageHandle = 0x00010000, /// <summary>If this bit is set on a check box or a radio button group, the button is drawn with the appearance of a push button, but its logic stays the same.</summary> PushLike = 0x00020000, /// <summary>If this bit is set, the text in the control is replaced by a bitmap image. The Text column in the Control table is a foreign key into the Binary table.</summary> Bitmap = 0x00040000, /// <summary>If this bit is set, text is replaced by an icon image and the Text column in the Control table is a foreign key into the Binary table.</summary> Icon = 0x00080000, /// <summary>If this bit is set, the picture is cropped or centered in the control without changing its shape or size.</summary> FixedSize = 0x00100000, /// <summary>Specifies which size of the icon image to load. If none of the bits are set, the first image is loaded.</summary> IconSize16 = 0x00200000, /// <summary>Specifies which size of the icon image to load. If none of the bits are set, the first image is loaded.</summary> IconSize32 = 0x00400000, /// <summary>Specifies which size of the icon image to load. If none of the bits are set, the first image is loaded.</summary> IconSize48 = 0x00600000, /// <summary>If this bit is set, and the installation is not yet running with elevated privileges, the control is created with a UAC icon.</summary> ElevationShield = 0x00800000, /// <summary>If this bit is set, the RadioButtonGroup has text and a border displayed around it.</summary> HasBorder = 0x01000000, } /// <summary> /// Defines flags for the Type column of the CustomAction table. /// </summary> [SuppressMessage("Microsoft.Usage", "CA2217:DoNotMarkEnumsWithFlags")] [Flags] public enum CustomActionTypes : int { /// <summary>Unspecified custom action type.</summary> None = 0x0000, /// <summary>Target = entry point name</summary> Dll = 0x0001, /// <summary>Target = command line args</summary> Exe = 0x0002, /// <summary>Target = text string to be formatted and set into property</summary> TextData = 0x0003, /// <summary>Target = entry point name, null if none to call</summary> JScript = 0x0005, /// <summary>Target = entry point name, null if none to call</summary> VBScript = 0x0006, /// <summary>Target = property list for nested engine initialization</summary> Install = 0x0007, /// <summary>Source = File.File, file part of installation</summary> SourceFile = 0x0010, /// <summary>Source = Directory.Directory, folder containing existing file</summary> Directory = 0x0020, /// <summary>Source = Property.Property, full path to executable</summary> Property = 0x0030, /// <summary>Ignore action return status, continue running</summary> Continue = 0x0040, /// <summary>Run asynchronously</summary> Async = 0x0080, /// <summary>Skip if UI sequence already run</summary> FirstSequence = 0x0100, /// <summary>Skip if UI sequence already run in same process</summary> OncePerProcess = 0x0200, /// <summary>Run on client only if UI already run on client</summary> ClientRepeat = 0x0300, /// <summary>Queue for execution within script</summary> InScript = 0x0400, /// <summary>In conjunction with InScript: queue in Rollback script</summary> Rollback = 0x0100, /// <summary>In conjunction with InScript: run Commit ops from script on success</summary> Commit = 0x0200, /// <summary>No impersonation, run in system context</summary> NoImpersonate = 0x0800, /// <summary>Impersonate for per-machine installs on TS machines</summary> TSAware = 0x4000, /// <summary>Script requires 64bit process</summary> SixtyFourBitScript = 0x1000, /// <summary>Don't record the contents of the Target field in the log file</summary> HideTarget = 0x2000, /// <summary>The custom action runs only when a patch is being uninstalled</summary> PatchUninstall = 0x8000, } /// <summary> /// Defines flags for the Attributes column of the Dialog table. /// </summary> [Flags] public enum DialogAttributes : int { /// <summary>If this bit is set, the dialog is originally created as visible, otherwise it is hidden.</summary> Visible = 0x00000001, /// <summary>If this bit is set, the dialog box is modal, other dialogs of the same application cannot be put on top of it, and the dialog keeps the control while it is running.</summary> Modal = 0x00000002, /// <summary>If this bit is set, the dialog box can be minimized. This bit is ignored for modal dialog boxes, which cannot be minimized.</summary> Minimize = 0x00000004, /// <summary>If this style bit is set, the dialog box will stop all other applications and no other applications can take the focus.</summary> SysModal = 0x00000008, /// <summary>If this bit is set, the other dialogs stay alive when this dialog box is created.</summary> KeepModeless = 0x00000010, /// <summary>If this bit is set, the dialog box periodically calls the installer. If the property changes, it notifies the controls on the dialog.</summary> TrackDiskSpace = 0x00000020, /// <summary>If this bit is set, the pictures on the dialog box are created with the custom palette (one per dialog received from the first control created).</summary> UseCustomPalette = 0x00000040, /// <summary>If this style bit is set the text in the dialog box is displayed in right-to-left-reading order.</summary> RightToLeftReadingOrder = 0x00000080, /// <summary>If this style bit is set, the text is aligned on the right side of the dialog box.</summary> RightAligned = 0x00000100, /// <summary>If this style bit is set, the scroll bar is located on the left side of the dialog box.</summary> LeftScroll = 0x00000200, /// <summary>This is a combination of the RightToLeftReadingOrder, RightAligned, and the LeftScroll dialog style bits.</summary> Bidirectional = RightToLeftReadingOrder | RightAligned | LeftScroll, /// <summary>If this bit is set, the dialog box is an error dialog.</summary> Error = 0x00010000, } /// <summary> /// Available values for the Attributes column of the Feature table. /// </summary> [Flags] public enum FeatureAttributes : int { /// <summary> /// Favor local - Components of this feature that are not marked for installation from source are installed locally. /// </summary> /// <remarks><p> /// A component shared by two or more features, some of which are set to FavorLocal and some to FavorSource, /// is installed locally. Components marked <see cref="ComponentAttributes.SourceOnly"/> in the Component /// table are always run from the source CD/server. The bits FavorLocal and FavorSource work with features not /// listed by the ADVERTISE property. /// </p></remarks> None = 0x0000, /// <summary> /// Components of this feature not marked for local installation are installed to run from the source /// CD-ROM or server. /// </summary> /// <remarks><p> /// A component shared by two or more features, some of which are set to FavorLocal and some to FavorSource, /// is installed to run locally. Components marked <see cref="ComponentAttributes.None"/> (local-only) in the /// Component table are always installed locally. The bits FavorLocal and FavorSource work with features /// not listed by the ADVERTISE property. /// </p></remarks> FavorSource = 0x0001, /// <summary> /// Set this attribute and the state of the feature is the same as the state of the feature's parent. /// You cannot use this option if the feature is located at the root of a feature tree. /// </summary> /// <remarks><p> /// Omit this attribute and the feature state is determined according to DisallowAdvertise and /// FavorLocal and FavorSource. /// <p>To guarantee that the child feature's state always follows the state of its parent, even when the /// child and parent are initially set to absent in the SelectionTree control, you must include both /// FollowParent and UIDisallowAbsent in the attributes of the child feature.</p> /// <p>Note that if you set FollowParent without setting UIDisallowAbsent, the installer cannot force /// the child feature out of the absent state. In this case, the child feature matches the parent's /// installation state only if the child is set to something other than absent.</p> /// <p>Set FollowParent and UIDisallowAbsent to ensure a child feature follows the state of the parent feature.</p> /// </p></remarks> FollowParent = 0x0002, /// <summary> /// Set this attribute and the feature state is Advertise. /// </summary> /// <remarks><p> /// If the feature is listed by the ADDDEFAULT property this bit is ignored and the feature state is determined /// according to FavorLocal and FavorSource. /// <p>Omit this attribute and the feature state is determined according to DisallowAdvertise and FavorLocal /// and FavorSource.</p> /// </p></remarks> FavorAdvertise = 0x0004, /// <summary> /// Set this attribute to prevent the feature from being advertised. /// </summary> /// <remarks><p> /// Note that this bit works only with features that are listed by the ADVERTISE property. /// <p>Set this attribute and if the listed feature is not a parent or child, the feature is installed according to /// FavorLocal and FavorSource.</p> /// <p>Set this attribute for the parent of a listed feature and the parent is installed.</p> /// <p>Set this attribute for the child of a listed feature and the state of the child is Absent.</p> /// <p>Omit this attribute and if the listed feature is not a parent or child, the feature state is Advertise.</p> /// <p>Omit this attribute and if the listed feature is a parent or child, the state of both features is Advertise.</p> /// </p></remarks> DisallowAdvertise = 0x0008, /// <summary> /// Set this attribute and the user interface does not display an option to change the feature state /// to Absent. Setting this attribute forces the feature to the installation state, whether or not the /// feature is visible in the UI. /// </summary> /// <remarks><p> /// Omit this attribute and the user interface displays an option to change the feature state to Absent. /// <p>Set FollowParent and UIDisallowAbsent to ensure a child feature follows the state of the parent feature.</p> /// <p>Setting this attribute not only affects the UI, but also forces the feature to the install state whether /// the feature is visible in the UI or not.</p> /// </p></remarks> UIDisallowAbsent = 0x0010, /// <summary> /// Set this attribute and advertising is disabled for the feature if the operating system shell does not /// support Windows Installer descriptors. /// </summary> NoUnsupportedAdvertise = 0x0020, } /// <summary> /// Available values for the Attributes column of the File table. /// </summary> [Flags] public enum FileAttributes : int { /// <summary>No attributes.</summary> None = 0x0000, /// <summary>Read-only.</summary> ReadOnly = 0x0001, /// <summary>Hidden.</summary> Hidden = 0x0002, /// <summary>System.</summary> System = 0x0004, /// <summary>The file is vital for the proper operation of the component to which it belongs.</summary> Vital = 0x0200, /// <summary>The file contains a valid checksum. A checksum is required to repair a file that has become corrupted.</summary> Checksum = 0x0400, /// <summary>This bit must only be added by a patch and if the file is being added by the patch.</summary> PatchAdded = 0x1000, /// <summary> /// The file's source type is uncompressed. If set, ignore the WordCount summary information property. If neither /// Noncompressed nor Compressed are set, the compression state of the file is specified by the WordCount summary /// information property. Do not set both Noncompressed and Compressed. /// </summary> NonCompressed = 0x2000, /// <summary> /// The file's source type is compressed. If set, ignore the WordCount summary information property. If neither /// Noncompressed or Compressed are set, the compression state of the file is specified by the WordCount summary /// information property. Do not set both Noncompressed and Compressed. /// </summary> Compressed = 0x4000, } /// <summary> /// Defines values for the Action column of the IniFile and RemoveIniFile tables. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Ini")] public enum IniFileAction : int { /// <summary>Creates or updates a .ini entry.</summary> AddLine = 0, /// <summary>Creates a .ini entry only if the entry does not already exist.</summary> CreateLine = 1, /// <summary>Deletes .ini entry.</summary> RemoveLine = 2, /// <summary>Creates a new entry or appends a new comma-separated value to an existing entry.</summary> AddTag = 3, /// <summary>Deletes a tag from a .ini entry.</summary> RemoveTag = 4, } /// <summary> /// Defines values for the Type column of the CompLocator, IniLocator, and RegLocator tables. /// </summary> [Flags] [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")] public enum LocatorTypes : int { /// <summary>Key path is a directory.</summary> Directory = 0x00000000, /// <summary>Key path is a file name.</summary> FileName = 0x00000001, /// <summary>Key path is a registry value.</summary> RawValue = 0x00000002, /// <summary>Set this bit to have the installer search the 64-bit portion of the registry.</summary> SixtyFourBit = 0x00000010, } /// <summary> /// Defines values for the Root column of the Registry, RemoveRegistry, and RegLocator tables. /// </summary> public enum RegistryRoot : int { /// <summary>HKEY_CURRENT_USER for a per-user installation, /// or HKEY_LOCAL_MACHINE for a per-machine installation.</summary> UserOrMachine = -1, /// <summary>HKEY_CLASSES_ROOT</summary> ClassesRoot = 0, /// <summary>HKEY_CURRENT_USER</summary> CurrentUser = 1, /// <summary>HKEY_LOCAL_MACHINE</summary> LocalMachine = 2, /// <summary>HKEY_USERS</summary> Users = 3, } /// <summary> /// Defines values for the InstallMode column of the RemoveFile table. /// </summary> [Flags] public enum RemoveFileModes : int { /// <summary>Never remove.</summary> None = 0, /// <summary>Remove when the associated component is being installed (install state = local or source).</summary> OnInstall = 1, /// <summary>Remove when the associated component is being removed (install state = absent).</summary> OnRemove = 2, } /// <summary> /// Defines values for the ServiceType, StartType, and ErrorControl columns of the ServiceInstall table. /// </summary> [Flags] public enum ServiceAttributes : int { /// <summary>No flags.</summary> None = 0, /// <summary>A Win32 service that runs its own process.</summary> OwnProcess = 0x0010, /// <summary>A Win32 service that shares a process.</summary> ShareProcess = 0x0020, /// <summary>A Win32 service that interacts with the desktop. /// This value cannot be used alone and must be added to either /// <see cref="OwnProcess"/> or <see cref="ShareProcess"/>.</summary> Interactive = 0x0100, /// <summary>Service starts during startup of the system.</summary> AutoStart = 0x0002, /// <summary>Service starts when the service control manager calls the StartService function.</summary> DemandStart = 0x0003, /// <summary>Specifies a service that can no longer be started.</summary> Disabled = 0x0004, /// <summary>Logs the error, displays a message box and continues the startup operation.</summary> ErrorMessage = 0x0001, /// <summary>Logs the error if it is possible and the system is restarted with the last configuration /// known to be good. If the last-known-good configuration is being started, the startup operation fails.</summary> ErrorCritical = 0x0003, /// <summary>When combined with other error flags, specifies that the overall install should fail if /// the service cannot be installed into the system.</summary> ErrorControlVital = 0x8000, } /// <summary> /// Defines values for the Event column of the ServiceControl table. /// </summary> [Flags] public enum ServiceControlEvents : int { /// <summary>No control events.</summary> None = 0x0000, /// <summary>During an install, starts the service during the StartServices action.</summary> Start = 0x0001, /// <summary>During an install, stops the service during the StopServices action.</summary> Stop = 0x0002, /// <summary>During an install, deletes the service during the DeleteServices action.</summary> Delete = 0x0008, /// <summary>During an uninstall, starts the service during the StartServices action.</summary> UninstallStart = 0x0010, /// <summary>During an uninstall, stops the service during the StopServices action.</summary> UninstallStop = 0x0020, /// <summary>During an uninstall, deletes the service during the DeleteServices action.</summary> UninstallDelete = 0x0080, } /// <summary> /// Defines values for the StyleBits column of the TextStyle table. /// </summary> [Flags] public enum TextStyles : int { /// <summary>Bold</summary> Bold = 0x0001, /// <summary>Italic</summary> Italic = 0x0002, /// <summary>Underline</summary> Underline = 0x0004, /// <summary>Strike out</summary> Strike = 0x0008, } /// <summary> /// Defines values for the Attributes column of the Upgrade table. /// </summary> [Flags] public enum UpgradeAttributes : int { /// <summary>Migrates feature states by enabling the logic in the MigrateFeatureStates action.</summary> MigrateFeatures = 0x0001, /// <summary>Detects products and applications but does not remove.</summary> OnlyDetect = 0x0002, /// <summary>Continues installation upon failure to remove a product or application.</summary> IgnoreRemoveFailure = 0x0004, /// <summary>Detects the range of versions including the value in VersionMin.</summary> VersionMinInclusive = 0x0100, /// <summary>Detects the range of versions including the value in VersionMax.</summary> VersionMaxInclusive = 0x0200, /// <summary>Detects all languages, excluding the languages listed in the Language column.</summary> LanguagesExclusive = 0x0400, } }
// This is a forked Class from Elze Kool (kooldevelopment.nl), which provided the whole class to me. // For size reasons I deleted all algorithms I do not need. using System; namespace netmfawss3.Utilities { /// <summary> /// Static class providing Secure Hashing Algorithm (SHA-1, SHA-224, SHA-256) /// </summary> public static class SHA { // Number used in SHA256 hash function private static readonly uint[] sha256_k = new uint[] { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; // Rotate bits left private static uint rotateleft(uint x, int n) { return ((x << n) | (x >> (32 - n))); } // Rotate bits right private static uint rotateright(uint x, int n) { return ((x >> n) | (x << (32 - n))); } // Convert 4 bytes to big endian uint32 private static uint big_endian_from_bytes(byte[] input, uint start) { uint r = 0; r |= (((uint) input[start]) << 24); r |= (((uint) input[start + 1]) << 16); r |= (((uint) input[start + 2]) << 8); r |= (((uint) input[start + 3])); return r; } // Convert big endian uint32 to bytes private static void bytes_from_big_endian(uint input, ref byte[] output, int start) { output[start] = (byte) ((input & 0xFF000000) >> 24); output[start + 1] = (byte) ((input & 0x00FF0000) >> 16); output[start + 2] = (byte) ((input & 0x0000FF00) >> 8); output[start + 3] = (byte) ((input & 0x000000FF)); } // SHA-224/SHA-256 choice function private static uint choice(uint x, uint y, uint z) { return ((x & y) ^ (~x & z)); } // SHA-224/SHA-256 majority function private static uint majority(uint x, uint y, uint z) { return ((x & y) ^ (x & z) ^ (y & z)); } /// <summary> /// Compute HMAC SHA-256 /// </summary> /// <param name="secret">Secret</param> /// <param name="value">Password</param> /// <returns>32 byte HMAC_SHA256</returns> public static byte[] computeHMAC_SHA256(byte[] secret, byte[] value) { // Create two arrays, bi and bo byte[] bi = new byte[64 + value.Length]; byte[] bo = new byte[64 + 32]; // Copy secret to both arrays Array.Copy(secret, bi, secret.Length); Array.Copy(secret, bo, secret.Length); for (int i = 0; i < 64; i++) { // Xor bi with 0x36 bi[i] = (byte) (bi[i] ^ 0x36); // Xor bo with 0x5c bo[i] = (byte) (bo[i] ^ 0x5c); } // Append value to bi Array.Copy(value, 0, bi, 64, value.Length); // Append SHA256(bi) to bo byte[] sha_bi = computeSHA256(bi); Array.Copy(sha_bi, 0, bo, 64, 32); // Return SHA256(bo) return computeSHA256(bo); } /// <summary> /// Compute SHA-256 digest /// </summary> /// <param name="input">Input array</param> public static byte[] computeSHA256(byte[] input) { // Initialize working parameters uint a, b, c, d, e, f, g, h, i, s0, s1, t1, t2; uint h0 = 0x6a09e667; uint h1 = 0xbb67ae85; uint h2 = 0x3c6ef372; uint h3 = 0xa54ff53a; uint h4 = 0x510e527f; uint h5 = 0x9b05688c; uint h6 = 0x1f83d9ab; uint h7 = 0x5be0cd19; uint blockstart = 0; // Calculate how long the padded message should be int newinputlength = input.Length + 1; while ((newinputlength%64) != 56) // length mod 512bits = 448bits { newinputlength++; } // Create array for padded data byte[] processed = new byte[newinputlength + 8]; Array.Copy(input, processed, input.Length); // Pad data with an 1 processed[input.Length] = 0x80; // Pad data with big endian 64bit length of message // We do only 32 bits becouse input.length is 32 bit processed[processed.Length - 4] = (byte) (((input.Length*8) & 0xFF000000) >> 24); processed[processed.Length - 3] = (byte) (((input.Length*8) & 0x00FF0000) >> 16); processed[processed.Length - 2] = (byte) (((input.Length*8) & 0x0000FF00) >> 8); processed[processed.Length - 1] = (byte) (((input.Length*8) & 0x000000FF)); // Block of 32 bits values used in calculations uint[] wordblock = new uint[64]; // Now process each 512 bit block while (blockstart < processed.Length) { // break chunk into sixteen 32-bit big-endian words for (i = 0; i < 16; i++) wordblock[i] = big_endian_from_bytes(processed, blockstart + (i*4)); // Extend the sixteen 32-bit words into sixty-four 32-bit words: for (i = 16; i < 64; i++) { s0 = rotateright(wordblock[i - 15], 7) ^ rotateright(wordblock[i - 15], 18) ^ (wordblock[i - 15] >> 3); s1 = rotateright(wordblock[i - 2], 17) ^ rotateright(wordblock[i - 2], 19) ^ (wordblock[i - 2] >> 10); wordblock[i] = wordblock[i - 16] + s0 + wordblock[i - 7] + s1; } // Initialize hash value for this chunk: a = h0; b = h1; c = h2; d = h3; e = h4; f = h5; g = h6; h = h7; // Main loop for (i = 0; i < 64; i++) { t1 = h + (rotateright(e, 6) ^ rotateright(e, 11) ^ rotateright(e, 25)) + choice(e, f, g) + sha256_k[i] + wordblock[i]; t2 = (rotateright(a, 2) ^ rotateright(a, 13) ^ rotateright(a, 22)) + majority(a, b, c); h = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2; } // Add this chunk's hash to result so far h0 += a; h1 += b; h2 += c; h3 += d; h4 += e; h5 += f; h6 += g; h7 += h; // Process next 512bit block blockstart += 64; } // Prepare output byte[] output = new byte[32]; bytes_from_big_endian(h0, ref output, 0); bytes_from_big_endian(h1, ref output, 4); bytes_from_big_endian(h2, ref output, 8); bytes_from_big_endian(h3, ref output, 12); bytes_from_big_endian(h4, ref output, 16); bytes_from_big_endian(h5, ref output, 20); bytes_from_big_endian(h6, ref output, 24); bytes_from_big_endian(h7, ref output, 28); return output; } } }
// 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: List for exceptions. ** ** ===========================================================*/ namespace System.Collections { /// This is a simple implementation of IDictionary using a singly linked list. This /// will be smaller and faster than a Hashtable if the number of elements is 10 or less. /// This should not be used if performance is important for large numbers of elements. [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] // Needs to be public to support binary serialization compatibility public class ListDictionaryInternal : IDictionary { private DictionaryNode? head; // Do not rename (binary serialization) private int version; // Do not rename (binary serialization) private int count; // Do not rename (binary serialization) public ListDictionaryInternal() { } public object? this[object key] { get { if (key == null) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } DictionaryNode? node = head; while (node != null) { if (node.key.Equals(key)) { return node.value; } node = node.next; } return null; } set { if (key == null) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } version++; DictionaryNode? last = null; DictionaryNode? node; for (node = head; node != null; node = node.next) { if (node.key.Equals(key)) { break; } last = node; } if (node != null) { // Found it node.value = value; return; } // Not found, so add a new one DictionaryNode newNode = new DictionaryNode(); newNode.key = key; newNode.value = value; if (last != null) { last.next = newNode; } else { head = newNode; } count++; } } public int Count => count; public ICollection Keys => new NodeKeyValueCollection(this, true); public bool IsReadOnly => false; public bool IsFixedSize => false; public bool IsSynchronized => false; public object SyncRoot => this; public ICollection Values => new NodeKeyValueCollection(this, false); public void Add(object key, object? value) { if (key == null) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } version++; DictionaryNode? last = null; DictionaryNode? node; for (node = head; node != null; node = node.next) { if (node.key.Equals(key)) { throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate__, node.key, key)); } last = node; } if (node != null) { // Found it node.value = value; return; } // Not found, so add a new one DictionaryNode newNode = new DictionaryNode(); newNode.key = key; newNode.value = value; if (last != null) { last.next = newNode; } else { head = newNode; } count++; } public void Clear() { count = 0; head = null; version++; } public bool Contains(object key) { if (key == null) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } for (DictionaryNode? node = head; node != null; node = node.next) { if (node.key.Equals(key)) { return true; } } return false; } public void CopyTo(Array array, int index) { if (array == null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - index < this.Count) throw new ArgumentException(SR.ArgumentOutOfRange_Index, nameof(index)); for (DictionaryNode? node = head; node != null; node = node.next) { array.SetValue(new DictionaryEntry(node.key, node.value), index); index++; } } public IDictionaryEnumerator GetEnumerator() { return new NodeEnumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return new NodeEnumerator(this); } public void Remove(object key) { if (key == null) { throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); } version++; DictionaryNode? last = null; DictionaryNode? node; for (node = head; node != null; node = node.next) { if (node.key.Equals(key)) { break; } last = node; } if (node == null) { return; } if (node == head) { head = node.next; } else { last!.next = node.next; } count--; } private class NodeEnumerator : IDictionaryEnumerator { private readonly ListDictionaryInternal list; private DictionaryNode? current; private readonly int version; private bool start; public NodeEnumerator(ListDictionaryInternal list) { this.list = list; version = list.version; start = true; current = null; } public object Current => Entry; public DictionaryEntry Entry { get { if (current == null) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return new DictionaryEntry(current.key, current.value); } } public object Key { get { if (current == null) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return current.key; } } public object? Value { get { if (current == null) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return current.value; } } public bool MoveNext() { if (version != list.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } if (start) { current = list.head; start = false; } else { if (current != null) { current = current.next; } } return current != null; } public void Reset() { if (version != list.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } start = true; current = null; } } private class NodeKeyValueCollection : ICollection { private readonly ListDictionaryInternal list; private readonly bool isKeys; public NodeKeyValueCollection(ListDictionaryInternal list, bool isKeys) { this.list = list; this.isKeys = isKeys; } void ICollection.CopyTo(Array array, int index) { if (array == null) throw new ArgumentNullException(nameof(array)); if (array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - index < list.Count) throw new ArgumentException(SR.ArgumentOutOfRange_Index, nameof(index)); for (DictionaryNode? node = list.head; node != null; node = node.next) { array.SetValue(isKeys ? node.key : node.value, index); index++; } } int ICollection.Count { get { int count = 0; for (DictionaryNode? node = list.head; node != null; node = node.next) { count++; } return count; } } bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => list.SyncRoot; IEnumerator IEnumerable.GetEnumerator() { return new NodeKeyValueEnumerator(list, isKeys); } private class NodeKeyValueEnumerator : IEnumerator { private readonly ListDictionaryInternal list; private DictionaryNode? current; private readonly int version; private readonly bool isKeys; private bool start; public NodeKeyValueEnumerator(ListDictionaryInternal list, bool isKeys) { this.list = list; this.isKeys = isKeys; version = list.version; start = true; current = null; } public object? Current { get { if (current == null) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return isKeys ? current.key : current.value; } } public bool MoveNext() { if (version != list.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } if (start) { current = list.head; start = false; } else { if (current != null) { current = current.next; } } return current != null; } public void Reset() { if (version != list.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } start = true; current = null; } } } [Serializable] private class DictionaryNode { public object key = null!; public object? value; public DictionaryNode? next; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Reflection.Internal; using System.Reflection.Metadata; using System.Text; using System.Threading; namespace System.Reflection.PortableExecutable { /// <summary> /// Portable Executable format reader. /// </summary> /// <remarks> /// The implementation is thread-safe, that is multiple threads can read data from the reader in parallel. /// Disposal of the reader is not thread-safe (see <see cref="Dispose"/>). /// </remarks> public sealed class PEReader : IDisposable { // May be null in the event that the entire image is not // deemed necessary and we have been instructed to read // the image contents without being lazy. private MemoryBlockProvider peImage; // If we read the data from the image lazily (peImage != null) we defer reading the PE headers. private PEHeaders lazyPEHeaders; private AbstractMemoryBlock lazyMetadataBlock; private AbstractMemoryBlock lazyImageBlock; private AbstractMemoryBlock[] lazyPESectionBlocks; /// <summary> /// Creates a Portable Executable reader over a PE image stored in memory. /// </summary> /// <param name="peImage">Pointer to the start of the PE image.</param> /// <param name="size">The size of the PE image.</param> /// <exception cref="ArgumentNullException"><paramref name="peImage"/> is <see cref="IntPtr.Zero"/>.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="size"/> is negative.</exception> /// <remarks> /// The memory is owned by the caller and not released on disposal of the <see cref="PEReader"/>. /// The caller is reponsible for keeping the memory alive and unmodified throughout the lifetime of the <see cref="PEReader"/>. /// The content of the image is not read during the construction of the <see cref="PEReader"/> /// </remarks> public unsafe PEReader(byte* peImage, int size) { if (peImage == null) { throw new ArgumentNullException("peImage"); } if (size < 0) { throw new ArgumentOutOfRangeException("size"); } this.peImage = new ExternalMemoryBlockProvider(peImage, size); } /// <summary> /// Creates a Portable Executable reader over a PE image stored in a stream. /// </summary> /// <param name="peStream">PE image stream.</param> /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> /// <exception cref="BadImageFormatException"> /// <see cref="PEStreamOptions.PrefetchMetadata"/> is specified and the PE headers of the image are invalid. /// </exception> /// <remarks> /// Ownership of the stream is transferred to the <see cref="PEReader"/> upon successful validation of constructor arguments. It will be /// disposed by the <see cref="PEReader"/> and the caller must not manipulate it. /// </remarks> public PEReader(Stream peStream) : this(peStream, PEStreamOptions.Default) { } /// <summary> /// Creates a Portable Executable reader over a PE image stored in a stream beginning at its current position and ending at the end of the stream. /// </summary> /// <param name="peStream">PE image stream.</param> /// <param name="options"> /// Options specifying how sections of the PE image are read from the stream. /// /// Unless <see cref="PEStreamOptions.LeaveOpen"/> is specified, ownership of the stream is transferred to the <see cref="PEReader"/> /// upon successful argument validation. It will be disposed by the <see cref="PEReader"/> and the caller must not manipulate it. /// /// Unless <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/> is specified no data /// is read from the stream during the construction of the <see cref="PEReader"/>. Furthermore, the stream must not be manipulated /// by caller while the <see cref="PEReader"/> is alive and undisposed. /// /// If <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/>, the <see cref="PEReader"/> /// will have read all of the data requested during construction. As such, if <see cref="PEStreamOptions.LeaveOpen"/> is also /// specified, the caller retains full ownership of the stream and is assured that it will not be manipulated by the <see cref="PEReader"/> /// after construction. /// </param> /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="options"/> has an invalid value.</exception> /// <exception cref="BadImageFormatException"> /// <see cref="PEStreamOptions.PrefetchMetadata"/> is specified and the PE headers of the image are invalid. /// </exception> public PEReader(Stream peStream, PEStreamOptions options) : this(peStream, options, (int?)null) { } /// <summary> /// Creates a Portable Executable reader over a PE image of the given size beginning at the stream's current position. /// </summary> /// <param name="peStream">PE image stream.</param> /// <param name="size">PE image size.</param> /// <param name="options"> /// Options specifying how sections of the PE image are read from the stream. /// /// Unless <see cref="PEStreamOptions.LeaveOpen"/> is specified, ownership of the stream is transferred to the <see cref="PEReader"/> /// upon successful argument validation. It will be disposed by the <see cref="PEReader"/> and the caller must not manipulate it. /// /// Unless <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/> is specified no data /// is read from the stream during the construction of the <see cref="PEReader"/>. Furthermore, the stream must not be manipulated /// by caller while the <see cref="PEReader"/> is alive and undisposed. /// /// If <see cref="PEStreamOptions.PrefetchMetadata"/> or <see cref="PEStreamOptions.PrefetchEntireImage"/>, the <see cref="PEReader"/> /// will have read all of the data requested during construction. As such, if <see cref="PEStreamOptions.LeaveOpen"/> is also /// specified, the caller retains full ownership of the stream and is assured that it will not be manipulated by the <see cref="PEReader"/> /// after construction. /// </param> /// <exception cref="ArgumentOutOfRangeException">Size is negative or extends past the end of the stream.</exception> public PEReader(Stream peStream, PEStreamOptions options, int size) : this(peStream, options, (int?)size) { } private unsafe PEReader(Stream peStream, PEStreamOptions options, int? sizeOpt) { if (peStream == null) { throw new ArgumentNullException("peStream"); } if (!peStream.CanRead || !peStream.CanSeek) { throw new ArgumentException(MetadataResources.StreamMustSupportReadAndSeek, "peStream"); } if (!options.IsValid()) { throw new ArgumentOutOfRangeException("options"); } long start = peStream.Position; int size = PEBinaryReader.GetAndValidateSize(peStream, sizeOpt); bool closeStream = true; try { bool isFileStream = FileStreamReadLightUp.IsFileStream(peStream); if ((options & (PEStreamOptions.PrefetchMetadata | PEStreamOptions.PrefetchEntireImage)) == 0) { this.peImage = new StreamMemoryBlockProvider(peStream, start, size, isFileStream, (options & PEStreamOptions.LeaveOpen) != 0); closeStream = false; } else { // Read in the entire image or metadata blob: if ((options & PEStreamOptions.PrefetchEntireImage) != 0) { var imageBlock = StreamMemoryBlockProvider.ReadMemoryBlockNoLock(peStream, isFileStream, 0, (int)Math.Min(peStream.Length, int.MaxValue)); this.lazyImageBlock = imageBlock; this.peImage = new ExternalMemoryBlockProvider(imageBlock.Pointer, imageBlock.Size); // if the caller asked for metadata initialize the PE headers (calculates metadata offset): if ((options & PEStreamOptions.PrefetchMetadata) != 0) { InitializePEHeaders(); } } else { // The peImage is left null, but the lazyMetadataBlock is initialized up front. this.lazyPEHeaders = new PEHeaders(peStream); this.lazyMetadataBlock = StreamMemoryBlockProvider.ReadMemoryBlockNoLock(peStream, isFileStream, lazyPEHeaders.MetadataStartOffset, lazyPEHeaders.MetadataSize); } // We read all we need, the stream is going to be closed. } } finally { if (closeStream && (options & PEStreamOptions.LeaveOpen) == 0) { peStream.Dispose(); } } } /// <summary> /// Creates a Portable Executable reader over a PE image stored in a byte array. /// </summary> /// <param name="peImage">PE image.</param> /// <remarks> /// The content of the image is not read during the construction of the <see cref="PEReader"/> /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="peImage"/> is null.</exception> public PEReader(ImmutableArray<byte> peImage) { if (peImage.IsDefault) { throw new ArgumentNullException("peImage"); } this.peImage = new ByteArrayMemoryProvider(peImage); } /// <summary> /// Disposes all memory allocated by the reader. /// </summary> /// <remarks> /// <see cref="Dispose"/> can be called multiple times (even in parallel). /// However, it is not safe to call <see cref="Dispose"/> in parallel with any other operation on the <see cref="PEReader"/> /// or reading from <see cref="PEMemoryBlock"/>s retrieved from the reader. /// </remarks> public void Dispose() { var image = peImage; if (image != null) { image.Dispose(); peImage = null; } var imageBlock = lazyImageBlock; if (imageBlock != null) { imageBlock.Dispose(); lazyImageBlock = null; } var metadataBlock = lazyMetadataBlock; if (metadataBlock != null) { metadataBlock.Dispose(); lazyMetadataBlock = null; } var peSectionBlocks = lazyPESectionBlocks; if (peSectionBlocks != null) { foreach (var block in peSectionBlocks) { if (block != null) { block.Dispose(); } } lazyPESectionBlocks = null; } } /// <summary> /// Gets the PE headers. /// </summary> /// <exception cref="BadImageFormatException">The headers contain invalid data.</exception> public PEHeaders PEHeaders { get { if (lazyPEHeaders == null) { InitializePEHeaders(); } return lazyPEHeaders; } } private void InitializePEHeaders() { Debug.Assert(peImage != null); StreamConstraints constraints; Stream stream = peImage.GetStream(out constraints); PEHeaders headers; if (constraints.GuardOpt != null) { lock (constraints.GuardOpt) { headers = ReadPEHeadersNoLock(stream, constraints.ImageStart, constraints.ImageSize); } } else { headers = ReadPEHeadersNoLock(stream, constraints.ImageStart, constraints.ImageSize); } Interlocked.CompareExchange(ref lazyPEHeaders, headers, null); } private static PEHeaders ReadPEHeadersNoLock(Stream stream, long imageStartPosition, int imageSize) { Debug.Assert(imageStartPosition >= 0 && imageStartPosition <= stream.Length); stream.Seek(imageStartPosition, SeekOrigin.Begin); return new PEHeaders(stream, imageSize); } /// <summary> /// Returns a view of the entire image as a pointer and length. /// </summary> /// <exception cref="InvalidOperationException">PE image not available.</exception> private AbstractMemoryBlock GetEntireImageBlock() { if (lazyImageBlock == null) { if (peImage == null) { throw new InvalidOperationException(MetadataResources.PEImageNotAvailable); } var newBlock = peImage.GetMemoryBlock(); if (Interlocked.CompareExchange(ref lazyImageBlock, newBlock, null) != null) { // another thread created the block already, we need to dispose ours: newBlock.Dispose(); } } return lazyImageBlock; } private AbstractMemoryBlock GetMetadataBlock() { if (!HasMetadata) { throw new InvalidOperationException(MetadataResources.PEImageDoesNotHaveMetadata); } if (lazyMetadataBlock == null) { Debug.Assert(peImage != null, "We always have metadata if peImage is not available."); var newBlock = peImage.GetMemoryBlock(PEHeaders.MetadataStartOffset, PEHeaders.MetadataSize); if (Interlocked.CompareExchange(ref lazyMetadataBlock, newBlock, null) != null) { // another thread created the block already, we need to dispose ours: newBlock.Dispose(); } } return lazyMetadataBlock; } private AbstractMemoryBlock GetPESectionBlock(int index) { Debug.Assert(index >= 0 && index < PEHeaders.SectionHeaders.Length); Debug.Assert(peImage != null); if (lazyPESectionBlocks == null) { Interlocked.CompareExchange(ref lazyPESectionBlocks, new AbstractMemoryBlock[PEHeaders.SectionHeaders.Length], null); } var newBlock = peImage.GetMemoryBlock( PEHeaders.SectionHeaders[index].PointerToRawData, PEHeaders.SectionHeaders[index].SizeOfRawData); if (Interlocked.CompareExchange(ref lazyPESectionBlocks[index], newBlock, null) != null) { // another thread created the block already, we need to dispose ours: newBlock.Dispose(); } return lazyPESectionBlocks[index]; } /// <summary> /// Return true if the reader can access the entire PE image. /// </summary> /// <remarks> /// Returns false if the <see cref="PEReader"/> is constructed from a stream and only part of it is prefetched into memory. /// </remarks> public bool IsEntireImageAvailable { get { return lazyImageBlock != null || peImage != null; } } /// <summary> /// Gets a pointer to and size of the PE image if available (<see cref="IsEntireImageAvailable"/>). /// </summary> /// <exception cref="InvalidOperationException">The entire PE image is not available.</exception> public PEMemoryBlock GetEntireImage() { return new PEMemoryBlock(GetEntireImageBlock()); } /// <summary> /// Returns true if the PE image contains CLI metadata. /// </summary> /// <exception cref="BadImageFormatException">The PE headers contain invalid data.</exception> public bool HasMetadata { get { return PEHeaders.MetadataSize > 0; } } /// <summary> /// Loads PE section that contains CLI metadata. /// </summary> /// <exception cref="InvalidOperationException">The PE image doesn't contain metadata (<see cref="HasMetadata"/> returns false).</exception> /// <exception cref="BadImageFormatException">The PE headers contain invalid data.</exception> public PEMemoryBlock GetMetadata() { return new PEMemoryBlock(GetMetadataBlock()); } /// <summary> /// Loads PE section that contains the specified <paramref name="relativeVirtualAddress"/> into memory /// and returns a memory block that starts at <paramref name="relativeVirtualAddress"/> and ends at the end of the containing section. /// </summary> /// <param name="relativeVirtualAddress">Relative Virtual Address of the data to read.</param> /// <returns> /// An empty block if <paramref name="relativeVirtualAddress"/> doesn't represent a location in any of the PE sections of this PE image. /// </returns> /// <exception cref="BadImageFormatException">The PE headers contain invalid data.</exception> public PEMemoryBlock GetSectionData(int relativeVirtualAddress) { var sectionIndex = PEHeaders.GetContainingSectionIndex(relativeVirtualAddress); if (sectionIndex < 0) { return default(PEMemoryBlock); } int relativeOffset = relativeVirtualAddress - PEHeaders.SectionHeaders[sectionIndex].VirtualAddress; int size = PEHeaders.SectionHeaders[sectionIndex].VirtualSize - relativeOffset; AbstractMemoryBlock block; if (peImage != null) { block = GetPESectionBlock(sectionIndex); } else { block = GetEntireImageBlock(); relativeOffset += PEHeaders.SectionHeaders[sectionIndex].PointerToRawData; } return new PEMemoryBlock(block, relativeOffset); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; namespace RRLab.PhysiologyWorkbench.Devices { public partial class FilterWheelPositionControl : UserControl { private List<char> _Wheels = new List<char>(3); private FilterWheel _FilterWheel; public FilterWheel FilterWheel { get { return _FilterWheel; } set { if (FilterWheel != null) FilterWheel.ShutterStateChanged -= new EventHandler(OnFilterWheelStateChanged); _FilterWheel = value; if (FilterWheel != null) FilterWheel.ShutterStateChanged += new EventHandler(OnFilterWheelStateChanged); LoadFilterWheelSettings(_FilterWheel); } } public char CurrentWheel { get { return _Wheels[WheelsBox.SelectedIndex]; } set { int index = _Wheels.FindIndex(delegate(char c) { return c == value; }); if ((index >= 0) && (index < WheelsBox.Items.Count)) WheelsBox.SelectedIndex = index; } } public int CurrentPosition { get { return FiltersBox.SelectedIndex; } set { FiltersBox.SelectedIndex = value; } } public FilterWheelPositionControl() { InitializeComponent(); } public FilterWheelPositionControl(FilterWheel filterWheel) { InitializeComponent(); FilterWheel = filterWheel; } protected virtual void LoadFilterWheelSettings(FilterWheel filterWheel) { if (InvokeRequired) { Invoke(new MethodInvoker(delegate() { LoadFilterWheelSettings(filterWheel); })); return; } WheelsBox.Items.Clear(); _Wheels.Clear(); if (filterWheel == null) { this.Enabled = false; } else { this.Enabled = true; _Wheels.AddRange(filterWheel.GetAvailableWheels()); foreach (char wheelLetter in _Wheels) { WheelsBox.Items.Add("Wheel " + wheelLetter); } WheelsBox.SelectedIndex = 0; if (FilterWheel is SerialPortFilterWheel) TakeControlButton.Enabled = true; else TakeControlButton.Enabled = false; } } protected virtual void LoadFilterDescriptions(FilterWheel filterWheel, char wheel) { if (filterWheel == null) return; if (InvokeRequired) { Invoke(new MethodInvoker(delegate() { LoadFilterDescriptions(filterWheel, wheel); })); return; } ShutterStateComboBox.DataSource = Enum.GetValues(typeof(FilterWheelShutterStatus)); FiltersBox.Enabled = true; FiltersBox.Items.Clear(); for (int i = 0; i < FilterWheel.NumberOfFilters; i++) { string name = i.ToString(); string description = FilterWheel.GetFilterDescription(CurrentWheel, i); if (description != null) name += " " + description; FiltersBox.Items.Add(name); } switch (Char.ToUpper(CurrentWheel)) { case 'A': ShutterStateComboBox.SelectedItem = FilterWheel.ShutterAStatus; break; case 'B': ShutterStateComboBox.SelectedItem = FilterWheel.ShutterBStatus; break; default: ShutterStateComboBox.SelectedItem = null; break; } } protected virtual void OnSelectedWheelChanged(object sender, EventArgs e) { if (InvokeRequired) { Invoke(new EventHandler(OnSelectedWheelChanged),sender,e); return; } if (WheelsBox.SelectedIndex != -1) { LoadFilterDescriptions(FilterWheel, CurrentWheel); } else { FiltersBox.Items.Clear(); FiltersBox.Enabled = false; } } protected virtual void OnSelectedFilterChanged(object sender, EventArgs e) { if (InvokeRequired) { Invoke(new EventHandler(OnSelectedFilterChanged), sender, e); return; } } protected virtual void OnSetFilterClicked(object sender, EventArgs e) { if (FilterWheel == null) return; try { FilterWheel.SetFilterWheelPosition(CurrentWheel, CurrentPosition, FilterWheel.DefaultSpeed); } catch (Exception x) { MessageBox.Show("Error while setting filter wheel position: " + x.Message); } } protected virtual void OnTakeControlClicked(object sender, EventArgs e) { if (FilterWheel == null || !(FilterWheel is SerialPortFilterWheel)) return; try { ((SerialPortFilterWheel)FilterWheel).ForceComputerControl(); } catch(Exception x) { MessageBox.Show("Error taking control of filter wheel: " + x.Message); } } private void OnSetShutterClicked(object sender, EventArgs e) { try { FilterWheelShutterStatus state = (FilterWheelShutterStatus)ShutterStateComboBox.SelectedValue; if (FilterWheel != null) FilterWheel.SetShutterState(CurrentWheel, state); } catch (Exception x) { MessageBox.Show("Error setting shutter state: " + x.Message); } } protected virtual void OnFilterWheelStateChanged(object sender, EventArgs e) { if (InvokeRequired) { Invoke(new EventHandler(OnFilterWheelStateChanged), sender, e); return; } LoadFilterWheelSettings(FilterWheel); } } }
/* The MIT License (MIT) Copyright (c) 2014 Play-Em 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 UnityEngine; #if UNITY_EDITOR using UnityEditor; using System.IO; #endif using System.Collections; using System.Collections.Generic; public class SortLayerMaterialEditor : EditorWindow { private Renderer renderer; private GameObject o; private GameObject copyFrom; private GameObject copyTo; private GameObject copyPosFrom; private GameObject copyPosTo; private int addToLayer = 0; private bool includeChildrenForSorting = false; private bool includeChildrenForMaterials = false; [MenuItem("Sprites And Bones/Sorting Layers And Materials")] protected static void ShowSortLayerMaterialEditor() { var wnd = GetWindow<SortLayerMaterialEditor>(); wnd.titleContent.text = "Sort Layers and Create Materials"; wnd.Show(); } static void CreateMaterial (GameObject go) { // Create a simple material asset if (go.GetComponent<Renderer>() != null) { Material material = new Material(go.GetComponent<Renderer>().sharedMaterial); material.CopyPropertiesFromMaterial(go.GetComponent<Renderer>().sharedMaterial); go.GetComponent<Renderer>().sharedMaterial = material; MaterialPropertyBlock block = new MaterialPropertyBlock(); go.GetComponent<Renderer>().GetPropertyBlock(block); #if UNITY_EDITOR if(!Directory.Exists("Assets/Materials")) { AssetDatabase.CreateFolder("Assets", "Materials"); AssetDatabase.Refresh(); } string textureName = null; if (block.GetTexture(0).name != null) { textureName = block.GetTexture(0).name; } else { textureName = material.mainTexture.name; } AssetDatabase.CreateAsset(material, "Assets/Materials/" + textureName + ".mat"); Debug.Log("Created material " + textureName + " for " + go.name); #endif } } public static void Reset () { #if UNITY_EDITOR if (Selection.activeGameObject != null) { GameObject o = Selection.activeGameObject; if (o.GetComponent<Renderer>() != null) { o.GetComponent<Renderer>().sortingLayerName = "Default"; o.GetComponent<Renderer>().sortingOrder = 0; } Transform[] children = o.GetComponentsInChildren<Transform>(true); foreach(Transform child in children) { if (child.gameObject.GetComponent<Renderer>() != null) { child.gameObject.GetComponent<Renderer>().sortingLayerName = "Default"; child.gameObject.GetComponent<Renderer>().sortingOrder = 0; } } } #endif } public void OnGUI() { GUILayout.Label("GameObject", EditorStyles.boldLabel); EditorGUI.BeginChangeCheck(); if (Selection.activeGameObject != null) { o = Selection.activeGameObject; } EditorGUILayout.ObjectField(o, typeof(GameObject), true); EditorGUI.EndChangeCheck(); if (o != null) { if (GUILayout.Button("Reset Sorting Layers")) { #if UNITY_EDITOR Reset(); #endif } EditorGUILayout.Separator(); GUILayout.Label("Add to Sorting Layers ", EditorStyles.boldLabel); addToLayer = EditorGUILayout.IntField("Add:", addToLayer); includeChildrenForSorting = EditorGUILayout.Toggle("Include Children", includeChildrenForSorting); if (GUILayout.Button("Add to Sorting Layers")) { #if UNITY_EDITOR if (Selection.activeGameObject != null) { o = Selection.activeGameObject; if (o.GetComponent<Renderer>() != null) { o.GetComponent<Renderer>().sortingOrder = o.GetComponent<Renderer>().sortingOrder+addToLayer; } if (includeChildrenForSorting) { Transform[] children = o.GetComponentsInChildren<Transform>(true); foreach(Transform child in children) { if (child.gameObject.GetComponent<Renderer>() != null) { child.gameObject.GetComponent<Renderer>().sortingOrder = child.gameObject.GetComponent<Renderer>().sortingOrder+addToLayer; } } } } #endif } GUILayout.Label("Create Materials from Renderer", EditorStyles.boldLabel); EditorGUILayout.Separator(); includeChildrenForMaterials = EditorGUILayout.Toggle("Include Children", includeChildrenForMaterials); if (GUILayout.Button("Create Material")) { #if UNITY_EDITOR if (Selection.activeGameObject != null) { o = Selection.activeGameObject; if (o.GetComponent<Renderer>() != null) { CreateMaterial(o); } if (includeChildrenForMaterials) { Transform[] children = o.GetComponentsInChildren<Transform>(true); foreach(Transform child in children) { if (child.gameObject.GetComponent<Renderer>() != null) { CreateMaterial(child.gameObject); } } } } #endif } EditorGUILayout.Separator(); GUILayout.Label("Copy Sorting Layers Between Objects", EditorStyles.boldLabel); EditorGUI.BeginChangeCheck(); copyFrom = (GameObject)EditorGUILayout.ObjectField("Copy From: ", copyFrom, typeof(GameObject), true); copyTo = (GameObject)EditorGUILayout.ObjectField("Copy To: ", copyTo, typeof(GameObject), true); EditorGUI.EndChangeCheck(); if (GUILayout.Button("Copy Sorting Layers")) { #if UNITY_EDITOR if (copyFrom != null && copyTo != null) { Transform[] copyFromChildren = copyFrom.GetComponentsInChildren<Transform>(true); Transform[] copyToChildren = copyTo.GetComponentsInChildren<Transform>(true); foreach(Transform copyFromChild in copyFromChildren) { if (copyFromChild.gameObject.GetComponent<Renderer>() != null) { foreach(Transform copyToChild in copyToChildren) { if (copyToChild.gameObject.GetComponent<Renderer>() != null && copyToChild.name == copyFromChild.name) { copyToChild.gameObject.GetComponent<Renderer>().sortingOrder = copyFromChild.gameObject.GetComponent<Renderer>().sortingOrder; } } } } } else { EditorGUILayout.HelpBox("No Gameobjects selected.", MessageType.Error); } #endif } EditorGUILayout.Separator(); GUILayout.Label("Copy Positions and Rotations Between Objects", EditorStyles.boldLabel); EditorGUI.BeginChangeCheck(); copyPosFrom = (GameObject)EditorGUILayout.ObjectField("Copy From: ", copyPosFrom, typeof(GameObject), true); copyPosTo = (GameObject)EditorGUILayout.ObjectField("Copy To: ", copyPosTo, typeof(GameObject), true); EditorGUI.EndChangeCheck(); if (GUILayout.Button("Copy Positions and Rotations")) { #if UNITY_EDITOR if (copyPosFrom != null && copyPosTo != null) { Transform[] copyFromChildren = copyPosFrom.GetComponentsInChildren<Transform>(true); Transform[] copyToChildren = copyPosTo.GetComponentsInChildren<Transform>(true); foreach(Transform copyFromChild in copyFromChildren) { if (copyFromChild.gameObject.GetComponent<Renderer>() != null) { foreach(Transform copyToChild in copyToChildren) { if (copyToChild.gameObject.GetComponent<Renderer>() != null && copyToChild.name == copyFromChild.name) { copyToChild.position = new Vector3(copyFromChild.position.x, copyFromChild.position.y, copyFromChild.position.z); copyToChild.rotation = new Quaternion(copyFromChild.rotation.x, copyFromChild.rotation.y, copyFromChild.rotation.z, copyFromChild.rotation.w); } } } } } else { EditorGUILayout.HelpBox("No Gameobjects selected.", MessageType.Error); } #endif } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Xml; using Orleans.Configuration; namespace Orleans.Runtime.Configuration { /// <summary> /// Individual node-specific silo configuration parameters. /// </summary> [Serializable] public class NodeConfiguration :IStatisticsConfiguration { private readonly DateTime creationTimestamp; private string siloName; /// <summary> /// The name of this silo. /// </summary> public string SiloName { get { return this.siloName; } set { this.siloName = value; } } /// <summary> /// The DNS host name of this silo. /// This is a true host name, no IP address. It is NOT settable, equals Dns.GetHostName(). /// </summary> public string DNSHostName { get; private set; } /// <summary> /// The host name or IP address of this silo. /// This is a configurable IP address or Hostname. /// </summary> public string HostNameOrIPAddress { get; set; } private IPAddress Address { get { return ConfigUtilities.ResolveIPAddress(this.HostNameOrIPAddress, this.Subnet, this.AddressType).GetResult(); } } /// <summary> /// The port this silo uses for silo-to-silo communication. /// </summary> public int Port { get; set; } /// <summary> /// The epoch generation number for this silo. /// </summary> public int Generation { get; set; } /// <summary> /// The IPEndPoint this silo uses for silo-to-silo communication. /// </summary> public IPEndPoint Endpoint { get { return new IPEndPoint(this.Address, this.Port); } } /// <summary> /// The AddressFamilyof the IP address of this silo. /// </summary> public AddressFamily AddressType { get; set; } /// <summary> /// The IPEndPoint this silo uses for (gateway) silo-to-client communication. /// </summary> public IPEndPoint ProxyGatewayEndpoint { get; set; } public byte[] Subnet { get; set; } // from global /// <summary> /// Whether this is a primary silo (applies for dev settings only). /// </summary> public bool IsPrimaryNode { get; set; } /// <summary> /// Whether this is one of the seed silos (applies for dev settings only). /// </summary> public bool IsSeedNode { get; set; } /// <summary> /// Whether this is silo is a proxying gateway silo. /// </summary> public bool IsGatewayNode { get { return this.ProxyGatewayEndpoint != null; } } /// <summary> /// The MaxActiveThreads attribute specifies the maximum number of simultaneous active threads the scheduler will allow. /// Generally this number should be roughly equal to the number of cores on the node. /// Using a value of 0 will look at System.Environment.ProcessorCount to decide the number instead, which is only valid when set from xml config /// </summary> public int MaxActiveThreads { get; set; } /// <summary> /// The DelayWarningThreshold attribute specifies the work item queuing delay threshold, at which a warning log message is written. /// That is, if the delay between enqueuing the work item and executing the work item is greater than DelayWarningThreshold, a warning log is written. /// The default value is 10 seconds. /// </summary> public TimeSpan DelayWarningThreshold { get; set; } /// <summary> /// ActivationSchedulingQuantum is a soft time limit on the duration of activation macro-turn (a number of micro-turns). /// If a activation was running its micro-turns longer than this, we will give up the thread. /// If this is set to zero or a negative number, then the full work queue is drained (MaxWorkItemsPerTurn allowing). /// </summary> public TimeSpan ActivationSchedulingQuantum { get; set; } /// <summary> /// TurnWarningLengthThreshold is a soft time limit to generate trace warning when the micro-turn executes longer then this period in CPU. /// </summary> public TimeSpan TurnWarningLengthThreshold { get; set; } internal bool EnableWorkerThreadInjection { get; set; } /// <summary> /// The LoadShedding element specifies the gateway load shedding configuration for the node. /// If it does not appear, gateway load shedding is disabled. /// </summary> public bool LoadSheddingEnabled { get; set; } /// <summary> /// The LoadLimit attribute specifies the system load, in CPU%, at which load begins to be shed. /// Note that this value is in %, so valid values range from 1 to 100, and a reasonable value is /// typically between 80 and 95. /// This value is ignored if load shedding is disabled, which is the default. /// If load shedding is enabled and this attribute does not appear, then the default limit is 95%. /// </summary> public int LoadSheddingLimit { get; set; } /// <summary> /// The values for various silo limits. /// </summary> public LimitManager LimitManager { get; private set; } /// <summary> /// Whether Trace.CorrelationManager.ActivityId settings should be propagated into grain calls. /// </summary> public bool PropagateActivityId { get; set; } /// <summary> /// Specifies the name of the Startup class in the configuration file. /// </summary> public string StartupTypeName { get; set; } [Obsolete("Statistics publishers are no longer supported.")] public string StatisticsProviderName { get; set; } /// <summary> /// The MetricsTableWriteInterval attribute specifies the frequency of updating the metrics in Azure table. /// The default is 30 seconds. /// </summary> public TimeSpan StatisticsMetricsTableWriteInterval { get; set; } /// <summary> /// The PerfCounterWriteInterval attribute specifies the frequency of updating the windows performance counters. /// The default is 30 seconds. /// </summary> public TimeSpan StatisticsPerfCountersWriteInterval { get; set; } /// <summary> /// The LogWriteInterval attribute specifies the frequency of updating the statistics in the log file. /// The default is 5 minutes. /// </summary> public TimeSpan StatisticsLogWriteInterval { get; set; } /// <summary> /// The WriteLogStatisticsToTable attribute specifies whether log statistics should also be written into a separate, special Azure table. /// The default is yes. /// </summary> [Obsolete("Statistics table is no longer supported.")] public bool StatisticsWriteLogStatisticsToTable { get; set; } /// <summary> /// </summary> public StatisticsLevel StatisticsCollectionLevel { get; set; } /// <summary> /// </summary> public int MinDotNetThreadPoolSize { get; set; } /// <summary> /// </summary> public bool Expect100Continue { get; set; } /// <summary> /// </summary> public int DefaultConnectionLimit { get; set; } /// <summary> /// </summary> public bool UseNagleAlgorithm { get; set; } public TelemetryConfiguration TelemetryConfiguration { get; } = new TelemetryConfiguration(); public Dictionary<string, SearchOption> AdditionalAssemblyDirectories { get; set; } public List<string> ExcludedGrainTypes { get; set; } public string SiloShutdownEventName { get; set; } internal const string DEFAULT_NODE_NAME = "default"; private static int DEFAULT_MAX_ACTIVE_THREADS = Math.Max(4, Environment.ProcessorCount); private static TimeSpan DEFAULT_DELAY_WARNING_THRESHOLD = TimeSpan.FromMilliseconds(10000); private static TimeSpan DEFAULT_ACTIVATION_SCHEDULING_QUANTUM = TimeSpan.FromMilliseconds(100); private static TimeSpan DEFAULT_TURN_WARNING_THRESHOLD = TimeSpan.FromMilliseconds(200); private static TimeSpan DEFAULT_METRICS_TABLE_WRITE_PERIOD = TimeSpan.FromSeconds(30); private static TimeSpan SILO_DEFAULT_PERF_COUNTERS_WRITE_PERIOD = TimeSpan.FromSeconds(30); private static TimeSpan DEFAULT_LOG_WRITE_PERIOD = TimeSpan.FromMinutes(5); private const bool DEFAULT_ENABLE_WORKER_THREAD_INJECTION = false; private const StatisticsLevel DEFAULT_COLLECTION_LEVEL = StatisticsLevel.Info; public NodeConfiguration() { this.creationTimestamp = DateTime.UtcNow; this.SiloName = ""; this.HostNameOrIPAddress = ""; this.DNSHostName = Dns.GetHostName(); this.Port = 0; this.Generation = 0; this.AddressType = AddressFamily.InterNetwork; this.ProxyGatewayEndpoint = null; this.MaxActiveThreads = DEFAULT_MAX_ACTIVE_THREADS; this.DelayWarningThreshold = DEFAULT_DELAY_WARNING_THRESHOLD; this.ActivationSchedulingQuantum = DEFAULT_ACTIVATION_SCHEDULING_QUANTUM; this.TurnWarningLengthThreshold = DEFAULT_TURN_WARNING_THRESHOLD; this.EnableWorkerThreadInjection = DEFAULT_ENABLE_WORKER_THREAD_INJECTION; this.LoadSheddingEnabled = false; this.LoadSheddingLimit = LoadSheddingOptions.DEFAULT_LOAD_SHEDDING_LIMIT; this.PropagateActivityId = MessagingOptions.DEFAULT_PROPAGATE_E2E_ACTIVITY_ID; this.StatisticsMetricsTableWriteInterval = DEFAULT_METRICS_TABLE_WRITE_PERIOD; this.StatisticsPerfCountersWriteInterval = SILO_DEFAULT_PERF_COUNTERS_WRITE_PERIOD; this.StatisticsLogWriteInterval = DEFAULT_LOG_WRITE_PERIOD; this.StatisticsCollectionLevel = DEFAULT_COLLECTION_LEVEL; this.LimitManager = new LimitManager(); this.MinDotNetThreadPoolSize = PerformanceTuningOptions.DEFAULT_MIN_DOT_NET_THREAD_POOL_SIZE; // .NET ServicePointManager settings / optimizations this.Expect100Continue = false; this.DefaultConnectionLimit = PerformanceTuningOptions.DEFAULT_MIN_DOT_NET_CONNECTION_LIMIT; this.UseNagleAlgorithm = false; this.AdditionalAssemblyDirectories = new Dictionary<string, SearchOption>(); this.ExcludedGrainTypes = new List<string>(); } public NodeConfiguration(NodeConfiguration other) { this.creationTimestamp = other.creationTimestamp; this.SiloName = other.SiloName; this.HostNameOrIPAddress = other.HostNameOrIPAddress; this.DNSHostName = other.DNSHostName; this.Port = other.Port; this.Generation = other.Generation; this.AddressType = other.AddressType; this.ProxyGatewayEndpoint = other.ProxyGatewayEndpoint; this.MaxActiveThreads = other.MaxActiveThreads; this.DelayWarningThreshold = other.DelayWarningThreshold; this.ActivationSchedulingQuantum = other.ActivationSchedulingQuantum; this.TurnWarningLengthThreshold = other.TurnWarningLengthThreshold; this.EnableWorkerThreadInjection = other.EnableWorkerThreadInjection; this.LoadSheddingEnabled = other.LoadSheddingEnabled; this.LoadSheddingLimit = other.LoadSheddingLimit; this.PropagateActivityId = other.PropagateActivityId; #pragma warning disable CS0618 // Type or member is obsolete this.StatisticsProviderName = other.StatisticsProviderName; #pragma warning restore CS0618 // Type or member is obsolete this.StatisticsMetricsTableWriteInterval = other.StatisticsMetricsTableWriteInterval; this.StatisticsPerfCountersWriteInterval = other.StatisticsPerfCountersWriteInterval; this.StatisticsLogWriteInterval = other.StatisticsLogWriteInterval; #pragma warning disable CS0618 // Type or member is obsolete this.StatisticsWriteLogStatisticsToTable = other.StatisticsWriteLogStatisticsToTable; #pragma warning restore CS0618 // Type or member is obsolete this.StatisticsCollectionLevel = other.StatisticsCollectionLevel; this.LimitManager = new LimitManager(other.LimitManager); // Shallow copy this.Subnet = other.Subnet; this.MinDotNetThreadPoolSize = other.MinDotNetThreadPoolSize; this.Expect100Continue = other.Expect100Continue; this.DefaultConnectionLimit = other.DefaultConnectionLimit; this.UseNagleAlgorithm = other.UseNagleAlgorithm; this.StartupTypeName = other.StartupTypeName; this.AdditionalAssemblyDirectories = new Dictionary<string, SearchOption>(other.AdditionalAssemblyDirectories); this.ExcludedGrainTypes = other.ExcludedGrainTypes.ToList(); this.TelemetryConfiguration = other.TelemetryConfiguration.Clone(); } public override string ToString() { var sb = new StringBuilder(); sb.Append(" Silo Name: ").AppendLine(this.SiloName); sb.Append(" Generation: ").Append(this.Generation).AppendLine(); sb.Append(" Host Name or IP Address: ").AppendLine(this.HostNameOrIPAddress); sb.Append(" DNS Host Name: ").AppendLine(this.DNSHostName); sb.Append(" Port: ").Append(this.Port).AppendLine(); sb.Append(" Subnet: ").Append(this.Subnet == null ? "" : this.Subnet.ToStrings(x => x.ToString(), ".")).AppendLine(); sb.Append(" Preferred Address Family: ").Append(this.AddressType).AppendLine(); if (this.IsGatewayNode) { sb.Append(" Proxy Gateway: ").Append(this.ProxyGatewayEndpoint.ToString()).AppendLine(); } else { sb.Append(" IsGatewayNode: ").Append(this.IsGatewayNode).AppendLine(); } sb.Append(" IsPrimaryNode: ").Append(this.IsPrimaryNode).AppendLine(); sb.Append(" Scheduler: ").AppendLine(); sb.Append(" ").Append(" Max Active Threads: ").Append(this.MaxActiveThreads).AppendLine(); sb.Append(" ").Append(" Processor Count: ").Append(System.Environment.ProcessorCount).AppendLine(); sb.Append(" ").Append(" Delay Warning Threshold: ").Append(this.DelayWarningThreshold).AppendLine(); sb.Append(" ").Append(" Activation Scheduling Quantum: ").Append(this.ActivationSchedulingQuantum).AppendLine(); sb.Append(" ").Append(" Turn Warning Length Threshold: ").Append(this.TurnWarningLengthThreshold).AppendLine(); sb.Append(" ").Append(" Inject More Worker Threads: ").Append(this.EnableWorkerThreadInjection).AppendLine(); sb.Append(" ").Append(" MinDotNetThreadPoolSize: ").Append(this.MinDotNetThreadPoolSize).AppendLine(); int workerThreads; int completionPortThreads; ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads); sb.Append(" ").AppendFormat(" .NET thread pool sizes - Min: Worker Threads={0} Completion Port Threads={1}", workerThreads, completionPortThreads).AppendLine(); ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads); sb.Append(" ").AppendFormat(" .NET thread pool sizes - Max: Worker Threads={0} Completion Port Threads={1}", workerThreads, completionPortThreads).AppendLine(); sb.Append(" ").AppendFormat(" .NET ServicePointManager - DefaultConnectionLimit={0} Expect100Continue={1} UseNagleAlgorithm={2}", this.DefaultConnectionLimit, this.Expect100Continue, this.UseNagleAlgorithm).AppendLine(); sb.Append(" Load Shedding Enabled: ").Append(this.LoadSheddingEnabled).AppendLine(); sb.Append(" Load Shedding Limit: ").Append(this.LoadSheddingLimit).AppendLine(); sb.Append(" SiloShutdownEventName: ").Append(this.SiloShutdownEventName).AppendLine(); sb.Append(" Debug: ").AppendLine(); sb.Append(ConfigUtilities.IStatisticsConfigurationToString(this)); sb.Append(this.LimitManager); return sb.ToString(); } internal void InitNodeSettingsFromGlobals(ClusterConfiguration clusterConfiguration) { this.IsPrimaryNode = this.Endpoint.Equals(clusterConfiguration.PrimaryNode); this.IsSeedNode = clusterConfiguration.Globals.SeedNodes.Contains(this.Endpoint); } internal void Load(XmlElement root) { this.SiloName = root.LocalName.Equals("Override") ? root.GetAttribute("Node") : DEFAULT_NODE_NAME; foreach (XmlNode c in root.ChildNodes) { var child = c as XmlElement; if (child == null) continue; // Skip comment lines switch (child.LocalName) { case "Networking": if (child.HasAttribute("Address")) { this.HostNameOrIPAddress = child.GetAttribute("Address"); } if (child.HasAttribute("Port")) { this.Port = ConfigUtilities.ParseInt(child.GetAttribute("Port"), "Non-numeric Port attribute value on Networking element for " + this.SiloName); } if (child.HasAttribute("PreferredFamily")) { this.AddressType = ConfigUtilities.ParseEnum<AddressFamily>(child.GetAttribute("PreferredFamily"), "Invalid preferred address family on Networking node. Valid choices are 'InterNetwork' and 'InterNetworkV6'"); } break; case "ProxyingGateway": this.ProxyGatewayEndpoint = ConfigUtilities.ParseIPEndPoint(child, this.Subnet).GetResult(); break; case "Scheduler": if (child.HasAttribute("MaxActiveThreads")) { this.MaxActiveThreads = ConfigUtilities.ParseInt(child.GetAttribute("MaxActiveThreads"), "Non-numeric MaxActiveThreads attribute value on Scheduler element for " + this.SiloName); if (this.MaxActiveThreads < 1) { this.MaxActiveThreads = Math.Max(4, System.Environment.ProcessorCount); } } if (child.HasAttribute("DelayWarningThreshold")) { this.DelayWarningThreshold = ConfigUtilities.ParseTimeSpan(child.GetAttribute("DelayWarningThreshold"), "Non-numeric DelayWarningThreshold attribute value on Scheduler element for " + this.SiloName); } if (child.HasAttribute("ActivationSchedulingQuantum")) { this.ActivationSchedulingQuantum = ConfigUtilities.ParseTimeSpan(child.GetAttribute("ActivationSchedulingQuantum"), "Non-numeric ActivationSchedulingQuantum attribute value on Scheduler element for " + this.SiloName); } if (child.HasAttribute("TurnWarningLengthThreshold")) { this.TurnWarningLengthThreshold = ConfigUtilities.ParseTimeSpan(child.GetAttribute("TurnWarningLengthThreshold"), "Non-numeric TurnWarningLengthThreshold attribute value on Scheduler element for " + this.SiloName); } if (child.HasAttribute("MinDotNetThreadPoolSize")) { this.MinDotNetThreadPoolSize = ConfigUtilities.ParseInt(child.GetAttribute("MinDotNetThreadPoolSize"), "Invalid ParseInt MinDotNetThreadPoolSize value on Scheduler element for " + this.SiloName); } if (child.HasAttribute("Expect100Continue")) { this.Expect100Continue = ConfigUtilities.ParseBool(child.GetAttribute("Expect100Continue"), "Invalid ParseBool Expect100Continue value on Scheduler element for " + this.SiloName); } if (child.HasAttribute("DefaultConnectionLimit")) { this.DefaultConnectionLimit = ConfigUtilities.ParseInt(child.GetAttribute("DefaultConnectionLimit"), "Invalid ParseInt DefaultConnectionLimit value on Scheduler element for " + this.SiloName); } if (child.HasAttribute("UseNagleAlgorithm ")) { this.UseNagleAlgorithm = ConfigUtilities.ParseBool(child.GetAttribute("UseNagleAlgorithm "), "Invalid ParseBool UseNagleAlgorithm value on Scheduler element for " + this.SiloName); } break; case "LoadShedding": if (child.HasAttribute("Enabled")) { this.LoadSheddingEnabled = ConfigUtilities.ParseBool(child.GetAttribute("Enabled"), "Invalid boolean value for Enabled attribute on LoadShedding attribute for " + this.SiloName); } if (child.HasAttribute("LoadLimit")) { this.LoadSheddingLimit = ConfigUtilities.ParseInt(child.GetAttribute("LoadLimit"), "Invalid integer value for LoadLimit attribute on LoadShedding attribute for " + this.SiloName); if (this.LoadSheddingLimit < 0) { this.LoadSheddingLimit = 0; } if (this.LoadSheddingLimit > 100) { this.LoadSheddingLimit = 100; } } break; case "Tracing": if (ConfigUtilities.TryParsePropagateActivityId(child, this.siloName, out var propagateActivityId)) this.PropagateActivityId = propagateActivityId; break; case "Statistics": ConfigUtilities.ParseStatistics(this, child, this.SiloName); break; case "Limits": ConfigUtilities.ParseLimitValues(this.LimitManager, child, this.SiloName); break; case "Startup": if (child.HasAttribute("Type")) { this.StartupTypeName = child.GetAttribute("Type"); } break; case "Telemetry": ConfigUtilities.ParseTelemetry(child, this.TelemetryConfiguration); break; case "AdditionalAssemblyDirectories": ConfigUtilities.ParseAdditionalAssemblyDirectories(this.AdditionalAssemblyDirectories, child); break; } } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using Microsoft.VisualStudio.InteractiveWindow.Commands; using Microsoft.VisualStudio.Text; using Moq; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.VisualStudio.InteractiveWindow.UnitTests { public class InteractiveWindowTests : IDisposable { #region Helpers private InteractiveWindowTestHost _testHost; private List<InteractiveWindow.State> _states; public InteractiveWindowTests() { _states = new List<InteractiveWindow.State>(); _testHost = new InteractiveWindowTestHost(_states.Add); } void IDisposable.Dispose() { _testHost.Dispose(); } private IInteractiveWindow Window => _testHost.Window; private static IEnumerable<IInteractiveWindowCommand> MockCommands(params string[] commandNames) { foreach (var name in commandNames) { var mock = new Mock<IInteractiveWindowCommand>(); mock.Setup(m => m.Names).Returns(new[] { name }); yield return mock.Object; } } private static ITextSnapshot MockSnapshot(string content) { var snapshotMock = new Mock<ITextSnapshot>(); snapshotMock.Setup(m => m[It.IsAny<int>()]).Returns<int>(index => content[index]); snapshotMock.Setup(m => m.Length).Returns(content.Length); snapshotMock.Setup(m => m.GetText()).Returns(content); snapshotMock.Setup(m => m.GetText(It.IsAny<int>(), It.IsAny<int>())).Returns<int, int>((start, length) => content.Substring(start, length)); snapshotMock.Setup(m => m.GetText(It.IsAny<Span>())).Returns<Span>(span => content.Substring(span.Start, span.Length)); return snapshotMock.Object; } #endregion [Fact] public void InteractiveWindow__CommandParsing() { var commandList = MockCommands("foo", "bar", "bz", "command1").ToArray(); var commands = new Commands.Commands(null, "%", commandList); AssertEx.Equal(commands.GetCommands(), commandList); var cmdBar = commandList[1]; Assert.Equal("bar", cmdBar.Names.First()); Assert.Equal("%", commands.CommandPrefix); commands.CommandPrefix = "#"; Assert.Equal("#", commands.CommandPrefix); //// 111111 //// 0123456789012345 var s1 = MockSnapshot("#bar arg1 arg2 "); SnapshotSpan prefixSpan, commandSpan, argsSpan; IInteractiveWindowCommand cmd; cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 0)), out prefixSpan, out commandSpan, out argsSpan); Assert.Null(cmd); cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 1)), out prefixSpan, out commandSpan, out argsSpan); Assert.Null(cmd); cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 2)), out prefixSpan, out commandSpan, out argsSpan); Assert.Null(cmd); Assert.Equal(0, prefixSpan.Start); Assert.Equal(1, prefixSpan.End); Assert.Equal(1, commandSpan.Start); Assert.Equal(2, commandSpan.End); Assert.Equal(2, argsSpan.Start); Assert.Equal(2, argsSpan.End); cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 3)), out prefixSpan, out commandSpan, out argsSpan); Assert.Null(cmd); Assert.Equal(0, prefixSpan.Start); Assert.Equal(1, prefixSpan.End); Assert.Equal(1, commandSpan.Start); Assert.Equal(3, commandSpan.End); Assert.Equal(3, argsSpan.Start); Assert.Equal(3, argsSpan.End); cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 4)), out prefixSpan, out commandSpan, out argsSpan); Assert.Equal(cmdBar, cmd); Assert.Equal(0, prefixSpan.Start); Assert.Equal(1, prefixSpan.End); Assert.Equal(1, commandSpan.Start); Assert.Equal(4, commandSpan.End); Assert.Equal(4, argsSpan.Start); Assert.Equal(4, argsSpan.End); cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 5)), out prefixSpan, out commandSpan, out argsSpan); Assert.Equal(cmdBar, cmd); Assert.Equal(0, prefixSpan.Start); Assert.Equal(1, prefixSpan.End); Assert.Equal(1, commandSpan.Start); Assert.Equal(4, commandSpan.End); Assert.Equal(5, argsSpan.Start); Assert.Equal(5, argsSpan.End); cmd = commands.TryParseCommand(s1.GetExtent(), out prefixSpan, out commandSpan, out argsSpan); Assert.Equal(cmdBar, cmd); Assert.Equal(0, prefixSpan.Start); Assert.Equal(1, prefixSpan.End); Assert.Equal(1, commandSpan.Start); Assert.Equal(4, commandSpan.End); Assert.Equal(5, argsSpan.Start); Assert.Equal(14, argsSpan.End); //// //// 0123456789 var s2 = MockSnapshot(" #bar "); cmd = commands.TryParseCommand(s2.GetExtent(), out prefixSpan, out commandSpan, out argsSpan); Assert.Equal(cmdBar, cmd); Assert.Equal(2, prefixSpan.Start); Assert.Equal(3, prefixSpan.End); Assert.Equal(3, commandSpan.Start); Assert.Equal(6, commandSpan.End); Assert.Equal(9, argsSpan.Start); Assert.Equal(9, argsSpan.End); //// 111111 //// 0123456789012345 var s3 = MockSnapshot(" # bar args"); cmd = commands.TryParseCommand(s3.GetExtent(), out prefixSpan, out commandSpan, out argsSpan); Assert.Equal(cmdBar, cmd); Assert.Equal(2, prefixSpan.Start); Assert.Equal(3, prefixSpan.End); Assert.Equal(6, commandSpan.Start); Assert.Equal(9, commandSpan.End); Assert.Equal(11, argsSpan.Start); Assert.Equal(15, argsSpan.End); } [Fact] public void InteractiveWindow_GetCommands() { var interactiveCommands = new InteractiveCommandsFactory(null, null).CreateInteractiveCommands( Window, "#", _testHost.ExportProvider.GetExports<IInteractiveWindowCommand>().Select(x => x.Value).ToArray()); var commands = interactiveCommands.GetCommands(); Assert.NotEmpty(commands); Assert.Equal(2, commands.Where(n => n.Names.First() == "cls").Count()); Assert.Equal(2, commands.Where(n => n.Names.Last() == "clear").Count()); Assert.NotNull(commands.Where(n => n.Names.First() == "help").SingleOrDefault()); Assert.NotNull(commands.Where(n => n.Names.First() == "reset").SingleOrDefault()); } [WorkItem(3970, "https://github.com/dotnet/roslyn/issues/3970")] [Fact] public void ResetStateTransitions() { Window.Operations.ResetAsync().PumpingWait(); Assert.Equal(_states, new[] { InteractiveWindow.State.Initializing, InteractiveWindow.State.WaitingForInput, InteractiveWindow.State.Resetting, InteractiveWindow.State.WaitingForInput, }); } [Fact] public void DoubleInitialize() { try { Window.InitializeAsync().PumpingWait(); Assert.True(false); } catch (AggregateException e) { Assert.IsType<InvalidOperationException>(e.InnerExceptions.Single()); } } [Fact] public void AccessPropertiesOnUIThread() { foreach (var property in typeof(IInteractiveWindow).GetProperties()) { Assert.Null(property.SetMethod); property.GetMethod.Invoke(Window, Array.Empty<object>()); } Assert.Empty(typeof(IInteractiveWindowOperations).GetProperties()); } [Fact] public void AccessPropertiesOnNonUIThread() { foreach (var property in typeof(IInteractiveWindow).GetProperties()) { Assert.Null(property.SetMethod); Task.Run(() => property.GetMethod.Invoke(Window, Array.Empty<object>())).PumpingWait(); } Assert.Empty(typeof(IInteractiveWindowOperations).GetProperties()); } /// <remarks> /// Confirm that we are, in fact, running on a non-UI thread. /// </remarks> [Fact] public void NonUIThread() { Task.Run(() => Assert.False(((InteractiveWindow)Window).OnUIThread())).PumpingWait(); } [Fact] public void CallCloseOnNonUIThread() { Task.Run(() => Window.Close()).PumpingWait(); } [Fact] public void CallInsertCodeOnNonUIThread() { Task.Run(() => Window.InsertCode("1")).PumpingWait(); } [Fact] public void CallSubmitAsyncOnNonUIThread() { Task.Run(() => Window.SubmitAsync(Array.Empty<string>()).GetAwaiter().GetResult()).PumpingWait(); } [Fact] public void CallWriteOnNonUIThread() { Task.Run(() => Window.WriteLine("1")).PumpingWait(); Task.Run(() => Window.Write("1")).PumpingWait(); Task.Run(() => Window.WriteErrorLine("1")).PumpingWait(); Task.Run(() => Window.WriteError("1")).PumpingWait(); } [Fact] public void CallFlushOutputOnNonUIThread() { Window.Write("1"); // Something to flush. Task.Run(() => Window.FlushOutput()).PumpingWait(); } [Fact] public void CallAddInputOnNonUIThread() { Task.Run(() => Window.AddInput("1")).PumpingWait(); } /// <remarks> /// Call is blocking, so we can't write a simple non-failing test. /// </remarks> [Fact] public void CallReadStandardInputOnUIThread() { Assert.Throws<InvalidOperationException>(() => Window.ReadStandardInput()); } [Fact] public void CallBackspaceOnNonUIThread() { Window.InsertCode("1"); // Something to backspace. Task.Run(() => Window.Operations.Backspace()).PumpingWait(); } [Fact] public void CallBreakLineOnNonUIThread() { Task.Run(() => Window.Operations.BreakLine()).PumpingWait(); } [Fact] public void CallClearHistoryOnNonUIThread() { Window.AddInput("1"); // Need a history entry. Task.Run(() => Window.Operations.ClearHistory()).PumpingWait(); } [Fact] public void CallClearViewOnNonUIThread() { Window.InsertCode("1"); // Something to clear. Task.Run(() => Window.Operations.ClearView()).PumpingWait(); } [Fact] public void CallHistoryNextOnNonUIThread() { Window.AddInput("1"); // Need a history entry. Task.Run(() => Window.Operations.HistoryNext()).PumpingWait(); } [Fact] public void CallHistoryPreviousOnNonUIThread() { Window.AddInput("1"); // Need a history entry. Task.Run(() => Window.Operations.HistoryPrevious()).PumpingWait(); } [Fact] public void CallHistorySearchNextOnNonUIThread() { Window.AddInput("1"); // Need a history entry. Task.Run(() => Window.Operations.HistorySearchNext()).PumpingWait(); } [Fact] public void CallHistorySearchPreviousOnNonUIThread() { Window.AddInput("1"); // Need a history entry. Task.Run(() => Window.Operations.HistorySearchPrevious()).PumpingWait(); } [Fact] public void CallHomeOnNonUIThread() { Window.Operations.BreakLine(); // Distinguish Home from End. Task.Run(() => Window.Operations.Home(true)).PumpingWait(); } [Fact] public void CallEndOnNonUIThread() { Window.Operations.BreakLine(); // Distinguish Home from End. Task.Run(() => Window.Operations.End(true)).PumpingWait(); } [Fact] public void ScrollToCursorOnHomeAndEndOnNonUIThread() { Window.InsertCode(new string('1', 512)); // a long input string var textView = Window.TextView; Window.Operations.Home(false); Assert.True(textView.TextViewModel.IsPointInVisualBuffer(textView.Caret.Position.BufferPosition, textView.Caret.Position.Affinity)); Window.Operations.End(false); Assert.True(textView.TextViewModel.IsPointInVisualBuffer(textView.Caret.Position.BufferPosition, textView.Caret.Position.Affinity)); } [Fact] public void CallSelectAllOnNonUIThread() { Window.InsertCode("1"); // Something to select. Task.Run(() => Window.Operations.SelectAll()).PumpingWait(); } [Fact] public void CallPasteOnNonUIThread() { Task.Run(() => Window.Operations.Paste()).PumpingWait(); } [Fact] public void CallCutOnNonUIThread() { Task.Run(() => Window.Operations.Cut()).PumpingWait(); } [Fact] public void CallDeleteOnNonUIThread() { Task.Run(() => Window.Operations.Delete()).PumpingWait(); } [Fact] public void CallReturnOnNonUIThread() { Task.Run(() => Window.Operations.Return()).PumpingWait(); } [Fact] public void CallTrySubmitStandardInputOnNonUIThread() { Task.Run(() => Window.Operations.TrySubmitStandardInput()).PumpingWait(); } [Fact] public void CallResetAsyncOnNonUIThread() { Task.Run(() => Window.Operations.ResetAsync()).PumpingWait(); } [Fact] public void CallExecuteInputOnNonUIThread() { Task.Run(() => Window.Operations.ExecuteInput()).PumpingWait(); } [Fact] public void CallCancelOnNonUIThread() { Task.Run(() => Window.Operations.Cancel()).PumpingWait(); } [WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")] [Fact] public void TestIndentation1() { TestIndentation(indentSize: 1); } [WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")] [Fact] public void TestIndentation2() { TestIndentation(indentSize: 2); } [WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")] [Fact] public void TestIndentation3() { TestIndentation(indentSize: 3); } [WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")] [Fact] public void TestIndentation4() { TestIndentation(indentSize: 4); } private void TestIndentation(int indentSize) { const int promptWidth = 2; _testHost.ExportProvider.GetExport<TestSmartIndentProvider>().Value.SmartIndent = new TestSmartIndent( promptWidth, promptWidth + indentSize, promptWidth ); AssertCaretVirtualPosition(0, promptWidth); Window.InsertCode("{"); AssertCaretVirtualPosition(0, promptWidth + 1); Window.Operations.BreakLine(); AssertCaretVirtualPosition(1, promptWidth + indentSize); Window.InsertCode("Console.WriteLine();"); Window.Operations.BreakLine(); AssertCaretVirtualPosition(2, promptWidth); Window.InsertCode("}"); AssertCaretVirtualPosition(2, promptWidth + 1); } private void AssertCaretVirtualPosition(int expectedLine, int expectedColumn) { ITextSnapshotLine actualLine; int actualColumn; Window.TextView.Caret.Position.VirtualBufferPosition.GetLineAndColumn(out actualLine, out actualColumn); Assert.Equal(expectedLine, actualLine.LineNumber); Assert.Equal(expectedColumn, actualColumn); } [Fact] public void ResetCommandArgumentParsing_Success() { bool initialize; Assert.True(ResetCommand.TryParseArguments("", out initialize)); Assert.True(initialize); Assert.True(ResetCommand.TryParseArguments(" ", out initialize)); Assert.True(initialize); Assert.True(ResetCommand.TryParseArguments("\r\n", out initialize)); Assert.True(initialize); Assert.True(ResetCommand.TryParseArguments("noconfig", out initialize)); Assert.False(initialize); Assert.True(ResetCommand.TryParseArguments(" noconfig ", out initialize)); Assert.False(initialize); Assert.True(ResetCommand.TryParseArguments("\r\nnoconfig\r\n", out initialize)); Assert.False(initialize); } [Fact] public void ResetCommandArgumentParsing_Failure() { bool initialize; Assert.False(ResetCommand.TryParseArguments("a", out initialize)); Assert.False(ResetCommand.TryParseArguments("noconfi", out initialize)); Assert.False(ResetCommand.TryParseArguments("noconfig1", out initialize)); Assert.False(ResetCommand.TryParseArguments("noconfig 1", out initialize)); Assert.False(ResetCommand.TryParseArguments("1 noconfig", out initialize)); Assert.False(ResetCommand.TryParseArguments("noconfig\r\na", out initialize)); Assert.False(ResetCommand.TryParseArguments("nOcOnfIg", out initialize)); } [Fact] public void ResetCommandNoConfigClassification() { Assert.Empty(ResetCommand.GetNoConfigPositions("")); Assert.Empty(ResetCommand.GetNoConfigPositions("a")); Assert.Empty(ResetCommand.GetNoConfigPositions("noconfi")); Assert.Empty(ResetCommand.GetNoConfigPositions("noconfig1")); Assert.Empty(ResetCommand.GetNoConfigPositions("1noconfig")); Assert.Empty(ResetCommand.GetNoConfigPositions("1noconfig1")); Assert.Empty(ResetCommand.GetNoConfigPositions("nOcOnfIg")); Assert.Equal(new[] { 0 }, ResetCommand.GetNoConfigPositions("noconfig")); Assert.Equal(new[] { 0 }, ResetCommand.GetNoConfigPositions("noconfig ")); Assert.Equal(new[] { 1 }, ResetCommand.GetNoConfigPositions(" noconfig")); Assert.Equal(new[] { 1 }, ResetCommand.GetNoConfigPositions(" noconfig ")); Assert.Equal(new[] { 2 }, ResetCommand.GetNoConfigPositions("\r\nnoconfig")); Assert.Equal(new[] { 0 }, ResetCommand.GetNoConfigPositions("noconfig\r\n")); Assert.Equal(new[] { 2 }, ResetCommand.GetNoConfigPositions("\r\nnoconfig\r\n")); Assert.Equal(new[] { 6 }, ResetCommand.GetNoConfigPositions("error noconfig")); Assert.Equal(new[] { 0, 9 }, ResetCommand.GetNoConfigPositions("noconfig noconfig")); Assert.Equal(new[] { 0, 15 }, ResetCommand.GetNoConfigPositions("noconfig error noconfig")); } [WorkItem(4755, "https://github.com/dotnet/roslyn/issues/4755")] [Fact] public void ReformatBraces() { var buffer = Window.CurrentLanguageBuffer; var snapshot = buffer.CurrentSnapshot; Assert.Equal(0, snapshot.Length); // Text before reformatting. snapshot = ApplyChanges( buffer, new TextChange(0, 0, "{ {\r\n } }")); // Text after reformatting. Assert.Equal(9, snapshot.Length); snapshot = ApplyChanges( buffer, new TextChange(1, 1, "\r\n "), new TextChange(5, 1, " "), new TextChange(7, 1, "\r\n")); // Text from language buffer. var actualText = snapshot.GetText(); Assert.Equal("{\r\n {\r\n }\r\n}", actualText); // Text including prompts. buffer = Window.TextView.TextBuffer; snapshot = buffer.CurrentSnapshot; actualText = snapshot.GetText(); Assert.Equal("> {\r\n> {\r\n> }\r\n> }", actualText); // Prompts should be read-only. var regions = buffer.GetReadOnlyExtents(new Span(0, snapshot.Length)); AssertEx.SetEqual(regions, new Span(0, 2), new Span(5, 2), new Span(14, 2), new Span(23, 2)); } [Fact] public void CopyWithinInput() { Clipboard.Clear(); Window.InsertCode("1 + 2"); Window.Operations.SelectAll(); Window.Operations.Copy(); VerifyClipboardData("1 + 2", "1 + 2", @"[{""content"":""1 + 2"",""kind"":2}]"); // Shrink the selection. var selection = Window.TextView.Selection; var span = selection.SelectedSpans[0]; selection.Select(new SnapshotSpan(span.Snapshot, span.Start + 1, span.Length - 2), isReversed: false); Window.Operations.Copy(); VerifyClipboardData(" + ", " + ", @"[{""content"":"" + "",""kind"":2}]"); } [Fact] public void CopyInputAndOutput() { Clipboard.Clear(); Submit( @"foreach (var o in new[] { 1, 2, 3 }) System.Console.WriteLine();", @"1 2 3 "); var caret = Window.TextView.Caret; caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); Window.Operations.SelectAll(); Window.Operations.SelectAll(); Window.Operations.Copy(); VerifyClipboardData(@"> foreach (var o in new[] { 1, 2, 3 }) > System.Console.WriteLine(); 1 2 3 > ", @"> foreach (var o in new[] \{ 1, 2, 3 \})\par > System.Console.WriteLine();\par 1\par 2\par 3\par > ", @"[{""content"":""> "",""kind"":2},{""content"":""foreach (var o in new[] { 1, 2, 3 })\u000d\u000a"",""kind"":2},{""content"":""> "",""kind"":2},{""content"":""System.Console.WriteLine();\u000d\u000a"",""kind"":2},{""content"":""1\u000d\u000a2\u000d\u000a3\u000d\u000a"",""kind"":2},{""content"":""> "",""kind"":2}]"); // Shrink the selection. var selection = Window.TextView.Selection; var span = selection.SelectedSpans[0]; selection.Select(new SnapshotSpan(span.Snapshot, span.Start + 3, span.Length - 6), isReversed: false); Window.Operations.Copy(); VerifyClipboardData(@"oreach (var o in new[] { 1, 2, 3 }) > System.Console.WriteLine(); 1 2 3", @"oreach (var o in new[] \{ 1, 2, 3 \})\par > System.Console.WriteLine();\par 1\par 2\par 3", @"[{""content"":""oreach (var o in new[] { 1, 2, 3 })\u000d\u000a"",""kind"":2},{""content"":""> "",""kind"":2},{""content"":""System.Console.WriteLine();\u000d\u000a"",""kind"":2},{""content"":""1\u000d\u000a2\u000d\u000a3"",""kind"":2}]"); } [Fact] public void CutWithinInput() { Clipboard.Clear(); Window.InsertCode("foreach (var o in new[] { 1, 2, 3 })"); Window.Operations.BreakLine(); Window.InsertCode("System.Console.WriteLine();"); Window.Operations.BreakLine(); var caret = Window.TextView.Caret; caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); Window.Operations.SelectAll(); // Shrink the selection. var selection = Window.TextView.Selection; var span = selection.SelectedSpans[0]; selection.Select(new SnapshotSpan(span.Snapshot, span.Start + 3, span.Length - 6), isReversed: false); Window.Operations.Cut(); VerifyClipboardData( @"each (var o in new[] { 1, 2, 3 }) System.Console.WriteLine()", expectedRtf: null, expectedRepl: null); } [Fact] public void CutInputAndOutput() { Clipboard.Clear(); Submit( @"foreach (var o in new[] { 1, 2, 3 }) System.Console.WriteLine();", @"1 2 3 "); var caret = Window.TextView.Caret; caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); Window.Operations.SelectAll(); Window.Operations.SelectAll(); Window.Operations.Cut(); VerifyClipboardData(null, null, null); } /// <summary> /// When there is no selection, copy /// should copy the current line. /// </summary> [Fact] public void CopyNoSelection() { Submit( @"s + t", @" 1 2 "); CopyNoSelectionAndVerify(0, 7, "> s +\r\n", @"> s +\par ", @"[{""content"":""> "",""kind"":2},{""content"":""s +\u000d\u000a"",""kind"":2}]"); CopyNoSelectionAndVerify(7, 11, "> \r\n", @"> \par ", @"[{""content"":""> "",""kind"":2},{""content"":""\u000d\u000a"",""kind"":2}]"); CopyNoSelectionAndVerify(11, 17, "> t\r\n", @"> t\par ", @"[{""content"":""> "",""kind"":2},{""content"":"" t\u000d\u000a"",""kind"":2}]"); CopyNoSelectionAndVerify(17, 21, " 1\r\n", @" 1\par ", @"[{""content"":"" 1\u000d\u000a"",""kind"":2}]"); CopyNoSelectionAndVerify(21, 23, "\r\n", @"\par ", @"[{""content"":""\u000d\u000a"",""kind"":2}]"); CopyNoSelectionAndVerify(23, 28, "2 > ", "2 > ", @"[{""content"":""2 "",""kind"":2},{""content"":""> "",""kind"":2}]"); } private void CopyNoSelectionAndVerify(int start, int end, string expectedText, string expectedRtf, string expectedRepl) { var caret = Window.TextView.Caret; var snapshot = Window.TextView.TextBuffer.CurrentSnapshot; for (int i = start; i < end; i++) { Clipboard.Clear(); caret.MoveTo(new SnapshotPoint(snapshot, i)); Window.Operations.Copy(); VerifyClipboardData(expectedText, expectedRtf, expectedRepl); } } [Fact] public void Paste() { var blocks = new[] { new BufferBlock(ReplSpanKind.Output, "a\r\nbc"), new BufferBlock(ReplSpanKind.Prompt, "> "), new BufferBlock(ReplSpanKind.Prompt, "< "), new BufferBlock(ReplSpanKind.Input, "12"), new BufferBlock(ReplSpanKind.StandardInput, "3"), new BufferBlock((ReplSpanKind)10, "xyz") }; // Paste from text clipboard format. CopyToClipboard(blocks, includeRepl: false); Window.Operations.Paste(); var text = Window.TextView.TextBuffer.CurrentSnapshot.GetText(); Assert.Equal("> a\r\n> bc> < 123xyz", text); Window.Operations.ClearView(); text = Window.TextView.TextBuffer.CurrentSnapshot.GetText(); Assert.Equal("> ", text); // Paste from custom clipboard format. CopyToClipboard(blocks, includeRepl: true); Window.Operations.Paste(); text = Window.TextView.TextBuffer.CurrentSnapshot.GetText(); Assert.Equal("> a\r\n> bc123", text); } private static void CopyToClipboard(BufferBlock[] blocks, bool includeRepl) { Clipboard.Clear(); var data = new DataObject(); var builder = new StringBuilder(); foreach (var block in blocks) { builder.Append(block.Content); } var text = builder.ToString(); data.SetData(DataFormats.UnicodeText, text); data.SetData(DataFormats.StringFormat, text); if (includeRepl) { data.SetData(InteractiveWindow.ClipboardFormat, BufferBlock.Serialize(blocks)); } Clipboard.SetDataObject(data, false); } [Fact] public void JsonSerialization() { var expectedContent = new [] { new BufferBlock(ReplSpanKind.Prompt, "> "), new BufferBlock(ReplSpanKind.Input, "Hello"), new BufferBlock(ReplSpanKind.Prompt, ". "), new BufferBlock(ReplSpanKind.StandardInput, "world"), new BufferBlock(ReplSpanKind.Output, "Hello world"), }; var actualJson = BufferBlock.Serialize(expectedContent); var expectedJson = @"[{""content"":""> "",""kind"":0},{""content"":""Hello"",""kind"":2},{""content"":"". "",""kind"":0},{""content"":""world"",""kind"":3},{""content"":""Hello world"",""kind"":1}]"; Assert.Equal(expectedJson, actualJson); var actualContent = BufferBlock.Deserialize(actualJson); Assert.Equal(expectedContent.Length, actualContent.Length); for (int i = 0; i < expectedContent.Length; i++) { var expectedBuffer = expectedContent[i]; var actualBuffer = actualContent[i]; Assert.Equal(expectedBuffer.Kind, actualBuffer.Kind); Assert.Equal(expectedBuffer.Content, actualBuffer.Content); } } [Fact] public void CancelMultiLineInput() { ApplyChanges( Window.CurrentLanguageBuffer, new TextChange(0, 0, "{\r\n {\r\n }\r\n}")); // Text including prompts. var buffer = Window.TextView.TextBuffer; var snapshot = buffer.CurrentSnapshot; Assert.Equal("> {\r\n> {\r\n> }\r\n> }", snapshot.GetText()); Task.Run(() => Window.Operations.Cancel()).PumpingWait(); // Text after cancel. snapshot = buffer.CurrentSnapshot; Assert.Equal("> ", snapshot.GetText()); } [Fact] public void SelectAllInHeader() { Window.WriteLine("Header"); Window.FlushOutput(); var fullText = Window.TextView.TextBuffer.CurrentSnapshot.GetText(); Assert.Equal("Header\r\n> ", fullText); Window.TextView.Caret.MoveTo(new SnapshotPoint(Window.TextView.TextBuffer.CurrentSnapshot, 1)); Window.Operations.SelectAll(); // Used to throw. // Everything is selected. Assert.Equal(new Span(0, fullText.Length), Window.TextView.Selection.SelectedSpans.Single().Span); } [Fact] public void DeleteWithOutSelectionInReadOnlyArea() { Submit( @"1", @"1 "); Window.InsertCode("2"); var caret = Window.TextView.Caret; // with empty selection, Delete() only handles caret movement, // so we can only test caret location. // Delete() with caret in readonly area, no-op caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); AssertCaretVirtualPosition(1, 1); Task.Run(() => Window.Operations.Delete()).PumpingWait(); AssertCaretVirtualPosition(1, 1); // Delete() with caret in active prompt, move caret to // closest editable buffer caret.MoveToNextCaretPosition(); AssertCaretVirtualPosition(2, 0); Task.Run(() => Window.Operations.Delete()).PumpingWait(); AssertCaretVirtualPosition(2, 2); } [Fact] public void DeleteWithSelectionInReadonlyArea() { Submit( @"1", @"1 "); Window.InsertCode("23"); var caret = Window.TextView.Caret; var selection = Window.TextView.Selection; // Delete() with selection in readonly area, no-op caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); AssertCaretVirtualPosition(1, 1); Window.Operations.SelectAll(); Task.Run(() => Window.Operations.Delete()).PumpingWait(); Assert.Equal("> 1\r\n1\r\n> 23", Window.TextView.TextBuffer.CurrentSnapshot.GetText()); // Delete() with selection in active prompt, no-op selection.Clear(); var start = caret.MoveToNextCaretPosition().VirtualBufferPosition; caret.MoveToNextCaretPosition(); var end = caret.MoveToNextCaretPosition().VirtualBufferPosition; AssertCaretVirtualPosition(2, 2); selection.Select(start, end); Task.Run(() => Window.Operations.Delete()).PumpingWait(); Assert.Equal("> 1\r\n1\r\n> 23", Window.TextView.TextBuffer.CurrentSnapshot.GetText()); // Delete() with selection overlaps with editable buffer, // delete editable content and move caret to closest editable location selection.Clear(); caret.MoveToPreviousCaretPosition(); start = caret.MoveToPreviousCaretPosition().VirtualBufferPosition; caret.MoveToNextCaretPosition(); caret.MoveToNextCaretPosition(); end = caret.MoveToNextCaretPosition().VirtualBufferPosition; AssertCaretVirtualPosition(2, 3); selection.Select(start, end); Task.Run(() => Window.Operations.Delete()).PumpingWait(); Assert.Equal("> 1\r\n1\r\n> 3", Window.TextView.TextBuffer.CurrentSnapshot.GetText()); AssertCaretVirtualPosition(2, 2); } [Fact] public void BackspaceWithOutSelectionInReadOnlyArea() { Submit( @"1", @"1 "); Window.InsertCode("int x"); Window.Operations.BreakLine(); Window.InsertCode(";"); var caret = Window.TextView.Caret; // Backspace() with caret in readonly area, no-op Window.Operations.Home(false); Window.Operations.Home(false); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); Window.Operations.Home(false); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); AssertCaretVirtualPosition(1, 1); Task.Run(() => Window.Operations.Backspace()).PumpingWait(); AssertCaretVirtualPosition(1, 1); Assert.Equal("> 1\r\n1\r\n> int x\r\n> ;", Window.TextView.TextBuffer.CurrentSnapshot.GetText()); // Backspace() with caret in 2nd active prompt, move caret to // closest editable buffer then delete prvious characer (breakline) caret.MoveToNextCaretPosition(); Window.Operations.End(false); caret.MoveToNextCaretPosition(); caret.MoveToNextCaretPosition(); AssertCaretVirtualPosition(3, 1); Task.Run(() => Window.Operations.Backspace()).PumpingWait(); AssertCaretVirtualPosition(2, 7); Assert.Equal("> 1\r\n1\r\n> int x;", Window.TextView.TextBuffer.CurrentSnapshot.GetText()); } [Fact] public void BackspaceWithSelectionInReadonlyArea() { Submit( @"1", @"1 "); Window.InsertCode("int x"); Window.Operations.BreakLine(); Window.InsertCode(";"); var caret = Window.TextView.Caret; var selection = Window.TextView.Selection; // Backspace() with selection in readonly area, no-op Window.Operations.Home(false); Window.Operations.Home(false); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); Window.Operations.Home(false); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); AssertCaretVirtualPosition(1, 1); Window.Operations.SelectAll(); Task.Run(() => Window.Operations.Backspace()).PumpingWait(); Assert.Equal("> 1\r\n1\r\n> int x\r\n> ;", Window.TextView.TextBuffer.CurrentSnapshot.GetText()); // Backspace() with selection in active prompt, no-op selection.Clear(); var start = caret.MoveToNextCaretPosition().VirtualBufferPosition; caret.MoveToNextCaretPosition(); var end = caret.MoveToNextCaretPosition().VirtualBufferPosition; AssertCaretVirtualPosition(2, 2); selection.Select(start, end); Task.Run(() => Window.Operations.Backspace()).PumpingWait(); Assert.Equal("> 1\r\n1\r\n> int x\r\n> ;", Window.TextView.TextBuffer.CurrentSnapshot.GetText()); // Backspace() with selection overlaps with editable buffer selection.Clear(); Window.Operations.End(false); start = caret.Position.VirtualBufferPosition; caret.MoveToNextCaretPosition(); caret.MoveToNextCaretPosition(); end = caret.MoveToNextCaretPosition().VirtualBufferPosition; AssertCaretVirtualPosition(3, 2); selection.Select(start, end); Task.Run(() => Window.Operations.Backspace()).PumpingWait(); Assert.Equal("> 1\r\n1\r\n> int x;", Window.TextView.TextBuffer.CurrentSnapshot.GetText()); AssertCaretVirtualPosition(2, 7); } [Fact] public void ReturnWithOutSelectionInReadOnlyArea() { Submit( @"1", @"1 "); var caret = Window.TextView.Caret; // Return() with caret in readonly area, no-op caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); AssertCaretVirtualPosition(1, 1); Task.Run(() => Window.Operations.Return()).PumpingWait(); AssertCaretVirtualPosition(1, 1); // Return() with caret in active prompt, move caret to // closest editable buffer first caret.MoveToNextCaretPosition(); AssertCaretVirtualPosition(2, 0); Task.Run(() => Window.Operations.Return()).PumpingWait(); AssertCaretVirtualPosition(3, 2); } [Fact] public void ReturnWithSelectionInReadonlyArea() { Submit( @"1", @"1 "); Window.InsertCode("23"); var caret = Window.TextView.Caret; var selection = Window.TextView.Selection; // Return() with selection in readonly area, no-op caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); AssertCaretVirtualPosition(1, 1); Window.Operations.SelectAll(); Task.Run(() => Window.Operations.Return()).PumpingWait(); Assert.Equal("> 1\r\n1\r\n> 23", Window.TextView.TextBuffer.CurrentSnapshot.GetText()); // Return() with selection in active prompt, no-op selection.Clear(); var start = caret.MoveToNextCaretPosition().VirtualBufferPosition; caret.MoveToNextCaretPosition(); var end = caret.MoveToNextCaretPosition().VirtualBufferPosition; AssertCaretVirtualPosition(2, 2); selection.Select(start, end); Task.Run(() => Window.Operations.Return()).PumpingWait(); Assert.Equal("> 1\r\n1\r\n> 23", Window.TextView.TextBuffer.CurrentSnapshot.GetText()); // Delete() with selection overlaps with editable buffer, // delete editable content and move caret to closest editable location and insert a return selection.Clear(); caret.MoveToPreviousCaretPosition(); start = caret.MoveToPreviousCaretPosition().VirtualBufferPosition; caret.MoveToNextCaretPosition(); caret.MoveToNextCaretPosition(); end = caret.MoveToNextCaretPosition().VirtualBufferPosition; AssertCaretVirtualPosition(2, 3); selection.Select(start, end); Task.Run(() => Window.Operations.Return()).PumpingWait(); Assert.Equal("> 1\r\n1\r\n> \r\n> 3", Window.TextView.TextBuffer.CurrentSnapshot.GetText()); AssertCaretVirtualPosition(3, 2); } [Fact] public void CutWithOutSelectionInReadOnlyArea() { Submit( @"1", @"1 "); Window.InsertCode("2"); var caret = Window.TextView.Caret; Clipboard.Clear(); // Cut() with caret in readonly area, no-op caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); AssertCaretVirtualPosition(1, 1); Task.Run(() => Window.Operations.Cut()).PumpingWait(); Assert.Equal("> 1\r\n1\r\n> 2", Window.TextView.TextBuffer.CurrentSnapshot.GetText()); AssertCaretVirtualPosition(1, 1); VerifyClipboardData(null, null, null); // Cut() with caret in active prompt caret.MoveToNextCaretPosition(); AssertCaretVirtualPosition(2, 0); Task.Run(() => Window.Operations.Cut()).PumpingWait(); Assert.Equal("> 1\r\n1\r\n> ", Window.TextView.TextBuffer.CurrentSnapshot.GetText()); AssertCaretVirtualPosition(2, 2); VerifyClipboardData("2", expectedRtf: null, expectedRepl: null); } [Fact] public void CutWithSelectionInReadonlyArea() { Submit( @"1", @"1 "); Window.InsertCode("23"); var caret = Window.TextView.Caret; var selection = Window.TextView.Selection; Clipboard.Clear(); // Cut() with selection in readonly area, no-op caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); AssertCaretVirtualPosition(1, 1); Window.Operations.SelectAll(); Task.Run(() => Window.Operations.Cut()).PumpingWait(); Assert.Equal("> 1\r\n1\r\n> 23", Window.TextView.TextBuffer.CurrentSnapshot.GetText()); VerifyClipboardData(null, null, null); // Cut() with selection in active prompt, no-op selection.Clear(); var start = caret.MoveToNextCaretPosition().VirtualBufferPosition; caret.MoveToNextCaretPosition(); var end = caret.MoveToNextCaretPosition().VirtualBufferPosition; AssertCaretVirtualPosition(2, 2); selection.Select(start, end); Task.Run(() => Window.Operations.Cut()).PumpingWait(); Assert.Equal("> 1\r\n1\r\n> 23", Window.TextView.TextBuffer.CurrentSnapshot.GetText()); VerifyClipboardData(null, null, null); // Cut() with selection overlaps with editable buffer, // Cut editable content and move caret to closest editable location selection.Clear(); caret.MoveToPreviousCaretPosition(); start = caret.MoveToPreviousCaretPosition().VirtualBufferPosition; caret.MoveToNextCaretPosition(); caret.MoveToNextCaretPosition(); end = caret.MoveToNextCaretPosition().VirtualBufferPosition; AssertCaretVirtualPosition(2, 3); selection.Select(start, end); Task.Run(() => Window.Operations.Cut()).PumpingWait(); Assert.Equal("> 1\r\n1\r\n> 3", Window.TextView.TextBuffer.CurrentSnapshot.GetText()); AssertCaretVirtualPosition(2, 2); VerifyClipboardData("2", expectedRtf: null, expectedRepl: null); } [Fact] public void PasteWithOutSelectionInReadOnlyArea() { Submit( @"1", @"1 "); Window.InsertCode("2"); var caret = Window.TextView.Caret; Clipboard.Clear(); Window.Operations.Home(true); Window.Operations.Copy(); VerifyClipboardData("2", @"\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue0;\red255\green255\blue255;}\f0 \fs24 \cf1 \cb2 \highlight2 2", @"[{""content"":""2"",""kind"":2}]"); // Paste() with caret in readonly area, no-op Window.TextView.Selection.Clear(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); AssertCaretVirtualPosition(1, 1); Task.Run(() => Window.Operations.Paste()).PumpingWait(); Assert.Equal("> 1\r\n1\r\n> 2", Window.TextView.TextBuffer.CurrentSnapshot.GetText()); AssertCaretVirtualPosition(1, 1); // Paste() with caret in active prompt caret.MoveToNextCaretPosition(); AssertCaretVirtualPosition(2, 0); Task.Run(() => Window.Operations.Paste()).PumpingWait(); Assert.Equal("> 1\r\n1\r\n> 22", Window.TextView.TextBuffer.CurrentSnapshot.GetText()); AssertCaretVirtualPosition(2, 3); } [Fact] public void PasteWithSelectionInReadonlyArea() { Submit( @"1", @"1 "); Window.InsertCode("23"); var caret = Window.TextView.Caret; var selection = Window.TextView.Selection; Clipboard.Clear(); Window.Operations.Home(true); Window.Operations.Copy(); VerifyClipboardData("23", @"\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue0;\red255\green255\blue255;}\f0 \fs24 \cf1 \cb2 \highlight2 23", @"[{""content"":""23"",""kind"":2}]"); // Paste() with selection in readonly area, no-op selection.Clear(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); caret.MoveToPreviousCaretPosition(); AssertCaretVirtualPosition(1, 1); Window.Operations.SelectAll(); Task.Run(() => Window.Operations.Paste()).PumpingWait(); Assert.Equal("> 1\r\n1\r\n> 23", Window.TextView.TextBuffer.CurrentSnapshot.GetText()); // Paste() with selection in active prompt, no-op selection.Clear(); var start = caret.MoveToNextCaretPosition().VirtualBufferPosition; caret.MoveToNextCaretPosition(); var end = caret.MoveToNextCaretPosition().VirtualBufferPosition; AssertCaretVirtualPosition(2, 2); selection.Select(start, end); Task.Run(() => Window.Operations.Paste()).PumpingWait(); Assert.Equal("> 1\r\n1\r\n> 23", Window.TextView.TextBuffer.CurrentSnapshot.GetText()); // Paste() with selection overlaps with editable buffer, // Cut editable content, move caret to closest editable location and insert text selection.Clear(); caret.MoveToPreviousCaretPosition(); start = caret.MoveToPreviousCaretPosition().VirtualBufferPosition; caret.MoveToNextCaretPosition(); caret.MoveToNextCaretPosition(); end = caret.MoveToNextCaretPosition().VirtualBufferPosition; AssertCaretVirtualPosition(2, 3); selection.Select(start, end); Task.Run(() => Window.Operations.Paste()).PumpingWait(); Assert.Equal("> 1\r\n1\r\n> 233", Window.TextView.TextBuffer.CurrentSnapshot.GetText()); AssertCaretVirtualPosition(2, 4); } private void Submit(string submission, string output) { Task.Run(() => Window.SubmitAsync(new[] { submission })).PumpingWait(); // TestInteractiveEngine.ExecuteCodeAsync() simply returns // success rather than executing the submission, so add the // expected output to the output buffer. var buffer = Window.OutputBuffer; using (var edit = buffer.CreateEdit()) { edit.Replace(buffer.CurrentSnapshot.Length, 0, output); edit.Apply(); } } private static void VerifyClipboardData(string expectedText, string expectedRtf, string expectedRepl) { var data = Clipboard.GetDataObject(); Assert.Equal(expectedText, data.GetData(DataFormats.StringFormat)); Assert.Equal(expectedText, data.GetData(DataFormats.Text)); Assert.Equal(expectedText, data.GetData(DataFormats.UnicodeText)); Assert.Equal(expectedRepl, (string)data.GetData(InteractiveWindow.ClipboardFormat)); var actualRtf = (string)data.GetData(DataFormats.Rtf); if (expectedRtf == null) { Assert.Null(actualRtf); } else { Assert.True(actualRtf.StartsWith(@"{\rtf")); Assert.True(actualRtf.EndsWith(expectedRtf + "}")); } } private struct TextChange { internal readonly int Start; internal readonly int Length; internal readonly string Text; internal TextChange(int start, int length, string text) { Start = start; Length = length; Text = text; } } private static ITextSnapshot ApplyChanges(ITextBuffer buffer, params TextChange[] changes) { using (var edit = buffer.CreateEdit()) { foreach (var change in changes) { edit.Replace(change.Start, change.Length, change.Text); } return edit.Apply(); } } } internal static class OperationsExtensions { internal static void Copy(this IInteractiveWindowOperations operations) { ((IInteractiveWindowOperations2)operations).Copy(); } } }
// 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.Collections.Generic; using System.Text; // TPL namespaces using System.Threading; using System.Threading.Tasks; using System.Diagnostics; using System.Linq; using System.Reflection; namespace System.Threading.Tasks.Tests { public static class TaskRtTests { [Fact] [OuterLoop] public static void RunRunTests() { // // Test that AttachedToParent is ignored in Task.Run delegate // { Task tInner = null; // Test Run(Action) Task t1 = Task.Run(() => { tInner = new Task(() => { }, TaskCreationOptions.AttachedToParent); }); Debug.WriteLine("RunRunTests - AttachToParentIgnored: -- Waiting on outer Task. If we hang, that's a failure"); t1.Wait(); tInner.Start(); tInner.Wait(); // Test Run(Func<int>) Task<int> f1 = Task.Run(() => { tInner = new Task(() => { }, TaskCreationOptions.AttachedToParent); return 42; }); Debug.WriteLine("RunRunTests - AttachToParentIgnored: -- Waiting on outer Task<int>. If we hang, that's a failure"); f1.Wait(); tInner.Start(); tInner.Wait(); // Test Run(Func<Task>) Task t2 = Task.Run(() => { tInner = new Task(() => { }, TaskCreationOptions.AttachedToParent); Task returnTask = Task.Factory.StartNew(() => { }); return returnTask; }); Debug.WriteLine("RunRunTests - AttachToParentIgnored: -- Waiting on outer Task (unwrap-style). If we hang, that's a failure"); t2.Wait(); tInner.Start(); tInner.Wait(); Task<int> fInner = null; // Test Run(Func<Task<int>>) Task<int> f2 = Task.Run(() => { // Make sure AttachedToParent is ignored for futures as well as tasks fInner = new Task<int>(() => { return 42; }, TaskCreationOptions.AttachedToParent); Task<int> returnTask = Task<int>.Factory.StartNew(() => 11); return returnTask; }); Debug.WriteLine("RunRunTests - AttachToParentIgnored: Waiting on outer Task<int> (unwrap-style). If we hang, that's a failure"); f2.Wait(); fInner.Start(); fInner.Wait(); } // // Test basic functionality w/o cancellation token // int count = 0; Task task1 = Task.Run(() => { count = 1; }); Debug.WriteLine("RunRunTests: waiting for a task. If we hang, something went wrong."); task1.Wait(); Assert.True(count == 1, " > FAILED. Task completed but did not run."); Assert.True(task1.Status == TaskStatus.RanToCompletion, " > FAILED. Task did not end in RanToCompletion state."); Task<int> future1 = Task.Run(() => { return 7; }); Debug.WriteLine("RunRunTests - Basic w/o CT: waiting for a future. If we hang, something went wrong."); future1.Wait(); Assert.True(future1.Result == 7, " > FAILED. Future completed but did not run."); Assert.True(future1.Status == TaskStatus.RanToCompletion, " > FAILED. Future did not end in RanToCompletion state."); task1 = Task.Run(() => { return Task.Run(() => { count = 11; }); }); Debug.WriteLine("RunRunTests - Basic w/o CT: waiting for a task(unwrapped). If we hang, something went wrong."); task1.Wait(); Assert.True(count == 11, " > FAILED. Task(unwrapped) completed but did not run."); Assert.True(task1.Status == TaskStatus.RanToCompletion, " > FAILED. Task(unwrapped) did not end in RanToCompletion state."); future1 = Task.Run(() => { return Task.Run(() => 17); }); Debug.WriteLine("RunRunTests - Basic w/o CT: waiting for a future(unwrapped). If we hang, something went wrong."); future1.Wait(); Assert.True(future1.Result == 17, " > FAILED. Future(unwrapped) completed but did not run."); Assert.True(future1.Status == TaskStatus.RanToCompletion, " > FAILED. Future(unwrapped) did not end in RanToCompletion state."); // // Test basic functionality w/ uncancelled cancellation token // CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken token = cts.Token; Task task2 = Task.Run(() => { count = 21; }, token); Debug.WriteLine("RunRunTests: waiting for a task w/ uncanceled token. If we hang, something went wrong."); task2.Wait(); Assert.True(count == 21, " > FAILED. Task w/ uncanceled token completed but did not run."); Assert.True(task2.Status == TaskStatus.RanToCompletion, " > FAILED. Task w/ uncanceled token did not end in RanToCompletion state."); Task<int> future2 = Task.Run(() => 27, token); Debug.WriteLine("RunRunTests: waiting for a future w/ uncanceled token. If we hang, something went wrong."); future2.Wait(); Assert.True(future2.Result == 27, " > FAILED. Future w/ uncanceled token completed but did not run."); Assert.True(future2.Status == TaskStatus.RanToCompletion, " > FAILED. Future w/ uncanceled token did not end in RanToCompletion state."); task2 = Task.Run(() => { return Task.Run(() => { count = 31; }); }, token); Debug.WriteLine("RunRunTests: waiting for a task(unwrapped) w/ uncanceled token. If we hang, something went wrong."); task2.Wait(); Assert.True(count == 31, " > FAILED. Task(unwrapped) w/ uncanceled token completed but did not run."); Assert.True(task2.Status == TaskStatus.RanToCompletion, " > FAILED. Task(unwrapped) w/ uncanceled token did not end in RanToCompletion state."); future2 = Task.Run(() => Task.Run(() => 37), token); Debug.WriteLine("RunRunTests: waiting for a future(unwrapped) w/ uncanceled token. If we hang, something went wrong."); future2.Wait(); Assert.True(future2.Result == 37, " > FAILED. Future(unwrapped) w/ uncanceled token completed but did not run."); Assert.True(future2.Status == TaskStatus.RanToCompletion, " > FAILED. Future(unwrapped) w/ uncanceled token did not end in RanToCompletion state."); } [Fact] [OuterLoop] public static void RunRunTests_Cancellation_Negative() { CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken token = cts.Token; int count = 0; // // Test that the right thing is done with a canceled cancellation token // cts.Cancel(); Task task3 = Task.Run(() => { count = 41; }, token); Debug.WriteLine("RunRunTests: waiting for a task w/ canceled token. If we hang, something went wrong."); Assert.Throws<AggregateException>( () => { task3.Wait(); }); Assert.False(count == 41, " > FAILED. Task w/ canceled token ran when it should not have."); Assert.True(task3.IsCanceled, " > FAILED. Task w/ canceled token should have ended in Canceled state"); Task future3 = Task.Run(() => { count = 47; return count; }, token); Debug.WriteLine("RunRunTests: waiting for a future w/ canceled token. If we hang, something went wrong."); Assert.Throws<AggregateException>( () => { future3.Wait(); }); Assert.False(count == 47, " > FAILED. Future w/ canceled token ran when it should not have."); Assert.True(future3.IsCanceled, " > FAILED. Future w/ canceled token should have ended in Canceled state"); task3 = Task.Run(() => { return Task.Run(() => { count = 51; }); }, token); Debug.WriteLine("RunRunTests: waiting for a task(unwrapped) w/ canceled token. If we hang, something went wrong."); Assert.Throws<AggregateException>( () => { task3.Wait(); }); Assert.False(count == 51, " > FAILED. Task(unwrapped) w/ canceled token ran when it should not have."); Assert.True(task3.IsCanceled, " > FAILED. Task(unwrapped) w/ canceled token should have ended in Canceled state"); future3 = Task.Run(() => { return Task.Run(() => { count = 57; return count; }); }, token); Debug.WriteLine("RunRunTests: waiting for a future(unwrapped) w/ canceled token. If we hang, something went wrong."); Assert.Throws<AggregateException>( () => { future3.Wait(); }); Assert.False(count == 57, " > FAILED. Future(unwrapped) w/ canceled token ran when it should not have."); Assert.True(future3.IsCanceled, " > FAILED. Future(unwrapped) w/ canceled token should have ended in Canceled state"); } [Fact] public static void RunRunTests_FastPathTests() { CancellationTokenSource cts = new CancellationTokenSource(); cts.Cancel(); CancellationToken token = cts.Token; // // Test that "fast paths" operate correctly // { // Create some pre-completed Tasks Task alreadyCompletedTask = Task.Factory.StartNew(() => { }); alreadyCompletedTask.Wait(); Task alreadyFaultedTask = Task.Factory.StartNew(() => { throw new Exception("FAULTED!"); }); try { alreadyFaultedTask.Wait(); } catch { } Task alreadyCanceledTask = new Task(() => { }, cts.Token); // should result in cancellation try { alreadyCanceledTask.Wait(); } catch { } // Now run them through Task.Run Task fastPath1 = Task.Run(() => alreadyCompletedTask); fastPath1.Wait(); Assert.True(fastPath1.Status == TaskStatus.RanToCompletion, "RunRunTests: Expected proxy for already-ran-to-completion task to be in RanToCompletion status"); fastPath1 = Task.Run(() => alreadyFaultedTask); try { fastPath1.Wait(); Assert.True(false, string.Format("RunRunTests: > FAILURE: Expected proxy for already-faulted Task to throw on Wait()")); } catch { } Assert.True(fastPath1.Status == TaskStatus.Faulted, "Expected proxy for already-faulted task to be in Faulted status"); fastPath1 = Task.Run(() => alreadyCanceledTask); try { fastPath1.Wait(); Assert.True(false, string.Format("RunRunTests: > FAILURE: Expected proxy for already-canceled Task to throw on Wait()")); } catch { } Assert.True(fastPath1.Status == TaskStatus.Canceled, "RunRunTests: Expected proxy for already-canceled task to be in Canceled status"); } { // Create some pre-completed Task<int>s Task<int> alreadyCompletedTask = Task<int>.Factory.StartNew(() => 42); alreadyCompletedTask.Wait(); bool doIt = true; Task<int> alreadyFaultedTask = Task<int>.Factory.StartNew(() => { if (doIt) throw new Exception("FAULTED!"); return 42; }); try { alreadyFaultedTask.Wait(); } catch { } Task<int> alreadyCanceledTask = new Task<int>(() => 42, cts.Token); // should result in cancellation try { alreadyCanceledTask.Wait(); } catch { } // Now run them through Task.Run Task<int> fastPath1 = Task.Run(() => alreadyCompletedTask); fastPath1.Wait(); Assert.True(fastPath1.Status == TaskStatus.RanToCompletion, "RunRunTests: Expected proxy for already-ran-to-completion future to be in RanToCompletion status"); fastPath1 = Task.Run(() => alreadyFaultedTask); try { fastPath1.Wait(); Assert.True(false, string.Format("RunRunTests: > FAILURE: Expected proxy for already-faulted future to throw on Wait()")); } catch { } Assert.True(fastPath1.Status == TaskStatus.Faulted, "Expected proxy for already-faulted future to be in Faulted status"); fastPath1 = Task.Run(() => alreadyCanceledTask); try { fastPath1.Wait(); Assert.True(false, string.Format("RunRunTests: > FAILURE: Expected proxy for already-canceled future to throw on Wait()")); } catch { } Assert.True(fastPath1.Status == TaskStatus.Canceled, "RunRunTests: Expected proxy for already-canceled future to be in Canceled status"); } } [Fact] public static void RunRunTests_Unwrap_NegativeCases() { // // Test cancellation/exceptions behavior in the unwrap overloads // Action<UnwrappedScenario> TestUnwrapped = delegate (UnwrappedScenario scenario) { Debug.WriteLine("RunRunTests: testing Task unwrap (scenario={0})", scenario); CancellationTokenSource cts1 = new CancellationTokenSource(); CancellationToken token1 = cts1.Token; int something = 0; Task t1 = Task.Run(() => { if (scenario == UnwrappedScenario.ThrowExceptionInDelegate) throw new Exception("thrownInDelegate"); if (scenario == UnwrappedScenario.ThrowOceInDelegate) throw new OperationCanceledException("thrownInDelegate"); return Task.Run(() => { if (scenario == UnwrappedScenario.ThrowExceptionInTask) throw new Exception("thrownInTask"); if (scenario == UnwrappedScenario.ThrowTargetOceInTask) { cts1.Cancel(); throw new OperationCanceledException(token1); } if (scenario == UnwrappedScenario.ThrowOtherOceInTask) throw new OperationCanceledException(CancellationToken.None); something = 1; }, token1); }); bool cancellationExpected = (scenario == UnwrappedScenario.ThrowOceInDelegate) || (scenario == UnwrappedScenario.ThrowTargetOceInTask); bool exceptionExpected = (scenario == UnwrappedScenario.ThrowExceptionInDelegate) || (scenario == UnwrappedScenario.ThrowExceptionInTask) || (scenario == UnwrappedScenario.ThrowOtherOceInTask); try { t1.Wait(); Assert.False(cancellationExpected || exceptionExpected, "TaskRtTests.RunRunTests: Expected exception or cancellation"); Assert.True(something == 1, "TaskRtTests.RunRunTests: Task completed but apparently did not run"); } catch (AggregateException ae) { Assert.True(cancellationExpected || exceptionExpected, "TaskRtTests.RunRunTests: Didn't expect exception, got " + ae); } if (cancellationExpected) { Assert.True(t1.IsCanceled, "TaskRtTests.RunRunTests: Expected t1 to be Canceled, was " + t1.Status); } else if (exceptionExpected) { Assert.True(t1.IsFaulted, "TaskRtTests.RunRunTests: Expected t1 to be Faulted, was " + t1.Status); } else { Assert.True(t1.Status == TaskStatus.RanToCompletion, "TaskRtTests.RunRunTests: Expected t1 to be RanToCompletion, was " + t1.Status); } Debug.WriteLine("RunRunTests: -- testing Task<int> unwrap (scenario={0})", scenario); CancellationTokenSource cts2 = new CancellationTokenSource(); CancellationToken token2 = cts2.Token; Task<int> f1 = Task.Run(() => { if (scenario == UnwrappedScenario.ThrowExceptionInDelegate) throw new Exception("thrownInDelegate"); if (scenario == UnwrappedScenario.ThrowOceInDelegate) throw new OperationCanceledException("thrownInDelegate"); return Task.Run(() => { if (scenario == UnwrappedScenario.ThrowExceptionInTask) throw new Exception("thrownInTask"); if (scenario == UnwrappedScenario.ThrowTargetOceInTask) { cts2.Cancel(); throw new OperationCanceledException(token2); } if (scenario == UnwrappedScenario.ThrowOtherOceInTask) throw new OperationCanceledException(CancellationToken.None); return 10; }, token2); }); try { f1.Wait(); Assert.False(cancellationExpected || exceptionExpected, "RunRunTests: Expected exception or cancellation"); Assert.True(f1.Result == 10, "RunRunTests: Expected f1.Result to be 10, and it was " + f1.Result); } catch (AggregateException ae) { Assert.True(cancellationExpected || exceptionExpected, "RunRunTests: Didn't expect exception, got " + ae); } if (cancellationExpected) { Assert.True(f1.IsCanceled, "RunRunTests: Expected f1 to be Canceled, was " + f1.Status); } else if (exceptionExpected) { Assert.True(f1.IsFaulted, "RunRunTests: Expected f1 to be Faulted, was " + f1.Status); } else { Assert.True(f1.Status == TaskStatus.RanToCompletion, "RunRunTests: Expected f1 to be RanToCompletion, was " + f1.Status); } }; TestUnwrapped(UnwrappedScenario.CleanRun); // no exceptions or cancellation TestUnwrapped(UnwrappedScenario.ThrowExceptionInDelegate); // exception in delegate TestUnwrapped(UnwrappedScenario.ThrowOceInDelegate); // delegate throws OCE TestUnwrapped(UnwrappedScenario.ThrowExceptionInTask); // user-produced Task throws exception TestUnwrapped(UnwrappedScenario.ThrowTargetOceInTask); // user-produced Task throws OCE(target) TestUnwrapped(UnwrappedScenario.ThrowOtherOceInTask); // user-produced Task throws OCE(random) } [Fact] public static void RunFromResult() { // Test FromResult with value type { var results = new[] { -1, 0, 1, 1, 42, Int32.MaxValue, Int32.MinValue, 42, -42 }; // includes duplicate values to ensure that tasks from these aren't the same object Task<int>[] tasks = new Task<int>[results.Length]; for (int i = 0; i < results.Length; i++) tasks[i] = Task.FromResult(results[i]); // Make sure they've all completed for (int i = 0; i < tasks.Length; i++) Assert.True(tasks[i].IsCompleted, "TaskRtTests.RunFromResult: > FAILED: Task " + i + " should have already completed (value)"); // Make sure they all completed successfully for (int i = 0; i < tasks.Length; i++) Assert.True(tasks[i].Status == TaskStatus.RanToCompletion, "TaskRtTests.RunFromResult: > FAILED: Task " + i + " should have already completed successfully (value)"); // Make sure no two are the same instance for (int i = 0; i < tasks.Length; i++) { for (int j = i + 1; j < tasks.Length; j++) { Assert.False(tasks[i] == tasks[j], "TaskRtTests.RunFromResult: > FAILED: " + i + " and " + j + " created tasks should not be equal (value)"); } } // Make sure they all have the correct results for (int i = 0; i < tasks.Length; i++) Assert.True(tasks[i].Result == results[i], "TaskRtTests.RunFromResult: > FAILED: Task " + i + " had the result " + tasks[i].Result + " but should have had " + results[i] + " (value)"); } // Test FromResult with reference type { var results = new[] { new object(), null, new object(), null, new object() }; // includes duplicate values to ensure that tasks from these aren't the same object Task<Object>[] tasks = new Task<Object>[results.Length]; for (int i = 0; i < results.Length; i++) tasks[i] = Task.FromResult(results[i]); // Make sure they've all completed for (int i = 0; i < tasks.Length; i++) Assert.True(tasks[i].IsCompleted, "TaskRtTests.RunFromResult: > FAILED: Task " + i + " should have already completed (ref)"); // Make sure they all completed successfully for (int i = 0; i < tasks.Length; i++) Assert.True(tasks[i].Status == TaskStatus.RanToCompletion, "TaskRtTests.RunFromResult: > FAILED: Task " + i + " should have already completed successfully (ref)"); // Make sure no two are the same instance for (int i = 0; i < tasks.Length; i++) { for (int j = i + 1; j < tasks.Length; j++) { Assert.False(tasks[i] == tasks[j], "TaskRtTests.RunFromResult: > FAILED: " + i + " and " + j + " created tasks should not be equal (ref)"); } } // Make sure they all have the correct results for (int i = 0; i < tasks.Length; i++) Assert.True(tasks[i].Result == results[i], "TaskRtTests.RunFromResult: > FAILED: Task " + i + " had the wrong result (ref)"); } // Test FromException { var exceptions = new Exception[] { new InvalidOperationException(), new OperationCanceledException(), new Exception(), new Exception() }; // includes duplicate values to ensure that tasks from these aren't the same object var tasks = exceptions.Select(e => Task.FromException<int>(e)).ToArray(); // Make sure they've all completed for (int i = 0; i < tasks.Length; i++) Assert.True(tasks[i].IsCompleted, "Task " + i + " should have already completed"); // Make sure they all completed with an error for (int i = 0; i < tasks.Length; i++) Assert.True(tasks[i].Status == TaskStatus.Faulted, " > FAILED: Task " + i + " should have already faulted"); // Make sure no two are the same instance for (int i = 0; i < tasks.Length; i++) { for (int j = i + 1; j < tasks.Length; j++) { Assert.True(tasks[i] != tasks[j], " > FAILED: " + i + " and " + j + " created tasks should not be equal"); } } // Make sure they all have the correct exceptions for (int i = 0; i < tasks.Length; i++) { Assert.NotNull(tasks[i].Exception); Assert.Equal(1, tasks[i].Exception.InnerExceptions.Count); Assert.Equal(exceptions[i], tasks[i].Exception.InnerException); } // Make sure we handle invalid exceptions correctly Assert.Throws<ArgumentNullException>(() => { Task.FromException<int>(null); }); // Make sure we throw from waiting on a faulted task Assert.Throws<AggregateException>(() => { var result = Task.FromException<object>(new InvalidOperationException()).Result; }); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Uses reflection to access internal fields of the Task class.")] public static void RunFromResult_FaultedTask() { // Make sure faulted tasks are actually faulted. We have little choice for this test but to use reflection, // as the harness will crash by throwing from the unobserved event if a task goes unhandled (everywhere // other than here it's a bad thing for an exception to go unobserved) var faultedTask = Task.FromException<object>(new InvalidOperationException("uh oh")); object holderObject = null; FieldInfo isHandledField = null; var contingentPropertiesField = typeof(Task).GetField("m_contingentProperties", BindingFlags.NonPublic | BindingFlags.Instance); if (contingentPropertiesField != null) { var contingentProperties = contingentPropertiesField.GetValue(faultedTask); if (contingentProperties != null) { var exceptionsHolderField = contingentProperties.GetType().GetField("m_exceptionsHolder", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (exceptionsHolderField != null) { holderObject = exceptionsHolderField.GetValue(contingentProperties); if (holderObject != null) { isHandledField = holderObject.GetType().GetField("m_isHandled", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); } } } } Assert.NotNull(holderObject); Assert.NotNull(isHandledField); Assert.False((bool)isHandledField.GetValue(holderObject), "Expected FromException task to be unobserved before accessing Exception"); var ignored = faultedTask.Exception; Assert.True((bool)isHandledField.GetValue(holderObject), "Expected FromException task to be observed after accessing Exception"); } [Fact] public static void RunDelayTests() { // // Test basic functionality // CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken token = cts.Token; // These should all complete quickly, with RAN_TO_COMPLETION status. Task task1 = Task.Delay(0); Task task2 = Task.Delay(new TimeSpan(0)); Task task3 = Task.Delay(0, token); Task task4 = Task.Delay(new TimeSpan(0), token); Debug.WriteLine("RunDelayTests: > Waiting for 0-delayed uncanceled tasks to complete. If we hang, something went wrong."); try { Task.WaitAll(task1, task2, task3, task4); } catch (Exception e) { Assert.True(false, string.Format("RunDelayTests: > FAILED. Unexpected exception on WaitAll(simple tasks): {0}", e)); } Assert.True(task1.Status == TaskStatus.RanToCompletion, " > FAILED. Expected Delay(0) to run to completion"); Assert.True(task2.Status == TaskStatus.RanToCompletion, " > FAILED. Expected Delay(TimeSpan(0)) to run to completion"); Assert.True(task3.Status == TaskStatus.RanToCompletion, " > FAILED. Expected Delay(0,uncanceledToken) to run to completion"); Assert.True(task4.Status == TaskStatus.RanToCompletion, " > FAILED. Expected Delay(TimeSpan(0),uncanceledToken) to run to completion"); // This should take some time Task task7 = Task.Delay(10000); Assert.False(task7.IsCompleted, "RunDelayTests: > FAILED. Delay(10000) appears to have completed too soon(1)."); Task t2 = Task.Delay(10); Assert.False(task7.IsCompleted, "RunDelayTests: > FAILED. Delay(10000) appears to have completed too soon(2)."); } [Fact] public static void RunDelayTests_NegativeCases() { CancellationTokenSource disposedCTS = new CancellationTokenSource(); CancellationToken disposedToken = disposedCTS.Token; disposedCTS.Dispose(); // // Test for exceptions // Assert.Throws<ArgumentOutOfRangeException>( () => { Task.Delay(-2); }); Assert.Throws<ArgumentOutOfRangeException>( () => { Task.Delay(new TimeSpan(1000, 0, 0, 0)); }); CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken token = cts.Token; cts.Cancel(); // These should complete quickly, in Canceled status Task task5 = Task.Delay(0, token); Task task6 = Task.Delay(new TimeSpan(0), token); Debug.WriteLine("RunDelayTests: > Waiting for 0-delayed canceled tasks to complete. If we hang, something went wrong."); try { Task.WaitAll(task5, task6); } catch { } Assert.True(task5.Status == TaskStatus.Canceled, "RunDelayTests: > FAILED. Expected Delay(0,canceledToken) to end up Canceled"); Assert.True(task6.Status == TaskStatus.Canceled, "RunDelayTests: > FAILED. Expected Delay(TimeSpan(0),canceledToken) to end up Canceled"); // Cancellation token on two tasks and waiting on a task a second time. CancellationTokenSource cts2 = new CancellationTokenSource(); Task task8 = Task.Delay(-1, cts2.Token); Task task9 = Task.Delay(new TimeSpan(1, 0, 0, 0), cts2.Token); Task.Factory.StartNew(() => { cts2.Cancel(); }); Debug.WriteLine("RunDelayTests: > Waiting for infinite-delayed, eventually-canceled tasks to complete. If we hang, something went wrong."); try { Task.WaitAll(task8, task9); } catch { } Assert.True(task8.IsCanceled, "RunDelayTests: > FAILED. Expected Delay(-1, token) to end up Canceled."); Assert.True(task9.IsCanceled, "RunDelayTests: > FAILED. Expected Delay(TimeSpan(1,0,0,0), token) to end up Canceled."); try { task8.Wait(); } catch (AggregateException ae) { Assert.True( ae.InnerException is OperationCanceledException && ((OperationCanceledException)ae.InnerException).CancellationToken == cts2.Token, "RunDelayTests: > FAILED. Expected resulting OCE to contain canceled token."); } } // Test that exceptions are properly wrapped when thrown in various scenarios. // Make sure that "indirect" logic does not add superfluous exception wrapping. [Fact] public static void RunExceptionWrappingTest() { Action throwException = delegate { throw new InvalidOperationException(); }; // // // Test Monadic ContinueWith() // // Action<Task, string> mcwExceptionChecker = delegate (Task mcwTask, string scenario) { try { mcwTask.Wait(); Assert.True(false, string.Format("RunExceptionWrappingTest: > FAILED. Wait-on-continuation did not throw for {0}", scenario)); } catch (Exception e) { int levels = NestedLevels(e); if (levels != 2) { Assert.True(false, string.Format("RunExceptionWrappingTest: > FAILED. Exception had {0} levels instead of 2 for {1}.", levels, scenario)); } } }; // Test mcw off of Task Task t = Task.Factory.StartNew(delegate { }); // Throw in the returned future Task<int> mcw1 = t.ContinueWith(delegate (Task antecedent) { Task<int> inner = Task<int>.Factory.StartNew(delegate { throw new InvalidOperationException(); }); return inner; }).Unwrap(); mcwExceptionChecker(mcw1, "Task antecedent, throw in ContinuationFunction"); // Throw in the continuationFunction Task<int> mcw2 = t.ContinueWith(delegate (Task antecedent) { throwException(); Task<int> inner = Task<int>.Factory.StartNew(delegate { return 0; }); return inner; }).Unwrap(); mcwExceptionChecker(mcw2, "Task antecedent, throw in returned Future"); // Test mcw off of future Task<int> f = Task<int>.Factory.StartNew(delegate { return 0; }); // Throw in the returned future mcw1 = f.ContinueWith(delegate (Task<int> antecedent) { Task<int> inner = Task<int>.Factory.StartNew(delegate { throw new InvalidOperationException(); }); return inner; }).Unwrap(); mcwExceptionChecker(mcw1, "Future antecedent, throw in ContinuationFunction"); // Throw in the continuationFunction mcw2 = f.ContinueWith(delegate (Task<int> antecedent) { throwException(); Task<int> inner = Task<int>.Factory.StartNew(delegate { return 0; }); return inner; }).Unwrap(); mcwExceptionChecker(mcw2, "Future antecedent, throw in returned Future"); // // // Test FromAsync() // // // Used to test APM-related functionality FakeAsyncClass fac = new FakeAsyncClass(); // Common logic for checking exception nesting Action<Task, string> AsyncExceptionChecker = delegate (Task _asyncTask, string msg) { try { _asyncTask.Wait(); Assert.True(false, string.Format("RunExceptionWrappingTest APM-Related Funct: > FAILED. {0} did not throw exception.", msg)); } catch (Exception e) { int levels = NestedLevels(e); if (levels != 2) { Assert.True(false, string.Format("RunExceptionWrappingTest APM-Related Funct: > FAILED. {0} exception had {1} levels instead of 2", msg, levels)); } } }; // Try Task.FromAsync(iar,...) Task asyncTask = Task.Factory.FromAsync(fac.StartWrite("1234567890", null, null), delegate (IAsyncResult iar) { throw new InvalidOperationException(); }); AsyncExceptionChecker(asyncTask, "Task-based FromAsync(iar, ...)"); // Try Task.FromAsync(beginMethod, endMethod, ...) asyncTask = Task.Factory.FromAsync(fac.StartWrite, delegate (IAsyncResult iar) { throw new InvalidOperationException(); }, "1234567890", null); AsyncExceptionChecker(asyncTask, "Task-based FromAsync(beginMethod, ...)"); // Try Task<string>.Factory.FromAsync(iar,...) Task<string> asyncFuture = Task<string>.Factory.FromAsync(fac.StartRead(10, null, null), delegate (IAsyncResult iar) { throwException(); return fac.EndRead(iar); }); AsyncExceptionChecker(asyncFuture, "Future-based FromAsync(iar, ...)"); asyncFuture = Task<string>.Factory.FromAsync(fac.StartRead, delegate (IAsyncResult iar) { throwException(); return fac.EndRead(iar); }, 10, null); AsyncExceptionChecker(asyncFuture, "Future-based FromAsync(beginMethod, ...)"); } [Fact] public static void RunHideSchedulerTests() { TaskScheduler[] schedules = new TaskScheduler[2]; schedules[0] = TaskScheduler.Default; for (int i = 0; i < schedules.Length; i++) { bool useCustomTs = (i == 1); TaskScheduler outerTs = schedules[i]; // useCustomTs ? customTs : TaskScheduler.Default; // If we are running CoreCLR, then schedules[1] = null, and we should continue in this case. if (i == 1 && outerTs == null) continue; for (int j = 0; j < 2; j++) { bool hideScheduler = (j == 0); TaskCreationOptions creationOptions = hideScheduler ? TaskCreationOptions.HideScheduler : TaskCreationOptions.None; TaskContinuationOptions continuationOptions = hideScheduler ? TaskContinuationOptions.HideScheduler : TaskContinuationOptions.None; TaskScheduler expectedInnerTs = hideScheduler ? TaskScheduler.Default : outerTs; Action<string> commonAction = delegate (string setting) { Assert.Equal(TaskScheduler.Current, expectedInnerTs); // And just for completeness, make sure that inner tasks are started on the correct scheduler TaskScheduler tsInner1 = null, tsInner2 = null; Task tInner = Task.Factory.StartNew(() => { tsInner1 = TaskScheduler.Current; }); Task continuation = tInner.ContinueWith(_ => { tsInner2 = TaskScheduler.Current; }); Task.WaitAll(tInner, continuation); Assert.Equal(tsInner1, expectedInnerTs); Assert.Equal(tsInner2, expectedInnerTs); }; Task outerTask = Task.Factory.StartNew(() => { commonAction("task"); }, CancellationToken.None, creationOptions, outerTs); Task outerContinuation = outerTask.ContinueWith(_ => { commonAction("continuation"); }, CancellationToken.None, continuationOptions, outerTs); Task.WaitAll(outerTask, outerContinuation); // Check that the option was internalized by the task/continuation Assert.True(hideScheduler == ((outerTask.CreationOptions & TaskCreationOptions.HideScheduler) != 0), "RunHideSchedulerTests: FAILED. CreationOptions mismatch on outerTask"); Assert.True(hideScheduler == ((outerContinuation.CreationOptions & TaskCreationOptions.HideScheduler) != 0), "RunHideSchedulerTests: FAILED. CreationOptions mismatch on outerContinuation"); } // end j-loop, for hideScheduler setting } // ending i-loop, for customTs setting } [Fact] public static void RunHideSchedulerTests_Negative() { // Test that HideScheduler is flagged as an illegal option when creating a TCS Assert.Throws<ArgumentOutOfRangeException>( () => { new TaskCompletionSource<int>(TaskCreationOptions.HideScheduler); }); } [Fact] public static void RunDenyChildAttachTests() { // StartNew, Task and Future Task i1 = null; Task t1 = Task.Factory.StartNew(() => { i1 = new Task(() => { }, TaskCreationOptions.AttachedToParent); }, TaskCreationOptions.DenyChildAttach); Task i2 = null; Task t2 = Task<int>.Factory.StartNew(() => { i2 = new Task(() => { }, TaskCreationOptions.AttachedToParent); return 42; }, TaskCreationOptions.DenyChildAttach); // ctor/Start, Task and Future Task i3 = null; Task t3 = new Task(() => { i3 = new Task(() => { }, TaskCreationOptions.AttachedToParent); }, TaskCreationOptions.DenyChildAttach); t3.Start(); Task i4 = null; Task t4 = new Task<int>(() => { i4 = new Task(() => { }, TaskCreationOptions.AttachedToParent); return 42; }, TaskCreationOptions.DenyChildAttach); t4.Start(); // continuations, Task and Future Task i5 = null; Task t5 = t3.ContinueWith(_ => { i5 = new Task(() => { }, TaskCreationOptions.AttachedToParent); }, TaskContinuationOptions.DenyChildAttach); Task i6 = null; Task t6 = t4.ContinueWith<int>(_ => { i6 = new Task(() => { }, TaskCreationOptions.AttachedToParent); return 42; }, TaskContinuationOptions.DenyChildAttach); // If DenyChildAttach doesn't work in any of the cases, then the associated "parent" // task will hang waiting for its child. Debug.WriteLine("RunDenyChildAttachTests: Waiting on 'parents' ... if we hang, something went wrong."); Task.WaitAll(t1, t2, t3, t4, t5, t6); // And clean up. i1.Start(); i1.Wait(); i2.Start(); i2.Wait(); i3.Start(); i3.Wait(); i4.Start(); i4.Wait(); i5.Start(); i5.Wait(); i6.Start(); i6.Wait(); } [Fact] public static void RunBasicFutureTest_Negative() { Task<int> future = new Task<int>(() => 1); Assert.ThrowsAsync<ArgumentNullException>( () => future.ContinueWith((Action<Task<int>, Object>)null, null, CancellationToken.None)); Assert.ThrowsAsync<ArgumentNullException>( () => future.ContinueWith((Action<Task<int>, Object>)null, null, TaskContinuationOptions.None)); Assert.ThrowsAsync<ArgumentNullException>( () => future.ContinueWith((Action<Task<int>, Object>)null, null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default)); Assert.ThrowsAsync<ArgumentNullException>( () => future.ContinueWith((t, s) => { }, null, CancellationToken.None, TaskContinuationOptions.None, null)); Assert.ThrowsAsync<ArgumentNullException>( () => future.ContinueWith<int>((Func<Task<int>, Object, int>)null, null, CancellationToken.None)); Assert.ThrowsAsync<ArgumentNullException>( () => future.ContinueWith<int>((Func<Task<int>, Object, int>)null, null, TaskContinuationOptions.None)); Assert.ThrowsAsync<ArgumentNullException>( () => future.ContinueWith<int>((Func<Task<int>, Object, int>)null, null, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default)); Assert.ThrowsAsync<ArgumentNullException>( () => future.ContinueWith<int>((t, s) => 2, null, CancellationToken.None, TaskContinuationOptions.None, null)); } #region Helper Methods / Classes private static int NestedLevels(Exception e) { int levels = 0; while (e != null) { levels++; AggregateException ae = e as AggregateException; if (ae != null) { e = ae.InnerExceptions[0]; } else break; } return levels; } internal enum UnwrappedScenario { CleanRun = 0, ThrowExceptionInDelegate = 1, ThrowOceInDelegate = 2, ThrowExceptionInTask = 3, ThrowTargetOceInTask = 4, ThrowOtherOceInTask = 5 }; // This class is used in testing APM Factory tests. private class FakeAsyncClass { private List<char> _list = new List<char>(); public override string ToString() { StringBuilder sb = new StringBuilder(); lock (_list) { for (int i = 0; i < _list.Count; i++) sb.Append(_list[i]); } return sb.ToString(); } // Silly use of Write, but I wanted to test no-argument StartXXX handling. public IAsyncResult StartWrite(AsyncCallback cb, object o) { return StartWrite("", 0, 0, cb, o); } public IAsyncResult StartWrite(string s, AsyncCallback cb, object o) { return StartWrite(s, 0, s.Length, cb, o); } public IAsyncResult StartWrite(string s, int length, AsyncCallback cb, object o) { return StartWrite(s, 0, length, cb, o); } public IAsyncResult StartWrite(string s, int offset, int length, AsyncCallback cb, object o) { myAsyncResult mar = new myAsyncResult(cb, o); // Allow for exception throwing to test our handling of that. if (s == null) throw new ArgumentNullException(nameof(s)); Task t = Task.Factory.StartNew(delegate { //Thread.Sleep(100); try { lock (_list) { for (int i = 0; i < length; i++) _list.Add(s[i + offset]); } mar.Signal(); } catch (Exception e) { mar.Signal(e); } }); return mar; } public void EndWrite(IAsyncResult iar) { myAsyncResult mar = iar as myAsyncResult; mar.Wait(); if (mar.IsFaulted) throw (mar.Exception); } public IAsyncResult StartRead(AsyncCallback cb, object o) { return StartRead(128 /*=maxbytes*/, null, 0, cb, o); } public IAsyncResult StartRead(int maxBytes, AsyncCallback cb, object o) { return StartRead(maxBytes, null, 0, cb, o); } public IAsyncResult StartRead(int maxBytes, char[] buf, AsyncCallback cb, object o) { return StartRead(maxBytes, buf, 0, cb, o); } public IAsyncResult StartRead(int maxBytes, char[] buf, int offset, AsyncCallback cb, object o) { myAsyncResult mar = new myAsyncResult(cb, o); // Allow for exception throwing to test our handling of that. if (maxBytes == -1) throw new ArgumentException("Value was not valid", nameof(maxBytes)); Task t = Task.Factory.StartNew(delegate { //Thread.Sleep(100); StringBuilder sb = new StringBuilder(); int bytesRead = 0; try { lock (_list) { while ((_list.Count > 0) && (bytesRead < maxBytes)) { sb.Append(_list[0]); if (buf != null) { buf[offset] = _list[0]; offset++; } _list.RemoveAt(0); bytesRead++; } } mar.SignalState(sb.ToString()); } catch (Exception e) { mar.Signal(e); } }); return mar; } public string EndRead(IAsyncResult iar) { myAsyncResult mar = iar as myAsyncResult; if (mar.IsFaulted) throw (mar.Exception); return (string)mar.AsyncState; } public void ResetStateTo(string s) { _list.Clear(); for (int i = 0; i < s.Length; i++) _list.Add(s[i]); } } // This is an internal class used for a concrete IAsyncResult in the APM Factory tests. private class myAsyncResult : IAsyncResult { private volatile int _isCompleted; private ManualResetEvent _asyncWaitHandle; private AsyncCallback _callback; private object _asyncState; private Exception _exception; public myAsyncResult(AsyncCallback cb, object o) { _isCompleted = 0; _asyncWaitHandle = new ManualResetEvent(false); _callback = cb; _asyncState = o; _exception = null; } public bool IsCompleted { get { return (_isCompleted == 1); } } public bool CompletedSynchronously { get { return false; } } public WaitHandle AsyncWaitHandle { get { return _asyncWaitHandle; } } public object AsyncState { get { return _asyncState; } } public void Signal() { _isCompleted = 1; _asyncWaitHandle.Set(); if (_callback != null) _callback(this); } public void Signal(Exception e) { _exception = e; Signal(); } public void SignalState(object o) { _asyncState = o; Signal(); } public void Wait() { _asyncWaitHandle.WaitOne(); if (_exception != null) throw (_exception); } public bool IsFaulted { get { return ((_isCompleted == 1) && (_exception != null)); } } public Exception Exception { get { return _exception; } } } #endregion } }
namespace PokerTell.PokerHand.Tests.Analyzation { using System.Linq; using Infrastructure; using Infrastructure.Enumerations.PokerHand; using NUnit.Framework; using PokerTell.PokerHand.Analyzation; using UnitTests; using UnitTests.Tools; public class SequenceStringConverterTests : TestWithLog { SequenceStringConverter _sut; [SetUp] public void _Init() { _sut = new SequenceStringConverter(); } [Test] public void Constructor_UsingApplicationPropertiesBetSizeKeys_InitializesStandardizedBetSizes() { _sut.StandardizedBetSizes.Count.ShouldBeEqualTo(ApplicationProperties.BetSizeKeys.Length); _sut.StandardizedBetSizes.First().ShouldBeEqualTo((int)(ApplicationProperties.BetSizeKeys.First() * 10)); _sut.StandardizedBetSizes.Last().ShouldBeEqualTo((int)(ApplicationProperties.BetSizeKeys.Last() * 10)); } [Test] public void Convert_NullString_ActionSequenceIsNonStandard() { _sut.Convert(null); _sut.ActionSequence.ShouldBeEqualTo(ActionSequences.NonStandard); } [Test] public void Convert_EmptyString_ActionSequenceIsNonStandard() { _sut.Convert(string.Empty); _sut.ActionSequence.ShouldBeEqualTo(ActionSequences.NonStandard); } [Test] public void Convert_EmptyString_BetSizeIndexIsZero() { _sut.Convert(string.Empty); _sut.BetSizeIndex.ShouldBeEqualTo(0); } [Test] public void Convert_X_ActionSequenceIsHeroX() { _sut.Convert("X"); _sut.ActionSequence.ShouldBeEqualTo(ActionSequences.HeroX); } [Test] public void Convert_X_BetSizeIndexIsZero() { _sut.Convert("X"); _sut.BetSizeIndex.ShouldBeEqualTo(0); } [Test] public void Convert_F_ActionSequenceIsHeroF() { _sut.Convert("F"); _sut.ActionSequence.ShouldBeEqualTo(ActionSequences.HeroF); } [Test] public void Convert_C_ActionSequenceIsHeroC() { _sut.Convert("C"); _sut.ActionSequence.ShouldBeEqualTo(ActionSequences.HeroC); } [Test] public void Convert_R_ActionSequenceIsHeroR() { _sut.Convert("R"); _sut.ActionSequence.ShouldBeEqualTo(ActionSequences.HeroR); } [Test] public void Convert_RF_ActionSequenceIsOppRHeroF() { _sut.Convert("RF"); _sut.ActionSequence.ShouldBeEqualTo(ActionSequences.OppRHeroF); } [Test] public void Convert_RC_ActionSequenceIsOppRHeroC() { _sut.Convert("RC"); _sut.ActionSequence.ShouldBeEqualTo(ActionSequences.OppRHeroC); } [Test] public void Convert_RR_ActionSequenceIsOppRHeroR() { _sut.Convert("RR"); _sut.ActionSequence.ShouldBeEqualTo(ActionSequences.OppRHeroR); } [Test] public void Convert_9_ActionSequenceIsHeroB() { _sut.Convert("9"); _sut.ActionSequence.ShouldBeEqualTo(ActionSequences.HeroB); } [Test] public void Convert_9_BetSizeIndexIsIndexOf9() { _sut.Convert("9"); _sut.BetSizeIndex.ShouldBeEqualTo(_sut.StandardizedBetSizes.IndexOf(9)); } [Test] public void Convert_15_BetSizeIndexIsIndexOf15() { _sut.Convert("15"); _sut.BetSizeIndex.ShouldBeEqualTo(_sut.StandardizedBetSizes.IndexOf(15)); } [Test] public void Convert_9F_ActionSequenceIsOppBHeroF() { _sut.Convert("9F"); _sut.ActionSequence.ShouldBeEqualTo(ActionSequences.OppBHeroF); } [Test] public void Convert_9F_BetSizeIndexIsIndexOf9() { _sut.Convert("9F"); _sut.BetSizeIndex.ShouldBeEqualTo(_sut.StandardizedBetSizes.IndexOf(9)); } [Test] public void Convert_15F_BetSizeIndexIsIndexOf15() { _sut.Convert("15F"); _sut.BetSizeIndex.ShouldBeEqualTo(_sut.StandardizedBetSizes.IndexOf(15)); } [Test] public void Convert_C9F_ActionSequenceIsNonStandard() { _sut.Convert("C9F"); _sut.ActionSequence.ShouldBeEqualTo(ActionSequences.NonStandard); } [Test] public void Convert_5C_ActionSequenceIsOppBHeroC() { _sut.Convert("5C"); _sut.ActionSequence.ShouldBeEqualTo(ActionSequences.OppBHeroC); } [Test] public void Convert_5C_BetSizeIndexIsIndexOf5() { _sut.Convert("5C"); _sut.BetSizeIndex.ShouldBeEqualTo(_sut.StandardizedBetSizes.IndexOf(5)); } [Test] public void Convert_15C_BetSizeIndexIsIndexOf15() { _sut.Convert("15C"); _sut.BetSizeIndex.ShouldBeEqualTo(_sut.StandardizedBetSizes.IndexOf(15)); } [Test] public void Convert_2R_ActionSequenceIsOppBHeroR() { _sut.Convert("2R"); _sut.ActionSequence.ShouldBeEqualTo(ActionSequences.OppBHeroR); } [Test] public void Convert_2R_BetSizeIndexIsIndexOf2() { _sut.Convert("2R"); _sut.BetSizeIndex.ShouldBeEqualTo(_sut.StandardizedBetSizes.IndexOf(2)); } [Test] public void Convert_15R_BetSizeIndexIsIndexOf15() { _sut.Convert("15R"); _sut.BetSizeIndex.ShouldBeEqualTo(_sut.StandardizedBetSizes.IndexOf(15)); } [Test] public void Convert_X9F_ActionSequenceIsHeroXOppBHeroF() { _sut.Convert("X9F"); _sut.ActionSequence.ShouldBeEqualTo(ActionSequences.HeroXOppBHeroF); } [Test] public void Convert_X9F_BetSizeIndexIsIndexOf9() { _sut.Convert("X9F"); _sut.BetSizeIndex.ShouldBeEqualTo(_sut.StandardizedBetSizes.IndexOf(9)); } [Test] public void Convert_X15F_BetSizeIndexIsIndexOf15() { _sut.Convert("X15F"); _sut.BetSizeIndex.ShouldBeEqualTo(_sut.StandardizedBetSizes.IndexOf(15)); } [Test] public void Convert_CX9F_ActionSequenceIsNonStandard() { _sut.Convert("CX9F"); _sut.ActionSequence.ShouldBeEqualTo(ActionSequences.NonStandard); } [Test] public void Convert_X5C_ActionSequenceIsHeroXOppBHeroC() { _sut.Convert("X5C"); _sut.ActionSequence.ShouldBeEqualTo(ActionSequences.HeroXOppBHeroC); } [Test] public void Convert_X5C_BetSizeIndexIsIndexOf5() { _sut.Convert("X5C"); _sut.BetSizeIndex.ShouldBeEqualTo(_sut.StandardizedBetSizes.IndexOf(5)); } [Test] public void Convert_X15C_BetSizeIndexIsIndexOf15() { _sut.Convert("X15C"); _sut.BetSizeIndex.ShouldBeEqualTo(_sut.StandardizedBetSizes.IndexOf(15)); } [Test] public void Convert_X2R_ActionSequenceIsHeroXOppBHeroR() { _sut.Convert("X2R"); _sut.ActionSequence.ShouldBeEqualTo(ActionSequences.HeroXOppBHeroR); } [Test] public void Convert_X2R_BetSizeIndexIsIndexOf2() { _sut.Convert("X2R"); _sut.BetSizeIndex.ShouldBeEqualTo(_sut.StandardizedBetSizes.IndexOf(2)); } [Test] public void Convert_X15R_BetSizeIndexIsIndexOf15() { _sut.Convert("X15R"); _sut.BetSizeIndex.ShouldBeEqualTo(_sut.StandardizedBetSizes.IndexOf(15)); } } }
using System; using System.Collections.Generic; using System.Reflection; using System.Threading.Tasks; using Plivo.Client; namespace Plivo.Resource.Conference { /// <summary> /// Conference interface. /// </summary> public class ConferenceInterface : ResourceInterface { /// <summary> /// Initializes a new instance of the <see cref="T:plivo.Resource.Conference.ConferenceInterface"/> class. /// </summary> /// <param name="client">Client.</param> public ConferenceInterface(HttpClient client) : base(client) { Uri = "Account/" + Client.GetAuthId() + "/Conference/"; } #region Get /// <summary> /// Get Conference with the specified name. /// </summary> /// <returns>The get.</returns> /// <param name="conferenceName">Name.</param> public Conference Get(string conferenceName) { return ExecuteWithExceptionUnwrap(() => { var conference = Task.Run(async () => await GetResource<Conference>(conferenceName,new Dictionary<string, object> () { {"is_voice_request", true} }).ConfigureAwait(false)).Result; conference.Interface = this; return conference; }); } /// <summary> /// Asynchronously Get Conference with the specified name. /// </summary> /// <returns>The get.</returns> /// <param name="conferenceName">Name.</param> public async Task<Conference> GetAsync(string conferenceName) { var conference = await GetResource<Conference>(conferenceName, new Dictionary<string, object> () { {"is_voice_request", true} }); conference.Interface = this; return conference; } #endregion #region List /// <summary> /// List Conferences. /// </summary> /// <returns>The list.</returns> public ConferenceListResponse List() { return ExecuteWithExceptionUnwrap(() => { return Task.Run(async () => await ListResources<ConferenceListResponse>(new Dictionary<string, object> () { {"is_voice_request", true} }).ConfigureAwait(false)).Result; }); } /// <summary> /// List Conferences. /// </summary> /// <returns>The list.</returns> public async Task<ConferenceListResponse> ListAsync() { return await ListResources<ConferenceListResponse>(new Dictionary<string, object> () { {"is_voice_request", true} }); } #endregion #region DeleteAll /// <summary> /// Deletes all. /// </summary> /// <returns>The all.</returns> public DeleteResponse<Conference> DeleteAll() { return ExecuteWithExceptionUnwrap(() => { var result = Task.Run(async () => await Client.Delete<DeleteResponse<Conference>>(Uri, new Dictionary<string, object> () { {"is_voice_request", true} }).ConfigureAwait(false)).Result; result.Object.StatusCode = result.StatusCode; return result.Object; }); } /// <summary> /// Asynchronously deletes all. /// </summary> /// <returns>The all.</returns> public async Task<DeleteResponse<Conference>> DeleteAllAsync() { var result = await Client.Delete<DeleteResponse<Conference>>(Uri, new Dictionary<string, object> () { {"is_voice_request", true} }); result.Object.StatusCode = result.StatusCode; return result.Object; } #endregion #region Delete /// <summary> /// Delete with the specified name. /// </summary> /// <returns>The delete.</returns> /// <param name="name">Name.</param> public DeleteResponse<Conference> Delete(string name) { return ExecuteWithExceptionUnwrap(() => { return Task.Run(async () => await DeleteResource<DeleteResponse<Conference>>(name,new Dictionary<string, object> () { {"is_voice_request", true} }).ConfigureAwait(false)).Result; }); } /// <summary> /// Asynchronously delete with the specified name. /// </summary> /// <returns>The delete.</returns> /// <param name="name">Name.</param> public async Task<DeleteResponse<Conference>> DeleteAsync(string name) { return await DeleteResource<DeleteResponse<Conference>>(name, new Dictionary<string, object> () { {"is_voice_request", true} }); } #endregion #region HangupMember /// <summary> /// Hangups the member. /// </summary> /// <returns>The member.</returns> /// <param name="conferenceName">Conference name.</param> /// <param name="memberId">Member identifier.</param> public ConferenceMemberActionResponse HangupMember( string conferenceName, string memberId) { return ExecuteWithExceptionUnwrap(() => { var result = Task.Run(async () => await Client.Delete<ConferenceMemberActionResponse>(Uri + conferenceName + "/Member/" + memberId + "/",new Dictionary<string, object> () { {"is_voice_request", true} }).ConfigureAwait(false)).Result; result.Object.StatusCode = result.StatusCode; return result.Object; }); } /// <summary> /// Asynchronously hangups the member. /// </summary> /// <returns>The member.</returns> /// <param name="conferenceName">Conference name.</param> /// <param name="memberId">Member identifier.</param> public async Task<ConferenceMemberActionResponse> HangupMemberAsync( string conferenceName, string memberId) { var result = await Client.Delete<ConferenceMemberActionResponse>(Uri + conferenceName + "/Member/" + memberId + "/", new Dictionary<string, object> () { {"is_voice_request", true} }); result.Object.StatusCode = result.StatusCode; return result.Object; } #endregion #region KickMember /// <summary> /// Kicks the member. /// </summary> /// <returns>The member.</returns> /// <param name="conferenceName">Conference name.</param> /// <param name="memberId">Member identifier.</param> public ConferenceMemberActionResponse KickMember( string conferenceName, string memberId) { return ExecuteWithExceptionUnwrap(() => { var result = Task.Run(async () => await Client.Update<ConferenceMemberActionResponse>(Uri + conferenceName + "/Member/" + memberId + "/Kick/",new Dictionary<string, object> () { {"is_voice_request", true} }).ConfigureAwait(false)).Result; result.Object.StatusCode = result.StatusCode; return result.Object; }); } /// <summary> /// Asynchronously kicks the member. /// </summary> /// <returns>The member.</returns> /// <param name="conferenceName">Conference name.</param> /// <param name="memberId">Member identifier.</param> public async Task<ConferenceMemberActionResponse> KickMemberAsync( string conferenceName, string memberId) { var result = await Client.Update<ConferenceMemberActionResponse>(Uri + conferenceName + "/Member/" + memberId + "/Kick/", new Dictionary<string, object> () { {"is_voice_request", true} }); result.Object.StatusCode = result.StatusCode; return result.Object; } #endregion #region MuteMember /// <summary> /// Mutes the member. /// </summary> /// <returns>The member.</returns> /// <param name="conferenceName">Conference name.</param> /// <param name="memberId">Member identifier.</param> public ConferenceMemberActionResponse MuteMember( string conferenceName, List<string> memberId) { return ExecuteWithExceptionUnwrap(() => { var result = Task.Run(async () => await Client.Update<ConferenceMemberActionResponse>(Uri + conferenceName + "/Member/" + string.Join(",", memberId) + "/Mute/", new Dictionary<string, object> () { {"is_voice_request", true} }).ConfigureAwait(false)).Result; result.Object.StatusCode = result.StatusCode; return result.Object; }); } /// <summary> /// Asynchronously mutes the member. /// </summary> /// <returns>The member.</returns> /// <param name="conferenceName">Conference name.</param> /// <param name="memberId">Member identifier.</param> public async Task<ConferenceMemberActionResponse> MuteMemberAsync( string conferenceName, List<string> memberId) { var result = await Client.Update<ConferenceMemberActionResponse>(Uri + conferenceName + "/Member/" + string.Join(",", memberId) + "/Mute/", new Dictionary<string, object> () { {"is_voice_request", true} }); result.Object.StatusCode = result.StatusCode; return result.Object; } #endregion #region UnmuteMember /// <summary> /// Unmutes the member. /// </summary> /// <param name="conferenceName">Conference name.</param> /// <param name="memberId">Member identifier.</param> public void UnmuteMember( string conferenceName, List<string> memberId) { ExecuteWithExceptionUnwrap(() => { Task.Run(async () => await Client.Delete<ConferenceMemberActionResponse>( Uri + conferenceName + "/Member/" + string.Join(",", memberId) + "/Mute/",new Dictionary<string, object> () { {"is_voice_request", true} }).ConfigureAwait(false)).Wait(); }); } /// <summary> /// Asynchronously unmutes the member. /// </summary> /// <param name="conferenceName">Conference name.</param> /// <param name="memberId">Member identifier.</param> public async Task UnmuteMemberAsync( string conferenceName, List<string> memberId) { await Client.Delete<ConferenceMemberActionResponse>( Uri + conferenceName + "/Member/" + string.Join(",", memberId) + "/Mute/", new Dictionary<string, object> () { {"is_voice_request", true} }); } #endregion #region PlayMember /// <summary> /// Plays audio to the member. /// </summary> /// <returns>The member.</returns> /// <param name="conferenceName">Conference name.</param> /// <param name="memberId">Member identifier.</param> /// <param name="url">URL.</param> public ConferenceMemberActionResponse PlayMember( string conferenceName, List<string> memberId, string url) { return ExecuteWithExceptionUnwrap(() => { var result = Task.Run(async () => await Client.Update<ConferenceMemberActionResponse>( Uri + conferenceName + "/Member/" + string.Join(",", memberId) + "/Play/", new Dictionary<string, object>() { { "url", url } , {"is_voice_request", true}} ).ConfigureAwait(false)).Result; result.Object.StatusCode = result.StatusCode; return result.Object; }); } /// <summary> /// Asynchronously plays audio to the member. /// </summary> /// <returns>The member.</returns> /// <param name="conferenceName">Conference name.</param> /// <param name="memberId">Member identifier.</param> /// <param name="url">URL.</param> public async Task<ConferenceMemberActionResponse> PlayMemberAsync( string conferenceName, List<string> memberId, string url) { var result = await Client.Update<ConferenceMemberActionResponse>( Uri + conferenceName + "/Member/" + string.Join(",", memberId) + "/Play/", new Dictionary<string, object>() { { "url", url }, {"is_voice_request", true} } ); result.Object.StatusCode = result.StatusCode; return result.Object; } #endregion #region StopPlayMember /// <summary> /// Stops playing audio to the member. /// </summary> /// <returns>The play member.</returns> /// <param name="conferenceName">Conference name.</param> /// <param name="memberId">Member identifier.</param> public ConferenceMemberActionResponse StopPlayMember( string conferenceName, List<string> memberId) { return ExecuteWithExceptionUnwrap(() => { var result = Task.Run(async () => await Client.Delete<ConferenceMemberActionResponse>( Uri + conferenceName + "/Member/" + string.Join(",", memberId) + "/Play/", new Dictionary<string, object> () { {"is_voice_request", true} } ).ConfigureAwait(false)).Result; result.Object.StatusCode = result.StatusCode; return result.Object; }); } /// <summary> /// Asynchronously stops playing audio to the member. /// </summary> /// <returns>The play member.</returns> /// <param name="conferenceName">Conference name.</param> /// <param name="memberId">Member identifier.</param> public async Task<ConferenceMemberActionResponse> StopPlayMemberAsync( string conferenceName, List<string> memberId) { var result = await Client.Delete<ConferenceMemberActionResponse>( Uri + conferenceName + "/Member/" + string.Join(",", memberId) + "/Play/", new Dictionary<string, object> () { {"is_voice_request", true} } ); result.Object.StatusCode = result.StatusCode; return result.Object; } #endregion #region SpeakMember /// <summary> /// Speaks text to the member. /// </summary> /// <returns>The member.</returns> /// <param name="conferenceName">Conference name.</param> /// <param name="memberId">Member identifier.</param> /// <param name="text">Text.</param> /// <param name="voice">Voice.</param> /// <param name="language">Language.</param> public ConferenceMemberActionResponse SpeakMember( string conferenceName, List<string> memberId, string text, string voice = null, string language = null) { var mandatoryParams = new List<string> { "" }; bool isVoiceRequest = true; var data = CreateData( mandatoryParams, new { text, voice, language, isVoiceRequest }); return ExecuteWithExceptionUnwrap(() => { var result = Task.Run(async () => await Client.Update<ConferenceMemberActionResponse>( Uri + conferenceName + "/Member/" + string.Join(",", memberId) + "/Speak/", data ).ConfigureAwait(false)).Result; result.Object.StatusCode = result.StatusCode; return result.Object; }); } /// <summary> /// Asynchronously speaks text to the member. /// </summary> /// <returns>The member.</returns> /// <param name="conferenceName">Conference name.</param> /// <param name="memberId">Member identifier.</param> /// <param name="text">Text.</param> /// <param name="voice">Voice.</param> /// <param name="language">Language.</param> public async Task<ConferenceMemberActionResponse> SpeakMemberAsync( string conferenceName, List<string> memberId, string text, string voice = null, string language = null) { var mandatoryParams = new List<string> { "" }; bool isVoiceRequest = true; var data = CreateData( mandatoryParams, new { text, voice, language, isVoiceRequest }); var result = await Client.Update<ConferenceMemberActionResponse>( Uri + conferenceName + "/Member/" + string.Join(",", memberId) + "/Speak/", data ); result.Object.StatusCode = result.StatusCode; return result.Object; } #endregion #region StopSpeakMember /// <summary> /// Stops speaking text to the member. /// </summary> /// <returns>The speak member.</returns> /// <param name="conferenceName">Conference name.</param> /// <param name="memberId">Member identifier.</param> public ConferenceMemberActionResponse StopSpeakMember( string conferenceName, List<string> memberId) { return ExecuteWithExceptionUnwrap(() => { var result = Task.Run(async () => await Client.Delete<ConferenceMemberActionResponse>( Uri + conferenceName + "/Member/" + string.Join(",", memberId) + "/Speak/", new Dictionary<string, object> () { {"is_voice_request", true} }).ConfigureAwait(false)) .Result; result.Object.StatusCode = result.StatusCode; return result.Object; }); } /// <summary> /// Asynchronously stops speaking text to the member. /// </summary> /// <returns>The speak member.</returns> /// <param name="conferenceName">Conference name.</param> /// <param name="memberId">Member identifier.</param> public async Task<ConferenceMemberActionResponse> StopSpeakMemberAsync( string conferenceName, List<string> memberId) { var result = await Client.Delete<ConferenceMemberActionResponse>( Uri + conferenceName + "/Member/" + string.Join(",", memberId) + "/Speak/", new Dictionary<string, object> () { {"is_voice_request", true} } ); result.Object.StatusCode = result.StatusCode; return result.Object; } #endregion #region DeafMember /// <summary> /// Deafs the member. /// </summary> /// <returns>The member.</returns> /// <param name="conferenceName">Conference name.</param> /// <param name="memberId">Member identifier.</param> public ConferenceMemberActionResponse DeafMember( string conferenceName, List<string> memberId) { return ExecuteWithExceptionUnwrap(() => { var result = Task.Run(async () => await Client.Update<ConferenceMemberActionResponse>( Uri + conferenceName + "/Member/" + string.Join(",", memberId) + "/Deaf/", new Dictionary<string, object> () { {"is_voice_request", true} } ).ConfigureAwait(false)).Result; result.Object.StatusCode = result.StatusCode; return result.Object; }); } /// <summary> /// Asynchronously deafs the member. /// </summary> /// <returns>The member.</returns> /// <param name="conferenceName">Conference name.</param> /// <param name="memberId">Member identifier.</param> public async Task<ConferenceMemberActionResponse> DeafMemberAsync( string conferenceName, List<string> memberId) { var result = await Client.Update<ConferenceMemberActionResponse>( Uri + conferenceName + "/Member/" + string.Join(",", memberId) + "/Deaf/", new Dictionary<string, object> () { {"is_voice_request", true} }); result.Object.StatusCode = result.StatusCode; return result.Object; } #endregion #region UnDeafMember /// <summary> /// Enables hearing of the member. /// </summary> /// <returns>The deaf member.</returns> /// <param name="conferenceName">Conference name.</param> /// <param name="memberId">Member identifier.</param> public ConferenceMemberActionResponse UnDeafMember( string conferenceName, List<string> memberId) { return ExecuteWithExceptionUnwrap(() => { var result = Task.Run(async () => await Client.Delete<ConferenceMemberActionResponse>( Uri + conferenceName + "/Member/" + string.Join(",", memberId) + "/Deaf/", new Dictionary<string, object> () { {"is_voice_request", true} } ).ConfigureAwait(false)).Result; try{ result.Object.StatusCode = result.StatusCode; } catch (System.NullReferenceException){ } return result.Object; }); } public async Task<ConferenceMemberActionResponse> UnDeafMemberAsync( string conferenceName, List<string> memberId) { var result = await Client.Delete<ConferenceMemberActionResponse>( Uri + conferenceName + "/Member/" + string.Join(",", memberId) + "/Deaf/", new Dictionary<string, object> () { {"is_voice_request", true} } ); result.Object.StatusCode = result.StatusCode; return result.Object; } #endregion #region StartRecording /// <summary> /// Starts the recording. /// </summary> /// <returns>The recording.</returns> /// <param name="conferenceName">Conference name.</param> /// <param name="fileFormat">File format.</param> /// <param name="transcriptionType">Transcription type.</param> /// <param name="transcriptionUrl">Transcription URL.</param> /// <param name="transcriptionMethod">Transcription method.</param> /// <param name="callbackUrl">Callback URL.</param> /// <param name="callbackMethod">Callback method.</param> public RecordCreateResponse<Conference> StartRecording( string conferenceName, string fileFormat = null, string transcriptionType = null, string transcriptionUrl = null, string transcriptionMethod = null, string callbackUrl = null, string callbackMethod = null) { var mandatoryParams = new List<string> { "" }; bool isVoiceRequest = true; var data = CreateData( mandatoryParams, new { fileFormat, transcriptionType, transcriptionUrl, transcriptionMethod, callbackUrl, callbackMethod, isVoiceRequest }); return ExecuteWithExceptionUnwrap(() => { var result = Task.Run(async () => await Client.Update<RecordCreateResponse<Conference>>( Uri + conferenceName + "/Record/", data ).ConfigureAwait(false)).Result; result.Object.StatusCode = result.StatusCode; return result.Object; }); } /// <summary> /// Asynchronously starts the recording. /// </summary> /// <returns>The recording.</returns> /// <param name="conferenceName">Conference name.</param> /// <param name="fileFormat">File format.</param> /// <param name="transcriptionType">Transcription type.</param> /// <param name="transcriptionUrl">Transcription URL.</param> /// <param name="transcriptionMethod">Transcription method.</param> /// <param name="callbackUrl">Callback URL.</param> /// <param name="callbackMethod">Callback method.</param> public async Task<RecordCreateResponse<Conference>> StartRecordingAsync( string conferenceName, string fileFormat = null, string transcriptionType = null, string transcriptionUrl = null, string transcriptionMethod = null, string callbackUrl = null, string callbackMethod = null) { var mandatoryParams = new List<string> { "" }; bool isVoiceRequest = true; var data = CreateData( mandatoryParams, new { fileFormat, transcriptionType, transcriptionUrl, transcriptionMethod, callbackUrl, callbackMethod, isVoiceRequest }); var result = await Client.Update<RecordCreateResponse<Conference>>( Uri + conferenceName + "/Record/", data ); result.Object.StatusCode = result.StatusCode; return result.Object; } #endregion #region StopRecording /// <summary> /// Stops the recording. /// </summary> /// <param name="conferenceName">Conference name.</param> public void StopRecording( string conferenceName) { ExecuteWithExceptionUnwrap(() => { Task.Run(async () => await Client.Delete<object>( Uri + conferenceName + "/Record/", new Dictionary<string, object> () { {"is_voice_request", true} } ).ConfigureAwait(false)).Wait(); }); } /// <summary> /// Asynchronously stops the recording. /// </summary> /// <param name="conferenceName">Conference name.</param> public async Task StopRecordingAsync( string conferenceName) { await Client.Delete<object>( Uri + conferenceName + "/Record/", new Dictionary<string, object> () { {"is_voice_request", true} } ); } #endregion } }
// Copyright (c) 1995-2009 held by the author(s). All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // nor the names of its contributors may be used to endorse or // promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1998 { /// <summary> /// 64 bit piece of data /// </summary> [Serializable] [XmlRoot] public partial class EightByteChunk { /// <summary> /// Eight bytes of arbitrary data /// </summary> private byte[] _otherParameters = new byte[8]; /// <summary> /// Initializes a new instance of the <see cref="EightByteChunk"/> class. /// </summary> public EightByteChunk() { } /// <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 !=(EightByteChunk left, EightByteChunk 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 ==(EightByteChunk left, EightByteChunk right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public virtual int GetMarshalledSize() { int marshalSize = 0; marshalSize += 8 * 1; // _otherParameters return marshalSize; } /// <summary> /// Gets or sets the Eight bytes of arbitrary data /// </summary> [XmlArray(ElementName = "otherParameters")] public byte[] OtherParameters { get { return this._otherParameters; } set { this._otherParameters = value; } } /// <summary> /// Occurs when exception when processing PDU is caught. /// </summary> public event EventHandler<PduExceptionEventArgs> ExceptionOccured; /// <summary> /// Called when exception occurs (raises the <see cref="Exception"/> event). /// </summary> /// <param name="e">The exception.</param> protected void RaiseExceptionOccured(Exception e) { if (Pdu.FireExceptionEvents && this.ExceptionOccured != null) { this.ExceptionOccured(this, new PduExceptionEventArgs(e)); } } /// <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 virtual void Marshal(DataOutputStream dos) { if (dos != null) { try { for (int idx = 0; idx < this._otherParameters.Length; idx++) { dos.WriteByte(this._otherParameters[idx]); } } 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 virtual void Unmarshal(DataInputStream dis) { if (dis != null) { try { for (int idx = 0; idx < this._otherParameters.Length; idx++) { this._otherParameters[idx] = dis.ReadByte(); } } 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 virtual void Reflection(StringBuilder sb) { sb.AppendLine("<EightByteChunk>"); try { for (int idx = 0; idx < this._otherParameters.Length; idx++) { sb.AppendLine("<otherParameters" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"byte\">" + this._otherParameters[idx] + "</otherParameters" + idx.ToString(CultureInfo.InvariantCulture) + ">"); } sb.AppendLine("</EightByteChunk>"); } 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 EightByteChunk; } /// <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(EightByteChunk obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } if (obj._otherParameters.Length != 8) { ivarsEqual = false; } if (ivarsEqual) { for (int idx = 0; idx < 8; idx++) { if (this._otherParameters[idx] != obj._otherParameters[idx]) { ivarsEqual = false; } } } return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; for (int idx = 0; idx < 8; idx++) { result = GenerateHash(result) ^ this._otherParameters[idx].GetHashCode(); } return result; } } }
using System; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; using Moq; using NUnit.Framework; using Thinktecture.Wscf.Framework.Tests.Helpers; namespace Thinktecture.Wscf.Framework.CodeGeneration { [TestFixture] public class WsdlImporterFactoryTests { private readonly MetadataSet metadataSet = TestMetadata.MetadataSet; private readonly XsdDataContractImporter xsdDataContractImporter = new XsdDataContractImporter(); private readonly XmlSerializerImportOptions xmlSerializerImportOptions = new XmlSerializerImportOptions(); private readonly WrappedOptions wrappedOptions = new WrappedOptions(); private readonly FaultImportOptions faultImportOptions = new FaultImportOptions(); [Test] public void Build_MetadataSet_ProvidedToImporter() { WsdlImporter wsdlImporter = GetWsdlImporter(new CodeGeneratorOptions()); Assert.That(wsdlImporter.WsdlDocuments, Has.Count.EqualTo(1)); Assert.That(wsdlImporter.XmlSchemas, Has.Count.EqualTo(3)); } [Test] public void Build_WsdlImportExtensions_AutoSerializer() { CodeGeneratorOptions options = new CodeGeneratorOptions {Serializer = SerializerMode.Auto}; WsdlImporter wsdlImporter = GetWsdlImporter(options); Type xmlSerializerType = typeof(XmlSerializerMessageContractImporter); Assert.That(wsdlImporter.WsdlImportExtensions.Contains(xmlSerializerType), Is.True); Type dataContractType = typeof(DataContractSerializerMessageContractImporter); Assert.That(wsdlImporter.WsdlImportExtensions.Contains(dataContractType), Is.True); } [Test] public void Build_WsdlImportExtensions_XmlSerializer() { CodeGeneratorOptions options = new CodeGeneratorOptions {Serializer = SerializerMode.XmlSerializer}; WsdlImporter wsdlImporter = GetWsdlImporter(options); Type xmlSerializerType = typeof(XmlSerializerMessageContractImporter); Assert.That(wsdlImporter.WsdlImportExtensions.Contains(xmlSerializerType), Is.True); Type dataContractType = typeof(DataContractSerializerMessageContractImporter); Assert.That(wsdlImporter.WsdlImportExtensions.Contains(dataContractType), Is.False); } [Test] public void Build_WsdlImportExtensions_DataContractSerializer() { CodeGeneratorOptions options = new CodeGeneratorOptions {Serializer = SerializerMode.DataContractSerializer}; WsdlImporter wsdlImporter = GetWsdlImporter(options); Type xmlSerializerType = typeof(XmlSerializerMessageContractImporter); Assert.That(wsdlImporter.WsdlImportExtensions.Contains(xmlSerializerType), Is.False); Type dataContractType = typeof(DataContractSerializerMessageContractImporter); Assert.That(wsdlImporter.WsdlImportExtensions.Contains(dataContractType), Is.True); } [Test] public void State_Serializer_Auto() { Mock<IXmlSerializerImportOptionsBuilder> xmlSerializerImportOptionsBuilder = CreateXmlSerializerImportOptionsBuilder(); Mock<IXsdDataContractImporterBuilder> xsdDataContractImporterBuilder = CreateXsdDataContractImporterBuilder(); Mock<IWrappedOptionsBuilder> wrappedOptionsBuilder = CreateWrappedOptionsBuilder(); Mock<IFaultImportOptionsBuilder> faultImportOptionsBuilder = CreateFaultImportOptionsBuilder(); CodeGeneratorOptions options = new CodeGeneratorOptions {Serializer = SerializerMode.Auto}; WsdlImporter wsdlImporter = GetWsdlImporter(options, xmlSerializerImportOptionsBuilder, xsdDataContractImporterBuilder, wrappedOptionsBuilder, faultImportOptionsBuilder); XsdDataContractImporter dataContractImporterState = GetState<XsdDataContractImporter>(wsdlImporter); Assert.That(dataContractImporterState, Is.EqualTo(xsdDataContractImporter)); XmlSerializerImportOptions xmlSerializerState = GetState<XmlSerializerImportOptions>(wsdlImporter); Assert.That(xmlSerializerState, Is.EqualTo(xmlSerializerImportOptions)); WrappedOptions wrappedOptionsState = GetState<WrappedOptions>(wsdlImporter); Assert.That(wrappedOptionsState, Is.EqualTo(wrappedOptions)); FaultImportOptions faultImportOptionsState = GetState<FaultImportOptions>(wsdlImporter); Assert.That(faultImportOptionsState, Is.EqualTo(faultImportOptions)); VerifyXmlSerializerImportOptionsBuilder(xmlSerializerImportOptionsBuilder, Times.Once()); VerifyXsdDataContractImporterBuilder(xsdDataContractImporterBuilder, Times.Once()); VerifyWrappedOptionsBuilder(wrappedOptionsBuilder, Times.Exactly(2)); VerifyFaultImportOptionsBuilder(faultImportOptionsBuilder, Times.Once()); } [Test] public void State_Serializer_XmlSerializer() { Mock<IXmlSerializerImportOptionsBuilder> xmlSerializerImportOptionsBuilder = CreateXmlSerializerImportOptionsBuilder(); Mock<IXsdDataContractImporterBuilder> xsdDataContractImporterBuilder = CreateXsdDataContractImporterBuilder(); Mock<IWrappedOptionsBuilder> wrappedOptionsBuilder = CreateWrappedOptionsBuilder(); Mock<IFaultImportOptionsBuilder> faultImportOptionsBuilder = CreateFaultImportOptionsBuilder(); CodeGeneratorOptions options = new CodeGeneratorOptions {Serializer = SerializerMode.XmlSerializer}; WsdlImporter wsdlImporter = GetWsdlImporter(options, xmlSerializerImportOptionsBuilder, xsdDataContractImporterBuilder, wrappedOptionsBuilder, faultImportOptionsBuilder); XmlSerializerImportOptions xmlSerializerState = GetState<XmlSerializerImportOptions>(wsdlImporter); Assert.That(xmlSerializerState, Is.EqualTo(xmlSerializerImportOptions)); WrappedOptions wrappedOptionsState = GetState<WrappedOptions>(wsdlImporter); Assert.That(wrappedOptionsState, Is.EqualTo(wrappedOptions)); FaultImportOptions faultImportOptionsState = GetState<FaultImportOptions>(wsdlImporter); Assert.That(faultImportOptionsState, Is.EqualTo(faultImportOptions)); VerifyXmlSerializerImportOptionsBuilder(xmlSerializerImportOptionsBuilder, Times.Once()); VerifyXsdDataContractImporterBuilder(xsdDataContractImporterBuilder, Times.Never()); VerifyWrappedOptionsBuilder(wrappedOptionsBuilder, Times.Once()); VerifyFaultImportOptionsBuilder(faultImportOptionsBuilder, Times.Once()); } [Test] public void State_Serializer_DataContractSerializer() { Mock<IXmlSerializerImportOptionsBuilder> xmlSerializerImportOptionsBuilder = CreateXmlSerializerImportOptionsBuilder(); Mock<IXsdDataContractImporterBuilder> xsdDataContractImporterBuilder = CreateXsdDataContractImporterBuilder(); Mock<IWrappedOptionsBuilder> wrappedOptionsBuilder = CreateWrappedOptionsBuilder(); Mock<IFaultImportOptionsBuilder> faultImportOptionsBuilder = CreateFaultImportOptionsBuilder(); CodeGeneratorOptions options = new CodeGeneratorOptions {Serializer = SerializerMode.DataContractSerializer}; WsdlImporter wsdlImporter = GetWsdlImporter(options, xmlSerializerImportOptionsBuilder, xsdDataContractImporterBuilder, wrappedOptionsBuilder, faultImportOptionsBuilder); XsdDataContractImporter dataContractImporterState = GetState<XsdDataContractImporter>(wsdlImporter); Assert.That(dataContractImporterState, Is.EqualTo(xsdDataContractImporter)); WrappedOptions wrappedOptionsState = GetState<WrappedOptions>(wsdlImporter); Assert.That(wrappedOptionsState, Is.EqualTo(wrappedOptions)); VerifyXmlSerializerImportOptionsBuilder(xmlSerializerImportOptionsBuilder, Times.Never()); VerifyXsdDataContractImporterBuilder(xsdDataContractImporterBuilder, Times.Once()); VerifyWrappedOptionsBuilder(wrappedOptionsBuilder, Times.Once()); VerifyFaultImportOptionsBuilder(faultImportOptionsBuilder, Times.Never()); } [Test] public void UseXmlSerializerForFaults_Serializer_Auto() { Mock<IXmlSerializerImportOptionsBuilder> xmlSerializerImportOptionsBuilder = CreateXmlSerializerImportOptionsBuilder(); Mock<IXsdDataContractImporterBuilder> xsdDataContractImporterBuilder = CreateXsdDataContractImporterBuilder(); Mock<IWrappedOptionsBuilder> wrappedOptionsBuilder = CreateWrappedOptionsBuilder(); Mock<IFaultImportOptionsBuilder> faultImportOptionsBuilder = CreateFaultImportOptionsBuilder(); CodeGeneratorOptions options = new CodeGeneratorOptions { Serializer = SerializerMode.Auto, UseXmlSerializerForFaults = true }; GetWsdlImporter(options, xmlSerializerImportOptionsBuilder, xsdDataContractImporterBuilder, wrappedOptionsBuilder, faultImportOptionsBuilder); VerifyXmlSerializerImportOptionsBuilder(xmlSerializerImportOptionsBuilder, Times.Once()); VerifyXsdDataContractImporterBuilder(xsdDataContractImporterBuilder, Times.Once()); VerifyWrappedOptionsBuilder(wrappedOptionsBuilder, Times.Exactly(2)); VerifyFaultImportOptionsBuilder(faultImportOptionsBuilder, Times.Once()); xmlSerializerImportOptionsBuilder = CreateXmlSerializerImportOptionsBuilder(); xsdDataContractImporterBuilder = CreateXsdDataContractImporterBuilder(); wrappedOptionsBuilder = CreateWrappedOptionsBuilder(); faultImportOptionsBuilder = CreateFaultImportOptionsBuilder(); options = new CodeGeneratorOptions { Serializer = SerializerMode.Auto, UseXmlSerializerForFaults = false }; GetWsdlImporter(options, xmlSerializerImportOptionsBuilder, xsdDataContractImporterBuilder, wrappedOptionsBuilder, faultImportOptionsBuilder); VerifyXmlSerializerImportOptionsBuilder(xmlSerializerImportOptionsBuilder, Times.Once()); VerifyXsdDataContractImporterBuilder(xsdDataContractImporterBuilder, Times.Once()); VerifyWrappedOptionsBuilder(wrappedOptionsBuilder, Times.Exactly(2)); VerifyFaultImportOptionsBuilder(faultImportOptionsBuilder, Times.Never()); } [Test] public void UseXmlSerializerForFaults_Serializer_XmlSerializer() { Mock<IXmlSerializerImportOptionsBuilder> xmlSerializerImportOptionsBuilder = CreateXmlSerializerImportOptionsBuilder(); Mock<IXsdDataContractImporterBuilder> xsdDataContractImporterBuilder = CreateXsdDataContractImporterBuilder(); Mock<IWrappedOptionsBuilder> wrappedOptionsBuilder = CreateWrappedOptionsBuilder(); Mock<IFaultImportOptionsBuilder> faultImportOptionsBuilder = CreateFaultImportOptionsBuilder(); CodeGeneratorOptions options = new CodeGeneratorOptions { Serializer = SerializerMode.XmlSerializer, UseXmlSerializerForFaults = true }; GetWsdlImporter(options, xmlSerializerImportOptionsBuilder, xsdDataContractImporterBuilder, wrappedOptionsBuilder, faultImportOptionsBuilder); VerifyXmlSerializerImportOptionsBuilder(xmlSerializerImportOptionsBuilder, Times.Once()); VerifyXsdDataContractImporterBuilder(xsdDataContractImporterBuilder, Times.Never()); VerifyWrappedOptionsBuilder(wrappedOptionsBuilder, Times.Once()); VerifyFaultImportOptionsBuilder(faultImportOptionsBuilder, Times.Once()); xmlSerializerImportOptionsBuilder = CreateXmlSerializerImportOptionsBuilder(); xsdDataContractImporterBuilder = CreateXsdDataContractImporterBuilder(); wrappedOptionsBuilder = CreateWrappedOptionsBuilder(); faultImportOptionsBuilder = CreateFaultImportOptionsBuilder(); options = new CodeGeneratorOptions { Serializer = SerializerMode.XmlSerializer, UseXmlSerializerForFaults = false }; GetWsdlImporter(options, xmlSerializerImportOptionsBuilder, xsdDataContractImporterBuilder, wrappedOptionsBuilder, faultImportOptionsBuilder); VerifyXmlSerializerImportOptionsBuilder(xmlSerializerImportOptionsBuilder, Times.Once()); VerifyXsdDataContractImporterBuilder(xsdDataContractImporterBuilder, Times.Once()); VerifyWrappedOptionsBuilder(wrappedOptionsBuilder, Times.Exactly(2)); VerifyFaultImportOptionsBuilder(faultImportOptionsBuilder, Times.Never()); } [Test] public void UseXmlSerializerForFaults_Serializer_DataContractSerializer() { Mock<IXmlSerializerImportOptionsBuilder> xmlSerializerImportOptionsBuilder = CreateXmlSerializerImportOptionsBuilder(); Mock<IXsdDataContractImporterBuilder> xsdDataContractImporterBuilder = CreateXsdDataContractImporterBuilder(); Mock<IWrappedOptionsBuilder> wrappedOptionsBuilder = CreateWrappedOptionsBuilder(); Mock<IFaultImportOptionsBuilder> faultImportOptionsBuilder = CreateFaultImportOptionsBuilder(); CodeGeneratorOptions options = new CodeGeneratorOptions { Serializer = SerializerMode.DataContractSerializer, UseXmlSerializerForFaults = true }; GetWsdlImporter(options, xmlSerializerImportOptionsBuilder, xsdDataContractImporterBuilder, wrappedOptionsBuilder, faultImportOptionsBuilder); VerifyXmlSerializerImportOptionsBuilder(xmlSerializerImportOptionsBuilder, Times.Never()); VerifyXsdDataContractImporterBuilder(xsdDataContractImporterBuilder, Times.Once()); VerifyWrappedOptionsBuilder(wrappedOptionsBuilder, Times.Once()); VerifyFaultImportOptionsBuilder(faultImportOptionsBuilder, Times.Never()); xmlSerializerImportOptionsBuilder = CreateXmlSerializerImportOptionsBuilder(); xsdDataContractImporterBuilder = CreateXsdDataContractImporterBuilder(); wrappedOptionsBuilder = CreateWrappedOptionsBuilder(); faultImportOptionsBuilder = CreateFaultImportOptionsBuilder(); options = new CodeGeneratorOptions { Serializer = SerializerMode.DataContractSerializer, UseXmlSerializerForFaults = false }; GetWsdlImporter(options, xmlSerializerImportOptionsBuilder, xsdDataContractImporterBuilder, wrappedOptionsBuilder, faultImportOptionsBuilder); VerifyXmlSerializerImportOptionsBuilder(xmlSerializerImportOptionsBuilder, Times.Never()); VerifyXsdDataContractImporterBuilder(xsdDataContractImporterBuilder, Times.Once()); VerifyWrappedOptionsBuilder(wrappedOptionsBuilder, Times.Once()); VerifyFaultImportOptionsBuilder(faultImportOptionsBuilder, Times.Never()); } private WsdlImporter GetWsdlImporter(CodeGeneratorOptions options) { return GetWsdlImporter(options, CreateXmlSerializerImportOptionsBuilder(), CreateXsdDataContractImporterBuilder(), CreateWrappedOptionsBuilder(), CreateFaultImportOptionsBuilder()); } private WsdlImporter GetWsdlImporter( CodeGeneratorOptions options, Mock<IXmlSerializerImportOptionsBuilder> xmlSerializerImportOptionsBuilder, Mock<IXsdDataContractImporterBuilder> xsdDataContractImporterBuilder, Mock<IWrappedOptionsBuilder> wrappedOptionsBuilder, Mock<IFaultImportOptionsBuilder> faultImportOptionsBuilder) { WsdlImporterFactory factory = new WsdlImporterFactory( xmlSerializerImportOptionsBuilder.Object, xsdDataContractImporterBuilder.Object, wrappedOptionsBuilder.Object, faultImportOptionsBuilder.Object); ICodeGeneratorContext codeGeneratorContext = CreateCodeGeneratorContext(options); return factory.GetWsdlImporter(codeGeneratorContext); } private ICodeGeneratorContext CreateCodeGeneratorContext(CodeGeneratorOptions codeGeneratorOptions) { return new CodeGeneratorContext(metadataSet, codeGeneratorOptions); } private Mock<IXsdDataContractImporterBuilder> CreateXsdDataContractImporterBuilder() { Mock<IXsdDataContractImporterBuilder> builder = new Mock<IXsdDataContractImporterBuilder>(); builder.Setup(mock => mock.Build(It.IsAny<ICodeGeneratorContext>())).Returns(xsdDataContractImporter); return builder; } private Mock<IXmlSerializerImportOptionsBuilder> CreateXmlSerializerImportOptionsBuilder() { Mock<IXmlSerializerImportOptionsBuilder> builder = new Mock<IXmlSerializerImportOptionsBuilder>(); builder.Setup(mock => mock.Build(It.IsAny<ICodeGeneratorContext>())).Returns(xmlSerializerImportOptions); return builder; } private Mock<IWrappedOptionsBuilder> CreateWrappedOptionsBuilder() { Mock<IWrappedOptionsBuilder> builder = new Mock<IWrappedOptionsBuilder>(); builder.Setup(mock => mock.Build(It.IsAny<CodeGeneratorOptions>())).Returns(wrappedOptions); return builder; } private Mock<IFaultImportOptionsBuilder> CreateFaultImportOptionsBuilder() { Mock<IFaultImportOptionsBuilder> builder = new Mock<IFaultImportOptionsBuilder>(); builder.Setup(mock => mock.Build()).Returns(faultImportOptions); return builder; } private static void VerifyXsdDataContractImporterBuilder(Mock<IXsdDataContractImporterBuilder> builder, Times times) { builder.Verify(mock => mock.Build(It.IsAny<ICodeGeneratorContext>()), times); } private static void VerifyXmlSerializerImportOptionsBuilder(Mock<IXmlSerializerImportOptionsBuilder> builder, Times times) { builder.Verify(mock => mock.Build(It.IsAny<ICodeGeneratorContext>()), times); } private static void VerifyWrappedOptionsBuilder(Mock<IWrappedOptionsBuilder> builder, Times times) { builder.Verify(mock => mock.Build(It.IsAny<CodeGeneratorOptions>()), times); } private static void VerifyFaultImportOptionsBuilder(Mock<IFaultImportOptionsBuilder> builder, Times times) { builder.Verify(mock => mock.Build(), times); } private static T GetState<T>(MetadataImporter wsdlImporter) where T : class { object state; wsdlImporter.State.TryGetValue(typeof(T), out state); return state as T; } } }
using System; using System.Linq; using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Services; using Umbraco.Tests.TestHelpers.Entities; using Umbraco.Tests.Testing; using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.PropertyEditors; namespace Umbraco.Tests.Models.Mapping { [TestFixture] [UmbracoTest(WithApplication = true)] public class ContentTypeModelMappingTests : UmbracoTestBase { // mocks of services that can be setup on a test by test basis to return whatever we want private readonly Mock<IContentTypeService> _contentTypeService = new Mock<IContentTypeService>(); private readonly Mock<IContentService> _contentService = new Mock<IContentService>(); private readonly Mock<IDataTypeService> _dataTypeService = new Mock<IDataTypeService>(); private readonly Mock<IEntityService> _entityService = new Mock<IEntityService>(); private readonly Mock<IFileService> _fileService = new Mock<IFileService>(); private Mock<PropertyEditorCollection> _editorsMock; protected override void Compose() { base.Compose(); // create and register a fake property editor collection to return fake property editors var editors = new DataEditor[] { new TextboxPropertyEditor(Mock.Of<ILogger>()), }; var dataEditors = new DataEditorCollection(editors); _editorsMock = new Mock<PropertyEditorCollection>(dataEditors); _editorsMock.Setup(x => x[It.IsAny<string>()]).Returns(editors[0]); Composition.RegisterUnique(f => _editorsMock.Object); Composition.RegisterUnique(_ => _contentTypeService.Object); Composition.RegisterUnique(_ => _contentService.Object); Composition.RegisterUnique(_ => _dataTypeService.Object); Composition.RegisterUnique(_ => _entityService.Object); Composition.RegisterUnique(_ => _fileService.Object); } [Test] public void MemberTypeSave_To_IMemberType() { //Arrange // setup the mocks to return the data we want to test against... _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(Mock.Of<IDataType>( definition => definition.Id == 555 && definition.EditorAlias == "myPropertyType" && definition.DatabaseType == ValueStorageType.Nvarchar)); var display = CreateMemberTypeSave(); //Act var result = Mapper.Map<IMemberType>(display); //Assert Assert.AreEqual(display.Alias, result.Alias); Assert.AreEqual(display.Description, result.Description); Assert.AreEqual(display.Icon, result.Icon); Assert.AreEqual(display.Id, result.Id); Assert.AreEqual(display.Name, result.Name); Assert.AreEqual(display.ParentId, result.ParentId); Assert.AreEqual(display.Path, result.Path); Assert.AreEqual(display.Thumbnail, result.Thumbnail); Assert.AreEqual(display.IsContainer, result.IsContainer); Assert.AreEqual(display.AllowAsRoot, result.AllowedAsRoot); Assert.AreEqual(display.CreateDate, result.CreateDate); Assert.AreEqual(display.UpdateDate, result.UpdateDate); // TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(display.Groups.Count(), result.PropertyGroups.Count); for (var i = 0; i < display.Groups.Count(); i++) { Assert.AreEqual(display.Groups.ElementAt(i).Id, result.PropertyGroups.ElementAt(i).Id); Assert.AreEqual(display.Groups.ElementAt(i).Name, result.PropertyGroups.ElementAt(i).Name); var propTypes = display.Groups.ElementAt(i).Properties; Assert.AreEqual(propTypes.Count(), result.PropertyTypes.Count()); for (var j = 0; j < propTypes.Count(); j++) { Assert.AreEqual(propTypes.ElementAt(j).Id, result.PropertyTypes.ElementAt(j).Id); Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.PropertyTypes.ElementAt(j).DataTypeId); Assert.AreEqual(propTypes.ElementAt(j).MemberCanViewProperty, result.MemberCanViewProperty(result.PropertyTypes.ElementAt(j).Alias)); Assert.AreEqual(propTypes.ElementAt(j).MemberCanEditProperty, result.MemberCanEditProperty(result.PropertyTypes.ElementAt(j).Alias)); Assert.AreEqual(propTypes.ElementAt(j).IsSensitiveData, result.IsSensitiveProperty(result.PropertyTypes.ElementAt(j).Alias)); } } Assert.AreEqual(display.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); for (var i = 0; i < display.AllowedContentTypes.Count(); i++) { Assert.AreEqual(display.AllowedContentTypes.ElementAt(i), result.AllowedContentTypes.ElementAt(i).Id.Value); } } [Test] public void MediaTypeSave_To_IMediaType() { //Arrange // setup the mocks to return the data we want to test against... _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(Mock.Of<IDataType>( definition => definition.Id == 555 && definition.EditorAlias == "myPropertyType" && definition.DatabaseType == ValueStorageType.Nvarchar)); var display = CreateMediaTypeSave(); //Act var result = Mapper.Map<IMediaType>(display); //Assert Assert.AreEqual(display.Alias, result.Alias); Assert.AreEqual(display.Description, result.Description); Assert.AreEqual(display.Icon, result.Icon); Assert.AreEqual(display.Id, result.Id); Assert.AreEqual(display.Name, result.Name); Assert.AreEqual(display.ParentId, result.ParentId); Assert.AreEqual(display.Path, result.Path); Assert.AreEqual(display.Thumbnail, result.Thumbnail); Assert.AreEqual(display.IsContainer, result.IsContainer); Assert.AreEqual(display.AllowAsRoot, result.AllowedAsRoot); Assert.AreEqual(display.CreateDate, result.CreateDate); Assert.AreEqual(display.UpdateDate, result.UpdateDate); // TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(display.Groups.Count(), result.PropertyGroups.Count); for (var i = 0; i < display.Groups.Count(); i++) { Assert.AreEqual(display.Groups.ElementAt(i).Id, result.PropertyGroups.ElementAt(i).Id); Assert.AreEqual(display.Groups.ElementAt(i).Name, result.PropertyGroups.ElementAt(i).Name); var propTypes = display.Groups.ElementAt(i).Properties; Assert.AreEqual(propTypes.Count(), result.PropertyTypes.Count()); for (var j = 0; j < propTypes.Count(); j++) { Assert.AreEqual(propTypes.ElementAt(j).Id, result.PropertyTypes.ElementAt(j).Id); Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.PropertyTypes.ElementAt(j).DataTypeId); } } Assert.AreEqual(display.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); for (var i = 0; i < display.AllowedContentTypes.Count(); i++) { Assert.AreEqual(display.AllowedContentTypes.ElementAt(i), result.AllowedContentTypes.ElementAt(i).Id.Value); } } [Test] public void ContentTypeSave_To_IContentType() { //Arrange // setup the mocks to return the data we want to test against... _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(Mock.Of<IDataType>( definition => definition.Id == 555 && definition.EditorAlias == "myPropertyType" && definition.DatabaseType == ValueStorageType.Nvarchar)); _fileService.Setup(x => x.GetTemplate(It.IsAny<string>())) .Returns((string alias) => Mock.Of<ITemplate>( definition => definition.Id == alias.GetHashCode() && definition.Alias == alias)); var display = CreateContentTypeSave(); //Act var result = Mapper.Map<IContentType>(display); //Assert Assert.AreEqual(display.Alias, result.Alias); Assert.AreEqual(display.Description, result.Description); Assert.AreEqual(display.Icon, result.Icon); Assert.AreEqual(display.Id, result.Id); Assert.AreEqual(display.Name, result.Name); Assert.AreEqual(display.ParentId, result.ParentId); Assert.AreEqual(display.Path, result.Path); Assert.AreEqual(display.Thumbnail, result.Thumbnail); Assert.AreEqual(display.IsContainer, result.IsContainer); Assert.AreEqual(display.AllowAsRoot, result.AllowedAsRoot); Assert.AreEqual(display.CreateDate, result.CreateDate); Assert.AreEqual(display.UpdateDate, result.UpdateDate); // TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(display.Groups.Count(), result.PropertyGroups.Count); for (var i = 0; i < display.Groups.Count(); i++) { Assert.AreEqual(display.Groups.ElementAt(i).Id, result.PropertyGroups.ElementAt(i).Id); Assert.AreEqual(display.Groups.ElementAt(i).Name, result.PropertyGroups.ElementAt(i).Name); var propTypes = display.Groups.ElementAt(i).Properties; Assert.AreEqual(propTypes.Count(), result.PropertyTypes.Count()); for (var j = 0; j < propTypes.Count(); j++) { Assert.AreEqual(propTypes.ElementAt(j).Id, result.PropertyTypes.ElementAt(j).Id); Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.PropertyTypes.ElementAt(j).DataTypeId); } } var allowedTemplateAliases = display.AllowedTemplates .Concat(new[] {display.DefaultTemplate}) .Distinct(); Assert.AreEqual(allowedTemplateAliases.Count(), result.AllowedTemplates.Count()); for (var i = 0; i < display.AllowedTemplates.Count(); i++) { Assert.AreEqual(display.AllowedTemplates.ElementAt(i), result.AllowedTemplates.ElementAt(i).Alias); } Assert.AreEqual(display.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); for (var i = 0; i < display.AllowedContentTypes.Count(); i++) { Assert.AreEqual(display.AllowedContentTypes.ElementAt(i), result.AllowedContentTypes.ElementAt(i).Id.Value); } } [Test] public void MediaTypeSave_With_Composition_To_IMediaType() { //Arrange // setup the mocks to return the data we want to test against... _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(Mock.Of<IDataType>( definition => definition.Id == 555 && definition.EditorAlias == "myPropertyType" && definition.DatabaseType == ValueStorageType.Nvarchar)); var display = CreateCompositionMediaTypeSave(); //Act var result = Mapper.Map<IMediaType>(display); //Assert // TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(display.Groups.Count(x => x.Inherited == false), result.PropertyGroups.Count); } [Test] public void ContentTypeSave_With_Composition_To_IContentType() { //Arrange // setup the mocks to return the data we want to test against... _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(Mock.Of<IDataType>( definition => definition.Id == 555 && definition.EditorAlias == "myPropertyType" && definition.DatabaseType == ValueStorageType.Nvarchar)); var display = CreateCompositionContentTypeSave(); //Act var result = Mapper.Map<IContentType>(display); //Assert // TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(display.Groups.Count(x => x.Inherited == false), result.PropertyGroups.Count); } [Test] public void IMemberType_To_MemberTypeDisplay() { //Arrange _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(new DataType(new VoidEditor(Mock.Of<ILogger>()))); // setup the mocks to return the data we want to test against... var memberType = MockedContentTypes.CreateSimpleMemberType(); memberType.MemberTypePropertyTypes[memberType.PropertyTypes.Last().Alias] = new MemberTypePropertyProfileAccess(true, true, true); MockedContentTypes.EnsureAllIds(memberType, 8888); //Act var result = Mapper.Map<MemberTypeDisplay>(memberType); //Assert Assert.AreEqual(memberType.Alias, result.Alias); Assert.AreEqual(memberType.Description, result.Description); Assert.AreEqual(memberType.Icon, result.Icon); Assert.AreEqual(memberType.Id, result.Id); Assert.AreEqual(memberType.Name, result.Name); Assert.AreEqual(memberType.ParentId, result.ParentId); Assert.AreEqual(memberType.Path, result.Path); Assert.AreEqual(memberType.Thumbnail, result.Thumbnail); Assert.AreEqual(memberType.IsContainer, result.IsContainer); Assert.AreEqual(memberType.CreateDate, result.CreateDate); Assert.AreEqual(memberType.UpdateDate, result.UpdateDate); // TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(memberType.PropertyGroups.Count(), result.Groups.Count()); for (var i = 0; i < memberType.PropertyGroups.Count(); i++) { Assert.AreEqual(memberType.PropertyGroups.ElementAt(i).Id, result.Groups.ElementAt(i).Id); Assert.AreEqual(memberType.PropertyGroups.ElementAt(i).Name, result.Groups.ElementAt(i).Name); var propTypes = memberType.PropertyGroups.ElementAt(i).PropertyTypes; Assert.AreEqual(propTypes.Count(), result.Groups.ElementAt(i).Properties.Count()); for (var j = 0; j < propTypes.Count(); j++) { Assert.AreEqual(propTypes.ElementAt(j).Id, result.Groups.ElementAt(i).Properties.ElementAt(j).Id); Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.Groups.ElementAt(i).Properties.ElementAt(j).DataTypeId); Assert.AreEqual(memberType.MemberCanViewProperty(propTypes.ElementAt(j).Alias), result.Groups.ElementAt(i).Properties.ElementAt(j).MemberCanViewProperty); Assert.AreEqual(memberType.MemberCanEditProperty(propTypes.ElementAt(j).Alias), result.Groups.ElementAt(i).Properties.ElementAt(j).MemberCanEditProperty); } } Assert.AreEqual(memberType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); for (var i = 0; i < memberType.AllowedContentTypes.Count(); i++) { Assert.AreEqual(memberType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i)); } } [Test] public void IMediaType_To_MediaTypeDisplay() { //Arrange _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(new DataType(new VoidEditor(Mock.Of<ILogger>()))); // setup the mocks to return the data we want to test against... var mediaType = MockedContentTypes.CreateImageMediaType(); MockedContentTypes.EnsureAllIds(mediaType, 8888); //Act var result = Mapper.Map<MediaTypeDisplay>(mediaType); //Assert Assert.AreEqual(mediaType.Alias, result.Alias); Assert.AreEqual(mediaType.Description, result.Description); Assert.AreEqual(mediaType.Icon, result.Icon); Assert.AreEqual(mediaType.Id, result.Id); Assert.AreEqual(mediaType.Name, result.Name); Assert.AreEqual(mediaType.ParentId, result.ParentId); Assert.AreEqual(mediaType.Path, result.Path); Assert.AreEqual(mediaType.Thumbnail, result.Thumbnail); Assert.AreEqual(mediaType.IsContainer, result.IsContainer); Assert.AreEqual(mediaType.CreateDate, result.CreateDate); Assert.AreEqual(mediaType.UpdateDate, result.UpdateDate); // TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(mediaType.PropertyGroups.Count(), result.Groups.Count()); for (var i = 0; i < mediaType.PropertyGroups.Count(); i++) { Assert.AreEqual(mediaType.PropertyGroups.ElementAt(i).Id, result.Groups.ElementAt(i).Id); Assert.AreEqual(mediaType.PropertyGroups.ElementAt(i).Name, result.Groups.ElementAt(i).Name); var propTypes = mediaType.PropertyGroups.ElementAt(i).PropertyTypes; Assert.AreEqual(propTypes.Count(), result.Groups.ElementAt(i).Properties.Count()); for (var j = 0; j < propTypes.Count(); j++) { Assert.AreEqual(propTypes.ElementAt(j).Id, result.Groups.ElementAt(i).Properties.ElementAt(j).Id); Assert.AreEqual(propTypes.ElementAt(j).DataTypeId, result.Groups.ElementAt(i).Properties.ElementAt(j).DataTypeId); } } Assert.AreEqual(mediaType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); for (var i = 0; i < mediaType.AllowedContentTypes.Count(); i++) { Assert.AreEqual(mediaType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i)); } } [Test] public void IContentType_To_ContentTypeDisplay() { //Arrange _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(new DataType(new VoidEditor(Mock.Of<ILogger>()))); // setup the mocks to return the data we want to test against... var contentType = MockedContentTypes.CreateTextPageContentType(); MockedContentTypes.EnsureAllIds(contentType, 8888); //Act var result = Mapper.Map<DocumentTypeDisplay>(contentType); //Assert Assert.AreEqual(contentType.Alias, result.Alias); Assert.AreEqual(contentType.Description, result.Description); Assert.AreEqual(contentType.Icon, result.Icon); Assert.AreEqual(contentType.Id, result.Id); Assert.AreEqual(contentType.Name, result.Name); Assert.AreEqual(contentType.ParentId, result.ParentId); Assert.AreEqual(contentType.Path, result.Path); Assert.AreEqual(contentType.Thumbnail, result.Thumbnail); Assert.AreEqual(contentType.IsContainer, result.IsContainer); Assert.AreEqual(contentType.CreateDate, result.CreateDate); Assert.AreEqual(contentType.UpdateDate, result.UpdateDate); Assert.AreEqual(contentType.DefaultTemplate.Alias, result.DefaultTemplate.Alias); // TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(contentType.PropertyGroups.Count, result.Groups.Count()); for (var i = 0; i < contentType.PropertyGroups.Count; i++) { Assert.AreEqual(contentType.PropertyGroups[i].Id, result.Groups.ElementAt(i).Id); Assert.AreEqual(contentType.PropertyGroups[i].Name, result.Groups.ElementAt(i).Name); var propTypes = contentType.PropertyGroups[i].PropertyTypes; Assert.AreEqual(propTypes.Count, result.Groups.ElementAt(i).Properties.Count()); for (var j = 0; j < propTypes.Count; j++) { Assert.AreEqual(propTypes[j].Id, result.Groups.ElementAt(i).Properties.ElementAt(j).Id); Assert.AreEqual(propTypes[j].DataTypeId, result.Groups.ElementAt(i).Properties.ElementAt(j).DataTypeId); } } Assert.AreEqual(contentType.AllowedTemplates.Count(), result.AllowedTemplates.Count()); for (var i = 0; i < contentType.AllowedTemplates.Count(); i++) { Assert.AreEqual(contentType.AllowedTemplates.ElementAt(i).Id, result.AllowedTemplates.ElementAt(i).Id); } Assert.AreEqual(contentType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); for (var i = 0; i < contentType.AllowedContentTypes.Count(); i++) { Assert.AreEqual(contentType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i)); } } [Test] public void MemberPropertyGroupBasic_To_MemberPropertyGroup() { _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(new DataType(new VoidEditor(Mock.Of<ILogger>()))); var basic = new PropertyGroupBasic<MemberPropertyTypeBasic> { Id = 222, Name = "Group 1", SortOrder = 1, Properties = new[] { new MemberPropertyTypeBasic() { MemberCanEditProperty = true, MemberCanViewProperty = true, IsSensitiveData = true, Id = 33, SortOrder = 1, Alias = "prop1", Description = "property 1", DataTypeId = 99, GroupId = 222, Label = "Prop 1", Validation = new PropertyTypeValidation() { Mandatory = true, Pattern = null } }, new MemberPropertyTypeBasic() { MemberCanViewProperty = false, MemberCanEditProperty = false, IsSensitiveData = false, Id = 34, SortOrder = 2, Alias = "prop2", Description = "property 2", DataTypeId = 99, GroupId = 222, Label = "Prop 2", Validation = new PropertyTypeValidation() { Mandatory = false, Pattern = null } }, } }; var contentType = new MemberTypeSave { Id = 0, ParentId = -1, Alias = "alias", Groups = new[] { basic } }; // proper group properties mapping takes place when mapping the content type, // not when mapping the group - because of inherited properties and such //var result = Mapper.Map<PropertyGroup>(basic); var result = Mapper.Map<IMemberType>(contentType).PropertyGroups[0]; Assert.AreEqual(basic.Name, result.Name); Assert.AreEqual(basic.Id, result.Id); Assert.AreEqual(basic.SortOrder, result.SortOrder); Assert.AreEqual(basic.Properties.Count(), result.PropertyTypes.Count()); } [Test] public void PropertyGroupBasic_To_PropertyGroup() { _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(new DataType(new VoidEditor(Mock.Of<ILogger>()))); var basic = new PropertyGroupBasic<PropertyTypeBasic> { Id = 222, Name = "Group 1", SortOrder = 1, Properties = new[] { new PropertyTypeBasic() { Id = 33, SortOrder = 1, Alias = "prop1", Description = "property 1", DataTypeId = 99, GroupId = 222, Label = "Prop 1", Validation = new PropertyTypeValidation() { Mandatory = true, Pattern = null } }, new PropertyTypeBasic() { Id = 34, SortOrder = 2, Alias = "prop2", Description = "property 2", DataTypeId = 99, GroupId = 222, Label = "Prop 2", Validation = new PropertyTypeValidation() { Mandatory = false, Pattern = null } }, } }; var contentType = new DocumentTypeSave { Id = 0, ParentId = -1, Alias = "alias", AllowedTemplates = Enumerable.Empty<string>(), Groups = new[] { basic } }; // proper group properties mapping takes place when mapping the content type, // not when mapping the group - because of inherited properties and such //var result = Mapper.Map<PropertyGroup>(basic); var result = Mapper.Map<IContentType>(contentType).PropertyGroups[0]; Assert.AreEqual(basic.Name, result.Name); Assert.AreEqual(basic.Id, result.Id); Assert.AreEqual(basic.SortOrder, result.SortOrder); Assert.AreEqual(basic.Properties.Count(), result.PropertyTypes.Count()); } [Test] public void MemberPropertyTypeBasic_To_PropertyType() { _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(new DataType(new VoidEditor(Mock.Of<ILogger>()))); var basic = new MemberPropertyTypeBasic() { Id = 33, SortOrder = 1, Alias = "prop1", Description = "property 1", DataTypeId = 99, GroupId = 222, Label = "Prop 1", Validation = new PropertyTypeValidation() { Mandatory = true, MandatoryMessage = "Please enter a value", Pattern = "xyz", PatternMessage = "Please match the pattern", } }; var result = Mapper.Map<PropertyType>(basic); Assert.AreEqual(basic.Id, result.Id); Assert.AreEqual(basic.SortOrder, result.SortOrder); Assert.AreEqual(basic.Alias, result.Alias); Assert.AreEqual(basic.Description, result.Description); Assert.AreEqual(basic.DataTypeId, result.DataTypeId); Assert.AreEqual(basic.Label, result.Name); Assert.AreEqual(basic.Validation.Mandatory, result.Mandatory); Assert.AreEqual(basic.Validation.MandatoryMessage, result.MandatoryMessage); Assert.AreEqual(basic.Validation.Pattern, result.ValidationRegExp); Assert.AreEqual(basic.Validation.PatternMessage, result.ValidationRegExpMessage); } [Test] public void PropertyTypeBasic_To_PropertyType() { _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(new DataType(new VoidEditor(Mock.Of<ILogger>()))); var basic = new PropertyTypeBasic() { Id = 33, SortOrder = 1, Alias = "prop1", Description = "property 1", DataTypeId = 99, GroupId = 222, Label = "Prop 1", Validation = new PropertyTypeValidation() { Mandatory = true, MandatoryMessage = "Please enter a value", Pattern = "xyz", PatternMessage = "Please match the pattern", } }; var result = Mapper.Map<PropertyType>(basic); Assert.AreEqual(basic.Id, result.Id); Assert.AreEqual(basic.SortOrder, result.SortOrder); Assert.AreEqual(basic.Alias, result.Alias); Assert.AreEqual(basic.Description, result.Description); Assert.AreEqual(basic.DataTypeId, result.DataTypeId); Assert.AreEqual(basic.Label, result.Name); Assert.AreEqual(basic.Validation.Mandatory, result.Mandatory); Assert.AreEqual(basic.Validation.MandatoryMessage, result.MandatoryMessage); Assert.AreEqual(basic.Validation.Pattern, result.ValidationRegExp); Assert.AreEqual(basic.Validation.PatternMessage, result.ValidationRegExpMessage); } [Test] public void IMediaTypeComposition_To_MediaTypeDisplay() { //Arrange _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(new DataType(new VoidEditor(Mock.Of<ILogger>()))); // setup the mocks to return the data we want to test against... _entityService.Setup(x => x.GetObjectType(It.IsAny<int>())) .Returns(UmbracoObjectTypes.DocumentType); var ctMain = MockedContentTypes.CreateSimpleMediaType("parent", "Parent"); //not assigned to tab ctMain.AddPropertyType(new PropertyType(Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { Alias = "umbracoUrlName", Name = "Slug", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 }); MockedContentTypes.EnsureAllIds(ctMain, 8888); var ctChild1 = MockedContentTypes.CreateSimpleMediaType("child1", "Child 1", ctMain, true); ctChild1.AddPropertyType(new PropertyType(Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { Alias = "someProperty", Name = "Some Property", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 }, "Another tab"); MockedContentTypes.EnsureAllIds(ctChild1, 7777); var contentType = MockedContentTypes.CreateSimpleMediaType("child2", "Child 2", ctChild1, true, "CustomGroup"); //not assigned to tab contentType.AddPropertyType(new PropertyType(Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { Alias = "umbracoUrlAlias", Name = "AltUrl", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 }); MockedContentTypes.EnsureAllIds(contentType, 6666); //Act var result = Mapper.Map<MediaTypeDisplay>(contentType); //Assert Assert.AreEqual(contentType.Alias, result.Alias); Assert.AreEqual(contentType.Description, result.Description); Assert.AreEqual(contentType.Icon, result.Icon); Assert.AreEqual(contentType.Id, result.Id); Assert.AreEqual(contentType.Name, result.Name); Assert.AreEqual(contentType.ParentId, result.ParentId); Assert.AreEqual(contentType.Path, result.Path); Assert.AreEqual(contentType.Thumbnail, result.Thumbnail); Assert.AreEqual(contentType.IsContainer, result.IsContainer); Assert.AreEqual(contentType.CreateDate, result.CreateDate); Assert.AreEqual(contentType.UpdateDate, result.UpdateDate); // TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(contentType.CompositionPropertyGroups.Select(x => x.Name).Distinct().Count(), result.Groups.Count(x => x.IsGenericProperties == false)); Assert.AreEqual(1, result.Groups.Count(x => x.IsGenericProperties)); Assert.AreEqual(contentType.PropertyGroups.Count(), result.Groups.Count(x => x.Inherited == false && x.IsGenericProperties == false)); var allPropertiesMapped = result.Groups.SelectMany(x => x.Properties).ToArray(); var allPropertyIdsMapped = allPropertiesMapped.Select(x => x.Id).ToArray(); var allSourcePropertyIds = contentType.CompositionPropertyTypes.Select(x => x.Id).ToArray(); Assert.AreEqual(contentType.PropertyTypes.Count(), allPropertiesMapped.Count(x => x.Inherited == false)); Assert.AreEqual(allPropertyIdsMapped.Count(), allSourcePropertyIds.Count()); Assert.IsTrue(allPropertyIdsMapped.ContainsAll(allSourcePropertyIds)); Assert.AreEqual(2, result.Groups.Count(x => x.ParentTabContentTypes.Any())); Assert.IsTrue(result.Groups.SelectMany(x => x.ParentTabContentTypes).ContainsAll(new[] { ctMain.Id, ctChild1.Id })); Assert.AreEqual(contentType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); for (var i = 0; i < contentType.AllowedContentTypes.Count(); i++) { Assert.AreEqual(contentType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i)); } } [Test] public void IContentTypeComposition_To_ContentTypeDisplay() { //Arrange _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(new DataType(new VoidEditor(Mock.Of<ILogger>()))); // setup the mocks to return the data we want to test against... _entityService.Setup(x => x.GetObjectType(It.IsAny<int>())) .Returns(UmbracoObjectTypes.DocumentType); var ctMain = MockedContentTypes.CreateSimpleContentType(); //not assigned to tab ctMain.AddPropertyType(new PropertyType(Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { Alias = "umbracoUrlName", Name = "Slug", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 }); MockedContentTypes.EnsureAllIds(ctMain, 8888); var ctChild1 = MockedContentTypes.CreateSimpleContentType("child1", "Child 1", ctMain, true); ctChild1.AddPropertyType(new PropertyType(Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { Alias = "someProperty", Name = "Some Property", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 }, "Another tab"); MockedContentTypes.EnsureAllIds(ctChild1, 7777); var contentType = MockedContentTypes.CreateSimpleContentType("child2", "Child 2", ctChild1, true, "CustomGroup"); //not assigned to tab contentType.AddPropertyType(new PropertyType(Constants.PropertyEditors.Aliases.TextBox, ValueStorageType.Ntext) { Alias = "umbracoUrlAlias", Name = "AltUrl", Description = "", Mandatory = false, SortOrder = 1, DataTypeId = -88 }); MockedContentTypes.EnsureAllIds(contentType, 6666); //Act var result = Mapper.Map<DocumentTypeDisplay>(contentType); //Assert Assert.AreEqual(contentType.Alias, result.Alias); Assert.AreEqual(contentType.Description, result.Description); Assert.AreEqual(contentType.Icon, result.Icon); Assert.AreEqual(contentType.Id, result.Id); Assert.AreEqual(contentType.Name, result.Name); Assert.AreEqual(contentType.ParentId, result.ParentId); Assert.AreEqual(contentType.Path, result.Path); Assert.AreEqual(contentType.Thumbnail, result.Thumbnail); Assert.AreEqual(contentType.IsContainer, result.IsContainer); Assert.AreEqual(contentType.CreateDate, result.CreateDate); Assert.AreEqual(contentType.UpdateDate, result.UpdateDate); Assert.AreEqual(contentType.DefaultTemplate.Alias, result.DefaultTemplate.Alias); // TODO: Now we need to assert all of the more complicated parts Assert.AreEqual(contentType.CompositionPropertyGroups.Select(x => x.Name).Distinct().Count(), result.Groups.Count(x => x.IsGenericProperties == false)); Assert.AreEqual(1, result.Groups.Count(x => x.IsGenericProperties)); Assert.AreEqual(contentType.PropertyGroups.Count(), result.Groups.Count(x => x.Inherited == false && x.IsGenericProperties == false)); var allPropertiesMapped = result.Groups.SelectMany(x => x.Properties).ToArray(); var allPropertyIdsMapped = allPropertiesMapped.Select(x => x.Id).ToArray(); var allSourcePropertyIds = contentType.CompositionPropertyTypes.Select(x => x.Id).ToArray(); Assert.AreEqual(contentType.PropertyTypes.Count(), allPropertiesMapped.Count(x => x.Inherited == false)); Assert.AreEqual(allPropertyIdsMapped.Count(), allSourcePropertyIds.Count()); Assert.IsTrue(allPropertyIdsMapped.ContainsAll(allSourcePropertyIds)); Assert.AreEqual(2, result.Groups.Count(x => x.ParentTabContentTypes.Any())); Assert.IsTrue(result.Groups.SelectMany(x => x.ParentTabContentTypes).ContainsAll(new[] {ctMain.Id, ctChild1.Id})); Assert.AreEqual(contentType.AllowedTemplates.Count(), result.AllowedTemplates.Count()); for (var i = 0; i < contentType.AllowedTemplates.Count(); i++) { Assert.AreEqual(contentType.AllowedTemplates.ElementAt(i).Id, result.AllowedTemplates.ElementAt(i).Id); } Assert.AreEqual(contentType.AllowedContentTypes.Count(), result.AllowedContentTypes.Count()); for (var i = 0; i < contentType.AllowedContentTypes.Count(); i++) { Assert.AreEqual(contentType.AllowedContentTypes.ElementAt(i).Id.Value, result.AllowedContentTypes.ElementAt(i)); } } [Test] public void MemberPropertyTypeBasic_To_MemberPropertyTypeDisplay() { _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(new DataType(new VoidEditor(Mock.Of<ILogger>()))); var basic = new MemberPropertyTypeBasic() { Id = 33, SortOrder = 1, Alias = "prop1", Description = "property 1", DataTypeId = 99, GroupId = 222, Label = "Prop 1", MemberCanViewProperty = true, MemberCanEditProperty = true, IsSensitiveData = true, Validation = new PropertyTypeValidation() { Mandatory = true, Pattern = "xyz" } }; var result = Mapper.Map<MemberPropertyTypeDisplay>(basic); Assert.AreEqual(basic.Id, result.Id); Assert.AreEqual(basic.SortOrder, result.SortOrder); Assert.AreEqual(basic.Alias, result.Alias); Assert.AreEqual(basic.Description, result.Description); Assert.AreEqual(basic.GroupId, result.GroupId); Assert.AreEqual(basic.Inherited, result.Inherited); Assert.AreEqual(basic.Label, result.Label); Assert.AreEqual(basic.Validation, result.Validation); Assert.AreEqual(basic.MemberCanViewProperty, result.MemberCanViewProperty); Assert.AreEqual(basic.MemberCanEditProperty, result.MemberCanEditProperty); Assert.AreEqual(basic.IsSensitiveData, result.IsSensitiveData); } [Test] public void PropertyTypeBasic_To_PropertyTypeDisplay() { _dataTypeService.Setup(x => x.GetDataType(It.IsAny<int>())) .Returns(new DataType(new VoidEditor(Mock.Of<ILogger>()))); var basic = new PropertyTypeBasic() { Id = 33, SortOrder = 1, Alias = "prop1", Description = "property 1", DataTypeId = 99, GroupId = 222, Label = "Prop 1", Validation = new PropertyTypeValidation() { Mandatory = true, Pattern = "xyz" } }; var result = Mapper.Map<PropertyTypeDisplay>(basic); Assert.AreEqual(basic.Id, result.Id); Assert.AreEqual(basic.SortOrder, result.SortOrder); Assert.AreEqual(basic.Alias, result.Alias); Assert.AreEqual(basic.Description, result.Description); Assert.AreEqual(basic.GroupId, result.GroupId); Assert.AreEqual(basic.Inherited, result.Inherited); Assert.AreEqual(basic.Label, result.Label); Assert.AreEqual(basic.Validation, result.Validation); } private MemberTypeSave CreateMemberTypeSave() { return new MemberTypeSave { Alias = "test", AllowAsRoot = true, AllowedContentTypes = new[] { 666, 667 }, Description = "hello world", Icon = "tree-icon", Id = 1234, Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"), Name = "My content type", Path = "-1,1234", ParentId = -1, Thumbnail = "tree-thumb", IsContainer = true, Groups = new[] { new PropertyGroupBasic<MemberPropertyTypeBasic>() { Id = 987, Name = "Tab 1", SortOrder = 0, Inherited = false, Properties = new[] { new MemberPropertyTypeBasic { MemberCanEditProperty = true, MemberCanViewProperty = true, IsSensitiveData = true, Alias = "property1", Description = "this is property 1", Inherited = false, Label = "Property 1", Validation = new PropertyTypeValidation { Mandatory = false, Pattern = string.Empty }, SortOrder = 0, DataTypeId = 555 } } } } }; } private MediaTypeSave CreateMediaTypeSave() { return new MediaTypeSave { Alias = "test", AllowAsRoot = true, AllowedContentTypes = new[] { 666, 667 }, Description = "hello world", Icon = "tree-icon", Id = 1234, Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"), Name = "My content type", Path = "-1,1234", ParentId = -1, Thumbnail = "tree-thumb", IsContainer = true, Groups = new[] { new PropertyGroupBasic<PropertyTypeBasic>() { Id = 987, Name = "Tab 1", SortOrder = 0, Inherited = false, Properties = new[] { new PropertyTypeBasic { Alias = "property1", Description = "this is property 1", Inherited = false, Label = "Property 1", Validation = new PropertyTypeValidation { Mandatory = false, Pattern = string.Empty }, SortOrder = 0, DataTypeId = 555 } } } } }; } private DocumentTypeSave CreateContentTypeSave() { return new DocumentTypeSave { Alias = "test", AllowAsRoot = true, AllowedTemplates = new [] { "template1", "template2" }, AllowedContentTypes = new [] {666, 667}, DefaultTemplate = "test", Description = "hello world", Icon = "tree-icon", Id = 1234, Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"), Name = "My content type", Path = "-1,1234", ParentId = -1, Thumbnail = "tree-thumb", IsContainer = true, Groups = new [] { new PropertyGroupBasic<PropertyTypeBasic>() { Id = 987, Name = "Tab 1", SortOrder = 0, Inherited = false, Properties = new[] { new PropertyTypeBasic { Alias = "property1", Description = "this is property 1", Inherited = false, Label = "Property 1", Validation = new PropertyTypeValidation { Mandatory = false, Pattern = string.Empty }, SortOrder = 0, DataTypeId = 555 } } } } }; } private MediaTypeSave CreateCompositionMediaTypeSave() { return new MediaTypeSave { Alias = "test", AllowAsRoot = true, AllowedContentTypes = new[] { 666, 667 }, Description = "hello world", Icon = "tree-icon", Id = 1234, Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"), Name = "My content type", Path = "-1,1234", ParentId = -1, Thumbnail = "tree-thumb", IsContainer = true, Groups = new[] { new PropertyGroupBasic<PropertyTypeBasic>() { Id = 987, Name = "Tab 1", SortOrder = 0, Inherited = false, Properties = new[] { new PropertyTypeBasic { Alias = "property1", Description = "this is property 1", Inherited = false, Label = "Property 1", Validation = new PropertyTypeValidation { Mandatory = false, Pattern = string.Empty }, SortOrder = 0, DataTypeId = 555 } } }, new PropertyGroupBasic<PropertyTypeBasic>() { Id = 894, Name = "Tab 2", SortOrder = 0, Inherited = true, Properties = new[] { new PropertyTypeBasic { Alias = "parentProperty", Description = "this is a property from the parent", Inherited = true, Label = "Parent property", Validation = new PropertyTypeValidation { Mandatory = false, Pattern = string.Empty }, SortOrder = 0, DataTypeId = 555 } } } } }; } private DocumentTypeSave CreateCompositionContentTypeSave() { return new DocumentTypeSave { Alias = "test", AllowAsRoot = true, AllowedTemplates = new[] { "template1", "template2" }, AllowedContentTypes = new[] { 666, 667 }, DefaultTemplate = "test", Description = "hello world", Icon = "tree-icon", Id = 1234, Key = new Guid("8A60656B-3866-46AB-824A-48AE85083070"), Name = "My content type", Path = "-1,1234", ParentId = -1, Thumbnail = "tree-thumb", IsContainer = true, Groups = new[] { new PropertyGroupBasic<PropertyTypeBasic>() { Id = 987, Name = "Tab 1", SortOrder = 0, Inherited = false, Properties = new[] { new PropertyTypeBasic { Alias = "property1", Description = "this is property 1", Inherited = false, Label = "Property 1", Validation = new PropertyTypeValidation { Mandatory = false, Pattern = string.Empty }, SortOrder = 0, DataTypeId = 555 } } }, new PropertyGroupBasic<PropertyTypeBasic>() { Id = 894, Name = "Tab 2", SortOrder = 0, Inherited = true, Properties = new[] { new PropertyTypeBasic { Alias = "parentProperty", Description = "this is a property from the parent", Inherited = true, Label = "Parent property", Validation = new PropertyTypeValidation { Mandatory = false, Pattern = string.Empty }, SortOrder = 0, DataTypeId = 555 } } } } }; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Reflection; using System.ServiceModel; using System.ServiceModel.Channels; using Xunit; public class DuplexChannelFactoryTest { [Fact] public static void CreateChannel_EndpointAddress_Null_Throws() { WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callback); NetTcpBinding binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.None; EndpointAddress remoteAddress = null; DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, remoteAddress); try { Assert.Throws<InvalidOperationException>(() => { factory.Open(); factory.CreateChannel(); }); } finally { factory.Abort(); } } [Fact] public static void CreateChannel_InvalidEndpointAddress_AsString_ThrowsUriFormat() { WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callback); Binding binding = new NetTcpBinding(); Assert.Throws<UriFormatException>(() => { DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, "invalid"); }); } [Fact] public static void CreateChannel_EmptyEndpointAddress_AsString_ThrowsUriFormat() { WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callback); Binding binding = new NetTcpBinding(); Assert.Throws<UriFormatException>(() => { DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, string.Empty); }); } [Fact] // valid address, but the scheme is incorrect public static void CreateChannel_ExpectedNetTcpScheme_HttpScheme_ThrowsUriFormat() { WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callback); NetTcpBinding binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.None; Assert.Throws<ArgumentException>("via", () => { DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, "http://not-the-right-scheme"); factory.CreateChannel(); }); } [Fact] // valid address, but the scheme is incorrect public static void CreateChannel_ExpectedNetTcpScheme_InvalidScheme_ThrowsUriFormat() { WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callback); NetTcpBinding binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.None; Assert.Throws<ArgumentException>("via", () => { DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, "qwerty://not-the-right-scheme"); factory.CreateChannel(); }); } [Fact] // valid address, but the scheme is incorrect public static void CreateChannel_BasicHttpBinding_Throws_InvalidOperation() { WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callback); Binding binding = new BasicHttpBinding(BasicHttpSecurityMode.None); // Contract requires Duplex, but Binding 'BasicHttpBinding' doesn't support it or isn't configured properly to support it. var exception = Assert.Throws<InvalidOperationException>(() => { DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, "http://basichttp-not-duplex"); factory.CreateChannel(); }); Assert.True(exception.Message.Contains("BasicHttpBinding"), string.Format("InvalidOperationException exception string should contain 'BasicHttpBinding'. Actual message:\r\n" + exception.ToString())); } [Fact] public static void CreateChannel_Address_NullString_ThrowsArgumentNull() { WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callback); Binding binding = new NetTcpBinding(); Assert.Throws<ArgumentNullException>("uri", () => { DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, (string)null); }); } [Fact] public static void CreateChannel_Address_NullEndpointAddress_ThrowsArgumentNull() { WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callback); Binding binding = new NetTcpBinding(); DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, (EndpointAddress)null); Assert.Throws<InvalidOperationException>(() => { factory.CreateChannel(); }); } [Fact] [ActiveIssue(300)] public static void CreateChannel_Using_NetTcpBinding_Defaults() { WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callback); Binding binding = new NetTcpBinding(); EndpointAddress endpoint = new EndpointAddress("net.tcp://not-an-endpoint"); DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, endpoint); IWcfDuplexService proxy = factory.CreateChannel(); Assert.NotNull(proxy); } [Fact] public static void CreateChannel_Using_NetTcp_NoSecurity() { WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callback); Binding binding = new NetTcpBinding(SecurityMode.None); EndpointAddress endpoint = new EndpointAddress("net.tcp://not-an-endpoint"); DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, endpoint); factory.CreateChannel(); } [Fact] public static void CreateChannel_Using_Http_NoSecurity() { WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callback); Binding binding = new NetHttpBinding(BasicHttpSecurityMode.None); EndpointAddress endpoint = new EndpointAddress(FakeAddress.HttpAddress); DuplexChannelFactory<IWcfDuplexService> factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, endpoint); factory.CreateChannel(); } [Fact] public static void CreateChannel_Of_IDuplexChannel_Using_NetTcpBinding_Creates_Unique_Instances() { DuplexChannelFactory<IWcfDuplexService> factory = null; DuplexChannelFactory<IWcfDuplexService> factory2 = null; IWcfDuplexService channel = null; IWcfDuplexService channel2 = null; WcfDuplexServiceCallback callback = new WcfDuplexServiceCallback(); InstanceContext context = new InstanceContext(callback); try { NetTcpBinding binding = new NetTcpBinding(SecurityMode.None); EndpointAddress endpointAddress = new EndpointAddress(FakeAddress.TcpAddress); // Create the channel factory for the request-reply message exchange pattern. factory = new DuplexChannelFactory<IWcfDuplexService>(context, binding, endpointAddress); factory2 = new DuplexChannelFactory<IWcfDuplexService>(context, binding, endpointAddress); // Create the channel. channel = factory.CreateChannel(); Assert.True(typeof(IWcfDuplexService).GetTypeInfo().IsAssignableFrom(channel.GetType().GetTypeInfo()), String.Format("Channel type '{0}' was not assignable to '{1}'", channel.GetType(), typeof(IDuplexChannel))); channel2 = factory2.CreateChannel(); Assert.True(typeof(IWcfDuplexService).GetTypeInfo().IsAssignableFrom(channel2.GetType().GetTypeInfo()), String.Format("Channel type '{0}' was not assignable to '{1}'", channel2.GetType(), typeof(IDuplexChannel))); // Validate ToString() string toStringResult = channel.ToString(); string toStringExpected = "IWcfDuplexService"; Assert.Equal<string>(toStringExpected, toStringResult); // Validate Equals() Assert.StrictEqual<IWcfDuplexService>(channel, channel); // Validate Equals(other channel) negative Assert.NotStrictEqual<IWcfDuplexService>(channel, channel2); // Validate Equals("other") negative Assert.NotStrictEqual<object>(channel, "other"); // Validate Equals(null) negative Assert.NotStrictEqual<IWcfDuplexService>(channel, null); } finally { if (factory != null) { factory.Close(); } if (factory2 != null) { factory2.Close(); } } } }
using UnityEngine; using System.Collections; [System.Serializable] public class tk2dTextMeshData { public int version = 0; public tk2dFontData font; public string text = ""; public Color color = Color.white; public Color color2 = Color.white; public bool useGradient = false; public int textureGradient = 0; public TextAnchor anchor = TextAnchor.LowerLeft; public int renderLayer = 0; public Vector3 scale = Vector3.one; public bool kerning = false; public int maxChars = 16; public bool inlineStyling = false; public bool formatting = false; public int wordWrapWidth = 0; public float spacing = 0.0f; public float lineSpacing = 0.0f; } [ExecuteInEditMode] [RequireComponent(typeof(MeshFilter))] [RequireComponent(typeof(MeshRenderer))] [AddComponentMenu("2D Toolkit/Text/tk2dTextMesh")] /// <summary> /// Text mesh /// </summary> public class tk2dTextMesh : MonoBehaviour, tk2dRuntime.ISpriteCollectionForceBuild { tk2dFontData _fontInst; string _formattedText = ""; // This stuff now kept in tk2dTextMeshData. Remove in future version. [SerializeField] tk2dFontData _font = null; [SerializeField] string _text = ""; [SerializeField] Color _color = Color.white; [SerializeField] Color _color2 = Color.white; [SerializeField] bool _useGradient = false; [SerializeField] int _textureGradient = 0; [SerializeField] TextAnchor _anchor = TextAnchor.LowerLeft; [SerializeField] Vector3 _scale = new Vector3(1.0f, 1.0f, 1.0f); [SerializeField] bool _kerning = false; [SerializeField] int _maxChars = 16; [SerializeField] bool _inlineStyling = false; [SerializeField] bool _formatting = false; [SerializeField] int _wordWrapWidth = 0; [SerializeField] float spacing = 0.0f; [SerializeField] float lineSpacing = 0.0f; // Holding the data in this struct for the next version [SerializeField] tk2dTextMeshData data = new tk2dTextMeshData(); // Batcher needs to grab this public string FormattedText { get {return _formattedText;} } void UpgradeData() { if (data.version != 1) { data.font = _font; data.text = _text; data.color = _color; data.color2 = _color2; data.useGradient = _useGradient; data.textureGradient = _textureGradient; data.anchor = _anchor; data.scale = _scale; data.kerning = _kerning; data.maxChars = _maxChars; data.inlineStyling = _inlineStyling; data.formatting = _formatting; data.wordWrapWidth = _wordWrapWidth; data.spacing = spacing; data.lineSpacing = lineSpacing; } data.version = 1; } Vector3[] vertices; Vector2[] uvs; Vector2[] uv2; Color32[] colors; Color32[] untintedColors; static int GetInlineStyleCommandLength(int cmdSymbol) { int val = 0; switch (cmdSymbol) { case 'c': val = 5; break; // cRGBA case 'C': val = 9; break; // CRRGGBBAA case 'g': val = 9; break; // gRGBARGBA case 'G': val = 17; break; // GRRGGBBAARRGGBBAA } return val; } /// <summary> /// Formats the string using the current settings, and returns the formatted string. /// You can use this if you need to calculate how many lines your string is going to be wrapped to. /// </summary> public string FormatText(string unformattedString) { string returnValue = ""; FormatText(ref returnValue, unformattedString); return returnValue; } void FormatText() { FormatText(ref _formattedText, data.text); } void FormatText(ref string _targetString, string _source) { InitInstance(); if (formatting == false || wordWrapWidth == 0 || _fontInst.texelSize == Vector2.zero) { _targetString = _source; return; } float lineWidth = _fontInst.texelSize.x * wordWrapWidth; System.Text.StringBuilder target = new System.Text.StringBuilder(_source.Length); float widthSoFar = 0.0f; float wordStart = 0.0f; int targetWordStartIndex = -1; int fmtWordStartIndex = -1; bool ignoreNextCharacter = false; for (int i = 0; i < _source.Length; ++i) { char idx = _source[i]; tk2dFontChar chr; bool inlineHatChar = (idx == '^'); if (_fontInst.useDictionary) { if (!_fontInst.charDict.ContainsKey(idx)) idx = (char)0; chr = _fontInst.charDict[idx]; } else { if (idx >= _fontInst.chars.Length) idx = (char)0; // should be space chr = _fontInst.chars[idx]; } if (inlineHatChar) idx = '^'; if (ignoreNextCharacter) { ignoreNextCharacter = false; continue; } if (data.inlineStyling && idx == '^' && i + 1 < _source.Length) { if (_source[i + 1] == '^') { ignoreNextCharacter = true; target.Append('^'); // add the second hat that we'll skip } else { int cmdLength = GetInlineStyleCommandLength(_source[i + 1]); int skipLength = 1 + cmdLength; // The ^ plus the command for (int j = 0; j < skipLength; ++j) { if (i + j < _source.Length) { target.Append(_source[i + j]); } } i += skipLength - 1; continue; } } if (idx == '\n') { widthSoFar = 0.0f; wordStart = 0.0f; targetWordStartIndex = target.Length; fmtWordStartIndex = i; } else if (idx == ' '/* || idx == '.' || idx == ',' || idx == ':' || idx == ';' || idx == '!'*/) { /*if ((widthSoFar + chr.p1.x * data.scale.x) > lineWidth) { target.Append('\n'); widthSoFar = chr.advance * data.scale.x; } else {*/ widthSoFar += (chr.advance + data.spacing) * data.scale.x; //} wordStart = widthSoFar; targetWordStartIndex = target.Length; fmtWordStartIndex = i; } else { if ((widthSoFar + chr.p1.x * data.scale.x) > lineWidth) { // If the last word started after the start of the line if (wordStart > 0.0f) { wordStart = 0.0f; widthSoFar = 0.0f; // rewind target.Remove(targetWordStartIndex + 1, target.Length - targetWordStartIndex - 1); target.Append('\n'); i = fmtWordStartIndex; continue; // don't add this character } else { target.Append('\n'); widthSoFar = (chr.advance + data.spacing) * data.scale.x; } } else { widthSoFar += (chr.advance + data.spacing) * data.scale.x; } } target.Append(idx); } _targetString = target.ToString(); } [System.FlagsAttribute] enum UpdateFlags { UpdateNone = 0, UpdateText = 1, // update text vertices & uvs UpdateColors = 2, // only colors have changed UpdateBuffers = 4, // update buffers (maxchars has changed) }; UpdateFlags updateFlags = UpdateFlags.UpdateBuffers; Mesh mesh; MeshFilter meshFilter; void SetNeedUpdate(UpdateFlags uf) { if (updateFlags == UpdateFlags.UpdateNone) { updateFlags |= uf; tk2dUpdateManager.QueueCommit(this); } else { // Already queued updateFlags |= uf; } } // accessors /// <summary>Gets or sets the font. Call <see cref="Commit"/> to commit changes.</summary> public tk2dFontData font { get { UpgradeData(); return data.font; } set { UpgradeData(); data.font = value; _fontInst = data.font.inst; SetNeedUpdate( UpdateFlags.UpdateText ); UpdateMaterial(); } } /// <summary>Enables or disables formatting. Call <see cref="Commit"/> to commit changes.</summary> public bool formatting { get { UpgradeData(); return data.formatting; } set { UpgradeData(); if (data.formatting != value) { data.formatting = value; SetNeedUpdate( UpdateFlags.UpdateText ); } } } /// <summary>Change word wrap width. This only works when formatting is enabled. /// Call <see cref="Commit"/> to commit changes.</summary> public int wordWrapWidth { get { UpgradeData(); return data.wordWrapWidth; } set { UpgradeData(); if (data.wordWrapWidth != value) { data.wordWrapWidth = value; SetNeedUpdate(UpdateFlags.UpdateText); } } } /// <summary>Gets or sets the text. Call <see cref="Commit"/> to commit changes.</summary> public string text { get { UpgradeData(); return data.text; } set { UpgradeData(); data.text = value; SetNeedUpdate(UpdateFlags.UpdateText); } } /// <summary>Gets or sets the color. Call <see cref="Commit"/> to commit changes.</summary> public Color color { get { UpgradeData(); return data.color; } set { UpgradeData(); data.color = value; SetNeedUpdate(UpdateFlags.UpdateColors); } } /// <summary>Gets or sets the secondary color (used in the gradient). Call <see cref="Commit"/> to commit changes.</summary> public Color color2 { get { UpgradeData(); return data.color2; } set { UpgradeData(); data.color2 = value; SetNeedUpdate(UpdateFlags.UpdateColors); } } /// <summary>Use vertex vertical gradient. Call <see cref="Commit"/> to commit changes.</summary> public bool useGradient { get { UpgradeData(); return data.useGradient; } set { UpgradeData(); data.useGradient = value; SetNeedUpdate(UpdateFlags.UpdateColors); } } /// <summary>Gets or sets the text anchor. Call <see cref="Commit"/> to commit changes.</summary> public TextAnchor anchor { get { UpgradeData(); return data.anchor; } set { UpgradeData(); data.anchor = value; SetNeedUpdate(UpdateFlags.UpdateText); } } /// <summary>Gets or sets the scale. Call <see cref="Commit"/> to commit changes.</summary> public Vector3 scale { get { UpgradeData(); return data.scale; } set { UpgradeData(); data.scale = value; SetNeedUpdate(UpdateFlags.UpdateText); } } /// <summary>Gets or sets kerning state. Call <see cref="Commit"/> to commit changes.</summary> public bool kerning { get { UpgradeData(); return data.kerning; } set { UpgradeData(); data.kerning = value; SetNeedUpdate(UpdateFlags.UpdateText); } } /// <summary>Gets or sets maxChars. Call <see cref="Commit"/> to commit changes. /// NOTE: This will free & allocate memory, avoid using at runtime. /// </summary> public int maxChars { get { UpgradeData(); return data.maxChars; } set { UpgradeData(); data.maxChars = value; SetNeedUpdate(UpdateFlags.UpdateBuffers); } } /// <summary>Gets or sets the default texture gradient. /// You can also change texture gradient inline by using ^1 - ^9 sequences within your text. /// Call <see cref="Commit"/> to commit changes.</summary> public int textureGradient { get { UpgradeData(); return data.textureGradient; } set { UpgradeData(); data.textureGradient = value % font.gradientCount; SetNeedUpdate(UpdateFlags.UpdateText); } } /// <summary>Enables or disables inline styling (texture gradient). Call <see cref="Commit"/> to commit changes.</summary> public bool inlineStyling { get { UpgradeData(); return data.inlineStyling; } set { UpgradeData(); data.inlineStyling = value; SetNeedUpdate(UpdateFlags.UpdateText); } } /// <summary>Additional spacing between characters. /// This can be negative to bring characters closer together. /// Call <see cref="Commit"/> to commit changes.</summary> public float Spacing { get { UpgradeData(); return data.spacing; } set { UpgradeData(); if (data.spacing != value) { data.spacing = value; SetNeedUpdate(UpdateFlags.UpdateText); } } } /// <summary>Additional line spacing for multieline text. /// This can be negative to bring lines closer together. /// Call <see cref="Commit"/> to commit changes.</summary> public float LineSpacing { get { UpgradeData(); return data.lineSpacing; } set { UpgradeData(); if (data.lineSpacing != value) { data.lineSpacing = value; SetNeedUpdate(UpdateFlags.UpdateText); } } } /// <summary> /// Gets or sets the sorting order /// The sorting order lets you override draw order for sprites which are at the same z position /// It is similar to offsetting in z - the sprite stays at the original position /// This corresponds to the renderer.sortingOrder property in Unity 4.3 /// </summary> public int SortingOrder { get { #if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) return data.renderLayer; #else return CachedRenderer.sortingOrder; #endif } set { #if (UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2) if (data.renderLayer != value) { data.renderLayer = value; SetNeedUpdate(UpdateFlags.UpdateText); } #else if (CachedRenderer.sortingOrder != value) { data.renderLayer = value; // for awake CachedRenderer.sortingOrder = value; #if UNITY_EDITOR UnityEditor.EditorUtility.SetDirty(CachedRenderer); #endif } #endif } } void InitInstance() { if (_fontInst == null && data.font != null) _fontInst = data.font.inst; } Renderer _cachedRenderer = null; Renderer CachedRenderer { get { if (_cachedRenderer == null) { _cachedRenderer = renderer; } return _cachedRenderer; } } // Use this for initialization void Awake() { UpgradeData(); if (data.font != null) _fontInst = data.font.inst; // force rebuild when awakened, for when the object has been pooled, etc // this is probably not the best way to do it updateFlags = UpdateFlags.UpdateBuffers; if (data.font != null) { Init(); UpdateMaterial(); } // Sensibly reset, so tk2dUpdateManager can deal with this properly updateFlags = UpdateFlags.UpdateNone; } protected void OnDestroy() { if (meshFilter == null) { meshFilter = GetComponent<MeshFilter>(); } if (meshFilter != null) { mesh = meshFilter.sharedMesh; } if (mesh) { DestroyImmediate(mesh, true); meshFilter.mesh = null; } } bool useInlineStyling { get { return inlineStyling && _fontInst.textureGradients; } } /// <summary> /// Returns the number of characters drawn for the currently active string. /// This may be less than string.Length - some characters are used as escape codes for switching texture gradient ^0-^9 /// Also, there might be more characters in the string than have been allocated for the textmesh, in which case /// the string will be truncated. /// </summary> public int NumDrawnCharacters() { int charsDrawn = NumTotalCharacters(); if (charsDrawn > data.maxChars) charsDrawn = data.maxChars; return charsDrawn; } /// <summary> /// Returns the number of characters excluding texture gradient escape codes. /// </summary> public int NumTotalCharacters() { InitInstance(); if ((updateFlags & (UpdateFlags.UpdateText | UpdateFlags.UpdateBuffers)) != 0) FormatText(); int numChars = 0; for (int i = 0; i < _formattedText.Length; ++i) { int idx = _formattedText[i]; bool inlineHatChar = (idx == '^'); if (_fontInst.useDictionary) { if (!_fontInst.charDict.ContainsKey(idx)) idx = 0; } else { if (idx >= _fontInst.chars.Length) idx = 0; // should be space } if (inlineHatChar) idx = '^'; if (idx == '\n') { continue; } else if (data.inlineStyling) { if (idx == '^' && i + 1 < _formattedText.Length) { if (_formattedText[i + 1] == '^') { ++i; } else { i += GetInlineStyleCommandLength(_formattedText[i + 1]); continue; } } } ++numChars; } return numChars; } [System.Obsolete("Use GetEstimatedMeshBoundsForString().size instead")] public Vector2 GetMeshDimensionsForString(string str) { return tk2dTextGeomGen.GetMeshDimensionsForString(str, tk2dTextGeomGen.Data( data, _fontInst, _formattedText )); } /// <summary> /// Calculates an estimated bounds for the given string if it were rendered /// using the current settings. /// This expects an unformatted string and will wrap the string if required. /// </summary> public Bounds GetEstimatedMeshBoundsForString( string str ) { InitInstance(); tk2dTextGeomGen.GeomData geomData = tk2dTextGeomGen.Data( data, _fontInst, _formattedText ); Vector2 dims = tk2dTextGeomGen.GetMeshDimensionsForString( FormatText( str ), geomData); float offsetY = tk2dTextGeomGen.GetYAnchorForHeight(dims.y, geomData); float offsetX = tk2dTextGeomGen.GetXAnchorForWidth(dims.x, geomData); float lineHeight = (_fontInst.lineHeight + data.lineSpacing) * data.scale.y; return new Bounds( new Vector3(offsetX + dims.x * 0.5f, offsetY + dims.y * 0.5f + lineHeight, 0), Vector3.Scale(dims, new Vector3(1, -1, 1)) ); } public void Init(bool force) { if (force) { SetNeedUpdate(UpdateFlags.UpdateBuffers); } Init(); } public void Init() { if (_fontInst && ((updateFlags & UpdateFlags.UpdateBuffers) != 0 || mesh == null)) { _fontInst.InitDictionary(); FormatText(); var geomData = tk2dTextGeomGen.Data( data, _fontInst, _formattedText ); // volatile data int numVertices; int numIndices; tk2dTextGeomGen.GetTextMeshGeomDesc(out numVertices, out numIndices, geomData); vertices = new Vector3[numVertices]; uvs = new Vector2[numVertices]; colors = new Color32[numVertices]; untintedColors = new Color32[numVertices]; if (_fontInst.textureGradients) { uv2 = new Vector2[numVertices]; } int[] triangles = new int[numIndices]; int target = tk2dTextGeomGen.SetTextMeshGeom(vertices, uvs, uv2, untintedColors, 0, geomData); if (!_fontInst.isPacked) { Color32 topColor = data.color; Color32 bottomColor = data.useGradient ? data.color2 : data.color; for (int i = 0; i < numVertices; ++i) { Color32 c = ((i % 4) < 2) ? topColor : bottomColor; byte red = (byte)(((int)untintedColors[i].r * (int)c.r) / 255); byte green = (byte)(((int)untintedColors[i].g * (int)c.g) / 255); byte blue = (byte)(((int)untintedColors[i].b * (int)c.b) / 255); byte alpha = (byte)(((int)untintedColors[i].a * (int)c.a) / 255); if (_fontInst.premultipliedAlpha) { red = (byte)(((int)red * (int)alpha) / 255); green = (byte)(((int)green * (int)alpha) / 255); blue = (byte)(((int)blue * (int)alpha) / 255); } colors[i] = new Color32(red, green, blue, alpha); } } else { colors = untintedColors; } tk2dTextGeomGen.SetTextMeshIndices(triangles, 0, 0, geomData, target); if (mesh == null) { if (meshFilter == null) meshFilter = GetComponent<MeshFilter>(); mesh = new Mesh(); mesh.hideFlags = HideFlags.DontSave; meshFilter.mesh = mesh; } else { mesh.Clear(); } mesh.vertices = vertices; mesh.uv = uvs; if (font.textureGradients) { mesh.uv2 = uv2; } mesh.triangles = triangles; mesh.colors32 = colors; mesh.RecalculateBounds(); mesh.bounds = tk2dBaseSprite.AdjustedMeshBounds( mesh.bounds, data.renderLayer ); updateFlags = UpdateFlags.UpdateNone; } } /// <summary> /// Calling commit is no longer required on text meshes. /// You can still call commit to manually commit all changes so far in the frame. /// </summary> public void Commit() { tk2dUpdateManager.FlushQueues(); } // Do not call this, its meant fo internal use public void DoNotUse__CommitInternal() { // Make sure instance is set up, might not be when calling from Awake. InitInstance(); // make sure fonts dictionary is initialized properly before proceeding if (_fontInst == null) { return; } _fontInst.InitDictionary(); // Can come in here without anything initalized when // instantiated in code if ((updateFlags & UpdateFlags.UpdateBuffers) != 0 || mesh == null) { Init(); } else { if ((updateFlags & UpdateFlags.UpdateText) != 0) { FormatText(); var geomData = tk2dTextGeomGen.Data( data, _fontInst, _formattedText ); int target = tk2dTextGeomGen.SetTextMeshGeom(vertices, uvs, uv2, untintedColors, 0, geomData); for (int i = target; i < data.maxChars; ++i) { // was/is unnecessary to fill anything else vertices[i * 4 + 0] = vertices[i * 4 + 1] = vertices[i * 4 + 2] = vertices[i * 4 + 3] = Vector3.zero; } mesh.vertices = vertices; mesh.uv = uvs; if (_fontInst.textureGradients) { mesh.uv2 = uv2; } if (_fontInst.isPacked) { colors = untintedColors; mesh.colors32 = colors; } if (data.inlineStyling) { SetNeedUpdate(UpdateFlags.UpdateColors); } mesh.RecalculateBounds(); mesh.bounds = tk2dBaseSprite.AdjustedMeshBounds( mesh.bounds, data.renderLayer ); } if (!font.isPacked && (updateFlags & UpdateFlags.UpdateColors) != 0) // packed fonts don't support tinting { Color32 topColor = data.color; Color32 bottomColor = data.useGradient ? data.color2 : data.color; for (int i = 0; i < colors.Length; ++i) { Color32 c = ((i % 4) < 2) ? topColor : bottomColor; byte red = (byte)(((int)untintedColors[i].r * (int)c.r) / 255); byte green = (byte)(((int)untintedColors[i].g * (int)c.g) / 255); byte blue = (byte)(((int)untintedColors[i].b * (int)c.b) / 255); byte alpha = (byte)(((int)untintedColors[i].a * (int)c.a) / 255); if (_fontInst.premultipliedAlpha) { red = (byte)(((int)red * (int)alpha) / 255); green = (byte)(((int)green * (int)alpha) / 255); blue = (byte)(((int)blue * (int)alpha) / 255); } colors[i] = new Color32(red, green, blue, alpha); } mesh.colors32 = colors; } } updateFlags = UpdateFlags.UpdateNone; } /// <summary> /// Makes the text mesh pixel perfect to the active camera. /// Automatically detects <see cref="tk2dCamera"/> if present /// Otherwise uses Camera.main /// </summary> public void MakePixelPerfect() { float s = 1.0f; tk2dCamera cam = tk2dCamera.CameraForLayer(gameObject.layer); if (cam != null) { if (_fontInst.version < 1) { Debug.LogError("Need to rebuild font."); } float zdist = (transform.position.z - cam.transform.position.z); float textMeshSize = (_fontInst.invOrthoSize * _fontInst.halfTargetHeight); s = cam.GetSizeAtDistance(zdist) * textMeshSize; } else if (Camera.main) { if (Camera.main.isOrthoGraphic) { s = Camera.main.orthographicSize; } else { float zdist = (transform.position.z - Camera.main.transform.position.z); s = tk2dPixelPerfectHelper.CalculateScaleForPerspectiveCamera(Camera.main.fieldOfView, zdist); } s *= _fontInst.invOrthoSize; } scale = new Vector3(Mathf.Sign(scale.x) * s, Mathf.Sign(scale.y) * s, Mathf.Sign(scale.z) * s); } // tk2dRuntime.ISpriteCollectionEditor public bool UsesSpriteCollection(tk2dSpriteCollectionData spriteCollection) { if (data.font != null && data.font.spriteCollection != null) return data.font.spriteCollection == spriteCollection; // No easy way to identify this at this stage return true; } void UpdateMaterial() { if (renderer.sharedMaterial != _fontInst.materialInst) renderer.material = _fontInst.materialInst; } public void ForceBuild() { if (data.font != null) { _fontInst = data.font.inst; UpdateMaterial(); } Init(true); } #if UNITY_EDITOR void OnDrawGizmos() { if (mesh != null) { Bounds b = mesh.bounds; Gizmos.color = Color.clear; Gizmos.matrix = transform.localToWorldMatrix; Gizmos.DrawCube(b.center, b.extents * 2); Gizmos.matrix = Matrix4x4.identity; Gizmos.color = Color.white; } } #endif }
// <copyright file=Sphere.cs // <copyright> // Copyright (c) 2016, University of Stuttgart // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software), // to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE // OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // </copyright> // <license>MIT License</license> // <main contributors> // Markus Funk, Thomas Kosch, Sven Mayer // </main contributors> // <co-contributors> // Paul Brombosch, Mai El-Komy, Juana Heusler, // Matthias Hoppe, Robert Konrad, Alexander Martin // </co-contributors> // <patent information> // We are aware that this software implements patterns and ideas, // which might be protected by patents in your country. // Example patents in Germany are: // Patent reference number: DE 103 20 557.8 // Patent reference number: DE 10 2013 220 107.9 // Please make sure when using this software not to violate any existing patents in your country. // </patent information> // <date> 11/2/2016 12:25:58 PM</date> using HciLab.Utilities.Mathematics.Core; using System; using System.ComponentModel; using System.Runtime.Serialization; using System.Text.RegularExpressions; namespace HciLab.Utilities.Mathematics.Geometry3D { /// <summary> /// Represents a sphere in 3D space. /// </summary> [Serializable] [TypeConverter(typeof(SphereConverter))] public struct Sphere : ISerializable, ICloneable { #region Private Fields private Vector3 _center; private float _radius; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Sphere"/> class using center and radius values. /// </summary> /// <param name="center">The sphere center point.</param> /// <param name="radius">The sphere radius.</param> public Sphere(Vector3 center, float radius) { _center = center; _radius = radius; } /// <summary> /// Initializes a new instance of the <see cref="Sphere"/> class using values from another sphere instance. /// </summary> /// <param name="sphere">A <see cref="Sphere"/> instance to take values from.</param> public Sphere(Sphere sphere) { _center = sphere.Center; _radius = sphere.Radius; } /// <summary> /// Initializes a new instance of the <see cref="Vector3"/> class with serialized data. /// </summary> /// <param name="info">The object that holds the serialized object data.</param> /// <param name="context">The contextual information about the source or destination.</param> private Sphere(SerializationInfo info, StreamingContext context) { _center = (Vector3)info.GetValue("Center", typeof(Vector3)); _radius = info.GetSingle("Radius"); } #endregion #region Public Properties /// <summary> /// Gets or sets the sphere's center. /// </summary> public Vector3 Center { get { return _center; } set { _center = value;} } /// <summary> /// Gets or sets the sphere's radius. /// </summary> public float Radius { get { return _radius; } set { _radius = value;} } #endregion #region ISerializable Members /// <summary> /// Populates a <see cref="SerializationInfo"/> with the data needed to serialize the target object. /// </summary> /// <param name="info">The <see cref="SerializationInfo"/> to populate with data. </param> /// <param name="context">The destination (see <see cref="StreamingContext"/>) for this serialization.</param> //[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter=true)] public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Center", _center, typeof(Vector3)); info.AddValue("Radius", _radius); } #endregion #region ICloneable Members /// <summary> /// Creates an exact copy of this <see cref="Sphere"/> object. /// </summary> /// <returns>The <see cref="Sphere"/> object this method creates, cast as an object.</returns> object ICloneable.Clone() { return new Sphere(this); } /// <summary> /// Creates an exact copy of this <see cref="Sphere"/> object. /// </summary> /// <returns>The <see cref="Sphere"/> object this method creates.</returns> public Sphere Clone() { return new Sphere(this); } #endregion #region Public Static Parse Methods /// <summary> /// Converts the specified string to its <see cref="Sphere"/> equivalent. /// </summary> /// <param name="s">A string representation of a <see cref="Sphere"/></param> /// <returns>A <see cref="Sphere"/> that represents the vector specified by the <paramref name="s"/> parameter.</returns> public static Sphere Parse(string s) { Regex r = new Regex(@"Sphere\(Center=(?<center>\([^\)]*\)), Radius=(?<radius>.*)\)", RegexOptions.None); Match m = r.Match(s); if (m.Success) { return new Sphere( Vector3.Parse(m.Result("${center}")), float.Parse(m.Result("${radius}")) ); } else { throw new ParseException("Unsuccessful Match."); } } #endregion #region Overrides /// <summary> /// Returns the hashcode for this instance. /// </summary> /// <returns>A 32-bit signed integer hash code.</returns> public override int GetHashCode() { return _center.GetHashCode() ^ _radius.GetHashCode(); } /// <summary> /// Returns a value indicating whether this instance is equal to /// the specified object. /// </summary> /// <param name="obj">An object to compare to this instance.</param> /// <returns><see langword="true"/> if <paramref name="obj"/> is a <see cref="Vector2"/> and has the same values as this instance; otherwise, <see langword="false"/>.</returns> public override bool Equals(object obj) { if(obj is Sphere) { Sphere s = (Sphere)obj; return (_center == s.Center) && (_radius == s.Radius); } return false; } /// <summary> /// Returns a string representation of this object. /// </summary> /// <returns>A string representation of this object.</returns> public override string ToString() { return string.Format( "Sphere(Center={0}, Radius={1})", _center, _radius); } #endregion #region Comparison Operators /// <summary> /// Tests whether two specified spheres are equal. /// </summary> /// <param name="a">The left-hand sphere.</param> /// <param name="b">The right-hand sphere.</param> /// <returns><see langword="true"/> if the two spheres are equal; otherwise, <see langword="false"/>.</returns> public static bool operator==(Sphere a, Sphere b) { return ValueType.Equals(a,b); } /// <summary> /// Tests whether two specified spheres are not equal. /// </summary> /// <param name="a">The left-hand sphere.</param> /// <param name="b">The right-hand sphere.</param> /// <returns><see langword="true"/> if the two spheres are not equal; otherwise, <see langword="false"/>.</returns> public static bool operator!=(Sphere a, Sphere b) { return !ValueType.Equals(a,b); } #endregion } #region SphereConverter class /// <summary> /// Converts a <see cref="Sphere"/> to and from string representation. /// </summary> public class SphereConverter : ExpandableObjectConverter { /// <summary> /// Returns whether this converter can convert an object of the given type to the type of this converter, using the specified context. /// </summary> /// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param> /// <param name="sourceType">A <see cref="Type"/> that represents the type you want to convert from.</param> /// <returns><b>true</b> if this converter can perform the conversion; otherwise, <b>false</b>.</returns> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) return true; return base.CanConvertFrom (context, sourceType); } /// <summary> /// Returns whether this converter can convert the object to the specified type, using the specified context. /// </summary> /// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param> /// <param name="destinationType">A <see cref="Type"/> that represents the type you want to convert to.</param> /// <returns><b>true</b> if this converter can perform the conversion; otherwise, <b>false</b>.</returns> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(string)) return true; return base.CanConvertTo (context, destinationType); } /// <summary> /// Converts the given value object to the specified type, using the specified context and culture information. /// </summary> /// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param> /// <param name="culture">A <see cref="System.Globalization.CultureInfo"/> object. If a null reference (Nothing in Visual Basic) is passed, the current culture is assumed.</param> /// <param name="value">The <see cref="Object"/> to convert.</param> /// <param name="destinationType">The Type to convert the <paramref name="value"/> parameter to.</param> /// <returns>An <see cref="Object"/> that represents the converted value.</returns> public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if ((destinationType == typeof(string)) && (value is Sphere)) { Sphere c = (Sphere)value; return c.ToString(); } return base.ConvertTo (context, culture, value, destinationType); } /// <summary> /// Converts the given object to the type of this converter, using the specified context and culture information. /// </summary> /// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param> /// <param name="culture">The <see cref="System.Globalization.CultureInfo"/> to use as the current culture. </param> /// <param name="value">The <see cref="Object"/> to convert.</param> /// <returns>An <see cref="Object"/> that represents the converted value.</returns> /// <exception cref="ParseException">Failed parsing from string.</exception> public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value.GetType() == typeof(string)) { return Sphere.Parse((string)value); } return base.ConvertFrom (context, culture, value); } } #endregion }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using RRLab.PhysiologyWorkbench.Data; namespace RRLab.PhysiologyWorkbench.GUI { public partial class QuickNotes : UserControl { public event EventHandler ProgramChanged; private PhysiologyWorkbenchProgram _Program; [Bindable(true)] public PhysiologyWorkbenchProgram Program { get { return _Program; } set { if (Program != null && Program.DataManager != null) { Program.DataManager.CurrentRecordingChanged -= new EventHandler(OnRecordingChanged); Program.DataManager.CurrentCellChanged -= new EventHandler(OnCellChanged); } _Program = value; if (Program != null && Program.DataManager != null) { Program.DataManager.CurrentRecordingChanged += new EventHandler(OnRecordingChanged); Program.DataManager.CurrentCellChanged += new EventHandler(OnCellChanged); } OnProgramChanged(EventArgs.Empty); } } protected virtual void OnProgramChanged(EventArgs e) { OnHotkeyManagerChanged(e); OnRecordingChanged(this, e); OnCellChanged(this, e); if (ProgramChanged != null) ProgramChanged(this, EventArgs.Empty); } public AnnotationTarget AnnotationTarget { get { if (CellRadioButton.Checked) return AnnotationTarget.Cell; else return AnnotationTarget.Recording; } } public QuickNotes() { InitializeComponent(); OnRecordingChanged(null, null); } protected virtual void OnHotkeyManagerChanged(EventArgs e) { if (Program != null && Program.HotkeyManager != null) { Program.HotkeyManager.RegisterAction("QuickNote -- Good", new System.Threading.ThreadStart(AddQuickNoteGood)); Program.HotkeyManager.RegisterAction("QuickNote -- Bad", new System.Threading.ThreadStart(AddQuickNoteBad)); Program.HotkeyManager.RegisterAction("QuickNote -- Odd", new System.Threading.ThreadStart(AddQuickNoteOdd)); Program.HotkeyManager.RegisterAction("QuickNote -- Problem", new System.Threading.ThreadStart(AddQuickNoteProblem)); } } protected virtual void OnCellChanged(object sender, EventArgs e) { UpdateControlState(); } protected virtual void OnRecordingChanged(object sender, EventArgs e) { UpdateControlState(); } protected virtual void UpdateControlState() { if (InvokeRequired) { Invoke(new System.Threading.ThreadStart(UpdateControlState)); return; } if (Program == null || Program.DataManager == null) this.Enabled = false; else { this.Enabled = Program.DataManager.CurrentCell != null || Program.DataManager.CurrentRecording != null; CellRadioButton.Enabled = Program.DataManager.CurrentCell != null; RecordingRadioButton.Enabled = Program.DataManager.CurrentRecording != null; if (!RecordingRadioButton.Enabled) CellRadioButton.Checked = true; } } protected virtual void OnClearButtonClicked(object sender, EventArgs e) { if (InvokeRequired) { Invoke(new EventHandler(OnClearButtonClicked), sender, e); return; } NoteTextBox.Clear(); AcceptButton.Enabled = false; ClearButton.Enabled = false; } private void OnAcceptButtonClicked(object sender, EventArgs e) { if (InvokeRequired) { Invoke(new EventHandler(OnAcceptButtonClicked), sender, e); return; } Annotate(NoteTextBox.Text); NoteTextBox.Clear(); AcceptButton.Enabled = false; ClearButton.Enabled = false; } protected virtual void Annotate(string text) { if (AnnotationTarget == AnnotationTarget.Cell) { if (Program == null || Program.DataManager == null || Program.DataManager.CurrentCell == null) return; Program.DataManager.CurrentCell.AddAnnotation(text, Program.User); } else if (AnnotationTarget == AnnotationTarget.Recording) { if (Program == null || Program.DataManager == null || Program.DataManager.CurrentRecording == null) return; Program.DataManager.CurrentRecording.AddAnnotation(text, Program.User); } } protected virtual void OnNoteTextChanged(object sender, EventArgs e) { if (InvokeRequired) { Invoke(new EventHandler(OnNoteTextChanged), sender, e); return; } if (NoteTextBox.Text == "") { AcceptButton.Enabled = false; ClearButton.Enabled = false; } else { AcceptButton.Enabled = true; ClearButton.Enabled = true; } } private void GoodButton_Click(object sender, EventArgs e) { AddQuickNoteGood(); } private void BadButton_Click(object sender, EventArgs e) { AddQuickNoteBad(); } private void OddButton_Click(object sender, EventArgs e) { AddQuickNoteOdd(); } private void ProblemButton_Click(object sender, EventArgs e) { AddQuickNoteProblem(); } public virtual void AddQuickNoteGood() { Annotate("Good"); } public virtual void AddQuickNoteBad() { Annotate("Bad"); } public virtual void AddQuickNoteOdd() { Annotate("Odd"); } public virtual void AddQuickNoteProblem() { Annotate("Problem"); } private void NoteTextBox_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { AcceptButton.PerformClick(); e.Handled = true; } } private void AddButton_Click(object sender, EventArgs e) { AddContextMenuStrip.Show(AddButton, new Point()); } private void uMIonomycinToolStripMenuItem_Click(object sender, EventArgs e) { Annotate("Added 10 uM ionomycin"); } private void mMEGTAToolStripMenuItem_Click(object sender, EventArgs e) { Annotate("Added 20 mM EGTA"); } } public enum AnnotationTarget { Cell, Recording }; }
using System; using System.Runtime.InteropServices; using System.Text; using System.Data; using System.Data.SqlClient; namespace HWD.HWDKernel { public class Utilities { [DllImport( "crypt32.dll", SetLastError=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)] private static extern bool CryptProtectData( ref DATA_BLOB pPlainText, string szDescription, ref DATA_BLOB pEntropy, IntPtr pReserved, ref CRYPTPROTECT_PROMPTSTRUCT pPrompt, int dwFlags, ref DATA_BLOB pCipherText); [DllImport( "crypt32.dll", SetLastError=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)] private static extern bool CryptUnprotectData(ref DATA_BLOB pCipherText, ref string pszDescription, ref DATA_BLOB pEntropy, IntPtr pReserved, ref CRYPTPROTECT_PROMPTSTRUCT pPrompt, int dwFlags, ref DATA_BLOB pPlainText); [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] internal struct DATA_BLOB { public int cbData; public IntPtr pbData; } [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] internal struct CRYPTPROTECT_PROMPTSTRUCT { public int cbSize; public int dwPromptFlags; public IntPtr hwndApp; public string szPrompt; } public enum KeyType {UserKey = 1, MachineKey}; private const int CRYPTPROTECT_UI_FORBIDDEN = 0x1; private const int CRYPTPROTECT_LOCAL_MACHINE = 0x4; private static byte [] Encrypt (byte [] text, KeyType keyType) { if(text==null) text = new byte[0]; DATA_BLOB blobText = new DATA_BLOB(); DATA_BLOB fill = new DATA_BLOB(); DATA_BLOB textEncryptedBlob = new DATA_BLOB(); byte[] cipherTextBytes; try { blobText.pbData = Marshal.AllocHGlobal(text.Length); blobText.cbData = text.Length; Marshal.Copy(text, 0, blobText.pbData, text.Length); byte[] strFill={0}; fill.pbData = Marshal.AllocHGlobal(strFill.Length); fill.cbData = strFill.Length; Marshal.Copy(strFill, 0, fill.pbData, strFill.Length); int flags = CRYPTPROTECT_UI_FORBIDDEN; if (keyType == KeyType.MachineKey) flags |= CRYPTPROTECT_LOCAL_MACHINE; string desc="Password Sql Server"; CRYPTPROTECT_PROMPTSTRUCT ps = new CRYPTPROTECT_PROMPTSTRUCT(); ps.cbSize = Marshal.SizeOf( typeof(CRYPTPROTECT_PROMPTSTRUCT)); ps.dwPromptFlags= 0; ps.hwndApp = IntPtr.Zero ; ps.szPrompt = null; bool success = CryptProtectData(ref blobText, desc, ref fill, IntPtr.Zero, ref ps, flags, ref textEncryptedBlob); cipherTextBytes = new byte[textEncryptedBlob.cbData]; Marshal.Copy(textEncryptedBlob.pbData, cipherTextBytes, 0, textEncryptedBlob.cbData); } catch { throw new Exception("Can not Decryp Message"); } finally { if(textEncryptedBlob.pbData!=IntPtr.Zero) Marshal.FreeHGlobal (textEncryptedBlob.pbData); if(blobText.pbData!=IntPtr.Zero) Marshal.FreeHGlobal (blobText.pbData); if(fill.pbData!=IntPtr.Zero) Marshal.FreeHGlobal (fill.pbData); } return cipherTextBytes; } public static string Encrypt(string text, KeyType keyType) { return Convert.ToBase64String( Encrypt(Encoding.UTF8.GetBytes(text), keyType) ); } public static string Decrypt(string encryptedText) { return Encoding.UTF8.GetString( Decrypt( Convert.FromBase64String(encryptedText) )); } public static byte[] Decrypt( byte[] encryptedText ) { if(encryptedText==null) encryptedText = new byte[0]; DATA_BLOB plainTextBlob = new DATA_BLOB(); DATA_BLOB cipherTextBlob = new DATA_BLOB(); DATA_BLOB fill = new DATA_BLOB(); byte[] plainTextBytes; try { cipherTextBlob.pbData = Marshal.AllocHGlobal(encryptedText.Length); cipherTextBlob.cbData = encryptedText.Length; Marshal.Copy(encryptedText, 0, cipherTextBlob.pbData, encryptedText.Length); byte[] strFill={0}; fill.pbData = Marshal.AllocHGlobal(strFill.Length); fill.cbData = strFill.Length; Marshal.Copy(strFill, 0, fill.pbData, strFill.Length); CRYPTPROTECT_PROMPTSTRUCT ps = new CRYPTPROTECT_PROMPTSTRUCT(); ps.cbSize = Marshal.SizeOf( typeof(CRYPTPROTECT_PROMPTSTRUCT)); ps.dwPromptFlags= 0; ps.hwndApp = IntPtr.Zero ; ps.szPrompt = null; string description = String.Empty; int flags = CRYPTPROTECT_UI_FORBIDDEN; bool success = CryptUnprotectData(ref cipherTextBlob, ref description, ref fill, IntPtr.Zero, ref ps, flags, ref plainTextBlob); plainTextBytes = new byte[plainTextBlob.cbData]; Marshal.Copy(plainTextBlob.pbData, plainTextBytes, 0, plainTextBlob.cbData); } catch { throw new Exception("Can not decrypy message"); } finally { if (plainTextBlob.pbData !=IntPtr.Zero) Marshal.FreeHGlobal(plainTextBlob.pbData); if (cipherTextBlob.pbData !=IntPtr.Zero) Marshal.FreeHGlobal(cipherTextBlob.pbData); if (fill.pbData !=IntPtr.Zero) Marshal.FreeHGlobal(fill.pbData); } return plainTextBytes; } public static void ChecaTablas(SqlConnection conn) { StringBuilder sb = new StringBuilder(); SqlCommand comm; comm = new SqlCommand(); comm.Connection = conn; try { comm.CommandText ="Select 1 from hwd"; comm.ExecuteNonQuery(); } catch { sb.Append("CREATE TABLE [HWD] (\r\n"); sb.Append(" [ID] [int] IDENTITY (1, 1) NOT NULL ,\r\n"); sb.Append(" [ComputerName] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,\r\n"); sb.Append(" [OS] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,\r\n"); sb.Append(" [Username] [nvarchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,\r\n"); sb.Append(" [Manufacturer] [nvarchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,\r\n"); sb.Append(" [Model] [nvarchar] (30) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,\r\n"); sb.Append(" [SerialNumber] [nvarchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,\r\n"); sb.Append(" [RAM] [nvarchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,\r\n"); sb.Append(" [Processor] [nvarchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,\r\n"); sb.Append(" [IDKind] [int] NULL ,\r\n"); sb.Append(" [IDLocation] [int] NULL ,\r\n"); sb.Append(" [Status] [bit] NULL CONSTRAINT [DF_HWD_Status] DEFAULT (1),\r\n"); sb.Append(" [Notes] [nvarchar] (255) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,\r\n"); sb.Append(" CONSTRAINT [PK_HWD] PRIMARY KEY CLUSTERED \r\n"); sb.Append(" (\r\n"); sb.Append(" [ComputerName]\r\n"); sb.Append(" ) ON [PRIMARY] \r\n"); sb.Append(") ON [PRIMARY]\r\n"); comm.CommandText = sb.ToString(); comm.ExecuteNonQuery(); } sb=new StringBuilder(""); try { comm.CommandText ="Select 1 from kwd"; comm.ExecuteNonQuery(); } catch { sb.Append("CREATE TABLE [KWD] (\r\n"); sb.Append(" [IDKind] [int] IDENTITY (1, 1) NOT NULL ,\r\n"); sb.Append(" [KindName] [nvarchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,\r\n"); sb.Append(" CONSTRAINT [PK_KWD] PRIMARY KEY CLUSTERED \r\n"); sb.Append(" (\r\n"); sb.Append(" [IDKind]\r\n"); sb.Append(" ) ON [PRIMARY] \r\n"); sb.Append(") ON [PRIMARY]\r\n"); comm.CommandText = sb.ToString(); comm.ExecuteNonQuery(); } sb=new StringBuilder(""); try { comm.CommandText ="Select 1 from lwd"; comm.ExecuteNonQuery(); } catch { sb.Append("CREATE TABLE [LWD] (\r\n"); sb.Append(" [IDLocation] [int] IDENTITY (1, 1) NOT NULL ,\r\n"); sb.Append(" [LocationName] [nvarchar] (20) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,\r\n"); sb.Append(" CONSTRAINT [PK_LWD] PRIMARY KEY CLUSTERED \r\n"); sb.Append(" (\r\n"); sb.Append(" [IDLocation]\r\n"); sb.Append(" ) ON [PRIMARY] \r\n"); sb.Append(") ON [PRIMARY]\r\n"); comm.CommandText = sb.ToString(); comm.ExecuteNonQuery(); } } } public class Handler { private bool isComplete = false; private System.Management.ManagementBaseObject returnObject; public void Done(object sender, System.Management.ObjectReadyEventArgs e) { isComplete = true; returnObject = e.NewObject; } public bool IsComplete { get { return isComplete; } } public System.Management.ManagementBaseObject ReturnObject { get { return returnObject; } } } }
#region File Description //----------------------------------------------------------------------------- // ScoreBar.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.Graphics; #endregion namespace HoneycombRush { /// <summary> /// Used by other components to display their status. /// </summary> public class ScoreBar : DrawableGameComponent { #region Enums /// <summary> /// Used to determine the component's orientation. /// </summary> public enum ScoreBarOrientation { Vertical, Horizontal } #endregion #region Fields/Properties public int MinValue { get; set; } public int MaxValue { get; set; } public Vector2 Position { get; set; } public Color ScoreBarColor { get; set; } public int CurrentValue { get { return currentValue; } } ScoreBarOrientation scoreBarOrientation; int height; int width; ScaledSpriteBatch scaledSpriteBatch; int currentValue; Texture2D backgroundTexture; Texture2D redTexture; Texture2D greenTexture; Texture2D yellowTexture; GameplayScreen gameplayScreen; bool isAppearAtCountDown; #endregion #region Initialization /// <summary> /// Creates a new score bar instance. /// </summary> /// <param name="game">The associated game object.</param> /// <param name="minValue">The score bar's minimal value.</param> /// <param name="maxValue">The score bar's maximal value.</param> /// <param name="position">The score bar's position.</param> /// <param name="height">The score bar's height.</param> /// <param name="width">The score bar's width.</param> /// <param name="scoreBarColor">Color to tint the scorebar's background with.</param> /// <param name="scoreBarOrientation">The score bar's orientation.</param> /// <param name="initialValue">The score bar's initial value.</param> /// <param name="screen">Gameplay screen where the score bar will appear.</param> /// <param name="isAppearAtCountDown">Whether or not the score bar will appear during the game's initial /// countdown phase.</param> public ScoreBar(Game game, int minValue, int maxValue, Vector2 position, int height, int width, Color scoreBarColor, ScoreBarOrientation scoreBarOrientation, int initialValue, GameplayScreen screen, bool isAppearAtCountDown) : base(game) { this.MinValue = minValue; this.MaxValue = maxValue; this.Position = position; this.ScoreBarColor = scoreBarColor; this.scoreBarOrientation = scoreBarOrientation; this.currentValue = initialValue; this.width = width; this.height = height; this.gameplayScreen = screen; this.isAppearAtCountDown = isAppearAtCountDown; scaledSpriteBatch = (ScaledSpriteBatch)Game.Services.GetService(typeof(ScaledSpriteBatch)); GetSpaceFromBorder(); } /// <summary> /// Loads the content that this component will use. /// </summary> protected override void LoadContent() { backgroundTexture = Game.Content.Load<Texture2D>("Textures/barBlackBorder"); greenTexture = Game.Content.Load<Texture2D>("Textures/barGreen"); yellowTexture = Game.Content.Load<Texture2D>("Textures/barYellow"); redTexture = Game.Content.Load<Texture2D>("Textures/barRed"); base.LoadContent(); } #endregion #region Render /// <summary> /// Draws the component. /// </summary> /// <param name="gameTime"></param> public override void Draw(GameTime gameTime) { if (!gameplayScreen.IsActive) { base.Draw(gameTime); return; } if (!isAppearAtCountDown && !gameplayScreen.IsStarted) { base.Draw(gameTime); return; } float rotation; // Determine the orientation of the component if (scoreBarOrientation == ScoreBar.ScoreBarOrientation.Horizontal) { rotation = 0f; } else { rotation = 1.57f; } scaledSpriteBatch.Begin(); // Draws the background of the score bar scaledSpriteBatch.Draw(backgroundTexture, new Rectangle((int)Position.X, (int)Position.Y, width, height), null, ScoreBarColor, rotation, new Vector2(0, 0), SpriteEffects.None, 0); // Gets the margin from the border decimal spaceFromBorder = GetSpaceFromBorder(); spaceFromBorder += 4; Texture2D coloredTexture = GetTextureByCurrentValue(currentValue); if (scoreBarOrientation == ScoreBarOrientation.Horizontal) { scaledSpriteBatch.Draw(coloredTexture, new Rectangle((int)Position.X + 2, (int)Position.Y + 2, width - (int)spaceFromBorder, height - 4), null, Color.White, rotation, new Vector2(0, 0), SpriteEffects.None, 0); } else { scaledSpriteBatch.Draw(coloredTexture, new Rectangle((int)Position.X + 2 - height, (int)Position.Y + width + -2, width - (int)spaceFromBorder, height - 4), null, ScoreBarColor, -rotation, new Vector2(0, 0), SpriteEffects.None, 0); } scaledSpriteBatch.End(); base.Draw(gameTime); } #endregion #region Public Methods /// <summary> /// Increases the current value of the score bar. /// </summary> /// <param name="valueToIncrease">Number to increase the value by</param> /// <remarks>Negative numbers will have no effect.</remarks> public void IncreaseCurrentValue(int valueToIncrease) { // Make sure that the target value does not exceed the max value if (valueToIncrease >= 0 && currentValue < MaxValue && currentValue + valueToIncrease <= MaxValue) { currentValue += valueToIncrease; } // If the target value exceeds the max value, clamp the value to the maximum else if (currentValue + valueToIncrease > MaxValue) { currentValue = MaxValue; } } /// <summary> /// Decreases the current value of the score bar. /// </summary> /// <param name="valueToDecrease">Number to decrease the value by.</param> public void DecreaseCurrentValue(int valueToDecrease) { DecreaseCurrentValue(valueToDecrease, false); } /// <summary> /// Decreases the current value of the score bar. /// </summary> /// <param name="valueToDecrease">Number to decrease the value by.</param> /// <param name="clampToMinimum">If true, then decreasing by an amount which will cause the bar's value /// to go under its minimum will set the bar to its minimal value. If false, performing such an operation /// as just described will leave the bar's value unchanged.</param> /// <returns>The actual amount which was subtracted from the bar's value.</returns> public int DecreaseCurrentValue(int valueToDecrease, bool clampToMinimum) { // Make sure that the target value does not exceed the min value int valueThatWasDecreased = 0; if (valueToDecrease >= 0 && currentValue > MinValue && currentValue - valueToDecrease >= MinValue) { currentValue -= valueToDecrease; valueThatWasDecreased = valueToDecrease; } // If the target value exceeds the min value, clamp the value to the minimum (or do nothing) else if (currentValue - valueToDecrease < MinValue && clampToMinimum) { valueThatWasDecreased = currentValue - MinValue; currentValue = MinValue; } return valueThatWasDecreased; } #endregion #region Private Methods /// <summary> /// Calculate the empty portion of the score bar according to its current value. /// </summary> /// <returns>Width of the bar portion which should be empty to represent the bar's current score.</returns> private decimal GetSpaceFromBorder() { int textureSize; textureSize = width; decimal valuePercent = Decimal.Divide(currentValue, MaxValue) * 100; return textureSize - ((decimal)textureSize * valuePercent / (decimal)100); } /// <summary> /// Returns a texture for the score bar's "fill" according to its value. /// </summary> /// <param name="value">Current value of the score bar.</param> /// <returns>A texture the color of which indicates how close to the bar's maximum the value is.</returns> private Texture2D GetTextureByCurrentValue(int value) { Texture2D selectedTexture; decimal valuePercent = Decimal.Divide(currentValue, MaxValue) * 100; if (valuePercent > 50) { selectedTexture = greenTexture; } else if (valuePercent > 25) { selectedTexture = yellowTexture; } else { selectedTexture = redTexture; } return selectedTexture; } #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. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// RouteTablesOperations operations. /// </summary> public partial interface IRouteTablesOperations { /// <summary> /// Deletes 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='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, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets 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='expand'> /// Expands referenced resources. /// </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<RouteTable>> GetWithHttpMessagesAsync(string resourceGroupName, string routeTableName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Create or updates a route table in a specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update route table 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<RouteTable>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, RouteTable parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all route tables in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </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<RouteTable>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all route tables in a subscription. /// </summary> /// <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<RouteTable>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes 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='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, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Create or updates a route table in a specified resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='routeTableName'> /// The name of the route table. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update route table 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<RouteTable>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string routeTableName, RouteTable parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all route tables in a resource group. /// </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<RouteTable>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all route tables in a subscription. /// </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<RouteTable>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
namespace Abacus { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; using BF = System.Reflection.BindingFlags; using static System.Convert; using static System.Console; using static System.Linq.Expressions.Expression; using static System.Double; using static System.String; using static Abacus.Error; using static Abacus.Assert; using static Abacus.Utils; //TODO: Explore different way to handle syntax errors. I think // for this particular component throwing exceptions // is not an option (performance wise). public class SyntaxWalker { static readonly Type WALKER_TYPE = typeof(SyntaxWalker); static readonly Type INTER_TYPE = typeof(Interpreter); static readonly CultureInfo DATE_CI = CultureInfo.InvariantCulture; const string DATE_FMT = "yyyy-MM-dd"; static readonly BF STAPRIVATE = BF.Static | BF.NonPublic | BF.InvokeMethod | BF.DeclaredOnly; static readonly BF INSTAPUB = BF.Instance | BF.Public | BF.InvokeMethod | BF.IgnoreCase; static readonly BF INSTAPRIVATE = BF.Instance | BF.NonPublic | BF.InvokeMethod | BF.IgnoreCase; // static readonly BF PRIVATE = // BF.Instance | BF.NonPublic | BF.InvokeMethod | BF.DeclaredOnly; static readonly MethodInfo IN = WALKER_TYPE.GetMethod( "__In", STAPRIVATE); static readonly MethodInfo LET = WALKER_TYPE.GetMethod( "__Let", STAPRIVATE); static readonly MethodInfo POW = WALKER_TYPE.GetMethod( "__Pow", STAPRIVATE); static readonly MethodInfo TRUNC = WALKER_TYPE.GetMethod( "__Trunc", STAPRIVATE); static readonly MethodInfo CMP = WALKER_TYPE.GetMethod( "__Cmp", STAPRIVATE); static readonly MethodInfo ADDDAT = WALKER_TYPE.GetMethod( "__AddDat", STAPRIVATE); static readonly MethodInfo SUBDAT = WALKER_TYPE.GetMethod( "__SubDat", STAPRIVATE); static readonly MethodInfo TOB = WALKER_TYPE.GetMethod( "__ToBln", STAPRIVATE); static readonly MethodInfo GET = WALKER_TYPE.GetMethod( "__GetLocal", STAPRIVATE); static readonly MethodInfo DISP = INTER_TYPE.GetMethod( "__Dispatch", STAPRIVATE, null, new [] { typeof(object), typeof(string), typeof(object[]) }, null); static readonly Expression MINUSONE = Constant(-1), ZERO = Constant(0), ONE = Constant(1); // Compiled function's arguments. ParameterExpression _localNames, _locals; /// Code generation entry point. public Func<string[], object[], object> Compile(SyntaxTree tree) { _localNames = Parameter(typeof(string[]), "localNames"); _locals = Parameter(typeof(object[]), "locals"); var program = Walk(tree); var lambda = Lambda<Func<string[], object[], object>>( program, new [] { _localNames, _locals }); PrintLinqTree(lambda); return lambda.Compile(); } // Version simplificada del walk, accedo al parametro directamente. public Expression Walk(SyntaxTree rootNode) { var childs = rootNode.GetChilds(); var body = new Expression[childs.Length]; for(int i = 0; i < childs.Length; ++i) { body[i] = childs[i].Accept(this); } int last = body.Length-1; if (body[last].Type != typeof(object)) body[last] = Convert(body[last], typeof(object)); return Block(body); } public Expression Walk(GetLocal expr) { return Call(null, GET, Constant(expr.Name), _localNames, _locals); } public Expression Walk(FuncCall fn) { Expression reciever = Constant(null); if (fn.Target != null) reciever = fn.Target.Accept(this); Expression[] args = new Expression[0]; Type[] argsTypes = new Type[0]; if (fn.Argv != null && fn.Argv.Length > 0) { args = new Expression[fn.Argv.Length]; argsTypes = new Type[args.Length]; Expression a; for(int i = 0; i < fn.Argv.Length; ++i) { a = fn.Argv[i].Accept(this); argsTypes[i] = a.Type; args[i] = a; } } DbgPrint(ArrToStr(args)); // Can we get the method's meta from target at compile time? // If so, use a std linq instance method call. if (reciever != null) { MethodInfo mi; if (TryGetMethod(reciever.Type, fn.FuncName, argsTypes, out mi)) return Call(reciever, mi, args); } // If we can't get method's meta at compile time, we just use // the generic dispatch mecanism. (Which is slower, but has access // to actual runtime types). for (int i= 0; i < args.Length; ++i) { if (args[i].Type != typeof(object)) args[i] = Convert(args[i], typeof(object)); } var argv = NewArrayInit(typeof(object), args); //Global function. var call = Call(null, DISP, reciever, Constant(fn.FuncName), argv); // Special case to support expressions like: // today + 1 // today - 1 if (fn.FuncName == "dat") return Convert(call, typeof(DateTime)); return call; } public static bool TryGetMethod( Type recieverType, string fnName, Type[] argstypes, out MethodInfo mi) { DbgPrint($"Looking for {fnName} ({ArrToStr(argstypes)})" + $" on {recieverType}"); mi = recieverType.GetMethod(fnName, INSTAPUB, null, argstypes, null); if (mi == null) { // maybe is a property getter, setter. if (fnName.StartsWith("get_") && argstypes.Length == 0) { mi = recieverType.GetMethod( fnName, INSTAPRIVATE, null, argstypes, null); } else if (fnName.StartsWith("set_") && argstypes.Length == 1) { mi = recieverType.GetMethod( fnName, INSTAPRIVATE, null, argstypes, null); } } return mi != null; } public Expression Walk(LetExpression expr) { var name = Constant(expr.Name); var val = expr.Val.Accept(this); return Call(null, LET, name, Obj(val)); } public Expression Walk(InExpression expr) { var item = expr.Item.Accept(this); var opts = expr.Opts.Accept(this); return Call(null, IN, Obj(item), Obj(opts)); } public Expression Walk(ArrayExpression arr) { var items = new Expression[arr.Items.Length]; for(int i=0; i < arr.Items.Length; ++i) { items[i] = Obj(arr.Items[i].Accept(this)); } return Expression.NewArrayInit(typeof(object), items); } public Expression Walk(UnaryExpression expr) { var val = expr.Expr.Accept(this); if (expr.Op == Operator.Neg) return Negate(val); return val; } public Expression Walk(ParenExpression pe) => pe.Expr.Accept(this); public Expression Walk(Const expr) => Constant(expr.Val, expr.Type); public Expression Walk(BinExpression expr) { var op = expr.Op; var lhs = expr.Lhs.Accept(this); var rhs = expr.Rhs.Accept(this); rhs = Dbl(rhs); /// Special cases to suppor expressions /// like this: /// now + 1 => tomorow. /// now - 1 => yesterday. if (lhs.Type == typeof(DateTime)) { if (op == Operator.Add) return Call(null, ADDDAT, lhs, rhs); if (op == Operator.Sub) return Call(null, SUBDAT, lhs, rhs); } lhs = Dbl(lhs); switch(op) { case Operator.Add: return Add(lhs, rhs); case Operator.Sub: return Subtract(lhs, rhs); case Operator.Multiply: return Multiply(lhs, rhs); case Operator.Divide: return Divide(lhs, rhs); case Operator.Modulo: return Modulo(lhs, rhs); case Operator.FloorDiv: return Floor(lhs, rhs); case Operator.Pow: return Pow(lhs, rhs); default: break; } ReportUnkwnowBinaryOp(op); return null; } public Expression Walk(EqualExpression expr) => Equal(CallCmp(expr.Lhs, expr.Rhs), ZERO); public Expression Walk(NotEqualExpression expr) => NotEqual(CallCmp(expr.Lhs, expr.Rhs), ZERO); public Expression Walk(LessThanExpression expr) => Equal(CallCmp(expr.Lhs, expr.Rhs), MINUSONE); public Expression Walk(LessThanEqExpression expr) => LessThan(CallCmp(expr.Lhs, expr.Rhs), ONE); public Expression Walk(GreaterThanExpression expr) => Equal(CallCmp(expr.Lhs, expr.Rhs), ONE); public Expression Walk(GreaterThanEqExpression expr) => GreaterThan(CallCmp(expr.Lhs, expr.Rhs), MINUSONE); public Expression Walk(AndExpression expr) => And(Bln(expr.Lhs.Accept(this)), Bln(expr.Rhs.Accept(this))); public Expression Walk(OrExpression expr) => Or(Bln(expr.Lhs.Accept(this)), Bln(expr.Rhs.Accept(this))); public Expression Walk(NotExpression expr) => Not(Bln(expr.Expr.Accept(this))); //RUNTIME HELPERS {{{ static double __Pow(double num, double pow) => Math.Pow(num, pow); static double __Trunc(double num, double div) => Math.Truncate(num/div); static bool __In(object item, object opts) { var @enum = opts as IEnumerable; DieIf(@enum == null, "opts must be enumerable"); var e = @enum.GetEnumerator(); while(e.MoveNext()) { if (item == null && e.Current == null) return true; if (item != null && item.Equals(e.Current)) return true; } // opts must be enumerable return false; } static object __Let(string name, object val) { //TODO: add local to session. // update parser locals from session. return null; } static object __GetLocal( string name, string[] localNames, object[] locals) { // Be careful, _localNames and GetLocals must be in sync with // eachother. DbgPrint($"==> get { name }"); DbgPrint($"==> localNames { ArrToStr(localNames) }"); DbgPrint($"==> locals { ArrToStr(locals) }"); var idx = Array.IndexOf(localNames, name); if (idx > -1) { #if DEBUG if (idx >= locals.Length) Die("_localNames and _locals out of sync."); return locals[idx]; #else return locals[idx]; #endif } #if DEBUG Die($"walker => undefined local {name}"); #endif // Undefined variable. return Interpreter.ERRNAME; } static bool __ToBln(object obj) { if (obj == null) return false; if (obj is bool) return (bool)obj; if (obj is string) return !IsNullOrEmpty((string)obj); if (obj is DateTime) obj = ((DateTime)obj).ToOADate(); return ToBoolean(obj); } static DateTime __AddDat(DateTime date, double days) => date.AddDays(days).Date; static DateTime __SubDat(DateTime date, double days) => date.AddDays(days * -1).Date; //TODO: Add strict comparison (something like JS). static int __Cmp(object lhs, object rhs) { DbgPrintCmp(lhs, rhs); if (lhs is DBNull) return rhs is DBNull ? 0 : -1; if (rhs is DBNull) return lhs is DBNull ? 0 : 1; // As of now, strings are the only "special case" for comparisons, // all the other types are converted to number and then compared // to each other. // (This may have to change if we extend the abaucs type system. // i.e. objects, arrays, etc....). if (lhs is string) { if ( (rhs == null) || (rhs is bool && !((bool)rhs)) || (rhs is double && (((double)rhs) ==0 || IsNaN((double)rhs))) ) { rhs = ""; } var lstr = (string)lhs; if (IsNullOrEmpty(lstr)) lstr = ""; return string.Compare(lstr, rhs?.ToString()); } // =============================================================== if (lhs is DateTime) { lhs = ((DateTime)lhs).ToOADate(); if (rhs is string) { //<- cmp date, date(str)) rhs = ConvertUtils.Str2Date((string) rhs, DATE_FMT, DATE_CI); } } if (rhs is DateTime) rhs = ((DateTime)rhs).ToOADate(); if (rhs is string && IsNullOrEmpty((string)rhs)) rhs = 0d; // Are we going to support multiple cultures? // If so, we must to take that into account when converting values. double lhd = ToDouble(lhs); double rhd = ToDouble(rhs); //NaN are also special cases. For comparison purposses //zero and NaN are the same thing. if (IsNaN(lhd) && rhd == 0d) return 0; if (IsNaN(rhd) && lhd == 0d) return 0; // ====================================== return lhd == rhd ? 0 : lhd < rhd ? -1 : 1; } [Conditional("DEBUG")] static void DbgPrintCmp(object lhs, object rhs) { WriteLine("========= cmp ========"); WriteLine($"lhs: {lhs}({lhs?.GetType()})"); WriteLine($"rhs: {rhs}({rhs?.GetType()})"); WriteLine("======================"); } //}}} // COMPILE TIME HELPERS {{{ // /// Converts an expression to double. If the /// expression's type is double already, returns /// the expression as is. Expression Dbl(Expression expr) => (expr.Type != typeof(double)) ? Convert(expr, typeof(double)) : expr; Expression Obj(Expression expr) => (expr.Type != typeof(object)) ? Convert(expr, typeof(object)) : expr; Expression Bln(Expression expr) => (expr.Type != typeof(bool)) ? Call(null, TOB, Obj(expr)) : expr; Expression CallCmp(SyntaxNode lhs, SyntaxNode rhs) => Call(null, CMP, Obj(lhs.Accept(this)), Obj(rhs.Accept(this))); /// Helper method to emulate the pow operator. Expression Pow(Expression num, Expression pow) => Call(null, POW, Dbl(num), Dbl(pow)); Expression Floor(Expression lhs, Expression rhs) => Call(null, TRUNC, Dbl(lhs), Dbl(rhs)); Expression Cmp(Expression lhs, Expression rhs) => Call(null, CMP, lhs, rhs); void ReportUnkwnowBinaryOp(Operator op) { Die($"Unknown binary operator {op}"); } //}}} } }
using System; using System.Data; using Csla; using Csla.Data; using SelfLoad.DataAccess; using SelfLoad.DataAccess.ERLevel; namespace SelfLoad.Business.ERLevel { /// <summary> /// C03_SubContinentColl (editable child list).<br/> /// This is a generated base class of <see cref="C03_SubContinentColl"/> business object. /// </summary> /// <remarks> /// This class is child of <see cref="C02_Continent"/> editable root object.<br/> /// The items of the collection are <see cref="C04_SubContinent"/> objects. /// </remarks> [Serializable] public partial class C03_SubContinentColl : BusinessListBase<C03_SubContinentColl, C04_SubContinent> { #region Collection Business Methods /// <summary> /// Removes a <see cref="C04_SubContinent"/> item from the collection. /// </summary> /// <param name="subContinent_ID">The SubContinent_ID of the item to be removed.</param> public void Remove(int subContinent_ID) { foreach (var c04_SubContinent in this) { if (c04_SubContinent.SubContinent_ID == subContinent_ID) { Remove(c04_SubContinent); break; } } } /// <summary> /// Determines whether a <see cref="C04_SubContinent"/> item is in the collection. /// </summary> /// <param name="subContinent_ID">The SubContinent_ID of the item to search for.</param> /// <returns><c>true</c> if the C04_SubContinent is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int subContinent_ID) { foreach (var c04_SubContinent in this) { if (c04_SubContinent.SubContinent_ID == subContinent_ID) { return true; } } return false; } /// <summary> /// Determines whether a <see cref="C04_SubContinent"/> item is in the collection's DeletedList. /// </summary> /// <param name="subContinent_ID">The SubContinent_ID of the item to search for.</param> /// <returns><c>true</c> if the C04_SubContinent is a deleted collection item; otherwise, <c>false</c>.</returns> public bool ContainsDeleted(int subContinent_ID) { foreach (var c04_SubContinent in DeletedList) { if (c04_SubContinent.SubContinent_ID == subContinent_ID) { return true; } } return false; } #endregion #region Find Methods /// <summary> /// Finds a <see cref="C04_SubContinent"/> item of the <see cref="C03_SubContinentColl"/> collection, based on a given SubContinent_ID. /// </summary> /// <param name="subContinent_ID">The SubContinent_ID.</param> /// <returns>A <see cref="C04_SubContinent"/> object.</returns> public C04_SubContinent FindC04_SubContinentBySubContinent_ID(int subContinent_ID) { for (var i = 0; i < this.Count; i++) { if (this[i].SubContinent_ID.Equals(subContinent_ID)) { return this[i]; } } return null; } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="C03_SubContinentColl"/> collection. /// </summary> /// <returns>A reference to the created <see cref="C03_SubContinentColl"/> collection.</returns> internal static C03_SubContinentColl NewC03_SubContinentColl() { return DataPortal.CreateChild<C03_SubContinentColl>(); } /// <summary> /// Factory method. Loads a <see cref="C03_SubContinentColl"/> collection, based on given parameters. /// </summary> /// <param name="parent_Continent_ID">The Parent_Continent_ID parameter of the C03_SubContinentColl to fetch.</param> /// <returns>A reference to the fetched <see cref="C03_SubContinentColl"/> collection.</returns> internal static C03_SubContinentColl GetC03_SubContinentColl(int parent_Continent_ID) { return DataPortal.FetchChild<C03_SubContinentColl>(parent_Continent_ID); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="C03_SubContinentColl"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public C03_SubContinentColl() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AllowNew = true; AllowEdit = true; AllowRemove = true; RaiseListChangedEvents = rlce; } #endregion #region Data Access /// <summary> /// Loads a <see cref="C03_SubContinentColl"/> collection from the database, based on given criteria. /// </summary> /// <param name="parent_Continent_ID">The Parent Continent ID.</param> protected void Child_Fetch(int parent_Continent_ID) { var args = new DataPortalHookArgs(parent_Continent_ID); OnFetchPre(args); using (var dalManager = DalFactorySelfLoad.GetManager()) { var dal = dalManager.GetProvider<IC03_SubContinentCollDal>(); var data = dal.Fetch(parent_Continent_ID); LoadCollection(data); } OnFetchPost(args); foreach (var item in this) { item.FetchChildren(); } } private void LoadCollection(IDataReader data) { using (var dr = new SafeDataReader(data)) { Fetch(dr); } } /// <summary> /// Loads all <see cref="C03_SubContinentColl"/> collection items from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; while (dr.Read()) { Add(C04_SubContinent.GetC04_SubContinent(dr)); } RaiseListChangedEvents = rlce; } #endregion #region DataPortal Hooks /// <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); #endregion } }
using System.Collections.Generic; using System.Runtime.Serialization; namespace Docker.DotNet.Models { [DataContract] public class SystemInfoResponse // (types.Info) { [DataMember(Name = "ID", EmitDefaultValue = false)] public string ID { get; set; } [DataMember(Name = "Containers", EmitDefaultValue = false)] public long Containers { get; set; } [DataMember(Name = "ContainersRunning", EmitDefaultValue = false)] public long ContainersRunning { get; set; } [DataMember(Name = "ContainersPaused", EmitDefaultValue = false)] public long ContainersPaused { get; set; } [DataMember(Name = "ContainersStopped", EmitDefaultValue = false)] public long ContainersStopped { get; set; } [DataMember(Name = "Images", EmitDefaultValue = false)] public long Images { get; set; } [DataMember(Name = "Driver", EmitDefaultValue = false)] public string Driver { get; set; } [DataMember(Name = "DriverStatus", EmitDefaultValue = false)] public IList<string[]> DriverStatus { get; set; } [DataMember(Name = "SystemStatus", EmitDefaultValue = false)] public IList<string[]> SystemStatus { get; set; } [DataMember(Name = "Plugins", EmitDefaultValue = false)] public PluginsInfo Plugins { get; set; } [DataMember(Name = "MemoryLimit", EmitDefaultValue = false)] public bool MemoryLimit { get; set; } [DataMember(Name = "SwapLimit", EmitDefaultValue = false)] public bool SwapLimit { get; set; } [DataMember(Name = "KernelMemory", EmitDefaultValue = false)] public bool KernelMemory { get; set; } [DataMember(Name = "KernelMemoryTCP", EmitDefaultValue = false)] public bool KernelMemoryTCP { get; set; } [DataMember(Name = "CpuCfsPeriod", EmitDefaultValue = false)] public bool CPUCfsPeriod { get; set; } [DataMember(Name = "CpuCfsQuota", EmitDefaultValue = false)] public bool CPUCfsQuota { get; set; } [DataMember(Name = "CPUShares", EmitDefaultValue = false)] public bool CPUShares { get; set; } [DataMember(Name = "CPUSet", EmitDefaultValue = false)] public bool CPUSet { get; set; } [DataMember(Name = "PidsLimit", EmitDefaultValue = false)] public bool PidsLimit { get; set; } [DataMember(Name = "IPv4Forwarding", EmitDefaultValue = false)] public bool IPv4Forwarding { get; set; } [DataMember(Name = "BridgeNfIptables", EmitDefaultValue = false)] public bool BridgeNfIptables { get; set; } [DataMember(Name = "BridgeNfIp6tables", EmitDefaultValue = false)] public bool BridgeNfIP6tables { get; set; } [DataMember(Name = "Debug", EmitDefaultValue = false)] public bool Debug { get; set; } [DataMember(Name = "NFd", EmitDefaultValue = false)] public long NFd { get; set; } [DataMember(Name = "OomKillDisable", EmitDefaultValue = false)] public bool OomKillDisable { get; set; } [DataMember(Name = "NGoroutines", EmitDefaultValue = false)] public long NGoroutines { get; set; } [DataMember(Name = "SystemTime", EmitDefaultValue = false)] public string SystemTime { get; set; } [DataMember(Name = "LoggingDriver", EmitDefaultValue = false)] public string LoggingDriver { get; set; } [DataMember(Name = "CgroupDriver", EmitDefaultValue = false)] public string CgroupDriver { get; set; } [DataMember(Name = "CgroupVersion", EmitDefaultValue = false)] public string CgroupVersion { get; set; } [DataMember(Name = "NEventsListener", EmitDefaultValue = false)] public long NEventsListener { get; set; } [DataMember(Name = "KernelVersion", EmitDefaultValue = false)] public string KernelVersion { get; set; } [DataMember(Name = "OperatingSystem", EmitDefaultValue = false)] public string OperatingSystem { get; set; } [DataMember(Name = "OSVersion", EmitDefaultValue = false)] public string OSVersion { get; set; } [DataMember(Name = "OSType", EmitDefaultValue = false)] public string OSType { get; set; } [DataMember(Name = "Architecture", EmitDefaultValue = false)] public string Architecture { get; set; } [DataMember(Name = "IndexServerAddress", EmitDefaultValue = false)] public string IndexServerAddress { get; set; } [DataMember(Name = "RegistryConfig", EmitDefaultValue = false)] public ServiceConfig RegistryConfig { get; set; } [DataMember(Name = "NCPU", EmitDefaultValue = false)] public long NCPU { get; set; } [DataMember(Name = "MemTotal", EmitDefaultValue = false)] public long MemTotal { get; set; } [DataMember(Name = "GenericResources", EmitDefaultValue = false)] public IList<GenericResource> GenericResources { get; set; } [DataMember(Name = "DockerRootDir", EmitDefaultValue = false)] public string DockerRootDir { get; set; } [DataMember(Name = "HttpProxy", EmitDefaultValue = false)] public string HTTPProxy { get; set; } [DataMember(Name = "HttpsProxy", EmitDefaultValue = false)] public string HTTPSProxy { get; set; } [DataMember(Name = "NoProxy", EmitDefaultValue = false)] public string NoProxy { get; set; } [DataMember(Name = "Name", EmitDefaultValue = false)] public string Name { get; set; } [DataMember(Name = "Labels", EmitDefaultValue = false)] public IList<string> Labels { get; set; } [DataMember(Name = "ExperimentalBuild", EmitDefaultValue = false)] public bool ExperimentalBuild { get; set; } [DataMember(Name = "ServerVersion", EmitDefaultValue = false)] public string ServerVersion { get; set; } [DataMember(Name = "ClusterStore", EmitDefaultValue = false)] public string ClusterStore { get; set; } [DataMember(Name = "ClusterAdvertise", EmitDefaultValue = false)] public string ClusterAdvertise { get; set; } [DataMember(Name = "Runtimes", EmitDefaultValue = false)] public IDictionary<string, Runtime> Runtimes { get; set; } [DataMember(Name = "DefaultRuntime", EmitDefaultValue = false)] public string DefaultRuntime { get; set; } [DataMember(Name = "Swarm", EmitDefaultValue = false)] public Info Swarm { get; set; } [DataMember(Name = "LiveRestoreEnabled", EmitDefaultValue = false)] public bool LiveRestoreEnabled { get; set; } [DataMember(Name = "Isolation", EmitDefaultValue = false)] public string Isolation { get; set; } [DataMember(Name = "InitBinary", EmitDefaultValue = false)] public string InitBinary { get; set; } [DataMember(Name = "ContainerdCommit", EmitDefaultValue = false)] public Commit ContainerdCommit { get; set; } [DataMember(Name = "RuncCommit", EmitDefaultValue = false)] public Commit RuncCommit { get; set; } [DataMember(Name = "InitCommit", EmitDefaultValue = false)] public Commit InitCommit { get; set; } [DataMember(Name = "SecurityOptions", EmitDefaultValue = false)] public IList<string> SecurityOptions { get; set; } [DataMember(Name = "ProductLicense", EmitDefaultValue = false)] public string ProductLicense { get; set; } [DataMember(Name = "DefaultAddressPools", EmitDefaultValue = false)] public IList<NetworkAddressPool> DefaultAddressPools { get; set; } [DataMember(Name = "Warnings", EmitDefaultValue = false)] public IList<string> Warnings { get; set; } } }
//! \file AudioOGG.cs //! \date Fri Nov 07 00:32:15 2014 //! \brief NVorbis wrapper for GameRes. // // Copyright (C) 2014 by morkt // // 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.ComponentModel.Composition; using System.IO; using System.Linq; using GameRes.Utility; using NVorbis; namespace GameRes.Formats { public class OggInput : SoundInput { VorbisReader m_reader; public override long Position { get { return (long)(m_reader.DecodedTime.TotalSeconds * m_reader.SampleRate * m_reader.Channels * sizeof(float)); } set { if (value < 0 || value > Length) throw new ArgumentOutOfRangeException("value"); m_reader.DecodedTime = TimeSpan.FromSeconds((double)value / m_reader.SampleRate / m_reader.Channels / sizeof(float)); } } public override bool CanSeek { get { return Source.CanSeek; } } public override int SourceBitrate { get { return m_reader.NominalBitrate; } } public override string SourceFormat { get { return "ogg"; } } public OggInput (Stream file) : base (file) { m_reader = new VorbisReader (Source, false); var format = new GameRes.WaveFormat(); format.FormatTag = 3; // WAVE_FORMAT_IEEE_FLOAT format.Channels = (ushort)m_reader.Channels; format.SamplesPerSecond = (uint)m_reader.SampleRate; format.BitsPerSample = 32; format.BlockAlign = (ushort)(4 * format.Channels); format.AverageBytesPerSecond = format.SamplesPerSecond * format.BlockAlign; this.Format = format; this.PcmSize = (long)(m_reader.TotalTime.TotalSeconds * format.SamplesPerSecond * format.Channels * sizeof(float)); } public override void Reset () { m_reader.DecodedTime = TimeSpan.FromSeconds (0); } // This buffer can be static because it can only be used by 1 instance per thread [ThreadStatic] static float[] _conversionBuffer = null; public override int Read(byte[] buffer, int offset, int count) { // adjust count so it is in floats instead of bytes count /= sizeof(float); // make sure we don't have an odd count count -= count % m_reader.Channels; // get the buffer, creating a new one if none exists or the existing one is too small var cb = _conversionBuffer ?? (_conversionBuffer = new float[count]); if (cb.Length < count) { cb = (_conversionBuffer = new float[count]); } // let ReadSamples(float[], int, int) do the actual reading; adjust count back to bytes int cnt = m_reader.ReadSamples (cb, 0, count) * sizeof(float); // move the data back to the request buffer Buffer.BlockCopy (cb, 0, buffer, offset, cnt); // done! return cnt; } #region IDisposable Members bool _ogg_disposed = false; protected override void Dispose (bool disposing) { if (!_ogg_disposed) { if (disposing) { m_reader.Dispose(); } _ogg_disposed = true; base.Dispose (disposing); } } #endregion } [Export(typeof(AudioFormat))] public sealed class OggAudio : AudioFormat { public override string Tag { get { return "OGG"; } } public override string Description { get { return "Ogg/Vorbis audio format"; } } public override uint Signature { get { return 0x5367674f; } } // 'OggS' public override bool CanWrite { get { return false; } } LocalResourceSetting FixCrc = new LocalResourceSetting ("OGGFixCrc"); public OggAudio () { Signatures = new uint[] { 0x5367674F, 0 }; Settings = new[] { FixCrc }; } public override SoundInput TryOpen (IBinaryStream file) { Stream input = file.AsStream; if (file.Signature == Wav.Signature) { var header = file.ReadHeader (0x14); if (!header.AsciiEqual (8, "WAVEfmt ")) return null; uint fmt_size = header.ToUInt32 (0x10); long fmt_pos = file.Position; ushort format = file.ReadUInt16(); if (format != 0x676F && format != 0x6770 && format != 0x6771 && format != 0x674F) return null; // interpret WAVE 'data' section as Ogg stream file.Position = fmt_pos + ((fmt_size + 1) & ~1); for (;;) // ended by end-of-stream exception { uint section_id = file.ReadUInt32(); uint section_size = file.ReadUInt32(); if (section_id == 0x61746164) // 'data' { long ogg_pos = file.Position; uint id = file.ReadUInt32(); if (id != Signature) return null; input = new StreamRegion (input, ogg_pos, section_size); break; } file.Seek ((section_size + 1) & ~1u, SeekOrigin.Current); } } else if (file.Signature != this.Signature) return null; if (FixCrc.Get<bool>()) input = new SeekableStream (new OggRestoreStream (input)); return new OggInput (input); } public static AudioFormat Instance { get { return s_OggFormat.Value; } } static readonly ResourceInstance<AudioFormat> s_OggFormat = new ResourceInstance<AudioFormat> ("OGG"); } /// <summary> /// Restore CRC checksums of the OGG stream pages. /// </summary> internal class OggRestoreStream : InputProxyStream { bool m_eof; bool m_ogg_ended; byte[] m_page = new byte[0x10000]; int m_page_pos = 0; int m_page_length = 0; public override bool CanSeek { get { return false; } } public OggRestoreStream (Stream input) : base (input) { } public override int Read (byte[] buffer, int offset, int count) { int total_read = 0; while (count > 0 && !m_eof) { if (m_page_pos == m_page_length) { if (m_ogg_ended) { int read = BaseStream.Read (buffer, offset, count); total_read += read; m_eof = 0 == read; break; } NextPage(); } if (m_eof) break; int available = Math.Min (m_page_length - m_page_pos, count); Buffer.BlockCopy (m_page, m_page_pos, buffer, offset, available); m_page_pos += available; offset += available; count -= available; total_read += available; } return total_read; } void NextPage () { m_page_pos = 0; m_page_length = BaseStream.Read (m_page, 0, 0x1B); if (0 == m_page_length) { m_eof = true; return; } if (m_page_length < 0x1B || !m_page.AsciiEqual ("OggS")) { m_ogg_ended = true; return; } int segment_count = m_page[0x1A]; m_page[0x16] = 0; m_page[0x17] = 0; m_page[0x18] = 0; m_page[0x19] = 0; if (segment_count != 0) { int table_length = BaseStream.Read (m_page, 0x1B, segment_count); m_page_length += table_length; if (table_length != segment_count) { m_ogg_ended = true; return; } int segments_length = 0; int segment_table = 0x1B; for (int i = 0; i < segment_count; ++i) segments_length += m_page[segment_table++]; m_page_length += BaseStream.Read (m_page, 0x1B+segment_count, segments_length); } uint crc = Crc32Normal.UpdateCrc (0, m_page, 0, m_page_length); LittleEndian.Pack (crc, m_page, 0x16); } } }
/* private Vector messageListeners; private Vector newLineListeners; private Vector matchListeners; private Vector tokenListeners; private Vector semPredListeners; private Vector synPredListeners; private Vector traceListeners; */ using System; using System.ComponentModel; using Solenoid.Expressions.Parser.antlr.collections; using Solenoid.Expressions.Parser.antlr.collections.impl; using Solenoid.Expressions.Parser.antlr.debug; namespace Solenoid.Expressions.Parser.antlr { /*ANTLR Translator Generator * Project led by Terence Parr at http://www.jGuru.com * Software rights: http://www.antlr.org/license.html * * $Id:$ */ // // ANTLR C# Code Generator by Micheal Jordan // Kunle Odutola : kunle UNDERSCORE odutola AT hotmail DOT com // Anthony Oguntimehin // // With many thanks to Eric V. Smith from the ANTLR list. // public abstract class Parser : IParserDebugSubject { // Used to store event delegates private EventHandlerList events_ = new EventHandlerList(); protected internal EventHandlerList Events { get { return events_; } } // The unique keys for each event that Parser [objects] can generate internal static readonly object EnterRuleEventKey = new object(); internal static readonly object ExitRuleEventKey = new object(); internal static readonly object DoneEventKey = new object(); internal static readonly object ReportErrorEventKey = new object(); internal static readonly object ReportWarningEventKey = new object(); internal static readonly object NewLineEventKey = new object(); internal static readonly object MatchEventKey = new object(); internal static readonly object MatchNotEventKey = new object(); internal static readonly object MisMatchEventKey = new object(); internal static readonly object MisMatchNotEventKey = new object(); internal static readonly object ConsumeEventKey = new object(); internal static readonly object LAEventKey = new object(); internal static readonly object SemPredEvaluatedEventKey = new object(); internal static readonly object SynPredStartedEventKey = new object(); internal static readonly object SynPredFailedEventKey = new object(); internal static readonly object SynPredSucceededEventKey = new object(); protected internal ParserSharedInputState inputState; /*Nesting level of registered handlers */ // protected int exceptionLevel = 0; /*Table of token type to token names */ protected internal string[] tokenNames; /*AST return value for a rule is squirreled away here */ protected internal AST returnAST; /*AST support code; parser and treeparser delegate to this object */ protected internal ASTFactory astFactory = new ASTFactory(); private bool ignoreInvalidDebugCalls = false; /*Used to keep track of indentdepth for traceIn/Out */ protected internal int traceDepth = 0; public Parser() { inputState = new ParserSharedInputState(); } public Parser(ParserSharedInputState state) { inputState = state; } /// <summary> /// /// </summary> public event TraceEventHandler EnterRule { add { Events.AddHandler(EnterRuleEventKey, value); } remove { Events.RemoveHandler(EnterRuleEventKey, value); } } public event TraceEventHandler ExitRule { add { Events.AddHandler(ExitRuleEventKey, value); } remove { Events.RemoveHandler(ExitRuleEventKey, value); } } public event TraceEventHandler Done { add { Events.AddHandler(DoneEventKey, value); } remove { Events.RemoveHandler(DoneEventKey, value); } } public event MessageEventHandler ErrorReported { add { Events.AddHandler(ReportErrorEventKey, value); } remove { Events.RemoveHandler(ReportErrorEventKey, value); } } public event MessageEventHandler WarningReported { add { Events.AddHandler(ReportWarningEventKey, value); } remove { Events.RemoveHandler(ReportWarningEventKey, value); } } public event MatchEventHandler MatchedToken { add { Events.AddHandler(MatchEventKey, value); } remove { Events.RemoveHandler(MatchEventKey, value); } } public event MatchEventHandler MatchedNotToken { add { Events.AddHandler(MatchNotEventKey, value); } remove { Events.RemoveHandler(MatchNotEventKey, value); } } public event MatchEventHandler MisMatchedToken { add { Events.AddHandler(MisMatchEventKey, value); } remove { Events.RemoveHandler(MisMatchEventKey, value); } } public event MatchEventHandler MisMatchedNotToken { add { Events.AddHandler(MisMatchNotEventKey, value); } remove { Events.RemoveHandler(MisMatchNotEventKey, value); } } public event TokenEventHandler ConsumedToken { add { Events.AddHandler(ConsumeEventKey, value); } remove { Events.RemoveHandler(ConsumeEventKey, value); } } public event TokenEventHandler TokenLA { add { Events.AddHandler(LAEventKey, value); } remove { Events.RemoveHandler(LAEventKey, value); } } public event SemanticPredicateEventHandler SemPredEvaluated { add { Events.AddHandler(SemPredEvaluatedEventKey, value); } remove { Events.RemoveHandler(SemPredEvaluatedEventKey, value); } } public event SyntacticPredicateEventHandler SynPredStarted { add { Events.AddHandler(SynPredStartedEventKey, value); } remove { Events.RemoveHandler(SynPredStartedEventKey, value); } } public event SyntacticPredicateEventHandler SynPredFailed { add { Events.AddHandler(SynPredFailedEventKey, value); } remove { Events.RemoveHandler(SynPredFailedEventKey, value); } } public event SyntacticPredicateEventHandler SynPredSucceeded { add { Events.AddHandler(SynPredSucceededEventKey, value); } remove { Events.RemoveHandler(SynPredSucceededEventKey, value); } } public virtual void addMessageListener(MessageListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("addMessageListener() is only valid if parser built for debugging"); } public virtual void addParserListener(ParserListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("addParserListener() is only valid if parser built for debugging"); } public virtual void addParserMatchListener(ParserMatchListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("addParserMatchListener() is only valid if parser built for debugging"); } public virtual void addParserTokenListener(ParserTokenListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("addParserTokenListener() is only valid if parser built for debugging"); } public virtual void addSemanticPredicateListener(SemanticPredicateListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("addSemanticPredicateListener() is only valid if parser built for debugging"); } public virtual void addSyntacticPredicateListener(SyntacticPredicateListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("addSyntacticPredicateListener() is only valid if parser built for debugging"); } public virtual void addTraceListener(TraceListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("addTraceListener() is only valid if parser built for debugging"); } /*Get another token object from the token stream */ public abstract void consume(); /*Consume tokens until one matches the given token */ public virtual void consumeUntil(int tokenType) { while (LA(1) != Token.EOF_TYPE && LA(1) != tokenType) { consume(); } } /*Consume tokens until one matches the given token set */ public virtual void consumeUntil(BitSet bset) { while (LA(1) != Token.EOF_TYPE && !bset.member(LA(1))) { consume(); } } protected internal virtual void defaultDebuggingSetup(TokenStream lexer, TokenBuffer tokBuf) { // by default, do nothing -- we're not debugging } /*Get the AST return value squirreled away in the parser */ public virtual AST getAST() { return returnAST; } public virtual ASTFactory getASTFactory() { return astFactory; } public virtual string getFilename() { return inputState.filename; } public virtual ParserSharedInputState getInputState() { return inputState; } public virtual void setInputState(ParserSharedInputState state) { inputState = state; } public virtual void resetState() { traceDepth = 0; inputState.reset(); } public virtual string getTokenName(int num) { return tokenNames[num]; } public virtual string[] getTokenNames() { return tokenNames; } public virtual bool isDebugMode() { return false; } /*Return the token type of the ith token of lookahead where i=1 * is the current token being examined by the parser (i.e., it * has not been matched yet). */ public abstract int LA(int i); /*Return the ith token of lookahead */ public abstract IToken LT(int i); // Forwarded to TokenBuffer public virtual int mark() { return inputState.input.mark(); } /*Make sure current lookahead symbol matches token type <tt>t</tt>. * Throw an exception upon mismatch, which is catch by either the * error handler or by the syntactic predicate. */ public virtual void match(int t) { if (LA(1) != t) throw new MismatchedTokenException(tokenNames, LT(1), t, false, getFilename()); else consume(); } /*Make sure current lookahead symbol matches the given set * Throw an exception upon mismatch, which is catch by either the * error handler or by the syntactic predicate. */ public virtual void match(BitSet b) { if (!b.member(LA(1))) throw new MismatchedTokenException(tokenNames, LT(1), b, false, getFilename()); else consume(); } public virtual void matchNot(int t) { if (LA(1) == t) throw new MismatchedTokenException(tokenNames, LT(1), t, true, getFilename()); else consume(); } /// <summary> /// @deprecated as of 2.7.2. This method calls System.exit() and writes /// directly to stderr, which is usually not appropriate when /// a parser is embedded into a larger application. Since the method is /// <code>static</code>, it cannot be overridden to avoid these problems. /// ANTLR no longer uses this method internally or in generated code. /// </summary> /// [Obsolete("De-activated since version 2.7.2.6 as it cannot be overidden.", true)] public static void panic() { System.Console.Error.WriteLine("Parser: panic"); System.Environment.Exit(1); } public virtual void removeMessageListener(MessageListener l) { if (!ignoreInvalidDebugCalls) throw new System.SystemException("removeMessageListener() is only valid if parser built for debugging"); } public virtual void removeParserListener(ParserListener l) { if (!ignoreInvalidDebugCalls) throw new System.SystemException("removeParserListener() is only valid if parser built for debugging"); } public virtual void removeParserMatchListener(ParserMatchListener l) { if (!ignoreInvalidDebugCalls) throw new System.SystemException("removeParserMatchListener() is only valid if parser built for debugging"); } public virtual void removeParserTokenListener(ParserTokenListener l) { if (!ignoreInvalidDebugCalls) throw new System.SystemException("removeParserTokenListener() is only valid if parser built for debugging"); } public virtual void removeSemanticPredicateListener(SemanticPredicateListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("removeSemanticPredicateListener() is only valid if parser built for debugging"); } public virtual void removeSyntacticPredicateListener(SyntacticPredicateListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("removeSyntacticPredicateListener() is only valid if parser built for debugging"); } public virtual void removeTraceListener(TraceListener l) { if (!ignoreInvalidDebugCalls) throw new System.SystemException("removeTraceListener() is only valid if parser built for debugging"); } /*Parser error-reporting function can be overridden in subclass */ public virtual void reportError(RecognitionException ex) { Console.Error.WriteLine(ex); } /*Parser error-reporting function can be overridden in subclass */ public virtual void reportError(string s) { if (getFilename() == null) { Console.Error.WriteLine("error: " + s); } else { Console.Error.WriteLine(getFilename() + ": error: " + s); } } /*Parser warning-reporting function can be overridden in subclass */ public virtual void reportWarning(string s) { if (getFilename() == null) { Console.Error.WriteLine("warning: " + s); } else { Console.Error.WriteLine(getFilename() + ": warning: " + s); } } public virtual void recover(RecognitionException ex, BitSet tokenSet) { consume(); consumeUntil(tokenSet); } public virtual void rewind(int pos) { inputState.input.rewind(pos); } /// <summary> /// Specify an object with support code (shared by Parser and TreeParser. /// Normally, the programmer does not play with this, using /// <see cref="setASTNodeClass"/> instead. /// </summary> /// <param name="f"></param> public virtual void setASTFactory(ASTFactory f) { astFactory = f; } /// <summary> /// Specify the type of node to create during tree building. /// </summary> /// <param name="cl">Fully qualified AST Node type name.</param> public virtual void setASTNodeClass(string cl) { astFactory.setASTNodeType(cl); } /// <summary> /// Specify the type of node to create during tree building. /// use <see cref="setASTNodeClass"/> now to be consistent with /// Token Object Type accessor. /// </summary> /// <param name="nodeType">Fully qualified AST Node type name.</param> [Obsolete("Replaced by setASTNodeClass(string) since version 2.7.1", true)] public virtual void setASTNodeType(string nodeType) { setASTNodeClass(nodeType); } public virtual void setDebugMode(bool debugMode) { if (!ignoreInvalidDebugCalls) throw new System.SystemException("setDebugMode() only valid if parser built for debugging"); } public virtual void setFilename(string f) { inputState.filename = f; } public virtual void setIgnoreInvalidDebugCalls(bool Value) { ignoreInvalidDebugCalls = Value; } /*Set or change the input token buffer */ public virtual void setTokenBuffer(TokenBuffer t) { inputState.input = t; } public virtual void traceIndent() { for (var i = 0; i < traceDepth; i++) Console.Out.Write(" "); } public virtual void traceIn(string rname) { traceDepth += 1; traceIndent(); Console.Out.WriteLine("> " + rname + "; LA(1)==" + LT(1).getText() + ((inputState.guessing > 0)?" [guessing]":"")); } public virtual void traceOut(string rname) { traceIndent(); Console.Out.WriteLine("< " + rname + "; LA(1)==" + LT(1).getText() + ((inputState.guessing > 0)?" [guessing]":"")); traceDepth -= 1; } } }
//! \file ArcEAGLS.cs //! \date Fri May 15 02:52:04 2015 //! \brief EAGLS system resource archives. // // Copyright (C) 2015-2016 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using System.Linq; using GameRes.Utility; namespace GameRes.Formats.Eagls { [Export(typeof(ArchiveFormat))] public class PakOpener : ArchiveFormat { public override string Tag { get { return "PAK/EAGLS"; } } public override string Description { get { return "EAGLS engine resource archive"; } } public override uint Signature { get { return 0; } } public override bool IsHierarchic { get { return false; } } public override bool CanCreate { get { return false; } } public PakOpener () { Extensions = new string[] { "pak" }; } internal static readonly string IndexKey = "1qaz2wsx3edc4rfv5tgb6yhn7ujm8ik,9ol.0p;/-@:^[]"; internal static readonly string Key = "EAGLS_SYSTEM"; // FIXME not thread-safe CRuntimeRandomGenerator m_rng = new CRuntimeRandomGenerator(); public override ArcFile TryOpen (ArcView file) { string idx_name = Path.ChangeExtension (file.Name, ".idx"); if (file.Name.Equals (idx_name, StringComparison.InvariantCultureIgnoreCase) || !VFS.FileExists (idx_name)) return null; var idx_entry = VFS.FindFile (idx_name); if (idx_entry.Size > 0xfffff || idx_entry.Size < 10000) return null; byte[] index; using (var idx = VFS.OpenView (idx_entry)) index = DecryptIndex (idx); int index_offset = 0; int entry_size = index.Length / 10000; bool long_offsets = 40 == entry_size; int name_size = long_offsets ? 0x18 : 0x14; long first_offset = LittleEndian.ToUInt32 (index, name_size); var dir = new List<Entry>(); while (index_offset < index.Length) { if (0 == index[index_offset]) break; var name = Binary.GetCString (index, index_offset, name_size); index_offset += name_size; var entry = FormatCatalog.Instance.Create<Entry> (name); if (name.EndsWith (".dat", StringComparison.InvariantCultureIgnoreCase)) entry.Type = "script"; if (long_offsets) { entry.Offset = LittleEndian.ToInt64 (index, index_offset) - first_offset; entry.Size = LittleEndian.ToUInt32 (index, index_offset+8); index_offset += 0x10; } else { entry.Offset = LittleEndian.ToUInt32 (index, index_offset) - first_offset; entry.Size = LittleEndian.ToUInt32 (index, index_offset+4); index_offset += 8; } if (!entry.CheckPlacement (file.MaxOffset)) return null; dir.Add (entry); } if (0 == dir.Count) return null; if (dir[0].Name.EndsWith (".gr", StringComparison.InvariantCultureIgnoreCase)) // CG archive return new CgArchive (file, this, dir); else return new ArcFile (file, this, dir); } public override Stream OpenEntry (ArcFile arc, Entry entry) { var cg_arc = arc as CgArchive; if (null != cg_arc) return cg_arc.DecryptEntry (entry); if (entry.Name.EndsWith (".dat", StringComparison.InvariantCultureIgnoreCase)) return DecryptDat (arc, entry); return arc.File.CreateStream (entry.Offset, entry.Size); } Stream DecryptDat (ArcFile arc, Entry entry) { byte[] input = arc.File.View.ReadBytes (entry.Offset, entry.Size); int text_offset = 3600; int text_length = (int)(entry.Size - text_offset - 2); m_rng.SRand ((sbyte)input[input.Length-1]); for (int i = 0; i < text_length; i += 2) { input[text_offset + i] ^= (byte)Key[m_rng.Rand() % Key.Length]; } return new MemoryStream (input); } byte[] DecryptIndex (ArcView idx) { int idx_size = (int)idx.MaxOffset-4; byte[] output = new byte[idx_size]; using (var view = idx.CreateViewAccessor (0, (uint)idx.MaxOffset)) unsafe { m_rng.SRand (view.ReadInt32 (idx_size)); byte* ptr = view.GetPointer (0); try { for (int i = 0; i < idx_size; ++i) { output[i] = (byte)(ptr[i] ^ IndexKey[m_rng.Rand() % IndexKey.Length]); } return output; } finally { view.SafeMemoryMappedViewHandle.ReleasePointer(); } } } } internal interface IRandomGenerator { void SRand (int seed); int Rand (); } internal class CRuntimeRandomGenerator : IRandomGenerator { uint m_seed; public void SRand (int seed) { m_seed = (uint)seed; } public int Rand () { m_seed = m_seed * 214013u + 2531011u; return (int)(m_seed >> 16) & 0x7FFF; } } internal class LehmerRandomGenerator : IRandomGenerator { int m_seed; const int A = 48271; const int Q = 44488; const int R = 3399; const int M = 2147483647; public void SRand (int seed) { m_seed = seed ^ 123459876; } public int Rand () { m_seed = A * (m_seed % Q) - R * (m_seed / Q); if (m_seed < 0) m_seed += M; return (int)(m_seed * 4.656612875245797e-10 * 256); } } internal class CgArchive : ArcFile { IRandomGenerator m_rng; public CgArchive (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir) : base (arc, impl, dir) { m_rng = DetectEncryptionScheme(); } IRandomGenerator DetectEncryptionScheme () { var first_entry = Dir.First(); int signature = (File.View.ReadInt32 (first_entry.Offset) >> 8) & 0xFFFF; byte seed = File.View.ReadByte (first_entry.Offset+first_entry.Size-1); IRandomGenerator[] rng_list = { new LehmerRandomGenerator(), new CRuntimeRandomGenerator(), }; foreach (var rng in rng_list) { rng.SRand (seed); rng.Rand(); // skip LZSS control byte int test = signature; test ^= PakOpener.Key[rng.Rand() % PakOpener.Key.Length]; test ^= PakOpener.Key[rng.Rand() % PakOpener.Key.Length] << 8; // FIXME // as key is rather short, this detection could produce false results sometimes if (0x4D42 == test) // 'BM' return rng; } throw new UnknownEncryptionScheme(); } public Stream DecryptEntry (Entry entry) { var input = File.View.ReadBytes (entry.Offset, entry.Size); m_rng.SRand (input[input.Length-1]); int limit = Math.Min (input.Length-1, 0x174b); for (int i = 0; i < limit; ++i) { input[i] ^= (byte)PakOpener.Key[m_rng.Rand() % PakOpener.Key.Length]; } return new MemoryStream (input); } } }
using System; using System.Net; using EventStore.Common.Utils; using EventStore.Core.Cluster; using EventStore.Core.Messaging; namespace EventStore.Core.Messages { public static class ElectionMessage { public class StartElections : Message { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public override string ToString() { return "---- StartElections"; } } public class ViewChange : Message { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly Guid ServerId; public readonly IPEndPoint ServerInternalHttp; public readonly int AttemptedView; public ViewChange(Guid serverId, IPEndPoint serverInternalHttp, int attemptedView) { ServerId = serverId; ServerInternalHttp = serverInternalHttp; AttemptedView = attemptedView; } public ViewChange(ElectionMessageDto.ViewChangeDto dto) { AttemptedView = dto.AttemptedView; ServerId = dto.ServerId; ServerInternalHttp = new IPEndPoint(IPAddress.Parse(dto.ServerInternalHttpAddress), dto.ServerInternalHttpPort); } public override string ToString() { return string.Format("---- ViewChange: attemptedView {0}, serverId {1}, serverInternalHttp {2}", AttemptedView, ServerId, ServerInternalHttp); } } public class ViewChangeProof : Message { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly Guid ServerId; public readonly IPEndPoint ServerInternalHttp; public readonly int InstalledView; public ViewChangeProof(Guid serverId, IPEndPoint serverInternalHttp, int installedView) { ServerId = serverId; ServerInternalHttp = serverInternalHttp; InstalledView = installedView; } public ViewChangeProof(ElectionMessageDto.ViewChangeProofDto dto) { ServerId = dto.ServerId; ServerInternalHttp = new IPEndPoint(IPAddress.Parse(dto.ServerInternalHttpAddress), dto.ServerInternalHttpPort); InstalledView = dto.InstalledView; } public override string ToString() { return string.Format("---- ViewChangeProof: serverId {0}, serverInternalHttp {1}, installedView {2}", ServerId, ServerInternalHttp, InstalledView); } } public class SendViewChangeProof : Message { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public override string ToString() { return string.Format("---- SendViewChangeProof"); } } public class ElectionsTimedOut : Message { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly int View; public ElectionsTimedOut(int view) { View = view; } public override string ToString() { return string.Format("---- ElectionsTimedOut: view {0}", View); } } public class Prepare : Message { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly Guid ServerId; public readonly IPEndPoint ServerInternalHttp; public readonly int View; public Prepare(Guid serverId, IPEndPoint serverInternalHttp, int view) { ServerId = serverId; ServerInternalHttp = serverInternalHttp; View = view; } public Prepare(ElectionMessageDto.PrepareDto dto) { ServerId = dto.ServerId; ServerInternalHttp = new IPEndPoint(IPAddress.Parse(dto.ServerInternalHttpAddress), dto.ServerInternalHttpPort); View = dto.View; } public override string ToString() { return string.Format("---- Prepare: serverId {0}, serverInternalHttp {1}, view {2}", ServerId, ServerInternalHttp, View); } } public class PrepareOk : Message { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly int View; public readonly Guid ServerId; public readonly IPEndPoint ServerInternalHttp; public readonly int EpochNumber; public readonly long EpochPosition; public readonly Guid EpochId; public readonly long LastCommitPosition; public readonly long WriterCheckpoint; public readonly long ChaserCheckpoint; public readonly int NodePriority; public PrepareOk(int view, Guid serverId, IPEndPoint serverInternalHttp, int epochNumber, long epochPosition, Guid epochId, long lastCommitPosition, long writerCheckpoint, long chaserCheckpoint, int nodePriority) { View = view; ServerId = serverId; ServerInternalHttp = serverInternalHttp; EpochNumber = epochNumber; EpochPosition = epochPosition; EpochId = epochId; LastCommitPosition = lastCommitPosition; WriterCheckpoint = writerCheckpoint; ChaserCheckpoint = chaserCheckpoint; NodePriority = nodePriority; } public PrepareOk(ElectionMessageDto.PrepareOkDto dto) { View = dto.View; ServerId = dto.ServerId; ServerInternalHttp = new IPEndPoint(IPAddress.Parse(dto.ServerInternalHttpAddress), dto.ServerInternalHttpPort); EpochNumber = dto.EpochNumber; EpochPosition = dto.EpochPosition; EpochId = dto.EpochId; LastCommitPosition = dto.LastCommitPosition; WriterCheckpoint = dto.WriterCheckpoint; ChaserCheckpoint = dto.ChaserCheckpoint; NodePriority = dto.NodePriority; } public override string ToString() { return string.Format("---- PrepareOk: view {0}, serverId {1}, serverInternalHttp {2}, epochNumber {3}, " + "epochPosition {4}, epochId {5}, lastCommitPosition {6}, writerCheckpoint {7}, chaserCheckpoint {8}, nodePriority: {9}", View, ServerId, ServerInternalHttp, EpochNumber, EpochPosition, EpochId, LastCommitPosition, WriterCheckpoint, ChaserCheckpoint, NodePriority); } } public class Proposal : Message { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly Guid ServerId; public readonly IPEndPoint ServerInternalHttp; public readonly Guid MasterId; public readonly IPEndPoint MasterInternalHttp; public readonly int View; public readonly int EpochNumber; public readonly long EpochPosition; public readonly Guid EpochId; public readonly long LastCommitPosition; public readonly long WriterCheckpoint; public readonly long ChaserCheckpoint; public Proposal(Guid serverId, IPEndPoint serverInternalHttp, Guid masterId, IPEndPoint masterInternalHttp, int view, int epochNumber, long epochPosition, Guid epochId, long lastCommitPosition, long writerCheckpoint, long chaserCheckpoint) { ServerId = serverId; ServerInternalHttp = serverInternalHttp; MasterId = masterId; MasterInternalHttp = masterInternalHttp; View = view; EpochNumber = epochNumber; EpochPosition = epochPosition; EpochId = epochId; LastCommitPosition = lastCommitPosition; WriterCheckpoint = writerCheckpoint; ChaserCheckpoint = chaserCheckpoint; } public Proposal(ElectionMessageDto.ProposalDto dto) { ServerId = dto.ServerId; ServerInternalHttp = new IPEndPoint(IPAddress.Parse(dto.ServerInternalHttpAddress), dto.ServerInternalHttpPort); MasterId = dto.MasterId; MasterInternalHttp = new IPEndPoint(IPAddress.Parse(dto.MasterInternalHttpAddress), dto.MasterInternalHttpPort); View = dto.View; EpochNumber = dto.EpochNumber; EpochPosition = dto.EpochPosition; EpochId = dto.EpochId; LastCommitPosition = dto.LastCommitPosition; WriterCheckpoint = dto.WriterCheckpoint; ChaserCheckpoint = dto.ChaserCheckpoint; } public override string ToString() { return string.Format("---- Proposal: serverId {0}, serverInternalHttp {1}, masterId {2}, masterInternalHttp {3}, " + "view {4}, lastCommitCheckpoint {5}, writerCheckpoint {6}, chaserCheckpoint {7}, epoch {8}@{9}:{10:B}", ServerId, ServerInternalHttp, MasterId, MasterInternalHttp, View, LastCommitPosition, WriterCheckpoint, ChaserCheckpoint, EpochNumber, EpochPosition, EpochId); } } public class Accept : Message { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly Guid ServerId; public readonly IPEndPoint ServerInternalHttp; public readonly Guid MasterId; public readonly IPEndPoint MasterInternalHttp; public readonly int View; public Accept(Guid serverId, IPEndPoint serverInternalHttp, Guid masterId, IPEndPoint masterInternalHttp, int view) { ServerId = serverId; ServerInternalHttp = serverInternalHttp; MasterId = masterId; MasterInternalHttp = masterInternalHttp; View = view; } public Accept(ElectionMessageDto.AcceptDto dto) { ServerId = dto.ServerId; ServerInternalHttp = new IPEndPoint(IPAddress.Parse(dto.ServerInternalHttpAddress), dto.ServerInternalHttpPort); MasterId = dto.MasterId; MasterInternalHttp = new IPEndPoint(IPAddress.Parse(dto.MasterInternalHttpAddress), dto.MasterInternalHttpPort); View = dto.View; } public override string ToString() { return string.Format("---- Accept: serverId {0}, serverInternalHttp {1}, masterId {2}, masterInternalHttp {3}, view {4}", ServerId, ServerInternalHttp, MasterId, MasterInternalHttp, View); } } public class ElectionsDone : Message { private static readonly int TypeId = System.Threading.Interlocked.Increment(ref NextMsgId); public override int MsgTypeId { get { return TypeId; } } public readonly int InstalledView; public readonly MemberInfo Master; public ElectionsDone(int installedView, MemberInfo master) { Ensure.Nonnegative(installedView, "installedView"); Ensure.NotNull(master, "master"); InstalledView = installedView; Master = master; } public override string ToString() { return string.Format("---- ElectionsDone: installedView {0}, master {1}", InstalledView, Master); } } } }
using System; using System.ComponentModel.DataAnnotations; using System.Collections.Generic; using System.Data; using NServiceKit.DataAnnotations; using System.Reflection; using NServiceKit.OrmLite; using NServiceKit.OrmLite.Firebird; namespace TestLiteFirebirdProcedures { [Alias("EMPLOYEE")] public class Employee{ [Alias("EMP_NO")] [Sequence("EMP_NO_GEN")] public Int16 Id{ get; set; } [Alias("FIRST_NAME")] [Required] public string FirstName{ get; set; } [Alias("LAST_NAME")] [Required] public string LastName{ get; set; } [Alias("PHONE_EXT")] public string PhoneExtension{ get; set; } [Alias("HIRE_DATE")] [Required] public DateTime HireDate{ get; set; } [Alias("DEPT_NO")] [Required] public string DepartamentNumber{ get; set; } [Alias("JOB_CODE")] [Required] public string JobCode{ get; set; } [Alias("JOB_GRADE")] public Int16 JobGrade{ get; set; } [Alias("JOB_COUNTRY")] [Required] public string JobCountry{ get; set; } [Alias("SALARY")] [Required] public Decimal Salary{ get; set; } } [Alias("DELETE_EMPLOYEE")] public class ProcedureDeleteEmployee { [Alias("EMP_NUM")] public Int16 EmployeeNumber{ get ; set; } } [Alias("SUB_TOT_BUDGET")] public class ProcedureSubTotalBudgetParameters{ [Alias("HEAD_DEPT")] public string HeadDepartament{ get; set; } } public class ProcedureSubTotalBudgetResult{ [Alias("TOT_BUDGET")] public decimal Total { get; set; } [Alias("AVG_BUDGET")] public decimal Average { get; set; } [Alias("MAX_BUDGET")] public decimal Max { get; set; } [Alias("MIN_BUDGET")] public decimal Min { get; set; } } [Alias("SHOW_LANGS")] public class ProcedureShowLangsParameters{ [Alias("CODE")] public string Code{ get; set; } [Alias("GRADE")] public Int16 Grade{ get; set; } [Alias("CTY")] public string Country{ get; set; } } public class ProcedureShowLangsResult{ [Alias("LANGUAGES")] public string Language{ get; set; } } [Alias("ALL_LANGS")] public class ProcedureAllLangs{ public List<ProcedureAllLangsResult> Execute(IDbCommand dbConn){ return dbConn.SelectFromProcedure<ProcedureAllLangsResult>(this); } //public List<ProcedureAllLangsResult> Results{ // get; set; //} public class ProcedureAllLangsResult{ [Alias("CODE")] public string Code{ get; set; } [Alias("GRADE")] public string Grade{ get; set; } [Alias("COUNTRY")] public string Country{ get; set; } [Alias("LANG")] public string Language{ get; set; } } } class MainClass { public static void Main (string[] args) { Console.WriteLine ("Hello World!"); OrmLiteConfig.DialectProvider = new FirebirdOrmLiteDialectProvider(); using (IDbConnection db = "User=SYSDBA;Password=masterkey;Database=employee.fdb;DataSource=localhost;Dialect=3;charset=ISO8859_1;".OpenDbConnection()) using ( IDbCommand dbConn = db.CreateCommand()) { try{ var employees = dbConn.Select<Employee>(); Console.WriteLine("Total Employees '{0}'", employees.Count); Employee employee = new Employee(){ FirstName="LILA", LastName= "FUTURAMA", PhoneExtension="0002", HireDate= DateTime.Now, DepartamentNumber= "900", JobCode="Eng", JobGrade=2, JobCountry="USA", Salary=75000 }; int count = employees.Count; dbConn.Insert(employee); Console.WriteLine ("Id for new employee : '{0}'", employee.Id); employees = dbConn.Select<Employee>(); Console.WriteLine("Total Employees '{0}' = '{1}'", employees.Count, count+1); Console.WriteLine("Executing 'DELETE_EMPLOYEE' for '{0}' - {1}", employee.Id, employee.LastName ); ProcedureDeleteEmployee de = new ProcedureDeleteEmployee(); de.EmployeeNumber= employee.Id; dbConn.ExecuteProcedure(de); employees = dbConn.Select<Employee>(); Console.WriteLine("Total Employees '{0}'= '{1}' ", employees.Count, count); } catch(Exception e){ Console.WriteLine(e.Message); } try{ ProcedureSubTotalBudgetParameters p = new ProcedureSubTotalBudgetParameters() { HeadDepartament="000" }; var results = dbConn.SelectFromProcedure<ProcedureSubTotalBudgetResult>(p, ""); foreach(var r in results){ Console.WriteLine("r.Total:{0} r.Average:{1} r.Max:{2} r.Min:{3}", r.Total, r.Average, r.Max, r.Min); } } catch(Exception e){ Console.WriteLine(e.Message); } try{ ProcedureShowLangsParameters l = new ProcedureShowLangsParameters() { Code ="Sales", Grade =3, Country ="England" }; var ls = dbConn.SelectFromProcedure<ProcedureShowLangsResult>(l,""); foreach(var lr in ls){ Console.WriteLine(lr.Language); } } catch(Exception e){ Console.WriteLine(e.Message); } try{ ProcedureAllLangs l = new ProcedureAllLangs(); //var ls = dbConn.SelectFromProcedure<ProcedureAllLangsResult>(l); //dbConn.SelectFromProcedure(l); var ls = l.Execute(dbConn); // better ? foreach(var lr in ls){ Console.WriteLine("lr.Code:{0} lr.Country:{1} lr.Grade:{2} lr.Language:{3}", lr.Code, lr.Country, lr.Grade, lr.Language); } } catch(Exception e){ Console.WriteLine(e.Message); } Console.WriteLine ("This is The End my friend!"); } } } }
// // Copyright 2011-2013, Xamarin Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Android.App; using Android.Content; using Android.Database; using Android.OS; using Android.Provider; using Environment = Android.OS.Environment; using Path = System.IO.Path; using Uri = Android.Net.Uri; using Media.Plugin.Abstractions; namespace Media.Plugin { /// <summary> /// Picker /// </summary> [Activity] [Android.Runtime.Preserve(AllMembers = true)] public class MediaPickerActivity : Activity { internal const string ExtraPath = "path"; internal const string ExtraLocation = "location"; internal const string ExtraType = "type"; internal const string ExtraId = "id"; internal const string ExtraAction = "action"; internal const string ExtraTasked = "tasked"; internal static event EventHandler<MediaPickedEventArgs> MediaPicked; private int id; private string title; private string description; private string type; /// <summary> /// The user's destination path. /// </summary> private Uri path; private bool isPhoto; private string action; private int seconds; private VideoQuality quality; private bool tasked; /// <summary> /// OnSaved /// </summary> /// <param name="outState"></param> protected override void OnSaveInstanceState(Bundle outState) { outState.PutBoolean("ran", true); outState.PutString(MediaStore.MediaColumns.Title, this.title); outState.PutString(MediaStore.Images.ImageColumns.Description, this.description); outState.PutInt(ExtraId, this.id); outState.PutString(ExtraType, this.type); outState.PutString(ExtraAction, this.action); outState.PutInt(MediaStore.ExtraDurationLimit, this.seconds); outState.PutInt(MediaStore.ExtraVideoQuality, (int)this.quality); outState.PutBoolean(ExtraTasked, this.tasked); if (this.path != null) outState.PutString(ExtraPath, this.path.Path); base.OnSaveInstanceState(outState); } /// <summary> /// OnCreate /// </summary> /// <param name="savedInstanceState"></param> protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Bundle b = (savedInstanceState ?? Intent.Extras); bool ran = b.GetBoolean("ran", defaultValue: false); this.title = b.GetString(MediaStore.MediaColumns.Title); this.description = b.GetString(MediaStore.Images.ImageColumns.Description); this.tasked = b.GetBoolean(ExtraTasked); this.id = b.GetInt(ExtraId, 0); this.type = b.GetString(ExtraType); if (this.type == "image/*") this.isPhoto = true; this.action = b.GetString(ExtraAction); Intent pickIntent = null; try { pickIntent = new Intent(this.action); if (this.action == Intent.ActionPick) pickIntent.SetType(type); else { if (!this.isPhoto) { this.seconds = b.GetInt(MediaStore.ExtraDurationLimit, 0); if (this.seconds != 0) pickIntent.PutExtra(MediaStore.ExtraDurationLimit, seconds); } this.quality = (VideoQuality)b.GetInt(MediaStore.ExtraVideoQuality, (int)VideoQuality.High); pickIntent.PutExtra(MediaStore.ExtraVideoQuality, GetVideoQuality(this.quality)); if (!ran) { this.path = GetOutputMediaFile(this, b.GetString(ExtraPath), this.title, this.isPhoto); Touch(); pickIntent.PutExtra(MediaStore.ExtraOutput, this.path); } else this.path = Uri.Parse(b.GetString(ExtraPath)); } if (!ran) StartActivityForResult(pickIntent, this.id); } catch (Exception ex) { OnMediaPicked(new MediaPickedEventArgs(this.id, ex)); } finally { if (pickIntent != null) pickIntent.Dispose(); } } private void Touch() { if (this.path.Scheme != "file") return; File.Create(GetLocalPath(this.path)).Close(); } internal static Task<MediaPickedEventArgs> GetMediaFileAsync(Context context, int requestCode, string action, bool isPhoto, ref Uri path, Uri data) { Task<Tuple<string, bool>> pathFuture; string originalPath = null; if (action != Intent.ActionPick) { originalPath = path.Path; // Not all camera apps respect EXTRA_OUTPUT, some will instead // return a content or file uri from data. if (data != null && data.Path != originalPath) { originalPath = data.ToString(); string currentPath = path.Path; pathFuture = TryMoveFileAsync(context, data, path, isPhoto).ContinueWith(t => new Tuple<string, bool>(t.Result ? currentPath : null, false)); } else pathFuture = TaskFromResult(new Tuple<string, bool>(path.Path, false)); } else if (data != null) { originalPath = data.ToString(); path = data; pathFuture = GetFileForUriAsync(context, path, isPhoto); } else pathFuture = TaskFromResult<Tuple<string, bool>>(null); return pathFuture.ContinueWith(t => { string resultPath = t.Result.Item1; if (resultPath != null && File.Exists(t.Result.Item1)) { var name = resultPath.Substring(resultPath.LastIndexOf("/")); var mf = new MediaFile(name, resultPath, () => { return File.OpenRead(resultPath); }, deletePathOnDispose: t.Result.Item2, dispose: (dis) => { if (t.Result.Item2) { try { File.Delete(t.Result.Item1); // We don't really care if this explodes for a normal IO reason. } catch (UnauthorizedAccessException) { } catch (DirectoryNotFoundException) { } catch (IOException) { } } }); return new MediaPickedEventArgs(requestCode, false, mf); } else return new MediaPickedEventArgs(requestCode, new MediaFileNotFoundException(originalPath)); }); } /// <summary> /// OnActivity Result /// </summary> /// <param name="requestCode"></param> /// <param name="resultCode"></param> /// <param name="data"></param> protected override void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (this.tasked) { Task<MediaPickedEventArgs> future; if (resultCode == Result.Canceled) future = TaskFromResult(new MediaPickedEventArgs(requestCode, isCanceled: true)); else future = GetMediaFileAsync(this, requestCode, this.action, this.isPhoto, ref this.path, (data != null) ? data.Data : null); Finish(); future.ContinueWith(t => OnMediaPicked(t.Result)); } else { if (resultCode == Result.Canceled) SetResult(Result.Canceled); else { Intent resultData = new Intent(); resultData.PutExtra("MediaFile", (data != null) ? data.Data : null); resultData.PutExtra("path", this.path); resultData.PutExtra("isPhoto", this.isPhoto); resultData.PutExtra("action", this.action); SetResult(Result.Ok, resultData); } Finish(); } } private static Task<bool> TryMoveFileAsync(Context context, Uri url, Uri path, bool isPhoto) { string moveTo = GetLocalPath(path); return GetFileForUriAsync(context, url, isPhoto).ContinueWith(t => { if (t.Result.Item1 == null) return false; File.Delete(moveTo); File.Move(t.Result.Item1, moveTo); if (url.Scheme == "content") context.ContentResolver.Delete(url, null, null); return true; }, TaskScheduler.Default); } private static int GetVideoQuality(VideoQuality videoQuality) { switch (videoQuality) { case VideoQuality.Medium: case VideoQuality.High: return 1; default: return 0; } } private static string GetUniquePath(string folder, string name, bool isPhoto) { string ext = Path.GetExtension(name); if (ext == String.Empty) ext = ((isPhoto) ? ".jpg" : ".mp4"); name = Path.GetFileNameWithoutExtension(name); string nname = name + ext; int i = 1; while (File.Exists(Path.Combine(folder, nname))) nname = name + "_" + (i++) + ext; return Path.Combine(folder, nname); } private static Uri GetOutputMediaFile(Context context, string subdir, string name, bool isPhoto) { subdir = subdir ?? String.Empty; if (String.IsNullOrWhiteSpace(name)) { string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss"); if (isPhoto) name = "IMG_" + timestamp + ".jpg"; else name = "VID_" + timestamp + ".mp4"; } string mediaType = (isPhoto) ? Environment.DirectoryPictures : Environment.DirectoryMovies; using (Java.IO.File mediaStorageDir = new Java.IO.File(context.GetExternalFilesDir(mediaType), subdir)) { if (!mediaStorageDir.Exists()) { if (!mediaStorageDir.Mkdirs()) throw new IOException("Couldn't create directory, have you added the WRITE_EXTERNAL_STORAGE permission?"); // Ensure this media doesn't show up in gallery apps using (Java.IO.File nomedia = new Java.IO.File(mediaStorageDir, ".nomedia")) nomedia.CreateNewFile(); } return Uri.FromFile(new Java.IO.File(GetUniquePath(mediaStorageDir.Path, name, isPhoto))); } } internal static Task<Tuple<string, bool>> GetFileForUriAsync(Context context, Uri uri, bool isPhoto) { var tcs = new TaskCompletionSource<Tuple<string, bool>>(); if (uri.Scheme == "file") tcs.SetResult(new Tuple<string, bool>(new System.Uri(uri.ToString()).LocalPath, false)); else if (uri.Scheme == "content") { Task.Factory.StartNew(() => { ICursor cursor = null; try { cursor = context.ContentResolver.Query(uri, null, null, null, null); if (cursor == null || !cursor.MoveToNext()) tcs.SetResult(new Tuple<string, bool>(null, false)); else { int column = cursor.GetColumnIndex(MediaStore.MediaColumns.Data); string contentPath = null; if (column != -1) contentPath = cursor.GetString(column); bool copied = false; // If they don't follow the "rules", try to copy the file locally if (contentPath == null || !contentPath.StartsWith("file")) { copied = true; Uri outputPath = GetOutputMediaFile(context, "temp", null, isPhoto); try { using (Stream input = context.ContentResolver.OpenInputStream(uri)) using (Stream output = File.Create(outputPath.Path)) input.CopyTo(output); contentPath = outputPath.Path; } catch (Java.IO.FileNotFoundException) { // If there's no data associated with the uri, we don't know // how to open this. contentPath will be null which will trigger // MediaFileNotFoundException. } } tcs.SetResult(new Tuple<string, bool>(contentPath, copied)); } } finally { if (cursor != null) { cursor.Close(); cursor.Dispose(); } } }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); } else tcs.SetResult(new Tuple<string, bool>(null, false)); return tcs.Task; } private static string GetLocalPath(Uri uri) { return new System.Uri(uri.ToString()).LocalPath; } private static Task<T> TaskFromResult<T>(T result) { var tcs = new TaskCompletionSource<T>(); tcs.SetResult(result); return tcs.Task; } private static void OnMediaPicked(MediaPickedEventArgs e) { var picked = MediaPicked; if (picked != null) picked(null, e); } } internal class MediaPickedEventArgs : EventArgs { public MediaPickedEventArgs(int id, Exception error) { if (error == null) throw new ArgumentNullException("error"); RequestId = id; Error = error; } public MediaPickedEventArgs(int id, bool isCanceled, MediaFile media = null) { RequestId = id; IsCanceled = isCanceled; if (!IsCanceled && media == null) throw new ArgumentNullException("media"); Media = media; } public int RequestId { get; private set; } public bool IsCanceled { get; private set; } public Exception Error { get; private set; } public MediaFile Media { get; private set; } public Task<MediaFile> ToTask() { var tcs = new TaskCompletionSource<MediaFile>(); if (IsCanceled) tcs.SetResult(null); else if (Error != null) tcs.SetResult(null); else tcs.SetResult(Media); return tcs.Task; } } }
using NuGet.Packaging.Core; using NuGet.Versioning; using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; using System.Linq; using NSubstitute; using NuKeeper.Abstractions; using NuKeeper.Abstractions.Logging; using NuKeeper.Inspection.Sort; using NuKeeper.Inspection.RepositoryInspection; using NuKeeper.Abstractions.RepositoryInspection; namespace NuKeeper.Tests.Engine.Sort { [TestFixture] public class PackageUpdateSortTests { private static readonly DateTimeOffset StandardPublishedDate = new DateTimeOffset(2018, 2, 19, 11, 12, 7, TimeSpan.Zero); [Test] public void CanSortWhenListIsEmpty() { var items = new List<PackageUpdateSet>(); var output = Sort(items); Assert.That(output, Is.Not.Null); } [Test] public void CanSortOneItem() { var items = OnePackageUpdateSet(1) .InList(); var output = Sort(items); Assert.That(output, Is.Not.Null); Assert.That(output.Count, Is.EqualTo(1)); Assert.That(output[0], Is.EqualTo(items[0])); } [Test] public void CanSortTwoItems() { var items = new List<PackageUpdateSet> { OnePackageUpdateSet(1), OnePackageUpdateSet(2) }; var output = Sort(items); Assert.That(output, Is.Not.Null); Assert.That(output.Count, Is.EqualTo(2)); } [Test] public void CanSortThreeItems() { var items = new List<PackageUpdateSet> { OnePackageUpdateSet(1), OnePackageUpdateSet(2), OnePackageUpdateSet(3), }; var output = Sort(items); Assert.That(output, Is.Not.Null); Assert.That(output.Count, Is.EqualTo(3)); } [Test] public void TwoPackageVersionsIsSortedToTop() { var twoVersions = MakeTwoProjectVersions(); var items = new List<PackageUpdateSet> { OnePackageUpdateSet(3), OnePackageUpdateSet(4), twoVersions }; var output = Sort(items); Assert.That(output, Is.Not.Null); Assert.That(output[0], Is.EqualTo(twoVersions)); } [Test] public void WillSortByProjectCount() { var items = new List<PackageUpdateSet> { OnePackageUpdateSet(1), OnePackageUpdateSet(2), OnePackageUpdateSet(3), }; var output = Sort(items); Assert.That(output.Count, Is.EqualTo(3)); Assert.That(output[0].CurrentPackages.Count, Is.EqualTo(3)); Assert.That(output[1].CurrentPackages.Count, Is.EqualTo(2)); Assert.That(output[2].CurrentPackages.Count, Is.EqualTo(1)); } [Test] public void WillSortByProjectVersionsOverProjectCount() { var twoVersions = MakeTwoProjectVersions(); var items = new List<PackageUpdateSet> { OnePackageUpdateSet(10), OnePackageUpdateSet(20), twoVersions, }; var output = Sort(items); Assert.That(output.Count, Is.EqualTo(3)); Assert.That(output[0], Is.EqualTo(twoVersions)); Assert.That(output[1].CurrentPackages.Count, Is.EqualTo(20)); Assert.That(output[2].CurrentPackages.Count, Is.EqualTo(10)); } [Test] public void WillSortByBiggestVersionChange() { var items = new List<PackageUpdateSet> { PackageChange("1.2.4", "1.2.3"), PackageChange("2.0.0", "1.2.3"), PackageChange("1.3.0", "1.2.3") }; var output = Sort(items); Assert.That(output.Count, Is.EqualTo(3)); Assert.That(SelectedVersion(output[0]), Is.EqualTo("2.0.0")); Assert.That(SelectedVersion(output[1]), Is.EqualTo("1.3.0")); Assert.That(SelectedVersion(output[2]), Is.EqualTo("1.2.4")); } [Test] public void WillSortByGettingOutOfBetaFirst() { var items = new List<PackageUpdateSet> { PackageChange("2.0.0", "1.2.3"), PackageChange("1.2.4", "1.2.3-beta1"), PackageChange("1.3.0-pre-2", "1.2.3-beta1") }; var output = Sort(items); Assert.That(output.Count, Is.EqualTo(3)); Assert.That(SelectedVersion(output[0]), Is.EqualTo("1.2.4")); Assert.That(SelectedVersion(output[1]), Is.EqualTo("2.0.0")); Assert.That(SelectedVersion(output[2]), Is.EqualTo("1.3.0-pre-2")); } [Test] public void WillSortByOldestFirstOverPatchVersionIncrement() { var items = new List<PackageUpdateSet> { PackageChange("1.2.6", "1.2.3", StandardPublishedDate), PackageChange("1.2.5", "1.2.3", StandardPublishedDate.AddYears(-1)), PackageChange("1.2.4", "1.2.3", StandardPublishedDate.AddYears(-2)) }; var output = Sort(items); Assert.That(output.Count, Is.EqualTo(3)); Assert.That(SelectedVersion(output[0]), Is.EqualTo("1.2.4")); Assert.That(SelectedVersion(output[1]), Is.EqualTo("1.2.5")); Assert.That(SelectedVersion(output[2]), Is.EqualTo("1.2.6")); } private static string SelectedVersion(PackageUpdateSet packageUpdateSet) { return packageUpdateSet.Selected.Identity.Version.ToString(); } private static PackageInProject MakePackageInProjectFor(PackageIdentity package) { var path = new PackagePath( Path.GetTempPath(), Path.Combine("folder", "src", "project1", "packages.config"), PackageReferenceType.PackagesConfig); return new PackageInProject(package.Id, package.Version.ToString(), path); } private static PackageUpdateSet OnePackageUpdateSet(int projectCount) { var newPackage = new PackageIdentity("foo.bar", new NuGetVersion("1.4.5")); var package = new PackageIdentity("foo.bar", new NuGetVersion("1.2.3")); var projects = new List<PackageInProject>(); foreach (var i in Enumerable.Range(1, projectCount)) { projects.Add(MakePackageInProjectFor(package)); } return PackageUpdates.UpdateSetFor(newPackage, projects.ToArray()); } private static PackageUpdateSet MakeTwoProjectVersions() { var newPackage = new PackageIdentity("foo.bar", new NuGetVersion("1.4.5")); var package123 = new PackageIdentity("foo.bar", new NuGetVersion("1.2.3")); var package124 = new PackageIdentity("foo.bar", new NuGetVersion("1.2.4")); var projects = new List<PackageInProject> { MakePackageInProjectFor(package123), MakePackageInProjectFor(package124), }; return PackageUpdates.UpdateSetFor(newPackage, projects.ToArray()); } private static PackageUpdateSet PackageChange(string newVersion, string oldVersion, DateTimeOffset? publishedDate = null) { var newPackage = new PackageIdentity("foo.bar", new NuGetVersion(newVersion)); var oldPackage = new PackageIdentity("foo.bar", new NuGetVersion(oldVersion)); if (!publishedDate.HasValue) { publishedDate = StandardPublishedDate; } var projects = new List<PackageInProject> { MakePackageInProjectFor(oldPackage) }; return PackageUpdates.UpdateSetFor(newPackage, publishedDate.Value, projects.ToArray()); } private static List<PackageUpdateSet> Sort(IReadOnlyCollection<PackageUpdateSet> input) { var sorter = new PackageUpdateSetSort(Substitute.For<INuKeeperLogger>()); return sorter.Sort(input) .ToList(); } } }