context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/*
* 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.
*/
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable NonReadonlyMemberInGetHashCode
#pragma warning disable 618
namespace Apache.Ignite.Core.Tests
{
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache.Affinity.Rendezvous;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cache.Eviction;
using Apache.Ignite.Core.Cache.Expiry;
using Apache.Ignite.Core.Cache.Store;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Ssl;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Communication.Tcp;
using Apache.Ignite.Core.Configuration;
using Apache.Ignite.Core.DataStructures.Configuration;
using Apache.Ignite.Core.Deployment;
using Apache.Ignite.Core.Discovery.Tcp;
using Apache.Ignite.Core.Discovery.Tcp.Multicast;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Failure;
using Apache.Ignite.Core.Lifecycle;
using Apache.Ignite.Core.Log;
using Apache.Ignite.Core.PersistentStore;
using Apache.Ignite.Core.Plugin.Cache;
using Apache.Ignite.Core.Tests.Binary;
using Apache.Ignite.Core.Tests.Plugin;
using Apache.Ignite.Core.Transactions;
using NUnit.Framework;
using CheckpointWriteOrder = Apache.Ignite.Core.PersistentStore.CheckpointWriteOrder;
using DataPageEvictionMode = Apache.Ignite.Core.Cache.Configuration.DataPageEvictionMode;
using WalMode = Apache.Ignite.Core.PersistentStore.WalMode;
/// <summary>
/// Tests <see cref="IgniteConfiguration"/> serialization.
/// </summary>
public class IgniteConfigurationSerializerTest
{
/// <summary>
/// Tests the predefined XML.
/// </summary>
[Test]
public void TestPredefinedXml()
{
var xml = File.ReadAllText(Path.Combine("Config", "full-config.xml"));
var cfg = IgniteConfiguration.FromXml(xml);
Assert.AreEqual("c:", cfg.WorkDirectory);
Assert.AreEqual("127.1.1.1", cfg.Localhost);
Assert.IsTrue(cfg.IsDaemon);
Assert.AreEqual(1024, cfg.JvmMaxMemoryMb);
Assert.AreEqual(TimeSpan.FromSeconds(10), cfg.MetricsLogFrequency);
Assert.AreEqual(TimeSpan.FromMinutes(1), ((TcpDiscoverySpi)cfg.DiscoverySpi).JoinTimeout);
Assert.AreEqual("192.168.1.1", ((TcpDiscoverySpi)cfg.DiscoverySpi).LocalAddress);
Assert.AreEqual(6655, ((TcpDiscoverySpi)cfg.DiscoverySpi).LocalPort);
Assert.AreEqual(7,
((TcpDiscoveryMulticastIpFinder) ((TcpDiscoverySpi) cfg.DiscoverySpi).IpFinder).AddressRequestAttempts);
Assert.AreEqual(new[] { "-Xms1g", "-Xmx4g" }, cfg.JvmOptions);
Assert.AreEqual(15, ((LifecycleBean) cfg.LifecycleHandlers.Single()).Foo);
Assert.AreEqual("testBar", ((NameMapper) cfg.BinaryConfiguration.NameMapper).Bar);
Assert.AreEqual(
"Apache.Ignite.Core.Tests.IgniteConfigurationSerializerTest+FooClass, Apache.Ignite.Core.Tests",
cfg.BinaryConfiguration.Types.Single());
Assert.IsFalse(cfg.BinaryConfiguration.CompactFooter);
Assert.AreEqual(new[] {42, EventType.TaskFailed, EventType.JobFinished}, cfg.IncludedEventTypes);
Assert.AreEqual(@"c:\myconfig.xml", cfg.SpringConfigUrl);
Assert.IsTrue(cfg.AutoGenerateIgniteInstanceName);
Assert.AreEqual(new TimeSpan(1, 2, 3), cfg.LongQueryWarningTimeout);
Assert.IsFalse(cfg.IsActiveOnStart);
Assert.IsTrue(cfg.AuthenticationEnabled);
Assert.AreEqual(10000, cfg.MvccVacuumFrequency);
Assert.AreEqual(4, cfg.MvccVacuumThreadCount);
Assert.AreEqual(123, cfg.SqlQueryHistorySize);
Assert.IsNotNull(cfg.SqlSchemas);
Assert.AreEqual(2, cfg.SqlSchemas.Count);
Assert.IsTrue(cfg.SqlSchemas.Contains("SCHEMA_1"));
Assert.IsTrue(cfg.SqlSchemas.Contains("schema_2"));
Assert.AreEqual("someId012", cfg.ConsistentId);
Assert.IsFalse(cfg.RedirectJavaConsoleOutput);
Assert.AreEqual("secondCache", cfg.CacheConfiguration.Last().Name);
var cacheCfg = cfg.CacheConfiguration.First();
Assert.AreEqual(CacheMode.Replicated, cacheCfg.CacheMode);
Assert.IsTrue(cacheCfg.ReadThrough);
Assert.IsTrue(cacheCfg.WriteThrough);
Assert.IsInstanceOf<MyPolicyFactory>(cacheCfg.ExpiryPolicyFactory);
Assert.IsTrue(cacheCfg.EnableStatistics);
Assert.IsFalse(cacheCfg.WriteBehindCoalescing);
Assert.AreEqual(PartitionLossPolicy.ReadWriteAll, cacheCfg.PartitionLossPolicy);
Assert.AreEqual("fooGroup", cacheCfg.GroupName);
Assert.AreEqual("bar", cacheCfg.KeyConfiguration.Single().AffinityKeyFieldName);
Assert.AreEqual("foo", cacheCfg.KeyConfiguration.Single().TypeName);
Assert.IsTrue(cacheCfg.OnheapCacheEnabled);
Assert.AreEqual(8, cacheCfg.StoreConcurrentLoadAllThreshold);
Assert.AreEqual(9, cacheCfg.RebalanceOrder);
Assert.AreEqual(10, cacheCfg.RebalanceBatchesPrefetchCount);
Assert.AreEqual(11, cacheCfg.MaxQueryIteratorsCount);
Assert.AreEqual(12, cacheCfg.QueryDetailMetricsSize);
Assert.AreEqual(13, cacheCfg.QueryParallelism);
Assert.AreEqual("mySchema", cacheCfg.SqlSchema);
var queryEntity = cacheCfg.QueryEntities.Single();
Assert.AreEqual(typeof(int), queryEntity.KeyType);
Assert.AreEqual(typeof(string), queryEntity.ValueType);
Assert.AreEqual("myTable", queryEntity.TableName);
Assert.AreEqual("length", queryEntity.Fields.Single().Name);
Assert.AreEqual(typeof(int), queryEntity.Fields.Single().FieldType);
Assert.IsTrue(queryEntity.Fields.Single().IsKeyField);
Assert.IsTrue(queryEntity.Fields.Single().NotNull);
Assert.AreEqual(3.456d, (double)queryEntity.Fields.Single().DefaultValue);
Assert.AreEqual("somefield.field", queryEntity.Aliases.Single().FullName);
Assert.AreEqual("shortField", queryEntity.Aliases.Single().Alias);
var queryIndex = queryEntity.Indexes.Single();
Assert.AreEqual(QueryIndexType.Geospatial, queryIndex.IndexType);
Assert.AreEqual("indexFld", queryIndex.Fields.Single().Name);
Assert.AreEqual(true, queryIndex.Fields.Single().IsDescending);
Assert.AreEqual(123, queryIndex.InlineSize);
var nearCfg = cacheCfg.NearConfiguration;
Assert.IsNotNull(nearCfg);
Assert.AreEqual(7, nearCfg.NearStartSize);
var nodeFilter = (AttributeNodeFilter)cacheCfg.NodeFilter;
Assert.IsNotNull(nodeFilter);
var attributes = nodeFilter.Attributes.ToList();
Assert.AreEqual(3, nodeFilter.Attributes.Count);
Assert.AreEqual(new KeyValuePair<string, object>("myNode", "true"), attributes[0]);
Assert.AreEqual(new KeyValuePair<string, object>("foo", null), attributes[1]);
Assert.AreEqual(new KeyValuePair<string, object>("baz", null), attributes[2]);
var plc = nearCfg.EvictionPolicy as FifoEvictionPolicy;
Assert.IsNotNull(plc);
Assert.AreEqual(10, plc.BatchSize);
Assert.AreEqual(20, plc.MaxSize);
Assert.AreEqual(30, plc.MaxMemorySize);
var plc2 = cacheCfg.EvictionPolicy as LruEvictionPolicy;
Assert.IsNotNull(plc2);
Assert.AreEqual(1, plc2.BatchSize);
Assert.AreEqual(2, plc2.MaxSize);
Assert.AreEqual(3, plc2.MaxMemorySize);
var af = cacheCfg.AffinityFunction as RendezvousAffinityFunction;
Assert.IsNotNull(af);
Assert.AreEqual(99, af.Partitions);
Assert.IsTrue(af.ExcludeNeighbors);
var platformCacheConfiguration = cacheCfg.PlatformCacheConfiguration;
Assert.AreEqual("int", platformCacheConfiguration.KeyTypeName);
Assert.AreEqual("string", platformCacheConfiguration.ValueTypeName);
Assert.IsTrue(platformCacheConfiguration.KeepBinary);
Assert.AreEqual(new Dictionary<string, object>
{
{"myNode", "true"},
{"foo", new FooClass {Bar = "Baz"}}
}, cfg.UserAttributes);
var atomicCfg = cfg.AtomicConfiguration;
Assert.AreEqual(2, atomicCfg.Backups);
Assert.AreEqual(CacheMode.Local, atomicCfg.CacheMode);
Assert.AreEqual(250, atomicCfg.AtomicSequenceReserveSize);
var tx = cfg.TransactionConfiguration;
Assert.AreEqual(TransactionConcurrency.Optimistic, tx.DefaultTransactionConcurrency);
Assert.AreEqual(TransactionIsolation.RepeatableRead, tx.DefaultTransactionIsolation);
Assert.AreEqual(new TimeSpan(0,1,2), tx.DefaultTimeout);
Assert.AreEqual(15, tx.PessimisticTransactionLogSize);
Assert.AreEqual(TimeSpan.FromSeconds(33), tx.PessimisticTransactionLogLinger);
var comm = cfg.CommunicationSpi as TcpCommunicationSpi;
Assert.IsNotNull(comm);
Assert.AreEqual(33, comm.AckSendThreshold);
Assert.AreEqual(new TimeSpan(0, 1, 2), comm.IdleConnectionTimeout);
Assert.IsInstanceOf<TestLogger>(cfg.Logger);
var binType = cfg.BinaryConfiguration.TypeConfigurations.Single();
Assert.AreEqual("typeName", binType.TypeName);
Assert.AreEqual("affKeyFieldName", binType.AffinityKeyFieldName);
Assert.IsTrue(binType.IsEnum);
Assert.AreEqual(true, binType.KeepDeserialized);
Assert.IsInstanceOf<IdMapper>(binType.IdMapper);
Assert.IsInstanceOf<NameMapper>(binType.NameMapper);
Assert.IsInstanceOf<TestSerializer>(binType.Serializer);
var plugins = cfg.PluginConfigurations;
Assert.IsNotNull(plugins);
Assert.IsNotNull(plugins.Cast<TestIgnitePluginConfiguration>().SingleOrDefault());
Assert.IsNotNull(cacheCfg.PluginConfigurations.Cast<MyPluginConfiguration>().SingleOrDefault());
var eventStorage = cfg.EventStorageSpi as MemoryEventStorageSpi;
Assert.IsNotNull(eventStorage);
Assert.AreEqual(23.45, eventStorage.ExpirationTimeout.TotalSeconds);
Assert.AreEqual(129, eventStorage.MaxEventCount);
var memCfg = cfg.MemoryConfiguration;
Assert.IsNotNull(memCfg);
Assert.AreEqual(3, memCfg.ConcurrencyLevel);
Assert.AreEqual("dfPlc", memCfg.DefaultMemoryPolicyName);
Assert.AreEqual(45, memCfg.PageSize);
Assert.AreEqual(67, memCfg.SystemCacheInitialSize);
Assert.AreEqual(68, memCfg.SystemCacheMaxSize);
var memPlc = memCfg.MemoryPolicies.Single();
Assert.AreEqual(1, memPlc.EmptyPagesPoolSize);
Assert.AreEqual(0.2, memPlc.EvictionThreshold);
Assert.AreEqual("dfPlc", memPlc.Name);
Assert.AreEqual(DataPageEvictionMode.RandomLru, memPlc.PageEvictionMode);
Assert.AreEqual("abc", memPlc.SwapFilePath);
Assert.AreEqual(89, memPlc.InitialSize);
Assert.AreEqual(98, memPlc.MaxSize);
Assert.IsTrue(memPlc.MetricsEnabled);
Assert.AreEqual(9, memPlc.SubIntervals);
Assert.AreEqual(TimeSpan.FromSeconds(62), memPlc.RateTimeInterval);
Assert.AreEqual(PeerAssemblyLoadingMode.CurrentAppDomain, cfg.PeerAssemblyLoadingMode);
var sql = cfg.SqlConnectorConfiguration;
Assert.IsNotNull(sql);
Assert.AreEqual("bar", sql.Host);
Assert.AreEqual(10, sql.Port);
Assert.AreEqual(11, sql.PortRange);
Assert.AreEqual(12, sql.SocketSendBufferSize);
Assert.AreEqual(13, sql.SocketReceiveBufferSize);
Assert.IsTrue(sql.TcpNoDelay);
Assert.AreEqual(14, sql.MaxOpenCursorsPerConnection);
Assert.AreEqual(15, sql.ThreadPoolSize);
var client = cfg.ClientConnectorConfiguration;
Assert.IsNotNull(client);
Assert.AreEqual("bar", client.Host);
Assert.AreEqual(10, client.Port);
Assert.AreEqual(11, client.PortRange);
Assert.AreEqual(12, client.SocketSendBufferSize);
Assert.AreEqual(13, client.SocketReceiveBufferSize);
Assert.IsTrue(client.TcpNoDelay);
Assert.AreEqual(14, client.MaxOpenCursorsPerConnection);
Assert.AreEqual(15, client.ThreadPoolSize);
Assert.AreEqual(19, client.IdleTimeout.TotalSeconds);
Assert.AreEqual(20, client.ThinClientConfiguration.MaxActiveTxPerConnection);
Assert.AreEqual(21, client.ThinClientConfiguration.MaxActiveComputeTasksPerConnection);
var pers = cfg.PersistentStoreConfiguration;
Assert.AreEqual(true, pers.AlwaysWriteFullPages);
Assert.AreEqual(TimeSpan.FromSeconds(1), pers.CheckpointingFrequency);
Assert.AreEqual(2, pers.CheckpointingPageBufferSize);
Assert.AreEqual(3, pers.CheckpointingThreads);
Assert.AreEqual(TimeSpan.FromSeconds(4), pers.LockWaitTime);
Assert.AreEqual("foo", pers.PersistentStorePath);
Assert.AreEqual(5, pers.TlbSize);
Assert.AreEqual("bar", pers.WalArchivePath);
Assert.AreEqual(TimeSpan.FromSeconds(6), pers.WalFlushFrequency);
Assert.AreEqual(7, pers.WalFsyncDelayNanos);
Assert.AreEqual(8, pers.WalHistorySize);
Assert.AreEqual(WalMode.None, pers.WalMode);
Assert.AreEqual(9, pers.WalRecordIteratorBufferSize);
Assert.AreEqual(10, pers.WalSegments);
Assert.AreEqual(11, pers.WalSegmentSize);
Assert.AreEqual("baz", pers.WalStorePath);
Assert.IsTrue(pers.MetricsEnabled);
Assert.AreEqual(3, pers.SubIntervals);
Assert.AreEqual(TimeSpan.FromSeconds(6), pers.RateTimeInterval);
Assert.AreEqual(CheckpointWriteOrder.Random, pers.CheckpointWriteOrder);
Assert.IsTrue(pers.WriteThrottlingEnabled);
var listeners = cfg.LocalEventListeners;
Assert.AreEqual(2, listeners.Count);
var rebalListener = (LocalEventListener<CacheRebalancingEvent>) listeners.First();
Assert.AreEqual(new[] {EventType.CacheObjectPut, 81}, rebalListener.EventTypes);
Assert.AreEqual("Apache.Ignite.Core.Tests.EventsTestLocalListeners+Listener`1" +
"[Apache.Ignite.Core.Events.CacheRebalancingEvent]",
rebalListener.Listener.GetType().ToString());
var ds = cfg.DataStorageConfiguration;
Assert.IsFalse(ds.AlwaysWriteFullPages);
Assert.AreEqual(TimeSpan.FromSeconds(1), ds.CheckpointFrequency);
Assert.AreEqual(3, ds.CheckpointThreads);
Assert.AreEqual(4, ds.ConcurrencyLevel);
Assert.AreEqual(TimeSpan.FromSeconds(5), ds.LockWaitTime);
Assert.IsTrue(ds.MetricsEnabled);
Assert.AreEqual(6, ds.PageSize);
Assert.AreEqual("cde", ds.StoragePath);
Assert.AreEqual(TimeSpan.FromSeconds(7), ds.MetricsRateTimeInterval);
Assert.AreEqual(8, ds.MetricsSubIntervalCount);
Assert.AreEqual(9, ds.SystemRegionInitialSize);
Assert.AreEqual(10, ds.SystemRegionMaxSize);
Assert.AreEqual(11, ds.WalThreadLocalBufferSize);
Assert.AreEqual("abc", ds.WalArchivePath);
Assert.AreEqual(TimeSpan.FromSeconds(12), ds.WalFlushFrequency);
Assert.AreEqual(13, ds.WalFsyncDelayNanos);
Assert.AreEqual(14, ds.WalHistorySize);
Assert.AreEqual(Core.Configuration.WalMode.Background, ds.WalMode);
Assert.AreEqual(15, ds.WalRecordIteratorBufferSize);
Assert.AreEqual(16, ds.WalSegments);
Assert.AreEqual(17, ds.WalSegmentSize);
Assert.AreEqual("wal-store", ds.WalPath);
Assert.AreEqual(TimeSpan.FromSeconds(18), ds.WalAutoArchiveAfterInactivity);
Assert.IsTrue(ds.WriteThrottlingEnabled);
Assert.AreEqual(DiskPageCompression.Zstd, ds.WalPageCompression);
var dr = ds.DataRegionConfigurations.Single();
Assert.AreEqual(1, dr.EmptyPagesPoolSize);
Assert.AreEqual(2, dr.EvictionThreshold);
Assert.AreEqual(3, dr.InitialSize);
Assert.AreEqual(4, dr.MaxSize);
Assert.AreEqual("reg2", dr.Name);
Assert.AreEqual(Core.Configuration.DataPageEvictionMode.RandomLru, dr.PageEvictionMode);
Assert.AreEqual(TimeSpan.FromSeconds(1), dr.MetricsRateTimeInterval);
Assert.AreEqual(5, dr.MetricsSubIntervalCount);
Assert.AreEqual("swap", dr.SwapPath);
Assert.IsTrue(dr.MetricsEnabled);
Assert.AreEqual(7, dr.CheckpointPageBufferSize);
dr = ds.DefaultDataRegionConfiguration;
Assert.AreEqual(2, dr.EmptyPagesPoolSize);
Assert.AreEqual(3, dr.EvictionThreshold);
Assert.AreEqual(4, dr.InitialSize);
Assert.AreEqual(5, dr.MaxSize);
Assert.AreEqual("reg1", dr.Name);
Assert.AreEqual(Core.Configuration.DataPageEvictionMode.Disabled, dr.PageEvictionMode);
Assert.AreEqual(TimeSpan.FromSeconds(3), dr.MetricsRateTimeInterval);
Assert.AreEqual(6, dr.MetricsSubIntervalCount);
Assert.AreEqual("swap2", dr.SwapPath);
Assert.IsFalse(dr.MetricsEnabled);
Assert.IsInstanceOf<SslContextFactory>(cfg.SslContextFactory);
Assert.IsInstanceOf<StopNodeOrHaltFailureHandler>(cfg.FailureHandler);
var failureHandler = (StopNodeOrHaltFailureHandler)cfg.FailureHandler;
Assert.IsTrue(failureHandler.TryStop);
Assert.AreEqual(TimeSpan.Parse("0:1:0"), failureHandler.Timeout);
var ec = cfg.ExecutorConfiguration;
Assert.NotNull(ec);
Assert.AreEqual(2, ec.Count);
Assert.AreEqual(new[] {"exec1", "exec2"}, ec.Select(e => e.Name));
Assert.AreEqual(new[] {1, 2}, ec.Select(e => e.Size));
}
/// <summary>
/// Tests the serialize deserialize.
/// </summary>
[Test]
public void TestSerializeDeserialize()
{
// Test custom
CheckSerializeDeserialize(GetTestConfig());
// Test custom with different culture to make sure numbers are serialized properly
RunWithCustomCulture(() => CheckSerializeDeserialize(GetTestConfig()));
// Test default
CheckSerializeDeserialize(new IgniteConfiguration());
}
/// <summary>
/// Tests that all properties are present in the schema.
/// </summary>
[Test]
public void TestAllPropertiesArePresentInSchema()
{
CheckAllPropertiesArePresentInSchema("IgniteConfigurationSection.xsd", "igniteConfiguration",
typeof(IgniteConfiguration));
}
/// <summary>
/// Checks that all properties are present in schema.
/// </summary>
[SuppressMessage("ReSharper", "PossibleNullReferenceException")]
public static void CheckAllPropertiesArePresentInSchema(string xsd, string sectionName, Type type)
{
var schema = XDocument.Load(xsd)
.Root.Elements()
.Single(x => x.Attribute("name").Value == sectionName);
CheckPropertyIsPresentInSchema(type, schema);
}
/// <summary>
/// Checks the property is present in schema.
/// </summary>
// ReSharper disable once UnusedParameter.Local
// ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local
private static void CheckPropertyIsPresentInSchema(Type type, XElement schema)
{
Func<string, string> toLowerCamel = x => char.ToLowerInvariant(x[0]) + x.Substring(1);
foreach (var prop in type.GetProperties())
{
if (!prop.CanWrite)
continue; // Read-only properties are not configured in XML.
if (prop.GetCustomAttributes(typeof(ObsoleteAttribute), true).Any())
continue; // Skip deprecated.
var propType = prop.PropertyType;
var isCollection = propType.IsGenericType &&
propType.GetGenericTypeDefinition() == typeof(ICollection<>);
if (isCollection)
propType = propType.GetGenericArguments().First();
var propName = toLowerCamel(prop.Name);
Assert.IsTrue(schema.Descendants().Select(x => x.Attribute("name"))
.Any(x => x != null && x.Value == propName),
"Property is missing in XML schema: " + propName);
var isComplexProp = propType.Namespace != null && propType.Namespace.StartsWith("Apache.Ignite.Core");
if (isComplexProp)
CheckPropertyIsPresentInSchema(propType, schema);
}
}
/// <summary>
/// Tests the schema validation.
/// </summary>
[Test]
public void TestSchemaValidation()
{
CheckSchemaValidation();
RunWithCustomCulture(CheckSchemaValidation);
// Check invalid xml
const string invalidXml =
@"<igniteConfiguration xmlns='http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection'>
<binaryConfiguration /><binaryConfiguration />
</igniteConfiguration>";
Assert.Throws<XmlSchemaValidationException>(() => CheckSchemaValidation(invalidXml));
}
/// <summary>
/// Tests the XML conversion.
/// </summary>
[Test]
public void TestToXml()
{
// Empty config
Assert.AreEqual(
"<?xml version=\"1.0\" encoding=\"utf-16\"?>" + Environment.NewLine +
"<igniteConfiguration xmlns=\"http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection\" />",
new IgniteConfiguration().ToXml());
// Some properties
var cfg = new IgniteConfiguration
{
IgniteInstanceName = "myGrid",
ClientMode = true,
CacheConfiguration = new[]
{
new CacheConfiguration("myCache")
{
CacheMode = CacheMode.Replicated,
QueryEntities = new[]
{
new QueryEntity(typeof(int)),
new QueryEntity(typeof(int), typeof(string))
}
}
},
IncludedEventTypes = new[]
{
EventType.CacheEntryCreated,
EventType.CacheNodesLeft
}
};
Assert.AreEqual(FixLineEndings(@"<?xml version=""1.0"" encoding=""utf-16""?>
<igniteConfiguration clientMode=""true"" igniteInstanceName=""myGrid"" xmlns=""http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection"">
<cacheConfiguration>
<cacheConfiguration cacheMode=""Replicated"" name=""myCache"">
<queryEntities>
<queryEntity valueType=""System.Int32"" valueTypeName=""java.lang.Integer"" />
<queryEntity keyType=""System.Int32"" keyTypeName=""java.lang.Integer"" valueType=""System.String"" valueTypeName=""java.lang.String"" />
</queryEntities>
</cacheConfiguration>
</cacheConfiguration>
<includedEventTypes>
<int>CacheEntryCreated</int>
<int>CacheNodesLeft</int>
</includedEventTypes>
</igniteConfiguration>"), cfg.ToXml());
// Custom section name and indent
var sb = new StringBuilder();
var settings = new XmlWriterSettings
{
Indent = true,
IndentChars = " "
};
using (var xmlWriter = XmlWriter.Create(sb, settings))
{
cfg.ToXml(xmlWriter, "igCfg");
}
Assert.AreEqual(FixLineEndings(@"<?xml version=""1.0"" encoding=""utf-16""?>
<igCfg clientMode=""true"" igniteInstanceName=""myGrid"" xmlns=""http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection"">
<cacheConfiguration>
<cacheConfiguration cacheMode=""Replicated"" name=""myCache"">
<queryEntities>
<queryEntity valueType=""System.Int32"" valueTypeName=""java.lang.Integer"" />
<queryEntity keyType=""System.Int32"" keyTypeName=""java.lang.Integer"" valueType=""System.String"" valueTypeName=""java.lang.String"" />
</queryEntities>
</cacheConfiguration>
</cacheConfiguration>
<includedEventTypes>
<int>CacheEntryCreated</int>
<int>CacheNodesLeft</int>
</includedEventTypes>
</igCfg>"), sb.ToString());
}
/// <summary>
/// Tests the deserialization.
/// </summary>
[Test]
public void TestFromXml()
{
// Empty section.
var cfg = IgniteConfiguration.FromXml("<x />");
AssertExtensions.ReflectionEqual(new IgniteConfiguration(), cfg);
// Empty section with XML header.
cfg = IgniteConfiguration.FromXml("<?xml version=\"1.0\" encoding=\"utf-16\"?><x />");
AssertExtensions.ReflectionEqual(new IgniteConfiguration(), cfg);
// Simple test.
cfg = IgniteConfiguration.FromXml(@"<igCfg igniteInstanceName=""myGrid"" clientMode=""true"" />");
AssertExtensions.ReflectionEqual(new IgniteConfiguration {IgniteInstanceName = "myGrid", ClientMode = true}, cfg);
// Invalid xml.
var ex = Assert.Throws<ConfigurationErrorsException>(() =>
IgniteConfiguration.FromXml(@"<igCfg foo=""bar"" />"));
Assert.AreEqual("Invalid IgniteConfiguration attribute 'foo=bar', there is no such property " +
"on 'Apache.Ignite.Core.IgniteConfiguration'", ex.Message);
// Xml reader.
using (var xmlReader = XmlReader.Create(
new StringReader(@"<igCfg igniteInstanceName=""myGrid"" clientMode=""true"" />")))
{
cfg = IgniteConfiguration.FromXml(xmlReader);
}
AssertExtensions.ReflectionEqual(new IgniteConfiguration { IgniteInstanceName = "myGrid", ClientMode = true }, cfg);
}
/// <summary>
/// Ensures windows-style \r\n line endings in a string literal.
/// Git settings may cause string literals in both styles.
/// </summary>
private static string FixLineEndings(string s)
{
return s.Split('\n').Select(x => x.TrimEnd('\r'))
.Aggregate((acc, x) => string.Format("{0}{1}{2}", acc, Environment.NewLine, x));
}
/// <summary>
/// Checks the schema validation.
/// </summary>
private static void CheckSchemaValidation()
{
CheckSchemaValidation(GetTestConfig().ToXml());
}
/// <summary>
/// Checks the schema validation.
/// </summary>
private static void CheckSchemaValidation(string xml)
{
var xmlns = "http://ignite.apache.org/schema/dotnet/IgniteConfigurationSection";
var schemaFile = "IgniteConfigurationSection.xsd";
CheckSchemaValidation(xml, xmlns, schemaFile);
}
/// <summary>
/// Checks the schema validation.
/// </summary>
public static void CheckSchemaValidation(string xml, string xmlns, string schemaFile)
{
var document = new XmlDocument();
document.Schemas.Add(xmlns, XmlReader.Create(schemaFile));
document.Load(new StringReader(xml));
document.Validate(null);
}
/// <summary>
/// Checks the serialize deserialize.
/// </summary>
/// <param name="cfg">The config.</param>
private static void CheckSerializeDeserialize(IgniteConfiguration cfg)
{
var resCfg = SerializeDeserialize(cfg);
AssertExtensions.ReflectionEqual(cfg, resCfg);
}
/// <summary>
/// Serializes and deserializes a config.
/// </summary>
private static IgniteConfiguration SerializeDeserialize(IgniteConfiguration cfg)
{
var xml = cfg.ToXml();
return IgniteConfiguration.FromXml(xml);
}
/// <summary>
/// Gets the test configuration.
/// </summary>
private static IgniteConfiguration GetTestConfig()
{
return new IgniteConfiguration
{
IgniteInstanceName = "gridName",
JvmOptions = new[] {"1", "2"},
Localhost = "localhost11",
JvmClasspath = "classpath",
Assemblies = new[] {"asm1", "asm2", "asm3"},
BinaryConfiguration = new BinaryConfiguration
{
TypeConfigurations = new[]
{
new BinaryTypeConfiguration
{
IsEnum = true,
KeepDeserialized = true,
AffinityKeyFieldName = "affKeyFieldName",
TypeName = "typeName",
IdMapper = new IdMapper(),
NameMapper = new NameMapper(),
Serializer = new TestSerializer()
},
new BinaryTypeConfiguration
{
IsEnum = false,
KeepDeserialized = false,
AffinityKeyFieldName = "affKeyFieldName",
TypeName = "typeName2",
Serializer = new BinaryReflectiveSerializer()
}
},
Types = new[] {typeof(string).FullName},
IdMapper = new IdMapper(),
KeepDeserialized = true,
NameMapper = new NameMapper(),
Serializer = new TestSerializer()
},
CacheConfiguration = new[]
{
new CacheConfiguration("cacheName")
{
AtomicityMode = CacheAtomicityMode.Transactional,
Backups = 15,
CacheMode = CacheMode.Replicated,
CacheStoreFactory = new TestCacheStoreFactory(),
CopyOnRead = false,
EagerTtl = false,
Invalidate = true,
KeepBinaryInStore = true,
LoadPreviousValue = true,
LockTimeout = TimeSpan.FromSeconds(56),
MaxConcurrentAsyncOperations = 24,
QueryEntities = new[]
{
new QueryEntity
{
Fields = new[]
{
new QueryField("field", typeof(int))
{
IsKeyField = true,
NotNull = true,
DefaultValue = "foo"
}
},
Indexes = new[]
{
new QueryIndex("field")
{
IndexType = QueryIndexType.FullText,
InlineSize = 32
}
},
Aliases = new[]
{
new QueryAlias("field.field", "fld")
},
KeyType = typeof(string),
ValueType = typeof(long),
TableName = "table-1",
KeyFieldName = "k",
ValueFieldName = "v"
},
},
ReadFromBackup = false,
RebalanceBatchSize = 33,
RebalanceDelay = TimeSpan.MaxValue,
RebalanceMode = CacheRebalanceMode.Sync,
RebalanceThrottle = TimeSpan.FromHours(44),
RebalanceTimeout = TimeSpan.FromMinutes(8),
SqlEscapeAll = true,
WriteBehindBatchSize = 45,
WriteBehindEnabled = true,
WriteBehindFlushFrequency = TimeSpan.FromSeconds(55),
WriteBehindFlushSize = 66,
WriteBehindFlushThreadCount = 2,
WriteBehindCoalescing = false,
WriteSynchronizationMode = CacheWriteSynchronizationMode.FullAsync,
NearConfiguration = new NearCacheConfiguration
{
NearStartSize = 5,
EvictionPolicy = new FifoEvictionPolicy
{
BatchSize = 19,
MaxMemorySize = 1024,
MaxSize = 555
}
},
PlatformCacheConfiguration = new PlatformCacheConfiguration
{
KeyTypeName = typeof(int).FullName,
ValueTypeName = typeof(string).FullName,
KeepBinary = true
},
EvictionPolicy = new LruEvictionPolicy
{
BatchSize = 18,
MaxMemorySize = 1023,
MaxSize = 554
},
AffinityFunction = new RendezvousAffinityFunction
{
ExcludeNeighbors = true,
Partitions = 48
},
ExpiryPolicyFactory = new MyPolicyFactory(),
EnableStatistics = true,
PluginConfigurations = new[]
{
new MyPluginConfiguration()
},
MemoryPolicyName = "somePolicy",
PartitionLossPolicy = PartitionLossPolicy.ReadOnlyAll,
GroupName = "abc",
SqlIndexMaxInlineSize = 24,
KeyConfiguration = new[]
{
new CacheKeyConfiguration
{
AffinityKeyFieldName = "abc",
TypeName = "def"
},
},
OnheapCacheEnabled = true,
StoreConcurrentLoadAllThreshold = 7,
RebalanceOrder = 3,
RebalanceBatchesPrefetchCount = 4,
MaxQueryIteratorsCount = 512,
QueryDetailMetricsSize = 100,
QueryParallelism = 16,
SqlSchema = "foo"
}
},
ClientMode = true,
DiscoverySpi = new TcpDiscoverySpi
{
NetworkTimeout = TimeSpan.FromSeconds(1),
SocketTimeout = TimeSpan.FromSeconds(2),
AckTimeout = TimeSpan.FromSeconds(3),
JoinTimeout = TimeSpan.FromSeconds(4),
MaxAckTimeout = TimeSpan.FromSeconds(5),
IpFinder = new TcpDiscoveryMulticastIpFinder
{
TimeToLive = 110,
MulticastGroup = "multicastGroup",
AddressRequestAttempts = 10,
MulticastPort = 987,
ResponseTimeout = TimeSpan.FromDays(1),
LocalAddress = "127.0.0.2",
Endpoints = new[] {"", "abc"}
},
ClientReconnectDisabled = true,
ForceServerMode = true,
IpFinderCleanFrequency = TimeSpan.FromMinutes(7),
LocalAddress = "127.0.0.1",
LocalPort = 49900,
LocalPortRange = 13,
ReconnectCount = 11,
StatisticsPrintFrequency = TimeSpan.FromSeconds(20),
ThreadPriority = 6,
TopologyHistorySize = 1234567
},
IgniteHome = "igniteHome",
IncludedEventTypes = EventType.CacheQueryAll,
JvmDllPath = @"c:\jvm",
JvmInitialMemoryMb = 1024,
JvmMaxMemoryMb = 2048,
LifecycleHandlers = new[] {new LifecycleBean(), new LifecycleBean()},
MetricsExpireTime = TimeSpan.FromSeconds(15),
MetricsHistorySize = 45,
MetricsLogFrequency = TimeSpan.FromDays(2),
MetricsUpdateFrequency = TimeSpan.MinValue,
NetworkSendRetryCount = 7,
NetworkSendRetryDelay = TimeSpan.FromSeconds(98),
NetworkTimeout = TimeSpan.FromMinutes(4),
SuppressWarnings = true,
WorkDirectory = @"c:\work",
IsDaemon = true,
UserAttributes = Enumerable.Range(1, 10).ToDictionary(x => x.ToString(),
x => x % 2 == 0 ? (object) x : new FooClass {Bar = x.ToString()}),
AtomicConfiguration = new AtomicConfiguration
{
CacheMode = CacheMode.Replicated,
AtomicSequenceReserveSize = 200,
Backups = 2
},
TransactionConfiguration = new TransactionConfiguration
{
PessimisticTransactionLogSize = 23,
DefaultTransactionIsolation = TransactionIsolation.ReadCommitted,
DefaultTimeout = TimeSpan.FromDays(2),
DefaultTransactionConcurrency = TransactionConcurrency.Optimistic,
PessimisticTransactionLogLinger = TimeSpan.FromHours(3)
},
CommunicationSpi = new TcpCommunicationSpi
{
LocalPort = 47501,
MaxConnectTimeout = TimeSpan.FromSeconds(34),
MessageQueueLimit = 15,
ConnectTimeout = TimeSpan.FromSeconds(17),
IdleConnectionTimeout = TimeSpan.FromSeconds(19),
SelectorsCount = 8,
ReconnectCount = 33,
SocketReceiveBufferSize = 512,
AckSendThreshold = 99,
DirectBuffer = false,
DirectSendBuffer = true,
LocalPortRange = 45,
LocalAddress = "127.0.0.1",
TcpNoDelay = false,
SlowClientQueueLimit = 98,
SocketSendBufferSize = 2045,
UnacknowledgedMessagesBufferSize = 3450
},
SpringConfigUrl = "test",
Logger = new ConsoleLogger(),
FailureDetectionTimeout = TimeSpan.FromMinutes(2),
ClientFailureDetectionTimeout = TimeSpan.FromMinutes(3),
LongQueryWarningTimeout = TimeSpan.FromDays(4),
PluginConfigurations = new[] {new TestIgnitePluginConfiguration()},
EventStorageSpi = new MemoryEventStorageSpi
{
ExpirationTimeout = TimeSpan.FromMilliseconds(12345),
MaxEventCount = 257
},
MemoryConfiguration = new MemoryConfiguration
{
ConcurrencyLevel = 3,
DefaultMemoryPolicyName = "somePolicy",
PageSize = 4,
SystemCacheInitialSize = 5,
SystemCacheMaxSize = 6,
MemoryPolicies = new[]
{
new MemoryPolicyConfiguration
{
Name = "myDefaultPlc",
PageEvictionMode = DataPageEvictionMode.Random2Lru,
InitialSize = 245 * 1024 * 1024,
MaxSize = 345 * 1024 * 1024,
EvictionThreshold = 0.88,
EmptyPagesPoolSize = 77,
SwapFilePath = "myPath1",
RateTimeInterval = TimeSpan.FromSeconds(22),
SubIntervals = 99
},
new MemoryPolicyConfiguration
{
Name = "customPlc",
PageEvictionMode = DataPageEvictionMode.RandomLru,
EvictionThreshold = 0.77,
EmptyPagesPoolSize = 66,
SwapFilePath = "somePath2",
MetricsEnabled = true
}
}
},
PeerAssemblyLoadingMode = PeerAssemblyLoadingMode.CurrentAppDomain,
ClientConnectorConfiguration = new ClientConnectorConfiguration
{
Host = "foo",
Port = 2,
PortRange = 3,
MaxOpenCursorsPerConnection = 4,
SocketReceiveBufferSize = 5,
SocketSendBufferSize = 6,
TcpNoDelay = false,
ThinClientEnabled = false,
OdbcEnabled = false,
JdbcEnabled = false,
ThreadPoolSize = 7,
IdleTimeout = TimeSpan.FromMinutes(5),
ThinClientConfiguration = new ThinClientConfiguration
{
MaxActiveTxPerConnection = 8,
MaxActiveComputeTasksPerConnection = 9
}
},
PersistentStoreConfiguration = new PersistentStoreConfiguration
{
AlwaysWriteFullPages = true,
CheckpointingFrequency = TimeSpan.FromSeconds(25),
CheckpointingPageBufferSize = 28 * 1024 * 1024,
CheckpointingThreads = 2,
LockWaitTime = TimeSpan.FromSeconds(5),
PersistentStorePath = Path.GetTempPath(),
TlbSize = 64 * 1024,
WalArchivePath = Path.GetTempPath(),
WalFlushFrequency = TimeSpan.FromSeconds(3),
WalFsyncDelayNanos = 3,
WalHistorySize = 10,
WalMode = WalMode.Background,
WalRecordIteratorBufferSize = 32 * 1024 * 1024,
WalSegments = 6,
WalSegmentSize = 5 * 1024 * 1024,
WalStorePath = Path.GetTempPath(),
SubIntervals = 25,
MetricsEnabled = true,
RateTimeInterval = TimeSpan.FromDays(1),
CheckpointWriteOrder = CheckpointWriteOrder.Random,
WriteThrottlingEnabled = true
},
IsActiveOnStart = false,
ConsistentId = "myId123",
LocalEventListeners = new[]
{
new LocalEventListener<IEvent>
{
EventTypes = new[] {1, 2},
Listener = new MyEventListener()
}
},
DataStorageConfiguration = new DataStorageConfiguration
{
AlwaysWriteFullPages = true,
CheckpointFrequency = TimeSpan.FromSeconds(25),
CheckpointThreads = 2,
LockWaitTime = TimeSpan.FromSeconds(5),
StoragePath = Path.GetTempPath(),
WalThreadLocalBufferSize = 64 * 1024,
WalArchivePath = Path.GetTempPath(),
WalFlushFrequency = TimeSpan.FromSeconds(3),
WalFsyncDelayNanos = 3,
WalHistorySize = 10,
WalMode = Core.Configuration.WalMode.None,
WalRecordIteratorBufferSize = 32 * 1024 * 1024,
WalSegments = 6,
WalSegmentSize = 5 * 1024 * 1024,
WalPath = Path.GetTempPath(),
MetricsEnabled = true,
MetricsSubIntervalCount = 7,
MetricsRateTimeInterval = TimeSpan.FromSeconds(9),
CheckpointWriteOrder = Core.Configuration.CheckpointWriteOrder.Sequential,
WriteThrottlingEnabled = true,
SystemRegionInitialSize = 64 * 1024 * 1024,
SystemRegionMaxSize = 128 * 1024 * 1024,
ConcurrencyLevel = 1,
PageSize = 5 * 1024,
WalAutoArchiveAfterInactivity = TimeSpan.FromSeconds(19),
WalPageCompression = DiskPageCompression.Lz4,
WalPageCompressionLevel = 10,
DefaultDataRegionConfiguration = new DataRegionConfiguration
{
Name = "reg1",
EmptyPagesPoolSize = 50,
EvictionThreshold = 0.8,
InitialSize = 100 * 1024 * 1024,
MaxSize = 150 * 1024 * 1024,
MetricsEnabled = true,
PageEvictionMode = Core.Configuration.DataPageEvictionMode.RandomLru,
PersistenceEnabled = false,
MetricsRateTimeInterval = TimeSpan.FromMinutes(2),
MetricsSubIntervalCount = 6,
SwapPath = Path.GetTempPath(),
CheckpointPageBufferSize = 7
},
DataRegionConfigurations = new[]
{
new DataRegionConfiguration
{
Name = "reg2",
EmptyPagesPoolSize = 51,
EvictionThreshold = 0.7,
InitialSize = 101 * 1024 * 1024,
MaxSize = 151 * 1024 * 1024,
MetricsEnabled = false,
PageEvictionMode = Core.Configuration.DataPageEvictionMode.RandomLru,
PersistenceEnabled = false,
MetricsRateTimeInterval = TimeSpan.FromMinutes(3),
MetricsSubIntervalCount = 7,
SwapPath = Path.GetTempPath()
}
}
},
SslContextFactory = new SslContextFactory(),
FailureHandler = new StopNodeOrHaltFailureHandler
{
TryStop = false,
Timeout = TimeSpan.FromSeconds(10)
},
SqlQueryHistorySize = 345,
ExecutorConfiguration = new[]
{
new ExecutorConfiguration
{
Name = "exec-1",
Size = 11
}
}
};
}
/// <summary>
/// Runs the with custom culture.
/// </summary>
/// <param name="action">The action.</param>
private static void RunWithCustomCulture(Action action)
{
RunWithCulture(action, CultureInfo.InvariantCulture);
RunWithCulture(action, CultureInfo.GetCultureInfo("ru-RU"));
}
/// <summary>
/// Runs the with culture.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="cultureInfo">The culture information.</param>
private static void RunWithCulture(Action action, CultureInfo cultureInfo)
{
var oldCulture = Thread.CurrentThread.CurrentCulture;
try
{
Thread.CurrentThread.CurrentCulture = cultureInfo;
action();
}
finally
{
Thread.CurrentThread.CurrentCulture = oldCulture;
}
}
/// <summary>
/// Test bean.
/// </summary>
public class LifecycleBean : ILifecycleHandler
{
/// <summary>
/// Gets or sets the foo.
/// </summary>
/// <value>
/// The foo.
/// </value>
public int Foo { get; set; }
/// <summary>
/// This method is called when lifecycle event occurs.
/// </summary>
/// <param name="evt">Lifecycle event.</param>
public void OnLifecycleEvent(LifecycleEventType evt)
{
// No-op.
}
}
/// <summary>
/// Test mapper.
/// </summary>
public class NameMapper : IBinaryNameMapper
{
/// <summary>
/// Gets or sets the bar.
/// </summary>
/// <value>
/// The bar.
/// </value>
public string Bar { get; set; }
/// <summary>
/// Gets the type name.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>
/// Type name.
/// </returns>
public string GetTypeName(string name)
{
return name;
}
/// <summary>
/// Gets the field name.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>
/// Field name.
/// </returns>
public string GetFieldName(string name)
{
return name;
}
}
/// <summary>
/// Serializer.
/// </summary>
public class TestSerializer : IBinarySerializer
{
/** <inheritdoc /> */
public void WriteBinary(object obj, IBinaryWriter writer)
{
// No-op.
}
/** <inheritdoc /> */
public void ReadBinary(object obj, IBinaryReader reader)
{
// No-op.
}
}
/// <summary>
/// Test class.
/// </summary>
public class FooClass
{
public string Bar { get; set; }
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != GetType()) return false;
return string.Equals(Bar, ((FooClass) obj).Bar);
}
public override int GetHashCode()
{
return Bar != null ? Bar.GetHashCode() : 0;
}
public static bool operator ==(FooClass left, FooClass right)
{
return Equals(left, right);
}
public static bool operator !=(FooClass left, FooClass right)
{
return !Equals(left, right);
}
}
/// <summary>
/// Test factory.
/// </summary>
public class TestCacheStoreFactory : IFactory<ICacheStore>
{
/// <summary>
/// Creates an instance of the cache store.
/// </summary>
/// <returns>
/// New instance of the cache store.
/// </returns>
public ICacheStore CreateInstance()
{
return null;
}
}
/// <summary>
/// Test logger.
/// </summary>
public class TestLogger : ILogger
{
/** <inheritdoc /> */
public void Log(LogLevel level, string message, object[] args, IFormatProvider formatProvider, string category,
string nativeErrorInfo, Exception ex)
{
throw new NotImplementedException();
}
/** <inheritdoc /> */
public bool IsEnabled(LogLevel level)
{
throw new NotImplementedException();
}
}
/// <summary>
/// Test factory.
/// </summary>
public class MyPolicyFactory : IFactory<IExpiryPolicy>
{
/** <inheritdoc /> */
public IExpiryPolicy CreateInstance()
{
throw new NotImplementedException();
}
}
public class MyPluginConfiguration : ICachePluginConfiguration
{
int? ICachePluginConfiguration.CachePluginConfigurationClosureFactoryId
{
get { return 0; }
}
void ICachePluginConfiguration.WriteBinary(IBinaryRawWriter writer)
{
throw new NotImplementedException();
}
}
public class MyEventListener : IEventListener<IEvent>
{
public bool Invoke(IEvent evt)
{
throw new NotImplementedException();
}
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.DeviceModels.Chipset.CortexM.Drivers
{
using System;
using System.Runtime.CompilerServices;
using Microsoft.DeviceModels.Chipset.CortexM;
using RT = Microsoft.Zelig.Runtime;
public class SystemTimer
{
public delegate void Callback( Timer timer, ulong currentTime );
public class Timer
{
//
// State
//
private SystemTimer m_owner;
private RT.KernelNode< Timer > m_node;
private ulong m_timeout;
private Callback m_callback;
//
// Constructor Methods
//
internal Timer( SystemTimer owner ,
Callback callback )
{
m_owner = owner;
m_node = new RT.KernelNode< Timer >( this );
m_callback = callback;
}
//
// Helper Methods
//
public void Cancel()
{
m_owner.Deregister( this );
}
internal void Invoke( ulong currentTime )
{
m_callback( this, currentTime );
}
//
// Access Methods
//
internal RT.KernelNode< Timer > Node
{
get
{
return m_node;
}
}
public ulong Timeout
{
get
{
return m_timeout;
}
set
{
m_timeout = value;
m_owner.Register( this );
}
}
public ulong RelativeTimeout
{
get
{
return m_timeout - m_owner.CurrentTime;
}
set
{
m_timeout = value + m_owner.CurrentTime;
m_owner.Register( this );
}
}
}
//
// State
//
const uint c_QuarterCycle = 0x40000000u;
const uint c_OverflowFlag = 0x80000000u;
//readonly OSTimers.OMCR_bitfield c_Timer1Ctrl =
// new OSTimers.OMCR_bitfield
// {
// P = true , // Keep the counter running after a match.
// C = false, // Channel 5 match against Channel 4 counter.
// CRES = OSTimers.OMCR_bitfield.Resolution.Freq1MHz,
// };
//readonly OSTimers.OMCR_bitfield c_Timer2Ctrl =
// new OSTimers.OMCR_bitfield
// {
// P = true, // Keep the counter running after a match.
// C = true, // Channel 4 matches against its counter.
// CRES = OSTimers.OMCR_bitfield.Resolution.Freq1MHz,
// };
private uint m_lastCount;
private uint m_highPart;
private InterruptController.Handler m_interrupt;
private InterruptController.Handler m_simulatedSoftInterrupt;
private RT.KernelList< Timer > m_timers;
//
// Helper Methods
//
public void Initialize()
{
m_timers = new RT.KernelList< Timer >();
m_interrupt = InterruptController.Handler.Create( 0, InterruptPriority.Normal, InterruptSettings.ActiveHigh, ProcessTimeout );
m_simulatedSoftInterrupt = InterruptController.Handler.Create( 1, InterruptPriority.Lowest, InterruptSettings.ActiveHigh, ProcessSoftInterrupt );
//--//
//var clockControl = PXA27x.ClockManager.Instance;
//clockControl.CKEN.EnOsTimer = true;
//--//
//var timer = PXA27x.OSTimers.Instance;
//timer.OIER = 0;
////--//
////
//// We use Timer0 as a soft interrupt, so we have to wait until it has fired and NEVER reset the match value.
////
//timer.EnableInterrupt( 0 );
//timer.WriteCounter( 0, 0 );
//timer.SetMatch ( 0, 100 );
//while(timer.HasFired( 0 ) == false)
//{
//}
////--//
//timer.SetControl( 5, c_Timer1Ctrl );
//timer.SetControl( 4, c_Timer2Ctrl );
////
//// Start the timer.
////
//timer.WriteCounter( 4, 0 );
//timer.EnableInterrupt( 4 );
//timer.EnableInterrupt( 5 );
//--//
var intc = InterruptController.Instance;
intc.RegisterAndEnable( m_interrupt );
intc.Register ( m_simulatedSoftInterrupt );
Refresh();
}
public Timer CreateTimer( Callback callback )
{
return new Timer( this, callback );
}
//--//
private void Register( Timer timer )
{
RT.KernelNode< Timer > node = timer.Node;
node.RemoveFromList();
ulong timeout = timer.Timeout;
RT.KernelNode< Timer > node2 = m_timers.StartOfForwardWalk;
while(node2.IsValidForForwardMove)
{
if(node2.Target.Timeout > timeout)
{
break;
}
node2 = node2.Next;
}
node.InsertBefore( node2 );
Refresh();
}
private void Deregister( Timer timer )
{
var node = timer.Node;
if(node.IsLinked)
{
node.RemoveFromList();
Refresh();
}
}
//--//
private void ProcessTimeout( InterruptController.Handler handler )
{
ulong currentTime = this.CurrentTime;
while(true)
{
RT.KernelNode< Timer > node = m_timers.StartOfForwardWalk;
if(node.IsValidForForwardMove == false)
{
break;
}
if(node.Target.Timeout > currentTime)
{
break;
}
node.RemoveFromList();
node.Target.Invoke( currentTime );
}
Refresh();
}
internal void CauseInterrupt()
{
//var timer = PXA27x.OSTimers.Instance;
//timer.SetMatch(0, timer.ReadCounter(0) + 8);
m_simulatedSoftInterrupt.Enable();
}
private void ProcessSoftInterrupt( InterruptController.Handler handler )
{
//m_simulatedSoftInterrupt.Disable();
InterruptController.Instance.ProcessSoftInterrupt();
}
void Refresh()
{
Timer target = m_timers.FirstTarget();
ulong timeout;
if(target != null)
{
timeout = target.Timeout;
}
else
{
timeout = ulong.MaxValue;
}
//--//
ulong now = this.CurrentTime;
//
// Timeout in the past? Trigger the match now.
//
if(now > timeout)
{
timeout = now;
}
//
// Timeout too far in the future? Generate match closer in time, so we handle wrap arounds.
//
ulong nowPlusQuarterCycle = now + c_QuarterCycle;
if(nowPlusQuarterCycle < timeout)
{
timeout = nowPlusQuarterCycle;
}
uint timeoutLow = (uint)timeout;
var timer = SysTick.Instance;
// disable second interrupt so we don't handle this timeout twice
timer.DisableInterrupt( 5 );
//
// Clear previous interrupts.
//
timer.ClearFired( 4 );
timer.ClearFired( 5 );
//
// Create two matches, to protect against race conditions (at least one will fire).
//
timer.SetMatch( 4, timeoutLow );
timer.SetMatch( 5, timeoutLow + 10 );
timer.EnableInterrupt( 5 );
}
//
// Access Methods
//
public static extern SystemTimer Instance
{
[RT.SingletonFactory()]
[MethodImpl( MethodImplOptions.InternalCall )]
get;
}
public uint CurrentTimeRaw
{
get
{
return SysTick.Instance.ReadCounter( 4 );
}
}
public ulong CurrentTime
{
get
{
using(RT.SmartHandles.InterruptState.Disable())
{
uint value = Chipset.CortexM.SysTick.Instance.ReadCounter( 4 );
uint highPart = m_highPart;
//
// Wrap around? Update high part.
//
if(((value ^ m_lastCount) & c_OverflowFlag) != 0)
{
highPart++;
m_lastCount = value;
m_highPart = highPart;
}
return (ulong)highPart << 32 | value;
}
}
}
}
}
| |
#region MIT License
/*
* Copyright (c) 2005-2007 Jonathan Mark Porter. http://physics2d.googlepages.com/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#endregion
#if UseDouble
using Scalar = System.Double;
#else
using Scalar = System.Single;
#endif
using System;
using System.Runtime.InteropServices;
using System.Xml.Serialization;
using AdvanceMath;
using AdvanceMath.Design;
namespace Physics2DDotNet.Math2D
{
/// <summary>
/// Class Used to store a Linear Value along with an Angular Value. Like Position and Orientation.
/// </summary>
[StructLayout(LayoutKind.Sequential, Size = ALVector2D.Size, Pack = 0), Serializable]
[System.ComponentModel.TypeConverter(typeof(AdvTypeConverter<ALVector2D>))]
[AdvBrowsableOrder("Angular,Linear")]
public struct ALVector2D : IEquatable<ALVector2D>
{
public static ALVector2D Parse(string text)
{
string[] vals = text.Trim(' ', '(', '[', '<', ')', ']', '>').Split(new char[] { ',' }, 2);
if (vals.Length != 2)
{
throw new FormatException(string.Format("Cannot parse the text '{0}' because it does not have 2 parts separated by commas in the form (x,y) with optional parenthesis.", text));
}
else
{
try
{
ALVector2D returnvalue;
returnvalue.Angular = Scalar.Parse(vals[0]);
returnvalue.Linear = Vector2D.Parse(vals[1]);
return returnvalue;
}
catch (Exception ex)
{
throw new FormatException("The parts of the vectors must be decimal numbers", ex);
}
}
}
public const int Size = sizeof(Scalar) + Vector2D.Size;
/// <summary>
/// ALVector2D(0,Vector2D.Zero)
/// </summary>
public static readonly ALVector2D Zero = new ALVector2D(0, Vector2D.Zero);
/// <summary>
/// This is the Angular value of this ALVector2D.
/// </summary>
/// <remarks>Example: Angular would be Orientation and Linear would be Location Completly describing a Position.</remarks>
[AdvBrowsable]
public Scalar Angular;
/// <summary>
/// This is the Linear value of this ALVector2D.
/// </summary>
/// <remarks>Example: Angular would be Orientation and Linear would be Location Completly describing a Position.</remarks>
[AdvBrowsable]
public Vector2D Linear;
/// <summary>
/// Creates a new ALVector2D instance on the stack.
/// </summary>
/// <param name="Angular">The Angular value.</param>
/// <param name="Linear">The Linear value.</param>
[InstanceConstructor("Angular,Linear")]
public ALVector2D(Scalar angular, Vector2D linear)
{
this.Angular = angular;
this.Linear = linear;
}
public ALVector2D(Scalar angular, Scalar x, Scalar y)
{
this.Angular = angular;
this.Linear = new Vector2D(x, y);
}
public static ALVector2D Add(ALVector2D left, ALVector2D right)
{
ALVector2D result;
result.Angular = left.Angular + right.Angular;
result.Linear.X = left.Linear.X + right.Linear.X;
result.Linear.Y = left.Linear.Y + right.Linear.Y;
return result;
}
public static void Add(ref ALVector2D left, ref ALVector2D right, out ALVector2D result)
{
result.Angular = left.Angular + right.Angular;
result.Linear.X = left.Linear.X + right.Linear.X;
result.Linear.Y = left.Linear.Y + right.Linear.Y;
}
/// <summary>
/// Does Addition of 2 ALVector2Ds.
/// </summary>
/// <param name="left">The left ALVector2D operand.</param>
/// <param name="right">The right ALVector2D operand.</param>
/// <returns>The Sum of the ALVector2Ds.</returns>
public static ALVector2D operator +(ALVector2D left, ALVector2D right)
{
ALVector2D result;
result.Angular = left.Angular + right.Angular;
result.Linear.X = left.Linear.X + right.Linear.X;
result.Linear.Y = left.Linear.Y + right.Linear.Y;
return result;
}
/// <summary>
/// Does Subtraction of 2 ALVector2Ds.
/// </summary>
/// <param name="left">The left ALVector2D operand.</param>
/// <param name="right">The right ALVector2D operand.</param>
/// <returns>The Difference of the ALVector2Ds.</returns>
public static ALVector2D operator -(ALVector2D left, ALVector2D right)
{
ALVector2D result;
result.Angular = left.Angular - right.Angular;
result.Linear.X = left.Linear.X - right.Linear.X;
result.Linear.Y = left.Linear.Y - right.Linear.Y;
return result;
}
public static ALVector2D Subtract(ALVector2D left, ALVector2D right)
{
ALVector2D result;
result.Angular = left.Angular - right.Angular;
result.Linear.X = left.Linear.X - right.Linear.X;
result.Linear.Y = left.Linear.Y - right.Linear.Y;
return result;
}
public static void Subtract(ref ALVector2D left,ref ALVector2D right, out ALVector2D result)
{
result.Angular = left.Angular - right.Angular;
result.Linear.X = left.Linear.X - right.Linear.X;
result.Linear.Y = left.Linear.Y - right.Linear.Y;
}
/// <summary>
/// Does Multiplication of 2 ALVector2Ds
/// </summary>
/// <param name="source">The ALVector2D to be Multiplied.</param>
/// <param name="scalar">The Scalar multiplier.</param>
/// <returns>The Product of the ALVector2Ds.</returns>
/// <remarks>It does normal Multiplication of the Angular value but does Scalar Multiplication of the Linear value.</remarks>
public static ALVector2D operator *(ALVector2D source, Scalar scalar)
{
ALVector2D result;
result.Angular = source.Angular * scalar;
result.Linear.X = source.Linear.X * scalar;
result.Linear.Y = source.Linear.Y * scalar;
return result;
}
public static ALVector2D Multiply(ALVector2D source, Scalar scalar)
{
ALVector2D result;
result.Angular = source.Angular * scalar;
result.Linear.X = source.Linear.X * scalar;
result.Linear.Y = source.Linear.Y * scalar;
return result;
}
public static void Multiply(ref ALVector2D source,ref Scalar scalar,out ALVector2D result)
{
result.Angular = source.Angular * scalar;
result.Linear.X = source.Linear.X * scalar;
result.Linear.Y = source.Linear.Y * scalar;
}
/// <summary>
/// Does Multiplication of 2 ALVector2Ds
/// </summary>
/// <param name="scalar">The Scalar multiplier.</param>
/// <param name="source">The ALVector2D to be Multiplied.</param>
/// <returns>The Product of the ALVector2Ds.</returns>
/// <remarks>It does normal Multiplication of the Angular value but does Scalar Multiplication of the Linear value.</remarks>
public static ALVector2D operator *(Scalar scalar, ALVector2D source)
{
ALVector2D result;
result.Angular = source.Angular * scalar;
result.Linear.X = source.Linear.X * scalar;
result.Linear.Y = source.Linear.Y * scalar;
return result;
}
public static ALVector2D Multiply(Scalar scalar, ALVector2D source)
{
ALVector2D result;
result.Angular = source.Angular * scalar;
result.Linear.X = source.Linear.X * scalar;
result.Linear.Y = source.Linear.Y * scalar;
return result;
}
public static void Multiply(ref Scalar scalar,ref ALVector2D source, out ALVector2D result)
{
result.Angular = source.Angular * scalar;
result.Linear.X = source.Linear.X * scalar;
result.Linear.Y = source.Linear.Y * scalar;
}
public static bool operator ==(ALVector2D left, ALVector2D right)
{
return left.Angular == right.Angular &&
Vector2D.Equals(ref left.Linear, ref right.Linear);
}
public static bool operator !=(ALVector2D left, ALVector2D right)
{
return !(left.Angular == right.Angular &&
Vector2D.Equals(ref left.Linear, ref right.Linear));
}
public static bool Equals(ALVector2D left, ALVector2D right)
{
return left.Angular == right.Angular &&
Vector2D.Equals(ref left.Linear, ref right.Linear);
}
[CLSCompliant(false)]
public static bool Equals(ref ALVector2D left,ref ALVector2D right)
{
return left.Angular == right.Angular &&
Vector2D.Equals(ref left.Linear, ref right.Linear);
}
public override bool Equals(object obj)
{
return
obj is ALVector2D &&
Equals((ALVector2D)obj);
}
public bool Equals(ALVector2D other)
{
return Equals(ref this, ref other);
}
public override int GetHashCode()
{
return Angular.GetHashCode() ^ Linear.GetHashCode();
}
public override string ToString()
{
return string.Format("({0}, {1})", Angular, Linear);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Reflection;
using System.Threading.Tasks;
using Xunit;
namespace Microsoft.AspNetCore.Testing
{
// TODO: eventually want: public partial class Assert : Xunit.Assert
public static class ExceptionAssert
{
/// <summary>
/// Verifies that an exception of the given type (or optionally a derived type) is thrown.
/// </summary>
/// <typeparam name="TException">The type of the exception expected to be thrown</typeparam>
/// <param name="testCode">A delegate to the code to be tested</param>
/// <returns>The exception that was thrown, when successful</returns>
public static TException Throws<TException>(Action testCode)
where TException : Exception
{
return VerifyException<TException>(RecordException(testCode));
}
/// <summary>
/// Verifies that an exception of the given type is thrown.
/// Also verifies that the exception message matches.
/// </summary>
/// <typeparam name="TException">The type of the exception expected to be thrown</typeparam>
/// <param name="testCode">A delegate to the code to be tested</param>
/// <param name="exceptionMessage">The exception message to verify</param>
/// <returns>The exception that was thrown, when successful</returns>
public static TException Throws<TException>(Action testCode, string exceptionMessage)
where TException : Exception
{
var ex = Throws<TException>(testCode);
VerifyExceptionMessage(ex, exceptionMessage);
return ex;
}
/// <summary>
/// Verifies that an exception of the given type is thrown.
/// Also verifies that the exception message matches.
/// </summary>
/// <typeparam name="TException">The type of the exception expected to be thrown</typeparam>
/// <param name="testCode">A delegate to the code to be tested</param>
/// <param name="exceptionMessage">The exception message to verify</param>
/// <returns>The exception that was thrown, when successful</returns>
public static async Task<TException> ThrowsAsync<TException>(Func<Task> testCode, string exceptionMessage)
where TException : Exception
{
// The 'testCode' Task might execute asynchronously in a different thread making it hard to enforce the thread culture.
// The correct way to verify exception messages in such a scenario would be to run the task synchronously inside of a
// culture enforced block.
var ex = await Assert.ThrowsAsync<TException>(testCode);
VerifyExceptionMessage(ex, exceptionMessage);
return ex;
}
/// <summary>
/// Verifies that an exception of the given type is thrown.
/// Also verified that the exception message matches.
/// </summary>
/// <typeparam name="TException">The type of the exception expected to be thrown</typeparam>
/// <param name="testCode">A delegate to the code to be tested</param>
/// <param name="exceptionMessage">The exception message to verify</param>
/// <returns>The exception that was thrown, when successful</returns>
public static TException Throws<TException>(Func<object> testCode, string exceptionMessage)
where TException : Exception
{
return Throws<TException>(() => { testCode(); }, exceptionMessage);
}
/// <summary>
/// Verifies that the code throws an <see cref="ArgumentException"/>.
/// </summary>
/// <param name="testCode">A delegate to the code to be tested</param>
/// <param name="paramName">The name of the parameter that should throw the exception</param>
/// <param name="exceptionMessage">The exception message to verify</param>
/// <returns>The exception that was thrown, when successful</returns>
public static ArgumentException ThrowsArgument(Action testCode, string paramName, string exceptionMessage)
{
return ThrowsArgumentInternal<ArgumentException>(testCode, paramName, exceptionMessage);
}
private static TException ThrowsArgumentInternal<TException>(
Action testCode,
string paramName,
string exceptionMessage)
where TException : ArgumentException
{
var ex = Throws<TException>(testCode);
if (paramName != null)
{
Assert.Equal(paramName, ex.ParamName);
}
VerifyExceptionMessage(ex, exceptionMessage, partialMatch: true);
return ex;
}
/// <summary>
/// Verifies that the code throws an <see cref="ArgumentException"/>.
/// </summary>
/// <param name="testCode">A delegate to the code to be tested</param>
/// <param name="paramName">The name of the parameter that should throw the exception</param>
/// <param name="exceptionMessage">The exception message to verify</param>
/// <returns>The exception that was thrown, when successful</returns>
public static Task<ArgumentException> ThrowsArgumentAsync(Func<Task> testCode, string paramName, string exceptionMessage)
{
return ThrowsArgumentAsyncInternal<ArgumentException>(testCode, paramName, exceptionMessage);
}
private static async Task<TException> ThrowsArgumentAsyncInternal<TException>(
Func<Task> testCode,
string paramName,
string exceptionMessage)
where TException : ArgumentException
{
var ex = await Assert.ThrowsAsync<TException>(testCode);
if (paramName != null)
{
Assert.Equal(paramName, ex.ParamName);
}
VerifyExceptionMessage(ex, exceptionMessage, partialMatch: true);
return ex;
}
/// <summary>
/// Verifies that the code throws an <see cref="ArgumentNullException"/>.
/// </summary>
/// <param name="testCode">A delegate to the code to be tested</param>
/// <param name="paramName">The name of the parameter that should throw the exception</param>
/// <returns>The exception that was thrown, when successful</returns>
public static ArgumentNullException ThrowsArgumentNull(Action testCode, string paramName)
{
var ex = Throws<ArgumentNullException>(testCode);
if (paramName != null)
{
Assert.Equal(paramName, ex.ParamName);
}
return ex;
}
/// <summary>
/// Verifies that the code throws an ArgumentException with the expected message that indicates that the value cannot
/// be null or empty.
/// </summary>
/// <param name="testCode">A delegate to the code to be tested</param>
/// <param name="paramName">The name of the parameter that should throw the exception</param>
/// <returns>The exception that was thrown, when successful</returns>
public static ArgumentException ThrowsArgumentNullOrEmpty(Action testCode, string paramName)
{
return ThrowsArgumentInternal<ArgumentException>(testCode, paramName, "Value cannot be null or empty.");
}
/// <summary>
/// Verifies that the code throws an ArgumentException with the expected message that indicates that the value cannot
/// be null or empty.
/// </summary>
/// <param name="testCode">A delegate to the code to be tested</param>
/// <param name="paramName">The name of the parameter that should throw the exception</param>
/// <returns>The exception that was thrown, when successful</returns>
public static Task<ArgumentException> ThrowsArgumentNullOrEmptyAsync(Func<Task> testCode, string paramName)
{
return ThrowsArgumentAsyncInternal<ArgumentException>(testCode, paramName, "Value cannot be null or empty.");
}
/// <summary>
/// Verifies that the code throws an ArgumentNullException with the expected message that indicates that the value cannot
/// be null or empty string.
/// </summary>
/// <param name="testCode">A delegate to the code to be tested</param>
/// <param name="paramName">The name of the parameter that should throw the exception</param>
/// <returns>The exception that was thrown, when successful</returns>
public static ArgumentException ThrowsArgumentNullOrEmptyString(Action testCode, string paramName)
{
return ThrowsArgumentInternal<ArgumentException>(testCode, paramName, "Value cannot be null or an empty string.");
}
/// <summary>
/// Verifies that the code throws an ArgumentNullException with the expected message that indicates that the value cannot
/// be null or empty string.
/// </summary>
/// <param name="testCode">A delegate to the code to be tested</param>
/// <param name="paramName">The name of the parameter that should throw the exception</param>
/// <returns>The exception that was thrown, when successful</returns>
public static Task<ArgumentException> ThrowsArgumentNullOrEmptyStringAsync(Func<Task> testCode, string paramName)
{
return ThrowsArgumentAsyncInternal<ArgumentException>(testCode, paramName, "Value cannot be null or an empty string.");
}
/// <summary>
/// Verifies that the code throws an ArgumentOutOfRangeException (or optionally any exception which derives from it).
/// </summary>
/// <param name="testCode">A delegate to the code to be tested</param>
/// <param name="paramName">The name of the parameter that should throw the exception</param>
/// <param name="exceptionMessage">The exception message to verify</param>
/// <param name="actualValue">The actual value provided</param>
/// <returns>The exception that was thrown, when successful</returns>
public static ArgumentOutOfRangeException ThrowsArgumentOutOfRange(Action testCode, string paramName, string exceptionMessage, object actualValue = null)
{
var ex = ThrowsArgumentInternal<ArgumentOutOfRangeException>(testCode, paramName, exceptionMessage);
if (paramName != null)
{
Assert.Equal(paramName, ex.ParamName);
}
if (actualValue != null)
{
Assert.Equal(actualValue, ex.ActualValue);
}
return ex;
}
// We've re-implemented all the xUnit.net Throws code so that we can get this
// updated implementation of RecordException which silently unwraps any instances
// of AggregateException. In addition to unwrapping exceptions, this method ensures
// that tests are executed in with a known set of Culture and UICulture. This prevents
// tests from failing when executed on a non-English machine.
private static Exception RecordException(Action testCode)
{
try
{
using (new CultureReplacer())
{
testCode();
}
return null;
}
catch (Exception exception)
{
return UnwrapException(exception);
}
}
private static Exception UnwrapException(Exception exception)
{
var aggEx = exception as AggregateException;
return aggEx != null ? aggEx.GetBaseException() : exception;
}
private static TException VerifyException<TException>(Exception exception)
{
var tie = exception as TargetInvocationException;
if (tie != null)
{
exception = tie.InnerException;
}
Assert.NotNull(exception);
return Assert.IsAssignableFrom<TException>(exception);
}
private static void VerifyExceptionMessage(Exception exception, string expectedMessage, bool partialMatch = false)
{
if (expectedMessage != null)
{
if (!partialMatch)
{
Assert.Equal(expectedMessage, exception.Message);
}
else
{
Assert.Contains(expectedMessage, exception.Message);
}
}
}
}
}
| |
using UnityEngine;
using System.Collections.Generic;
[System.Serializable]
public class Warp
{
public string name = "None";
public Vector3[] points = new Vector3[16];
public void GetWarp(MegaBezPatch mod)
{
mod.p11 = points[0];
mod.p12 = points[1];
mod.p13 = points[2];
mod.p14 = points[3];
mod.p21 = points[4];
mod.p22 = points[5];
mod.p23 = points[6];
mod.p24 = points[7];
mod.p31 = points[8];
mod.p32 = points[9];
mod.p33 = points[10];
mod.p34 = points[11];
mod.p41 = points[12];
mod.p42 = points[13];
mod.p43 = points[14];
mod.p44 = points[15];
}
public void SetWarp(MegaBezPatch mod)
{
points[0] = mod.p11;
points[1] = mod.p12;
points[2] = mod.p13;
points[3] = mod.p14;
points[4] = mod.p21;
points[5] = mod.p22;
points[6] = mod.p23;
points[7] = mod.p24;
points[8] = mod.p31;
points[9] = mod.p32;
points[10] = mod.p33;
points[11] = mod.p34;
points[12] = mod.p41;
points[13] = mod.p42;
points[14] = mod.p43;
points[15] = mod.p44;
}
public void AdjustLattice(float wr, float hr)
{
Vector3 r = new Vector3(wr, hr, 1.0f);
points[0] = Vector3.Scale(points[0], r);
points[1] = Vector3.Scale(points[1], r);
points[2] = Vector3.Scale(points[2], r);
points[3] = Vector3.Scale(points[3], r);
points[4] = Vector3.Scale(points[4], r);
points[5] = Vector3.Scale(points[5], r);
points[6] = Vector3.Scale(points[6], r);
points[7] = Vector3.Scale(points[7], r);
points[8] = Vector3.Scale(points[8], r);
points[9] = Vector3.Scale(points[9], r);
points[10] = Vector3.Scale(points[10], r);
points[11] = Vector3.Scale(points[11], r);
points[12] = Vector3.Scale(points[12], r);
points[13] = Vector3.Scale(points[13], r);
points[14] = Vector3.Scale(points[14], r);
points[15] = Vector3.Scale(points[15], r);
}
}
[ExecuteInEditMode]
public class MegaBezPatch : MonoBehaviour
{
public float Width = 1.0f;
public float Height = 1.0f;
public int WidthSegs = 20;
public int HeightSegs = 20;
public bool GenUVs = true;
public bool recalcBounds = false;
public bool recalcTangents = true;
public bool recalcCollider = false;
public bool showgizmos = true;
public bool showlatticepoints = false;
public Color latticecol = Color.white;
public float handlesize = 0.075f;
public bool positionhandles = false;
public bool showlabels = true;
public Vector2 snap = new Vector2(0.25f, 0.25f);
public List<Warp> warps = new List<Warp>();
public int srcwarp;
public int destwarp;
[HideInInspector]
public Vector3[] verts;
[HideInInspector]
public Vector2[] uvs;
[HideInInspector]
public int[] tris;
[HideInInspector]
public Vector3[] norms;
[HideInInspector]
public bool rebuild = true;
public Vector2 UVOffset = Vector2.zero;
public Vector2 UVScale = Vector2.one;
public int currentwarp = 0;
[HideInInspector]
public Mesh mesh;
public float switchtime = 1.0f;
public float time = 1000.0f;
public Vector3 p11;
public Vector3 p21;
public Vector3 p31;
public Vector3 p41;
public Vector3 p12;
public Vector3 p22;
public Vector3 p32;
public Vector3 p42;
public Vector3 p13;
public Vector3 p23;
public Vector3 p33;
public Vector3 p43;
public Vector3 p14;
public Vector3 p24;
public Vector3 p34;
public Vector3 p44;
public bool animateWarps = true;
//public bool useWarpValue = false;
//public float warpValue = 0.0f;
public void AddWarp()
{
Warp warp = new Warp();
warp.SetWarp(this);
warps.Add(warp);
}
public void UpdateWarp(int i)
{
Warp warp = warps[i];
warp.SetWarp(this);
}
public void SetDestWarp(int i)
{
destwarp = i;
}
public void SetWarp(int i)
{
if ( Application.isPlaying )
{
time = 0.0f;
srcwarp = currentwarp;
destwarp = i;
}
else
{
time = 100.0f;
currentwarp = i;
warps[i].GetWarp(this);
}
}
void Start()
{
time = 0.0f;
}
public void Reset()
{
InitLattice();
Rebuild();
}
public void Rebuild()
{
MeshFilter mf = GetComponent<MeshFilter>();
if ( mf != null )
{
Mesh mesh1 = mf.sharedMesh;
if ( mesh1 == null )
{
mesh1 = new Mesh();
mf.sharedMesh = mesh1;
}
mesh = mesh1;
}
}
void Update()
{
if ( animateWarps )
ChangeWarp(srcwarp, destwarp);
else
{
CheckForChange();
}
if ( mesh == null )
Rebuild();
if ( rebuild )
BuildMesh(mesh);
}
void MakeQuad1(int f, int a, int b, int c, int d)
{
tris[f++] = a;
tris[f++] = b;
tris[f++] = c;
tris[f++] = c;
tris[f++] = d;
tris[f++] = a;
}
// Put in utils
int MaxComponent(Vector3 v)
{
if ( Mathf.Abs(v.x) > Mathf.Abs(v.y) )
{
if ( Mathf.Abs(v.x) > Mathf.Abs(v.z) )
return 0;
else
return 2;
}
else
{
if ( Mathf.Abs(v.y) > Mathf.Abs(v.z) )
return 1;
else
return 2;
}
}
void UpdateSurface()
{
}
// Only call this on size or seg change
void BuildMesh(Mesh mesh)
{
if ( WidthSegs < 1 )
WidthSegs = 1;
if ( HeightSegs < 1 )
HeightSegs = 1;
Vector3 p = Vector3.zero;
int numverts = (WidthSegs + 1) * (HeightSegs + 1);
if ( verts == null )
{
InitLattice();
}
if ( verts == null || verts.Length != numverts )
{
verts = new Vector3[numverts];
uvs = new Vector2[numverts];
tris = new int[HeightSegs * WidthSegs * 2 * 3];
norms = new Vector3[numverts];
for ( int i = 0; i < norms.Length; i++ )
norms[i] = Vector3.back;
}
Vector2 uv = Vector2.zero;
int index = 0;
p = Vector3.zero;
for ( int i = 0; i <= HeightSegs; i++ )
{
index = i * (WidthSegs + 1);
for ( int j = 0; j <= WidthSegs; j++ )
{
float xIndex = (float)j / (float)WidthSegs;
float yIndex = (float)i / (float)HeightSegs;
float omx = 1.0f - xIndex;
float omy = 1.0f - yIndex;
float x1 = omx * omx * omx;
float x2 = (3.0f * omx) * omx * xIndex;
float x3 = (3.0f * omx) * xIndex * xIndex;
float x4 = xIndex * xIndex * xIndex;
float y1 = omy * omy * omy;
float y2 = (3.0f * omy) * omy * yIndex;
float y3 = (3.0f * omy) * yIndex * yIndex;
float y4 = yIndex * yIndex * yIndex;
p.x = (x1 * p11.x * y1) + (x2 * p12.x * y1) + (x3 * p13.x * y1) + (x4 * p14.x * y1)
+ (x1 * p21.x * y2) + (x2 * p22.x * y2) + (x3 * p23.x * y2) + (x4 * p24.x * y2)
+ (x1 * p31.x * y3) + (x2 * p32.x * y3) + (x3 * p33.x * y3) + (x4 * p34.x * y3)
+ (x1 * p41.x * y4) + (x2 * p42.x * y4) + (x3 * p43.x * y4) + (x4 * p44.x * y4);
p.y = (x1 * p11.y * y1) + (x2 * p12.y * y1) + (x3 * p13.y * y1) + (x4 * p14.y * y1)
+ (x1 * p21.y * y2) + (x2 * p22.y * y2) + (x3 * p23.y * y2) + (x4 * p24.y * y2)
+ (x1 * p31.y * y3) + (x2 * p32.y * y3) + (x3 * p33.y * y3) + (x4 * p34.y * y3)
+ (x1 * p41.y * y4) + (x2 * p42.y * y4) + (x3 * p43.y * y4) + (x4 * p44.y * y4);
verts[index + j] = p;
if ( GenUVs )
{
uv.x = (xIndex + UVOffset.x) * UVScale.x;
uv.y = (yIndex + UVOffset.y) * UVScale.y;
uvs[index + j] = uv;
}
}
}
int f = 0;
for ( int iz = 0; iz < HeightSegs; iz++ )
{
int kv = iz * (WidthSegs + 1);
for ( int ix = 0; ix < WidthSegs; ix++ )
{
tris[f++] = kv;
tris[f++] = kv + WidthSegs + 1;
tris[f++] = kv + WidthSegs + 2;
tris[f++] = kv + WidthSegs + 2;
tris[f++] = kv + 1;
tris[f++] = kv;
kv++;
}
}
mesh.Clear();
mesh.subMeshCount = 1;
mesh.vertices = verts;
mesh.uv = uvs;
mesh.SetTriangles(tris, 0);
mesh.normals = norms;
mesh.RecalculateBounds();
if ( recalcTangents )
BuildTangents(mesh, verts, norms, tris, uvs);
}
public void InitLattice()
{
float w = Width;
float h = Height;
p11 = new Vector3(-1.5f * w, -1.5f * h, 0.0f);
p12 = new Vector3(-0.5f * w, -1.5f * h, 0.0f);
p13 = new Vector3(0.5f * w, -1.5f * h, 0.0f);
p14 = new Vector3(1.5f * w, -1.5f * h, 0.0f);
p21 = new Vector3(-1.5f * w, -0.5f * h, 0.0f);
p22 = new Vector3(-0.5f * w, -0.5f * h, 0.0f);
p23 = new Vector3(0.5f * w, -0.5f * h, 0.0f);
p24 = new Vector3(1.5f * w, -0.5f * h, 0.0f);
p31 = new Vector3(-1.5f * w, 0.5f * h, 0.0f);
p32 = new Vector3(-0.5f * w, 0.5f * h, 0.0f);
p33 = new Vector3(0.5f * w, 0.5f * h, 0.0f);
p34 = new Vector3(1.5f * w, 0.5f * h, 0.0f);
p41 = new Vector3(-1.5f * w, 1.5f * h, 0.0f);
p42 = new Vector3(-0.5f * w, 1.5f * h, 0.0f);
p43 = new Vector3(0.5f * w, 1.5f * h, 0.0f);
p44 = new Vector3(1.5f * w, 1.5f * h, 0.0f);
}
public Vector3[] lpoints;
public void AdjustLattice(float w, float h)
{
float wr = w / Width;
float hr = h / Height;
Vector3 r = new Vector3(wr, hr, 1.0f);
p11 = Vector3.Scale(p11, r);
p12 = Vector3.Scale(p12, r);
p13 = Vector3.Scale(p13, r);
p14 = Vector3.Scale(p14, r);
p21 = Vector3.Scale(p21, r);
p22 = Vector3.Scale(p22, r);
p23 = Vector3.Scale(p23, r);
p24 = Vector3.Scale(p24, r);
p31 = Vector3.Scale(p31, r);
p32 = Vector3.Scale(p32, r);
p33 = Vector3.Scale(p33, r);
p34 = Vector3.Scale(p34, r);
p41 = Vector3.Scale(p41, r);
p42 = Vector3.Scale(p42, r);
p43 = Vector3.Scale(p43, r);
p44 = Vector3.Scale(p44, r);
for ( int i = 0; i < warps.Count; i++ )
{
warps[i].AdjustLattice(wr, hr);
}
Height = h;
Width = w;
}
static public void BuildTangents(Mesh mesh, Vector3[] verts, Vector3[] norms, int[] tris, Vector2[] uvs)
{
int vertexCount = mesh.vertices.Length;
Vector3[] tan1 = new Vector3[vertexCount];
Vector3[] tan2 = new Vector3[vertexCount];
Vector4[] tangents = new Vector4[vertexCount];
for ( int a = 0; a < tris.Length; a += 3 )
{
long i1 = tris[a];
long i2 = tris[a + 1];
long i3 = tris[a + 2];
Vector3 v1 = verts[i1];
Vector3 v2 = verts[i2];
Vector3 v3 = verts[i3];
Vector2 w1 = uvs[i1];
Vector2 w2 = uvs[i2];
Vector2 w3 = uvs[i3];
float x1 = v2.x - v1.x;
float x2 = v3.x - v1.x;
float y1 = v2.y - v1.y;
float y2 = v3.y - v1.y;
float z1 = v2.z - v1.z;
float z2 = v3.z - v1.z;
float s1 = w2.x - w1.x;
float s2 = w3.x - w1.x;
float t1 = w2.y - w1.y;
float t2 = w3.y - w1.y;
float r = 1.0f / (s1 * t2 - s2 * t1);
Vector3 sdir = new Vector3((t2 * x1 - t1 * x2) * r, (t2 * y1 - t1 * y2) * r, (t2 * z1 - t1 * z2) * r);
Vector3 tdir = new Vector3((s1 * x2 - s2 * x1) * r, (s1 * y2 - s2 * y1) * r, (s1 * z2 - s2 * z1) * r);
tan1[i1] += sdir;
tan1[i2] += sdir;
tan1[i3] += sdir;
tan2[i1] += tdir;
tan2[i2] += tdir;
tan2[i3] += tdir;
}
for ( int a = 0; a < vertexCount; a++ )
{
Vector3 n = norms[a];
Vector3 t = tan1[a];
Vector3.OrthoNormalize(ref n, ref t);
tangents[a].x = t.x;
tangents[a].y = t.y;
tangents[a].z = t.z;
tangents[a].w = (Vector3.Dot(Vector3.Cross(n, t), tan2[a]) < 0.0f) ? -1.0f : 1.0f;
}
mesh.tangents = tangents;
}
Vector3 bounce(Vector3 start, Vector3 end, float value)
{
value /= 1.0f;
end -= start;
if ( value < (1.0f / 2.75f) )
{
return end * (7.5625f * value * value) + start;
}
else
{
if ( value < (2.0f / 2.75f) )
{
value -= (1.5f / 2.75f);
return end * (7.5625f * (value) * value + 0.75f) + start;
}
else
{
if ( value < (2.5f / 2.75f) )
{
value -= (2.25f / 2.75f);
return end * (7.5625f * (value) * value + .9375f) + start;
}
else
{
value -= (2.625f / 2.75f);
return end * (7.5625f * (value) * value + .984375f) + start;
}
}
}
}
Vector3 easeInOutSine(Vector3 start, Vector3 end, float value)
{
end -= start;
return -end / 2.0f * (Mathf.Cos(Mathf.PI * value / 1.0f) - 1.0f) + start;
}
float delay = -1.0f;
int currentDest;
public void CheckForChange()
{
if ( !Application.isPlaying )
return;
if ( destwarp < 0 || destwarp >= warps.Count )
return;
if ( destwarp != srcwarp )
{
if ( destwarp != currentDest )
{
time = 0.0f;
currentDest = destwarp;
}
time += Time.deltaTime;
Warp from = warps[srcwarp];
Warp to = warps[destwarp];
float a = time / switchtime;
if ( a >= 1.0f )
{
a = 1.0f;
time = 0.0f;
srcwarp = destwarp;
}
p11 = easeInOutSine(from.points[0], to.points[0], a);
p12 = easeInOutSine(from.points[1], to.points[1], a);
p13 = easeInOutSine(from.points[2], to.points[2], a);
p14 = easeInOutSine(from.points[3], to.points[3], a);
p21 = easeInOutSine(from.points[4], to.points[4], a);
p22 = easeInOutSine(from.points[5], to.points[5], a);
p23 = easeInOutSine(from.points[6], to.points[6], a);
p24 = easeInOutSine(from.points[7], to.points[7], a);
p31 = easeInOutSine(from.points[8], to.points[8], a);
p32 = easeInOutSine(from.points[9], to.points[9], a);
p33 = easeInOutSine(from.points[10], to.points[10], a);
p34 = easeInOutSine(from.points[11], to.points[11], a);
p41 = easeInOutSine(from.points[12], to.points[12], a);
p42 = easeInOutSine(from.points[13], to.points[13], a);
p43 = easeInOutSine(from.points[14], to.points[14], a);
p44 = easeInOutSine(from.points[15], to.points[15], a);
}
else
time = 0.0f;
}
public void ChangeWarp(int f, int t)
{
if ( !Application.isPlaying )
return;
if ( delay > 0.0f )
{
delay -= Time.deltaTime;
return;
}
if ( time <= switchtime )
{
time += Time.deltaTime;
Warp from = warps[f];
Warp to = warps[t];
float a = time / switchtime;
if ( a > 1.0f )
{
a = 1.0f;
currentwarp = t;
t++;
destwarp = t;
if ( destwarp >= warps.Count )
destwarp = 0;
srcwarp = currentwarp;
time = 0.0f;
delay = 1.0f;
}
p11 = easeInOutSine(from.points[0], to.points[0], a);
p12 = easeInOutSine(from.points[1], to.points[1], a);
p13 = easeInOutSine(from.points[2], to.points[2], a);
p14 = easeInOutSine(from.points[3], to.points[3], a);
p21 = easeInOutSine(from.points[4], to.points[4], a);
p22 = easeInOutSine(from.points[5], to.points[5], a);
p23 = easeInOutSine(from.points[6], to.points[6], a);
p24 = easeInOutSine(from.points[7], to.points[7], a);
p31 = easeInOutSine(from.points[8], to.points[8], a);
p32 = easeInOutSine(from.points[9], to.points[9], a);
p33 = easeInOutSine(from.points[10], to.points[10], a);
p34 = easeInOutSine(from.points[11], to.points[11], a);
p41 = easeInOutSine(from.points[12], to.points[12], a);
p42 = easeInOutSine(from.points[13], to.points[13], a);
p43 = easeInOutSine(from.points[14], to.points[14], a);
p44 = easeInOutSine(from.points[15], to.points[15], a);
}
}
}
| |
using System;
using System.Collections;
using System.Xml.Serialization;
namespace CslaGenerator.Metadata
{
/// <summary>
/// A strongly-typed collection of <see cref="Property"/> objects.
/// </summary>
[Serializable]
public class PropertyCollection : IList, ICloneable
{
#region Interfaces
/// <summary>
/// Supports type-safe iteration over a <see cref="PropertyCollection"/>.
/// </summary>
public interface IPropertyCollectionEnumerator
{
/// <summary>
/// Gets the current element in the collection.
/// </summary>
Property Current { get; }
/// <summary>
/// Advances the enumerator to the next element in the collection.
/// </summary>
/// <exception cref="InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
/// <returns>
/// <c>true</c> if the enumerator was successfully advanced to the next element;
/// <c>false</c> if the enumerator has passed the end of the collection.
/// </returns>
bool MoveNext();
/// <summary>
/// Sets the enumerator to its initial position, before the first element in the collection.
/// </summary>
void Reset();
}
#endregion
private const int DEFAULT_CAPACITY = 16;
#region Implementation (data)
private Property[] _array;
private int _count = 0;
[XmlIgnore] private int _version = 0;
#endregion
#region Static Wrappers
/// <summary>
/// Creates a synchronized (thread-safe) wrapper for a
/// <c>PropertyCollection</c> instance.
/// </summary>
/// <returns>
/// An <c>PropertyCollection</c> wrapper that is synchronized (thread-safe).
/// </returns>
public static PropertyCollection Synchronized(PropertyCollection list)
{
if (list == null)
throw new ArgumentNullException("list");
return new SyncPropertyCollection(list);
}
/// <summary>
/// Creates a read-only wrapper for a
/// <c>PropertyCollection</c> instance.
/// </summary>
/// <returns>
/// An <c>PropertyCollection</c> wrapper that is read-only.
/// </returns>
public static PropertyCollection ReadOnly(PropertyCollection list)
{
if (list == null)
throw new ArgumentNullException("list");
return new ReadOnlyPropertyCollection(list);
}
#endregion
#region Construction
/// <summary>
/// Initializes a new instance of the <c>PropertyCollection</c> class
/// that is empty and has the default initial capacity.
/// </summary>
public PropertyCollection()
{
_array = new Property[DEFAULT_CAPACITY];
}
/// <summary>
/// Initializes a new instance of the <c>PropertyCollection</c> class
/// that has the specified initial capacity.
/// </summary>
/// <param name="capacity">
/// The number of elements that the new <c>PropertyCollection</c> is initially capable of storing.
/// </param>
public PropertyCollection(int capacity)
{
_array = new Property[capacity];
}
/// <summary>
/// Initializes a new instance of the <c>PropertyCollection</c> class
/// that contains elements copied from the specified <c>PropertyCollection</c>.
/// </summary>
/// <param name="c">The <c>PropertyCollection</c> whose elements are copied to the new collection.</param>
public PropertyCollection(PropertyCollection c)
{
_array = new Property[c.Count];
AddRange(c);
}
/// <summary>
/// Initializes a new instance of the <c>PropertyCollection</c> class
/// that contains elements copied from the specified <see cref="Property"/> array.
/// </summary>
/// <param name="a">The <see cref="Property"/> array whose elements are copied to the new list.</param>
public PropertyCollection(Property[] a)
{
_array = new Property[a.Length];
AddRange(a);
}
protected enum Tag
{
Default
}
protected PropertyCollection(Tag t)
{
_array = null;
}
#endregion
#region Operations (type-safe ICollection)
/// <summary>
/// Gets the number of elements actually contained in the <c>PropertyCollection</c>.
/// </summary>
public virtual int Count
{
get { return _count; }
}
/// <summary>
/// Copies the entire <c>PropertyCollection</c> to a one-dimensional
/// <see cref="Property"/> array.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Property"/> array to copy to.</param>
public virtual void CopyTo(Property[] array)
{
this.CopyTo(array, 0);
}
/// <summary>
/// Copies the entire <c>PropertyCollection</c> to a one-dimensional
/// <see cref="Property"/> array, starting at the specified index of the target array.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Property"/> array to copy to.</param>
/// <param name="start">The zero-based index in <paramref name="array"/> at which copying begins.</param>
public virtual void CopyTo(Property[] array, int start)
{
if (_count > array.GetUpperBound(0) + 1 - start)
throw new System.ArgumentException("Destination array was not long enough.");
Array.Copy(_array, 0, array, start, _count);
}
/// <summary>
/// Gets a value indicating whether access to the collection is synchronized (thread-safe).
/// </summary>
/// <returns>true if access to the ICollection is synchronized (thread-safe); otherwise, false.</returns>
public virtual bool IsSynchronized
{
get { return _array.IsSynchronized; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the collection.
/// </summary>
public virtual object SyncRoot
{
get { return _array.SyncRoot; }
}
#endregion
#region Operations (type-safe IList)
/// <summary>
/// Gets or sets the <see cref="Property"/> at the specified index.
/// </summary>
/// <param name="index">The zero-based index of the element to get or set.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="PropertyCollection.Count"/>.</para>
/// </exception>
public virtual Property this[int index]
{
get
{
ValidateIndex(index); // throws
return _array[index];
}
set
{
ValidateIndex(index); // throws
++_version;
_array[index] = value;
}
}
/// <summary>
/// Adds a <see cref="Property"/> to the end of the <c>PropertyCollection</c>.
/// </summary>
/// <param name="item">The <see cref="Property"/> to be added to the end of the <c>PropertyCollection</c>.</param>
/// <returns>The index at which the value has been added.</returns>
public virtual int Add(Property item)
{
//This is done so that the collection stores Property Objects ONLY
//and avoid saving a ValueProperty to the xml when there's no need.
if (_count == _array.Length)
EnsureCapacity(_count + 1);
_array[_count] = item;
_version++;
return _count++;
}
/// <summary>
/// Removes all elements from the <c>PropertyCollection</c>.
/// </summary>
public virtual void Clear()
{
++_version;
_array = new Property[DEFAULT_CAPACITY];
_count = 0;
}
/// <summary>
/// Creates a shallow copy of the <see cref="PropertyCollection"/>.
/// </summary>
public virtual object Clone()
{
PropertyCollection newColl = new PropertyCollection(_count);
Array.Copy(_array, 0, newColl._array, 0, _count);
newColl._count = _count;
newColl._version = _version;
return newColl;
}
/// <summary>
/// Determines whether a given <see cref="Property"/> is in the <c>PropertyCollection</c>.
/// </summary>
/// <param name="item">The <see cref="Property"/> to check for.</param>
/// <returns><c>true</c> if <paramref name="item"/> is found in the <c>PropertyCollection</c>; otherwise, <c>false</c>.</returns>
public virtual bool Contains(Property item)
{
for (int i = 0; i != _count; ++i)
if (_array[i].Equals(item))
return true;
return false;
}
/// <summary>
/// Determines whether a given <see cref="Property"/> is in the <c>PropertyCollection</c>.
/// </summary>
/// <param name="name">The property name to check for.</param>
/// <returns><c>true</c> if <paramref name="name"/> is found in the <c>PropertyCollection</c>; otherwise, <c>false</c>.</returns>
public virtual bool Contains(string name)
{
for (int i = 0; i != _count; ++i)
if (CaseInsensitiveComparer.Default.Compare(_array[i].Name, name) == 0)
return true;
return false;
}
/// <summary>
/// Returns the zero-based index of the first occurrence of a <see cref="Property"/>
/// in the <c>PropertyCollection</c>.
/// </summary>
/// <param name="item">The <see cref="Property"/> to locate in the <c>PropertyCollection</c>.</param>
/// <returns>
/// The zero-based index of the first occurrence of <paramref name="item"/>
/// in the entire <c>PropertyCollection</c>, if found; otherwise, -1.
/// </returns>
public virtual int IndexOf(Property item)
{
for (int i = 0; i != _count; ++i)
if (_array[i].Equals(item))
return i;
return -1;
}
/// <summary>
/// Inserts an element into the <c>PropertyCollection</c> at the specified index.
/// </summary>
/// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param>
/// <param name="item">The <see cref="Property"/> to insert.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="PropertyCollection.Count"/>.</para>
/// </exception>
public virtual void Insert(int index, Property item)
{
ValidateIndex(index, true); // throws
if (_count == _array.Length)
EnsureCapacity(_count + 1);
if (index < _count)
{
Array.Copy(_array, index, _array, index + 1, _count - index);
}
item = new Property(item);
_array[index] = item;
_count++;
_version++;
}
/// <summary>
/// Removes the first occurrence of a specific <see cref="Property"/> from the <c>PropertyCollection</c>.
/// </summary>
/// <param name="item">The <see cref="Property"/> to remove from the <c>PropertyCollection</c>.</param>
/// <exception cref="ArgumentException">
/// The specified <see cref="Property"/> was not found in the <c>PropertyCollection</c>.
/// </exception>
public virtual void Remove(Property item)
{
int i = IndexOf(item);
if (i < 0)
throw new ArgumentException(
"Cannot remove the specified item because it was not found in the specified Collection.");
++_version;
RemoveAt(i);
}
/// <summary>
/// Removes the element at the specified index of the <c>PropertyCollection</c>.
/// </summary>
/// <param name="index">The zero-based index of the element to remove.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="PropertyCollection.Count"/>.</para>
/// </exception>
public virtual void RemoveAt(int index)
{
ValidateIndex(index); // throws
_count--;
if (index < _count)
{
Array.Copy(_array, index + 1, _array, index, _count - index);
}
// We can't set the deleted entry equal to null, because it might be a value type.
// Instead, we'll create an empty single-element array of the right type and copy it
// over the entry we want to erase.
Property[] temp = new Property[1];
Array.Copy(temp, 0, _array, _count, 1);
_version++;
}
/// <summary>
/// Gets a value indicating whether the collection has a fixed size.
/// </summary>
/// <value>true if the collection has a fixed size; otherwise, false. The default is false</value>
public virtual bool IsFixedSize
{
get { return false; }
}
/// <summary>
/// gets a value indicating whether the <B>IList</B> is read-only.
/// </summary>
/// <value>true if the collection is read-only; otherwise, false. The default is false</value>
public virtual bool IsReadOnly
{
get { return false; }
}
#endregion
#region Operations (type-safe IEnumerable)
/// <summary>
/// Returns an enumerator that can iterate through the <c>PropertyCollection</c>.
/// </summary>
/// <returns>An <see cref="Enumerator"/> for the entire <c>PropertyCollection</c>.</returns>
public virtual IPropertyCollectionEnumerator GetEnumerator()
{
return new Enumerator(this);
}
#endregion
#region Public helpers (just to mimic some nice features of ArrayList)
/// <summary>
/// Gets or sets the number of elements the <c>PropertyCollection</c> can contain.
/// </summary>
public virtual int Capacity
{
get { return _array.Length; }
set
{
if (value < _count)
value = _count;
if (value != _array.Length)
{
if (value > 0)
{
Property[] temp = new Property[value];
Array.Copy(_array, temp, _count);
_array = temp;
}
else
{
_array = new Property[DEFAULT_CAPACITY];
}
}
}
}
/// <summary>
/// Adds the elements of another <c>PropertyCollection</c> to the current <c>PropertyCollection</c>.
/// </summary>
/// <param name="x">The <c>PropertyCollection</c> whose elements should be added to the end of the current <c>PropertyCollection</c>.</param>
/// <returns>The new <see cref="PropertyCollection.Count"/> of the <c>PropertyCollection</c>.</returns>
public virtual int AddRange(PropertyCollection x)
{
if (_count + x.Count >= _array.Length)
EnsureCapacity(_count + x.Count);
Array.Copy(x._array, 0, _array, _count, x.Count);
_count += x.Count;
_version++;
return _count;
}
/// <summary>
/// Adds the elements of a <see cref="Property"/> array to the current <c>PropertyCollection</c>.
/// </summary>
/// <param name="x">The <see cref="Property"/> array whose elements should be added to the end of the <c>PropertyCollection</c>.</param>
/// <returns>The new <see cref="PropertyCollection.Count"/> of the <c>PropertyCollection</c>.</returns>
public virtual int AddRange(Property[] x)
{
if (_count + x.Length >= _array.Length)
EnsureCapacity(_count + x.Length);
Array.Copy(x, 0, _array, _count, x.Length);
_count += x.Length;
_version++;
return _count;
}
/// <summary>
/// Sets the capacity to the actual number of elements.
/// </summary>
public virtual void TrimToSize()
{
Capacity = _count;
}
#endregion
#region Implementation (helpers)
/// <exception cref="ArgumentOutOfRangeException">
/// <para><paramref name="index"/> is less than zero</para>
/// <para>-or-</para>
/// <para><paramref name="index"/> is equal to or greater than <see cref="PropertyCollection.Count"/>.</para>
/// </exception>
private void ValidateIndex(int i)
{
ValidateIndex(i, false);
}
/// <summary>
/// Validates the index.
/// </summary>
/// <param name="i">The i.</param>
/// <param name="allowEqualEnd">if set to <c>true</c> [allow equal end].</param>
/// <exception cref="ArgumentOutOfRangeException"></exception>
private void ValidateIndex(int i, bool allowEqualEnd)
{
int max = (allowEqualEnd) ? (_count) : (_count - 1);
if (i < 0 || i > max)
throw new ArgumentOutOfRangeException(
"Index was out of range. Must be non-negative and less than the size of the collection.",
i, "Specified argument was out of the range of valid values.");
}
private void EnsureCapacity(int min)
{
int newCapacity = ((_array.Length == 0) ? DEFAULT_CAPACITY : _array.Length*2);
if (newCapacity < min)
newCapacity = min;
Capacity = newCapacity;
}
#endregion
#region Implementation (ICollection)
void ICollection.CopyTo(Array array, int start)
{
CopyTo((Property[]) array, start);
}
#endregion
#region Implementation (IList)
object IList.this[int i]
{
get { return this[i]; }
set { this[i] = (Property) value; }
}
int IList.Add(object x)
{
return this.Add((Property) x);
}
bool IList.Contains(object x)
{
return Contains((Property) x);
}
int IList.IndexOf(object x)
{
return IndexOf((Property) x);
}
void IList.Insert(int pos, object x)
{
Insert(pos, (Property) x);
}
void IList.Remove(object x)
{
Remove((Property) x);
}
void IList.RemoveAt(int pos)
{
RemoveAt(pos);
}
#endregion
#region Implementation (IEnumerable)
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator) (GetEnumerator());
}
#endregion
#region Nested enumerator class
/// <summary>
/// Supports simple iteration over a <see cref="PropertyCollection"/>.
/// </summary>
private class Enumerator : IEnumerator, IPropertyCollectionEnumerator
{
#region Implementation (data)
private PropertyCollection _collection;
private int _index;
private int _version;
#endregion
#region Construction
/// <summary>
/// Initializes a new instance of the <c>Enumerator</c> class.
/// </summary>
/// <param name="tc"></param>
internal Enumerator(PropertyCollection tc)
{
_collection = tc;
_index = -1;
_version = tc._version;
}
#endregion
#region Operations (type-safe IEnumerator)
/// <summary>
/// Gets the current element in the collection.
/// </summary>
public Property Current
{
get { return _collection[_index]; }
}
/// <summary>
/// Advances the enumerator to the next element in the collection.
/// </summary>
/// <exception cref="InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
/// <returns>
/// <c>true</c> if the enumerator was successfully advanced to the next element;
/// <c>false</c> if the enumerator has passed the end of the collection.
/// </returns>
public bool MoveNext()
{
if (_version != _collection._version)
throw new InvalidOperationException(
"Collection was modified; enumeration operation may not execute.");
++_index;
return (_index < _collection.Count);
}
/// <summary>
/// Sets the enumerator to its initial position, before the first element in the collection.
/// </summary>
public void Reset()
{
_index = -1;
}
#endregion
#region Implementation (IEnumerator)
object IEnumerator.Current
{
get { return Current; }
}
#endregion
}
#endregion
#region Nested Syncronized Wrapper class
[Serializable]
private class SyncPropertyCollection : PropertyCollection, System.Runtime.Serialization.IDeserializationCallback
{
#region Implementation (data)
private const int Timeout = 0; // infinite
private PropertyCollection _collection;
[XmlIgnore]
private System.Threading.ReaderWriterLock _rwLock;
#endregion
#region Construction
internal SyncPropertyCollection(PropertyCollection list)
: base(Tag.Default)
{
_rwLock = new System.Threading.ReaderWriterLock();
_collection = list;
}
#endregion
#region IDeserializationCallback Members
void System.Runtime.Serialization.IDeserializationCallback.OnDeserialization(object sender)
{
_rwLock = new System.Threading.ReaderWriterLock();
}
#endregion
#region Type-safe ICollection
public override void CopyTo(Property[] array)
{
_rwLock.AcquireReaderLock(Timeout);
try
{
_collection.CopyTo(array);
}
finally
{
_rwLock.ReleaseReaderLock();
}
}
public override void CopyTo(Property[] array, int start)
{
_rwLock.AcquireReaderLock(Timeout);
try
{
_collection.CopyTo(array, start);
}
finally
{
_rwLock.ReleaseReaderLock();
}
}
public override int Count
{
get
{
int count = 0;
_rwLock.AcquireReaderLock(Timeout);
try
{
count = _collection.Count;
}
finally
{
_rwLock.ReleaseReaderLock();
}
return count;
}
}
public override bool IsSynchronized
{
get { return true; }
}
public override object SyncRoot
{
get { return _collection.SyncRoot; }
}
#endregion
#region Type-safe IList
public override Property this[int i]
{
get
{
Property thisItem;
_rwLock.AcquireReaderLock(Timeout);
try
{
thisItem = _collection[i];
}
finally
{
_rwLock.ReleaseReaderLock();
}
return thisItem;
}
set
{
_rwLock.AcquireWriterLock(Timeout);
try
{
_collection[i] = value;
}
finally
{
_rwLock.ReleaseWriterLock();
}
}
}
public override int Add(Property x)
{
int result;
_rwLock.AcquireWriterLock(Timeout);
try
{
result = _collection.Add(x);
}
finally
{
_rwLock.ReleaseWriterLock();
}
return result;
}
public override void Clear()
{
_rwLock.AcquireWriterLock(Timeout);
try
{
_collection.Clear();
}
finally
{
_rwLock.ReleaseWriterLock();
}
}
public override bool Contains(Property x)
{
bool result = false;
_rwLock.AcquireReaderLock(Timeout);
try
{
result = _collection.Contains(x);
}
finally
{
_rwLock.ReleaseReaderLock();
}
return result;
}
public override int IndexOf(Property x)
{
int result;
_rwLock.AcquireReaderLock(Timeout);
try
{
result = _collection.IndexOf(x);
}
finally
{
_rwLock.ReleaseReaderLock();
}
return result;
}
public override void Insert(int pos, Property x)
{
_rwLock.AcquireWriterLock(Timeout);
try
{
_collection.Insert(pos, x);
}
finally
{
_rwLock.ReleaseWriterLock();
}
}
public override void Remove(Property x)
{
_rwLock.AcquireWriterLock(Timeout);
try
{
_collection.Remove(x);
}
finally
{
_rwLock.ReleaseWriterLock();
}
}
public override void RemoveAt(int pos)
{
_rwLock.AcquireWriterLock(Timeout);
try
{
_collection.RemoveAt(pos);
}
finally
{
_rwLock.ReleaseWriterLock();
}
}
public override bool IsFixedSize
{
get { return _collection.IsFixedSize; }
}
public override bool IsReadOnly
{
get { return _collection.IsReadOnly; }
}
#endregion
#region Type-safe IEnumerable
public override IPropertyCollectionEnumerator GetEnumerator()
{
IPropertyCollectionEnumerator enumerator;
_rwLock.AcquireReaderLock(Timeout);
try
{
enumerator = _collection.GetEnumerator();
}
finally
{
_rwLock.ReleaseReaderLock();
}
return enumerator;
}
#endregion
#region Public Helpers
// (just to mimic some nice features of ArrayList)
public override int Capacity
{
get
{
int result;
_rwLock.AcquireReaderLock(Timeout);
try
{
result = _collection.Capacity;
}
finally
{
_rwLock.ReleaseReaderLock();
}
return result;
}
set
{
_rwLock.AcquireWriterLock(Timeout);
try
{
_collection.Capacity = value;
}
finally
{
_rwLock.ReleaseWriterLock();
}
}
}
public override int AddRange(PropertyCollection x)
{
int result;
_rwLock.AcquireWriterLock(Timeout);
try
{
result = _collection.AddRange(x);
}
finally
{
_rwLock.ReleaseWriterLock();
}
return result;
}
public override int AddRange(Property[] x)
{
int result;
_rwLock.AcquireWriterLock(Timeout);
try
{
result = _collection.AddRange(x);
}
finally
{
_rwLock.ReleaseWriterLock();
}
return result;
}
#endregion
}
#endregion
#region Nested Read Only Wrapper class
[Serializable]
private class ReadOnlyPropertyCollection : PropertyCollection
{
#region Implementation (data)
private PropertyCollection _collection;
#endregion
#region Construction
internal ReadOnlyPropertyCollection(PropertyCollection list)
: base(Tag.Default)
{
_collection = list;
}
#endregion
#region Type-safe ICollection
public override void CopyTo(Property[] array)
{
_collection.CopyTo(array);
}
public override void CopyTo(Property[] array, int start)
{
_collection.CopyTo(array, start);
}
public override int Count
{
get { return _collection.Count; }
}
public override bool IsSynchronized
{
get { return _collection.IsSynchronized; }
}
public override object SyncRoot
{
get { return _collection.SyncRoot; }
}
#endregion
#region Type-safe IList
public override Property this[int i]
{
get { return _collection[i]; }
set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); }
}
public override int Add(Property x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override void Clear()
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override bool Contains(Property x)
{
return _collection.Contains(x);
}
public override int IndexOf(Property x)
{
return _collection.IndexOf(x);
}
public override void Insert(int pos, Property x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override void Remove(Property x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override void RemoveAt(int pos)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override bool IsFixedSize
{
get { return true; }
}
public override bool IsReadOnly
{
get { return true; }
}
#endregion
#region Type-safe IEnumerable
public override IPropertyCollectionEnumerator GetEnumerator()
{
return _collection.GetEnumerator();
}
#endregion
#region Public Helpers
// (just to mimic some nice features of ArrayList)
public override int Capacity
{
get { return _collection.Capacity; }
set { throw new NotSupportedException("This is a Read Only Collection and can not be modified"); }
}
public override int AddRange(PropertyCollection x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
public override int AddRange(Property[] x)
{
throw new NotSupportedException("This is a Read Only Collection and can not be modified");
}
#endregion
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Orleans.Runtime.ConsistentRing
{
/// <summary>
/// We use the 'backward/clockwise' definition to assign responsibilities on the ring.
/// E.g. in a ring of nodes {5, 10, 15} the responsible for key 7 is 10 (the node is responsible for its predecessing range).
/// The backwards/clockwise approach is consistent with many overlays, e.g., Chord, Cassandra, etc.
/// Note: MembershipOracle uses 'forward/counter-clockwise' definition to assign responsibilities.
/// E.g. in a ring of nodes {5, 10, 15}, the responsible of key 7 is node 5 (the node is responsible for its sucessing range)..
/// </summary>
internal class ConsistentRingProvider : MarshalByRefObject, IConsistentRingProvider, ISiloStatusListener // make the ring shutdown-able?
{
// internal, so that unit tests can access them
internal SiloAddress MyAddress { get; private set; }
internal IRingRange MyRange { get; private set; }
/// list of silo members sorted by the hash value of their address
private readonly List<SiloAddress> membershipRingList;
private readonly Logger log;
private bool isRunning;
private readonly int myKey;
private readonly List<IRingRangeListener> statusListeners;
public ConsistentRingProvider(SiloAddress siloAddr)
{
log = LogManager.GetLogger(typeof(ConsistentRingProvider).Name);
membershipRingList = new List<SiloAddress>();
MyAddress = siloAddr;
myKey = MyAddress.GetConsistentHashCode();
// add myself to the list of members
AddServer(MyAddress);
MyRange = RangeFactory.CreateFullRange(); // i am responsible for the whole range
statusListeners = new List<IRingRangeListener>();
Start();
}
/// <summary>
/// Returns the silo that this silo thinks is the primary owner of the key
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public SiloAddress GetPrimaryTargetSilo(uint key)
{
return CalculateTargetSilo(key);
}
public IRingRange GetMyRange()
{
return MyRange; // its immutable, so no need to clone
}
/// <summary>
/// Returns null if silo is not in the list of members
/// </summary>
public List<SiloAddress> GetMySucessors(int n = 1)
{
return FindSuccessors(MyAddress, n);
}
/// <summary>
/// Returns null if silo is not in the list of members
/// </summary>
public List<SiloAddress> GetMyPredecessors(int n = 1)
{
return FindPredecessors(MyAddress, n);
}
#region Handling the membership
private void Start()
{
isRunning = true;
}
private void Stop()
{
isRunning = false;
}
internal void AddServer(SiloAddress silo)
{
lock (membershipRingList)
{
if (membershipRingList.Contains(silo)) return; // we already have this silo
int myOldIndex = membershipRingList.FindIndex(elem => elem.Equals(MyAddress));
if (!(membershipRingList.Count == 0 || myOldIndex != -1))
throw new OrleansException(string.Format("{0}: Couldn't find my position in the ring {1}.", MyAddress, Utils.EnumerableToString(membershipRingList)));
// insert new silo in the sorted order
int hash = silo.GetConsistentHashCode();
// Find the last silo with hash smaller than the new silo, and insert the latter after (this is why we have +1 here) the former.
// Notice that FindLastIndex might return -1 if this should be the first silo in the list, but then
// 'index' will get 0, as needed.
int index = membershipRingList.FindLastIndex(siloAddr => siloAddr.GetConsistentHashCode() < hash) + 1;
membershipRingList.Insert(index, silo);
// relating to triggering handler ... new node took over some of my responsibility
if (index == myOldIndex || // new node was inserted in my place
(myOldIndex == 0 && index == membershipRingList.Count - 1)) // I am the first node, and the new server is the last node
{
IRingRange oldRange = MyRange;
try
{
MyRange = RangeFactory.CreateRange(unchecked((uint)hash), unchecked((uint)myKey));
}
catch (OverflowException exc)
{
log.Error(ErrorCode.ConsistentRingProviderBase + 5,
String.Format("OverflowException: hash as int= x{0, 8:X8}, hash as uint= x{1, 8:X8}, myKey as int x{2, 8:X8}, myKey as uint x{3, 8:X8}.",
hash, (uint)hash, myKey, (uint)myKey), exc);
}
NotifyLocalRangeSubscribers(oldRange, MyRange, false);
}
log.Info("Added Server {0}. Current view: {1}", silo.ToStringWithHashCode(), this.ToString());
}
}
public override string ToString()
{
lock (membershipRingList)
{
if (membershipRingList.Count == 1)
return Utils.EnumerableToString(membershipRingList, silo => String.Format("{0} -> {1}", silo.ToStringWithHashCode(), RangeFactory.CreateFullRange()));
var sb = new StringBuilder("[");
for (int i=0; i < membershipRingList.Count; i++)
{
SiloAddress curr = membershipRingList[ i ];
SiloAddress next = membershipRingList[ (i +1) % membershipRingList.Count];
IRingRange range = RangeFactory.CreateRange(unchecked((uint)curr.GetConsistentHashCode()), unchecked((uint)next.GetConsistentHashCode()));
sb.Append(String.Format("{0} -> {1}, ", curr.ToStringWithHashCode(), range));
}
sb.Append("]");
return sb.ToString();
}
}
internal void RemoveServer(SiloAddress silo)
{
lock (membershipRingList)
{
int indexOfFailedSilo = membershipRingList.FindIndex(elem => elem.Equals(silo));
if (indexOfFailedSilo < 0) return; // we have already removed this silo
membershipRingList.Remove(silo);
// related to triggering handler
int myNewIndex = membershipRingList.FindIndex(elem => elem.Equals(MyAddress));
if (myNewIndex == -1)
throw new OrleansException(string.Format("{0}: Couldn't find my position in the ring {1}.", MyAddress, this.ToString()));
bool wasMyPred = ((myNewIndex == indexOfFailedSilo) || (myNewIndex == 0 && indexOfFailedSilo == membershipRingList.Count)); // no need for '- 1'
if (wasMyPred) // failed node was our predecessor
{
if (log.IsVerbose) log.Verbose("Failed server was my pred? {0}, updated view {1}", wasMyPred, this.ToString());
IRingRange oldRange = MyRange;
if (membershipRingList.Count == 1) // i'm the only one left
{
MyRange = RangeFactory.CreateFullRange();
NotifyLocalRangeSubscribers(oldRange, MyRange, true);
}
else
{
int myNewPredIndex = myNewIndex == 0 ? membershipRingList.Count - 1 : myNewIndex - 1;
int myPredecessorsHash = membershipRingList[myNewPredIndex].GetConsistentHashCode();
MyRange = RangeFactory.CreateRange(unchecked((uint)myPredecessorsHash), unchecked((uint)myKey));
NotifyLocalRangeSubscribers(oldRange, MyRange, true);
}
}
log.Info("Removed Server {0} hash {1}. Current view {2}", silo, silo.GetConsistentHashCode(), this.ToString());
}
}
/// <summary>
/// Returns null if silo is not in the list of members
/// </summary>
internal List<SiloAddress> FindPredecessors(SiloAddress silo, int count)
{
lock (membershipRingList)
{
int index = membershipRingList.FindIndex(elem => elem.Equals(silo));
if (index == -1)
{
log.Warn(ErrorCode.Runtime_Error_100201, "Got request to find predecessors of silo " + silo + ", which is not in the list of members.");
return null;
}
var result = new List<SiloAddress>();
int numMembers = membershipRingList.Count;
for (int i = index - 1; ((i + numMembers) % numMembers) != index && result.Count < count; i--)
{
result.Add(membershipRingList[(i + numMembers) % numMembers]);
}
return result;
}
}
/// <summary>
/// Returns null if silo is not in the list of members
/// </summary>
internal List<SiloAddress> FindSuccessors(SiloAddress silo, int count)
{
lock (membershipRingList)
{
int index = membershipRingList.FindIndex(elem => elem.Equals(silo));
if (index == -1)
{
log.Warn(ErrorCode.Runtime_Error_100203, "Got request to find successors of silo " + silo + ", which is not in the list of members.");
return null;
}
var result = new List<SiloAddress>();
int numMembers = membershipRingList.Count;
for (int i = index + 1; i % numMembers != index && result.Count < count; i++)
{
result.Add(membershipRingList[i % numMembers]);
}
return result;
}
}
#region Notification related
public bool SubscribeToRangeChangeEvents(IRingRangeListener observer)
{
lock (statusListeners)
{
if (statusListeners.Contains(observer)) return false;
statusListeners.Add(observer);
return true;
}
}
public bool UnSubscribeFromRangeChangeEvents(IRingRangeListener observer)
{
lock (statusListeners)
{
return statusListeners.Contains(observer) && statusListeners.Remove(observer);
}
}
private void NotifyLocalRangeSubscribers(IRingRange old, IRingRange now, bool increased)
{
log.Info("-NotifyLocalRangeSubscribers about old {0} new {1} increased? {2}", old, now, increased);
List<IRingRangeListener> copy;
lock (statusListeners)
{
copy = statusListeners.ToList();
}
foreach (IRingRangeListener listener in copy)
{
try
{
listener.RangeChangeNotification(old, now, increased);
}
catch (Exception exc)
{
log.Error(ErrorCode.CRP_Local_Subscriber_Exception,
String.Format("Local IRangeChangeListener {0} has thrown an exception when was notified about RangeChangeNotification about old {1} new {2} increased? {3}",
listener.GetType().FullName, old, now, increased), exc);
}
}
}
#endregion
public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status)
{
// This silo's status has changed
if (updatedSilo.Equals(MyAddress))
{
if (status.IsTerminating())
{
Stop();
}
}
else // Status change for some other silo
{
if (status.IsTerminating())
{
RemoveServer(updatedSilo);
}
else if (status.Equals(SiloStatus.Active)) // do not do anything with SiloStatus.Created or SiloStatus.Joining -- wait until it actually becomes active
{
AddServer(updatedSilo);
}
}
}
#endregion
/// <summary>
/// Finds the silo that owns the given hash value.
/// This routine will always return a non-null silo address unless the excludeThisSiloIfStopping parameter is true,
/// this is the only silo known, and this silo is stopping.
/// </summary>
/// <param name="hash"></param>
/// <param name="excludeThisSiloIfStopping"></param>
/// <returns></returns>
public SiloAddress CalculateTargetSilo(uint hash, bool excludeThisSiloIfStopping = true)
{
SiloAddress siloAddress;
lock (membershipRingList)
{
// excludeMySelf from being a TargetSilo if we're not running and the excludeThisSIloIfStopping flag is true. see the comment in the Stop method.
bool excludeMySelf = excludeThisSiloIfStopping && !isRunning;
if (membershipRingList.Count == 0)
{
// If the membership ring is empty, then we're the owner by default unless we're stopping.
return excludeMySelf ? null : MyAddress;
}
// use clockwise ... current code in membershipOracle.CalculateTargetSilo() does counter-clockwise ...
// if you want to stick to counter-clockwise, change the responsibility definition in 'In()' method & responsibility defs in OrleansReminderMemory
// need to implement a binary search, but for now simply traverse the list of silos sorted by their hashes
siloAddress = membershipRingList.Find(siloAddr => (siloAddr.GetConsistentHashCode() >= hash) && // <= hash for counter-clockwise responsibilities
(!siloAddr.Equals(MyAddress) || !excludeMySelf));
if (siloAddress == null)
{
// if not found in traversal, then first silo should be returned (we are on a ring)
// if you go back to their counter-clockwise policy, then change the 'In()' method in OrleansReminderMemory
siloAddress = membershipRingList[0]; // vs [membershipRingList.Count - 1]; for counter-clockwise policy
// Make sure it's not us...
if (siloAddress.Equals(MyAddress) && excludeMySelf)
{
// vs [membershipRingList.Count - 2]; for counter-clockwise policy
siloAddress = membershipRingList.Count > 1 ? membershipRingList[1] : null;
}
}
}
if (log.IsVerbose2) log.Verbose2("Silo {0} calculated ring partition owner silo {1} for key {2}: {3} --> {4}", MyAddress, siloAddress, hash, hash, siloAddress.GetConsistentHashCode());
return siloAddress;
}
}
}
| |
/// OSVR-Unity Connection
///
/// http://sensics.com/osvr
///
/// <copyright>
/// Copyright 2014 Sensics, 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.
/// </copyright>
/// <summary>
/// Author: Bob Berkebile
/// Email: bob@bullyentertainment.com || bobb@pixelplacement.com
/// </summary>
using UnityEngine;
using System.Collections;
using System.Reflection;
using System;
namespace OSVR
{
namespace Unity
{
public class VREye : MonoBehaviour
{
public const int NUM_SURFACES = 1;
#region Private Variables
private VRViewer _viewer; //the viewer associated with this eye
private VRSurface[] _surfaces; //the surfaces associated with this eye
private uint _surfaceCount;
private uint _eyeIndex;
#endregion
#region Public Variables
public uint EyeIndex
{
get { return _eyeIndex; }
set { _eyeIndex = value; }
}
public VRSurface[] Surfaces { get { return _surfaces; } }
public uint SurfaceCount { get { return _surfaceCount; } }
public VRViewer Viewer
{
get { return _viewer; }
set { _viewer = value; }
}
[HideInInspector]
public Transform cachedTransform;
#endregion
#region Init
void Awake()
{
Init();
}
#endregion
#region Public Methods
#endregion
#region Private Methods
void Init()
{
//cache:
cachedTransform = transform;
}
#endregion
// Updates the position and rotation of the eye
// Optionally, update the viewer associated with this eye
public void UpdateEyePose(OSVR.ClientKit.Pose3 eyePose)
{
// Convert from OSVR space into Unity space.
Vector3 pos = Math.ConvertPosition(eyePose.translation);
Quaternion rot = Math.ConvertOrientation(eyePose.rotation);
// RenderManager produces the eyeFromSpace matrix, but
// Unity wants the inverse of that.
if (Viewer.DisplayController.UseRenderManager)
{
// Invert the transformation
cachedTransform.localRotation = Quaternion.Inverse(rot);
Vector3 invPos = -pos;
cachedTransform.localPosition = Quaternion.Inverse(rot) * invPos;
}
else
{
cachedTransform.localPosition = pos;
cachedTransform.localRotation = rot;
}
}
//For each Surface, update viewing parameters and render the surface
public void UpdateSurfaces()
{
//for each surface
for (uint surfaceIndex = 0; surfaceIndex < SurfaceCount; surfaceIndex++)
{
//get the eye's surface
VRSurface surface = Surfaces[surfaceIndex];
OSVR.ClientKit.Viewport viewport;
OSVR.ClientKit.Matrix44f projMatrix;
//get viewport from ClientKit and set surface viewport
if (Viewer.DisplayController.UseRenderManager)
{
viewport = Viewer.DisplayController.RenderManager.GetEyeViewport((int)EyeIndex);
surface.SetViewportRect(Math.ConvertViewportRenderManager(viewport));
//get projection matrix from RenderManager and set surface projection matrix
surface.SetProjectionMatrix(Viewer.DisplayController.RenderManager.GetEyeProjectionMatrix((int)EyeIndex));
surface.Render();
}
else
{
//get viewport from ClientKit and set surface viewport
viewport = Viewer.DisplayController.DisplayConfig.GetRelativeViewportForViewerEyeSurface(
Viewer.ViewerIndex, (byte)_eyeIndex, surfaceIndex);
int displayInputIndex = Viewer.DisplayController.DisplayConfig.GetViewerEyeSurfaceDisplayInputIndex(Viewer.ViewerIndex, (byte)_eyeIndex, surfaceIndex);
int numDisplayInputs = Viewer.DisplayController.DisplayConfig.GetNumDisplayInputs();
surface.SetViewportRect(Math.ConvertViewport(viewport, Viewer.DisplayController.DisplayConfig.GetDisplayDimensions((byte)displayInputIndex),
numDisplayInputs, (int)_eyeIndex, (int)Viewer.DisplayController.TotalDisplayWidth));
//get projection matrix from ClientKit and set surface projection matrix
projMatrix = Viewer.DisplayController.DisplayConfig.GetProjectionMatrixForViewerEyeSurfacef(
Viewer.ViewerIndex, (byte)_eyeIndex, surfaceIndex,
surface.Camera.nearClipPlane, surface.Camera.farClipPlane, OSVR.ClientKit.MatrixConventionsFlags.ColMajor);
surface.SetProjectionMatrix(Math.ConvertMatrix(projMatrix));
//render the surface
surface.Render();
}
}
}
public void ClearSurfaces()
{
//for each surface
for (uint surfaceIndex = 0; surfaceIndex < SurfaceCount; surfaceIndex++)
{
//get the eye's surface
VRSurface surface = Surfaces[surfaceIndex];
surface.ClearRenderTarget();
}
}
//Create this Eye's VRSurfaces.
//Each VRSurface has a camera component which controls rendering for the VREye
public void CreateSurfaces(uint surfaceCount)
{
_surfaceCount = surfaceCount;
_surfaces = new VRSurface[_surfaceCount];
if (surfaceCount != NUM_SURFACES)
{
Debug.LogError("[OSVR-Unity] Eye" + _eyeIndex + " has " + surfaceCount + " surfaces, but " +
"this implementation requires exactly one surface per eye.");
return;
}
uint surfaceIndex = 0;
uint foundSurfaces = 0;
//Check if there are already VRSurfaces in the hierarchy.
//If so, use them instead of creating a new gameobjects
VRSurface[] eyeSurfaces = GetComponentsInChildren<VRSurface>();
foundSurfaces = (uint)eyeSurfaces.Length;
if (eyeSurfaces != null && foundSurfaces > 0)
{
for (surfaceIndex = 0; surfaceIndex < eyeSurfaces.Length; surfaceIndex++)
{
VRSurface surface = eyeSurfaces[surfaceIndex];
// get the VRSurface gameobject
GameObject surfaceGameObject = surface.gameObject;
surfaceGameObject.name = "VRSurface" + surfaceIndex;
surface.Eye = this;
surface.Camera = surfaceGameObject.GetComponent<Camera>(); //VRSurface has camera component by default
//don't copy from the main camera if the VRSurface already existed before runtime
//CopyCamera(Viewer.Camera, surface.Camera); //copy camera properties from the "dummy" camera to surface camera
surface.Camera.enabled = false; //disabled so we can control rendering manually
surface.SurfaceIndex = surfaceIndex; //set the surface index
surfaceGameObject.transform.localPosition = Vector3.zero;
surfaceGameObject.transform.rotation = this.transform.rotation;
Surfaces[surfaceIndex] = surface;
//distortion
bool useDistortion = Viewer.DisplayController.DisplayConfig.DoesViewerEyeSurfaceWantDistortion(Viewer.ViewerIndex, (byte)_eyeIndex, surfaceIndex);
if (useDistortion)
{
//@todo figure out which type of distortion to use
//right now, there is only one option, SurfaceRadialDistortion
//get distortion parameters
OSVR.ClientKit.RadialDistortionParameters distortionParameters =
Viewer.DisplayController.DisplayConfig.GetViewerEyeSurfaceRadialDistortion(
Viewer.ViewerIndex, (byte)_eyeIndex, surfaceIndex);
surface.SetDistortion(distortionParameters);
}
//render manager
if (Viewer.DisplayController.UseRenderManager)
{
surface.SetViewport(Viewer.DisplayController.RenderManager.GetEyeViewport((int)EyeIndex));
//create a RenderTexture for this eye's camera to render into
RenderTexture renderTexture = new RenderTexture(surface.Viewport.Width, surface.Viewport.Height, 24, RenderTextureFormat.Default);
if (QualitySettings.antiAliasing > 0)
{
renderTexture.antiAliasing = QualitySettings.antiAliasing;
}
surface.SetRenderTexture(renderTexture);
}
}
}
//loop through surfaces because at some point we could support eyes with multiple surfaces
//but this implementation currently supports exactly one
for (; surfaceIndex < surfaceCount; surfaceIndex++)
{
GameObject surfaceGameObject = new GameObject("VRSurface" + surfaceIndex);
VRSurface surface = surfaceGameObject.AddComponent<VRSurface>();
surface.Eye = this;
surface.Camera = surfaceGameObject.GetComponent<Camera>(); //VRSurface has camera component by default
CopyCamera(Viewer.Camera, surface.Camera); //copy camera properties from the "dummy" camera to surface camera
surface.Camera.enabled = false; //disabled so we can control rendering manually
surface.SurfaceIndex = surfaceIndex; //set the surface index
surfaceGameObject.transform.parent = this.transform; //surface is child of Eye
surfaceGameObject.transform.localPosition = Vector3.zero;
Surfaces[surfaceIndex] = surface;
//distortion
bool useDistortion = Viewer.DisplayController.DisplayConfig.DoesViewerEyeSurfaceWantDistortion(Viewer.ViewerIndex, (byte)_eyeIndex, surfaceIndex);
if(useDistortion)
{
//@todo figure out which type of distortion to use
//right now, there is only one option, SurfaceRadialDistortion
//get distortion parameters
OSVR.ClientKit.RadialDistortionParameters distortionParameters =
Viewer.DisplayController.DisplayConfig.GetViewerEyeSurfaceRadialDistortion(
Viewer.ViewerIndex, (byte)_eyeIndex, surfaceIndex);
surface.SetDistortion(distortionParameters);
}
//render manager
if(Viewer.DisplayController.UseRenderManager)
{
//Set the surfaces viewport from RenderManager
surface.SetViewport(Viewer.DisplayController.RenderManager.GetEyeViewport((int)EyeIndex));
//create a RenderTexture for this eye's camera to render into
RenderTexture renderTexture = new RenderTexture(surface.Viewport.Width, surface.Viewport.Height, 24, RenderTextureFormat.Default);
if (QualitySettings.antiAliasing > 0)
{
renderTexture.antiAliasing = QualitySettings.antiAliasing;
}
surface.SetRenderTexture(renderTexture);
}
}
}
//helper method that copies camera properties from one camera to another
//copies from srcCamera to destCamera
private void CopyCamera(Camera srcCamera, Camera destCamera)
{
//Copy the camera properties.
destCamera.CopyFrom(srcCamera);
destCamera.depth = 0;
//@todo Copy other components attached to the DisplayController?
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="_ConnectionGroup.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Net {
using System.Collections;
using System.Threading;
//
// ConnectionGroup groups a list of connections within the ServerPoint context,
// this used to keep context for things such as proxies or seperate clients.
//
internal class ConnectionGroup {
//
// Members
//
private const int DefaultConnectionListSize = 3;
private ServicePoint m_ServicePoint;
private string m_Name;
private int m_ConnectionLimit;
private ArrayList m_ConnectionList;
private object m_Event;
private Queue m_AuthenticationRequestQueue;
internal bool m_AuthenticationGroup;
private HttpAbortDelegate m_AbortDelegate;
private bool m_NtlmNegGroup;
private int m_IISVersion = -1;
private int m_ActiveConnections;
private TimerThread.Timer m_ExpiringTimer;
//
// Constructors
//
internal ConnectionGroup(ServicePoint servicePoint, string connName) {
m_ServicePoint = servicePoint;
m_ConnectionLimit = servicePoint.ConnectionLimit;
m_ConnectionList = new ArrayList(DefaultConnectionListSize); //it may grow beyond
m_Name = MakeQueryStr(connName);
m_AbortDelegate = new HttpAbortDelegate(Abort);
GlobalLog.Print("ConnectionGroup::.ctor m_ConnectionLimit:" + m_ConnectionLimit.ToString());
// Don't start the idle timer. This group is technically idle, but it will be put to use
// immediately and has nothing to clean up right now.
}
internal string Name
{
get { return m_Name; }
}
//
// Accessors
//
internal ServicePoint ServicePoint {
get {
return m_ServicePoint;
}
}
internal int CurrentConnections {
get {
return m_ConnectionList.Count;
}
}
internal int ConnectionLimit {
get {
return m_ConnectionLimit;
}
set {
m_ConnectionLimit = value;
PruneExcesiveConnections();
GlobalLog.Print("ConnectionGroup::ConnectionLimit.set m_ConnectionLimit:" + m_ConnectionLimit.ToString());
}
}
private ManualResetEvent AsyncWaitHandle {
get {
if (m_Event == null) {
//
// lazy allocation of the event:
// if this property is never accessed this object is never created
//
Interlocked.CompareExchange(ref m_Event, new ManualResetEvent(false), null);
}
ManualResetEvent castedEvent = (ManualResetEvent)m_Event;
return castedEvent;
}
}
private Queue AuthenticationRequestQueue {
get {
if (m_AuthenticationRequestQueue == null) {
lock (m_ConnectionList) {
if (m_AuthenticationRequestQueue == null) {
m_AuthenticationRequestQueue = new Queue();
}
}
}
return m_AuthenticationRequestQueue;
}
set {
m_AuthenticationRequestQueue = value;
}
}
//
// Methods
//
internal static string MakeQueryStr(string connName) {
return ((connName == null) ? "" : connName);
}
/// <devdoc>
/// <para>
/// These methods are made available to the underlying Connection
/// object so that we don't leak them because we're keeping a local
/// reference in our m_ConnectionList.
/// Called by the Connection's constructor
/// </para>
/// </devdoc>
internal void Associate(Connection connection) {
lock (m_ConnectionList) {
m_ConnectionList.Add(connection);
}
GlobalLog.Print("ConnectionGroup::Associate() Connection:" + connection.GetHashCode());
}
/// <devdoc>
/// <para>
/// Used by the Connection's explicit finalizer (note this is
/// not a destructor, since that's never calld unless we
/// remove reference to the object from our internal list)
/// </para>
/// </devdoc>
internal void Disassociate(Connection connection) {
lock (m_ConnectionList) {
m_ConnectionList.Remove(connection);
}
}
/// <devdoc>
/// <para>
/// Called when a connection is idle and ready to process new requests
/// </para>
/// </devdoc>
internal void ConnectionGoneIdle() {
if (m_AuthenticationGroup) {
lock (m_ConnectionList) {
GlobalLog.Print("ConnectionGroup::ConnectionGoneIdle() setting the event");
AsyncWaitHandle.Set();
}
}
}
internal void IncrementConnection() {
// we need these to be atomic operations
lock (m_ConnectionList) {
m_ActiveConnections++;
if (m_ActiveConnections == 1) {
CancelIdleTimer();
}
}
}
internal void DecrementConnection() {
// we need these to be atomic operations
lock (m_ConnectionList) {
m_ActiveConnections--;
if (m_ActiveConnections == 0) {
Diagnostics.Debug.Assert(m_ExpiringTimer == null, "Timer not cleared");
m_ExpiringTimer = ServicePoint.CreateConnectionGroupTimer(this);
}
else if (m_ActiveConnections < 0) {
m_ActiveConnections = 0;
Diagnostics.Debug.Assert(false, "ConnectionGroup; Too many decrements.");
}
}
}
internal void CancelIdleTimer() {
lock (m_ConnectionList) {
TimerThread.Timer timer = m_ExpiringTimer;
m_ExpiringTimer = null;
if (timer != null)
{
timer.Cancel();
}
}
}
/// <devdoc>
/// <para>
/// Causes an abort of any aborted requests waiting in the ConnectionGroup
/// </para>
/// </devdoc>
private bool Abort(HttpWebRequest request, WebException webException)
{
lock (m_ConnectionList)
{
AsyncWaitHandle.Set();
}
return true;
}
/// <devdoc>
/// <para>
/// Removes aborted requests from our queue.
/// </para>
/// </devdoc>
private void PruneAbortedRequests() {
lock (m_ConnectionList) {
Queue updatedQueue = new Queue();
foreach(HttpWebRequest request in AuthenticationRequestQueue) {
if (!request.Aborted) {
updatedQueue.Enqueue(request);
}
}
AuthenticationRequestQueue = updatedQueue;
}
}
/// <devdoc>
/// <para>
/// Removes extra connections that are found when reducing the connection limit
/// </para>
/// </devdoc>
private void PruneExcesiveConnections() {
ArrayList connectionsToClose = new ArrayList();
lock(m_ConnectionList) {
int connectionLimit = ConnectionLimit;
if (CurrentConnections > connectionLimit) {
int numberToPrune = CurrentConnections - connectionLimit;
for (int i=0; i<numberToPrune; i++) {
connectionsToClose.Add(m_ConnectionList[i]);
}
m_ConnectionList.RemoveRange(0, numberToPrune);
}
}
foreach (Connection currentConnection in connectionsToClose) {
currentConnection.CloseOnIdle();
}
}
/// <devdoc>
/// <para>
/// Forces all connections on the ConnectionGroup to not be KeepAlive.
/// </para>
/// </devdoc>
internal void DisableKeepAliveOnConnections() {
// The timer thread is allowed to call this. (It doesn't call user code and doesn't block.)
GlobalLog.ThreadContract(ThreadKinds.Unknown, ThreadKinds.SafeSources | ThreadKinds.Timer, "ConnectionGroup#" + ValidationHelper.HashString(this) + "::DisableKeepAliveOnConnections");
ArrayList connectionsToClose = new ArrayList();
lock (m_ConnectionList) {
GlobalLog.Print("ConnectionGroup#" + ValidationHelper.HashString(this) + "::DisableKeepAliveOnConnections() Name = " + m_Name + ", Count:" + m_ConnectionList.Count);
foreach (Connection currentConnection in m_ConnectionList) {
//
// For each Connection set KeepAlive to false
//
GlobalLog.Print("ConnectionGroup#" + ValidationHelper.HashString(this) + "::DisableKeepAliveOnConnections() setting KeepAlive to false Connection#" + ValidationHelper.HashString(currentConnection));
connectionsToClose.Add(currentConnection);
}
m_ConnectionList.Clear();
}
foreach (Connection currentConnection in connectionsToClose) {
currentConnection.CloseOnIdle();
}
}
/// <devdoc>
/// <para>
/// Attempts to match a request with a connection, if a connection is unassigned ie not locked with
/// a request, then the least busy connections is returned in "leastbusyConnection." If the
/// connection limit allows, and all connections are busy, a new one is allocated and returned.
///
/// RETURNS: a Connection shown to match a previously locked Request/Connection (OTHERWISE)
/// leasebusyConnection - will contain a newly allocated Connection or least Busy one
/// suiteable for requests.
///
/// NOTE: For Whidbey: try to integrate this code into FindConnection()
/// </para>
/// </devdoc>
private Connection FindMatchingConnection(HttpWebRequest request, string connName, out Connection leastbusyConnection) {
int minBusyCount = Int32.MaxValue;
bool freeConnectionsAvail = false;
leastbusyConnection = null;
lock (m_ConnectionList) {
//
// go through the list of open connections to this service point and pick the first free one or,
// if none is free, pick the least busy one. Skip all connections with non keep-alive request pipelined.
//
minBusyCount = Int32.MaxValue;
foreach (Connection currentConnection in m_ConnectionList) {
GlobalLog.Print("ConnectionGroup::FindMatchingConnection currentConnection.BusyCount:" + currentConnection.BusyCount.ToString());
if (currentConnection.LockedRequest == request) {
leastbusyConnection = currentConnection;
return currentConnection;
}
GlobalLog.Print("ConnectionGroup::FindMatchingConnection: lockedRequest# " + ((currentConnection.LockedRequest == null) ? "null" : currentConnection.LockedRequest.GetHashCode().ToString()));
if (!currentConnection.NonKeepAliveRequestPipelined && currentConnection.BusyCount < minBusyCount && currentConnection.LockedRequest == null) {
leastbusyConnection = currentConnection;
minBusyCount = currentConnection.BusyCount;
if (minBusyCount == 0) {
freeConnectionsAvail = true;
}
}
}
//
// If there is NOT a Connection free, then we allocate a new Connection
//
if (!freeConnectionsAvail && CurrentConnections < ConnectionLimit) {
//
// If we can create a new connection, then do it,
// this may have complications in pipeling because
// we may wish to optimize this case by actually
// using existing connections, rather than creating new ones
//
// Note: this implicately results in a this.Associate being called.
//
GlobalLog.Print("ConnectionGroup::FindMatchingConnection [returning new Connection] CurrentConnections:" + CurrentConnections.ToString() + " ConnectionLimit:" + ConnectionLimit.ToString());
leastbusyConnection = new Connection(this);
}
}
return null; // only if we have a locked Connection that matches can return non-null
}
/// <devdoc>
/// <para>
/// Used by the ServicePoint to find a free or new Connection
/// for use in making Requests, this is done with the cavet,
/// that once a Connection is "locked" it can only be used
/// by a specific request.
///
/// NOTE: For Whidbey: try to integrate this code into FindConnection()
/// </para>
/// </devdoc>
private Connection FindConnectionAuthenticationGroup(HttpWebRequest request, string connName) {
Connection leastBusyConnection = null;
GlobalLog.Print("ConnectionGroup::FindConnectionAuthenticationGroup [" + connName + "] for request#" + request.GetHashCode() +", m_ConnectionList.Count:" + m_ConnectionList.Count.ToString());
//
// First try and find a free Connection (i.e. one not busy with Authentication handshake)
// or try to find a Request that has already locked a specific Connection,
// if a matching Connection is found, then we're done
//
lock (m_ConnectionList) {
Connection matchingConnection;
matchingConnection = FindMatchingConnection(request, connName, out leastBusyConnection);
if (matchingConnection != null) {
matchingConnection.MarkAsReserved();
return matchingConnection;
}
if (AuthenticationRequestQueue.Count == 0) {
if (leastBusyConnection != null) {
if (request.LockConnection) {
m_NtlmNegGroup = true;
m_IISVersion = leastBusyConnection.IISVersion;
}
if(request.LockConnection || (m_NtlmNegGroup && !request.Pipelined && request.UnsafeOrProxyAuthenticatedConnectionSharing && m_IISVersion >= 6)){
GlobalLog.Print("Assigning New Locked Request#" + request.GetHashCode().ToString());
leastBusyConnection.LockedRequest = request;
}
leastBusyConnection.MarkAsReserved();
return leastBusyConnection;
}
}
else if (leastBusyConnection != null) {
AsyncWaitHandle.Set();
}
AuthenticationRequestQueue.Enqueue(request);
}
//
// If all the Connections are busy, then we queue ourselves and need to wait. As soon as
// one of the Connections are free, we grab the lock, and see if we find ourselves
// at the head of the queue. If not, we loop backaround.
// Care is taken to examine the request when we wakeup, in case the request is aborted.
//
while (true) {
GlobalLog.Print("waiting");
request.AbortDelegate = m_AbortDelegate;
if (!request.Aborted)
AsyncWaitHandle.WaitOne();
GlobalLog.Print("wait up");
lock(m_ConnectionList) {
if (request.Aborted)
{
PruneAbortedRequests();
// Note that request is not on any connection and it will not be submitted
return null;
}
FindMatchingConnection(request, connName, out leastBusyConnection);
if (AuthenticationRequestQueue.Peek() == request) {
GlobalLog.Print("dequeue");
AuthenticationRequestQueue.Dequeue();
if (leastBusyConnection != null) {
if (request.LockConnection) {
m_NtlmNegGroup = true;
m_IISVersion = leastBusyConnection.IISVersion;
}
if(request.LockConnection || (m_NtlmNegGroup && !request.Pipelined && request.UnsafeOrProxyAuthenticatedConnectionSharing && m_IISVersion >= 6)){
leastBusyConnection.LockedRequest = request;
}
leastBusyConnection.MarkAsReserved();
return leastBusyConnection;
}
AuthenticationRequestQueue.Enqueue(request);
}
if (leastBusyConnection == null) {
AsyncWaitHandle.Reset();
}
}
}
}
/// <devdoc>
/// <para>
/// Used by the ServicePoint to find a free or new Connection
/// for use in making Requests. Under NTLM and Negotiate requests,
/// this function depricates itself and switches the object over to
/// using a new code path (see FindConnectionAuthenticationGroup).
/// </para>
/// </devdoc>
internal Connection FindConnection(HttpWebRequest request, string connName, out bool forcedsubmit) {
Connection leastbusyConnection = null;
Connection newConnection = null;
bool freeConnectionsAvail = false;
forcedsubmit = false;
if (m_AuthenticationGroup || request.LockConnection) {
m_AuthenticationGroup = true;
return FindConnectionAuthenticationGroup(request, connName);
}
GlobalLog.Print("ConnectionGroup::FindConnection [" + connName + "] m_ConnectionList.Count:" + m_ConnectionList.Count.ToString());
lock (m_ConnectionList) {
//
// go through the list of open connections to this service point and pick the connection as follows:
// - free connection
// - if there is no free connection and if we are under connection limit, create new connection
// - pick the least busy connection which does not have non-keep alive request pipelined
// - pick the least busy connection which may have non-keep alive request pipelined
// If we pick the connection with non keep-alive request pipelined on it, we set forcedsubmit to true.
// This will make sure that we don't start the request immediately and it gets queued on the connection.
//
int minBusyCount = Int32.MaxValue;
bool foundLiveConnection = false;
foreach (Connection currentConnection in m_ConnectionList) {
GlobalLog.Print("ConnectionGroup::FindConnection currentConnection.BusyCount:" + currentConnection.BusyCount.ToString());
bool useThisConnection = false;
if (foundLiveConnection) {
useThisConnection = (!currentConnection.NonKeepAliveRequestPipelined && minBusyCount > currentConnection.BusyCount);
} else {
useThisConnection = (!currentConnection.NonKeepAliveRequestPipelined || minBusyCount > currentConnection.BusyCount);
}
if (useThisConnection) {
leastbusyConnection = currentConnection;
minBusyCount = currentConnection.BusyCount;
if (!foundLiveConnection) {
foundLiveConnection = !currentConnection.NonKeepAliveRequestPipelined;
} else {
GlobalLog.Assert(!currentConnection.NonKeepAliveRequestPipelined, "Connection.NonKeepAliveRequestPipelined == false|Non keep-alive request has been pipelined on this connection.");
}
if (foundLiveConnection && minBusyCount == 0) {
freeConnectionsAvail = true;
break;
}
}
}
//
// If there is NOT a Connection free, then we allocate a new Connection
//
if (!freeConnectionsAvail && CurrentConnections < ConnectionLimit) {
//
// If we can create a new connection, then do it,
// this may have complications in pipeling because
// we may wish to optimize this case by actually
// using existing connections, rather than creating new ones
//
// Note: this implicately results in a this.Associate being called.
//
GlobalLog.Print("ConnectionGroup::FindConnection [returning new Connection] freeConnectionsAvail:" + freeConnectionsAvail.ToString() + " CurrentConnections:" + CurrentConnections.ToString() + " ConnectionLimit:" + ConnectionLimit.ToString());
newConnection = new Connection(this);
forcedsubmit = false;
}
else {
//
// All connections are busy, use the least busy one
//
GlobalLog.Print("ConnectionGroup::FindConnection [returning leastbusyConnection] freeConnectionsAvail:" + freeConnectionsAvail.ToString() + " CurrentConnections:" + CurrentConnections.ToString() + " ConnectionLimit:" + ConnectionLimit.ToString());
GlobalLog.Assert(leastbusyConnection != null, "Connect.leastbusyConnection != null|All connections have BusyCount equal to Int32.MaxValue.");
newConnection = leastbusyConnection;
forcedsubmit = !foundLiveConnection;
}
newConnection.MarkAsReserved();
}
return newConnection;
}
[System.Diagnostics.Conditional("DEBUG")]
internal void DebugMembers(int requestHash) {
foreach(Connection connection in m_ConnectionList) {
connection.DebugMembers(requestHash);
}
}
}
}
| |
using Tibia.Addresses;
namespace Tibia
{
public partial class Version
{
public static void SetVersion852()
{
BattleList.Start = 0x633EF0;
BattleList.End = 0x633EF0 + 0xA0 * 250;
BattleList.StepCreatures = 0xA0;
BattleList.MaxCreatures = 250;
Client.StartTime = 0x7923C0;
Client.XTeaKey = 0x78CEF4;
Client.SocketStruct = 0x78CEC8;
Client.RecvPointer = 0x5B15DC;
Client.SendPointer = 0x5B1608;
Client.FrameRatePointer = 0x7910A4;
Client.FrameRateCurrentOffset = 0x60;
Client.FrameRateLimitOffset = 0x58;
Client.MultiClient = 0x5067E4;
Client.Status = 0x790558;
Client.SafeMode = 0x78D31C;
Client.FollowMode = Client.SafeMode + 4;
Client.AttackMode = Client.FollowMode + 4;
Client.ActionState = 0x7905B8;
Client.LastMSGText = 0x792630;
Client.LastMSGAuthor = Client.LastMSGText - 0x28;
Client.StatusbarText = 0x7923E0;
Client.StatusbarTime = Client.StatusbarText - 4;
Client.ClickId = 0x7905F8;
Client.ClickCount = Client.ClickId + 4;
Client.ClickZ = Client.ClickId - 0x68;
Client.SeeId = Client.ClickId + 12;
Client.SeeCount = Client.SeeId + 4;
Client.SeeZ = Client.SeeId - 0x68;
Client.ClickContextMenuItemId = 0x790604;
Client.ClickContextMenuItemGroundId = 0x790608;
Client.ClickContextMenuCreatureId = 0x790600;
Client.SeeText = 0;
Client.LoginServerStart = 0x787E30;
Client.StepLoginServer = 112;
Client.DistancePort = 100;
Client.MaxLoginServers = 10;
Client.RSA = 0x5B0610;
Client.LoginCharList = 0x79050C;
Client.LoginCharListLength = 0x790510;
Client.LoginSelectedChar = 0x790508;
Client.GameWindowRectPointer = 0x63F894;
Client.GameWindowBar = 0x7923D4;
Client.DatPointer = 0x78CF14;
Client.EventTriggerPointer = 0x5197D0;
Client.DialogPointer = 0x642BFC;
Client.DialogLeft = 0x14;
Client.DialogTop = 0x18;
Client.DialogWidth = 0x1C;
Client.DialogHeight = 0x20;
Client.DialogCaption = 0x50;
Client.LastRcvPacket = 0x7886A8;
Client.DecryptCall = 0x45B8E5;
Client.LoginAccountNum = 0;
Client.LoginPassword = 0x790514;
Client.LoginAccount = Client.LoginPassword + 32;
Client.LoginPatch = 0;
Client.LoginPatch2 = 0;
Client.LoginPatchOrig = new byte[] { 0xE8, 0x0D, 0x1D, 0x09, 0x00 };
Client.LoginPatchOrig2 = new byte[] { 0xE8, 0xC8, 0x15, 0x09, 0x00 };
Client.ParserFunc = 0x45B8B0;
Client.GetNextPacketCall = 0x45B8E5;
Client.RecvStream = 0x78CEE4;
Container.Start = 0x640348;
Container.StepContainer = 492;
Container.StepSlot = 12;
Container.MaxContainers = 16;
Container.MaxStack = 100;
Container.DistanceIsOpen = 0;
Container.DistanceId = 4;
Container.DistanceName = 16;
Container.DistanceVolume = 48;
Container.DistanceAmount = 56;
Container.DistanceItemId = 60;
Container.DistanceItemCount = 64;
Container.End = Container.Start + (Container.MaxContainers * Container.StepContainer);
ContextMenus.AddContextMenuPtr = 0x4518D0;
ContextMenus.OnClickContextMenuPtr = 0x44E070;
ContextMenus.OnClickContextMenuVf = 0x5B67D8;
ContextMenus.AddSetOutfitContextMenu = 0x452802;
ContextMenus.AddPartyActionContextMenu = 0x452853;
ContextMenus.AddCopyNameContextMenu = 0x45286A;
ContextMenus.AddTradeWithContextMenu = 0x452479;
ContextMenus.AddLookContextMenu = 0x45232F;
Creature.DistanceId = 0;
Creature.DistanceType = 3;
Creature.DistanceName = 4;
Creature.DistanceX = 36;
Creature.DistanceY = 40;
Creature.DistanceZ = 44;
Creature.DistanceScreenOffsetHoriz = 48;
Creature.DistanceScreenOffsetVert = 52;
Creature.DistanceIsWalking = 76;
Creature.DistanceWalkSpeed = 140;
Creature.DistanceDirection = 80;
Creature.DistanceIsVisible = 144;
Creature.DistanceBlackSquare = 132;
Creature.DistanceLight = 120;
Creature.DistanceLightColor = 124;
Creature.DistanceHPBar = 136;
Creature.DistanceSkull = 148;
Creature.DistanceParty = 152;
Creature.DistanceOutfit = 96;
Creature.DistanceColorHead = 100;
Creature.DistanceColorBody = 104;
Creature.DistanceColorLegs = 108;
Creature.DistanceColorFeet = 112;
Creature.DistanceAddon = 116;
DatItem.StepItems = 0x50;
DatItem.Width = 0;
DatItem.Height = 4;
DatItem.MaxSizeInPixels = 8;
DatItem.Layers = 12;
DatItem.PatternX = 16;
DatItem.PatternY = 20;
DatItem.PatternDepth = 24;
DatItem.Phase = 28;
DatItem.Sprite = 32;
DatItem.Flags = 36;
DatItem.CanLookAt = 40;
DatItem.WalkSpeed = 44;
DatItem.TextLimit = 48;
DatItem.LightRadius = 52;
DatItem.LightColor = 56;
DatItem.ShiftX = 60;
DatItem.ShiftY = 64;
DatItem.WalkHeight = 68;
DatItem.Automap = 72;
DatItem.LensHelp = 76;
DrawItem.DrawItemFunc = 0x4B0C50;
DrawSkin.DrawSkinFunc = 0x4B48E0;
Hotkey.SendAutomaticallyStart = 0x78D518;
Hotkey.SendAutomaticallyStep = 0x01;
Hotkey.TextStart = 0x78D540;
Hotkey.TextStep = 0x100;
Hotkey.ObjectStart = 0x78D48C;
Hotkey.ObjectStep = 0x04;
Hotkey.ObjectUseTypeStart = 0x78D36C;
Hotkey.ObjectUseTypeStep = 0x04;
Hotkey.MaxHotkeys = 36;
Map.MapPointer = 0x647750;
Map.StepTile = 168;
Map.StepTileObject = 12;
Map.DistanceTileObjectCount = 0;
Map.DistanceTileObjects = 4;
Map.DistanceObjectId = 0;
Map.DistanceObjectData = 4;
Map.DistanceObjectDataEx = 8;
Map.MaxTileObjects = 10;
Map.MaxX = 18;
Map.MaxY = 14;
Map.MaxZ = 8;
Map.MaxTiles = 2016;
Map.ZAxisDefault = 7;
Map.NameSpy1 = 0x4ED2C9;
Map.NameSpy2 = 0x4ED2D3;
Map.NameSpy1Default = 19061;
Map.NameSpy2Default = 16501;
Map.LevelSpy1 = 0x4EF17A;
Map.LevelSpy2 = 0x4EF27F;
Map.LevelSpy3 = 0x4EF300;
Map.LevelSpyPtr = 0x63F894;
Map.LevelSpyAdd1 = 28;
Map.LevelSpyAdd2 = 0x2A88;
Map.LevelSpyDefault = new byte[] { 0x89, 0x86, 0x88, 0x2A, 0x00, 0x00 };
Map.RevealInvisible1 = 0x45F7A3;
Map.RevealInvisible2 = 0x4EC595;
Map.FullLightNop = 0x4E5A59;
Map.FullLightAdr = 0x4E5A5C;
Map.FullLightNopDefault = new byte[] { 0x7E, 0x05 };
Map.FullLightNopEdited = new byte[] { 0x90, 0x90 };
Map.FullLightAdrDefault = 0x80;
Map.FullLightAdrEdited = 0xFF;
Player.Experience = 0x633E84;
Player.Flags = Player.Experience - 108;
Player.Id = Player.Experience + 12;
Player.Health = Player.Experience + 8;
Player.HealthMax = Player.Experience + 4;
Player.Level = Player.Experience - 4;
Player.MagicLevel = Player.Experience - 8;
Player.LevelPercent = Player.Experience - 12;
Player.MagicLevelPercent = Player.Experience - 16;
Player.Mana = Player.Experience - 20;
Player.ManaMax = Player.Experience - 24;
Player.Soul = Player.Experience - 28;
Player.Stamina = Player.Experience - 32;
Player.Capacity = Player.Experience - 36;
Player.FistPercent = 0x633E1C;
Player.ClubPercent = Player.FistPercent + 4;
Player.SwordPercent = Player.FistPercent + 8;
Player.AxePercent = Player.FistPercent + 12;
Player.DistancePercent = Player.FistPercent + 16;
Player.ShieldingPercent = Player.FistPercent + 20;
Player.FishingPercent = Player.FistPercent + 24;
Player.Fist = Player.FistPercent + 28;
Player.Club = Player.FistPercent + 32;
Player.Sword = Player.FistPercent + 36;
Player.Axe = Player.FistPercent + 40;
Player.Distance = Player.FistPercent + 44;
Player.Shielding = Player.FistPercent + 48;
Player.Fishing = Player.FistPercent + 52;
Player.SlotHead = 0x6402D0;
Player.SlotNeck = Player.SlotHead + 12;
Player.SlotBackpack = Player.SlotHead + 24;
Player.SlotArmor = Player.SlotHead + 36;
Player.SlotRight = Player.SlotHead + 48;
Player.SlotLeft = Player.SlotHead + 60;
Player.SlotLegs = Player.SlotHead + 72;
Player.SlotFeet = Player.SlotHead + 84;
Player.SlotRing = Player.SlotHead + 96;
Player.SlotAmmo = Player.SlotHead + 108;
Player.MaxSlots = 10;
Player.DistanceSlotCount = 4;
Player.CurrentTileToGo = 0x633E98;
Player.TilesToGo = 0x633E9C;
Player.GoToX = Player.Experience + 80;
Player.GoToY = Player.GoToX - 4;
Player.GoToZ = Player.GoToX - 8;
Player.RedSquare = 0x633E5C;
Player.GreenSquare = Player.RedSquare - 4;
Player.WhiteSquare = Player.GreenSquare - 8;
Player.AccessN = 0;
Player.AccessS = 0;
Player.TargetId = Player.RedSquare;
Player.TargetBattlelistId = Player.TargetId - 8;
Player.TargetBattlelistType = Player.TargetId - 5;
Player.TargetType = Player.TargetId + 3;
Player.Z = 0x642C38;
TextDisplay.PrintName = 0x4F02B1;
TextDisplay.PrintFPS = 0x4597C8;
TextDisplay.ShowFPS = 0x630B34;
TextDisplay.PrintTextFunc = 0x4B0090;
TextDisplay.NopFPS = 0x459704;
Vip.Start = 0x631BB0;
Vip.StepPlayers = 0x2C;
Vip.MaxPlayers = 200;
Vip.DistanceId = 0;
Vip.DistanceName = 4;
Vip.DistanceStatus = 34;
Vip.DistanceIcon = 40;
Vip.End = Vip.Start + (Vip.StepPlayers * Vip.MaxPlayers);
}
}
}
| |
// 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 Internal.Cryptography;
using Internal.NativeCrypto;
using System.IO;
namespace System.Security.Cryptography
{
public sealed partial class RSACryptoServiceProvider : RSA, ICspAsymmetricAlgorithm
{
private const int DefaultKeySize = 1024;
private readonly RSA _impl;
private bool _publicOnly;
public RSACryptoServiceProvider()
: this(DefaultKeySize) { }
public RSACryptoServiceProvider(int dwKeySize)
{
if (dwKeySize < 0)
throw new ArgumentOutOfRangeException(nameof(dwKeySize), SR.ArgumentOutOfRange_NeedNonNegNum);
// This class wraps RSA
_impl = RSA.Create(dwKeySize);
}
public RSACryptoServiceProvider(int dwKeySize, CspParameters parameters) =>
throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CAPI_Required, nameof(CspParameters)));
public RSACryptoServiceProvider(CspParameters parameters) =>
throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CAPI_Required, nameof(CspParameters)));
public CspKeyContainerInfo CspKeyContainerInfo =>
throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CAPI_Required, nameof(CspKeyContainerInfo)));
public byte[] Decrypt(byte[] rgb, bool fOAEP)
{
if (rgb == null)
throw new ArgumentNullException(nameof(rgb));
// size check -- must be exactly the modulus size
if (rgb.Length != (KeySize / 8))
throw new CryptographicException(SR.Cryptography_RSA_DecryptWrongSize);
return _impl.Decrypt(rgb, fOAEP ? RSAEncryptionPadding.OaepSHA1 : RSAEncryptionPadding.Pkcs1);
}
public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (padding == null)
throw new ArgumentNullException(nameof(padding));
return
padding == RSAEncryptionPadding.Pkcs1 ? Decrypt(data, fOAEP: false) :
padding == RSAEncryptionPadding.OaepSHA1 ? Decrypt(data, fOAEP: true) : // For compat, this prevents OaepSHA2 options as fOAEP==true will cause Decrypt to use OaepSHA1
throw PaddingModeNotSupported();
}
public override bool TryDecrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding, out int bytesWritten)
{
if (padding == null)
throw new ArgumentNullException(nameof(padding));
if (data.Length != (KeySize / 8))
throw new CryptographicException(SR.Cryptography_RSA_DecryptWrongSize);
if (padding != RSAEncryptionPadding.Pkcs1 && padding != RSAEncryptionPadding.OaepSHA1)
throw PaddingModeNotSupported();
return _impl.TryDecrypt(data, destination, padding, out bytesWritten);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_impl.Dispose();
base.Dispose(disposing);
}
}
public byte[] Encrypt(byte[] rgb, bool fOAEP)
{
if (rgb == null)
throw new ArgumentNullException(nameof(rgb));
return _impl.Encrypt(rgb, fOAEP ? RSAEncryptionPadding.OaepSHA1 : RSAEncryptionPadding.Pkcs1);
}
public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding)
{
if (data == null)
throw new ArgumentNullException(nameof(data));
if (padding == null)
throw new ArgumentNullException(nameof(padding));
return
padding == RSAEncryptionPadding.Pkcs1 ? Encrypt(data, fOAEP: false) :
padding == RSAEncryptionPadding.OaepSHA1 ? Encrypt(data, fOAEP: true) : // For compat, this prevents OaepSHA2 options as fOAEP==true will cause Decrypt to use OaepSHA1
throw PaddingModeNotSupported();
}
public override bool TryEncrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding, out int bytesWritten)
{
if (padding == null)
throw new ArgumentNullException(nameof(padding));
if (padding != RSAEncryptionPadding.Pkcs1 && padding != RSAEncryptionPadding.OaepSHA1)
throw PaddingModeNotSupported();
return _impl.TryEncrypt(data, destination, padding, out bytesWritten);
}
public byte[] ExportCspBlob(bool includePrivateParameters)
{
RSAParameters parameters = ExportParameters(includePrivateParameters);
return parameters.ToKeyBlob();
}
public override RSAParameters ExportParameters(bool includePrivateParameters) =>
_impl.ExportParameters(includePrivateParameters);
protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) =>
AsymmetricAlgorithmHelpers.HashData(data, offset, count, hashAlgorithm);
protected override bool TryHashData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) =>
AsymmetricAlgorithmHelpers.TryHashData(data, destination, hashAlgorithm, out bytesWritten);
protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) =>
AsymmetricAlgorithmHelpers.HashData(data, hashAlgorithm);
public override void FromXmlString(string xmlString) => _impl.FromXmlString(xmlString);
public void ImportCspBlob(byte[] keyBlob)
{
RSAParameters parameters = CapiHelper.ToRSAParameters(keyBlob, !IsPublic(keyBlob));
ImportParameters(parameters);
}
public override void ImportParameters(RSAParameters parameters)
{
// Although _impl supports larger Exponent, limit here for compat.
if (parameters.Exponent == null || parameters.Exponent.Length > 4)
throw new CryptographicException(SR.Argument_InvalidValue);
_impl.ImportParameters(parameters);
// P was verified in ImportParameters
_publicOnly = (parameters.P == null || parameters.P.Length == 0);
}
public override void ImportEncryptedPkcs8PrivateKey(
ReadOnlySpan<byte> passwordBytes,
ReadOnlySpan<byte> source,
out int bytesRead)
{
_impl.ImportEncryptedPkcs8PrivateKey(passwordBytes, source, out bytesRead);
}
public override void ImportEncryptedPkcs8PrivateKey(
ReadOnlySpan<char> password,
ReadOnlySpan<byte> source,
out int bytesRead)
{
_impl.ImportEncryptedPkcs8PrivateKey(password, source, out bytesRead);
}
public override string KeyExchangeAlgorithm => _impl.KeyExchangeAlgorithm;
public override int KeySize
{
get { return _impl.KeySize; }
set { _impl.KeySize = value; }
}
// RSAOpenSsl is (512, 16384, 8), RSASecurityTransforms is (1024, 16384, 8)
// Either way the minimum is lifted off of CAPI's 384, due to platform constraints.
public override KeySizes[] LegalKeySizes => _impl.LegalKeySizes;
// PersistKeyInCsp has no effect in Unix
public bool PersistKeyInCsp { get; set; }
public bool PublicOnly => _publicOnly;
public override string SignatureAlgorithm => "http://www.w3.org/2000/09/xmldsig#rsa-sha1";
public override byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) =>
padding == null ? throw new ArgumentNullException(nameof(padding)) :
padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() :
_impl.SignData(data, hashAlgorithm, padding);
public override byte[] SignData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) =>
padding == null ? throw new ArgumentNullException(nameof(padding)) :
padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() :
_impl.SignData(data, offset, count, hashAlgorithm, padding);
public override bool TrySignData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten) =>
padding == null ? throw new ArgumentNullException(nameof(padding)) :
padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() :
_impl.TrySignData(data, destination, hashAlgorithm, padding, out bytesWritten);
public byte[] SignData(byte[] buffer, int offset, int count, object halg) =>
_impl.SignData(buffer, offset, count, HashAlgorithmNames.ObjToHashAlgorithmName(halg), RSASignaturePadding.Pkcs1);
public byte[] SignData(byte[] buffer, object halg) =>
_impl.SignData(buffer, HashAlgorithmNames.ObjToHashAlgorithmName(halg), RSASignaturePadding.Pkcs1);
public byte[] SignData(Stream inputStream, object halg) =>
_impl.SignData(inputStream, HashAlgorithmNames.ObjToHashAlgorithmName(halg), RSASignaturePadding.Pkcs1);
public override byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) =>
padding == null ? throw new ArgumentNullException(nameof(padding)) :
padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() :
_impl.SignHash(hash, hashAlgorithm, padding);
public override bool TrySignHash(ReadOnlySpan<byte> hash, Span<byte> destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten) =>
padding == null ? throw new ArgumentNullException(nameof(padding)) :
padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() :
_impl.TrySignHash(hash, destination, hashAlgorithm, padding, out bytesWritten);
public byte[] SignHash(byte[] rgbHash, string str)
{
if (rgbHash == null)
throw new ArgumentNullException(nameof(rgbHash));
if (PublicOnly)
throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);
HashAlgorithmName algName = HashAlgorithmNames.NameOrOidToHashAlgorithmName(str);
return _impl.SignHash(rgbHash, algName, RSASignaturePadding.Pkcs1);
}
public override string ToXmlString(bool includePrivateParameters) => _impl.ToXmlString(includePrivateParameters);
public bool VerifyData(byte[] buffer, object halg, byte[] signature) =>
_impl.VerifyData(buffer, signature, HashAlgorithmNames.ObjToHashAlgorithmName(halg), RSASignaturePadding.Pkcs1);
public override bool VerifyData(byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) =>
padding == null ? throw new ArgumentNullException(nameof(padding)) :
padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() :
_impl.VerifyData(data, offset, count, signature, hashAlgorithm, padding);
public override bool VerifyData(ReadOnlySpan<byte> data, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) =>
padding == null ? throw new ArgumentNullException(nameof(padding)) :
padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() :
_impl.VerifyData(data, signature, hashAlgorithm, padding);
public override bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding)
{
if (hash == null)
{
throw new ArgumentNullException(nameof(hash));
}
if (signature == null)
{
throw new ArgumentNullException(nameof(signature));
}
return VerifyHash((ReadOnlySpan<byte>)hash, (ReadOnlySpan<byte>)signature, hashAlgorithm, padding);
}
public override bool VerifyHash(ReadOnlySpan<byte> hash, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) =>
padding == null ? throw new ArgumentNullException(nameof(padding)) :
padding != RSASignaturePadding.Pkcs1 ? throw PaddingModeNotSupported() :
_impl.VerifyHash(hash, signature, hashAlgorithm, padding);
public bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature)
{
if (rgbHash == null)
{
throw new ArgumentNullException(nameof(rgbHash));
}
if (rgbSignature == null)
{
throw new ArgumentNullException(nameof(rgbSignature));
}
return VerifyHash(
(ReadOnlySpan<byte>)rgbHash, (ReadOnlySpan<byte>)rgbSignature,
HashAlgorithmNames.NameOrOidToHashAlgorithmName(str), RSASignaturePadding.Pkcs1);
}
// UseMachineKeyStore has no effect in Unix
public static bool UseMachineKeyStore { get; set; }
private static Exception PaddingModeNotSupported()
{
return new CryptographicException(SR.Cryptography_InvalidPaddingMode);
}
/// <summary>
/// find whether an RSA key blob is public.
/// </summary>
private static bool IsPublic(byte[] keyBlob)
{
if (keyBlob == null)
throw new ArgumentNullException(nameof(keyBlob));
// The CAPI RSA public key representation consists of the following sequence:
// - BLOBHEADER
// - RSAPUBKEY
// The first should be PUBLICKEYBLOB and magic should be RSA_PUB_MAGIC "RSA1"
if (keyBlob[0] != CapiHelper.PUBLICKEYBLOB)
{
return false;
}
if (keyBlob[11] != 0x31 || keyBlob[10] != 0x41 || keyBlob[9] != 0x53 || keyBlob[8] != 0x52)
{
return false;
}
return true;
}
}
}
| |
namespace Volante.Impl
{
using System;
using System.Collections;
using System.Collections.Generic;
using Volante;
public class LinkImpl<T> : ILink<T> where T : class,IPersistent
{
private void Modify()
{
if (owner != null)
owner.Modify();
}
public int Count
{
get
{
return used;
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public void CopyTo(T[] dst, int i)
{
Pin();
Array.Copy(arr, 0, dst, i, used);
}
public virtual int Size()
{
return used;
}
public virtual int Length
{
get
{
return used;
}
set
{
if (value < used)
{
Array.Clear(arr, value, used - value);
Modify();
}
else
{
reserveSpace(value - used);
}
used = value;
}
}
public virtual T this[int i]
{
get
{
return Get(i);
}
set
{
Set(i, value);
}
}
void EnsureValidIndex(int i)
{
if (i < 0 || i >= used)
throw new IndexOutOfRangeException();
}
public virtual T Get(int i)
{
EnsureValidIndex(i);
return loadElem(i);
}
public virtual IPersistent GetRaw(int i)
{
EnsureValidIndex(i);
return arr[i];
}
public virtual void Set(int i, T obj)
{
EnsureValidIndex(i);
arr[i] = obj;
Modify();
}
public bool Remove(T obj)
{
int i = IndexOf(obj);
if (i >= 0)
{
RemoveAt(i);
return true;
}
return false;
}
public virtual void RemoveAt(int i)
{
EnsureValidIndex(i);
used -= 1;
Array.Copy(arr, i + 1, arr, i, used - i);
arr[used] = null;
Modify();
}
internal void reserveSpace(int len)
{
if (used + len > arr.Length)
{
int newLen = used + len > arr.Length * 2 ? used + len : arr.Length * 2;
IPersistent[] newArr = new IPersistent[newLen];
Array.Copy(arr, 0, newArr, 0, used);
arr = newArr;
}
Modify();
}
public virtual void Insert(int i, T obj)
{
EnsureValidIndex(i);
reserveSpace(1);
Array.Copy(arr, i, arr, i + 1, used - i);
arr[i] = obj;
used += 1;
}
public virtual void Add(T obj)
{
reserveSpace(1);
arr[used++] = obj;
}
public virtual void AddAll(T[] a)
{
AddAll(a, 0, a.Length);
}
public virtual void AddAll(T[] a, int from, int length)
{
reserveSpace(length);
Array.Copy(a, from, arr, used, length);
used += length;
}
public virtual void AddAll(ILink<T> link)
{
int n = link.Length;
reserveSpace(n);
for (int i = 0; i < n; i++)
{
arr[used++] = link.GetRaw(i);
}
}
public virtual Array ToRawArray()
{
//TODO: this seems like the right code, but changing it
//breaks a lot of code in Btree (it uses ILink internally
//for its implementation). Maybe they rely on having the
//original array
//T[] arrUsed = new T[used];
//Array.Copy(arr, arrUsed, used);
//return arrUsed;
return arr;
}
public virtual T[] ToArray()
{
T[] a = new T[used];
for (int i = used; --i >= 0; )
{
a[i] = loadElem(i);
}
return a;
}
public virtual bool Contains(T obj)
{
return IndexOf(obj) >= 0;
}
int IndexOfByOid(int oid)
{
for (int i = 0; i < used; i++)
{
IPersistent elem = arr[i];
if (elem != null && elem.Oid == oid)
return i;
}
return -1;
}
int IndexOfByObj(T obj)
{
IPersistent po = (IPersistent)obj;
for (int i = 0; i < used; i++)
{
IPersistent o = arr[i];
if (o == po)
return i;
}
return -1;
}
public virtual int IndexOf(T obj)
{
if (obj == null)
return -1;
int oid = obj.Oid;
int idx;
if (oid != 0)
idx = IndexOfByOid(oid);
else
idx = IndexOfByObj(obj);
return idx;
}
public virtual bool ContainsElement(int i, T obj)
{
EnsureValidIndex(i);
IPersistent elem = arr[i];
T elTyped = elem as T;
if (elTyped == obj)
return true;
if (null == elem)
return false;
return elem.Oid != 0 && elem.Oid == obj.Oid;
}
public virtual void Clear()
{
Array.Clear(arr, 0, used);
used = 0;
Modify();
}
class LinkEnumerator : IEnumerator<T>
{
public void Dispose() { }
public bool HasMore()
{
return i + 1 < link.Length;
}
public bool ReachEnd()
{
return i == link.Length + 1;
}
public bool MoveNext()
{
if (HasMore())
{
i += 1;
return true;
}
i = link.Length + 1;
return false;
}
public T Current
{
get
{
if (ReachEnd())
throw new InvalidOperationException();
return link[i];
}
}
object IEnumerator.Current
{
get
{
return Current;
}
}
public void Reset()
{
i = -1;
}
internal LinkEnumerator(ILink<T> link)
{
this.link = link;
i = -1;
}
private int i;
private ILink<T> link;
}
public IEnumerator<T> GetEnumerator()
{
return new LinkEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new LinkEnumerator(this);
}
public void Pin()
{
for (int i = 0, n = used; i < n; i++)
{
arr[i] = loadElem(i);
}
}
public void Unpin()
{
for (int i = 0, n = used; i < n; i++)
{
IPersistent elem = arr[i];
if (elem != null && !elem.IsRaw() && elem.IsPersistent())
arr[i] = new PersistentStub(elem.Database, elem.Oid);
}
}
private T loadElem(int i)
{
IPersistent elem = arr[i];
if (elem != null && elem.IsRaw())
elem = ((DatabaseImpl)elem.Database).lookupObject(elem.Oid, null);
return (T)elem;
}
public void SetOwner(IPersistent owner)
{
this.owner = owner;
}
internal LinkImpl()
{
}
internal LinkImpl(int initSize)
{
arr = new IPersistent[initSize];
}
internal LinkImpl(IPersistent[] arr, IPersistent owner)
{
this.arr = arr;
this.owner = owner;
used = arr.Length;
}
IPersistent[] arr;
int used;
[NonSerialized()]
IPersistent owner;
}
}
| |
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace GameWindows.Game.Base
{
public abstract class MovableBase : IMovable
{
private Vector2? destination;
public MovableBase()
{
}
public MovableBase(Texture2D texture, Vector2 position, float width, float height)
{
Texture = texture;
this.Position = position;
this.Width = width;
this.Height = height;
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="IObject" /> is active.
/// </summary>
/// <value>
/// <c>true</c> if active; otherwise, <c>false</c>.
/// </value>
public bool Active { get; set; }
/// <summary>
/// Gets or sets the height of the object.
/// </summary>
/// <value>
/// The height.
/// </value>
public float Height { get; set; }
/// <summary>
/// Gets or sets the inertia.
/// </summary>
/// <value>
/// The inertia.
/// </value>
public float Inertia { get; set; }
/// <summary>
/// Gets or sets the position of the object.
/// </summary>
/// <value>
/// The position.
/// </value>
public Vector2 Position { get; set; }
/// <summary>
/// Gets or sets the speed.
/// </summary>
/// <value>
/// The speed.
/// </value>
public float Speed { get; set; }
/// <summary>
/// Gets or sets the texture.
/// </summary>
/// <value>
/// The texture.
/// </value>
public Texture2D Texture { get; set; }
/// <summary>
/// Gets or sets the velocity.
/// </summary>
/// <value>
/// The velocity.
/// </value>
public Vector2 Velocity { get; set; }
/// <summary>
/// Gets or sets the width of the object.
/// </summary>
/// <value>
/// The width.
/// </value>
public float Width { get; set; }
/// <summary>
/// Draws the object.
/// </summary>
/// <param name="sb">The sb.</param>
/// <param name="delta">The delta.</param>
/// <exception cref="NotImplementedException"></exception>
public virtual void Draw(SpriteBatch sb, float delta)
{
sb.Draw(this.Texture, this.Position, null, null, Vector2.One / 2f, 0, Vector2.One * 2, Color.White, SpriteEffects.None, 0);
}
/// <summary>
/// Move by specified delta.
/// </summary>
/// <param name="xDelta">The x delta.</param>
/// <param name="yDelta">The y delta.</param>
/// <exception cref="NotImplementedException"></exception>
public void Move(float xDelta, float yDelta)
{
this.Position += new Vector2(float.IsNaN(xDelta) ? 0 : xDelta, float.IsNaN(yDelta) ? 0 : yDelta);
}
/// <summary>
/// Moves to given position. This will move object to destination over time, not in one frame.
/// </summary>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <exception cref="NotImplementedException"></exception>
public void MoveTo(float x, float y)
{
this.destination = new Vector2(x, y);
}
/// <summary>
/// Sets the position.
/// </summary>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
public void SetPosition(float x, float y)
{
this.Position = new Vector2(x, y);
}
/// <summary>
/// Updates the object.
/// </summary>
/// <param name="delta">The delta.</param>
/// <exception cref="NotImplementedException"></exception>
public virtual void Update(float delta)
{
// Move toward position
if (this.destination != null)
{
var direction = DetermineDirection(this.destination.Value);
var speed = ApplySpeed(direction);
var newVelocity = this.Velocity + speed;
this.Velocity = this.ClipVelocity(newVelocity);
}
}
/// <summary>
/// Clips the velocity.
/// </summary>
/// <param name="velocity">The velocity.</param>
/// <returns></returns>
protected Vector2 ClipVelocity(Vector2 velocity)
{
return new Vector2(
MathHelper.Clamp(velocity.X, -this.Speed, this.Speed),
MathHelper.Clamp(velocity.Y, -this.Speed, this.Speed));
}
/// <summary>
/// Applies the speed.
/// </summary>
/// <param name="direction">The direction.</param>
/// <returns></returns>
protected Vector2 ApplySpeed(Vector2 direction)
{
return direction*this.Speed*(1f/this.Inertia);
}
/// <summary>
/// Determines the direction.
/// </summary>
/// <param name="destination">The destination.</param>
/// <returns></returns>
protected Vector2 DetermineDirection(Vector2 destination)
{
return destination - this.Position;
}
/// <summary>
/// Determines whether object is at the specified position.
/// </summary>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <returns></returns>
protected bool IsAtPosition(float x, float y)
{
return this.IsAtPosition(new Vector2(x, y));
}
/// <summary>
/// Determines whether object is at the specified position.
/// </summary>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <returns></returns>
protected bool IsAtPosition(Vector2 destination)
{
var delta = this.Position - destination;
return Math.Abs(delta.X) < 0.1f && Math.Abs(delta.Y) < 0.1f;
}
#region IDisposable Support
private bool disposedValue = false;
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
}
disposedValue = true;
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
}
#endregion
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using PCSComUtils.Common;
namespace PCSUtils.Utils
{
#region InputBox return result
/// <summary>
/// Class used to store the result of an InputBox.Show message.
/// </summary>
public class PCSInputBoxResult
{
public DialogResult ReturnCode;
public object Value;
}
#endregion
/// <summary>
/// Summary description for InputBox.
/// </summary>
public class PCSInputBox
{
#region Private Windows Contols and Constructor
// Create a new instance of the form.
private static Form frmInputDialog;
private static Label lblPrompt;
private static Button btnOK;
private static Button btnCancel;
private static C1.Win.C1Input.C1NumericEdit txtInput;
public PCSInputBox()
{
}
#endregion
#region Private Variables
private static string mformCaption = string.Empty;
private static string mformPrompt = string.Empty;
private static PCSInputBoxResult moutputResponse = new PCSInputBoxResult();
private static object mdefaultValue = DBNull.Value;
private static int mxPos = -1;
private static int myPos = -1;
private static bool mInputNegative = false;
#endregion
#region Windows Form code
private static void InitializeComponent()
{
// Create a new instance of the form.
frmInputDialog = new Form();
lblPrompt = new Label();
btnOK = new Button();
btnCancel = new Button();
txtInput = new C1.Win.C1Input.C1NumericEdit();
frmInputDialog.SuspendLayout();
//
// lblPrompt
//
lblPrompt.Anchor = ((AnchorStyles)((((AnchorStyles.Top | AnchorStyles.Bottom) | AnchorStyles.Left) | AnchorStyles.Right)));
lblPrompt.BackColor = SystemColors.Control;
lblPrompt.Font = new Font("Microsoft Sans Serif", 8.25F, FontStyle.Regular, GraphicsUnit.Point, ((Byte)(0)));
lblPrompt.Location = new Point(12, 9);
lblPrompt.Name = "lblPrompt";
lblPrompt.Size = new Size(302, 82);
lblPrompt.TabIndex = 3;
//
// btnOK
//
btnOK.DialogResult = DialogResult.OK;
btnOK.FlatStyle = FlatStyle.System;
btnOK.Location = new Point(326, 8);
btnOK.Name = "btnOK";
btnOK.Size = new Size(64, 24);
btnOK.TabIndex = 1;
btnOK.Text = "&OK";
btnOK.Click += new EventHandler(btnOK_Click);
//
// btnCancel
//
btnCancel.DialogResult = DialogResult.Cancel;
btnCancel.FlatStyle = FlatStyle.System;
btnCancel.Location = new Point(326, 40);
btnCancel.Name = "btnCancel";
btnCancel.Size = new Size(64, 24);
btnCancel.TabIndex = 2;
btnCancel.Text = "&Cancel";
btnCancel.Click += new EventHandler(btnCancel_Click);
//
// txtInput
//
txtInput.Location = new Point(8, 100);
txtInput.Name = "txtInput";
txtInput.Size = new Size(379, 20);
txtInput.TabIndex = 0;
txtInput.Text = "";
//
// InputBoxDialog
//
frmInputDialog.AutoScaleBaseSize = new Size(5, 13);
frmInputDialog.ClientSize = new Size(398, 128);
frmInputDialog.Controls.Add(txtInput);
frmInputDialog.Controls.Add(btnCancel);
frmInputDialog.Controls.Add(btnOK);
frmInputDialog.Controls.Add(lblPrompt);
frmInputDialog.FormBorderStyle = FormBorderStyle.FixedDialog;
frmInputDialog.MaximizeBox = false;
frmInputDialog.MinimizeBox = false;
frmInputDialog.Name = "InputBoxDialog";
frmInputDialog.ResumeLayout(false);
}
#endregion
#region Private function, InputBox Form move and change size
static private bool LoadForm()
{
const string THIS = "PCSUtils.Utils.PCSInputBox";
try
{
//Set form security
Security objSecurity = new Security();
frmInputDialog.Name = THIS;
if (objSecurity.SetRightForUserOnForm(frmInputDialog, SystemProperty.UserName) == 0)
{
// You don't have the right to view this item
PCSMessageBox.Show(ErrorCode.MESSAGE_YOU_HAVE_NO_RIGHT_TO_VIEW, MessageBoxIcon.Warning);
return false;
}
OutputResponse.ReturnCode = DialogResult.Ignore;
OutputResponse.Value = DBNull.Value;
txtInput.Value = mdefaultValue;
txtInput.VisibleButtons = C1.Win.C1Input.DropDownControlButtonFlags.None;
txtInput.FormatType = C1.Win.C1Input.FormatTypeEnum.CustomFormat;
txtInput.CustomFormat = Constants.DECIMAL_NUMBERFORMAT;
//Not allow input negative
if(!mInputNegative)
{
txtInput.NumericInputKeys = ((C1.Win.C1Input.NumericInputKeyFlags)((((C1.Win.C1Input.NumericInputKeyFlags.F9 | C1.Win.C1Input.NumericInputKeyFlags.Plus)
| C1.Win.C1Input.NumericInputKeyFlags.Decimal)
| C1.Win.C1Input.NumericInputKeyFlags.X)));
}
lblPrompt.Text = mformPrompt;
frmInputDialog.Text = mformCaption;
frmInputDialog.AcceptButton = btnOK;
frmInputDialog.CancelButton = btnCancel;
// Retrieve the working rectangle from the Screen class
// using the PrimaryScreen and the WorkingArea properties.
System.Drawing.Rectangle workingRectangle = Screen.PrimaryScreen.WorkingArea;
if((mxPos >= 0 && mxPos < workingRectangle.Width-100) && (myPos >= 0 && myPos < workingRectangle.Height-100))
{
frmInputDialog.StartPosition = FormStartPosition.Manual;
frmInputDialog.Location = new System.Drawing.Point(mxPos, myPos);
}
else
{
frmInputDialog.StartPosition = FormStartPosition.CenterScreen;
}
string PrompText = lblPrompt.Text;
int n = 0;
int Index = 0;
while(PrompText.IndexOf("\n",Index) > -1)
{
Index = PrompText.IndexOf("\n",Index)+1;
n++;
}
if( n == 0 )
n = 1;
System.Drawing.Point Txt = txtInput.Location;
Txt.Y = Txt.Y + (n*4);
txtInput.Location = Txt;
System.Drawing.Size form = frmInputDialog.Size;
form.Height = form.Height + (n*4);
frmInputDialog.Size = form;
txtInput.SelectionStart = 0;
txtInput.SelectionLength = txtInput.Text.Length;
txtInput.Focus();
return true;
}
catch
{
return false;
}
}
#endregion
#region Button control click event
static private void btnOK_Click(object sender, System.EventArgs e)
{
try
{
if(txtInput.ValueIsDbNull || txtInput.Text == string.Empty)
{
OutputResponse.ReturnCode = DialogResult.Cancel;
OutputResponse.Value = DBNull.Value;
return;
}
OutputResponse.ReturnCode = DialogResult.OK;
OutputResponse.Value = txtInput.Value;
frmInputDialog.Dispose();
}
catch
{}
}
static private void btnCancel_Click(object sender, System.EventArgs e)
{
try
{
OutputResponse.ReturnCode = DialogResult.Cancel;
OutputResponse.Value = DBNull.Value;
frmInputDialog.Dispose();
}
catch
{}
}
#endregion
#region Public Static Show functions
static public PCSInputBoxResult Show(string pstrPrompt)
{
try
{
InitializeComponent();
FormPrompt = pstrPrompt;
// Display the form as a modal dialog box.
if(LoadForm())
{
frmInputDialog.ShowDialog();
}
return OutputResponse;
}
catch
{
return OutputResponse;
}
}
static public PCSInputBoxResult Show(string pstrPrompt, string pstrTitle)
{
try
{
InitializeComponent();
FormCaption = pstrTitle;
FormPrompt = pstrPrompt;
// Display the form as a modal dialog box.
if(LoadForm())
{
frmInputDialog.ShowDialog();
}
return OutputResponse;
}
catch
{
return OutputResponse;
}
}
static public PCSInputBoxResult Show(string pstrPrompt, string pstrTitle, bool pblnInputNegative)
{
try
{
InitializeComponent();
InputNegative = pblnInputNegative;
FormCaption = pstrTitle;
FormPrompt = pstrPrompt;
// Display the form as a modal dialog box.
if(LoadForm())
{
frmInputDialog.ShowDialog();
}
return OutputResponse;
}
catch
{
return OutputResponse;
}
}
static public PCSInputBoxResult Show(string pstrPrompt, string pstrTitle, string pstrDefault)
{
try
{
InitializeComponent();
FormCaption = pstrTitle;
FormPrompt = pstrPrompt;
DefaultValue = pstrDefault;
// Display the form as a modal dialog box.
if(LoadForm())
{
frmInputDialog.ShowDialog();
}
return OutputResponse;
}
catch
{
return OutputResponse;
}
}
static public PCSInputBoxResult Show(string pstrPrompt, string pstrTitle, string pstrDefault, bool pblnInputNegative)
{
try
{
InitializeComponent();
InputNegative = pblnInputNegative;
FormCaption = pstrTitle;
FormPrompt = pstrPrompt;
DefaultValue = pstrDefault;
// Display the form as a modal dialog box.
if(LoadForm())
{
frmInputDialog.ShowDialog();
}
return OutputResponse;
}
catch
{
return OutputResponse;
}
}
static public PCSInputBoxResult Show(string pstrPrompt, string pstrTitle, string pstrDefault, int pintXPos, int pintYPos)
{
try
{
InitializeComponent();
FormCaption = pstrTitle;
FormPrompt = pstrPrompt;
DefaultValue = pstrDefault;
XPosition = pintXPos;
YPosition = pintYPos;
// Display the form as a modal dialog box.
if(LoadForm())
{
frmInputDialog.ShowDialog();
}
return OutputResponse;
}
catch
{
return OutputResponse;
}
}
#endregion
#region Private Properties
/// <summary>
/// property FormCaption
/// </summary>
static private string FormCaption
{
set
{
mformCaption = value;
}
get
{
return mformCaption;
}
}
static private bool InputNegative
{
set{ mInputNegative = value;}
get{ return mInputNegative;}
}
/// <summary>
/// property FormPrompt
/// </summary>
static private string FormPrompt
{
set{mformPrompt = value;}
get{ return mformPrompt; }
}
static private PCSInputBoxResult OutputResponse
{
get
{
return moutputResponse;
}
set
{
moutputResponse = value;
}
} // property InputResponse
static private string DefaultValue
{
set
{
mdefaultValue = value;
}
} // property DefaultValue
static private int XPosition
{
set
{
if( value >= 0 )
mxPos = value;
}
} // property XPos
static private int YPosition
{
set
{
if( value >= 0 )
myPos = value;
}
} // property YPos
#endregion
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// 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.
//
using NLog.Config;
namespace NLog.UnitTests.Targets.Wrappers
{
using System;
using System.Threading;
using NLog.Common;
using NLog.Targets;
using NLog.Targets.Wrappers;
using Xunit;
public class AutoFlushTargetWrapperTests : NLogTestBase
{
[Fact]
public void AutoFlushTargetWrapperSyncTest1()
{
var myTarget = new MyTarget();
var wrapper = new AutoFlushTargetWrapper
{
WrappedTarget = myTarget,
};
myTarget.Initialize(null);
wrapper.Initialize(null);
var logEvent = new LogEventInfo();
Exception lastException = null;
bool continuationHit = false;
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationHit = true;
};
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
Assert.True(continuationHit);
Assert.Null(lastException);
Assert.Equal(1, myTarget.FlushCount);
Assert.Equal(1, myTarget.WriteCount);
continuationHit = false;
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
Assert.True(continuationHit);
Assert.Null(lastException);
Assert.Equal(2, myTarget.WriteCount);
Assert.Equal(2, myTarget.FlushCount);
}
[Fact]
public void AutoFlushTargetWrapperAsyncTest1()
{
var myTarget = new MyAsyncTarget();
var wrapper = new AutoFlushTargetWrapper(myTarget);
myTarget.Initialize(null);
wrapper.Initialize(null);
var logEvent = new LogEventInfo();
Exception lastException = null;
var continuationHit = new ManualResetEvent(false);
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationHit.Set();
};
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.Null(lastException);
Assert.Equal(1, myTarget.FlushCount);
Assert.Equal(1, myTarget.WriteCount);
continuationHit.Reset();
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.Null(lastException);
Assert.Equal(2, myTarget.WriteCount);
Assert.Equal(2, myTarget.FlushCount);
}
[Fact]
public void AutoFlushTargetWrapperAsyncTest2()
{
var myTarget = new MyAsyncTarget();
var wrapper = new AutoFlushTargetWrapper(myTarget);
myTarget.Initialize(null);
wrapper.Initialize(null);
var logEvent = new LogEventInfo();
Exception lastException = null;
for (int i = 0; i < 100; ++i)
{
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(ex => lastException = ex));
}
var continuationHit = new ManualResetEvent(false);
AsyncContinuation continuation =
ex =>
{
continuationHit.Set();
};
wrapper.Flush(ex => { });
Assert.Null(lastException);
wrapper.Flush(continuation);
Assert.Null(lastException);
continuationHit.WaitOne();
Assert.Null(lastException);
wrapper.Flush(ex => { }); // Executed right away
Assert.Null(lastException);
Assert.Equal(100, myTarget.WriteCount);
Assert.Equal(103, myTarget.FlushCount);
}
[Fact]
public void AutoFlushTargetWrapperAsyncWithExceptionTest1()
{
var myTarget = new MyAsyncTarget
{
ThrowExceptions = true,
};
var wrapper = new AutoFlushTargetWrapper(myTarget);
myTarget.Initialize(null);
wrapper.Initialize(null);
var logEvent = new LogEventInfo();
Exception lastException = null;
var continuationHit = new ManualResetEvent(false);
AsyncContinuation continuation =
ex =>
{
lastException = ex;
continuationHit.Set();
};
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.NotNull(lastException);
Assert.IsType<InvalidOperationException>(lastException);
// no flush on exception
Assert.Equal(0, myTarget.FlushCount);
Assert.Equal(1, myTarget.WriteCount);
continuationHit.Reset();
lastException = null;
wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
continuationHit.WaitOne();
Assert.NotNull(lastException);
Assert.IsType<InvalidOperationException>(lastException);
Assert.Equal(0, myTarget.FlushCount);
Assert.Equal(2, myTarget.WriteCount);
}
[Fact]
public void AutoFlushConditionConfigurationTest()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"<nlog>
<targets>
<target type='AutoFlushWrapper' condition='level >= LogLevel.Debug' name='FlushOnError'>
<target name='d2' type='Debug' />
</target>
</targets>
<rules>
<logger name='*' level='Warn' writeTo='FlushOnError'>
</logger>
</rules>
</nlog>");
var target = LogManager.Configuration.FindTargetByName("FlushOnError") as AutoFlushTargetWrapper;
Assert.NotNull(target);
Assert.NotNull(target.Condition);
Assert.Equal("(level >= Debug)", target.Condition.ToString());
Assert.Equal("d2", target.WrappedTarget.Name);
}
[Fact]
public void AutoFlushOnConditionTest()
{
var testTarget = new MyTarget();
var autoFlushWrapper = new AutoFlushTargetWrapper(testTarget);
autoFlushWrapper.Condition = "level > LogLevel.Info";
testTarget.Initialize(null);
autoFlushWrapper.Initialize(null);
AsyncContinuation continuation = ex => { };
autoFlushWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Info, "*", "test").WithContinuation(continuation));
autoFlushWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Trace, "*", "test").WithContinuation(continuation));
Assert.Equal(2, testTarget.WriteCount);
Assert.Equal(0, testTarget.FlushCount);
autoFlushWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Warn, "*", "test").WithContinuation(continuation));
autoFlushWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Error, "*", "test").WithContinuation(continuation));
Assert.Equal(4, testTarget.WriteCount);
Assert.Equal(2, testTarget.FlushCount);
}
[Fact]
public void MultipleConditionalAutoFlushWrappersTest()
{
var testTarget = new MyTarget();
var autoFlushOnLevelWrapper = new AutoFlushTargetWrapper(testTarget);
autoFlushOnLevelWrapper.Condition = "level > LogLevel.Info";
var autoFlushOnMessageWrapper = new AutoFlushTargetWrapper(autoFlushOnLevelWrapper);
autoFlushOnMessageWrapper.Condition = "contains('${message}','FlushThis')";
testTarget.Initialize(null);
autoFlushOnLevelWrapper.Initialize(null);
autoFlushOnMessageWrapper.Initialize(null);
AsyncContinuation continuation = ex => { };
autoFlushOnMessageWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Trace, "*", "test").WithContinuation(continuation));
Assert.Equal(1, testTarget.WriteCount);
Assert.Equal(0, testTarget.FlushCount);
autoFlushOnMessageWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Fatal, "*", "test").WithContinuation(continuation));
Assert.Equal(2, testTarget.WriteCount);
Assert.Equal(1, testTarget.FlushCount);
autoFlushOnMessageWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Trace, "*", "Please FlushThis").WithContinuation(continuation));
Assert.Equal(3, testTarget.WriteCount);
Assert.Equal(2, testTarget.FlushCount);
}
[Fact]
public void BufferingAutoFlushWrapperTest()
{
var testTarget = new MyTarget();
var bufferingTargetWrapper = new BufferingTargetWrapper(testTarget, 100);
var autoFlushOnLevelWrapper = new AutoFlushTargetWrapper(bufferingTargetWrapper);
autoFlushOnLevelWrapper.Condition = "level > LogLevel.Info";
testTarget.Initialize(null);
bufferingTargetWrapper.Initialize(null);
autoFlushOnLevelWrapper.Initialize(null);
AsyncContinuation continuation = ex => { };
autoFlushOnLevelWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Trace, "*", "test").WithContinuation(continuation));
Assert.Equal(0, testTarget.WriteCount);
Assert.Equal(0, testTarget.FlushCount);
autoFlushOnLevelWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Fatal, "*", "test").WithContinuation(continuation));
Assert.Equal(2, testTarget.WriteCount);
Assert.Equal(1, testTarget.FlushCount);
autoFlushOnLevelWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Trace, "*", "Please do not FlushThis").WithContinuation(continuation));
Assert.Equal(2, testTarget.WriteCount);
Assert.Equal(1, testTarget.FlushCount);
autoFlushOnLevelWrapper.Flush(continuation);
Assert.Equal(3, testTarget.WriteCount);
Assert.Equal(2, testTarget.FlushCount);
}
[Fact]
public void IgnoreExplicitAutoFlushWrapperTest()
{
var testTarget = new MyTarget();
var bufferingTargetWrapper = new BufferingTargetWrapper(testTarget, 100);
var autoFlushOnLevelWrapper = new AutoFlushTargetWrapper(bufferingTargetWrapper);
autoFlushOnLevelWrapper.Condition = "level > LogLevel.Info";
autoFlushOnLevelWrapper.FlushOnConditionOnly = true;
testTarget.Initialize(null);
bufferingTargetWrapper.Initialize(null);
autoFlushOnLevelWrapper.Initialize(null);
AsyncContinuation continuation = ex => { };
autoFlushOnLevelWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Trace, "*", "test").WithContinuation(continuation));
Assert.Equal(0, testTarget.WriteCount);
Assert.Equal(0, testTarget.FlushCount);
autoFlushOnLevelWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Fatal, "*", "test").WithContinuation(continuation));
Assert.Equal(2, testTarget.WriteCount);
Assert.Equal(1, testTarget.FlushCount);
autoFlushOnLevelWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Trace, "*", "Please do not FlushThis").WithContinuation(continuation));
Assert.Equal(2, testTarget.WriteCount);
Assert.Equal(1, testTarget.FlushCount);
autoFlushOnLevelWrapper.Flush(continuation);
Assert.Equal(2, testTarget.WriteCount);
Assert.Equal(1, testTarget.FlushCount);
}
class MyAsyncTarget : Target
{
public int FlushCount { get; private set; }
public int WriteCount { get; private set; }
protected override void Write(LogEventInfo logEvent)
{
throw new NotSupportedException();
}
protected override void Write(AsyncLogEventInfo logEvent)
{
Assert.True(FlushCount <= WriteCount);
WriteCount++;
ThreadPool.QueueUserWorkItem(
s =>
{
if (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)
{
FlushCount++;
ThreadPool.QueueUserWorkItem(
s => asyncContinuation(null));
}
public bool ThrowExceptions { get; set; }
}
class MyTarget : Target
{
public int FlushCount { get; set; }
public int WriteCount { get; set; }
protected override void Write(LogEventInfo logEvent)
{
Assert.True(FlushCount <= WriteCount);
WriteCount++;
}
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
FlushCount++;
asyncContinuation(null);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO.Pipes
{
public abstract partial class PipeStream : Stream
{
internal const string AnonymousPipeName = "anonymous";
private static readonly Task<int> s_zeroTask = Task.FromResult(0);
private SafePipeHandle _handle;
private bool _canRead;
private bool _canWrite;
private bool _isAsync;
private bool _isMessageComplete;
private bool _isFromExistingHandle;
private bool _isHandleExposed;
private PipeTransmissionMode _readMode;
private PipeTransmissionMode _transmissionMode;
private PipeDirection _pipeDirection;
private int _outBufferSize;
private PipeState _state;
protected PipeStream(PipeDirection direction, int bufferSize)
{
if (direction < PipeDirection.In || direction > PipeDirection.InOut)
{
throw new ArgumentOutOfRangeException(nameof(direction), SR.ArgumentOutOfRange_DirectionModeInOutOrInOut);
}
if (bufferSize < 0)
{
throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedNonNegNum);
}
Init(direction, PipeTransmissionMode.Byte, bufferSize);
}
protected PipeStream(PipeDirection direction, PipeTransmissionMode transmissionMode, int outBufferSize)
{
if (direction < PipeDirection.In || direction > PipeDirection.InOut)
{
throw new ArgumentOutOfRangeException(nameof(direction), SR.ArgumentOutOfRange_DirectionModeInOutOrInOut);
}
if (transmissionMode < PipeTransmissionMode.Byte || transmissionMode > PipeTransmissionMode.Message)
{
throw new ArgumentOutOfRangeException(nameof(transmissionMode), SR.ArgumentOutOfRange_TransmissionModeByteOrMsg);
}
if (outBufferSize < 0)
{
throw new ArgumentOutOfRangeException(nameof(outBufferSize), SR.ArgumentOutOfRange_NeedNonNegNum);
}
Init(direction, transmissionMode, outBufferSize);
}
private void Init(PipeDirection direction, PipeTransmissionMode transmissionMode, int outBufferSize)
{
Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction");
Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");
Debug.Assert(outBufferSize >= 0, "outBufferSize is negative");
// always defaults to this until overridden
_readMode = transmissionMode;
_transmissionMode = transmissionMode;
_pipeDirection = direction;
if ((_pipeDirection & PipeDirection.In) != 0)
{
_canRead = true;
}
if ((_pipeDirection & PipeDirection.Out) != 0)
{
_canWrite = true;
}
_outBufferSize = outBufferSize;
// This should always default to true
_isMessageComplete = true;
_state = PipeState.WaitingToConnect;
}
// Once a PipeStream has a handle ready, it should call this method to set up the PipeStream. If
// the pipe is in a connected state already, it should also set the IsConnected (protected) property.
// This method may also be called to uninitialize a handle, setting it to null.
[SecuritySafeCritical]
protected void InitializeHandle(SafePipeHandle handle, bool isExposed, bool isAsync)
{
if (isAsync && handle != null)
{
InitializeAsyncHandle(handle);
}
_handle = handle;
_isAsync = isAsync;
// track these separately; _isHandleExposed will get updated if accessed though the property
_isHandleExposed = isExposed;
_isFromExistingHandle = isExposed;
}
[SecurityCritical]
public override int Read(byte[] buffer, int offset, int count)
{
if (_isAsync)
{
return ReadAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
}
CheckReadWriteArgs(buffer, offset, count);
if (!CanRead)
{
throw Error.GetReadNotSupported();
}
CheckReadOperations();
return ReadCore(new Span<byte>(buffer, offset, count));
}
public override int Read(Span<byte> destination)
{
if (_isAsync)
{
return base.Read(destination);
}
if (!CanRead)
{
throw Error.GetReadNotSupported();
}
CheckReadOperations();
return ReadCore(destination);
}
[SecuritySafeCritical]
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
CheckReadWriteArgs(buffer, offset, count);
if (!CanRead)
{
throw Error.GetReadNotSupported();
}
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<int>(cancellationToken);
}
CheckReadOperations();
if (!_isAsync)
{
return base.ReadAsync(buffer, offset, count, cancellationToken);
}
if (count == 0)
{
UpdateMessageCompletion(false);
return s_zeroTask;
}
return ReadAsyncCore(buffer, offset, count, cancellationToken);
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
if (_isAsync)
return TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), callback, state);
else
return base.BeginRead(buffer, offset, count, callback, state);
}
public override int EndRead(IAsyncResult asyncResult)
{
if (_isAsync)
return TaskToApm.End<int>(asyncResult);
else
return base.EndRead(asyncResult);
}
[SecurityCritical]
public override void Write(byte[] buffer, int offset, int count)
{
if (_isAsync)
{
WriteAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult();
return;
}
CheckReadWriteArgs(buffer, offset, count);
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
CheckWriteOperations();
WriteCore(new ReadOnlySpan<byte>(buffer, offset, count));
}
public override void Write(ReadOnlySpan<byte> source)
{
if (_isAsync)
{
base.Write(source);
return;
}
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
CheckWriteOperations();
WriteCore(source);
}
[SecuritySafeCritical]
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
CheckReadWriteArgs(buffer, offset, count);
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<int>(cancellationToken);
}
CheckWriteOperations();
if (!_isAsync)
{
return base.WriteAsync(buffer, offset, count, cancellationToken);
}
if (count == 0)
{
return Task.CompletedTask;
}
return WriteAsyncCore(buffer, offset, count, cancellationToken);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
if (_isAsync)
return TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), callback, state);
else
return base.BeginWrite(buffer, offset, count, callback, state);
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (_isAsync)
TaskToApm.End(asyncResult);
else
base.EndWrite(asyncResult);
}
private void CheckReadWriteArgs(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
[Conditional("DEBUG")]
private static void DebugAssertHandleValid(SafePipeHandle handle)
{
Debug.Assert(handle != null, "handle is null");
Debug.Assert(!handle.IsClosed, "handle is closed");
}
[Conditional("DEBUG")]
private static void DebugAssertReadWriteArgs(byte[] buffer, int offset, int count, SafePipeHandle handle)
{
Debug.Assert(buffer != null, "buffer is null");
Debug.Assert(offset >= 0, "offset is negative");
Debug.Assert(count >= 0, "count is negative");
Debug.Assert(offset <= buffer.Length - count, "offset + count is too big");
DebugAssertHandleValid(handle);
}
// Reads a byte from the pipe stream. Returns the byte cast to an int
// or -1 if the connection has been broken.
[SecurityCritical]
public override unsafe int ReadByte()
{
byte b;
return Read(new Span<byte>(&b, 1)) > 0 ? b : -1;
}
[SecurityCritical]
public override unsafe void WriteByte(byte value)
{
Write(new ReadOnlySpan<byte>(&value, 1));
}
// Does nothing on PipeStreams. We cannot call Interop.FlushFileBuffers here because we can deadlock
// if the other end of the pipe is no longer interested in reading from the pipe.
[SecurityCritical]
public override void Flush()
{
CheckWriteOperations();
if (!CanWrite)
{
throw Error.GetWriteNotSupported();
}
}
[SecurityCritical]
protected override void Dispose(bool disposing)
{
try
{
// Nothing will be done differently based on whether we are
// disposing vs. finalizing.
if (_handle != null && !_handle.IsClosed)
{
_handle.Dispose();
}
UninitializeAsyncHandle();
}
finally
{
base.Dispose(disposing);
}
_state = PipeState.Closed;
}
// ********************** Public Properties *********************** //
// APIs use coarser definition of connected, but these map to internal
// Connected/Disconnected states. Note that setter is protected; only
// intended to be called by custom PipeStream concrete children
public bool IsConnected
{
get
{
return State == PipeState.Connected;
}
protected set
{
_state = (value) ? PipeState.Connected : PipeState.Disconnected;
}
}
public bool IsAsync
{
get { return _isAsync; }
}
// Set by the most recent call to Read or EndRead. Will be false if there are more buffer in the
// message, otherwise it is set to true.
public bool IsMessageComplete
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
// omitting pipe broken exception to allow reader to finish getting message
if (_state == PipeState.WaitingToConnect)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected);
}
if (_state == PipeState.Disconnected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeDisconnected);
}
if (CheckOperationsRequiresSetHandle && _handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed))
{
throw Error.GetPipeNotOpen();
}
// don't need to check transmission mode; just care about read mode. Always use
// cached mode; otherwise could throw for valid message when other side is shutting down
if (_readMode != PipeTransmissionMode.Message)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeReadModeNotMessage);
}
return _isMessageComplete;
}
}
internal void UpdateMessageCompletion(bool completion)
{
// Set message complete to true because the pipe is broken as well.
// Need this to signal to readers to stop reading.
_isMessageComplete = (completion || _state == PipeState.Broken);
}
public SafePipeHandle SafePipeHandle
{
[SecurityCritical]
[SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")]
get
{
if (_handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
if (_handle.IsClosed)
{
throw Error.GetPipeNotOpen();
}
_isHandleExposed = true;
return _handle;
}
}
internal SafePipeHandle InternalHandle
{
[SecurityCritical]
get
{
return _handle;
}
}
protected bool IsHandleExposed
{
get
{
return _isHandleExposed;
}
}
public override bool CanRead
{
[Pure]
get
{
return _canRead;
}
}
public override bool CanWrite
{
[Pure]
get
{
return _canWrite;
}
}
public override bool CanSeek
{
[Pure]
get
{
return false;
}
}
public override long Length
{
get
{
throw Error.GetSeekNotSupported();
}
}
public override long Position
{
get
{
throw Error.GetSeekNotSupported();
}
set
{
throw Error.GetSeekNotSupported();
}
}
public override void SetLength(long value)
{
throw Error.GetSeekNotSupported();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw Error.GetSeekNotSupported();
}
// anonymous pipe ends and named pipe server can get/set properties when broken
// or connected. Named client overrides
protected internal virtual void CheckPipePropertyOperations()
{
if (CheckOperationsRequiresSetHandle && _handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
// these throw object disposed
if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed))
{
throw Error.GetPipeNotOpen();
}
}
// Reads can be done in Connected and Broken. In the latter,
// read returns 0 bytes
protected internal void CheckReadOperations()
{
// Invalid operation
if (_state == PipeState.WaitingToConnect)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected);
}
if (_state == PipeState.Disconnected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeDisconnected);
}
if (CheckOperationsRequiresSetHandle && _handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
// these throw object disposed
if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed))
{
throw Error.GetPipeNotOpen();
}
}
// Writes can only be done in connected state
protected internal void CheckWriteOperations()
{
// Invalid operation
if (_state == PipeState.WaitingToConnect)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeNotYetConnected);
}
if (_state == PipeState.Disconnected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeDisconnected);
}
if (CheckOperationsRequiresSetHandle && _handle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
// IOException
if (_state == PipeState.Broken)
{
throw new IOException(SR.IO_PipeBroken);
}
// these throw object disposed
if ((_state == PipeState.Closed) || (_handle != null && _handle.IsClosed))
{
throw Error.GetPipeNotOpen();
}
}
internal PipeState State
{
get
{
return _state;
}
set
{
_state = value;
}
}
}
}
| |
// iMarkupYourOtherMind.cs
//
// Copyright (c) 2013 Brent Knowles (http://www.brentknowles.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.
//
// Review documentation at http://www.yourothermind.com for updated implementation notes, license updates
// or other general information/
//
// Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW
// Full source code: https://github.com/BrentKnowles/YourOtherMind
//###
//
// iMarkupYourOtherMind.cs
//
// Authors:
// Brent Knowles <writer@brentknowles.com>
//
// Copyright (C) 2013 Brent Knowles
// [LICENSE MUST BE REDONE]
//
using System;
using Layout;
using CoreUtilities;
using System.Windows.Forms;
using System.Drawing;
using System.Collections;
using System.Text.RegularExpressions;
using System.Collections.Generic;
namespace YourOtherMind
{
public class iMarkupYourOtherMind : iMarkupLanguage
{
public iMarkupYourOtherMind ()
{
}
public override string ToString ()
{
return nameAndIdentifier;
}
private string nameAndIdentifier= Loc.Instance.GetString("YourOtherMind");
public string NameAndIdentifier {
get {
return nameAndIdentifier;
}
set {
nameAndIdentifier = value;
}
}
public string CleanWordRequest(string incoming)
{
string sLine = incoming.Replace ("[[words]]", "").Trim ();
return sLine;
}
public bool IsWordRequest (string incoming)
{
bool result = false;
if (incoming.IndexOf ("[[words]]") > -1) {
result = true;
}
return result;
}
public bool IsOver (string incoming)
{
bool result = false;
if (incoming.IndexOf ("[[end") > -1) {
result = true;
}
return result;
}
public bool IsGroupRequest (string incoming)
{
bool result = false;
if (incoming.IndexOf ("[[Group") > -1) {
result = true;
}
return result;
}
public bool IsIndex (string incoming)
{
bool result = false;
if ( "[[index]]" == incoming) {
result = true;
}
return result;
}
void PaintLink (PaintEventArgs e, int Start, int End, RichTextBox RichText)
{
Graphics g;
g = RichText.CreateGraphics ();
//Pen myPen = null;// new Pen (Color.FromArgb (60, Color.Yellow)); // Alpha did not seem to work this way
// this gets tricky. The loop is just to find all the [[~scenes]] on the note
// even if offscreen.
// OK: but with th eoptimization to only show on screen stuff, do we need this anymore???
// august 10 - settting it back
// now trying regex
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex ("\\w\\|\\w",
System.Text.RegularExpressions.RegexOptions.IgnoreCase |
System.Text.RegularExpressions.RegexOptions.Multiline);
System.Text.RegularExpressions.MatchCollection matches = regex.Matches (RichText.Text, Start);
foreach (System.Text.RegularExpressions.Match match in matches) {
if (match.Index > End)
break; // we exit if already at end
Point pos = RichText.GetPositionFromCharIndex (match.Index);
if (pos.X > -1 && pos.Y > -1) {
int testpos = match.Index + 2;
Color colorToUse = Color.FromArgb(255, ControlPaint.Dark (TextUtils.InvertColor(RichText.BackColor)));
// default is [[facts]] and stuff
pos = CoreUtilities.General.BuildLocationForOverlayText (pos, DockStyle.Bottom, "|");
System.Drawing.SolidBrush brush1 = new System.Drawing.SolidBrush( colorToUse);
//myPen.Width = 1;
//myPen.Color = Color.Red;
int scaler = Math.Max (10, (int)(Math.Round (RichText.ZoomFactor / 2) * 10));
Rectangle rec = new Rectangle (new Point (pos.X, pos.Y - 25), new Size ((int)(scaler * 1.5), (int)(scaler * 0.75)));
Rectangle rec2 = new Rectangle (new Point (pos.X+20, pos.Y - 25), new Size ((int)(scaler * 1), (int)(scaler * 0.65)));
//g.DrawLine(myPen, pos.X, pos.Y -10, pos.X + 50, pos.Y-10);
//g.FillRectangle (brush1, rec);
g.FillEllipse(brush1, rec);
g.FillEllipse(brush1, rec2);
}
/*
locationInText = locationInText + sParam.Length;
if (locationInText > end)
{
// don't search past visible end
pos = emptyPoint;
}
else
pos = GetPositionForFoundText(sParam, ref locationInText);*/
}
// regex matches
g.Dispose ();
//myPen.Dispose ();
}
int BuildScaler (float zoomFactor)
{
return Math.Max (10, (int)(Math.Round (zoomFactor / 2) * 10));
}
void PaintNoSpaceAfterPeriod (PaintEventArgs e, int Start, int End, RichTextBox RichText)
{
Graphics g;
g = RichText.CreateGraphics ();
//Pen myPen = null;// new Pen (Color.FromArgb (60, Color.Yellow)); // Alpha did not seem to work this way
// this gets tricky. The loop is just to find all the [[~scenes]] on the note
// even if offscreen.
// OK: but with th eoptimization to only show on screen stuff, do we need this anymore???
// august 10 - settting it back
// now trying regex
System.Text.RegularExpressions.Regex regex =
new System.Text.RegularExpressions.Regex ("\\.\\w|\\. \\w|\\?\\w|\\? \\w|\\!\\w|\\! \\w|\\;\\w|\\; \\w|\\:\\w|\\: \\w|\\,\\w|\\, \\w",
System.Text.RegularExpressions.RegexOptions.IgnoreCase | RegexOptions.Compiled|
System.Text.RegularExpressions.RegexOptions.Multiline);
System.Text.RegularExpressions.MatchCollection matches = regex.Matches (RichText.Text, Start);
foreach (System.Text.RegularExpressions.Match match in matches) {
if (match.Index > End)
break; // we exit if already at end
Point pos = RichText.GetPositionFromCharIndex (match.Index);
if (pos.X > -1 && pos.Y > -1) {
int testpos = match.Index + 2;
Color colorToUse = Color.FromArgb(175, Color.Red);
// default is [[facts]] and stuff
// pos = CoreUtilities.General.BuildLocationForOverlayText (pos, DockStyle.Bottom, " ");
// System.Drawing.SolidBrush brush1 = new System.Drawing.SolidBrush( colorToUse);
System.Drawing.Pen pen1 = new Pen(colorToUse);
//myPen.Width = 1;
//myPen.Color = Color.Red;
// int scaler = BuildScaler(RichText.ZoomFactor);
Rectangle rec = GetRectangleForSmallRectangle(g, pos, RichText, match.Index, match.Value, true);// new Rectangle (new Point (pos.X+(int)(scaler*1.5), pos.Y -(5+scaler)), new Size ((int)(scaler * 1.5), (int)(scaler * 1.5)));
//Rectangle rec = new Rectangle (new Point (pos.X+scaler, pos.Y-15), new Size ((int)(scaler * 1.5), (int)(scaler * 0.75)));
// Rectangle rec2 = new Rectangle (new Point (pos.X+20, pos.Y - 25), new Size ((int)(scaler * 1), (int)(scaler * 0.65)));
//g.DrawLine(myPen, pos.X, pos.Y -10, pos.X + 50, pos.Y-10);
//g.FillRectangle (brush1, rec);
//g.FillEllipse(brush1, rec);
rec.Height = 1;
g.DrawRectangle(pen1, rec);
// g.FillEllipse(brush1, rec2);
}
/*
locationInText = locationInText + sParam.Length;
if (locationInText > end)
{
// don't search past visible end
pos = emptyPoint;
}
else
pos = GetPositionForFoundText(sParam, ref locationInText);*/
}
// regex matches
g.Dispose ();
//myPen.Dispose ();
}
void PaintDoubleSpaces (PaintEventArgs e, int Start, int End, RichTextBox RichText)
{
Graphics g;
g = RichText.CreateGraphics ();
//Pen myPen = null;// new Pen (Color.FromArgb (60, Color.Yellow)); // Alpha did not seem to work this way
// this gets tricky. The loop is just to find all the [[~scenes]] on the note
// even if offscreen.
// OK: but with th eoptimization to only show on screen stuff, do we need this anymore???
// august 10 - settting it back
// now trying regex
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex ("\\w \\w",
System.Text.RegularExpressions.RegexOptions.IgnoreCase | RegexOptions.Compiled|
System.Text.RegularExpressions.RegexOptions.Multiline);
System.Text.RegularExpressions.MatchCollection matches = regex.Matches (RichText.Text, Start);
foreach (System.Text.RegularExpressions.Match match in matches) {
if (match.Index > End)
break; // we exit if already at end
Point pos = RichText.GetPositionFromCharIndex (match.Index);
if (pos.X > -1 && pos.Y > -1) {
int testpos = match.Index + 2;
Color colorToUse = Color.FromArgb(175, Color.Red);
// default is [[facts]] and stuff
// pos = CoreUtilities.General.BuildLocationForOverlayText (pos, DockStyle.Bottom, " ");
// System.Drawing.SolidBrush brush1 = new System.Drawing.SolidBrush( colorToUse);
System.Drawing.Pen pen1 = new Pen(colorToUse);
//myPen.Width = 1;
//myPen.Color = Color.Red;
// int scaler = BuildScaler(RichText.ZoomFactor);
Rectangle rec = GetRectangleForSmallRectangle(g, pos, RichText, match.Index, match.Value, true);// new Rectangle (new Point (pos.X+(int)(scaler*1.5), pos.Y -(5+scaler)), new Size ((int)(scaler * 1.5), (int)(scaler * 1.5)));
//Rectangle rec = new Rectangle (new Point (pos.X+scaler, pos.Y-15), new Size ((int)(scaler * 1.5), (int)(scaler * 0.75)));
// Rectangle rec2 = new Rectangle (new Point (pos.X+20, pos.Y - 25), new Size ((int)(scaler * 1), (int)(scaler * 0.65)));
//g.DrawLine(myPen, pos.X, pos.Y -10, pos.X + 50, pos.Y-10);
//g.FillRectangle (brush1, rec);
//g.FillEllipse(brush1, rec);
rec.Height = 1;
g.DrawRectangle(pen1, rec);
// g.FillEllipse(brush1, rec2);
}
/*
locationInText = locationInText + sParam.Length;
if (locationInText > end)
{
// don't search past visible end
pos = emptyPoint;
}
else
pos = GetPositionForFoundText(sParam, ref locationInText);*/
}
// regex matches
g.Dispose ();
//myPen.Dispose ();
}
/// <summary>
/// Gets the main headings.
///
/// Used for TabNavigation
/// </summary>
/// <returns>
/// The main headings.
/// </returns>
/// <param name='box'>
/// Box.
/// </param>
public List<string> GetMainHeadings (RichTextBox box)
{
System.Text.RegularExpressions.Regex Mainheading = new System.Text.RegularExpressions.Regex ("^=[^=]+=$",
RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.Multiline);
MatchCollection matches = Mainheading.Matches (box.Text, 0);
List<string> result = new List<string>();
foreach (System.Text.RegularExpressions.Match match in matches) {
result.Add (match.Value);
}
return result;
}
void PaintHeadings (PaintEventArgs e, int Start, int End, RichTextBox RichText, System.Text.RegularExpressions.Regex regex2, Color color, string text, Font f)
{
//string exp = ".*\\=([^)]+?)\\=";
// this one was fast but inaccurate (very)
//string exp = String.Format (".*?\\=\\w([^)]+?)\\w\\={0}?", Environment.NewLine); // added lazy operations to attempt a speed improvement
Graphics g = e.Graphics;//RichText.CreateGraphics ();
System.Drawing.Pen pen1 = new Pen(color);
System.Text.RegularExpressions.MatchCollection matches = regex2.Matches (RichText.Text, Start);
foreach (System.Text.RegularExpressions.Match match in matches) {
if (match.Index > End)
break; // we exit if already at end
Point pos = RichText.GetPositionFromCharIndex (match.Index);
if (pos.X > -1 && pos.Y > -1) {
pen1.Width = 8;
string stext = text+match.Value+text;
//pos = CoreUtilities.General.BuildLocationForOverlayText (pos, DockStyle.Right,match.Value );
int newWidth = Convert.ToInt32 (g.MeasureString (stext, f).Width * RichText.ZoomFactor);
pos = new Point(pos.X + (newWidth), pos.Y + 10);
g.DrawLine (pen1, pos.X, pos.Y, pos.X + 500, pos.Y);
// Rectangle rec = GetRectangleForSmallRectangle(g, pos, RichText, match.Index, match.Value, true);// new Rectangle (new Point (pos.X+(int)(scaler*1.5), pos.Y -(5+scaler)), new Size ((int)(scaler * 1.5), (int)(scaler * 1.5)));
// rec.Height = 2;
//
// g.DrawRectangle(pen1, rec);
}
}
// g.Dispose (); don't dispose what we are borrowing
}
System.Text.RegularExpressions.Regex Mainheading = new System.Text.RegularExpressions.Regex ("^=[^=]+=$",
RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Compiled| System.Text.RegularExpressions.RegexOptions.Multiline );
System.Text.RegularExpressions.Regex Mainheading2 = new System.Text.RegularExpressions.Regex ("^==[^=]+==$",
RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Compiled| System.Text.RegularExpressions.RegexOptions.Multiline );
System.Text.RegularExpressions.Regex Mainheading3 = new System.Text.RegularExpressions.Regex ("^===[^=]+===$",
RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Compiled| System.Text.RegularExpressions.RegexOptions.Multiline );
public void DoPaint (PaintEventArgs e, int Start, int End, RichTextBox RichText)
{
try {
PaintDoubleSpaces(e, Start, End, RichText);
PaintNoSpaceAfterPeriod(e, Start, End, RichText);
PaintLink(e, Start, End, RichText);
bool doheadings = true;
if (doheadings)
{
Font f = new Font(RichText.Font.FontFamily, RichText.Font.Size, RichText.Font.Style, GraphicsUnit.Pixel, Convert.ToByte(0), false);
Color newColor = TextUtils.InvertColor(RichText.BackColor);
Color colorToUse = Color.FromArgb(175, ControlPaint.Dark(newColor));
PaintHeadings(e, Start, End, RichText, Mainheading, colorToUse,"=",f);
colorToUse = Color.FromArgb(175,ControlPaint.Light(newColor));
PaintHeadings(e, Start, End, RichText, Mainheading2, colorToUse,"==",f);
colorToUse = Color.FromArgb(175, ControlPaint.LightLight(newColor));
PaintHeadings(e, Start, End, RichText, Mainheading3, colorToUse,"===",f);
}
// int locationInText = GetCharIndexFromPosition(new Point(0, 0));
string sParam = "[[~scene]]";
// assuming function only being used for [[~scene]] delimiters
// I've moved this position up to core function as an optimization
// instead of being used in each call to GetPositionForFoundText
// int start =
// if (locationInText < start)
// {
// locationInText = start;
// }
// The loop is what makes this
// Point pos = GetPositionForFoundText(sParam, ref locationInText);
Graphics g;
//g = RichText.CreateGraphics ();
g = e.Graphics;
Pen myPen = new Pen (Color.FromArgb (255, ControlPaint.LightLight (TextUtils.InvertColor(RichText.BackColor))));
// this gets tricky. The loop is just to find all the [[~scenes]] on the note
// even if offscreen.
// OK: but with th eoptimization to only show on screen stuff, do we need this anymore???
// august 10 - settting it back
// now trying regex
// This worked for = match but it was WAAY too slow
// System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex (".*\\=([^)]+)\\=",
// System.Text.RegularExpressions.RegexOptions.IgnoreCase);
// this works just experimenting
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex ("\\[\\[(.*?)\\]\\]",
System.Text.RegularExpressions.RegexOptions.IgnoreCase |
System.Text.RegularExpressions.RegexOptions.Multiline);
System.Text.RegularExpressions.MatchCollection matches = regex.Matches (RichText.Text, Start);
foreach (System.Text.RegularExpressions.Match match in matches) {
if (match.Index > End)
break; // we exit if already at end
Point pos = RichText.GetPositionFromCharIndex (match.Index);
if (pos.X > -1 && pos.Y > -1) {
// but we only draw the line IF we are onscreen
//if (pos.X > -1 && pos.Y > -1)
//if (sParam == "[[~scene]]")
//test instead to see if pos + 2 is a ~
int testpos = match.Index + 2;
/// November 2012 - only want this to appear for ~scene
if (RichText.Text.Length > (testpos + 1) && RichText.Text [testpos] == '~' && RichText.Text [testpos + 1] == 's') {
if (g != null) {
//myPen.Color = Color.Yellow;
// myPen = new Pen (Color.FromArgb (225, Color.Yellow));
myPen.Width = 8;
pos = CoreUtilities.General.BuildLocationForOverlayText (pos, DockStyle.Right, sParam);
g.DrawLine (myPen, pos.X, pos.Y, pos.X + 500, pos.Y);
}
} else {
Color colorToUse = Color.FromArgb (255, ControlPaint.LightLight (TextUtils.InvertColor(RichText.BackColor)));//Color.FromArgb(255, Color.Green);
// November 2012 - testing to see if there's a period right before which means it will count)
if (match.Index > 0) {
if ('.' == RichText.Text [match.Index - 1]) {
// we have a period so the code .[[f]] will not do anything
// show in a different color
colorToUse = Color.Red;// Alpha worked but because not all areas are redrawn at same time did not look right (May 2013) Color.FromArgb(255, Color.Red);
}
}
// default is [[facts]] and stuff
//pos = CoreUtilities.General.BuildLocationForOverlayText (pos, DockStyle.Bottom, sParam);
// if (e.Graphics. .Contains(pos))
{
//System.Drawing.SolidBrush brush1 = new System.Drawing.SolidBrush (colorToUse);
System.Drawing.Pen pen1 = new System.Drawing.Pen (colorToUse);
//myPen.Width = 1;
//myPen.Color = Color.Red;
//int scaler = BuildScaler(RichText.ZoomFactor);
Rectangle rec = GetRectangleForSmallRectangle(g, pos, RichText, match.Index, match.Value, false);// new Rectangle (new Point (pos.X+(int)(scaler*1.5), pos.Y -(5+scaler)), new Size ((int)(scaler * 1.5), (int)(scaler * 1.5)));
//g.DrawLine(myPen, pos.X, pos.Y -10, pos.X + 50, pos.Y-10);
// SolidBrush brushEmpty = new SolidBrush(RichText.BackColor);
// g.FillRectangle (brushEmpty, rec);
g.DrawRectangle (pen1, rec);
}
}
/*
locationInText = locationInText + sParam.Length;
if (locationInText > end)
{
// don't search past visible end
pos = emptyPoint;
}
else
pos = GetPositionForFoundText(sParam, ref locationInText);*/
}
} // regex matches
// don't dispose of this, since it is used elsewhere (i.e., we did not create it)
// g.Dispose ();
myPen.Dispose ();
} catch (Exception ex) {
NewMessage.Show (String.Format ("Failed in WRITER part Start {0} End {1}", Start, End) + ex.ToString ());
}
}
// used for starting a rectangle or line from the point of a match
Point GetBottomLeftCornerOfMatch(Point passedPos, RichTextBox box)
{
Point newPoint = new Point ( (int)(passedPos.X + box.ZoomFactor), (int)(passedPos.Y - (box.ZoomFactor *.95)));
return newPoint;
}
// Rectangle GetRectangleForSmallRectangle (Graphics g, Point passedPos, RichTextBox box, int textposition, string text, bool drawFromBottom)
// {
// return GetRectangleForSmallRectangle(g, passedPos, box, textposition, text, drawFromBottom,Constants.BLANK);
// }
// returns a rectangle suitable for a small rectangle covering the beginning of the matched text
Rectangle GetRectangleForSmallRectangle (Graphics g, Point passedPos, RichTextBox box, int textposition, string text, bool drawFromBottom/*, string offsetx*/)
{
int scaler = BuildScaler (box.ZoomFactor);
Point newPos = GetBottomLeftCornerOfMatch (passedPos, box);
// int newX = ((int)(scaler * 1.5)) - scaler;
// int newY = (int)(scaler * 1.5);
// default is ignored. We construct width and height based on size of text
Size newSize = new Size (100, 100);
using (Font f = new Font(box.Font.FontFamily, box.Font.Size, box.Font.Style, GraphicsUnit.Pixel, Convert.ToByte(0), false)) {
//char ch = box.Text [textposition];
//newSize.Width = Convert.ToInt32 (g.MeasureString (ch.ToString(), f).Width * box.ZoomFactor);
newSize.Width = Convert.ToInt32 (g.MeasureString (text, f).Width * box.ZoomFactor);
// June 2013 -- the box height is slightly too much, trying to reduce
newSize.Height = Convert.ToInt32 (box.Font.Height * (box.ZoomFactor-0.15));
// // doh. We need to adjust yPosition to accomdate the way rectangles draw
if (true == drawFromBottom) {
newPos.Y = newPos.Y + newSize.Height;
}
// if (Constants.BLANK != offsetx) {
// // by default we start at the first left
// // but for certain things like headings we actually want to sh ift over towards the right a measure
// newPos.X = newPos.X + (offsetx.Length * newSize.Width);
// }
}
return new Rectangle(newPos, newSize);
}
public ArrayList GetListOfPages(string sLine, ref bool bGetWords, LayoutPanelBase usedLayout)
{
//NewMessage.Show ("YOM GetListOfPages for line = " + sLine);
ArrayList ListOfParsePages = new ArrayList();
string[] items = sLine.Split(',');
if (items != null)
{
string sStoryboardName = items[1];
string sGroupMatch = items[2];
if (sLine.IndexOf(",words") > -1)
{
bGetWords = true;
}
ListOfParsePages.AddRange(usedLayout.GetListOfGroupEmNameMatching(sStoryboardName, sGroupMatch));
//NewMessage.Show(sStoryboardName + " " + sGroupMatch);
}
return ListOfParsePages;
}
/// <summary>
/// Builds the list. for the bookmark system
/// </summary>
/// <returns>
/// The list.
/// </returns>
/// <param name='RichText'>
/// Rich text.
/// </param>
public List<TreeItem> BuildList (NoteDataXML_RichText RichText)
{
System.Text.RegularExpressions.Regex Mainheading = new System.Text.RegularExpressions.Regex ("^=[^=]+=$",
RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.Multiline);
System.Text.RegularExpressions.Regex Mainheading2 = new System.Text.RegularExpressions.Regex ("^==[^=]+==$",
RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.Multiline);
System.Text.RegularExpressions.Regex Mainheading3 = new System.Text.RegularExpressions.Regex ("^===[^=]+===$",
RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.Multiline);
System.Text.RegularExpressions.Regex Mainheading4 = new System.Text.RegularExpressions.Regex ("^====[^=]+====$",
RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.Multiline);
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex ("\\[\\[~(.*?)\\]\\]",
System.Text.RegularExpressions.RegexOptions.IgnoreCase |
System.Text.RegularExpressions.RegexOptions.Multiline);
//TODO: Move this into the MarkupLanguage
List<TreeItem> items = new List<TreeItem> ();
//For [ ] text
System.Text.RegularExpressions.MatchCollection matches = regex.Matches (RichText.GetRichTextBox().Text, 0);
foreach (System.Text.RegularExpressions.Match match in matches) {
string value = match.Value;
if (value.IndexOf("~var") > -1)
{
// December 2013
// we don't show variable text.
}
else
{
items.Add (new TreeItem(match.Value, 0,match.Index));
}
}
matches = Mainheading.Matches (RichText.GetRichTextBox().Text, 0);
foreach (System.Text.RegularExpressions.Match match in matches) {
items.Add (new TreeItem(match.Value.Replace ("=",""), 0,match.Index));
}
matches = Mainheading2.Matches (RichText.GetRichTextBox().Text, 0);
foreach (System.Text.RegularExpressions.Match match in matches) {
items.Add (new TreeItem(match.Value.Replace ("=",""), 1,match.Index));
}
matches = Mainheading3.Matches (RichText.GetRichTextBox().Text, 0);
foreach (System.Text.RegularExpressions.Match match in matches) {
items.Add (new TreeItem(match.Value.Replace ("=",""), 2,match.Index));
}
matches = Mainheading4.Matches (RichText.GetRichTextBox().Text, 0);
foreach (System.Text.RegularExpressions.Match match in matches) {
items.Add (new TreeItem(match.Value.Replace ("=",""), 3,match.Index));
}
//need to somehow merge and sort by index
// need to a custom fort
items.Sort ();
return items;
}
}
}
| |
using System;
using System.Collections.Generic;
using NDatabase.Api;
using NDatabase.Api.Triggers;
using NDatabase.Container;
using NDatabase.Exceptions;
using NDatabase.Meta;
using NDatabase.Tool.Wrappers;
using NDatabase.Triggers;
namespace NDatabase.Core.Engine
{
internal sealed class InternalTriggerManager : IInternalTriggerManager
{
/// <summary>
/// key is class Name, value is the collection of triggers for the class
/// </summary>
private readonly IDictionary<Type, IOdbList<Trigger>> _listOfDeleteTriggers =
new OdbHashMap<Type, IOdbList<Trigger>>();
/// <summary>
/// key is class Name, value is the collection of triggers for the class
/// </summary>
private readonly IDictionary<Type, IOdbList<Trigger>> _listOfInsertTriggers =
new OdbHashMap<Type, IOdbList<Trigger>>();
/// <summary>
/// key is class Name, value is the collection of triggers for the class
/// </summary>
private readonly IDictionary<Type, IOdbList<Trigger>> _listOfSelectTriggers =
new OdbHashMap<Type, IOdbList<Trigger>>();
/// <summary>
/// key is class Name, value is the collection of triggers for the class
/// </summary>
private readonly IDictionary<Type, IOdbList<Trigger>> _listOfUpdateTriggers =
new OdbHashMap<Type, IOdbList<Trigger>>();
private readonly IStorageEngine _storageEngine;
public InternalTriggerManager(IStorageEngine engine)
{
_storageEngine = engine;
}
#region IInternalTriggerManager Members
public void AddUpdateTriggerFor(Type type, UpdateTrigger trigger)
{
AddTriggerFor(type, trigger, _listOfUpdateTriggers);
}
public void AddInsertTriggerFor(Type type, InsertTrigger trigger)
{
AddTriggerFor(type, trigger, _listOfInsertTriggers);
}
public void AddDeleteTriggerFor(Type type, DeleteTrigger trigger)
{
AddTriggerFor(type, trigger, _listOfDeleteTriggers);
}
public void AddSelectTriggerFor(Type type, SelectTrigger trigger)
{
AddTriggerFor(type, trigger, _listOfSelectTriggers);
}
public void ManageInsertTriggerBefore(Type type, object @object)
{
if (!HasInsertTriggersFor(type))
return;
foreach (InsertTrigger trigger in GetListOfInsertTriggersFor(type))
{
if (trigger.Odb == null)
trigger.Odb = DependencyContainer.Resolve<IOdbForTrigger>(_storageEngine);
try
{
if (@object != null)
trigger.BeforeInsert(@object);
}
catch (Exception e)
{
var warning =
NDatabaseError.BeforeInsertTriggerHasThrownException.AddParameter(trigger.GetType().FullName)
.AddParameter(e.ToString());
throw new OdbRuntimeException(warning, e);
}
}
}
public void ManageInsertTriggerAfter(Type type, object @object, OID oid)
{
if (!HasInsertTriggersFor(type))
return;
foreach (InsertTrigger trigger in GetListOfInsertTriggersFor(type))
{
if (trigger.Odb == null)
trigger.Odb = DependencyContainer.Resolve<IOdbForTrigger>(_storageEngine);
try
{
trigger.AfterInsert(@object, oid);
}
catch (Exception e)
{
var warning =
NDatabaseError.AfterInsertTriggerHasThrownException.AddParameter(trigger.GetType().FullName).
AddParameter(e.ToString());
throw new OdbRuntimeException(warning, e);
}
}
}
public void ManageUpdateTriggerBefore(Type type, NonNativeObjectInfo oldNnoi, object newObject, OID oid)
{
if (!HasUpdateTriggersFor(type))
return;
foreach (UpdateTrigger trigger in GetListOfUpdateTriggersFor(type))
{
if (trigger.Odb == null)
trigger.Odb = DependencyContainer.Resolve<IOdbForTrigger>(_storageEngine);
try
{
var classInfoProvider = ((IClassInfoProvider) trigger.Odb).GetClassInfoProvider();
trigger.BeforeUpdate(new ObjectRepresentation(oldNnoi, classInfoProvider), newObject, oid);
}
catch (Exception e)
{
var warning =
NDatabaseError.BeforeUpdateTriggerHasThrownException.AddParameter(trigger.GetType().FullName)
.AddParameter(e.ToString());
throw new OdbRuntimeException(warning, e);
}
}
}
public void ManageUpdateTriggerAfter(Type type, NonNativeObjectInfo oldNnoi, object newObject, OID oid)
{
if (!HasUpdateTriggersFor(type))
return;
foreach (UpdateTrigger trigger in GetListOfUpdateTriggersFor(type))
{
if (trigger.Odb == null)
trigger.Odb = DependencyContainer.Resolve<IOdbForTrigger>(_storageEngine);
try
{
var classInfoProvider = ((IClassInfoProvider) trigger.Odb).GetClassInfoProvider();
trigger.AfterUpdate(new ObjectRepresentation(oldNnoi, classInfoProvider), newObject, oid);
}
catch (Exception e)
{
var warning =
NDatabaseError.AfterUpdateTriggerHasThrownException.AddParameter(trigger.GetType().FullName).
AddParameter(e.ToString());
throw new OdbRuntimeException(warning, e);
}
}
}
public void ManageDeleteTriggerBefore(Type type, object @object, OID oid)
{
if (!HasDeleteTriggersFor(type))
return;
foreach (DeleteTrigger trigger in GetListOfDeleteTriggersFor(type))
{
if (trigger.Odb == null)
trigger.Odb = DependencyContainer.Resolve<IOdbForTrigger>(_storageEngine);
try
{
trigger.BeforeDelete(@object, oid);
}
catch (Exception e)
{
var warning =
NDatabaseError.BeforeDeleteTriggerHasThrownException.AddParameter(trigger.GetType().FullName)
.AddParameter(e.ToString());
throw new OdbRuntimeException(warning, e);
}
}
}
public void ManageDeleteTriggerAfter(Type type, object @object, OID oid)
{
if (!HasDeleteTriggersFor(type))
return;
foreach (DeleteTrigger trigger in GetListOfDeleteTriggersFor(type))
{
if (trigger.Odb == null)
trigger.Odb = DependencyContainer.Resolve<IOdbForTrigger>(_storageEngine);
try
{
trigger.AfterDelete(@object, oid);
}
catch (Exception e)
{
var warning =
NDatabaseError.AfterDeleteTriggerHasThrownException.AddParameter(trigger.GetType().FullName).
AddParameter(e.ToString());
throw new OdbRuntimeException(warning, e);
}
}
}
public void ManageSelectTriggerAfter(Type type, object @object, OID oid)
{
if (!HasSelectTriggersFor(type))
return;
foreach (SelectTrigger trigger in GetListOfSelectTriggersFor(type))
{
if (trigger.Odb == null)
trigger.Odb = DependencyContainer.Resolve<IOdbForTrigger>(_storageEngine);
if (@object != null)
trigger.AfterSelect(@object, oid);
}
}
#endregion
private bool HasDeleteTriggersFor(Type type)
{
return _listOfDeleteTriggers.ContainsKey(type) || _listOfDeleteTriggers.ContainsKey(typeof (object));
}
private bool HasInsertTriggersFor(Type type)
{
return _listOfInsertTriggers.ContainsKey(type) || _listOfInsertTriggers.ContainsKey(typeof (object));
}
private bool HasSelectTriggersFor(Type type)
{
return _listOfSelectTriggers.ContainsKey(type) || _listOfSelectTriggers.ContainsKey(typeof (object));
}
private bool HasUpdateTriggersFor(Type type)
{
return _listOfUpdateTriggers.ContainsKey(type) || _listOfUpdateTriggers.ContainsKey(typeof (object));
}
private static void AddTriggerFor<TTrigger>(Type type, TTrigger trigger,
IDictionary<Type, IOdbList<Trigger>> listOfTriggers)
where TTrigger : Trigger
{
var triggers = listOfTriggers[type];
if (triggers == null)
{
triggers = new OdbList<Trigger>();
listOfTriggers.Add(type, triggers);
}
triggers.Add(trigger);
}
private IEnumerable<Trigger> GetListOfDeleteTriggersFor(Type type)
{
return GetListOfTriggersFor(type, _listOfDeleteTriggers);
}
private IEnumerable<Trigger> GetListOfInsertTriggersFor(Type type)
{
return GetListOfTriggersFor(type, _listOfInsertTriggers);
}
private IEnumerable<Trigger> GetListOfSelectTriggersFor(Type type)
{
return GetListOfTriggersFor(type, _listOfSelectTriggers);
}
private IEnumerable<Trigger> GetListOfUpdateTriggersFor(Type type)
{
return GetListOfTriggersFor(type, _listOfUpdateTriggers);
}
private static IEnumerable<Trigger> GetListOfTriggersFor(Type type,
IDictionary<Type, IOdbList<Trigger>> listOfTriggers)
{
var listOfTriggersByClassName = listOfTriggers[type];
var listOfTriggersByAllClassTrigger = listOfTriggers[typeof (object)];
if (listOfTriggersByAllClassTrigger != null)
{
var size = listOfTriggersByAllClassTrigger.Count;
if (listOfTriggersByClassName != null)
size = size + listOfTriggersByClassName.Count;
var listOfTriggersToReturn = new OdbList<Trigger>(size);
if (listOfTriggersByClassName != null)
{
listOfTriggersToReturn.AddRange(listOfTriggersByClassName);
}
listOfTriggersToReturn.AddRange(listOfTriggersByAllClassTrigger);
return listOfTriggersToReturn;
}
return listOfTriggersByClassName;
}
}
}
| |
// 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.WebSites
{
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>
/// AppServiceCertificateOrdersOperations operations.
/// </summary>
public partial interface IAppServiceCertificateOrdersOperations
{
/// <summary>
/// List all certificate orders in a subscription.
/// </summary>
/// <remarks>
/// List all certificate orders in a subscription.
/// </remarks>
/// <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<AppServiceCertificateOrder>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Validate information for a certificate order.
/// </summary>
/// <remarks>
/// Validate information for a certificate order.
/// </remarks>
/// <param name='appServiceCertificateOrder'>
/// Information for a certificate order.
/// </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> ValidatePurchaseInformationWithHttpMessagesAsync(AppServiceCertificateOrder appServiceCertificateOrder, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get certificate orders in a resource group.
/// </summary>
/// <remarks>
/// Get certificate orders in a resource group.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </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<AppServiceCertificateOrder>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get a certificate order.
/// </summary>
/// <remarks>
/// Get a certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order..
/// </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<AppServiceCertificateOrder>> GetWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create or update a certificate purchase order.
/// </summary>
/// <remarks>
/// Create or update a certificate purchase order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='certificateDistinguishedName'>
/// Distinguished name to to use for the certificate order.
/// </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<AppServiceCertificateOrder>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, AppServiceCertificateOrder certificateDistinguishedName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete an existing certificate order.
/// </summary>
/// <remarks>
/// Delete an existing certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </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 certificateOrderName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List all certificates associated with a certificate order.
/// </summary>
/// <remarks>
/// List all certificates associated with a certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </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<AppServiceCertificateResource>>> ListCertificatesWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the certificate associated with a certificate order.
/// </summary>
/// <remarks>
/// Get the certificate associated with a certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </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<AppServiceCertificateResource>> GetCertificateWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a certificate and associates with key vault
/// secret.
/// </summary>
/// <remarks>
/// Creates or updates a certificate and associates with key vault
/// secret.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='keyVaultCertificate'>
/// Key vault certificate resource Id.
/// </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<AppServiceCertificateResource>> CreateOrUpdateCertificateWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, string name, AppServiceCertificateResource keyVaultCertificate, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete the certificate associated with a certificate order.
/// </summary>
/// <remarks>
/// Delete the certificate associated with a certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </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> DeleteCertificateWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Reissue an existing certificate order.
/// </summary>
/// <remarks>
/// Reissue an existing certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='reissueCertificateOrderRequest'>
/// Parameters for the reissue.
/// </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> ReissueWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, ReissueCertificateOrderRequest reissueCertificateOrderRequest, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Renew an existing certificate order.
/// </summary>
/// <remarks>
/// Renew an existing certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='renewCertificateOrderRequest'>
/// Renew parameters
/// </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> RenewWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, RenewCertificateOrderRequest renewCertificateOrderRequest, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Resend certificate email.
/// </summary>
/// <remarks>
/// Resend certificate email.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </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> ResendEmailWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Verify domain ownership for this certificate order.
/// </summary>
/// <remarks>
/// Verify domain ownership for this certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='nameIdentifier'>
/// Email address
/// </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> ResendRequestEmailsWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, NameIdentifier nameIdentifier, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Verify domain ownership for this certificate order.
/// </summary>
/// <remarks>
/// Verify domain ownership for this certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='siteSealRequest'>
/// Site seal request.
/// </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<SiteSeal>> RetrieveSiteSealWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, SiteSealRequest siteSealRequest, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Verify domain ownership for this certificate order.
/// </summary>
/// <remarks>
/// Verify domain ownership for this certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </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> VerifyDomainOwnershipWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Retrieve the list of certificate actions.
/// </summary>
/// <remarks>
/// Retrieve the list of certificate actions.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='name'>
/// Name of the certificate order.
/// </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<IList<CertificateOrderAction>>> RetrieveCertificateActionsWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Retrieve email history.
/// </summary>
/// <remarks>
/// Retrieve email history.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='name'>
/// Name of the certificate order.
/// </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<IList<CertificateEmail>>> RetrieveCertificateEmailHistoryWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create or update a certificate purchase order.
/// </summary>
/// <remarks>
/// Create or update a certificate purchase order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='certificateDistinguishedName'>
/// Distinguished name to to use for the certificate order.
/// </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<AppServiceCertificateOrder>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, AppServiceCertificateOrder certificateDistinguishedName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a certificate and associates with key vault
/// secret.
/// </summary>
/// <remarks>
/// Creates or updates a certificate and associates with key vault
/// secret.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='keyVaultCertificate'>
/// Key vault certificate resource Id.
/// </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<AppServiceCertificateResource>> BeginCreateOrUpdateCertificateWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, string name, AppServiceCertificateResource keyVaultCertificate, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List all certificate orders in a subscription.
/// </summary>
/// <remarks>
/// List all certificate orders in a subscription.
/// </remarks>
/// <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<AppServiceCertificateOrder>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get certificate orders in a resource group.
/// </summary>
/// <remarks>
/// Get certificate orders in a resource group.
/// </remarks>
/// <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<AppServiceCertificateOrder>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List all certificates associated with a certificate order.
/// </summary>
/// <remarks>
/// List all certificates associated with a certificate order.
/// </remarks>
/// <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<AppServiceCertificateResource>>> ListCertificatesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
using System;
using System.Linq;
using System.Runtime.InteropServices;
using Torque6.Engine.SimObjects;
using Torque6.Engine.SimObjects.Scene;
using Torque6.Engine.Namespaces;
using Torque6.Utility;
namespace Torque6.Engine.SimObjects
{
public unsafe class ActionMap : SimObject
{
public ActionMap()
{
ObjectPtr = Sim.WrapObject(InternalUnsafeMethods.ActionMapCreateInstance());
}
public ActionMap(uint pId) : base(pId)
{
}
public ActionMap(string pName) : base(pName)
{
}
public ActionMap(IntPtr pObjPtr) : base(pObjPtr)
{
}
public ActionMap(Sim.SimObjectPtr* pObjPtr) : base(pObjPtr)
{
}
public ActionMap(SimObject pObj) : base(pObj)
{
}
#region UnsafeNativeMethods
new internal struct InternalUnsafeMethods
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _ActionMapCreateInstance();
private static _ActionMapCreateInstance _ActionMapCreateInstanceFunc;
internal static IntPtr ActionMapCreateInstance()
{
if (_ActionMapCreateInstanceFunc == null)
{
_ActionMapCreateInstanceFunc =
(_ActionMapCreateInstance)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"ActionMapCreateInstance"), typeof(_ActionMapCreateInstance));
}
return _ActionMapCreateInstanceFunc();
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _ActionMapBind(IntPtr map, int argc, string[] argv);
private static _ActionMapBind _ActionMapBindFunc;
internal static void ActionMapBind(IntPtr map, int argc, string[] argv)
{
if (_ActionMapBindFunc == null)
{
_ActionMapBindFunc =
(_ActionMapBind)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"ActionMapBind"), typeof(_ActionMapBind));
}
_ActionMapBindFunc(map, argc, argv);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _ActionMapBindObj(IntPtr map, int argc, string[] argv, IntPtr obj);
private static _ActionMapBindObj _ActionMapBindObjFunc;
internal static void ActionMapBindObj(IntPtr map, int argc, string[] argv, IntPtr obj)
{
if (_ActionMapBindObjFunc == null)
{
_ActionMapBindObjFunc =
(_ActionMapBindObj)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"ActionMapBindObj"), typeof(_ActionMapBindObj));
}
_ActionMapBindObjFunc(map, argc, argv, obj);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _ActionMapBindCmd(IntPtr map, string device, string action, string makeCmd, string breakCmd);
private static _ActionMapBindCmd _ActionMapBindCmdFunc;
internal static void ActionMapBindCmd(IntPtr map, string device, string action, string makeCmd, string breakCmd)
{
if (_ActionMapBindCmdFunc == null)
{
_ActionMapBindCmdFunc =
(_ActionMapBindCmd)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"ActionMapBindCmd"), typeof(_ActionMapBindCmd));
}
_ActionMapBindCmdFunc(map, device, action, makeCmd, breakCmd);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _ActionMapUnbind(IntPtr map, string device, string action);
private static _ActionMapUnbind _ActionMapUnbindFunc;
internal static void ActionMapUnbind(IntPtr map, string device, string action)
{
if (_ActionMapUnbindFunc == null)
{
_ActionMapUnbindFunc =
(_ActionMapUnbind)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"ActionMapUnbind"), typeof(_ActionMapUnbind));
}
_ActionMapUnbindFunc(map, device, action);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _ActionMapUnbindObj(IntPtr map, string device, string action, IntPtr obj);
private static _ActionMapUnbindObj _ActionMapUnbindObjFunc;
internal static void ActionMapUnbindObj(IntPtr map, string device, string action, IntPtr obj)
{
if (_ActionMapUnbindObjFunc == null)
{
_ActionMapUnbindObjFunc =
(_ActionMapUnbindObj)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"ActionMapUnbindObj"), typeof(_ActionMapUnbindObj));
}
_ActionMapUnbindObjFunc(map, device, action, obj);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _ActionMapSave(IntPtr map, string fileName, bool append);
private static _ActionMapSave _ActionMapSaveFunc;
internal static void ActionMapSave(IntPtr map, string fileName, bool append)
{
if (_ActionMapSaveFunc == null)
{
_ActionMapSaveFunc =
(_ActionMapSave)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"ActionMapSave"), typeof(_ActionMapSave));
}
_ActionMapSaveFunc(map, fileName, append);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _ActionMapPush(IntPtr map);
private static _ActionMapPush _ActionMapPushFunc;
internal static void ActionMapPush(IntPtr map)
{
if (_ActionMapPushFunc == null)
{
_ActionMapPushFunc =
(_ActionMapPush)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"ActionMapPush"), typeof(_ActionMapPush));
}
_ActionMapPushFunc(map);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void _ActionMapPop(IntPtr map);
private static _ActionMapPop _ActionMapPopFunc;
internal static void ActionMapPop(IntPtr map)
{
if (_ActionMapPopFunc == null)
{
_ActionMapPopFunc =
(_ActionMapPop)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"ActionMapPop"), typeof(_ActionMapPop));
}
_ActionMapPopFunc(map);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _ActionMapGetBinding(IntPtr map, string command);
private static _ActionMapGetBinding _ActionMapGetBindingFunc;
internal static IntPtr ActionMapGetBinding(IntPtr map, string command)
{
if (_ActionMapGetBindingFunc == null)
{
_ActionMapGetBindingFunc =
(_ActionMapGetBinding)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"ActionMapGetBinding"), typeof(_ActionMapGetBinding));
}
return _ActionMapGetBindingFunc(map, command);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _ActionMapGetCommand(IntPtr map, string device, string action);
private static _ActionMapGetCommand _ActionMapGetCommandFunc;
internal static IntPtr ActionMapGetCommand(IntPtr map, string device, string action)
{
if (_ActionMapGetCommandFunc == null)
{
_ActionMapGetCommandFunc =
(_ActionMapGetCommand)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"ActionMapGetCommand"), typeof(_ActionMapGetCommand));
}
return _ActionMapGetCommandFunc(map, device, action);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool _ActionMapIsInverted(IntPtr map, string device, string action);
private static _ActionMapIsInverted _ActionMapIsInvertedFunc;
internal static bool ActionMapIsInverted(IntPtr map, string device, string action)
{
if (_ActionMapIsInvertedFunc == null)
{
_ActionMapIsInvertedFunc =
(_ActionMapIsInverted)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"ActionMapIsInverted"), typeof(_ActionMapIsInverted));
}
return _ActionMapIsInvertedFunc(map, device, action);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate float _ActionMapGetScale(IntPtr map, string device, string action);
private static _ActionMapGetScale _ActionMapGetScaleFunc;
internal static float ActionMapGetScale(IntPtr map, string device, string action)
{
if (_ActionMapGetScaleFunc == null)
{
_ActionMapGetScaleFunc =
(_ActionMapGetScale)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"ActionMapGetScale"), typeof(_ActionMapGetScale));
}
return _ActionMapGetScaleFunc(map, device, action);
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr _ActionMapGetDeadZone(IntPtr map, string device, string action);
private static _ActionMapGetDeadZone _ActionMapGetDeadZoneFunc;
internal static IntPtr ActionMapGetDeadZone(IntPtr map, string device, string action)
{
if (_ActionMapGetDeadZoneFunc == null)
{
_ActionMapGetDeadZoneFunc =
(_ActionMapGetDeadZone)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle,
"ActionMapGetDeadZone"), typeof(_ActionMapGetDeadZone));
}
return _ActionMapGetDeadZoneFunc(map, device, action);
}
}
#endregion
#region Properties
#endregion
#region Methods
public void Bind(int argc, string[] argv)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.ActionMapBind(ObjectPtr->ObjPtr, argc, argv);
}
public void BindObj(int argc, string[] argv, SimObject obj)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.ActionMapBindObj(ObjectPtr->ObjPtr, argc, argv, obj.ObjectPtr->ObjPtr);
}
public void BindCmd(string device, string action, string makeCmd, string breakCmd)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.ActionMapBindCmd(ObjectPtr->ObjPtr, device, action, makeCmd, breakCmd);
}
public void Unbind(string device, string action)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.ActionMapUnbind(ObjectPtr->ObjPtr, device, action);
}
public void UnbindObj(string device, string action, SimObject obj)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.ActionMapUnbindObj(ObjectPtr->ObjPtr, device, action, obj.ObjectPtr->ObjPtr);
}
public void Save(string fileName = null, bool append = false)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.ActionMapSave(ObjectPtr->ObjPtr, fileName, append);
}
public void Push()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.ActionMapPush(ObjectPtr->ObjPtr);
}
public void Pop()
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
InternalUnsafeMethods.ActionMapPop(ObjectPtr->ObjPtr);
}
public string GetBinding(string command)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.ActionMapGetBinding(ObjectPtr->ObjPtr, command));
}
public string GetCommand(string device, string action)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.ActionMapGetCommand(ObjectPtr->ObjPtr, device, action));
}
public bool IsInverted(string device, string action)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.ActionMapIsInverted(ObjectPtr->ObjPtr, device, action);
}
public float GetScale(string device, string action)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return InternalUnsafeMethods.ActionMapGetScale(ObjectPtr->ObjPtr, device, action);
}
public string GetDeadZone(string device, string action)
{
if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException();
return Marshal.PtrToStringAnsi(InternalUnsafeMethods.ActionMapGetDeadZone(ObjectPtr->ObjPtr, device, action));
}
#endregion
}
}
| |
#region CopyrightHeader
//
// Copyright by Contributors
//
// 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.txt
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Collections;
using System.Text;
using gov.va.medora.utils;
using gov.va.medora.mdo.exceptions;
using gov.va.medora.mdo.src.mdo;
namespace gov.va.medora.mdo.dao.vista
{
public class VistaRadiologyDao : IRadiologyDao
{
AbstractConnection cxn = null;
public VistaRadiologyDao(AbstractConnection cxn)
{
this.cxn = cxn;
}
#region Radiology Reports
public RadiologyReport[] getRadiologyReports(string fromDate, string toDate, int nrpts)
{
return getRadiologyReports(cxn.Pid, fromDate, toDate, nrpts);
}
public RadiologyReport[] getRadiologyReports(string dfn, string fromDate, string toDate, int nrpts)
{
MdoQuery request = VistaUtils.buildReportTextRequest(dfn, fromDate, toDate, nrpts, "OR_R18:IMAGING~RIM;ORDV08;0;");
string response = (string)cxn.query(request);
return toRadiologyReports(response);
}
internal RadiologyReport[] toRadiologyReports(string response)
{
if (response == "")
{
return null;
}
string[] lines = StringUtils.split(response, StringUtils.CRLF);
ArrayList lst = new ArrayList();
RadiologyReport rec = null;
for (int i = 0; i < lines.Length; i++)
{
if (lines[i] == "")
{
continue;
}
string[] flds = StringUtils.split(lines[i], StringUtils.CARET);
if (flds[1] == "[+]")
{
lst.Add(rec);
continue;
}
int fldnum = Convert.ToInt32(flds[0]);
switch (fldnum)
{
// TODO
// need to consider the following case:
//1^NH CAMP PENDLETON;NH CAMP PENDLETON <--- not a recognized site code, should add to site 200
//2^05/24/2010 12:26
//3^L-SPINE, SERIES (3)
// lots more stuff in between
//10^[+]
case 1:
//if (rec != null)
//{
// lst.Add(rec);
//}
rec = new RadiologyReport();
string[] parts = StringUtils.split(flds[1], StringUtils.SEMICOLON);
if (parts.Length == 2)
{
rec.Facility = new SiteId(parts[1], parts[0]);
}
else if (flds[1] != "")
{
rec.Facility = new SiteId(cxn.DataSource.SiteId.Id, flds[1]);
}
else
{
rec.Facility = cxn.DataSource.SiteId;
}
break;
case 2:
if (flds.Length == 2)
{
rec.Timestamp = VistaTimestamp.toUtcFromRdv(flds[1]);
}
break;
case 3:
if (flds.Length == 2)
{
rec.Title = flds[1];
}
break;
case 4:
if (flds.Length == 2)
{
rec.Status = flds[1];
}
break;
case 5:
if (flds.Length == 2)
{
rec.CaseNumber = flds[1];
rec.AccessionNumber = rec.getAccessionNumber(rec.Timestamp, rec.CaseNumber, DateFormat.ISO);
}
break;
case 6:
if (flds.Length == 2)
{
rec.Text += flds[1] + '\n';
}
break;
//case 7:
// if (flds.Length == 2)
// {
// rec.Impression += flds[1] + '\n';
// }
// break;
//case 8:
// if (flds.Length == 2)
// {
// rec.Text += flds[1] + '\n';
// }
// break;
}
}
//if (rec != null)
//{
// lst.Add(rec);
//}
return (RadiologyReport[])lst.ToArray(typeof(RadiologyReport));
}
public RadiologyReport getImagingReport(string dfn, string accessionNumber)
{
return getReport(dfn, accessionNumber);
}
// TODO - need to return a RadiologyReport object here with correctly parsed data
public RadiologyReport getReport(string dfn, string accessionNumber)
{
Dictionary<string, RadiologyReport> exams = getExamList(dfn);
if (null == exams || !exams.ContainsKey(accessionNumber))
{
return null;
}
MdoQuery request = null;
string response = "";
try
{
string caseNumber = accessionNumber.Substring(accessionNumber.IndexOf('-') + 1);
request = buildGetReportRequest(dfn, exams[accessionNumber].Id, caseNumber);
response = (string)cxn.query(request);
return toRadiologyReport(exams[accessionNumber], response);
}
catch (Exception exc)
{
throw new exceptions.MdoException(request, response, exc);
}
}
internal MdoQuery buildGetReportRequest(string dfn, string id, string caseNumber)
{
VistaQuery vq = new VistaQuery("ORWRP REPORT TEXT");
vq.addParameter(vq.LITERAL, dfn);
vq.addParameter(vq.LITERAL, "18:IMAGING (LOCAL ONLY)~");
vq.addParameter(vq.LITERAL, "");
vq.addParameter(vq.LITERAL, "");
vq.addParameter(vq.LITERAL, id + '#' + caseNumber);
vq.addParameter(vq.LITERAL, "0");
vq.addParameter(vq.LITERAL, "0");
return vq;
}
public RadiologyReport toRadiologyReport(RadiologyReport report, string reportText)
{
report.Text = reportText;
return report;
}
#endregion
#region Get Exams
/// <summary>
/// Currently this dao method is not in use. Unit test written for this DAO method.
/// </summary>
/// <param name="dfn"></param>
/// <param name="timestamp"></param>
/// <returns></returns>
internal ArrayList getExams(string dfn, string timestamp)
{
DdrLister query = buildGetExamsQuery(dfn, timestamp);
string[] response = query.execute();
return toExamArrayList(response);
}
internal DdrLister buildGetExamsQuery(string dfn, string timestamp)
{
DdrLister result = new DdrLister(cxn);
result.File = "70.03";
result.Iens = "," + timestamp + "," + dfn + ",";
result.Fields = ".01;2;3;17";
result.Flags = "IP";
result.Xref = "";
return result;
}
internal ArrayList toExamArrayList(string[] response)
{
return null;
}
#endregion
// GetExamList
/// <summary>
/// Get a Dictionary of RadiologyReport objects with the accession number as the key
/// </summary>
/// <param name="dfn">The patient's local ID</param>
/// <returns>Dictionary of RadiologyReport objects with accession number as the key</returns>
public Dictionary<string, RadiologyReport> getExamList(string dfn)
{
MdoQuery request = null;
string response = "";
try
{
request = buildGetExamListRequest(dfn);
response = (string)cxn.query(request);
return toImagingExamIds(response);
}
catch (Exception exc)
{
throw new exceptions.MdoException(request, response, exc);
}
}
internal MdoQuery buildGetExamListRequest(string dfn)
{
VistaUtils.CheckRpcParams(dfn);
VistaQuery vq = new VistaQuery("ORWRA IMAGING EXAMS1");
vq.addParameter(vq.LITERAL, dfn);
return vq;
}
internal Dictionary<string, RadiologyReport> toImagingExamIds(string response)
{
if (String.IsNullOrEmpty(response))
{
return null;
}
Dictionary<string, RadiologyReport> result = new Dictionary<string, RadiologyReport>();
string[] rex = StringUtils.split(response, StringUtils.CRLF);
rex = StringUtils.trimArray(rex);
for (int i = 0; i < rex.Length; i++)
{
RadiologyReport newReport = new RadiologyReport();
string[] flds = StringUtils.split(rex[i], StringUtils.CARET);
newReport.AccessionNumber = newReport.getAccessionNumber(flds[2], flds[4], DateFormat.VISTA);
newReport.Id = flds[1];
newReport.Timestamp = flds[2];
newReport.Title = flds[3];
newReport.CaseNumber = flds[4];
newReport.Status = flds[5];
newReport.Exam = new ImagingExam();
newReport.Exam.Status = (flds[8].Split(new char[] { '~' }))[1]; // e.g. 9~COMPLETE
// maybe map some more fields? lot's of stuff being returned by RPC. For example:
//ANN ARBOR VAMC;506
//^6899085.8548-1
//^3100914.1451
//^TIBIA & FIBULA 2 VIEWS
//^794
//^Verified
//^
//^878633
//^9~COMPLETE
//^AA RADIOLOGY,AA
//^RAD~GENERAL RADIOLOGY
//^
//^73590
//^20323714
//^N
//^
//^
result.Add(newReport.AccessionNumber, newReport);
}
return result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Kappa.RestServices.Areas.HelpPage.ModelDescriptions;
using Kappa.RestServices.Areas.HelpPage.Models;
namespace Kappa.RestServices.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Description:
// Implementation of TextLexicalService abstract class used by TextFormatter for
// document layout. This implementation is based on the hyphenation service in
// NaturalLanguage6.dll - the component owned by the Natural Language Team.
//
// History:
// 06/28/2005 : Worachai Chaoweeraprasit (Wchao) - created
//
//---------------------------------------------------------------------------
using System.Security;
using System.Collections;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Media.TextFormatting;
using MS.Win32;
using MS.Internal;
using DllImport=MS.Internal.PresentationFramework.DllImport;
namespace System.Windows.Documents
{
/// <summary>
/// The NLG hyphenation-based implementation of TextLexicalService used by TextFormatter
/// for line-breaking purpose.
/// </summary>
internal class NaturalLanguageHyphenator : TextLexicalService, IDisposable
{
/// <SecurityNote>
/// Critical: Holds a COM component instance that has unmanged code elevations
/// </SecurityNote>
[SecurityCritical]
private IntPtr _hyphenatorResource;
private bool _disposed;
/// <summary>
/// Construct an NLG-based hyphenator
/// </summary>
/// <SecurityNote>
/// Critical: This code calls into NlCreateHyphenator, which elevates unmanaged code permission.
/// TreatAsSafe: This function call takes no input parameters
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
internal NaturalLanguageHyphenator()
{
try
{
_hyphenatorResource = UnsafeNativeMethods.NlCreateHyphenator();
}
catch (DllNotFoundException)
{
}
catch (EntryPointNotFoundException)
{
}
}
/// <summary>
/// Finalize hyphenator's unmanaged resource
/// </summary>
~NaturalLanguageHyphenator()
{
CleanupInternal(true);
}
/// <summary>
/// Dispose hyphenator's unmanaged resource
/// </summary>
void IDisposable.Dispose()
{
GC.SuppressFinalize(this);
CleanupInternal(false);
}
/// <summary>
/// Internal clean-up routine
/// </summary>
/// <SecurityNote>
/// Critical: This code calls into NlDestroyHyphenator, which elevates unmanaged code permission.
/// TreatAsSafe: This function call takes no input memory block
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
private void CleanupInternal(bool finalizing)
{
if (!_disposed && _hyphenatorResource != IntPtr.Zero)
{
UnsafeNativeMethods.NlDestroyHyphenator(ref _hyphenatorResource);
_disposed = true;
}
}
/// <summary>
/// TextFormatter to query whether the lexical services component could provides
/// analysis for the specified culture.
/// </summary>
/// <param name="culture">Culture whose text is to be analyzed</param>
/// <returns>Boolean value indicates whether the specified culture is supported</returns>
public override bool IsCultureSupported(CultureInfo culture)
{
// Accept all cultures for the time being. Ideally NL6 should provide a way for the client
// to test supported culture.
return true;
}
/// <summary>
/// TextFormatter to get the lexical breaks of the specified raw text
/// </summary>
/// <param name="characterSource">character array</param>
/// <param name="length">number of character in the character array to analyze</param>
/// <param name="textCulture">culture of the specified character source</param>
/// <returns>lexical breaks of the text</returns>
/// <SecurityNote>
/// Critical: This code calls NlHyphenate which is critical.
/// TreatAsSafe: This code accepts a buffer that is length checked and returns
/// data that is ok to return.
/// </SecurityNote>
[SecurityCritical, SecurityTreatAsSafe]
public override TextLexicalBreaks AnalyzeText(
char[] characterSource,
int length,
CultureInfo textCulture
)
{
Invariant.Assert(
characterSource != null
&& characterSource.Length > 0
&& length > 0
&& length <= characterSource.Length
);
if (_hyphenatorResource == IntPtr.Zero)
{
// No hyphenator available, no service delivered
return null;
}
if (_disposed)
{
throw new ObjectDisposedException(SR.Get(SRID.HyphenatorDisposed));
}
byte[] isHyphenPositions = new byte[(length + 7) / 8];
UnsafeNativeMethods.NlHyphenate(
_hyphenatorResource,
characterSource,
length,
((textCulture != null && textCulture != CultureInfo.InvariantCulture) ? textCulture.LCID : 0),
isHyphenPositions,
isHyphenPositions.Length
);
return new HyphenBreaks(isHyphenPositions, length);
}
/// <summary>
/// Private implementation of TextLexicalBreaks that encapsulates hyphen opportunities within
/// a character string.
/// </summary>
private class HyphenBreaks : TextLexicalBreaks
{
private byte[] _isHyphenPositions;
private int _numPositions;
internal HyphenBreaks(byte[] isHyphenPositions, int numPositions)
{
_isHyphenPositions = isHyphenPositions;
_numPositions = numPositions;
}
/// <summary>
/// Indexer for the value at the nth break index (bit nth of the logical bit array)
/// </summary>
private bool this[int index]
{
get { return (_isHyphenPositions[index / 8] & (1 << index % 8)) != 0; }
}
public override int Length
{
get
{
return _numPositions;
}
}
public override int GetNextBreak(int currentIndex)
{
if (_isHyphenPositions != null && currentIndex >= 0)
{
int ich = currentIndex + 1;
while (ich < _numPositions && !this[ich])
ich++;
if (ich < _numPositions)
return ich;
}
// return negative value when break is not found.
return -1;
}
public override int GetPreviousBreak(int currentIndex)
{
if (_isHyphenPositions != null && currentIndex < _numPositions)
{
int ich = currentIndex;
while (ich > 0 && !this[ich])
ich--;
if (ich > 0)
return ich;
}
// return negative value when break is not found.
return -1;
}
}
private static class UnsafeNativeMethods
{
/// <SecurityNote>
/// Critical: This elevates to unmanaged code permission
/// </SecurityNote>
[SecurityCritical, SuppressUnmanagedCodeSecurity]
[DllImport(DllImport.PresentationNative, PreserveSig = false)]
internal static extern IntPtr NlCreateHyphenator();
/// <SecurityNote>
/// Critical: This elevates to unmanaged code permission
/// </SecurityNote>
[SecurityCritical, SuppressUnmanagedCodeSecurity]
[DllImport(DllImport.PresentationNative, PreserveSig = true)]
internal static extern void NlDestroyHyphenator(ref IntPtr hyphenator);
/// <SecurityNote>
/// Critical: This elevates to unmanaged code permission
/// </SecurityNote>
[SecurityCritical, SuppressUnmanagedCodeSecurity]
[DllImport(DllImport.PresentationNative, PreserveSig = false)]
internal static extern void NlHyphenate(
IntPtr hyphenator,
[In, MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U2, SizeParamIndex = 2)]
char[] inputText,
int textLength,
int localeID,
[In, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 5)]
byte[] hyphenBreaks,
int numPositions
);
}
}
}
| |
/* 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:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using XenAdmin.Controls;
using XenAdmin.XCM;
using XenAPI;
using XenCenterLib;
namespace XenAdmin.Wizards.ConversionWizard
{
public partial class SrSelectionPage : XenTabPage
{
private bool _buttonNextEnabled;
private long _requiredDiskSize;
public SrSelectionPage()
{
InitializeComponent();
}
#region XenTabPage Implementation
public override string Text => Messages.CONVERSION_STORAGE_PAGE_TEXT;
public override string PageTitle => Messages.CONVERSION_STORAGE_PAGE_TITLE;
public override string HelpID => "SrSelection";
public override bool EnableNext()
{
return _buttonNextEnabled;
}
protected override void PageLoadedCore(PageLoadedDirection direction)
{
if (direction == PageLoadedDirection.Forward)
RebuildSrList();
}
public override void PageCancelled(ref bool cancel)
{
backgroundWorker1.CancelAsync();
}
#endregion
#region Properties
public ConversionClient ConversionClient { private get; set; }
public VmInstance[] SelectedVms
{
set { _requiredDiskSize = value.Select(vm => vm.CommittedStorage + vm.UncommittedStorage).Sum(); }
}
public SR SelectedSR { get; private set; }
#endregion
private void RebuildSrList()
{
comboBoxSr.Items.Clear();
buttonRefresh.Enabled = false;
pictureBoxError.Image = Images.StaticImages.ajax_loader;
labelError.Text = Messages.CONVERSION_STORAGE_PAGE_QUERYING_SRS;
tableLayoutPanelError.Visible = true;
UpdatePieChart();
UpdateButtons();
backgroundWorker1.RunWorkerAsync();
}
private void UpdatePieChart()
{
var wrapper = comboBoxSr.SelectedItem as SrWrapper;
if (wrapper == null)
{
chart1.Visible = false;
return;
}
SR sr = wrapper.item;
var availableSpace = wrapper.AvailableSpace;
var usedSpace = sr.physical_size - availableSpace;
//order of colours in palette: blue, yellow, red
string[] xValues =
{
string.Format(Messages.CONVERSION_STORAGE_PAGE_FREE_SPACE, Util.DiskSizeString(availableSpace)),
string.Format(Messages.CONVERSION_STORAGE_PAGE_REQUIRED_SPACE, Util.DiskSizeString(_requiredDiskSize)),
string.Format(Messages.CONVERSION_STORAGE_PAGE_USED_SPACE, Util.DiskSizeString(usedSpace))
};
long[] yValues =
{
availableSpace > _requiredDiskSize? availableSpace - _requiredDiskSize : 0,
availableSpace > _requiredDiskSize ? _requiredDiskSize : availableSpace,
usedSpace
};
chart1.Series[0].Points.DataBindXY(xValues, yValues);
chart1.Visible = true;
}
private void UpdateButtons()
{
_buttonNextEnabled = comboBoxSr.SelectedItem is SrWrapper wrapper &&
wrapper.AvailableSpace >= _requiredDiskSize;
OnPageUpdated();
}
private void ShowError(string msg)
{
pictureBoxError.Image = Images.StaticImages._000_error_h32bit_16;
labelError.Text = msg;
tableLayoutPanelError.Visible = true;
}
#region Event handler
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var spacePerSr = new Dictionary<SR, long>();
foreach (var pbd in Connection.Cache.PBDs)
{
if (pbd.SR == null)
continue;
var sr = Connection.Resolve(pbd.SR);
if (sr == null || sr.IsDetached() || !sr.Show(XenAdminConfigManager.Provider.ShowHiddenVMs))
continue;
if (sr.content_type.ToLower() == "iso" || sr.type.ToLower() == "iso")
continue;
var hosts = Connection.Cache.Hosts;
if (hosts.Any(h => !sr.CanBeSeenFrom(h)))
continue;
var reservedSpace = ConversionClient.GetReservedDiskSpace(sr.uuid);
var srFreeSpace = sr.FreeSpace();
if (srFreeSpace > reservedSpace)
spacePerSr[sr] = srFreeSpace - reservedSpace;
}
e.Result = spacePerSr;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Dictionary<SR, long> spacePerSr;
if (e.Cancelled)
{
tableLayoutPanelError.Visible = false;
}
else if (e.Error != null)
{
ShowError(Messages.CONVERSION_STORAGE_PAGE_QUERYING_SRS_FAILURE);
}
else if ((spacePerSr = e.Result as Dictionary<SR, long>) != null && spacePerSr.Count > 0)
{
tableLayoutPanelError.Visible = false;
foreach (var kvp in spacePerSr)
{
var sr = kvp.Key;
var wrapper = new SrWrapper(sr, kvp.Value);
comboBoxSr.Items.Add(wrapper);
if (SelectedSR != null && SelectedSR.uuid == sr.uuid)
comboBoxSr.SelectedItem = wrapper;
else if (SelectedSR == null && SR.IsDefaultSr(sr))
comboBoxSr.SelectedItem = wrapper;
}
}
else if (spacePerSr != null)
{
ShowError(Messages.CONVERSION_STORAGE_PAGE_QUERYING_SRS_EMPTY);
}
buttonRefresh.Enabled = true;
}
private void buttonRefresh_Click(object sender, EventArgs e)
{
RebuildSrList();
}
private void comboBoxSr_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBoxSr.SelectedItem is SrWrapper wrapper)
{
SelectedSR = wrapper.item;
if (wrapper.AvailableSpace >= _requiredDiskSize)
tableLayoutPanelError.Visible = false;
else
ShowError(Messages.CONVERSION_STORAGE_PAGE_SR_TOO_SMALL);
}
UpdatePieChart();
UpdateButtons();
}
#endregion
#region Nested Items
private class SrWrapper : ToStringWrapper<SR>
{
public readonly long AvailableSpace;
public SrWrapper(SR sr, long availableSpace)
: base(sr, $"{sr.Name()}, {Util.DiskSizeString(availableSpace)} {Messages.AVAILABLE}")
{
AvailableSpace = availableSpace;
}
}
#endregion
}
}
| |
using System;
using NBitcoin.BouncyCastle.Crypto.Generators;
using NBitcoin.BouncyCastle.Crypto.Parameters;
using NBitcoin.BouncyCastle.Crypto.Utilities;
namespace NBitcoin.BouncyCastle.Crypto.Macs
{
/// <summary>
/// Poly1305 message authentication code, designed by D. J. Bernstein.
/// </summary>
/// <remarks>
/// Poly1305 computes a 128-bit (16 bytes) authenticator, using a 128 bit nonce and a 256 bit key
/// consisting of a 128 bit key applied to an underlying cipher, and a 128 bit key (with 106
/// effective key bits) used in the authenticator.
///
/// The polynomial calculation in this implementation is adapted from the public domain <a
/// href="https://github.com/floodyberry/poly1305-donna">poly1305-donna-unrolled</a> C implementation
/// by Andrew M (@floodyberry).
/// </remarks>
/// <seealso cref="NBitcoin.BouncyCastle.Crypto.Generators.Poly1305KeyGenerator"/>
public class Poly1305
: IMac
{
private const int BLOCK_SIZE = 16;
private readonly IBlockCipher cipher;
private readonly byte[] singleByte = new byte[1];
// Initialised state
/** Polynomial key */
private uint r0, r1, r2, r3, r4;
/** Precomputed 5 * r[1..4] */
private uint s1, s2, s3, s4;
/** Encrypted nonce */
private uint k0, k1, k2, k3;
// Accumulating state
/** Current block of buffered input */
private byte[] currentBlock = new byte[BLOCK_SIZE];
/** Current offset in input buffer */
private int currentBlockOffset = 0;
/** Polynomial accumulator */
private uint h0, h1, h2, h3, h4;
/**
* Constructs a Poly1305 MAC, where the key passed to init() will be used directly.
*/
public Poly1305()
{
this.cipher = null;
}
/**
* Constructs a Poly1305 MAC, using a 128 bit block cipher.
*/
public Poly1305(IBlockCipher cipher)
{
if (cipher.GetBlockSize() != BLOCK_SIZE)
{
throw new ArgumentException("Poly1305 requires a 128 bit block cipher.");
}
this.cipher = cipher;
}
/// <summary>
/// Initialises the Poly1305 MAC.
/// </summary>
/// <param name="parameters">a {@link ParametersWithIV} containing a 128 bit nonce and a {@link KeyParameter} with
/// a 256 bit key complying to the {@link Poly1305KeyGenerator Poly1305 key format}.</param>
public void Init(ICipherParameters parameters)
{
byte[] nonce = null;
if (cipher != null)
{
if (!(parameters is ParametersWithIV))
throw new ArgumentException("Poly1305 requires an IV when used with a block cipher.", "parameters");
ParametersWithIV ivParams = (ParametersWithIV)parameters;
nonce = ivParams.GetIV();
parameters = ivParams.Parameters;
}
if (!(parameters is KeyParameter))
throw new ArgumentException("Poly1305 requires a key.");
KeyParameter keyParams = (KeyParameter)parameters;
SetKey(keyParams.GetKey(), nonce);
Reset();
}
private void SetKey(byte[] key, byte[] nonce)
{
if (cipher != null && (nonce == null || nonce.Length != BLOCK_SIZE))
throw new ArgumentException("Poly1305 requires a 128 bit IV.");
Poly1305KeyGenerator.CheckKey(key);
// Extract r portion of key
uint t0 = Pack.LE_To_UInt32(key, BLOCK_SIZE + 0);
uint t1 = Pack.LE_To_UInt32(key, BLOCK_SIZE + 4);
uint t2 = Pack.LE_To_UInt32(key, BLOCK_SIZE + 8);
uint t3 = Pack.LE_To_UInt32(key, BLOCK_SIZE + 12);
r0 = t0 & 0x3ffffff; t0 >>= 26; t0 |= t1 << 6;
r1 = t0 & 0x3ffff03; t1 >>= 20; t1 |= t2 << 12;
r2 = t1 & 0x3ffc0ff; t2 >>= 14; t2 |= t3 << 18;
r3 = t2 & 0x3f03fff; t3 >>= 8;
r4 = t3 & 0x00fffff;
// Precompute multipliers
s1 = r1 * 5;
s2 = r2 * 5;
s3 = r3 * 5;
s4 = r4 * 5;
byte[] kBytes;
if (cipher == null)
{
kBytes = key;
}
else
{
// Compute encrypted nonce
kBytes = new byte[BLOCK_SIZE];
cipher.Init(true, new KeyParameter(key, 0, BLOCK_SIZE));
cipher.ProcessBlock(nonce, 0, kBytes, 0);
}
k0 = Pack.LE_To_UInt32(kBytes, 0);
k1 = Pack.LE_To_UInt32(kBytes, 4);
k2 = Pack.LE_To_UInt32(kBytes, 8);
k3 = Pack.LE_To_UInt32(kBytes, 12);
}
public string AlgorithmName
{
get { return cipher == null ? "Poly1305" : "Poly1305-" + cipher.AlgorithmName; }
}
public int GetMacSize()
{
return BLOCK_SIZE;
}
public void Update(byte input)
{
singleByte[0] = input;
BlockUpdate(singleByte, 0, 1);
}
public void BlockUpdate(byte[] input, int inOff, int len)
{
int copied = 0;
while (len > copied)
{
if (currentBlockOffset == BLOCK_SIZE)
{
processBlock();
currentBlockOffset = 0;
}
int toCopy = System.Math.Min((len - copied), BLOCK_SIZE - currentBlockOffset);
Array.Copy(input, copied + inOff, currentBlock, currentBlockOffset, toCopy);
copied += toCopy;
currentBlockOffset += toCopy;
}
}
private void processBlock()
{
if (currentBlockOffset < BLOCK_SIZE)
{
currentBlock[currentBlockOffset] = 1;
for (int i = currentBlockOffset + 1; i < BLOCK_SIZE; i++)
{
currentBlock[i] = 0;
}
}
ulong t0 = Pack.LE_To_UInt32(currentBlock, 0);
ulong t1 = Pack.LE_To_UInt32(currentBlock, 4);
ulong t2 = Pack.LE_To_UInt32(currentBlock, 8);
ulong t3 = Pack.LE_To_UInt32(currentBlock, 12);
h0 += (uint)(t0 & 0x3ffffffU);
h1 += (uint)((((t1 << 32) | t0) >> 26) & 0x3ffffff);
h2 += (uint)((((t2 << 32) | t1) >> 20) & 0x3ffffff);
h3 += (uint)((((t3 << 32) | t2) >> 14) & 0x3ffffff);
h4 += (uint)(t3 >> 8);
if (currentBlockOffset == BLOCK_SIZE)
{
h4 += (1 << 24);
}
ulong tp0 = mul32x32_64(h0,r0) + mul32x32_64(h1,s4) + mul32x32_64(h2,s3) + mul32x32_64(h3,s2) + mul32x32_64(h4,s1);
ulong tp1 = mul32x32_64(h0,r1) + mul32x32_64(h1,r0) + mul32x32_64(h2,s4) + mul32x32_64(h3,s3) + mul32x32_64(h4,s2);
ulong tp2 = mul32x32_64(h0,r2) + mul32x32_64(h1,r1) + mul32x32_64(h2,r0) + mul32x32_64(h3,s4) + mul32x32_64(h4,s3);
ulong tp3 = mul32x32_64(h0,r3) + mul32x32_64(h1,r2) + mul32x32_64(h2,r1) + mul32x32_64(h3,r0) + mul32x32_64(h4,s4);
ulong tp4 = mul32x32_64(h0,r4) + mul32x32_64(h1,r3) + mul32x32_64(h2,r2) + mul32x32_64(h3,r1) + mul32x32_64(h4,r0);
ulong b;
h0 = (uint)tp0 & 0x3ffffff; b = (tp0 >> 26);
tp1 += b; h1 = (uint)tp1 & 0x3ffffff; b = (tp1 >> 26);
tp2 += b; h2 = (uint)tp2 & 0x3ffffff; b = (tp2 >> 26);
tp3 += b; h3 = (uint)tp3 & 0x3ffffff; b = (tp3 >> 26);
tp4 += b; h4 = (uint)tp4 & 0x3ffffff; b = (tp4 >> 26);
h0 += (uint)(b * 5);
}
public int DoFinal(byte[] output, int outOff)
{
if (outOff + BLOCK_SIZE > output.Length)
{
throw new DataLengthException("Output buffer is too short.");
}
if (currentBlockOffset > 0)
{
// Process padded block
processBlock();
}
ulong f0, f1, f2, f3;
uint b = h0 >> 26;
h0 = h0 & 0x3ffffff;
h1 += b; b = h1 >> 26; h1 = h1 & 0x3ffffff;
h2 += b; b = h2 >> 26; h2 = h2 & 0x3ffffff;
h3 += b; b = h3 >> 26; h3 = h3 & 0x3ffffff;
h4 += b; b = h4 >> 26; h4 = h4 & 0x3ffffff;
h0 += b * 5;
uint g0, g1, g2, g3, g4;
g0 = h0 + 5; b = g0 >> 26; g0 &= 0x3ffffff;
g1 = h1 + b; b = g1 >> 26; g1 &= 0x3ffffff;
g2 = h2 + b; b = g2 >> 26; g2 &= 0x3ffffff;
g3 = h3 + b; b = g3 >> 26; g3 &= 0x3ffffff;
g4 = h4 + b - (1 << 26);
b = (g4 >> 31) - 1;
uint nb = ~b;
h0 = (h0 & nb) | (g0 & b);
h1 = (h1 & nb) | (g1 & b);
h2 = (h2 & nb) | (g2 & b);
h3 = (h3 & nb) | (g3 & b);
h4 = (h4 & nb) | (g4 & b);
f0 = ((h0 ) | (h1 << 26)) + (ulong)k0;
f1 = ((h1 >> 6 ) | (h2 << 20)) + (ulong)k1;
f2 = ((h2 >> 12) | (h3 << 14)) + (ulong)k2;
f3 = ((h3 >> 18) | (h4 << 8 )) + (ulong)k3;
Pack.UInt32_To_LE((uint)f0, output, outOff);
f1 += (f0 >> 32);
Pack.UInt32_To_LE((uint)f1, output, outOff + 4);
f2 += (f1 >> 32);
Pack.UInt32_To_LE((uint)f2, output, outOff + 8);
f3 += (f2 >> 32);
Pack.UInt32_To_LE((uint)f3, output, outOff + 12);
Reset();
return BLOCK_SIZE;
}
public void Reset()
{
currentBlockOffset = 0;
h0 = h1 = h2 = h3 = h4 = 0;
}
private static ulong mul32x32_64(uint i1, uint i2)
{
return ((ulong)i1) * i2;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using NUnit.Framework;
using Umbraco.Core;
using Umbraco.Core.Dynamics;
using Umbraco.Core.Models;
using Umbraco.Core.Models.PublishedContent;
using Umbraco.Tests.TestHelpers;
using Umbraco.Web;
namespace Umbraco.Tests.PublishedContent
{
/// <summary>
/// Unit tests for IPublishedContent and extensions
/// </summary>
[TestFixture]
public class PublishedContentDataTableTests : BaseRoutingTest
{
public override void Initialize()
{
base.Initialize();
// need to specify a custom callback for unit tests
// AutoPublishedContentTypes generates properties automatically
var type = new AutoPublishedContentType(0, "anything", new PublishedPropertyType[] {});
PublishedContentType.GetPublishedContentTypeCallback = (alias) => type;
// need to specify a different callback for testing
PublishedContentExtensions.GetPropertyAliasesAndNames = s =>
{
var userFields = new Dictionary<string, string>()
{
{"property1", "Property 1"},
{"property2", "Property 2"}
};
if (s == "Child")
{
userFields.Add("property4", "Property 4");
}
else
{
userFields.Add("property3", "Property 3");
}
//ensure the standard fields are there
var allFields = new Dictionary<string, string>()
{
{"Id", "Id"},
{"NodeName", "NodeName"},
{"NodeTypeAlias", "NodeTypeAlias"},
{"CreateDate", "CreateDate"},
{"UpdateDate", "UpdateDate"},
{"CreatorName", "CreatorName"},
{"WriterName", "WriterName"},
{"Url", "Url"}
};
foreach (var f in userFields.Where(f => !allFields.ContainsKey(f.Key)))
{
allFields.Add(f.Key, f.Value);
}
return allFields;
};
var routingContext = GetRoutingContext("/test");
//set the UmbracoContext.Current since the extension methods rely on it
UmbracoContext.Current = routingContext.UmbracoContext;
}
public override void TearDown()
{
base.TearDown();
Umbraco.Web.PublishedContentExtensions.GetPropertyAliasesAndNames = null;
UmbracoContext.Current = null;
}
[Test]
public void To_DataTable()
{
var doc = GetContent(true, 1);
var dt = doc.ChildrenAsTable();
Assert.AreEqual(11, dt.Columns.Count);
Assert.AreEqual(3, dt.Rows.Count);
Assert.AreEqual("value4", dt.Rows[0]["Property 1"]);
Assert.AreEqual("value5", dt.Rows[0]["Property 2"]);
Assert.AreEqual("value6", dt.Rows[0]["Property 4"]);
Assert.AreEqual("value7", dt.Rows[1]["Property 1"]);
Assert.AreEqual("value8", dt.Rows[1]["Property 2"]);
Assert.AreEqual("value9", dt.Rows[1]["Property 4"]);
Assert.AreEqual("value10", dt.Rows[2]["Property 1"]);
Assert.AreEqual("value11", dt.Rows[2]["Property 2"]);
Assert.AreEqual("value12", dt.Rows[2]["Property 4"]);
}
[Test]
public void To_DataTable_With_Filter()
{
var doc = GetContent(true, 1);
//change a doc type alias
((TestPublishedContent) doc.Children.ElementAt(0)).DocumentTypeAlias = "DontMatch";
var dt = doc.ChildrenAsTable("Child");
Assert.AreEqual(11, dt.Columns.Count);
Assert.AreEqual(2, dt.Rows.Count);
Assert.AreEqual("value7", dt.Rows[0]["Property 1"]);
Assert.AreEqual("value8", dt.Rows[0]["Property 2"]);
Assert.AreEqual("value9", dt.Rows[0]["Property 4"]);
Assert.AreEqual("value10", dt.Rows[1]["Property 1"]);
Assert.AreEqual("value11", dt.Rows[1]["Property 2"]);
Assert.AreEqual("value12", dt.Rows[1]["Property 4"]);
}
[Test]
public void To_DataTable_No_Rows()
{
var doc = GetContent(false, 1);
var dt = doc.ChildrenAsTable();
//will return an empty data table
Assert.AreEqual(0, dt.Columns.Count);
Assert.AreEqual(0, dt.Rows.Count);
}
private IPublishedContent GetContent(bool createChildren, int indexVals)
{
var contentTypeAlias = createChildren ? "Parent" : "Child";
var d = new TestPublishedContent
{
CreateDate = DateTime.Now,
CreatorId = 1,
CreatorName = "Shannon",
DocumentTypeAlias = contentTypeAlias,
DocumentTypeId = 2,
Id = 3,
SortOrder = 4,
TemplateId = 5,
UpdateDate = DateTime.Now,
Path = "-1,3",
UrlName = "home-page",
Name = "Page" + Guid.NewGuid().ToString(),
Version = Guid.NewGuid(),
WriterId = 1,
WriterName = "Shannon",
Parent = null,
Level = 1,
Properties = new Collection<IPublishedProperty>(
new List<IPublishedProperty>()
{
new PropertyResult("property1", "value" + indexVals, PropertyResultType.UserProperty),
new PropertyResult("property2", "value" + (indexVals + 1), PropertyResultType.UserProperty)
}),
Children = new List<IPublishedContent>()
};
if (createChildren)
{
d.Children = new List<IPublishedContent>()
{
GetContent(false, indexVals + 3),
GetContent(false, indexVals + 6),
GetContent(false, indexVals + 9)
};
}
if (!createChildren)
{
//create additional columns, used to test the different columns for child nodes
d.Properties.Add(new PropertyResult("property4", "value" + (indexVals + 2), PropertyResultType.UserProperty));
}
else
{
d.Properties.Add(new PropertyResult("property3", "value" + (indexVals + 2), PropertyResultType.UserProperty));
}
return d;
}
// note - could probably rewrite those tests using SolidPublishedContentCache
// l8tr...
private class TestPublishedContent : IPublishedContent
{
public string Url { get; set; }
public PublishedItemType ItemType { get; set; }
IPublishedContent IPublishedContent.Parent
{
get { return Parent; }
}
IEnumerable<IPublishedContent> IPublishedContent.Children
{
get { return Children; }
}
public IPublishedContent Parent { get; set; }
public int Id { get; set; }
public int TemplateId { get; set; }
public int SortOrder { get; set; }
public string Name { get; set; }
public string UrlName { get; set; }
public string DocumentTypeAlias { get; set; }
public int DocumentTypeId { get; set; }
public string WriterName { get; set; }
public string CreatorName { get; set; }
public int WriterId { get; set; }
public int CreatorId { get; set; }
public string Path { get; set; }
public DateTime CreateDate { get; set; }
public DateTime UpdateDate { get; set; }
public Guid Version { get; set; }
public int Level { get; set; }
public bool IsDraft { get; set; }
public int GetIndex() { throw new NotImplementedException();}
public ICollection<IPublishedProperty> Properties { get; set; }
public object this[string propertyAlias]
{
get { return GetProperty(propertyAlias).Value; }
}
public IEnumerable<IPublishedContent> Children { get; set; }
public IPublishedProperty GetProperty(string alias)
{
return Properties.FirstOrDefault(x => x.PropertyTypeAlias.InvariantEquals(alias));
}
public IPublishedProperty GetProperty(string alias, bool recurse)
{
var property = GetProperty(alias);
if (recurse == false) return property;
IPublishedContent content = this;
while (content != null && (property == null || property.HasValue == false))
{
content = content.Parent;
property = content == null ? null : content.GetProperty(alias);
}
return property;
}
public IEnumerable<IPublishedContent> ContentSet
{
get { throw new NotImplementedException(); }
}
public PublishedContentType ContentType
{
get { throw new NotImplementedException(); }
}
}
}
}
| |
namespace AsposeCloudSdkExamples
{
partial class FormStorageExamples
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.textBox1 = new System.Windows.Forms.TextBox();
this.panel1 = new System.Windows.Forms.Panel();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.txtPath = new System.Windows.Forms.TextBox();
this.txtFileName = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.buttonSelectFile = new System.Windows.Forms.Button();
this.txtSelectFile = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.panel2 = new System.Windows.Forms.Panel();
this.linkDeleteFile = new System.Windows.Forms.LinkLabel();
this.linkDownloadFile = new System.Windows.Forms.LinkLabel();
this.linkUploadFile = new System.Windows.Forms.LinkLabel();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.linkFileExist = new System.Windows.Forms.LinkLabel();
this.linkDeleteFolder = new System.Windows.Forms.LinkLabel();
this.linkCreateFolder = new System.Windows.Forms.LinkLabel();
this.linkFilesList = new System.Windows.Forms.LinkLabel();
this.linkDiskUsage = new System.Windows.Forms.LinkLabel();
this.tableLayoutPanel1.SuspendLayout();
this.panel1.SuspendLayout();
this.panel2.SuspendLayout();
this.SuspendLayout();
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.ColumnCount = 1;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 20F));
this.tableLayoutPanel1.Controls.Add(this.textBox1, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.panel1, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.panel2, 0, 2);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 3;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 16.66667F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 23.77049F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 59.28962F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(973, 447);
this.tableLayoutPanel1.TabIndex = 0;
//
// textBox1
//
this.textBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.textBox1.Location = new System.Drawing.Point(3, 3);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.ReadOnly = true;
this.textBox1.Size = new System.Drawing.Size(967, 68);
this.textBox1.TabIndex = 0;
//
// panel1
//
this.panel1.Controls.Add(this.label5);
this.panel1.Controls.Add(this.label4);
this.panel1.Controls.Add(this.txtPath);
this.panel1.Controls.Add(this.txtFileName);
this.panel1.Controls.Add(this.label3);
this.panel1.Controls.Add(this.label2);
this.panel1.Controls.Add(this.buttonSelectFile);
this.panel1.Controls.Add(this.txtSelectFile);
this.panel1.Controls.Add(this.label1);
this.panel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel1.Location = new System.Drawing.Point(3, 77);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(967, 100);
this.panel1.TabIndex = 3;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(510, 69);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(452, 13);
this.label5.TabIndex = 10;
this.label5.Text = "Path of the cloud strage folder e.g. Folder1 or Folder1/SubFolder1. Leave empty f" +
"or root folder.";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(510, 43);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(225, 13);
this.label4.TabIndex = 9;
this.label4.Text = "Enter name of the file if file is already uploaded";
//
// txtPath
//
this.txtPath.Location = new System.Drawing.Point(96, 66);
this.txtPath.Name = "txtPath";
this.txtPath.Size = new System.Drawing.Size(408, 20);
this.txtPath.TabIndex = 8;
//
// txtFileName
//
this.txtFileName.Location = new System.Drawing.Point(96, 40);
this.txtFileName.Name = "txtFileName";
this.txtFileName.Size = new System.Drawing.Size(408, 20);
this.txtFileName.TabIndex = 7;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(23, 43);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(54, 13);
this.label3.TabIndex = 6;
this.label3.Text = "File Name";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(23, 69);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(69, 13);
this.label2.TabIndex = 5;
this.label2.Text = "Storage Path";
//
// buttonSelectFile
//
this.buttonSelectFile.Location = new System.Drawing.Point(510, 12);
this.buttonSelectFile.Name = "buttonSelectFile";
this.buttonSelectFile.Size = new System.Drawing.Size(105, 23);
this.buttonSelectFile.TabIndex = 4;
this.buttonSelectFile.Text = "Browse";
this.buttonSelectFile.UseVisualStyleBackColor = true;
this.buttonSelectFile.Click += new System.EventHandler(this.buttonSelectFile_Click);
//
// txtSelectFile
//
this.txtSelectFile.BackColor = System.Drawing.SystemColors.Window;
this.txtSelectFile.Location = new System.Drawing.Point(96, 14);
this.txtSelectFile.Name = "txtSelectFile";
this.txtSelectFile.ReadOnly = true;
this.txtSelectFile.Size = new System.Drawing.Size(408, 20);
this.txtSelectFile.TabIndex = 3;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(23, 17);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(56, 13);
this.label1.TabIndex = 2;
this.label1.Text = "Select File";
//
// panel2
//
this.panel2.Controls.Add(this.linkDiskUsage);
this.panel2.Controls.Add(this.linkFilesList);
this.panel2.Controls.Add(this.linkCreateFolder);
this.panel2.Controls.Add(this.linkDeleteFolder);
this.panel2.Controls.Add(this.linkFileExist);
this.panel2.Controls.Add(this.linkDeleteFile);
this.panel2.Controls.Add(this.linkDownloadFile);
this.panel2.Controls.Add(this.linkUploadFile);
this.panel2.Dock = System.Windows.Forms.DockStyle.Fill;
this.panel2.Location = new System.Drawing.Point(3, 183);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(967, 261);
this.panel2.TabIndex = 4;
//
// linkDeleteFile
//
this.linkDeleteFile.AutoSize = true;
this.linkDeleteFile.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.linkDeleteFile.Location = new System.Drawing.Point(23, 94);
this.linkDeleteFile.Name = "linkDeleteFile";
this.linkDeleteFile.Size = new System.Drawing.Size(241, 16);
this.linkDeleteFile.TabIndex = 3;
this.linkDeleteFile.TabStop = true;
this.linkDeleteFile.Text = "Delete File from Aspose Cloud Storage";
this.linkDeleteFile.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkDeleteFile_LinkClicked);
//
// linkDownloadFile
//
this.linkDownloadFile.AutoSize = true;
this.linkDownloadFile.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.linkDownloadFile.Location = new System.Drawing.Point(23, 64);
this.linkDownloadFile.Name = "linkDownloadFile";
this.linkDownloadFile.Size = new System.Drawing.Size(262, 16);
this.linkDownloadFile.TabIndex = 2;
this.linkDownloadFile.TabStop = true;
this.linkDownloadFile.Text = "Download File from Aspose Cloud Storage";
this.linkDownloadFile.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkDownloadFile_LinkClicked);
//
// linkUploadFile
//
this.linkUploadFile.AutoSize = true;
this.linkUploadFile.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.linkUploadFile.Location = new System.Drawing.Point(23, 32);
this.linkUploadFile.Name = "linkUploadFile";
this.linkUploadFile.Size = new System.Drawing.Size(227, 16);
this.linkUploadFile.TabIndex = 1;
this.linkUploadFile.TabStop = true;
this.linkUploadFile.Text = "Upload File to Aspose Clour Storage";
this.linkUploadFile.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkUploadFile_LinkClicked);
//
// openFileDialog1
//
this.openFileDialog1.FileName = "openFileDialog1";
this.openFileDialog1.FileOk += new System.ComponentModel.CancelEventHandler(this.openFileDialog1_FileOk);
//
// linkFileExist
//
this.linkFileExist.AutoSize = true;
this.linkFileExist.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.linkFileExist.Location = new System.Drawing.Point(23, 127);
this.linkFileExist.Name = "linkFileExist";
this.linkFileExist.Size = new System.Drawing.Size(275, 16);
this.linkFileExist.TabIndex = 4;
this.linkFileExist.TabStop = true;
this.linkFileExist.Text = "Check if File Exists on Aspose Cloud Storage";
this.linkFileExist.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkFileExist_LinkClicked);
//
// linkDeleteFolder
//
this.linkDeleteFolder.AutoSize = true;
this.linkDeleteFolder.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.linkDeleteFolder.Location = new System.Drawing.Point(394, 127);
this.linkDeleteFolder.Name = "linkDeleteFolder";
this.linkDeleteFolder.Size = new System.Drawing.Size(258, 16);
this.linkDeleteFolder.TabIndex = 5;
this.linkDeleteFolder.TabStop = true;
this.linkDeleteFolder.Text = "Delete Folder from Aspose Cloud Storage";
this.linkDeleteFolder.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkDeleteFolder_LinkClicked);
//
// linkCreateFolder
//
this.linkCreateFolder.AutoSize = true;
this.linkCreateFolder.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.linkCreateFolder.Location = new System.Drawing.Point(394, 94);
this.linkCreateFolder.Name = "linkCreateFolder";
this.linkCreateFolder.Size = new System.Drawing.Size(274, 16);
this.linkCreateFolder.TabIndex = 6;
this.linkCreateFolder.TabStop = true;
this.linkCreateFolder.Text = "Create new Folder on Aspose Cloud Storage";
this.linkCreateFolder.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkCreateFolder_LinkClicked);
//
// linkFilesList
//
this.linkFilesList.AutoSize = true;
this.linkFilesList.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.linkFilesList.Location = new System.Drawing.Point(394, 64);
this.linkFilesList.Name = "linkFilesList";
this.linkFilesList.Size = new System.Drawing.Size(266, 16);
this.linkFilesList.TabIndex = 7;
this.linkFilesList.TabStop = true;
this.linkFilesList.Text = "Get List of Files from Aspose Cloud Storage";
this.linkFilesList.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkFilesList_LinkClicked);
//
// linkDiskUsage
//
this.linkDiskUsage.AutoSize = true;
this.linkDiskUsage.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.linkDiskUsage.Location = new System.Drawing.Point(394, 32);
this.linkDiskUsage.Name = "linkDiskUsage";
this.linkDiskUsage.Size = new System.Drawing.Size(243, 16);
this.linkDiskUsage.TabIndex = 8;
this.linkDiskUsage.TabStop = true;
this.linkDiskUsage.Text = "Check Usage of Aspose Cloud Storage";
this.linkDiskUsage.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkDiskUsage_LinkClicked);
//
// FormStorageExamples
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(973, 447);
this.Controls.Add(this.tableLayoutPanel1);
this.Name = "FormStorageExamples";
this.Text = "Storage Examples";
this.Load += new System.EventHandler(this.FormStorageExamples_Load);
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Button buttonSelectFile;
private System.Windows.Forms.TextBox txtSelectFile;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox txtPath;
private System.Windows.Forms.TextBox txtFileName;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.LinkLabel linkDeleteFile;
private System.Windows.Forms.LinkLabel linkDownloadFile;
private System.Windows.Forms.LinkLabel linkUploadFile;
private System.Windows.Forms.LinkLabel linkFileExist;
private System.Windows.Forms.LinkLabel linkDiskUsage;
private System.Windows.Forms.LinkLabel linkFilesList;
private System.Windows.Forms.LinkLabel linkCreateFolder;
private System.Windows.Forms.LinkLabel linkDeleteFolder;
}
}
| |
// 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.IO;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Http
{
public class HttpClient : HttpMessageInvoker
{
#region Fields
private static readonly TimeSpan s_defaultTimeout = TimeSpan.FromSeconds(100);
private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue);
private static readonly TimeSpan s_infiniteTimeout = Threading.Timeout.InfiniteTimeSpan;
private const HttpCompletionOption defaultCompletionOption = HttpCompletionOption.ResponseContentRead;
private volatile bool _operationStarted;
private volatile bool _disposed;
private CancellationTokenSource _pendingRequestsCts;
private HttpRequestHeaders _defaultRequestHeaders;
private Uri _baseAddress;
private TimeSpan _timeout;
private int _maxResponseContentBufferSize;
#endregion Fields
#region Properties
public HttpRequestHeaders DefaultRequestHeaders
{
get
{
if (_defaultRequestHeaders == null)
{
_defaultRequestHeaders = new HttpRequestHeaders();
}
return _defaultRequestHeaders;
}
}
public Uri BaseAddress
{
get { return _baseAddress; }
set
{
CheckBaseAddress(value, nameof(value));
CheckDisposedOrStarted();
if (NetEventSource.IsEnabled) NetEventSource.UriBaseAddress(this, value);
_baseAddress = value;
}
}
public TimeSpan Timeout
{
get { return _timeout; }
set
{
if (value != s_infiniteTimeout && (value <= TimeSpan.Zero || value > s_maxTimeout))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
CheckDisposedOrStarted();
_timeout = value;
}
}
public long MaxResponseContentBufferSize
{
get { return _maxResponseContentBufferSize; }
set
{
if (value <= 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
if (value > HttpContent.MaxBufferSize)
{
throw new ArgumentOutOfRangeException(nameof(value), value,
string.Format(System.Globalization.CultureInfo.InvariantCulture,
SR.net_http_content_buffersize_limit, HttpContent.MaxBufferSize));
}
CheckDisposedOrStarted();
Debug.Assert(HttpContent.MaxBufferSize <= int.MaxValue);
_maxResponseContentBufferSize = (int)value;
}
}
#endregion Properties
#region Constructors
public HttpClient()
: this(new HttpClientHandler())
{
}
public HttpClient(HttpMessageHandler handler)
: this(handler, true)
{
}
public HttpClient(HttpMessageHandler handler, bool disposeHandler)
: base(handler, disposeHandler)
{
if (NetEventSource.IsEnabled) NetEventSource.Enter(this, handler);
_timeout = s_defaultTimeout;
_maxResponseContentBufferSize = HttpContent.MaxBufferSize;
_pendingRequestsCts = new CancellationTokenSource();
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
#endregion Constructors
#region Public Send
#region Simple Get Overloads
public Task<string> GetStringAsync(string requestUri) =>
GetStringAsync(CreateUri(requestUri));
public Task<string> GetStringAsync(Uri requestUri) =>
GetStringAsyncCore(GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead));
private async Task<string> GetStringAsyncCore(Task<HttpResponseMessage> getTask)
{
// Wait for the response message.
using (HttpResponseMessage responseMessage = await getTask.ConfigureAwait(false))
{
// Make sure it completed successfully.
responseMessage.EnsureSuccessStatusCode();
// Get the response content.
HttpContent c = responseMessage.Content;
if (c != null)
{
#if NET46
return await c.ReadAsStringAsync().ConfigureAwait(false);
#else
HttpContentHeaders headers = c.Headers;
// Since the underlying byte[] will never be exposed, we use an ArrayPool-backed
// stream to which we copy all of the data from the response.
using (Stream responseStream = c.TryReadAsStream() ?? await c.ReadAsStreamAsync().ConfigureAwait(false))
using (var buffer = new HttpContent.LimitArrayPoolWriteStream(_maxResponseContentBufferSize, (int)headers.ContentLength.GetValueOrDefault()))
{
await responseStream.CopyToAsync(buffer).ConfigureAwait(false);
if (buffer.Length > 0)
{
// Decode and return the data from the buffer.
return HttpContent.ReadBufferAsString(buffer.GetBuffer(), headers);
}
}
#endif
}
// No content to return.
return string.Empty;
}
}
public Task<byte[]> GetByteArrayAsync(string requestUri) =>
GetByteArrayAsync(CreateUri(requestUri));
public Task<byte[]> GetByteArrayAsync(Uri requestUri) =>
GetByteArrayAsyncCore(GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead));
private async Task<byte[]> GetByteArrayAsyncCore(Task<HttpResponseMessage> getTask)
{
// Wait for the response message.
using (HttpResponseMessage responseMessage = await getTask.ConfigureAwait(false))
{
// Make sure it completed successfully.
responseMessage.EnsureSuccessStatusCode();
// Get the response content.
HttpContent c = responseMessage.Content;
if (c != null)
{
#if NET46
return await c.ReadAsByteArrayAsync().ConfigureAwait(false);
#else
HttpContentHeaders headers = c.Headers;
using (Stream responseStream = c.TryReadAsStream() ?? await c.ReadAsStreamAsync().ConfigureAwait(false))
{
long? contentLength = headers.ContentLength;
Stream buffer; // declared here to share the state machine field across both if/else branches
if (contentLength.HasValue)
{
// If we got a content length, then we assume that it's correct and create a MemoryStream
// to which the content will be transferred. That way, assuming we actually get the exact
// amount we were expecting, we can simply return the MemoryStream's underlying buffer.
buffer = new HttpContent.LimitMemoryStream(_maxResponseContentBufferSize, (int)contentLength.GetValueOrDefault());
await responseStream.CopyToAsync(buffer).ConfigureAwait(false);
if (buffer.Length > 0)
{
return ((HttpContent.LimitMemoryStream)buffer).GetSizedBuffer();
}
}
else
{
// If we didn't get a content length, then we assume we're going to have to grow
// the buffer potentially several times and that it's unlikely the underlying buffer
// at the end will be the exact size needed, in which case it's more beneficial to use
// ArrayPool buffers and copy out to a new array at the end.
buffer = new HttpContent.LimitArrayPoolWriteStream(_maxResponseContentBufferSize);
try
{
await responseStream.CopyToAsync(buffer).ConfigureAwait(false);
if (buffer.Length > 0)
{
return ((HttpContent.LimitArrayPoolWriteStream)buffer).ToArray();
}
}
finally { buffer.Dispose(); }
}
}
#endif
}
// No content to return.
return Array.Empty<byte>();
}
}
// Unbuffered by default
public Task<Stream> GetStreamAsync(string requestUri)
{
return GetStreamAsync(CreateUri(requestUri));
}
// Unbuffered by default
public Task<Stream> GetStreamAsync(Uri requestUri)
{
return FinishGetStreamAsync(GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead));
}
private async Task<Stream> FinishGetStreamAsync(Task<HttpResponseMessage> getTask)
{
HttpResponseMessage response = await getTask.ConfigureAwait(false);
response.EnsureSuccessStatusCode();
HttpContent c = response.Content;
return c != null ?
(c.TryReadAsStream() ?? await c.ReadAsStreamAsync().ConfigureAwait(false)) :
Stream.Null;
}
#endregion Simple Get Overloads
#region REST Send Overloads
public Task<HttpResponseMessage> GetAsync(string requestUri)
{
return GetAsync(CreateUri(requestUri));
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri)
{
return GetAsync(requestUri, defaultCompletionOption);
}
public Task<HttpResponseMessage> GetAsync(string requestUri, HttpCompletionOption completionOption)
{
return GetAsync(CreateUri(requestUri), completionOption);
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri, HttpCompletionOption completionOption)
{
return GetAsync(requestUri, completionOption, CancellationToken.None);
}
public Task<HttpResponseMessage> GetAsync(string requestUri, CancellationToken cancellationToken)
{
return GetAsync(CreateUri(requestUri), cancellationToken);
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri, CancellationToken cancellationToken)
{
return GetAsync(requestUri, defaultCompletionOption, cancellationToken);
}
public Task<HttpResponseMessage> GetAsync(string requestUri, HttpCompletionOption completionOption,
CancellationToken cancellationToken)
{
return GetAsync(CreateUri(requestUri), completionOption, cancellationToken);
}
public Task<HttpResponseMessage> GetAsync(Uri requestUri, HttpCompletionOption completionOption,
CancellationToken cancellationToken)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Get, requestUri), completionOption, cancellationToken);
}
public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content)
{
return PostAsync(CreateUri(requestUri), content);
}
public Task<HttpResponseMessage> PostAsync(Uri requestUri, HttpContent content)
{
return PostAsync(requestUri, content, CancellationToken.None);
}
public Task<HttpResponseMessage> PostAsync(string requestUri, HttpContent content,
CancellationToken cancellationToken)
{
return PostAsync(CreateUri(requestUri), content, cancellationToken);
}
public Task<HttpResponseMessage> PostAsync(Uri requestUri, HttpContent content,
CancellationToken cancellationToken)
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri);
request.Content = content;
return SendAsync(request, cancellationToken);
}
public Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content)
{
return PutAsync(CreateUri(requestUri), content);
}
public Task<HttpResponseMessage> PutAsync(Uri requestUri, HttpContent content)
{
return PutAsync(requestUri, content, CancellationToken.None);
}
public Task<HttpResponseMessage> PutAsync(string requestUri, HttpContent content,
CancellationToken cancellationToken)
{
return PutAsync(CreateUri(requestUri), content, cancellationToken);
}
public Task<HttpResponseMessage> PutAsync(Uri requestUri, HttpContent content,
CancellationToken cancellationToken)
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, requestUri);
request.Content = content;
return SendAsync(request, cancellationToken);
}
public Task<HttpResponseMessage> PatchAsync(string requestUri, HttpContent content)
{
return PatchAsync(CreateUri(requestUri), content);
}
public Task<HttpResponseMessage> PatchAsync(Uri requestUri, HttpContent content)
{
return PatchAsync(requestUri, content, CancellationToken.None);
}
public Task<HttpResponseMessage> PatchAsync(string requestUri, HttpContent content,
CancellationToken cancellationToken)
{
return PatchAsync(CreateUri(requestUri), content, cancellationToken);
}
public Task<HttpResponseMessage> PatchAsync(Uri requestUri, HttpContent content,
CancellationToken cancellationToken)
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Patch, requestUri);
request.Content = content;
return SendAsync(request, cancellationToken);
}
public Task<HttpResponseMessage> DeleteAsync(string requestUri)
{
return DeleteAsync(CreateUri(requestUri));
}
public Task<HttpResponseMessage> DeleteAsync(Uri requestUri)
{
return DeleteAsync(requestUri, CancellationToken.None);
}
public Task<HttpResponseMessage> DeleteAsync(string requestUri, CancellationToken cancellationToken)
{
return DeleteAsync(CreateUri(requestUri), cancellationToken);
}
public Task<HttpResponseMessage> DeleteAsync(Uri requestUri, CancellationToken cancellationToken)
{
return SendAsync(new HttpRequestMessage(HttpMethod.Delete, requestUri), cancellationToken);
}
#endregion REST Send Overloads
#region Advanced Send Overloads
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request)
{
return SendAsync(request, defaultCompletionOption, CancellationToken.None);
}
public override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
return SendAsync(request, defaultCompletionOption, cancellationToken);
}
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption)
{
return SendAsync(request, completionOption, CancellationToken.None);
}
public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption,
CancellationToken cancellationToken)
{
if (request == null)
{
throw new ArgumentNullException(nameof(request));
}
CheckDisposed();
CheckRequestMessage(request);
SetOperationStarted();
PrepareRequestMessage(request);
// PrepareRequestMessage will resolve the request address against the base address.
// We need a CancellationTokenSource to use with the request. We always have the global
// _pendingRequestsCts to use, plus we may have a token provided by the caller, and we may
// have a timeout. If we have a timeout or a caller-provided token, we need to create a new
// CTS (we can't, for example, timeout the pending requests CTS, as that could cancel other
// unrelated operations). Otherwise, we can use the pending requests CTS directly.
CancellationTokenSource cts;
bool disposeCts;
bool hasTimeout = _timeout != s_infiniteTimeout;
if (hasTimeout || cancellationToken.CanBeCanceled)
{
disposeCts = true;
cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _pendingRequestsCts.Token);
if (hasTimeout)
{
cts.CancelAfter(_timeout);
}
}
else
{
disposeCts = false;
cts = _pendingRequestsCts;
}
// Initiate the send
Task<HttpResponseMessage> sendTask = base.SendAsync(request, cts.Token);
return completionOption == HttpCompletionOption.ResponseContentRead ?
FinishSendAsyncBuffered(sendTask, request, cts, disposeCts) :
FinishSendAsyncUnbuffered(sendTask, request, cts, disposeCts);
}
private async Task<HttpResponseMessage> FinishSendAsyncBuffered(
Task<HttpResponseMessage> sendTask, HttpRequestMessage request, CancellationTokenSource cts, bool disposeCts)
{
HttpResponseMessage response = null;
try
{
// Wait for the send request to complete, getting back the response.
response = await sendTask.ConfigureAwait(false);
if (response == null)
{
throw new InvalidOperationException(SR.net_http_handler_noresponse);
}
// Buffer the response content if we've been asked to and we have a Content to buffer.
if (response.Content != null)
{
await response.Content.LoadIntoBufferAsync(_maxResponseContentBufferSize).ConfigureAwait(false);
}
if (NetEventSource.IsEnabled) NetEventSource.ClientSendCompleted(this, response, request);
return response;
}
catch (Exception e)
{
response?.Dispose();
HandleFinishSendAsyncError(e, cts);
throw;
}
finally
{
HandleFinishSendAsyncCleanup(cts, disposeCts);
}
}
private async Task<HttpResponseMessage> FinishSendAsyncUnbuffered(
Task<HttpResponseMessage> sendTask, HttpRequestMessage request, CancellationTokenSource cts, bool disposeCts)
{
try
{
HttpResponseMessage response = await sendTask.ConfigureAwait(false);
if (response == null)
{
throw new InvalidOperationException(SR.net_http_handler_noresponse);
}
if (NetEventSource.IsEnabled) NetEventSource.ClientSendCompleted(this, response, request);
return response;
}
catch (Exception e)
{
HandleFinishSendAsyncError(e, cts);
throw;
}
finally
{
HandleFinishSendAsyncCleanup(cts, disposeCts);
}
}
private void HandleFinishSendAsyncError(Exception e, CancellationTokenSource cts)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, e);
// If the cancellation token was canceled, we consider the exception to be caused by the
// cancellation (e.g. WebException when reading from canceled response stream).
if (cts.IsCancellationRequested && e is HttpRequestException)
{
if (NetEventSource.IsEnabled) NetEventSource.Error(this, $"Canceled");
throw new OperationCanceledException(cts.Token);
}
}
private void HandleFinishSendAsyncCleanup(CancellationTokenSource cts, bool disposeCts)
{
// Dispose of the CancellationTokenSource if it was created specially for this request
// rather than being used across multiple requests.
if (disposeCts)
{
cts.Dispose();
}
// This method used to also dispose of the request content, e.g.:
// request.Content?.Dispose();
// This has multiple problems:
// 1. It prevents code from reusing request content objects for subsequent requests,
// as disposing of the object likely invalidates it for further use.
// 2. It prevents the possibility of partial or full duplex communication, even if supported
// by the handler, as the request content may still be in use even if the response
// (or response headers) has been received.
// By changing this to not dispose of the request content, disposal may end up being
// left for the finalizer to handle, or the developer can explicitly dispose of the
// content when they're done with it. But it allows request content to be reused,
// and more importantly it enables handlers that allow receiving of the response before
// fully sending the request. Prior to this change, a handler like CurlHandler would
// fail trying to access certain sites, if the site sent its response before it had
// completely received the request: CurlHandler might then find that the request content
// was disposed of while it still needed to read from it.
}
public void CancelPendingRequests()
{
CheckDisposed();
if (NetEventSource.IsEnabled) NetEventSource.Enter(this);
// With every request we link this cancellation token source.
CancellationTokenSource currentCts = Interlocked.Exchange(ref _pendingRequestsCts,
new CancellationTokenSource());
currentCts.Cancel();
currentCts.Dispose();
if (NetEventSource.IsEnabled) NetEventSource.Exit(this);
}
#endregion Advanced Send Overloads
#endregion Public Send
#region IDisposable Members
protected override void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
_disposed = true;
// Cancel all pending requests (if any). Note that we don't call CancelPendingRequests() but cancel
// the CTS directly. The reason is that CancelPendingRequests() would cancel the current CTS and create
// a new CTS. We don't want a new CTS in this case.
_pendingRequestsCts.Cancel();
_pendingRequestsCts.Dispose();
}
base.Dispose(disposing);
}
#endregion
#region Private Helpers
private void SetOperationStarted()
{
// This method flags the HttpClient instances as "active". I.e. we executed at least one request (or are
// in the process of doing so). This information is used to lock-down all property setters. Once a
// Send/SendAsync operation started, no property can be changed.
if (!_operationStarted)
{
_operationStarted = true;
}
}
private void CheckDisposedOrStarted()
{
CheckDisposed();
if (_operationStarted)
{
throw new InvalidOperationException(SR.net_http_operation_started);
}
}
private void CheckDisposed()
{
if (_disposed)
{
throw new ObjectDisposedException(GetType().ToString());
}
}
private static void CheckRequestMessage(HttpRequestMessage request)
{
if (!request.MarkAsSent())
{
throw new InvalidOperationException(SR.net_http_client_request_already_sent);
}
}
private void PrepareRequestMessage(HttpRequestMessage request)
{
Uri requestUri = null;
if ((request.RequestUri == null) && (_baseAddress == null))
{
throw new InvalidOperationException(SR.net_http_client_invalid_requesturi);
}
if (request.RequestUri == null)
{
requestUri = _baseAddress;
}
else
{
// If the request Uri is an absolute Uri, just use it. Otherwise try to combine it with the base Uri.
if (!request.RequestUri.IsAbsoluteUri)
{
if (_baseAddress == null)
{
throw new InvalidOperationException(SR.net_http_client_invalid_requesturi);
}
else
{
requestUri = new Uri(_baseAddress, request.RequestUri);
}
}
}
// We modified the original request Uri. Assign the new Uri to the request message.
if (requestUri != null)
{
request.RequestUri = requestUri;
}
// Add default headers
if (_defaultRequestHeaders != null)
{
request.Headers.AddHeaders(_defaultRequestHeaders);
}
}
private static void CheckBaseAddress(Uri baseAddress, string parameterName)
{
if (baseAddress == null)
{
return; // It's OK to not have a base address specified.
}
if (!baseAddress.IsAbsoluteUri)
{
throw new ArgumentException(SR.net_http_client_absolute_baseaddress_required, parameterName);
}
if (!HttpUtilities.IsHttpUri(baseAddress))
{
throw new ArgumentException(SR.net_http_client_http_baseaddress_required, parameterName);
}
}
private Uri CreateUri(String uri)
{
if (string.IsNullOrEmpty(uri))
{
return null;
}
return new Uri(uri, UriKind.RelativeOrAbsolute);
}
#endregion Private Helpers
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using NPOI.POIFS.Common;
using NPOI.POIFS.Dev;
using NPOI.POIFS.NIO;
using NPOI.POIFS.Properties;
using NPOI.POIFS.Storage;
using NPOI.Util;
using NPOI.POIFS.EventFileSystem;
namespace NPOI.POIFS.FileSystem
{
/**
* This is the main class of the POIFS system; it manages the entire
* life cycle of the filesystem.
* This is the new NIO version
*/
public class NPOIFSFileSystem : BlockStore, POIFSViewable , ICloseable
{
private static POILogger _logger =
POILogFactory.GetLogger(typeof(NPOIFSFileSystem));
/**
* Convenience method for clients that want to avoid the auto-close behaviour of the constructor.
*/
public static Stream CreateNonClosingInputStream(Stream stream)
{
return new CloseIgnoringInputStream(stream);
}
private NPOIFSMiniStore _mini_store;
private NPropertyTable _property_table;
private List<BATBlock> _xbat_blocks;
private List<BATBlock> _bat_blocks;
private HeaderBlock _header;
private DirectoryNode _root;
private DataSource _data;
/**
* What big block size the file uses. Most files
* use 512 bytes, but a few use 4096
*/
private POIFSBigBlockSize bigBlockSize =
POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS;
public DataSource Data
{
get { return _data; }
set { _data = value; }
}
private NPOIFSFileSystem(bool newFS)
{
_header = new HeaderBlock(bigBlockSize);
_property_table = new NPropertyTable(_header);
_mini_store = new NPOIFSMiniStore(this, _property_table.Root, new List<BATBlock>(), _header);
_xbat_blocks = new List<BATBlock>();
_bat_blocks = new List<BATBlock>();
_root = null;
if (newFS)
{
// Data needs to Initially hold just the header block,
// a single bat block, and an empty properties section
_data = new ByteArrayBackedDataSource(new byte[bigBlockSize.GetBigBlockSize() * 3]);
}
}
/**
* Constructor, intended for writing
*/
public NPOIFSFileSystem()
: this(true)
{
// Reserve block 0 for the start of the Properties Table
// Create a single empty BAT, at pop that at offset 1
_header.BATCount = 1;
_header.BATArray = new int[] { 1 };
BATBlock bb = BATBlock.CreateEmptyBATBlock(bigBlockSize, false);
bb.OurBlockIndex = 1;
_bat_blocks.Add(bb);
SetNextBlock(0, POIFSConstants.END_OF_CHAIN);
SetNextBlock(1, POIFSConstants.FAT_SECTOR_BLOCK);
_property_table.StartBlock = 0;
}
/**
* <p>Creates a POIFSFileSystem from a <tt>File</tt>. This uses less memory than
* creating from an <tt>InputStream</tt>. The File will be opened read-only</p>
*
* <p>Note that with this constructor, you will need to call {@link #close()}
* when you're done to have the underlying file closed, as the file is
* kept open during normal operation to read the data out.</p>
*
* @param file the File from which to read the data
*
* @exception IOException on errors reading, or on invalid data
*/
public NPOIFSFileSystem(FileInfo file)
: this(file, true)
{
}
/**
* <p>Creates a POIFSFileSystem from a <tt>File</tt>. This uses less memory than
* creating from an <tt>InputStream</tt>.</p>
*
* <p>Note that with this constructor, you will need to call {@link #close()}
* when you're done to have the underlying file closed, as the file is
* kept open during normal operation to read the data out.</p>
*
* @param file the File from which to read or read/write the data
* @param readOnly whether the POIFileSystem will only be used in read-only mode
*
* @exception IOException on errors reading, or on invalid data
*/
public NPOIFSFileSystem(FileInfo file, bool readOnly)
: this(null, file, readOnly, true)
{
;
}
/**
* <p>Creates a POIFSFileSystem from an open <tt>FileChannel</tt>. This uses
* less memory than creating from an <tt>InputStream</tt>. The stream will
* be used in read-only mode.</p>
*
* <p>Note that with this constructor, you will need to call {@link #close()}
* when you're done to have the underlying Channel closed, as the channel is
* kept open during normal operation to read the data out.</p>
*
* @param channel the FileChannel from which to read the data
*
* @exception IOException on errors reading, or on invalid data
*/
public NPOIFSFileSystem(FileStream channel)
: this(channel, true)
{
}
/**
* <p>Creates a POIFSFileSystem from an open <tt>FileChannel</tt>. This uses
* less memory than creating from an <tt>InputStream</tt>.</p>
*
* <p>Note that with this constructor, you will need to call {@link #close()}
* when you're done to have the underlying Channel closed, as the channel is
* kept open during normal operation to read the data out.</p>
*
* @param channel the FileChannel from which to read or read/write the data
* @param readOnly whether the POIFileSystem will only be used in read-only mode
*
* @exception IOException on errors reading, or on invalid data
*/
public NPOIFSFileSystem(FileStream channel, bool readOnly)
: this(channel, null, readOnly, false)
{
;
}
public NPOIFSFileSystem(FileStream channel, FileInfo srcFile, bool readOnly, bool closeChannelOnError)
: this(false)
{
try
{
// Initialize the datasource
if (srcFile != null)
{
if (srcFile.Length == 0)
throw new EmptyFileException();
//FileBackedDataSource d = new FileBackedDataSource(srcFile, readOnly);
channel = new FileStream(srcFile.FullName, FileMode.Open, FileAccess.Read);
_data = new FileBackedDataSource(channel, readOnly);
}
else
{
_data = new FileBackedDataSource(channel, readOnly);
}
try
{
// Get the header
byte[] headerBuffer = new byte[POIFSConstants.SMALLER_BIG_BLOCK_SIZE];
IOUtils.ReadFully(channel, headerBuffer);
// Have the header Processed
_header = new HeaderBlock(headerBuffer);
// Now process the various entries
//_data = new FileBackedDataSource(channel, readOnly);
ReadCoreContents();
}
catch (Exception)
{
throw;
}
finally
{
if (channel != null)
channel.Close();
}
}
catch (IOException e)
{
if (closeChannelOnError && channel != null)
{
channel.Close();
channel = null;
}
throw e;
}
catch (RuntimeException e)
{
// Comes from Iterators etc.
// TODO Decide if we can handle these better whilst
// still sticking to the iterator contract
if (closeChannelOnError && channel != null)
{
channel.Close();
channel = null;
}
throw e;
}
}
/**
* Create a POIFSFileSystem from an <tt>InputStream</tt>. Normally the stream is read until
* EOF. The stream is always closed.<p/>
*
* Some streams are usable After reaching EOF (typically those that return <code>true</code>
* for <tt>markSupported()</tt>). In the unlikely case that the caller has such a stream
* <i>and</i> needs to use it After this constructor completes, a work around is to wrap the
* stream in order to trap the <tt>close()</tt> call. A convenience method (
* <tt>CreateNonClosingInputStream()</tt>) has been provided for this purpose:
* <pre>
* InputStream wrappedStream = POIFSFileSystem.CreateNonClosingInputStream(is);
* HSSFWorkbook wb = new HSSFWorkbook(wrappedStream);
* is.Reset();
* doSomethingElse(is);
* </pre>
* Note also the special case of <tt>MemoryStream</tt> for which the <tt>close()</tt>
* method does nothing.
* <pre>
* MemoryStream bais = ...
* HSSFWorkbook wb = new HSSFWorkbook(bais); // calls bais.Close() !
* bais.Reset(); // no problem
* doSomethingElse(bais);
* </pre>
*
* @param stream the InputStream from which to read the data
*
* @exception IOException on errors Reading, or on invalid data
*/
public NPOIFSFileSystem(Stream stream)
: this(false)
{
Stream channel = null;
bool success = false;
try
{
// Turn our InputStream into something NIO based
channel = stream;
// Get the header
ByteBuffer headerBuffer = ByteBuffer.CreateBuffer(POIFSConstants.SMALLER_BIG_BLOCK_SIZE);
IOUtils.ReadFully(channel, headerBuffer.Buffer);
// Have the header Processed
_header = new HeaderBlock(headerBuffer);
// Sanity check the block count
BlockAllocationTableReader.SanityCheckBlockCount(_header.BATCount);
// We need to buffer the whole file into memory when
// working with an InputStream.
// The max possible size is when each BAT block entry is used
long maxSize = BATBlock.CalculateMaximumSize(_header);
if (maxSize > int.MaxValue)
{
throw new ArgumentException("Unable read a >2gb file via an InputStream");
}
ByteBuffer data = ByteBuffer.CreateBuffer((int)maxSize);
headerBuffer.Position = 0;
data.Write(headerBuffer.Buffer);
data.Position = headerBuffer.Length;
//IOUtils.ReadFully(channel, data);
data.Position += IOUtils.ReadFully(channel, data.Buffer, data.Position, (int)channel.Length);
success = true;
// Turn it into a DataSource
_data = new ByteArrayBackedDataSource(data.Buffer, data.Position);
}
finally
{
// As per the constructor contract, always close the stream
if (channel != null)
channel.Close();
CloseInputStream(stream, success);
}
// Now process the various entries
ReadCoreContents();
}
/**
* @param stream the stream to be closed
* @param success <code>false</code> if an exception is currently being thrown in the calling method
*/
private void CloseInputStream(Stream stream, bool success)
{
try
{
stream.Close();
}
catch (IOException e)
{
if (success)
{
throw new Exception(e.Message);
}
}
}
/**
* Checks that the supplied InputStream (which MUST
* support mark and reset, or be a PushbackInputStream)
* has a POIFS (OLE2) header at the start of it.
* If your InputStream does not support mark / reset,
* then wrap it in a PushBackInputStream, then be
* sure to always use that, and not the original!
* @param inp An InputStream which supports either mark/reset, or is a PushbackInputStream
*/
public static bool HasPOIFSHeader(Stream inp)
{
// We want to peek at the first 8 bytes
//inp.Mark(8);
byte[] header = new byte[8];
int bytesRead = IOUtils.ReadFully(inp, header);
LongField signature = new LongField(HeaderBlockConstants._signature_offset, header);
// Wind back those 8 bytes
if (inp is PushbackInputStream) {
PushbackInputStream pin = (PushbackInputStream)inp;
pin.Unread(header, 0, bytesRead);
} else {
inp.Position = 0;
}
// Did it match the signature?
return (signature.Value == HeaderBlockConstants._signature);
}
/**
* Checks if the supplied first 8 bytes of a stream / file
* has a POIFS (OLE2) header.
*/
public static bool HasPOIFSHeader(byte[] header8Bytes)
{
LongField signature = new LongField(HeaderBlockConstants._signature_offset, header8Bytes);
return (signature.Value == HeaderBlockConstants._signature);
}
/**
* Read and process the PropertiesTable and the
* FAT / XFAT blocks, so that we're Ready to
* work with the file
*/
private void ReadCoreContents()
{
// Grab the block size
bigBlockSize = _header.BigBlockSize;
// Each block should only ever be used by one of the
// FAT, XFAT or Property Table. Ensure it does
ChainLoopDetector loopDetector = GetChainLoopDetector();
// Read the FAT blocks
foreach (int fatAt in _header.BATArray)
{
ReadBAT(fatAt, loopDetector);
}
// Work out how many FAT blocks remain in the XFATs
int remainingFATs = _header.BATCount - _header.BATArray.Length;
// Now read the XFAT blocks, and the FATs within them
BATBlock xfat;
int nextAt = _header.XBATIndex;
for (int i = 0; i < _header.XBATCount; i++)
{
loopDetector.Claim(nextAt);
ByteBuffer fatData = GetBlockAt(nextAt);
xfat = BATBlock.CreateBATBlock(bigBlockSize, fatData);
xfat.OurBlockIndex = nextAt;
nextAt = xfat.GetValueAt(bigBlockSize.GetXBATEntriesPerBlock());
_xbat_blocks.Add(xfat);
// Process all the (used) FATs from this XFAT
int xbatFATs = Math.Min(remainingFATs, bigBlockSize.GetXBATEntriesPerBlock());
for(int j=0; j<xbatFATs; j++)
{
int fatAt = xfat.GetValueAt(j);
if (fatAt == POIFSConstants.UNUSED_BLOCK || fatAt == POIFSConstants.END_OF_CHAIN) break;
ReadBAT(fatAt, loopDetector);
}
remainingFATs -= xbatFATs;
}
// We're now able to load steams
// Use this to read in the properties
_property_table = new NPropertyTable(_header, this);
// Finally read the Small Stream FAT (SBAT) blocks
BATBlock sfat;
List<BATBlock> sbats = new List<BATBlock>();
_mini_store = new NPOIFSMiniStore(this, _property_table.Root, sbats, _header);
nextAt = _header.SBATStart;
for (int i = 0; i < _header.SBATCount && nextAt != POIFSConstants.END_OF_CHAIN; i++)
{
loopDetector.Claim(nextAt);
ByteBuffer fatData = GetBlockAt(nextAt);
sfat = BATBlock.CreateBATBlock(bigBlockSize, fatData);
sfat.OurBlockIndex = nextAt;
sbats.Add(sfat);
nextAt = GetNextBlock(nextAt);
}
}
private void ReadBAT(int batAt, ChainLoopDetector loopDetector)
{
loopDetector.Claim(batAt);
ByteBuffer fatData = GetBlockAt(batAt);
// byte[] fatData = GetBlockAt(batAt);
BATBlock bat = BATBlock.CreateBATBlock(bigBlockSize, fatData);
bat.OurBlockIndex = batAt;
_bat_blocks.Add(bat);
}
private BATBlock CreateBAT(int offset, bool isBAT)
{
// Create a new BATBlock
BATBlock newBAT = BATBlock.CreateEmptyBATBlock(bigBlockSize, !isBAT);
newBAT.OurBlockIndex = offset;
// Ensure there's a spot in the file for it
ByteBuffer buffer = ByteBuffer.CreateBuffer(bigBlockSize.GetBigBlockSize());
int WriteTo = (1 + offset) * bigBlockSize.GetBigBlockSize(); // Header isn't in BATs
_data.Write(buffer, WriteTo);
// All done
return newBAT;
}
/**
* Load the block at the given offset.
*/
public override ByteBuffer GetBlockAt(int offset)
{
// The header block doesn't count, so add one
long startAt = (offset + 1) * bigBlockSize.GetBigBlockSize();
try
{
return _data.Read(bigBlockSize.GetBigBlockSize(), startAt);
}
catch (IndexOutOfRangeException e)
{
throw new IndexOutOfRangeException("Block " + offset + " not found - ", e);
}
}
/**
* Load the block at the given offset,
* extending the file if needed
*/
public override ByteBuffer CreateBlockIfNeeded(int offset)
{
try
{
return GetBlockAt(offset);
}
catch (IndexOutOfRangeException)
{
// The header block doesn't count, so add one
long startAt = (offset + 1) * bigBlockSize.GetBigBlockSize();
// Allocate and write
ByteBuffer buffer = ByteBuffer.CreateBuffer(GetBigBlockSize());
// byte[] buffer = new byte[GetBigBlockSize()];
_data.Write(buffer, startAt);
// Retrieve the properly backed block
return GetBlockAt(offset);
}
}
/**
* Returns the BATBlock that handles the specified offset,
* and the relative index within it
*/
public override BATBlockAndIndex GetBATBlockAndIndex(int offset)
{
return BATBlock.GetBATBlockAndIndex(offset, _header, _bat_blocks);
}
/**
* Works out what block follows the specified one.
*/
public override int GetNextBlock(int offset)
{
BATBlockAndIndex bai = GetBATBlockAndIndex(offset);
return bai.Block.GetValueAt(bai.Index);
}
/**
* Changes the record of what block follows the specified one.
*/
public override void SetNextBlock(int offset, int nextBlock)
{
BATBlockAndIndex bai = GetBATBlockAndIndex(offset);
bai.Block.SetValueAt(bai.Index, nextBlock);
}
/**
* Finds a free block, and returns its offset.
* This method will extend the file if needed, and if doing
* so, allocate new FAT blocks to Address the extra space.
*/
public override int GetFreeBlock()
{
int numSectors = bigBlockSize.GetBATEntriesPerBlock();
// First up, do we have any spare ones?
int offset = 0;
foreach(BATBlock temp in _bat_blocks)
{
if (temp.HasFreeSectors)
{
// Claim one of them and return it
for (int j = 0; j < numSectors; j++)
{
int batValue = temp.GetValueAt(j);
if (batValue == POIFSConstants.UNUSED_BLOCK)
{
// Bingo
return offset + j;
}
}
}
// Move onto the next BAT
offset += numSectors;
}
// If we Get here, then there aren't any free sectors
// in any of the BATs, so we need another BAT
BATBlock bat = CreateBAT(offset, true);
bat.SetValueAt(0, POIFSConstants.FAT_SECTOR_BLOCK);
_bat_blocks.Add(bat);
// Now store a reference to the BAT in the required place
if (_header.BATCount >= 109)
{
// Needs to come from an XBAT
BATBlock xbat = null;
foreach (BATBlock x in _xbat_blocks)
{
if (x.HasFreeSectors)
{
xbat = x;
break;
}
}
if (xbat == null)
{
// Oh joy, we need a new XBAT too...
xbat = CreateBAT(offset + 1, false);
// Allocate our new BAT as the first block in the XBAT
xbat.SetValueAt(0, offset);
// And allocate the XBAT in the BAT
bat.SetValueAt(1, POIFSConstants.DIFAT_SECTOR_BLOCK);
// Will go one place higher as XBAT Added in
offset++;
// Chain it
if (_xbat_blocks.Count == 0)
{
_header.XBATStart = offset;
}
else
{
_xbat_blocks[_xbat_blocks.Count - 1].SetValueAt(
bigBlockSize.GetXBATEntriesPerBlock(), offset
);
}
_xbat_blocks.Add(xbat);
_header.XBATCount = _xbat_blocks.Count;
}
else
{
// Allocate us in the XBAT
for (int i = 0; i < bigBlockSize.GetXBATEntriesPerBlock(); i++)
{
if (xbat.GetValueAt(i) == POIFSConstants.UNUSED_BLOCK)
{
xbat.SetValueAt(i, offset);
break;
}
}
}
}
else
{
// Store us in the header
int[] newBATs = new int[_header.BATCount + 1];
Array.Copy(_header.BATArray, 0, newBATs, 0, newBATs.Length - 1);
newBATs[newBATs.Length - 1] = offset;
_header.BATArray = newBATs;
}
_header.BATCount = _bat_blocks.Count;
// The current offset stores us, but the next one is free
return offset + 1;
}
protected internal long Size
{
get
{
return _data.Size;
}
}
public override ChainLoopDetector GetChainLoopDetector()
{
return new ChainLoopDetector(_data.Size, this);
}
/**
* For unit Testing only! Returns the underlying
* properties table
*/
public NPropertyTable PropertyTable
{
get { return _property_table; }
}
/**
* Returns the MiniStore, which performs a similar low
* level function to this, except for the small blocks.
*/
public NPOIFSMiniStore GetMiniStore()
{
return _mini_store;
}
/**
* add a new POIFSDocument to the FileSytem
*
* @param document the POIFSDocument being Added
*/
public void AddDocument(NPOIFSDocument document)
{
_property_table.AddProperty(document.DocumentProperty);
}
/**
* add a new DirectoryProperty to the FileSystem
*
* @param directory the DirectoryProperty being Added
*/
public void AddDirectory(DirectoryProperty directory)
{
_property_table.AddProperty(directory);
}
/**
* Create a new document to be Added to the root directory
*
* @param stream the InputStream from which the document's data
* will be obtained
* @param name the name of the new POIFSDocument
*
* @return the new DocumentEntry
*
* @exception IOException on error creating the new POIFSDocument
*/
public DocumentEntry CreateDocument(Stream stream, String name)
{
return Root.CreateDocument(name, stream);
}
/**
* create a new DocumentEntry in the root entry; the data will be
* provided later
*
* @param name the name of the new DocumentEntry
* @param size the size of the new DocumentEntry
* @param Writer the Writer of the new DocumentEntry
*
* @return the new DocumentEntry
*
* @exception IOException
*/
public DocumentEntry CreateDocument(String name, int size, POIFSWriterListener writer)
{
return Root.CreateDocument(name, size, writer);
}
/**
* create a new DirectoryEntry in the root directory
*
* @param name the name of the new DirectoryEntry
*
* @return the new DirectoryEntry
*
* @exception IOException on name duplication
*/
public DirectoryEntry CreateDirectory(String name)
{
return Root.CreateDirectory(name);
}
/**
* Set the contents of a document in1 the root directory,
* creating if needed, otherwise updating
*
* @param stream the InputStream from which the document's data
* will be obtained
* @param name the name of the new or existing POIFSDocument
*
* @return the new or updated DocumentEntry
*
* @exception IOException on error populating the POIFSDocument
*/
public DocumentEntry CreateOrUpdateDocument(Stream stream,
String name)
{
return Root.CreateOrUpdateDocument(name, stream);
}
/**
* Does the filesystem support an in-place write via
* {@link #writeFilesystem()} ? If false, only writing out to
* a brand new file via {@link #writeFilesystem(OutputStream)}
* is supported.
*/
public bool IsInPlaceWriteable()
{
if (_data is FileBackedDataSource) {
if (((FileBackedDataSource)_data).IsWriteable)
{
return true;
}
}
return false;
}
/**
* Write the filesystem out to the open file. Will thrown an
* {@link ArgumentException} if opened from an
* {@link InputStream}.
*
* @exception IOException thrown on errors writing to the stream
*/
public void WriteFileSystem()
{
if (_data is FileBackedDataSource)
{
// Good, correct type
}
else
{
throw new ArgumentException(
"POIFS opened from an inputstream, so WriteFilesystem() may " +
"not be called. Use WriteFilesystem(OutputStream) instead"
);
}
syncWithDataSource();
}
/**
* Write the filesystem out
*
* @param stream the OutputStream to which the filesystem will be
* written
*
* @exception IOException thrown on errors writing to the stream
*/
public void WriteFileSystem(Stream stream)
{
// Have the datasource updated
syncWithDataSource();
// Now copy the contents to the stream
_data.CopyTo(stream);
}
/**
* Has our in-memory objects write their state
* to their backing blocks
*/
private void syncWithDataSource()
{
// Mini Stream + SBATs first, as mini-stream details have
// to be stored in the Root Property
_mini_store.SyncWithDataSource();
// Properties
NPOIFSStream propStream = new NPOIFSStream(this, _header.PropertyStart);
_property_table.PreWrite();
_property_table.Write(propStream);
// _header.setPropertyStart has been updated on write ...
// HeaderBlock
HeaderBlockWriter hbw = new HeaderBlockWriter(_header);
hbw.WriteBlock(GetBlockAt(-1));
// BATs
foreach (BATBlock bat in _bat_blocks)
{
ByteBuffer block = GetBlockAt(bat.OurBlockIndex);
//byte[] block = GetBlockAt(bat.OurBlockIndex);
BlockAllocationTableWriter.WriteBlock(bat, block);
}
// XBats
foreach (BATBlock bat in _xbat_blocks)
{
ByteBuffer block = GetBlockAt(bat.OurBlockIndex);
BlockAllocationTableWriter.WriteBlock(bat, block);
}
}
/**
* Closes the FileSystem, freeing any underlying files, streams
* and buffers. After this, you will be unable to read or
* write from the FileSystem.
*/
public void Close()
{
_data.Close();
}
/**
* Get the root entry
*
* @return the root entry
*/
public DirectoryNode Root
{
get
{
if (_root == null)
{
_root = new DirectoryNode(_property_table.Root, this, null);
}
return _root;
}
}
/**
* open a document in the root entry's list of entries
*
* @param documentName the name of the document to be opened
*
* @return a newly opened DocumentInputStream
*
* @exception IOException if the document does not exist or the
* name is that of a DirectoryEntry
*/
public DocumentInputStream CreateDocumentInputStream(string documentName)
{
return Root.CreateDocumentInputStream(documentName);
}
/**
* remove an entry
*
* @param entry to be Removed
*/
public void Remove(EntryNode entry)
{
// If it's a document, free the blocks
if (entry is DocumentEntry) {
NPOIFSDocument doc = new NPOIFSDocument((DocumentProperty)entry.Property, this);
doc.Free();
}
_property_table.RemoveProperty(entry.Property);
}
/* ********** START begin implementation of POIFSViewable ********** */
/**
* Get an array of objects, some of which may implement
* POIFSViewable
*
* @return an array of Object; may not be null, but may be empty
*/
protected Object[] GetViewableArray()
{
if (PreferArray)
{
Array ar = ((POIFSViewable)Root).ViewableArray;
Object[] rval = new Object[ar.Length];
for (int i = 0; i < ar.Length; i++)
rval[i] = ar.GetValue(i);
return rval;
}
return new Object[0];
}
/**
* Get an Iterator of objects, some of which may implement
* POIFSViewable
*
* @return an Iterator; may not be null, but may have an empty
* back end store
*/
protected IEnumerator GetViewableIterator()
{
if (!PreferArray)
{
return ((POIFSViewable)Root).ViewableIterator;
}
return null;
}
/**
* Provides a short description of the object, to be used when a
* POIFSViewable object has not provided its contents.
*
* @return short description
*/
protected String GetShortDescription()
{
return "POIFS FileSystem";
}
/* ********** END begin implementation of POIFSViewable ********** */
/**
* @return The Big Block size, normally 512 bytes, sometimes 4096 bytes
*/
public int GetBigBlockSize()
{
return bigBlockSize.GetBigBlockSize();
}
/**
* @return The Big Block size, normally 512 bytes, sometimes 4096 bytes
*/
public POIFSBigBlockSize GetBigBlockSizeDetails()
{
return bigBlockSize;
}
public override int GetBlockStoreBlockSize()
{
return GetBigBlockSize();
}
#region POIFSViewable Members
public bool PreferArray
{
get { return ((POIFSViewable)Root).PreferArray; }
}
public string ShortDescription
{
get { return GetShortDescription(); }
}
public Array ViewableArray
{
get { return GetViewableArray(); }
}
public IEnumerator ViewableIterator
{
get { return GetViewableIterator(); }
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void CompareScalarUnorderedEqualBoolean()
{
var test = new BooleanBinaryOpTest__CompareScalarUnorderedEqualBoolean();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class BooleanBinaryOpTest__CompareScalarUnorderedEqualBoolean
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private GCHandle inHandle1;
private GCHandle inHandle2;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] inArray2, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Single> _fld1;
public Vector128<Single> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(BooleanBinaryOpTest__CompareScalarUnorderedEqualBoolean testClass)
{
var result = Sse.CompareScalarUnorderedEqual(_fld1, _fld2);
testClass.ValidateResult(_fld1, _fld2, result);
}
public void RunStructFldScenario_Load(BooleanBinaryOpTest__CompareScalarUnorderedEqualBoolean testClass)
{
fixed (Vector128<Single>* pFld1 = &_fld1)
fixed (Vector128<Single>* pFld2 = &_fld2)
{
var result = Sse.CompareScalarUnorderedEqual(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2))
);
testClass.ValidateResult(_fld1, _fld2, result);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private DataTable _dataTable;
static BooleanBinaryOpTest__CompareScalarUnorderedEqualBoolean()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public BooleanBinaryOpTest__CompareScalarUnorderedEqualBoolean()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, _data2, LargestVectorSize);
}
public bool IsSupported => Sse.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse.CompareScalarUnorderedEqual(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse.CompareScalarUnorderedEqual(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse.CompareScalarUnorderedEqual(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarUnorderedEqual), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarUnorderedEqual), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse).GetMethod(nameof(Sse.CompareScalarUnorderedEqual), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
});
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result));
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse.CompareScalarUnorderedEqual(
_clsVar1,
_clsVar2
);
ValidateResult(_clsVar1, _clsVar2, result);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Single>* pClsVar1 = &_clsVar1)
fixed (Vector128<Single>* pClsVar2 = &_clsVar2)
{
var result = Sse.CompareScalarUnorderedEqual(
Sse.LoadVector128((Single*)(pClsVar1)),
Sse.LoadVector128((Single*)(pClsVar2))
);
ValidateResult(_clsVar1, _clsVar2, result);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse.CompareScalarUnorderedEqual(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareScalarUnorderedEqual(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.CompareScalarUnorderedEqual(op1, op2);
ValidateResult(op1, op2, result);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new BooleanBinaryOpTest__CompareScalarUnorderedEqualBoolean();
var result = Sse.CompareScalarUnorderedEqual(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new BooleanBinaryOpTest__CompareScalarUnorderedEqualBoolean();
fixed (Vector128<Single>* pFld1 = &test._fld1)
fixed (Vector128<Single>* pFld2 = &test._fld2)
{
var result = Sse.CompareScalarUnorderedEqual(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse.CompareScalarUnorderedEqual(_fld1, _fld2);
ValidateResult(_fld1, _fld2, result);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Single>* pFld1 = &_fld1)
fixed (Vector128<Single>* pFld2 = &_fld2)
{
var result = Sse.CompareScalarUnorderedEqual(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2))
);
ValidateResult(_fld1, _fld2, result);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse.CompareScalarUnorderedEqual(test._fld1, test._fld2);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse.CompareScalarUnorderedEqual(
Sse.LoadVector128((Single*)(&test._fld1)),
Sse.LoadVector128((Single*)(&test._fld2))
);
ValidateResult(test._fld1, test._fld2, result);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, bool result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2);
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, result, method);
}
private void ValidateResult(Single[] left, Single[] right, bool result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((left[0] == right[0]) != result)
{
succeeded = false;
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse)}.{nameof(Sse.CompareScalarUnorderedEqual)}<Boolean>(Vector128<Single>, Vector128<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({result})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace au.util.comctl {
public delegate void FolderChangedHandler(object sender);
/// <summary>
/// Folder selection control
/// </summary>
[ToolboxBitmap(typeof(FoldernameBox), "Properties.Resources.browseFolder.png")]
public partial class FoldernameBox : UserControl {
#region Events
/// <summary>
/// Triggered whenever a different folder is selected
/// </summary>
public event FolderChangedHandler Changed;
#endregion // Events
#region Data Members
private string _basepath;
private bool _stripbase;
private bool _limitbase;
private bool _mustExist = true;
#endregion // Data Members
#region Constructor
public FoldernameBox() {
InitializeComponent();
}
#endregion // Constructor
#region Properties
/// <summary>
/// Currently selected folder
/// </summary>
[Description("Currently selected folder"), Category("FoldernameBox")]
public string FolderName {
get { return _txtFoldername.Text; }
set {
if(value.Length == 0)
_txtFoldername.Text = "";
else {
if(_stripbase) {
if(_mustExist && !Directory.Exists(Path.Combine(_basepath, value)))
throw new FolderNotFoundException(Path.Combine(_basepath, value));
} else {
if(_limitbase && !value.StartsWith(_basepath))
throw new PathMismatchException(_basepath, value);
if(_mustExist && !Directory.Exists(value))
throw new FolderNotFoundException(value);
}
_txtFoldername.Text = value;
if(!_txtFoldername.Text.EndsWith(@"\"))
_txtFoldername.Text += @"\";
}
if(Changed != null)
Changed(this);
}
}
/// <summary>
/// Full path to the currently selected folder
/// </summary>
[Description("Full path to the currently selected folder"), Category("FoldernameBox")]
public string FolderFullName {
get {
if(_stripbase)
return Path.Combine(_basepath, _txtFoldername.Text);
return _txtFoldername.Text;
}
set {
if(value.Length == 0)
_txtFoldername.Text = "";
else {
if(_limitbase && !value.StartsWith(_basepath))
throw new PathMismatchException(_basepath, value);
if(_mustExist && !Directory.Exists(value))
throw new FolderNotFoundException(value);
if(_stripbase)
_txtFoldername.Text = FolderStripBase(value);
else
_txtFoldername.Text = value;
if(!_txtFoldername.Text.EndsWith(@"\"))
_txtFoldername.Text += @"\";
}
if(Changed != null)
Changed(this);
}
}
/// <summary>
/// Gets or sets an option that controls how automatic path completion works
/// </summary>
[Description("Gets or sets an option that controls how automatic path completion works"), Category("FilenameBox"), DefaultValue(AutoCompleteMode.None)]
public AutoCompleteMode AutoCompleteMode {
get { return _txtFoldername.AutoCompleteMode; }
set { _txtFoldername.AutoCompleteSource = (_txtFoldername.AutoCompleteMode = value) == AutoCompleteMode.None ? AutoCompleteSource.None : AutoCompleteSource.FileSystemDirectories; }
}
/// <summary>
/// True if only existing folders can be selected
/// </summary>
[Description("True if only existing folders can be selected"), Category("FoldernameBox")]
public bool FolderMustExist {
get { return _mustExist; }
set { _mustExist = value; }
}
/// <summary>
/// Starting point for folder selection
/// </summary>
[Description("Starting point for folder selection"), Category("FoldernameBox")]
public string BasePath {
get { return _basepath; }
set {
_basepath = value;
if(_basepath == null)
_basepath = "";
if(_basepath.Length > 0 && !_basepath.EndsWith(@"\"))
_basepath += @"\";
}
}
/// <summary>
///
/// </summary>
[Description("Whether the base path should be displayed to the user and returned with the foldername property"), Category("FoldernameBox")]
public bool StripBase {
get { return _stripbase; }
set {
_stripbase = value;
if(_stripbase)
_limitbase = true;
}
}
/// <summary>
/// Whether the selection should be limited to folders within the base path
/// </summary>
[Description("Whether the selection should be limited to folders within the base path"), Category("FoldernameBox")]
public bool LimitBase {
get { return _limitbase; }
set {
if(!_stripbase)
_limitbase = value;
}
}
/// <summary>
///
/// </summary>
[Description("Text to display above the browse dialog"), Category("FoldernameBox")]
public string Description {
get { return _dlgFolderBrowse.Description; }
set { _dlgFolderBrowse.Description = value; }
}
/// <summary>
/// Gets or sets whether the button will appear flat
/// </summary>
[Description("Gets or sets whether the button will appear flat"), Category("Appearance")]
public bool FlatButton {
get { return _btnBrowse.FlatStyle == FlatStyle.Flat; }
set { _btnBrowse.FlatStyle = value ? _btnBrowse.FlatStyle = FlatStyle.Flat : _btnBrowse.FlatStyle = FlatStyle.Standard; }
}
/// <summary>
/// True when the selected folder exists
/// </summary>
[Browsable(false)]
public bool FolderExists {
get { return Directory.Exists(FolderFullName); }
}
#endregion // Properties
private string FolderStripBase(string path) {
path = path.Substring(_basepath.Length);
while(path.StartsWith(@"\"))
path = path.Substring(1);
return path;
}
#region Event Handlers
private void _btnBrowse_Click(object sender, EventArgs e) {
if(_txtFoldername.Text.Length > 0)
if(_stripbase)
_dlgFolderBrowse.SelectedPath = _basepath + _txtFoldername.Text;
else
_dlgFolderBrowse.SelectedPath = _txtFoldername.Text;
else
_dlgFolderBrowse.SelectedPath = _basepath;
_dlgFolderBrowse.ShowDialog(this);
if(_dlgFolderBrowse.SelectedPath != _basepath) {
if(_stripbase)
if(_dlgFolderBrowse.SelectedPath.StartsWith(_basepath))
_txtFoldername.Text = _dlgFolderBrowse.SelectedPath.Substring(_basepath.Length);
else
throw new PathMismatchException(_basepath, _dlgFolderBrowse.SelectedPath);
else
_txtFoldername.Text = _dlgFolderBrowse.SelectedPath;
if(!_txtFoldername.Text.EndsWith(@"\"))
_txtFoldername.Text += @"\";
if(Changed != null)
Changed(this);
}
}
private void _txtFoldername_Validating(object sender, System.ComponentModel.CancelEventArgs e) {
string foldername = _txtFoldername.Text;
if(foldername.Length > 0) {
if(_stripbase)
foldername = _basepath + foldername;
else if(_limitbase && !_txtFoldername.Text.StartsWith(_basepath)) {
MessageBox.Show(this, string.Format(Properties.Resources.PathMismatchMessageBoxMessage, BasePath), Properties.Resources.FoldernameBoxMessageBoxCaption);
e.Cancel = true;
}
if(!e.Cancel && _mustExist && !Directory.Exists(foldername)) {
MessageBox.Show(this, string.Format(Properties.Resources.FolderNotFoundMessageBoxMessage, foldername), Properties.Resources.FoldernameBoxMessageBoxCaption);
e.Cancel = true;
}
if(!e.Cancel && !foldername.EndsWith(@"\"))
_txtFoldername.Text += @"\";
}
if(Changed != null)
Changed(this);
}
private void FoldernameBox_EnabledChanged(object sender, EventArgs e) {
_txtFoldername.Enabled = _btnBrowse.Enabled = Enabled;
}
#endregion // event handlers
}
}
| |
/*
* Copyright 2012-2016 The Pkcs11Interop Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Written for the Pkcs11Interop project by:
* Jaroslav IMRICH <jimrich@jimrich.sk>
*/
using Net.Pkcs11Interop.Common;
using Net.Pkcs11Interop.HighLevelAPI40;
using NUnit.Framework;
namespace Net.Pkcs11Interop.Tests.HighLevelAPI40
{
/// <summary>
/// OpenSession, CloseSession, CloseAllSessions and GetSessionInfo tests.
/// </summary>
[TestFixture()]
public class _06_SessionTest
{
/// <summary>
/// Basic OpenSession and CloseSession test.
/// </summary>
[Test()]
public void _01_BasicSessionTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
{
// Find first slot with token present
Slot slot = Helpers.GetUsableSlot(pkcs11);
// Open RO (read-only) session
Session session = slot.OpenSession(true);
// Do something interesting in RO session
// Close session
session.CloseSession();
}
}
/// <summary>
/// Using statement test.
/// </summary>
[Test()]
public void _02_UsingSessionTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
{
// Find first slot with token present
Slot slot = Helpers.GetUsableSlot(pkcs11);
// Session class can be used in using statement which defines a scope
// at the end of which the session will be closed automatically.
using (Session session = slot.OpenSession(true))
{
// Do something interesting in RO session
}
}
}
/// <summary>
/// CloseSession via slot test.
/// </summary>
[Test()]
public void _03_CloseSessionViaSlotTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
{
// Find first slot with token present
Slot slot = Helpers.GetUsableSlot(pkcs11);
// Open RO (read-only) session
Session session = slot.OpenSession(true);
// Do something interesting in RO session
// Alternatively session can be closed with CloseSession method of Slot class.
slot.CloseSession(session);
}
}
/// <summary>
/// CloseAllSessions test.
/// </summary>
[Test()]
public void _04_CloseAllSessionsTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
{
// Find first slot with token present
Slot slot = Helpers.GetUsableSlot(pkcs11);
// Open RO (read-only) session
Session session = slot.OpenSession(true);
// Do something interesting in RO session
Assert.IsNotNull(session);
// All sessions can be closed with CloseAllSessions method of Slot class.
slot.CloseAllSessions();
}
}
/// <summary>
/// Read-only session test.
/// </summary>
[Test()]
public void _05_ReadOnlySessionTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
{
// Find first slot with token present
Slot slot = Helpers.GetUsableSlot(pkcs11);
// Open RO (read-only) session
using (Session session = slot.OpenSession(true))
{
// Do something interesting in RO session
}
}
}
/// <summary>
/// Read-write session test.
/// </summary>
[Test()]
public void _06_ReadWriteSessionTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
{
// Find first slot with token present
Slot slot = Helpers.GetUsableSlot(pkcs11);
// Open RW (read-write) session
using (Session session = slot.OpenSession(false))
{
// Do something interesting in RW session
}
}
}
/// <summary>
/// GetSessionInfo test.
/// </summary>
[Test()]
public void _07_SessionInfoTest()
{
if (Platform.UnmanagedLongSize != 4 || Platform.StructPackingSize != 0)
Assert.Inconclusive("Test cannot be executed on this platform");
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.UseOsLocking))
{
// Find first slot with token present
Slot slot = Helpers.GetUsableSlot(pkcs11);
// Open RO (read-only) session
using (Session session = slot.OpenSession(true))
{
// Get session details
SessionInfo sessionInfo = session.GetSessionInfo();
// Do something interesting with session info
Assert.IsTrue(sessionInfo.SlotId == slot.SlotId);
Assert.IsNotNull(sessionInfo.SessionFlags);
}
}
}
}
}
| |
// 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.Runtime.InteropServices;
using System.Threading;
namespace System.Collections.Concurrent
{
/// <summary>
/// Represents a thread-safe first-in, first-out collection of objects.
/// </summary>
/// <typeparam name="T">Specifies the type of elements in the queue.</typeparam>
/// <remarks>
/// All public and protected members of <see cref="ConcurrentQueue{T}"/> are thread-safe and may be used
/// concurrently from multiple threads.
/// </remarks>
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(IProducerConsumerCollectionDebugView<>))]
public class ConcurrentQueue<T> : IProducerConsumerCollection<T>, IReadOnlyCollection<T>
{
// This implementation provides an unbounded, multi-producer multi-consumer queue
// that supports the standard Enqueue/TryDequeue operations, as well as support for
// snapshot enumeration (GetEnumerator, ToArray, CopyTo), peeking, and Count/IsEmpty.
// It is composed of a linked list of bounded ring buffers, each of which has a head
// and a tail index, isolated from each other to minimize false sharing. As long as
// the number of elements in the queue remains less than the size of the current
// buffer (Segment), no additional allocations are required for enqueued items. When
// the number of items exceeds the size of the current segment, the current segment is
// "frozen" to prevent further enqueues, and a new segment is linked from it and set
// as the new tail segment for subsequent enqueues. As old segments are consumed by
// dequeues, the head reference is updated to point to the segment that dequeuers should
// try next. To support snapshot enumeration, segments also support the notion of
// preserving for observation, whereby they avoid overwriting state as part of dequeues.
// Any operation that requires a snapshot results in all current segments being
// both frozen for enqueues and preserved for observation: any new enqueues will go
// to new segments, and dequeuers will consume from the existing segments but without
// overwriting the existing data.
/// <summary>Initial length of the segments used in the queue.</summary>
private const int InitialSegmentLength = 32;
/// <summary>
/// Maximum length of the segments used in the queue. This is a somewhat arbitrary limit:
/// larger means that as long as we don't exceed the size, we avoid allocating more segments,
/// but if we do exceed it, then the segment becomes garbage.
/// </summary>
private const int MaxSegmentLength = 1024 * 1024;
/// <summary>
/// Lock used to protect cross-segment operations, including any updates to <see cref="_tail"/> or <see cref="_head"/>
/// and any operations that need to get a consistent view of them.
/// </summary>
private object _crossSegmentLock;
/// <summary>The current tail segment.</summary>
private volatile ConcurrentQueueSegment<T> _tail;
/// <summary>The current head segment.</summary>
private volatile ConcurrentQueueSegment<T> _head; // SOS's ThreadPool command depends on this name
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/> class.
/// </summary>
public ConcurrentQueue()
{
_crossSegmentLock = new object();
_tail = _head = new ConcurrentQueueSegment<T>(InitialSegmentLength);
}
/// <summary>
/// Initializes the contents of the queue from an existing collection.
/// </summary>
/// <param name="collection">A collection from which to copy elements.</param>
private void InitializeFromCollection(IEnumerable<T> collection)
{
_crossSegmentLock = new object();
// Determine the initial segment size. We'll use the default,
// unless the collection is known to be larger than that, in which
// case we round its length up to a power of 2, as all segments must
// be a power of 2 in length.
int length = InitialSegmentLength;
if (collection is ICollection<T> c)
{
int count = c.Count;
if (count > length)
{
length = Math.Min(ConcurrentQueueSegment<T>.RoundUpToPowerOf2(count), MaxSegmentLength);
}
}
// Initialize the segment and add all of the data to it.
_tail = _head = new ConcurrentQueueSegment<T>(length);
foreach (T item in collection)
{
Enqueue(item);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ConcurrentQueue{T}"/> class that contains elements copied
/// from the specified collection.
/// </summary>
/// <param name="collection">
/// The collection whose elements are copied to the new <see cref="ConcurrentQueue{T}"/>.
/// </param>
/// <exception cref="System.ArgumentNullException">The <paramref name="collection"/> argument is null.</exception>
public ConcurrentQueue(IEnumerable<T> collection)
{
if (collection == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.collection);
}
InitializeFromCollection(collection);
}
/// <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">Array</see> that is the destination of the
/// elements copied from the <see cref="ConcurrentQueue{T}"/>. <paramref name="array"/> must have
/// zero-based indexing.
/// </param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param>
/// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in
/// Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than
/// zero.</exception>
/// <exception cref="ArgumentException">
/// <paramref name="array"/> is multidimensional. -or-
/// <paramref name="array"/> does not have zero-based indexing. -or-
/// <paramref name="index"/> is equal to or greater than the length of the <paramref name="array"/>
/// -or- The number of elements in the source <see cref="ICollection"/> is
/// greater than the available space from <paramref name="index"/> to the end of the destination
/// <paramref name="array"/>. -or- The type of the source <see
/// cref="ICollection"/> cannot be cast automatically to the type of the
/// destination <paramref name="array"/>.
/// </exception>
void ICollection.CopyTo(Array array, int index)
{
// Special-case when the Array is actually a T[], taking a faster path
if (array is T[] szArray)
{
CopyTo(szArray, index);
return;
}
// Validate arguments.
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
// Otherwise, fall back to the slower path that first copies the contents
// to an array, and then uses that array's non-generic CopyTo to do the copy.
ToArray().CopyTo(array, index);
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="ICollection"/> is
/// synchronized with the SyncRoot.
/// </summary>
/// <value>true if access to the <see cref="ICollection"/> is synchronized
/// with the SyncRoot; otherwise, false. For <see cref="ConcurrentQueue{T}"/>, this property always
/// returns false.</value>
bool ICollection.IsSynchronized => false; // always false, as true implies synchronization via SyncRoot
/// <summary>
/// Gets an object that can be used to synchronize access to the <see
/// cref="ICollection"/>. This property is not supported.
/// </summary>
/// <exception cref="NotSupportedException">The SyncRoot property is not supported.</exception>
object ICollection.SyncRoot { get { ThrowHelper.ThrowNotSupportedException(ExceptionResource.ConcurrentCollection_SyncRoot_NotSupported); return default; } }
/// <summary>Returns an enumerator that iterates through a collection.</summary>
/// <returns>An <see cref="IEnumerator"/> that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable<T>)this).GetEnumerator();
/// <summary>
/// Attempts to add an object to the <see cref="Concurrent.IProducerConsumerCollection{T}"/>.
/// </summary>
/// <param name="item">The object to add to the <see
/// cref="Concurrent.IProducerConsumerCollection{T}"/>. The value can be a null
/// reference (Nothing in Visual Basic) for reference types.
/// </param>
/// <returns>true if the object was added successfully; otherwise, false.</returns>
/// <remarks>For <see cref="ConcurrentQueue{T}"/>, this operation will always add the object to the
/// end of the <see cref="ConcurrentQueue{T}"/>
/// and return true.</remarks>
bool IProducerConsumerCollection<T>.TryAdd(T item)
{
Enqueue(item);
return true;
}
/// <summary>
/// Attempts to remove and return an object from the <see cref="Concurrent.IProducerConsumerCollection{T}"/>.
/// </summary>
/// <param name="item">
/// When this method returns, if the operation was successful, <paramref name="item"/> contains the
/// object removed. If no object was available to be removed, the value is unspecified.
/// </param>
/// <returns>true if an element was removed and returned successfully; otherwise, false.</returns>
/// <remarks>For <see cref="ConcurrentQueue{T}"/>, this operation will attempt to remove the object
/// from the beginning of the <see cref="ConcurrentQueue{T}"/>.
/// </remarks>
bool IProducerConsumerCollection<T>.TryTake(out T item) => TryDequeue(out item);
/// <summary>
/// Gets a value that indicates whether the <see cref="ConcurrentQueue{T}"/> is empty.
/// </summary>
/// <value>true if the <see cref="ConcurrentQueue{T}"/> is empty; otherwise, false.</value>
/// <remarks>
/// For determining whether the collection contains any items, use of this property is recommended
/// rather than retrieving the number of items from the <see cref="Count"/> property and comparing it
/// to 0. However, as this collection is intended to be accessed concurrently, it may be the case
/// that another thread will modify the collection after <see cref="IsEmpty"/> returns, thus invalidating
/// the result.
/// </remarks>
public bool IsEmpty
{
get
{
// IsEmpty == !TryPeek. We use a "resultUsed:false" peek in order to avoid marking
// segments as preserved for observation, making IsEmpty a cheaper way than either
// TryPeek(out T) or Count == 0 to check whether any elements are in the queue.
T ignoredResult;
return !TryPeek(out ignoredResult, resultUsed: false);
}
}
/// <summary>Copies the elements stored in the <see cref="ConcurrentQueue{T}"/> to a new array.</summary>
/// <returns>A new array containing a snapshot of elements copied from the <see cref="ConcurrentQueue{T}"/>.</returns>
public T[] ToArray()
{
// Snap the current contents for enumeration.
ConcurrentQueueSegment<T> head, tail;
int headHead, tailTail;
SnapForObservation(out head, out headHead, out tail, out tailTail);
// Count the number of items in that snapped set, and use it to allocate an
// array of the right size.
long count = GetCount(head, headHead, tail, tailTail);
T[] arr = new T[count];
// Now enumerate the contents, copying each element into the array.
using (IEnumerator<T> e = Enumerate(head, headHead, tail, tailTail))
{
int i = 0;
while (e.MoveNext())
{
arr[i++] = e.Current;
}
Debug.Assert(count == i);
}
// And return it.
return arr;
}
/// <summary>
/// Gets the number of elements contained in the <see cref="ConcurrentQueue{T}"/>.
/// </summary>
/// <value>The number of elements contained in the <see cref="ConcurrentQueue{T}"/>.</value>
/// <remarks>
/// For determining whether the collection contains any items, use of the <see cref="IsEmpty"/>
/// property is recommended rather than retrieving the number of items from the <see cref="Count"/>
/// property and comparing it to 0.
/// </remarks>
public int Count
{
get
{
var spinner = new SpinWait();
while (true)
{
// Capture the head and tail, as well as the head's head and tail.
ConcurrentQueueSegment<T> head = _head;
ConcurrentQueueSegment<T> tail = _tail;
int headHead = Volatile.Read(ref head._headAndTail.Head);
int headTail = Volatile.Read(ref head._headAndTail.Tail);
if (head == tail)
{
// There was a single segment in the queue. If the captured segments still
// match, then we can trust the values to compute the segment's count. (It's
// theoretically possible the values could have looped around and still exactly match,
// but that would required at least ~4 billion elements to have been enqueued and
// dequeued between the reads.)
if (head == _head &&
tail == _tail &&
headHead == Volatile.Read(ref head._headAndTail.Head) &&
headTail == Volatile.Read(ref head._headAndTail.Tail))
{
return GetCount(head, headHead, headTail);
}
}
else if (head._nextSegment == tail)
{
// There were two segments in the queue. Get the positions from the tail, and as above,
// if the captured values match the previous reads, return the sum of the counts from both segments.
int tailHead = Volatile.Read(ref tail._headAndTail.Head);
int tailTail = Volatile.Read(ref tail._headAndTail.Tail);
if (head == _head &&
tail == _tail &&
headHead == Volatile.Read(ref head._headAndTail.Head) &&
headTail == Volatile.Read(ref head._headAndTail.Tail) &&
tailHead == Volatile.Read(ref tail._headAndTail.Head) &&
tailTail == Volatile.Read(ref tail._headAndTail.Tail))
{
return GetCount(head, headHead, headTail) + GetCount(tail, tailHead, tailTail);
}
}
else
{
// There were more than two segments in the queue. Fall back to taking the cross-segment lock,
// which will ensure that the head and tail segments we read are stable (since the lock is needed to change them);
// for the two-segment case above, we can simply rely on subsequent comparisons, but for the two+ case, we need
// to be able to trust the internal segments between the head and tail.
lock (_crossSegmentLock)
{
// Now that we hold the lock, re-read the previously captured head and tail segments and head positions.
// If either has changed, start over.
if (head == _head && tail == _tail)
{
// Get the positions from the tail, and as above, if the captured values match the previous reads,
// we can use the values to compute the count of the head and tail segments.
int tailHead = Volatile.Read(ref tail._headAndTail.Head);
int tailTail = Volatile.Read(ref tail._headAndTail.Tail);
if (headHead == Volatile.Read(ref head._headAndTail.Head) &&
headTail == Volatile.Read(ref head._headAndTail.Tail) &&
tailHead == Volatile.Read(ref tail._headAndTail.Head) &&
tailTail == Volatile.Read(ref tail._headAndTail.Tail))
{
// We got stable values for the head and tail segments, so we can just compute the sizes
// based on those and add them. Note that this and the below additions to count may overflow: previous
// implementations allowed that, so we don't check, either, and it is theoretically possible for the
// queue to store more than int.MaxValue items.
int count = GetCount(head, headHead, headTail) + GetCount(tail, tailHead, tailTail);
// Now add the counts for each internal segment. Since there were segments before these,
// for counting purposes we consider them to start at the 0th element, and since there is at
// least one segment after each, each was frozen, so we can count until each's frozen tail.
// With the cross-segment lock held, we're guaranteed that all of these internal segments are
// consistent, as the head and tail segment can't be changed while we're holding the lock, and
// dequeueing and enqueueing can only be done from the head and tail segments, which these aren't.
for (ConcurrentQueueSegment<T> s = head._nextSegment; s != tail; s = s._nextSegment)
{
Debug.Assert(s._frozenForEnqueues, "Internal segment must be frozen as there's a following segment.");
count += s._headAndTail.Tail - s.FreezeOffset;
}
return count;
}
}
}
}
// We raced with enqueues/dequeues and captured an inconsistent picture of the queue.
// Spin and try again.
spinner.SpinOnce();
}
}
}
/// <summary>Computes the number of items in a segment based on a fixed head and tail in that segment.</summary>
private static int GetCount(ConcurrentQueueSegment<T> s, int head, int tail)
{
if (head != tail && head != tail - s.FreezeOffset)
{
head &= s._slotsMask;
tail &= s._slotsMask;
return head < tail ? tail - head : s._slots.Length - head + tail;
}
return 0;
}
/// <summary>Gets the number of items in snapped region.</summary>
private static long GetCount(ConcurrentQueueSegment<T> head, int headHead, ConcurrentQueueSegment<T> tail, int tailTail)
{
// All of the segments should have been both frozen for enqueues and preserved for observation.
// Validate that here for head and tail; we'll validate it for intermediate segments later.
Debug.Assert(head._preservedForObservation);
Debug.Assert(head._frozenForEnqueues);
Debug.Assert(tail._preservedForObservation);
Debug.Assert(tail._frozenForEnqueues);
long count = 0;
// Head segment. We've already marked it as frozen for enqueues, so its tail position is fixed,
// and we've already marked it as preserved for observation (before we grabbed the head), so we
// can safely enumerate from its head to its tail and access its elements.
int headTail = (head == tail ? tailTail : Volatile.Read(ref head._headAndTail.Tail)) - head.FreezeOffset;
if (headHead < headTail)
{
// Mask the head and tail for the head segment
headHead &= head._slotsMask;
headTail &= head._slotsMask;
// Increase the count by either the one or two regions, based on whether tail
// has wrapped to be less than head.
count += headHead < headTail ?
headTail - headHead :
head._slots.Length - headHead + headTail;
}
// We've enumerated the head. If the tail is different from the head, we need to
// enumerate the remaining segments.
if (head != tail)
{
// Count the contents of each segment between head and tail, not including head and tail.
// Since there were segments before these, for our purposes we consider them to start at
// the 0th element, and since there is at least one segment after each, each was frozen
// by the time we snapped it, so we can iterate until each's frozen tail.
for (ConcurrentQueueSegment<T> s = head._nextSegment; s != tail; s = s._nextSegment)
{
Debug.Assert(s._preservedForObservation);
Debug.Assert(s._frozenForEnqueues);
count += s._headAndTail.Tail - s.FreezeOffset;
}
// Finally, enumerate the tail. As with the intermediate segments, there were segments
// before this in the snapped region, so we can start counting from the beginning. Unlike
// the intermediate segments, we can't just go until the Tail, as that could still be changing;
// instead we need to go until the tail we snapped for observation.
count += tailTail - tail.FreezeOffset;
}
// Return the computed count.
return count;
}
/// <summary>
/// Copies the <see cref="ConcurrentQueue{T}"/> elements to an existing one-dimensional <see
/// cref="Array">Array</see>, starting at the specified array index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Array">Array</see> that is the
/// destination of the elements copied from the
/// <see cref="ConcurrentQueue{T}"/>. The <see cref="Array">Array</see> must have zero-based
/// indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying
/// begins.</param>
/// <exception cref="ArgumentNullException"><paramref name="array"/> is a null reference (Nothing in
/// Visual Basic).</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than
/// zero.</exception>
/// <exception cref="ArgumentException"><paramref name="index"/> is equal to or greater than the
/// length of the <paramref name="array"/>
/// -or- The number of elements in the source <see cref="ConcurrentQueue{T}"/> is greater than the
/// available space from <paramref name="index"/> to the end of the destination <paramref
/// name="array"/>.
/// </exception>
public void CopyTo(T[] array, int index)
{
if (array == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array);
}
if (index < 0)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index);
}
// Snap for enumeration
ConcurrentQueueSegment<T> head, tail;
int headHead, tailTail;
SnapForObservation(out head, out headHead, out tail, out tailTail);
// Get the number of items to be enumerated
long count = GetCount(head, headHead, tail, tailTail);
if (index > array.Length - count)
{
ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall);
}
// Copy the items to the target array
int i = index;
using (IEnumerator<T> e = Enumerate(head, headHead, tail, tailTail))
{
while (e.MoveNext())
{
array[i++] = e.Current;
}
}
Debug.Assert(count == i - index);
}
/// <summary>Returns an enumerator that iterates through the <see cref="ConcurrentQueue{T}"/>.</summary>
/// <returns>An enumerator for the contents of the <see
/// cref="ConcurrentQueue{T}"/>.</returns>
/// <remarks>
/// The enumeration represents a moment-in-time snapshot of the contents
/// of the queue. It does not reflect any updates to the collection after
/// <see cref="GetEnumerator"/> was called. The enumerator is safe to use
/// concurrently with reads from and writes to the queue.
/// </remarks>
public IEnumerator<T> GetEnumerator()
{
ConcurrentQueueSegment<T> head, tail;
int headHead, tailTail;
SnapForObservation(out head, out headHead, out tail, out tailTail);
return Enumerate(head, headHead, tail, tailTail);
}
/// <summary>
/// Gets the head and tail information of the current contents of the queue.
/// After this call returns, the specified region can be enumerated any number
/// of times and will not change.
/// </summary>
private void SnapForObservation(out ConcurrentQueueSegment<T> head, out int headHead, out ConcurrentQueueSegment<T> tail, out int tailTail)
{
lock (_crossSegmentLock) // _head and _tail may only change while the lock is held.
{
// Snap the head and tail
head = _head;
tail = _tail;
Debug.Assert(head != null);
Debug.Assert(tail != null);
Debug.Assert(tail._nextSegment == null);
// Mark them and all segments in between as preserving, and ensure no additional items
// can be added to the tail.
for (ConcurrentQueueSegment<T> s = head; ; s = s._nextSegment)
{
s._preservedForObservation = true;
if (s == tail) break;
Debug.Assert(s._frozenForEnqueues); // any non-tail should already be marked
}
tail.EnsureFrozenForEnqueues(); // we want to prevent the tailTail from moving
// At this point, any dequeues from any segment won't overwrite the value, and
// none of the existing segments can have new items enqueued.
headHead = Volatile.Read(ref head._headAndTail.Head);
tailTail = Volatile.Read(ref tail._headAndTail.Tail);
}
}
/// <summary>Gets the item stored in the <paramref name="i"/>th entry in <paramref name="segment"/>.</summary>
private T GetItemWhenAvailable(ConcurrentQueueSegment<T> segment, int i)
{
Debug.Assert(segment._preservedForObservation);
// Get the expected value for the sequence number
int expectedSequenceNumberAndMask = (i + 1) & segment._slotsMask;
// If the expected sequence number is not yet written, we're still waiting for
// an enqueuer to finish storing it. Spin until it's there.
if ((segment._slots[i].SequenceNumber & segment._slotsMask) != expectedSequenceNumberAndMask)
{
var spinner = new SpinWait();
while ((Volatile.Read(ref segment._slots[i].SequenceNumber) & segment._slotsMask) != expectedSequenceNumberAndMask)
{
spinner.SpinOnce();
}
}
// Return the value from the slot.
return segment._slots[i].Item;
}
private IEnumerator<T> Enumerate(ConcurrentQueueSegment<T> head, int headHead, ConcurrentQueueSegment<T> tail, int tailTail)
{
Debug.Assert(head._preservedForObservation);
Debug.Assert(head._frozenForEnqueues);
Debug.Assert(tail._preservedForObservation);
Debug.Assert(tail._frozenForEnqueues);
// Head segment. We've already marked it as not accepting any more enqueues,
// so its tail position is fixed, and we've already marked it as preserved for
// enumeration (before we grabbed its head), so we can safely enumerate from
// its head to its tail.
int headTail = (head == tail ? tailTail : Volatile.Read(ref head._headAndTail.Tail)) - head.FreezeOffset;
if (headHead < headTail)
{
headHead &= head._slotsMask;
headTail &= head._slotsMask;
if (headHead < headTail)
{
for (int i = headHead; i < headTail; i++) yield return GetItemWhenAvailable(head, i);
}
else
{
for (int i = headHead; i < head._slots.Length; i++) yield return GetItemWhenAvailable(head, i);
for (int i = 0; i < headTail; i++) yield return GetItemWhenAvailable(head, i);
}
}
// We've enumerated the head. If the tail is the same, we're done.
if (head != tail)
{
// Each segment between head and tail, not including head and tail. Since there were
// segments before these, for our purposes we consider it to start at the 0th element.
for (ConcurrentQueueSegment<T> s = head._nextSegment; s != tail; s = s._nextSegment)
{
Debug.Assert(s._preservedForObservation, "Would have had to been preserved as a segment part of enumeration");
Debug.Assert(s._frozenForEnqueues, "Would have had to be frozen for enqueues as it's intermediate");
int sTail = s._headAndTail.Tail - s.FreezeOffset;
for (int i = 0; i < sTail; i++)
{
yield return GetItemWhenAvailable(s, i);
}
}
// Enumerate the tail. Since there were segments before this, we can just start at
// its beginning, and iterate until the tail we already grabbed.
tailTail -= tail.FreezeOffset;
for (int i = 0; i < tailTail; i++)
{
yield return GetItemWhenAvailable(tail, i);
}
}
}
/// <summary>Adds an object to the end of the <see cref="ConcurrentQueue{T}"/>.</summary>
/// <param name="item">
/// The object to add to the end of the <see cref="ConcurrentQueue{T}"/>.
/// The value can be a null reference (Nothing in Visual Basic) for reference types.
/// </param>
public void Enqueue(T item)
{
// Try to enqueue to the current tail.
if (!_tail.TryEnqueue(item))
{
// If we're unable to, we need to take a slow path that will
// try to add a new tail segment.
EnqueueSlow(item);
}
}
/// <summary>Adds to the end of the queue, adding a new segment if necessary.</summary>
private void EnqueueSlow(T item)
{
while (true)
{
ConcurrentQueueSegment<T> tail = _tail;
// Try to append to the existing tail.
if (tail.TryEnqueue(item))
{
return;
}
// If we were unsuccessful, take the lock so that we can compare and manipulate
// the tail. Assuming another enqueuer hasn't already added a new segment,
// do so, then loop around to try enqueueing again.
lock (_crossSegmentLock)
{
if (tail == _tail)
{
// Make sure no one else can enqueue to this segment.
tail.EnsureFrozenForEnqueues();
// We determine the new segment's length based on the old length.
// In general, we double the size of the segment, to make it less likely
// that we'll need to grow again. However, if the tail segment is marked
// as preserved for observation, something caused us to avoid reusing this
// segment, and if that happens a lot and we grow, we'll end up allocating
// lots of wasted space. As such, in such situations we reset back to the
// initial segment length; if these observations are happening frequently,
// this will help to avoid wasted memory, and if they're not, we'll
// relatively quickly grow again to a larger size.
int nextSize = tail._preservedForObservation ? InitialSegmentLength : Math.Min(tail.Capacity * 2, MaxSegmentLength);
var newTail = new ConcurrentQueueSegment<T>(nextSize);
// Hook up the new tail.
tail._nextSegment = newTail;
_tail = newTail;
}
}
}
}
/// <summary>
/// Attempts to remove and return the object at the beginning of the <see
/// cref="ConcurrentQueue{T}"/>.
/// </summary>
/// <param name="result">
/// When this method returns, if the operation was successful, <paramref name="result"/> contains the
/// object removed. If no object was available to be removed, the value is unspecified.
/// </param>
/// <returns>
/// true if an element was removed and returned from the beginning of the
/// <see cref="ConcurrentQueue{T}"/> successfully; otherwise, false.
/// </returns>
public bool TryDequeue(out T result) =>
_head.TryDequeue(out result) || // fast-path that operates just on the head segment
TryDequeueSlow(out result); // slow path that needs to fix up segments
/// <summary>Tries to dequeue an item, removing empty segments as needed.</summary>
private bool TryDequeueSlow(out T item)
{
while (true)
{
// Get the current head
ConcurrentQueueSegment<T> head = _head;
// Try to take. If we're successful, we're done.
if (head.TryDequeue(out item))
{
return true;
}
// Check to see whether this segment is the last. If it is, we can consider
// this to be a moment-in-time empty condition (even though between the TryDequeue
// check and this check, another item could have arrived).
if (head._nextSegment == null)
{
item = default;
return false;
}
// At this point we know that head.Next != null, which means
// this segment has been frozen for additional enqueues. But between
// the time that we ran TryDequeue and checked for a next segment,
// another item could have been added. Try to dequeue one more time
// to confirm that the segment is indeed empty.
Debug.Assert(head._frozenForEnqueues);
if (head.TryDequeue(out item))
{
return true;
}
// This segment is frozen (nothing more can be added) and empty (nothing is in it).
// Update head to point to the next segment in the list, assuming no one's beat us to it.
lock (_crossSegmentLock)
{
if (head == _head)
{
_head = head._nextSegment;
}
}
}
}
/// <summary>
/// Attempts to return an object from the beginning of the <see cref="ConcurrentQueue{T}"/>
/// without removing it.
/// </summary>
/// <param name="result">
/// When this method returns, <paramref name="result"/> contains an object from
/// the beginning of the <see cref="Concurrent.ConcurrentQueue{T}"/> or default(T)
/// if the operation failed.
/// </param>
/// <returns>true if and object was returned successfully; otherwise, false.</returns>
/// <remarks>
/// For determining whether the collection contains any items, use of the <see cref="IsEmpty"/>
/// property is recommended rather than peeking.
/// </remarks>
public bool TryPeek(out T result) => TryPeek(out result, resultUsed: true);
/// <summary>Attempts to retrieve the value for the first element in the queue.</summary>
/// <param name="result">The value of the first element, if found.</param>
/// <param name="resultUsed">true if the result is needed; otherwise false if only the true/false outcome is needed.</param>
/// <returns>true if an element was found; otherwise, false.</returns>
private bool TryPeek(out T result, bool resultUsed)
{
// Starting with the head segment, look through all of the segments
// for the first one we can find that's not empty.
ConcurrentQueueSegment<T> s = _head;
while (true)
{
// Grab the next segment from this one, before we peek.
// This is to be able to see whether the value has changed
// during the peek operation.
ConcurrentQueueSegment<T> next = Volatile.Read(ref s._nextSegment);
// Peek at the segment. If we find an element, we're done.
if (s.TryPeek(out result, resultUsed))
{
return true;
}
// The current segment was empty at the moment we checked.
if (next != null)
{
// If prior to the peek there was already a next segment, then
// during the peek no additional items could have been enqueued
// to it and we can just move on to check the next segment.
Debug.Assert(next == s._nextSegment);
s = next;
}
else if (Volatile.Read(ref s._nextSegment) == null)
{
// The next segment is null. Nothing more to peek at.
break;
}
// The next segment was null before we peeked but non-null after.
// That means either when we peeked the first segment had
// already been frozen but the new segment not yet added,
// or that the first segment was empty and between the time
// that we peeked and then checked _nextSegment, so many items
// were enqueued that we filled the first segment and went
// into the next. Since we need to peek in order, we simply
// loop around again to peek on the same segment. The next
// time around on this segment we'll then either successfully
// peek or we'll find that next was non-null before peeking,
// and we'll traverse to that segment.
}
result = default;
return false;
}
/// <summary>
/// Removes all objects from the <see cref="ConcurrentQueue{T}"/>.
/// </summary>
public void Clear()
{
lock (_crossSegmentLock)
{
// Simply substitute a new segment for the existing head/tail,
// as is done in the constructor. Operations currently in flight
// may still read from or write to an existing segment that's
// getting dropped, meaning that in flight operations may not be
// linear with regards to this clear operation. To help mitigate
// in-flight operations enqueuing onto the tail that's about to
// be dropped, we first freeze it; that'll force enqueuers to take
// this lock to synchronize and see the new tail.
_tail.EnsureFrozenForEnqueues();
_tail = _head = new ConcurrentQueueSegment<T>(InitialSegmentLength);
}
}
}
}
| |
using System;
using MonoTouch.UIKit;
using MonoTouch.Foundation;
using System.Drawing;
using MonoTouch.CoreGraphics;
using QuartzSample;
public class LineDrawingView : QuartzView {
public override void DrawInContext (CGContext context)
{
// Draw lines with a white stroke color
context.SetRGBStrokeColor (1f, 1f, 1f, 1f);
// Draw them with a 2.0 stroke width so they are more visible
context.SetLineWidth (2);
context.MoveTo (10, 30);
context.AddLineToPoint (310, 30);
context.StrokePath ();
// Draw connected sequence of lines
var points = new PointF [] {
new PointF (10, 90),
new PointF (70, 60),
new PointF (130, 90),
new PointF (190, 60),
new PointF (250, 90),
new PointF (310, 60)
};
context.AddLines (points);
context.StrokePath ();
var segments = new PointF [] {
new PointF (10, 150),
new PointF (70, 120),
new PointF (130, 150),
new PointF (190, 120),
new PointF (250, 150),
new PointF (310, 120),
};
// Bulk call to stroke a sequence of line segments
context.StrokeLineSegments (segments);
}
}
public class LineWidthDrawingView : QuartzView {
public override void DrawInContext (CGContext context)
{
context.SetRGBStrokeColor (1, 1, 1, 1f);
// Draw lines with a stroke width from 1-10
for (int i = 1; i <= 10; ++i) {
context.SetLineWidth (i);
context.MoveTo (10, (float) i * 20.5f);
context.AddLineToPoint (310, (float)i * 20.5f);
context.StrokePath ();
}
// Demonstration that stroke is even on both sides of the line
context.SetLineWidth(15);
context.MoveTo (10, 245.5f);
context.AddLineToPoint (310, 245.5f);
context.StrokePath ();
context.SetRGBStrokeColor (1, 0, 0, 1);
context.SetLineWidth (3);
context.MoveTo (10, 245.5f);
context.AddLineToPoint (310, 245.5f);
context.StrokePath ();
}
}
public class LineCapJoinDrawingView : QuartzView {
public override void DrawInContext (CGContext context)
{
// Drawing lines with a white stroke color
context.SetRGBStrokeColor(1, 1, 1, 1);
// Preserve the current drawing state
context.SaveState();
// Set the line width so that the cap is visible
context.SetLineWidth(20);
// Line caps demonstration
// Line cap butt, default.
context.SetLineCap(CGLineCap.Butt);
context.MoveTo(40, 30);
context.AddLineToPoint(280, 30);
context.StrokePath();
// Line cap round
context.SetLineCap(CGLineCap.Round);
context.MoveTo(40, 65);
context.AddLineToPoint(280, 65);
context.StrokePath();
// Line cap square
context.SetLineCap(CGLineCap.Square);
context.MoveTo(40, 100);
context.AddLineToPoint(280, 100);
context.StrokePath();
// Restore the previous drawing state, and save it again.
context.RestoreState();
context.SaveState();
// Set the line width so that the join is visible
context.SetLineWidth(20);
// Line join miter, default
context.SetLineJoin(CGLineJoin.Miter);
context.MoveTo(40, 260);
context.AddLineToPoint(160, 140);
context.AddLineToPoint(280, 260);
context.StrokePath();
// Line join round
context.SetLineJoin(CGLineJoin.Round);
context.MoveTo(40, 320);
context.AddLineToPoint(160, 200);
context.AddLineToPoint(280, 320);
context.StrokePath();
// Line join bevel
context.SetLineJoin(CGLineJoin.Bevel);
context.MoveTo(40, 380);
context.AddLineToPoint(160, 260);
context.AddLineToPoint(280, 380);
context.StrokePath();
// Restore the previous drawing state.
context.RestoreState();
// Demonstrate where the path that generated each line is
context.SetRGBStrokeColor(1, 0, 0, 1);
context.SetLineWidth(3);
context.MoveTo(40, 30);
context.AddLineToPoint(280, 30);
context.MoveTo(40, 65);
context.AddLineToPoint(280, 65);
context.MoveTo(40, 100);
context.AddLineToPoint(280, 100);
context.MoveTo(40, 260);
context.AddLineToPoint(160, 140);
context.AddLineToPoint(280, 260);
context.MoveTo(40, 320);
context.AddLineToPoint(160, 200);
context.AddLineToPoint(280, 320);
context.MoveTo(40, 380);
context.AddLineToPoint(160, 260);
context.AddLineToPoint(280, 380);
context.StrokePath();
}
}
public class LineDashDrawingView : QuartzView {
public override void DrawInContext (CGContext context)
{
// Drawing lines with a white stroke color
context.SetRGBStrokeColor(1, 1, 1, 1);
// Draw them with a 2 stroke width so they are a bit more visible.
context.SetLineWidth(2);
// Each dash entry is a run-length in the current coordinate system.
// For dash1 we demonstrate the effect of the number of entries in the dash array
// when count==2, we get length 10 drawn, length 10 skipped, etc
// when count==3, we get 10 drawn, 10 skipped, 20 draw, 10 skipped, 10 drawn, 20 skipped, etc
// and so on
float [] dash1 = new float [] {10, 10, 20, 30, 50};
// Different dash lengths
for(int i = 2; i <= 5; ++i)
{
context.SetLineDash(0, dash1, i);
context.MoveTo(10, (i - 1) * 20);
context.AddLineToPoint(310, (i - 1) * 20);
context.StrokePath();
}
// For dash2 we always use count 4, but use it to demonstrate the phase
// phase=0 starts us 0 points into the dash, so we draw 10, skip 10, draw 20, skip 20, etc.
// phase=6 starts 6 points in, so we draw 4, skip 10, draw 20, skip 20, draw 10, skip 10, etc.
// phase=12 stats us 12 points in, so we skip 8, draw 20, skip 20, draw 10, skip 10, etc.
// and so on.
float [] dash2 = {10, 10, 20, 20};
// Different dash phases
for(int i = 0; i < 10; ++i)
{
context.SetLineDash((float) i * 6, dash2, 4);
context.MoveTo(10, (float) (i + 6) * 20);
context.AddLineToPoint(310, (float)(i + 6) * 20);
context.StrokePath();
}
}
}
| |
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Org.BouncyCastle.Math;
namespace Org.BouncyCastle.Asn1
{
public class DerObjectIdentifier
: Asn1Object
{
private static readonly Regex OidRegex = new Regex(@"\A[0-2](\.[0-9]+)+\z");
private readonly string identifier;
/**
* return an Oid from the passed in object
*
* @exception ArgumentException if the object cannot be converted.
*/
public static DerObjectIdentifier GetInstance(
object obj)
{
if (obj == null || obj is DerObjectIdentifier)
{
return (DerObjectIdentifier) obj;
}
if (obj is Asn1OctetString)
{
return new DerObjectIdentifier(((Asn1OctetString)obj).GetOctets());
}
if (obj is Asn1TaggedObject)
{
return GetInstance(((Asn1TaggedObject)obj).GetObject());
}
throw new ArgumentException("illegal object in GetInstance: " + obj.GetType().Name, "obj");
}
/**
* return an object Identifier from a tagged object.
*
* @param obj the tagged object holding the object we want
* @param explicitly true if the object is meant to be explicitly
* tagged false otherwise.
* @exception ArgumentException if the tagged object cannot
* be converted.
*/
public static DerObjectIdentifier GetInstance(
Asn1TaggedObject obj,
bool explicitly)
{
return GetInstance(obj.GetObject());
}
public DerObjectIdentifier(
string identifier)
{
if (identifier == null)
throw new ArgumentNullException("identifier");
if (!OidRegex.IsMatch(identifier))
throw new FormatException("string " + identifier + " not an OID");
this.identifier = identifier;
}
// TODO Change to ID?
public string Id
{
get { return identifier; }
}
internal DerObjectIdentifier(
byte[] bytes)
: this(MakeOidStringFromBytes(bytes))
{
}
private void WriteField(
Stream outputStream,
long fieldValue)
{
if (fieldValue >= (1L << 7))
{
if (fieldValue >= (1L << 14))
{
if (fieldValue >= (1L << 21))
{
if (fieldValue >= (1L << 28))
{
if (fieldValue >= (1L << 35))
{
if (fieldValue >= (1L << 42))
{
if (fieldValue >= (1L << 49))
{
if (fieldValue >= (1L << 56))
{
outputStream.WriteByte((byte)((fieldValue >> 56) | 0x80));
}
outputStream.WriteByte((byte)((fieldValue >> 49) | 0x80));
}
outputStream.WriteByte((byte)((fieldValue >> 42) | 0x80));
}
outputStream.WriteByte((byte)((fieldValue >> 35) | 0x80));
}
outputStream.WriteByte((byte)((fieldValue >> 28) | 0x80));
}
outputStream.WriteByte((byte)((fieldValue >> 21) | 0x80));
}
outputStream.WriteByte((byte)((fieldValue >> 14) | 0x80));
}
outputStream.WriteByte((byte)((fieldValue >> 7) | 0x80));
}
outputStream.WriteByte((byte)(fieldValue & 0x7f));
}
private void WriteField(
Stream outputStream,
BigInteger fieldValue)
{
int byteCount = (fieldValue.BitLength + 6) / 7;
if (byteCount == 0)
{
outputStream.WriteByte(0);
}
else
{
BigInteger tmpValue = fieldValue;
byte[] tmp = new byte[byteCount];
for (int i = byteCount-1; i >= 0; i--)
{
tmp[i] = (byte) ((tmpValue.IntValue & 0x7f) | 0x80);
tmpValue = tmpValue.ShiftRight(7);
}
tmp[byteCount-1] &= 0x7f;
outputStream.Write(tmp, 0, tmp.Length);
}
}
internal override void Encode(
DerOutputStream derOut)
{
OidTokenizer tok = new OidTokenizer(identifier);
MemoryStream bOut = new MemoryStream();
DerOutputStream dOut = new DerOutputStream(bOut);
string token = tok.NextToken();
int first = int.Parse(token);
token = tok.NextToken();
int second = int.Parse(token);
WriteField(bOut, first * 40 + second);
while (tok.HasMoreTokens)
{
token = tok.NextToken();
if (token.Length < 18)
{
WriteField(bOut, Int64.Parse(token));
}
else
{
WriteField(bOut, new BigInteger(token));
}
}
dOut.Close();
derOut.WriteEncoded(Asn1Tags.ObjectIdentifier, bOut.ToArray());
}
protected override int Asn1GetHashCode()
{
return identifier.GetHashCode();
}
protected override bool Asn1Equals(
Asn1Object asn1Object)
{
DerObjectIdentifier other = asn1Object as DerObjectIdentifier;
if (other == null)
return false;
return this.identifier.Equals(other.identifier);
}
public override string ToString()
{
return identifier;
}
private static string MakeOidStringFromBytes(
byte[] bytes)
{
StringBuilder objId = new StringBuilder();
long value = 0;
BigInteger bigValue = null;
bool first = true;
for (int i = 0; i != bytes.Length; i++)
{
int b = bytes[i];
if (value < 0x80000000000000L)
{
value = value * 128 + (b & 0x7f);
if ((b & 0x80) == 0) // end of number reached
{
if (first)
{
switch ((int)value / 40)
{
case 0:
objId.Append('0');
break;
case 1:
objId.Append('1');
value -= 40;
break;
default:
objId.Append('2');
value -= 80;
break;
}
first = false;
}
objId.Append('.');
objId.Append(value);
value = 0;
}
}
else
{
if (bigValue == null)
{
bigValue = BigInteger.ValueOf(value);
}
bigValue = bigValue.ShiftLeft(7);
bigValue = bigValue.Or(BigInteger.ValueOf(b & 0x7f));
if ((b & 0x80) == 0)
{
objId.Append('.');
objId.Append(bigValue);
bigValue = null;
value = 0;
}
}
}
return objId.ToString();
}
}
}
| |
#define MCG_WINRT_SUPPORTED
using Mcg.System;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
// -----------------------------------------------------------------------------------------------------------
//
// WARNING: THIS SOURCE FILE IS FOR 64-BIT BUILDS ONLY!
//
// MCG GENERATED CODE
//
// This C# source file is generated by MCG and is added into the application at compile time to support interop features.
//
// It has three primary components:
//
// 1. Public type definitions with interop implementation used by this application including WinRT & COM data structures and P/Invokes.
//
// 2. The 'McgInterop' class containing marshaling code that acts as a bridge from managed code to native code.
//
// 3. The 'McgNative' class containing marshaling code and native type definitions that call into native code and are called by native code.
//
// -----------------------------------------------------------------------------------------------------------
//
// warning CS0067: The event 'event' is never used
#pragma warning disable 67
// warning CS0169: The field 'field' is never used
#pragma warning disable 169
// warning CS0649: Field 'field' is never assigned to, and will always have its default value 0
#pragma warning disable 414
// warning CS0414: The private field 'field' is assigned but its value is never used
#pragma warning disable 649
// warning CS1591: Missing XML comment for publicly visible type or member 'Type_or_Member'
#pragma warning disable 1591
// warning CS0108 'member1' hides inherited member 'member2'. Use the new keyword if hiding was intended.
#pragma warning disable 108
// warning CS0114 'member1' hides inherited member 'member2'. To make the current method override that implementation, add the override keyword. Otherwise add the new keyword.
#pragma warning disable 114
// warning CS0659 'type' overrides Object.Equals but does not override GetHashCode.
#pragma warning disable 659
// warning CS0465 Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor?
#pragma warning disable 465
// warning CS0028 'function declaration' has the wrong signature to be an entry point
#pragma warning disable 28
// warning CS0162 Unreachable code Detected
#pragma warning disable 162
// warning CS0628 new protected member declared in sealed class
#pragma warning disable 628
namespace McgInterop
{
/// <summary>
/// P/Invoke class for module '[MRT]'
/// </summary>
public unsafe static partial class _MRT_
{
// Signature, RhWaitForPendingFinalizers, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "RhWaitForPendingFinalizers")]
public static void RhWaitForPendingFinalizers(int allowReentrantWait)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes.RhWaitForPendingFinalizers(allowReentrantWait);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
// Signature, RhCompatibleReentrantWaitAny, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr___ptr__w64 int *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "RhCompatibleReentrantWaitAny")]
public static int RhCompatibleReentrantWaitAny(
int alertable,
int timeout,
int count,
global::System.IntPtr* handles)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop._MRT__PInvokes.RhCompatibleReentrantWaitAny(
alertable,
timeout,
count,
((global::System.IntPtr*)handles)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, _ecvt_s, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] double__double, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int___ptrint *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int___ptrint *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "_ecvt_s")]
public static void _ecvt_s(
byte* buffer,
int sizeInBytes,
double value,
int count,
int* dec,
int* sign)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes._ecvt_s(
((byte*)buffer),
sizeInBytes,
value,
count,
((int*)dec),
((int*)sign)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
// Signature, memmove, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] ulong__unsigned __int64,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "System.Runtime.RuntimeImports", "memmove")]
public static void memmove(
byte* dmem,
byte* smem,
ulong size)
{
// Marshalling
// Call to native method
global::McgInterop._MRT__PInvokes.memmove(
((byte*)dmem),
((byte*)smem),
size
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
}
/// <summary>
/// P/Invoke class for module '*'
/// </summary>
public unsafe static partial class _
{
// Signature, CallingConventionConverter_GetStubs, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.TypeLoader, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.Runtime.TypeLoader.CallConverterThunk", "CallingConventionConverter_GetStubs")]
public static void CallingConventionConverter_GetStubs(
out global::System.IntPtr returnVoidStub,
out global::System.IntPtr returnIntegerStub,
out global::System.IntPtr commonStub)
{
// Setup
global::System.IntPtr unsafe_returnVoidStub;
global::System.IntPtr unsafe_returnIntegerStub;
global::System.IntPtr unsafe_commonStub;
// Marshalling
// Call to native method
global::McgInterop.__PInvokes.CallingConventionConverter_GetStubs(
&(unsafe_returnVoidStub),
&(unsafe_returnIntegerStub),
&(unsafe_commonStub)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
commonStub = unsafe_commonStub;
returnIntegerStub = unsafe_returnIntegerStub;
returnVoidStub = unsafe_returnVoidStub;
// Return
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-errorhandling-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_errorhandling_l1_1_0_dll
{
// Signature, GetLastError, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Runtime.Extensions, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "GetLastError")]
public static int GetLastError()
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_errorhandling_l1_1_0_dll_PInvokes.GetLastError();
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-winrt-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_winrt_l1_1_0_dll
{
// Signature, RoInitialize, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "RoInitialize")]
public static int RoInitialize(uint initType)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_winrt_l1_1_0_dll_PInvokes.RoInitialize(initType);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-localization-l1-2-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_localization_l1_2_0_dll
{
// Signature, IsValidLocaleName, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "IsValidLocaleName")]
public static int IsValidLocaleName(char* lpLocaleName)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.IsValidLocaleName(((ushort*)lpLocaleName));
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, ResolveLocaleName, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] char___ptrwchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.WinRTInterop.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "mincore+mincore_PInvokes", "ResolveLocaleName")]
public static int ResolveLocaleName(
char* lpNameToResolve,
char* lpLocaleName,
int cchLocaleName)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.ResolveLocaleName(
((ushort*)lpNameToResolve),
((ushort*)lpLocaleName),
cchLocaleName
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, GetCPInfoExW, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages___ptr__Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Text.Encoding.CodePages, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "GetCPInfoExW")]
public static int GetCPInfoExW(
uint CodePage,
uint dwFlags,
global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages* lpCPInfoEx)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.GetCPInfoExW(
CodePage,
dwFlags,
((global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages*)lpCPInfoEx)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, FormatMessage, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [out] [Mcg.CodeGen.StringBuilderMarshaller] System_Text_StringBuilder__wchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableArrayMarshaller] rg_System_IntPtr____w64 int *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "FormatMessage")]
public static int FormatMessage(
int dwFlags,
global::System.IntPtr lpSource_mustBeNull,
uint dwMessageId,
int dwLanguageId,
global::System.Text.StringBuilder lpBuffer,
int nSize,
global::System.IntPtr[] arguments)
{
// Setup
ushort* unsafe_lpBuffer = default(ushort*);
global::System.IntPtr* unsafe_arguments;
int unsafe___value;
try
{
// Marshalling
if (lpBuffer == null)
unsafe_lpBuffer = null;
else
{
unsafe_lpBuffer = (ushort*)global::McgInterop.McgHelpers.CoTaskMemAllocAndZeroMemory(new global::System.IntPtr(checked(lpBuffer.Capacity * 2
+ 2)));
if (unsafe_lpBuffer == null)
throw new global::System.OutOfMemoryException();
}
if (unsafe_lpBuffer != null)
global::System.Runtime.InteropServices.McgMarshal.StringBuilderToUnicodeString(
lpBuffer,
unsafe_lpBuffer
);
fixed (global::System.IntPtr* pinned_arguments = global::McgInterop.McgCoreHelpers.GetArrayForCompat(arguments))
{
unsafe_arguments = (global::System.IntPtr*)pinned_arguments;
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_localization_l1_2_0_dll_PInvokes.FormatMessage(
dwFlags,
lpSource_mustBeNull,
dwMessageId,
dwLanguageId,
unsafe_lpBuffer,
nSize,
unsafe_arguments
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
}
if (lpBuffer != null)
global::System.Runtime.InteropServices.McgMarshal.UnicodeStringToStringBuilder(
unsafe_lpBuffer,
lpBuffer
);
// Return
return unsafe___value;
}
finally
{
// Cleanup
if (unsafe_lpBuffer != null)
global::System.Runtime.InteropServices.ExternalInterop.SafeCoTaskMemFree(unsafe_lpBuffer);
}
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-com-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_com_l1_1_0_dll
{
// Signature, CoCreateInstance, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.StackTraceGenerator, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.StackTraceGenerator.StackTraceGenerator", "CoCreateInstance")]
public static int CoCreateInstance(
byte* rclsid,
global::System.IntPtr pUnkOuter,
int dwClsContext,
byte* riid,
out global::System.IntPtr ppv)
{
// Setup
global::System.IntPtr unsafe_ppv;
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_com_l1_1_0_dll_PInvokes.CoCreateInstance(
((byte*)rclsid),
pUnkOuter,
dwClsContext,
((byte*)riid),
&(unsafe_ppv)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
ppv = unsafe_ppv;
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'clrcompression.dll'
/// </summary>
public unsafe static partial class clrcompression_dll
{
// Signature, deflateInit2_, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.Compression, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Interop", "deflateInit2_")]
public static int deflateInit2_(
byte* stream,
int level,
int method,
int windowBits,
int memLevel,
int strategy,
byte* version,
int stream_size)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.clrcompression_dll_PInvokes.deflateInit2_(
((byte*)stream),
level,
method,
windowBits,
memLevel,
strategy,
((byte*)version),
stream_size
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, deflateEnd, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.Compression, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Interop", "deflateEnd")]
public static int deflateEnd(byte* strm)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.clrcompression_dll_PInvokes.deflateEnd(((byte*)strm));
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, inflateEnd, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.Compression, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Interop", "inflateEnd")]
public static int inflateEnd(byte* stream)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.clrcompression_dll_PInvokes.inflateEnd(((byte*)stream));
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
// Signature, deflate, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.Compression, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Interop", "deflate")]
public static int deflate(
byte* stream,
int flush)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.clrcompression_dll_PInvokes.deflate(
((byte*)stream),
flush
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
return unsafe___value;
}
}
/// <summary>
/// P/Invoke class for module 'OleAut32'
/// </summary>
public unsafe static partial class OleAut32
{
// Signature, SysFreeString, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Private.StackTraceGenerator, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Internal.LightweightInterop.MarshalExtensions", "SysFreeString")]
public static void SysFreeString(global::System.IntPtr bstr)
{
// Marshalling
// Call to native method
global::McgInterop.OleAut32_PInvokes.SysFreeString(bstr);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-file-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_file_l1_1_0_dll
{
// Signature, GetFileAttributesEx, [fwd] [return] [Mcg.CodeGen.Win32BoolMarshaller] bool__System.Boolean, [fwd] [in] [Mcg.CodeGen.UnicodeStringMarshaller] string__wchar_t *, [fwd] [in] [Mcg.CodeGen.EnumMarshaller] Interop_mincore_GET_FILEEX_INFO_LEVELS__System_IO_FileSystem__Interop_mincore_GET_FILEEX_INFO_LEVELS__System_IO_FileSystem, [fwd] [in] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableStructMarshaller] Interop_mincore_WIN32_FILE_ATTRIBUTE_DATA__System_IO_FileSystem____Interop_mincore_WIN32_FILE_ATTRIBUTE_DATA__System_IO_FileSystem,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "GetFileAttributesEx")]
public static bool GetFileAttributesEx(
string name,
global::Interop_mincore_GET_FILEEX_INFO_LEVELS__System_IO_FileSystem fileInfoLevel,
ref global::Interop_mincore_WIN32_FILE_ATTRIBUTE_DATA__System_IO_FileSystem lpFileInformation)
{
// Setup
ushort* unsafe_name = default(ushort*);
global::Interop_mincore_WIN32_FILE_ATTRIBUTE_DATA__System_IO_FileSystem unsafe_lpFileInformation;
int unsafe___value;
// Marshalling
fixed (char* pinned_name = name)
{
unsafe_name = (ushort*)pinned_name;
unsafe_lpFileInformation = lpFileInformation;
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_file_l1_1_0_dll_PInvokes.GetFileAttributesEx(
unsafe_name,
fileInfoLevel,
&(unsafe_lpFileInformation)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
lpFileInformation = unsafe_lpFileInformation;
}
// Return
return unsafe___value != 0;
}
// Signature, GetFileType, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.Win32HandleMarshaller] System_Runtime_InteropServices_SafeHandle____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "GetFileType")]
public static int GetFileType(global::System.Runtime.InteropServices.SafeHandle hFile)
{
// Setup
bool addRefed = false;
int unsafe___value;
// Marshalling
hFile.DangerousAddRef(ref addRefed);
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_file_l1_1_0_dll_PInvokes.GetFileType(hFile.DangerousGetHandle());
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
if (addRefed)
hFile.DangerousRelease();
// Return
return unsafe___value;
}
// Signature, FindFirstFileEx, [fwd] [return] [Mcg.CodeGen.Win32HandleMarshaller] Microsoft_Win32_SafeHandles_SafeFindHandle__System_IO_FileSystem____w64 int, [fwd] [in] [Mcg.CodeGen.UnicodeStringMarshaller] string__wchar_t *, [fwd] [in] [Mcg.CodeGen.EnumMarshaller] Interop_mincore_FINDEX_INFO_LEVELS__System_IO_FileSystem__Interop_mincore_FINDEX_INFO_LEVELS__System_IO_FileSystem, [fwd] [in] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.StructMarshaller] Interop_mincore_WIN32_FIND_DATA__System_IO_FileSystem____Interop_mincore_WIN32_FIND_DATA__System_IO_FileSystem, [fwd] [in] [Mcg.CodeGen.EnumMarshaller] Interop_mincore_FINDEX_SEARCH_OPS__System_IO_FileSystem__Interop_mincore_FINDEX_SEARCH_OPS__System_IO_FileSystem, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "FindFirstFileEx")]
public static global::Microsoft.Win32.SafeHandles.SafeFindHandle__System_IO_FileSystem FindFirstFileEx(
string lpFileName,
global::Interop_mincore_FINDEX_INFO_LEVELS__System_IO_FileSystem fInfoLevelId,
ref global::Interop_mincore_WIN32_FIND_DATA__System_IO_FileSystem lpFindFileData,
global::Interop_mincore_FINDEX_SEARCH_OPS__System_IO_FileSystem fSearchOp,
global::System.IntPtr lpSearchFilter,
int dwAdditionalFlags)
{
// Setup
ushort* unsafe_lpFileName = default(ushort*);
global::Interop_mincore_WIN32_FIND_DATA__System_IO_FileSystem__Impl.UnsafeType unsafe_lpFindFileData = default(global::Interop_mincore_WIN32_FIND_DATA__System_IO_FileSystem__Impl.UnsafeType);
global::Microsoft.Win32.SafeHandles.SafeFindHandle__System_IO_FileSystem __value;
global::System.IntPtr unsafe___value;
// Marshalling
fixed (char* pinned_lpFileName = lpFileName)
{
unsafe_lpFileName = (ushort*)pinned_lpFileName;
global::Interop_mincore_WIN32_FIND_DATA__System_IO_FileSystem__Impl.Marshal__SafeToUnsafe(
ref lpFindFileData,
out unsafe_lpFindFileData
);
__value = new global::Microsoft.Win32.SafeHandles.SafeFindHandle__System_IO_FileSystem();
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_file_l1_1_0_dll_PInvokes.FindFirstFileEx(
unsafe_lpFileName,
fInfoLevelId,
&(unsafe_lpFindFileData),
fSearchOp,
lpSearchFilter,
dwAdditionalFlags
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
global::System.Runtime.InteropServices.McgMarshal.InitializeHandle(
__value,
unsafe___value
);
global::Interop_mincore_WIN32_FIND_DATA__System_IO_FileSystem__Impl.Marshal__UnsafeToSafe(
ref unsafe_lpFindFileData,
out lpFindFileData
);
}
// Return
return __value;
}
// Signature, SetFilePointerEx, [fwd] [return] [Mcg.CodeGen.Win32BoolMarshaller] bool__System.Boolean, [fwd] [in] [Mcg.CodeGen.Win32HandleMarshaller] Microsoft_Win32_SafeHandles_SafeFileHandle__System_IO_FileSystem____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] long____int64, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] long____int64, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "SetFilePointerEx")]
public static bool SetFilePointerEx(
global::Microsoft.Win32.SafeHandles.SafeFileHandle__System_IO_FileSystem hFile,
long liDistanceToMove,
out long lpNewFilePointer,
uint dwMoveMethod)
{
// Setup
bool addRefed = false;
long unsafe_lpNewFilePointer;
int unsafe___value;
// Marshalling
hFile.DangerousAddRef(ref addRefed);
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_file_l1_1_0_dll_PInvokes.SetFilePointerEx(
hFile.DangerousGetHandle(),
liDistanceToMove,
&(unsafe_lpNewFilePointer),
dwMoveMethod
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
lpNewFilePointer = unsafe_lpNewFilePointer;
if (addRefed)
hFile.DangerousRelease();
// Return
return unsafe___value != 0;
}
// Signature, SetEndOfFile, [fwd] [return] [Mcg.CodeGen.Win32BoolMarshaller] bool__System.Boolean, [fwd] [in] [Mcg.CodeGen.Win32HandleMarshaller] Microsoft_Win32_SafeHandles_SafeFileHandle__System_IO_FileSystem____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "SetEndOfFile")]
public static bool SetEndOfFile(global::Microsoft.Win32.SafeHandles.SafeFileHandle__System_IO_FileSystem hFile)
{
// Setup
bool addRefed = false;
int unsafe___value;
// Marshalling
hFile.DangerousAddRef(ref addRefed);
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_file_l1_1_0_dll_PInvokes.SetEndOfFile(hFile.DangerousGetHandle());
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
if (addRefed)
hFile.DangerousRelease();
// Return
return unsafe___value != 0;
}
// Signature, FindClose, [fwd] [return] [Mcg.CodeGen.Win32BoolMarshaller] bool__System.Boolean, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "FindClose")]
public static bool FindClose(global::System.IntPtr hFindFile)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_file_l1_1_0_dll_PInvokes.FindClose(hFindFile);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
// Return
return unsafe___value != 0;
}
// Signature, ReadFile, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.Win32HandleMarshaller] System_Runtime_InteropServices_SafeHandle____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_Threading_NativeOverlapped__System_Threading_Overlapped___ptrSystem_Threading__NativeOverlapped__System_Threading_Overlapped *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "ReadFile")]
public static int ReadFile(
global::System.Runtime.InteropServices.SafeHandle handle,
byte* bytes,
int numBytesToRead,
global::System.IntPtr numBytesRead_mustBeZero,
global::System.Threading.NativeOverlapped__System_Threading_Overlapped* overlapped)
{
// Setup
bool addRefed = false;
int unsafe___value;
// Marshalling
handle.DangerousAddRef(ref addRefed);
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_file_l1_1_0_dll_PInvokes.ReadFile(
handle.DangerousGetHandle(),
((byte*)bytes),
numBytesToRead,
numBytesRead_mustBeZero,
((global::System.Threading.NativeOverlapped__System_Threading_Overlapped*)overlapped)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
if (addRefed)
handle.DangerousRelease();
// Return
return unsafe___value;
}
// Signature, ReadFile__0, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.Win32HandleMarshaller] System_Runtime_InteropServices_SafeHandle____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "ReadFile")]
public static int ReadFile__0(
global::System.Runtime.InteropServices.SafeHandle handle,
byte* bytes,
int numBytesToRead,
out int numBytesRead,
global::System.IntPtr mustBeZero)
{
// Setup
bool addRefed = false;
int unsafe_numBytesRead;
int unsafe___value;
// Marshalling
handle.DangerousAddRef(ref addRefed);
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_file_l1_1_0_dll_PInvokes.ReadFile__0(
handle.DangerousGetHandle(),
((byte*)bytes),
numBytesToRead,
&(unsafe_numBytesRead),
mustBeZero
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
numBytesRead = unsafe_numBytesRead;
if (addRefed)
handle.DangerousRelease();
// Return
return unsafe___value;
}
// Signature, WriteFile, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.Win32HandleMarshaller] System_Runtime_InteropServices_SafeHandle____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_Threading_NativeOverlapped__System_Threading_Overlapped___ptrSystem_Threading__NativeOverlapped__System_Threading_Overlapped *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "WriteFile")]
public static int WriteFile(
global::System.Runtime.InteropServices.SafeHandle handle,
byte* bytes,
int numBytesToWrite,
global::System.IntPtr numBytesWritten_mustBeZero,
global::System.Threading.NativeOverlapped__System_Threading_Overlapped* lpOverlapped)
{
// Setup
bool addRefed = false;
int unsafe___value;
// Marshalling
handle.DangerousAddRef(ref addRefed);
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_file_l1_1_0_dll_PInvokes.WriteFile(
handle.DangerousGetHandle(),
((byte*)bytes),
numBytesToWrite,
numBytesWritten_mustBeZero,
((global::System.Threading.NativeOverlapped__System_Threading_Overlapped*)lpOverlapped)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
if (addRefed)
handle.DangerousRelease();
// Return
return unsafe___value;
}
// Signature, WriteFile__0, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.Win32HandleMarshaller] System_Runtime_InteropServices_SafeHandle____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] byte___ptrunsigned char *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "WriteFile")]
public static int WriteFile__0(
global::System.Runtime.InteropServices.SafeHandle handle,
byte* bytes,
int numBytesToWrite,
out int numBytesWritten,
global::System.IntPtr mustBeZero)
{
// Setup
bool addRefed = false;
int unsafe_numBytesWritten;
int unsafe___value;
// Marshalling
handle.DangerousAddRef(ref addRefed);
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_file_l1_1_0_dll_PInvokes.WriteFile__0(
handle.DangerousGetHandle(),
((byte*)bytes),
numBytesToWrite,
&(unsafe_numBytesWritten),
mustBeZero
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
numBytesWritten = unsafe_numBytesWritten;
if (addRefed)
handle.DangerousRelease();
// Return
return unsafe___value;
}
// Signature, FlushFileBuffers, [fwd] [return] [Mcg.CodeGen.Win32BoolMarshaller] bool__System.Boolean, [fwd] [in] [Mcg.CodeGen.Win32HandleMarshaller] System_Runtime_InteropServices_SafeHandle____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "FlushFileBuffers")]
public static bool FlushFileBuffers(global::System.Runtime.InteropServices.SafeHandle hHandle)
{
// Setup
bool addRefed = false;
int unsafe___value;
// Marshalling
hHandle.DangerousAddRef(ref addRefed);
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_file_l1_1_0_dll_PInvokes.FlushFileBuffers(hHandle.DangerousGetHandle());
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
if (addRefed)
hHandle.DangerousRelease();
// Return
return unsafe___value != 0;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-file-l2-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_file_l2_1_0_dll
{
// Signature, GetFileInformationByHandleEx, [fwd] [return] [Mcg.CodeGen.Win32BoolMarshaller] bool__System.Boolean, [fwd] [in] [Mcg.CodeGen.Win32HandleMarshaller] Microsoft_Win32_SafeHandles_SafeFileHandle__System_IO_FileSystem____w64 int, [fwd] [in] [Mcg.CodeGen.EnumMarshaller] Interop_mincore_FILE_INFO_BY_HANDLE_CLASS__System_IO_FileSystem__Interop_mincore_FILE_INFO_BY_HANDLE_CLASS__System_IO_FileSystem, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.StructMarshaller] Interop_mincore_FILE_STANDARD_INFO__System_IO_FileSystem____Interop_mincore_FILE_STANDARD_INFO__System_IO_FileSystem, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] uint__unsigned int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "GetFileInformationByHandleEx")]
public static bool GetFileInformationByHandleEx(
global::Microsoft.Win32.SafeHandles.SafeFileHandle__System_IO_FileSystem hFile,
global::Interop_mincore_FILE_INFO_BY_HANDLE_CLASS__System_IO_FileSystem FileInformationClass,
out global::Interop_mincore_FILE_STANDARD_INFO__System_IO_FileSystem lpFileInformation,
uint dwBufferSize)
{
// Setup
bool addRefed = false;
global::Interop_mincore_FILE_STANDARD_INFO__System_IO_FileSystem__Impl.UnsafeType unsafe_lpFileInformation = default(global::Interop_mincore_FILE_STANDARD_INFO__System_IO_FileSystem__Impl.UnsafeType);
int unsafe___value;
// Marshalling
hFile.DangerousAddRef(ref addRefed);
unsafe_lpFileInformation = default(global::Interop_mincore_FILE_STANDARD_INFO__System_IO_FileSystem__Impl.UnsafeType);
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_file_l2_1_0_dll_PInvokes.GetFileInformationByHandleEx(
hFile.DangerousGetHandle(),
FileInformationClass,
&(unsafe_lpFileInformation),
dwBufferSize
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
global::Interop_mincore_FILE_STANDARD_INFO__System_IO_FileSystem__Impl.Marshal__UnsafeToSafe(
ref unsafe_lpFileInformation,
out lpFileInformation
);
if (addRefed)
hFile.DangerousRelease();
// Return
return unsafe___value != 0;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-threadpool-l1-2-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_threadpool_l1_2_0_dll
{
// Signature, CreateThreadpoolIo, [fwd] [return] [Mcg.CodeGen.Win32HandleMarshaller] Microsoft_Win32_SafeHandles_SafeThreadPoolIOHandle__System_Threading_Overlapped____w64 int, [fwd] [in] [Mcg.CodeGen.Win32HandleMarshaller] System_Runtime_InteropServices_SafeHandle____w64 int, [fwd] [in] [Mcg.CodeGen.PInvokeDelegateMarshaller] Interop_NativeIoCompletionCallback__System_Threading_Overlapped____Interop_NativeIoCompletionCallback__System_Threading_Overlapped, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Threading.Overlapped, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "CreateThreadpoolIo")]
public static global::Microsoft.Win32.SafeHandles.SafeThreadPoolIOHandle__System_Threading_Overlapped CreateThreadpoolIo(
global::System.Runtime.InteropServices.SafeHandle fl,
global::Interop_NativeIoCompletionCallback__System_Threading_Overlapped pfnio,
global::System.IntPtr context,
global::System.IntPtr pcbe)
{
// Setup
bool addRefed = false;
void* unsafe_pfnio = default(void*);
global::Microsoft.Win32.SafeHandles.SafeThreadPoolIOHandle__System_Threading_Overlapped __value;
global::System.IntPtr unsafe___value;
try
{
// Marshalling
fl.DangerousAddRef(ref addRefed);
unsafe_pfnio = (void*)global::System.Runtime.InteropServices.McgModuleManager.GetStubForPInvokeDelegate(
global::System.Runtime.InteropServices.TypeOfHelper.RuntimeTypeHandleOf("Interop+NativeIoCompletionCallback,System.Threading.Overlapped, Version=4.0.0.0, Culture=neutral, PublicKeyToken" +
"=b03f5f7f11d50a3a"),
pfnio
);
__value = new global::Microsoft.Win32.SafeHandles.SafeThreadPoolIOHandle__System_Threading_Overlapped();
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_threadpool_l1_2_0_dll_PInvokes.CreateThreadpoolIo(
fl.DangerousGetHandle(),
unsafe_pfnio,
context,
pcbe
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
global::System.Runtime.InteropServices.McgMarshal.InitializeHandle(
__value,
unsafe___value
);
if (addRefed)
fl.DangerousRelease();
// Return
return __value;
}
finally
{
// Cleanup
global::System.GC.KeepAlive(pfnio);
}
}
// Signature, CloseThreadpoolIo, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Threading.Overlapped, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "CloseThreadpoolIo")]
public static void CloseThreadpoolIo(global::System.IntPtr pio)
{
// Marshalling
// Call to native method
global::McgInterop.api_ms_win_core_threadpool_l1_2_0_dll_PInvokes.CloseThreadpoolIo(pio);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
// Return
}
// Signature, StartThreadpoolIo, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.Win32HandleMarshaller] Microsoft_Win32_SafeHandles_SafeThreadPoolIOHandle__System_Threading_Overlapped____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Threading.Overlapped, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "StartThreadpoolIo")]
public static void StartThreadpoolIo(global::Microsoft.Win32.SafeHandles.SafeThreadPoolIOHandle__System_Threading_Overlapped pio)
{
// Setup
bool addRefed = false;
// Marshalling
pio.DangerousAddRef(ref addRefed);
// Call to native method
global::McgInterop.api_ms_win_core_threadpool_l1_2_0_dll_PInvokes.StartThreadpoolIo(pio.DangerousGetHandle());
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
if (addRefed)
pio.DangerousRelease();
// Return
}
// Signature, CancelThreadpoolIo, [fwd] [return] [Mcg.CodeGen.VoidReturnMarshaller] void__void, [fwd] [in] [Mcg.CodeGen.Win32HandleMarshaller] Microsoft_Win32_SafeHandles_SafeThreadPoolIOHandle__System_Threading_Overlapped____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Threading.Overlapped, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "CancelThreadpoolIo")]
public static void CancelThreadpoolIo(global::Microsoft.Win32.SafeHandles.SafeThreadPoolIOHandle__System_Threading_Overlapped pio)
{
// Setup
bool addRefed = false;
// Marshalling
pio.DangerousAddRef(ref addRefed);
// Call to native method
global::McgInterop.api_ms_win_core_threadpool_l1_2_0_dll_PInvokes.CancelThreadpoolIo(pio.DangerousGetHandle());
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
if (addRefed)
pio.DangerousRelease();
// Return
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-file-l1-2-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_file_l1_2_0_dll
{
// Signature, CreateFile2, [fwd] [return] [Mcg.CodeGen.Win32HandleMarshaller] Microsoft_Win32_SafeHandles_SafeFileHandle__System_IO_FileSystem____w64 int, [fwd] [in] [Mcg.CodeGen.UnicodeStringMarshaller] string__wchar_t *, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [in] [Mcg.CodeGen.EnumMarshaller] System_IO_FileShare__System_IO_FileSystem_Primitives__FileShare__System_IO_FileSystem_Primitives, [fwd] [in] [Mcg.CodeGen.EnumMarshaller] System_IO_FileMode__System_IO_FileSystem_Primitives__FileMode__System_IO_FileSystem_Primitives, [fwd] [in] [managedbyref] [nativebyref] [Mcg.CodeGen.BlittableStructMarshaller] Interop_mincore_CREATEFILE2_EXTENDED_PARAMETERS__System_IO_FileSystem____Interop_mincore_CREATEFILE2_EXTENDED_PARAMETERS__System_IO_FileSystem,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "CreateFile2")]
public static global::Microsoft.Win32.SafeHandles.SafeFileHandle__System_IO_FileSystem CreateFile2(
string lpFileName,
int dwDesiredAccess,
global::System.IO.FileShare__System_IO_FileSystem_Primitives dwShareMode,
global::System.IO.FileMode__System_IO_FileSystem_Primitives dwCreationDisposition,
ref global::Interop_mincore_CREATEFILE2_EXTENDED_PARAMETERS__System_IO_FileSystem parameters)
{
// Setup
ushort* unsafe_lpFileName = default(ushort*);
global::Interop_mincore_CREATEFILE2_EXTENDED_PARAMETERS__System_IO_FileSystem unsafe_parameters;
global::Microsoft.Win32.SafeHandles.SafeFileHandle__System_IO_FileSystem __value;
global::System.IntPtr unsafe___value;
// Marshalling
fixed (char* pinned_lpFileName = lpFileName)
{
unsafe_lpFileName = (ushort*)pinned_lpFileName;
unsafe_parameters = parameters;
__value = new global::Microsoft.Win32.SafeHandles.SafeFileHandle__System_IO_FileSystem();
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_file_l1_2_0_dll_PInvokes.CreateFile2(
unsafe_lpFileName,
dwDesiredAccess,
dwShareMode,
dwCreationDisposition,
&(unsafe_parameters)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
global::System.Runtime.InteropServices.McgMarshal.InitializeHandle(
__value,
unsafe___value
);
}
// Return
return __value;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-winrt-robuffer-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_winrt_robuffer_l1_1_0_dll
{
// Signature, RoGetBufferMarshaler, [fwd] [return] [Mcg.CodeGen.BlittableValueMarshaller] int__int, [fwd] [out] [managedbyref] [nativebyref] [Mcg.CodeGen.ComInterfaceMarshaller] System_Runtime_InteropServices_IMarshal__System_Runtime_WindowsRuntime__System_Runtime_InteropServices__IMarshal__System_Runtime_WindowsRuntime *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.Runtime.WindowsRuntime, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "Interop+mincore_PInvokes", "RoGetBufferMarshaler")]
public static int RoGetBufferMarshaler(out global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime bufferMarshalerPtr)
{
// Setup
global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl** unsafe_bufferMarshalerPtr = default(global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl**);
int unsafe___value;
try
{
// Marshalling
unsafe_bufferMarshalerPtr = null;
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_winrt_robuffer_l1_1_0_dll_PInvokes.RoGetBufferMarshaler(&(unsafe_bufferMarshalerPtr));
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
bufferMarshalerPtr = (global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime)global::System.Runtime.InteropServices.McgModuleManager.ComInterfaceToObject(
((global::System.IntPtr)unsafe_bufferMarshalerPtr),
global::System.Runtime.InteropServices.TypeOfHelper.RuntimeTypeHandleOf("System.Runtime.InteropServices.IMarshal,System.Runtime.WindowsRuntime, Version=4.0.10.0, Culture=neutral, Public" +
"KeyToken=b77a5c561934e089")
);
// Return
return unsafe___value;
}
finally
{
// Cleanup
global::System.Runtime.InteropServices.McgMarshal.ComSafeRelease(new global::System.IntPtr(((void*)unsafe_bufferMarshalerPtr)));
}
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-handle-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_handle_l1_1_0_dll
{
// Signature, CloseHandle, [fwd] [return] [Mcg.CodeGen.Win32BoolMarshaller] bool__System.Boolean, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_IntPtr____w64 int,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "CloseHandle")]
public static bool CloseHandle(global::System.IntPtr handle)
{
// Setup
int unsafe___value;
// Marshalling
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_handle_l1_1_0_dll_PInvokes.CloseHandle(handle);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
// Return
return unsafe___value != 0;
}
}
/// <summary>
/// P/Invoke class for module 'api-ms-win-core-io-l1-1-0.dll'
/// </summary>
public unsafe static partial class api_ms_win_core_io_l1_1_0_dll
{
// Signature, CancelIoEx, [fwd] [return] [Mcg.CodeGen.Win32BoolMarshaller] bool__System.Boolean, [fwd] [in] [Mcg.CodeGen.Win32HandleMarshaller] System_Runtime_InteropServices_SafeHandle____w64 int, [fwd] [in] [Mcg.CodeGen.BlittableValueMarshaller] System_Threading_NativeOverlapped__System_Threading_Overlapped___ptrSystem_Threading__NativeOverlapped__System_Threading_Overlapped *,
[global::System.Runtime.InteropServices.McgGeneratedMarshallingCode]
[global::System.Runtime.InteropServices.McgPInvokeMarshalStub("System.IO.FileSystem, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", "Interop+mincore", "CancelIoEx")]
public static bool CancelIoEx(
global::System.Runtime.InteropServices.SafeHandle handle,
global::System.Threading.NativeOverlapped__System_Threading_Overlapped* lpOverlapped)
{
// Setup
bool addRefed = false;
int unsafe___value;
// Marshalling
handle.DangerousAddRef(ref addRefed);
// Call to native method
unsafe___value = global::McgInterop.api_ms_win_core_io_l1_1_0_dll_PInvokes.CancelIoEx(
handle.DangerousGetHandle(),
((global::System.Threading.NativeOverlapped__System_Threading_Overlapped*)lpOverlapped)
);
global::System.Runtime.InteropServices.DebugAnnotations.PreviousCallContainsUserCode();
global::System.Runtime.InteropServices.McgMarshal.SaveLastWin32Error();
if (addRefed)
handle.DangerousRelease();
// Return
return unsafe___value != 0;
}
}
public unsafe static partial class _MRT__PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void RhWaitForPendingFinalizers(int allowReentrantWait);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int RhCompatibleReentrantWaitAny(
int alertable,
int timeout,
int count,
global::System.IntPtr* handles);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void _ecvt_s(
byte* buffer,
int sizeInBytes,
double value,
int count,
int* dec,
int* sign);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("[MRT]", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void memmove(
byte* dmem,
byte* smem,
ulong size);
}
public unsafe static partial class __PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("*", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void CallingConventionConverter_GetStubs(
global::System.IntPtr* returnVoidStub,
global::System.IntPtr* returnIntegerStub,
global::System.IntPtr* commonStub);
}
public unsafe static partial class api_ms_win_core_errorhandling_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-errorhandling-l1-1-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int GetLastError();
}
public unsafe static partial class api_ms_win_core_winrt_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-winrt-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int RoInitialize(uint initType);
}
public unsafe static partial class api_ms_win_core_localization_l1_2_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int IsValidLocaleName(ushort* lpLocaleName);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int ResolveLocaleName(
ushort* lpNameToResolve,
ushort* lpLocaleName,
int cchLocaleName);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int GetCPInfoExW(
uint CodePage,
uint dwFlags,
global::Interop_mincore_CPINFOEXW__System_Text_Encoding_CodePages* lpCPInfoEx);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-localization-l1-2-1.dll", EntryPoint="FormatMessageW", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int FormatMessage(
int dwFlags,
global::System.IntPtr lpSource_mustBeNull,
uint dwMessageId,
int dwLanguageId,
ushort* lpBuffer,
int nSize,
global::System.IntPtr* arguments);
}
public unsafe static partial class api_ms_win_core_com_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-com-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int CoCreateInstance(
byte* rclsid,
global::System.IntPtr pUnkOuter,
int dwClsContext,
byte* riid,
global::System.IntPtr* ppv);
}
public unsafe static partial class clrcompression_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("clrcompression.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int deflateInit2_(
byte* stream,
int level,
int method,
int windowBits,
int memLevel,
int strategy,
byte* version,
int stream_size);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("clrcompression.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int deflateEnd(byte* strm);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("clrcompression.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int inflateEnd(byte* stream);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("clrcompression.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int deflate(
byte* stream,
int flush);
}
public unsafe static partial class OleAut32_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("oleaut32.dll", EntryPoint="#6", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void SysFreeString(global::System.IntPtr bstr);
}
public unsafe static partial class api_ms_win_core_file_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-file-l1-2-1.dll", EntryPoint="GetFileAttributesExW", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int GetFileAttributesEx(
ushort* name,
global::Interop_mincore_GET_FILEEX_INFO_LEVELS__System_IO_FileSystem fileInfoLevel,
global::Interop_mincore_WIN32_FILE_ATTRIBUTE_DATA__System_IO_FileSystem* lpFileInformation);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-file-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int GetFileType(global::System.IntPtr hFile);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-file-l1-2-1.dll", EntryPoint="FindFirstFileExW", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static global::System.IntPtr FindFirstFileEx(
ushort* lpFileName,
global::Interop_mincore_FINDEX_INFO_LEVELS__System_IO_FileSystem fInfoLevelId,
global::Interop_mincore_WIN32_FIND_DATA__System_IO_FileSystem__Impl.UnsafeType* lpFindFileData,
global::Interop_mincore_FINDEX_SEARCH_OPS__System_IO_FileSystem fSearchOp,
global::System.IntPtr lpSearchFilter,
int dwAdditionalFlags);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-file-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int SetFilePointerEx(
global::System.IntPtr hFile,
long liDistanceToMove,
long* lpNewFilePointer,
uint dwMoveMethod);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-file-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int SetEndOfFile(global::System.IntPtr hFile);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-file-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int FindClose(global::System.IntPtr hFindFile);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-file-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int ReadFile(
global::System.IntPtr handle,
byte* bytes,
int numBytesToRead,
global::System.IntPtr numBytesRead_mustBeZero,
global::System.Threading.NativeOverlapped__System_Threading_Overlapped* overlapped);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-file-l1-2-1.dll", EntryPoint="ReadFile", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int ReadFile__0(
global::System.IntPtr handle,
byte* bytes,
int numBytesToRead,
int* numBytesRead,
global::System.IntPtr mustBeZero);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-file-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int WriteFile(
global::System.IntPtr handle,
byte* bytes,
int numBytesToWrite,
global::System.IntPtr numBytesWritten_mustBeZero,
global::System.Threading.NativeOverlapped__System_Threading_Overlapped* lpOverlapped);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-file-l1-2-1.dll", EntryPoint="WriteFile", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int WriteFile__0(
global::System.IntPtr handle,
byte* bytes,
int numBytesToWrite,
int* numBytesWritten,
global::System.IntPtr mustBeZero);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-file-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int FlushFileBuffers(global::System.IntPtr hHandle);
}
public unsafe static partial class api_ms_win_core_file_l2_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-file-l2-1-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int GetFileInformationByHandleEx(
global::System.IntPtr hFile,
global::Interop_mincore_FILE_INFO_BY_HANDLE_CLASS__System_IO_FileSystem FileInformationClass,
global::Interop_mincore_FILE_STANDARD_INFO__System_IO_FileSystem__Impl.UnsafeType* lpFileInformation,
uint dwBufferSize);
}
public unsafe static partial class api_ms_win_core_threadpool_l1_2_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-threadpool-l1-2-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static global::System.IntPtr CreateThreadpoolIo(
global::System.IntPtr fl,
void* pfnio,
global::System.IntPtr context,
global::System.IntPtr pcbe);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-threadpool-l1-2-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void CloseThreadpoolIo(global::System.IntPtr pio);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-threadpool-l1-2-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void StartThreadpoolIo(global::System.IntPtr pio);
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-threadpool-l1-2-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static void CancelThreadpoolIo(global::System.IntPtr pio);
}
public unsafe static partial class api_ms_win_core_file_l1_2_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-file-l1-2-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static global::System.IntPtr CreateFile2(
ushort* lpFileName,
int dwDesiredAccess,
global::System.IO.FileShare__System_IO_FileSystem_Primitives dwShareMode,
global::System.IO.FileMode__System_IO_FileSystem_Primitives dwCreationDisposition,
global::Interop_mincore_CREATEFILE2_EXTENDED_PARAMETERS__System_IO_FileSystem* parameters);
}
public unsafe static partial class api_ms_win_core_winrt_robuffer_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-winrt-robuffer-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.StdCall)]
public extern static int RoGetBufferMarshaler(global::System.Runtime.InteropServices.IMarshal__System_Runtime_WindowsRuntime__Impl.Vtbl*** bufferMarshalerPtr);
}
public unsafe static partial class api_ms_win_core_handle_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-handle-l1-1-0.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int CloseHandle(global::System.IntPtr handle);
}
public unsafe static partial class api_ms_win_core_io_l1_1_0_dll_PInvokes
{
[global::McgInterop.McgGeneratedNativeCallCode]
[global::System.Runtime.InteropServices.DllImport("api-ms-win-core-io-l1-1-1.dll", CallingConvention=global::System.Runtime.InteropServices.CallingConvention.Winapi)]
public extern static int CancelIoEx(
global::System.IntPtr handle,
global::System.Threading.NativeOverlapped__System_Threading_Overlapped* lpOverlapped);
}
}
| |
using WixSharp;
using WixSharp.UI.Forms;
namespace WixSharpSetup.Dialogs
{
partial class MaintenanceTypeDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.topBorder = new System.Windows.Forms.Panel();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.remove = new System.Windows.Forms.Button();
this.repair = new System.Windows.Forms.Button();
this.change = new System.Windows.Forms.Button();
this.topPanel = new System.Windows.Forms.Panel();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.banner = new System.Windows.Forms.PictureBox();
this.bottomPanel = new System.Windows.Forms.Panel();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.back = new System.Windows.Forms.Button();
this.next = new System.Windows.Forms.Button();
this.cancel = new System.Windows.Forms.Button();
this.border1 = new System.Windows.Forms.Panel();
this.middlePanel = new System.Windows.Forms.TableLayoutPanel();
this.panel3 = new System.Windows.Forms.Panel();
this.panel4 = new System.Windows.Forms.Panel();
this.panel5 = new System.Windows.Forms.Panel();
this.topPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.banner)).BeginInit();
this.bottomPanel.SuspendLayout();
this.tableLayoutPanel1.SuspendLayout();
this.middlePanel.SuspendLayout();
this.panel3.SuspendLayout();
this.panel4.SuspendLayout();
this.panel5.SuspendLayout();
this.SuspendLayout();
//
// topBorder
//
this.topBorder.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.topBorder.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.topBorder.Location = new System.Drawing.Point(0, 58);
this.topBorder.Name = "topBorder";
this.topBorder.Size = new System.Drawing.Size(494, 1);
this.topBorder.TabIndex = 18;
//
// label5
//
this.label5.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.label5.AutoEllipsis = true;
this.label5.BackColor = System.Drawing.Color.Transparent;
this.label5.Location = new System.Drawing.Point(28, 40);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(442, 38);
this.label5.TabIndex = 1;
this.label5.Text = "[MaintenanceTypeDlgRemoveText]";
//
// label4
//
this.label4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.label4.AutoEllipsis = true;
this.label4.BackColor = System.Drawing.Color.Transparent;
this.label4.Location = new System.Drawing.Point(28, 40);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(440, 34);
this.label4.TabIndex = 1;
this.label4.Text = "[MaintenanceTypeDlgRepairText]";
//
// label3
//
this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.label3.AutoEllipsis = true;
this.label3.BackColor = System.Drawing.Color.Transparent;
this.label3.Location = new System.Drawing.Point(28, 40);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(440, 34);
this.label3.TabIndex = 1;
this.label3.Text = "[MaintenanceTypeDlgChangeText]";
//
// remove
//
this.remove.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.remove.AutoSize = true;
this.remove.Location = new System.Drawing.Point(0, 5);
this.remove.MaximumSize = new System.Drawing.Size(113, 0);
this.remove.MinimumSize = new System.Drawing.Size(113, 0);
this.remove.Name = "remove";
this.remove.Size = new System.Drawing.Size(113, 23);
this.remove.TabIndex = 16;
this.remove.Text = "[MaintenanceTypeDlgRemoveButton]";
this.remove.UseVisualStyleBackColor = true;
this.remove.Click += new System.EventHandler(this.remove_Click);
//
// repair
//
this.repair.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.repair.AutoSize = true;
this.repair.Location = new System.Drawing.Point(0, 5);
this.repair.MaximumSize = new System.Drawing.Size(113, 0);
this.repair.MinimumSize = new System.Drawing.Size(113, 0);
this.repair.Name = "repair";
this.repair.Size = new System.Drawing.Size(113, 23);
this.repair.TabIndex = 15;
this.repair.Text = "[MaintenanceTypeDlgRepairButton]";
this.repair.UseVisualStyleBackColor = true;
this.repair.Click += new System.EventHandler(this.repair_Click);
//
// change
//
this.change.Anchor = System.Windows.Forms.AnchorStyles.Left;
this.change.AutoSize = true;
this.change.Location = new System.Drawing.Point(0, 5);
this.change.MaximumSize = new System.Drawing.Size(113, 0);
this.change.MinimumSize = new System.Drawing.Size(113, 0);
this.change.Name = "change";
this.change.Size = new System.Drawing.Size(113, 23);
this.change.TabIndex = 0;
this.change.Text = "[MaintenanceTypeDlgChangeButton]";
this.change.UseVisualStyleBackColor = true;
this.change.Click += new System.EventHandler(this.change_Click);
//
// topPanel
//
this.topPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.topPanel.BackColor = System.Drawing.SystemColors.Control;
this.topPanel.Controls.Add(this.label2);
this.topPanel.Controls.Add(this.label1);
this.topPanel.Controls.Add(this.banner);
this.topPanel.Location = new System.Drawing.Point(0, 0);
this.topPanel.Name = "topPanel";
this.topPanel.Size = new System.Drawing.Size(494, 58);
this.topPanel.TabIndex = 13;
//
// label2
//
this.label2.AutoSize = true;
this.label2.BackColor = System.Drawing.Color.Transparent;
this.label2.Location = new System.Drawing.Point(19, 31);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(168, 13);
this.label2.TabIndex = 1;
this.label2.Text = "[MaintenanceTypeDlgDescription]";
//
// label1
//
this.label1.AutoSize = true;
this.label1.BackColor = System.Drawing.Color.Transparent;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(11, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(160, 13);
this.label1.TabIndex = 1;
this.label1.Text = "[MaintenanceTypeDlgTitle]";
//
// banner
//
this.banner.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.banner.BackColor = System.Drawing.Color.White;
this.banner.Location = new System.Drawing.Point(0, 0);
this.banner.Name = "banner";
this.banner.Size = new System.Drawing.Size(494, 58);
this.banner.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.banner.TabIndex = 0;
this.banner.TabStop = false;
//
// bottomPanel
//
this.bottomPanel.BackColor = System.Drawing.SystemColors.Control;
this.bottomPanel.Controls.Add(this.tableLayoutPanel1);
this.bottomPanel.Controls.Add(this.border1);
this.bottomPanel.Dock = System.Windows.Forms.DockStyle.Bottom;
this.bottomPanel.Location = new System.Drawing.Point(0, 312);
this.bottomPanel.Name = "bottomPanel";
this.bottomPanel.Size = new System.Drawing.Size(494, 49);
this.bottomPanel.TabIndex = 12;
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right)));
this.tableLayoutPanel1.ColumnCount = 5;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 14F));
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
this.tableLayoutPanel1.Controls.Add(this.back, 1, 0);
this.tableLayoutPanel1.Controls.Add(this.next, 2, 0);
this.tableLayoutPanel1.Controls.Add(this.cancel, 4, 0);
this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 3);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 1;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(491, 43);
this.tableLayoutPanel1.TabIndex = 7;
//
// back
//
this.back.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.back.AutoSize = true;
this.back.Enabled = false;
this.back.Location = new System.Drawing.Point(222, 10);
this.back.MinimumSize = new System.Drawing.Size(75, 0);
this.back.Name = "back";
this.back.Size = new System.Drawing.Size(77, 23);
this.back.TabIndex = 0;
this.back.Text = "[WixUIBack]";
this.back.UseVisualStyleBackColor = true;
this.back.Click += new System.EventHandler(this.back_Click);
//
// next
//
this.next.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.next.AutoSize = true;
this.next.Enabled = false;
this.next.Location = new System.Drawing.Point(305, 10);
this.next.MinimumSize = new System.Drawing.Size(75, 0);
this.next.Name = "next";
this.next.Size = new System.Drawing.Size(77, 23);
this.next.TabIndex = 0;
this.next.Text = "[WixUINext]";
this.next.UseVisualStyleBackColor = true;
this.next.Click += new System.EventHandler(this.next_Click);
//
// cancel
//
this.cancel.Anchor = System.Windows.Forms.AnchorStyles.Right;
this.cancel.AutoSize = true;
this.cancel.Location = new System.Drawing.Point(402, 10);
this.cancel.MinimumSize = new System.Drawing.Size(75, 0);
this.cancel.Name = "cancel";
this.cancel.Size = new System.Drawing.Size(86, 23);
this.cancel.TabIndex = 0;
this.cancel.Text = "[WixUICancel]";
this.cancel.UseVisualStyleBackColor = true;
this.cancel.Click += new System.EventHandler(this.cancel_Click);
//
// border1
//
this.border1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.border1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.border1.Location = new System.Drawing.Point(0, 0);
this.border1.Name = "border1";
this.border1.Size = new System.Drawing.Size(494, 1);
this.border1.TabIndex = 17;
//
// middlePanel
//
this.middlePanel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.middlePanel.ColumnCount = 1;
this.middlePanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.middlePanel.Controls.Add(this.panel3, 0, 0);
this.middlePanel.Controls.Add(this.panel4, 0, 1);
this.middlePanel.Controls.Add(this.panel5, 0, 2);
this.middlePanel.Location = new System.Drawing.Point(15, 61);
this.middlePanel.Name = "middlePanel";
this.middlePanel.RowCount = 3;
this.middlePanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.middlePanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.middlePanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333F));
this.middlePanel.Size = new System.Drawing.Size(479, 248);
this.middlePanel.TabIndex = 20;
//
// panel3
//
this.panel3.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.panel3.Controls.Add(this.change);
this.panel3.Controls.Add(this.label3);
this.panel3.Location = new System.Drawing.Point(3, 3);
this.panel3.Name = "panel3";
this.panel3.Size = new System.Drawing.Size(473, 76);
this.panel3.TabIndex = 0;
//
// panel4
//
this.panel4.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.panel4.Controls.Add(this.repair);
this.panel4.Controls.Add(this.label4);
this.panel4.Location = new System.Drawing.Point(3, 85);
this.panel4.Name = "panel4";
this.panel4.Size = new System.Drawing.Size(473, 76);
this.panel4.TabIndex = 1;
//
// panel5
//
this.panel5.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.panel5.Controls.Add(this.remove);
this.panel5.Controls.Add(this.label5);
this.panel5.Location = new System.Drawing.Point(3, 167);
this.panel5.Name = "panel5";
this.panel5.Size = new System.Drawing.Size(473, 78);
this.panel5.TabIndex = 2;
//
// MaintenanceTypeDialog
//
this.ClientSize = new System.Drawing.Size(494, 361);
this.Controls.Add(this.middlePanel);
this.Controls.Add(this.topBorder);
this.Controls.Add(this.topPanel);
this.Controls.Add(this.bottomPanel);
this.Name = "MaintenanceTypeDialog";
this.Text = "[MaintenanceTypeDlg_Title]";
this.Load += new System.EventHandler(this.MaintenanceTypeDialog_Load);
this.topPanel.ResumeLayout(false);
this.topPanel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.banner)).EndInit();
this.bottomPanel.ResumeLayout(false);
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.middlePanel.ResumeLayout(false);
this.panel3.ResumeLayout(false);
this.panel3.PerformLayout();
this.panel4.ResumeLayout(false);
this.panel4.PerformLayout();
this.panel5.ResumeLayout(false);
this.panel5.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.PictureBox banner;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Panel topPanel;
private System.Windows.Forms.Panel bottomPanel;
private System.Windows.Forms.Button change;
private System.Windows.Forms.Button repair;
private System.Windows.Forms.Button remove;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Panel border1;
private System.Windows.Forms.Panel topBorder;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.Button back;
private System.Windows.Forms.Button next;
private System.Windows.Forms.Button cancel;
private System.Windows.Forms.TableLayoutPanel middlePanel;
private System.Windows.Forms.Panel panel3;
private System.Windows.Forms.Panel panel4;
private System.Windows.Forms.Panel panel5;
}
}
| |
using System.Collections.Generic;
using UnityEngine.EventSystems;
using UnityEngine.Serialization;
namespace UnityEngine.UI
{
[DisallowMultipleComponent]
[ExecuteInEditMode]
[RequireComponent(typeof(RectTransform))]
public abstract class LayoutGroup : UIBehaviour, ILayoutElement, ILayoutGroup
{
[SerializeField] protected RectOffset m_Padding = new RectOffset();
public RectOffset padding { get { return m_Padding; } set { SetProperty(ref m_Padding, value); } }
[FormerlySerializedAs("m_Alignment")]
[SerializeField] protected TextAnchor m_ChildAlignment = TextAnchor.UpperLeft;
public TextAnchor childAlignment { get { return m_ChildAlignment; } set { SetProperty(ref m_ChildAlignment, value); } }
[System.NonSerialized] private RectTransform m_Rect;
protected RectTransform rectTransform
{
get
{
if (m_Rect == null)
m_Rect = GetComponent<RectTransform>();
return m_Rect;
}
}
protected DrivenRectTransformTracker m_Tracker;
private Vector2 m_TotalMinSize = Vector2.zero;
private Vector2 m_TotalPreferredSize = Vector2.zero;
private Vector2 m_TotalFlexibleSize = Vector2.zero;
[System.NonSerialized] private List<RectTransform> m_RectChildren = new List<RectTransform>();
protected List<RectTransform> rectChildren { get { return m_RectChildren; } }
// ILayoutElement Interface
public virtual void CalculateLayoutInputHorizontal()
{
m_RectChildren.Clear();
var toIgnoreList = ListPool<Component>.Get();
for (int i = 0; i < rectTransform.childCount; i++)
{
var rect = rectTransform.GetChild(i) as RectTransform;
if (rect == null || !rect.gameObject.activeInHierarchy)
continue;
rect.GetComponents(typeof(ILayoutIgnorer), toIgnoreList);
if (toIgnoreList.Count == 0)
{
m_RectChildren.Add(rect);
continue;
}
for (int j = 0; j < toIgnoreList.Count; j++)
{
var ignorer = (ILayoutIgnorer)toIgnoreList[j];
if (!ignorer.ignoreLayout)
{
m_RectChildren.Add(rect);
break;
}
}
}
ListPool<Component>.Release(toIgnoreList);
m_Tracker.Clear();
}
public abstract void CalculateLayoutInputVertical();
public virtual float minWidth { get { return GetTotalMinSize(0); } }
public virtual float preferredWidth { get { return GetTotalPreferredSize(0); } }
public virtual float flexibleWidth { get { return GetTotalFlexibleSize(0); } }
public virtual float minHeight { get { return GetTotalMinSize(1); } }
public virtual float preferredHeight { get { return GetTotalPreferredSize(1); } }
public virtual float flexibleHeight { get { return GetTotalFlexibleSize(1); } }
public virtual int layoutPriority { get { return 0; } }
// ILayoutController Interface
public abstract void SetLayoutHorizontal();
public abstract void SetLayoutVertical();
// Implementation
protected LayoutGroup()
{
if (m_Padding == null)
m_Padding = new RectOffset();
}
#region Unity Lifetime calls
protected override void OnEnable()
{
base.OnEnable();
SetDirty();
}
protected override void OnDisable()
{
m_Tracker.Clear();
LayoutRebuilder.MarkLayoutForRebuild(rectTransform);
base.OnDisable();
}
protected override void OnDidApplyAnimationProperties()
{
SetDirty();
}
#endregion
protected float GetTotalMinSize(int axis)
{
return m_TotalMinSize[axis];
}
protected float GetTotalPreferredSize(int axis)
{
return m_TotalPreferredSize[axis];
}
protected float GetTotalFlexibleSize(int axis)
{
return m_TotalFlexibleSize[axis];
}
protected float GetStartOffset(int axis, float requiredSpaceWithoutPadding)
{
float requiredSpace = requiredSpaceWithoutPadding + (axis == 0 ? padding.horizontal : padding.vertical);
float availableSpace = rectTransform.rect.size[axis];
float surplusSpace = availableSpace - requiredSpace;
float alignmentOnAxis = 0;
if (axis == 0)
alignmentOnAxis = ((int)childAlignment % 3) * 0.5f;
else
alignmentOnAxis = ((int)childAlignment / 3) * 0.5f;
return (axis == 0 ? padding.left : padding.top) + surplusSpace * alignmentOnAxis;
}
protected void SetLayoutInputForAxis(float totalMin, float totalPreferred, float totalFlexible, int axis)
{
m_TotalMinSize[axis] = totalMin;
m_TotalPreferredSize[axis] = totalPreferred;
m_TotalFlexibleSize[axis] = totalFlexible;
}
protected void SetChildAlongAxis(RectTransform rect, int axis, float pos, float size)
{
if (rect == null)
return;
m_Tracker.Add(this, rect,
DrivenTransformProperties.Anchors |
DrivenTransformProperties.AnchoredPosition |
DrivenTransformProperties.SizeDelta);
rect.SetInsetAndSizeFromParentEdge(axis == 0 ? RectTransform.Edge.Left : RectTransform.Edge.Top, pos, size);
}
private bool isRootLayoutGroup
{
get
{
Transform parent = transform.parent;
if (parent == null)
return true;
return transform.parent.GetComponent(typeof(ILayoutGroup)) == null;
}
}
protected override void OnRectTransformDimensionsChange()
{
base.OnRectTransformDimensionsChange();
if (isRootLayoutGroup)
SetDirty();
}
protected virtual void OnTransformChildrenChanged()
{
SetDirty();
}
protected void SetProperty<T>(ref T currentValue, T newValue)
{
if ((currentValue == null && newValue == null) || (currentValue != null && currentValue.Equals(newValue)))
return;
currentValue = newValue;
SetDirty();
}
protected void SetDirty()
{
if (!IsActive())
return;
LayoutRebuilder.MarkLayoutForRebuild(rectTransform);
}
#if UNITY_EDITOR
protected override void OnValidate()
{
SetDirty();
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Microsoft.Ccr.Core;
using Microsoft.Dss.Core.Attributes;
using Microsoft.Dss.ServiceModel.Dssp;
using Microsoft.Dss.ServiceModel.DsspServiceBase;
using W3C.Soap;
using Microsoft.Dss.Core.DsspHttp;
using TrackRoamer.Robotics.Utility.LibPicSensors;
namespace TrackRoamer.Robotics.Services.TrackRoamerBrickProximityBoard
{
/// <summary>
/// TrackRoamerBrickProximityBoard contract class
/// </summary>
public sealed class Contract
{
/// <summary>
/// DSS contract identifer for TrackRoamerBrickProximityBoard
/// </summary>
[DataMember]
public const string Identifier = "http://schemas.trackroamer.com/robotics/2011/01/trackroamerbrickproximityboard.html";
}
/// <summary>
/// TrackRoamerBrickProximityBoard state
/// </summary>
[DataContract]
public class TrackRoamerBrickProximityBoardState
{
[DataMember]
public bool IsConnected = false;
[DataMember]
public Int32 VendorId;
[DataMember]
public Int32 ProductId;
[DataMember]
public DateTime LastSampleTimestamp;
[DataMember]
public string LinkState = "undefined";
[DataMember]
public string Description = "undefined";
/// <summary>
/// Last sonar reading.
/// </summary>
[DataMember, Browsable(true)]
public SonarDataDssSerializable MostRecentSonar = null;
/// <summary>
/// Last compass reading.
/// </summary>
[DataMember, Browsable(true)]
public DirectionDataDssSerializable MostRecentDirection = null;
/// <summary>
/// Last Accelerometer reading.
/// </summary>
[DataMember, Browsable(true)]
public AccelerometerDataDssSerializable MostRecentAccelerometer = null;
/// <summary>
/// Last IR Proximity sensors reading.
/// </summary>
[DataMember, Browsable(true)]
public ProximityDataDssSerializable MostRecentProximity = null;
/// <summary>
/// Last Parking Sensor sensors reading.
/// </summary>
[DataMember, Browsable(true)]
public ParkingSensorDataDssSerializable MostRecentParkingSensor = null;
/// <summary>
/// Last POT reading. (pin 2 AN0 of PIC 4550 etc.)
/// </summary>
[DataMember, Browsable(true)]
public AnalogDataDssSerializable MostRecentAnalogData;
/// <summary>
/// Angular range of the sonar sweep measurement.
/// </summary>
[DataMember]
[Description("The angular range of the sonar sweep measurement.")]
public int AngularRange;
/// <summary>
/// Angular resolution of a given sonar sweep ray.
/// </summary>
[DataMember]
[Description("The angular resolution of the sonar sweep measurement.")]
public double AngularResolution;
}
/// <summary>
/// TrackRoamerBrickProximityBoard main operations port
/// </summary>
[ServicePort]
class TrackRoamerBrickProximityBoardOperations :
PortSet<
DsspDefaultLookup,
DsspDefaultDrop,
Get,
Replace,
ReliableSubscribe,
Subscribe,
UpdateSonarData,
UpdateDirectionData,
UpdateAccelerometerData,
UpdateProximityData,
UpdateParkingSensorData,
UpdateAnalogData,
Reset,
HttpGet
>
{
}
/// <summary>
/// TrackRoamerBrickProximityBoard get operation
/// </summary>
public class Get : Get<GetRequestType, PortSet<TrackRoamerBrickProximityBoardState, Fault>>
{
/// <summary>
/// Creates a new instance of Get
/// </summary>
public Get()
{
}
/// <summary>
/// Creates a new instance of Get
/// </summary>
/// <param name="body">the request message body</param>
public Get(GetRequestType body)
: base(body)
{
}
/// <summary>
/// Creates a new instance of Get
/// </summary>
/// <param name="body">the request message body</param>
/// <param name="responsePort">the response port for the request</param>
public Get(GetRequestType body, PortSet<TrackRoamerBrickProximityBoardState, Fault> responsePort)
: base(body, responsePort)
{
}
}
/// <summary>
/// TrackRoamerBrickProximityBoard subscribe operation
/// </summary>
public class Subscribe : Subscribe<SubscribeRequestType, PortSet<SubscribeResponseType, Fault>>
{
/// <summary>
/// Creates a new instance of Subscribe
/// </summary>
public Subscribe()
{
}
/// <summary>
/// Creates a new instance of Subscribe
/// </summary>
/// <param name="body">the request message body</param>
public Subscribe(SubscribeRequestType body)
: base(body)
{
}
/// <summary>
/// Creates a new instance of Subscribe
/// </summary>
/// <param name="body">the request message body</param>
/// <param name="responsePort">the response port for the request</param>
public Subscribe(SubscribeRequestType body, PortSet<SubscribeResponseType, Fault> responsePort)
: base(body, responsePort)
{
}
}
class ReliableSubscribe : Subscribe<ReliableSubscribeRequestType, DsspResponsePort<SubscribeResponseType>, TrackRoamerBrickProximityBoardOperations> { }
/// <summary>
/// Replace message.
/// Send this message to the SickLRF service port to replace the state of the service.
/// </summary>
[DisplayName("Measurement")]
[Description("Indicates when the Proximity Board reports a new measurement.")]
class Replace : Replace<TrackRoamerBrickProximityBoardState, DsspResponsePort<DefaultReplaceResponseType>> { }
[Description("Resets the Proximity Board.")]
class Reset : Submit<ResetType, DsspResponsePort<DefaultSubmitResponseType>>
{
}
/// <summary>
/// ResetType
/// </summary>
[DataContract]
public class ResetType
{
}
// Notification messages:
[DisplayName("UpdateSonarData")]
[Description("Updates or indicates an arrival of the Sonar sweep frame.")]
public class UpdateSonarData : Update<SonarDataDssSerializable, PortSet<DefaultUpdateResponseType, Fault>>
{
}
[DisplayName("UpdateDirectionData")]
[Description("Updates or indicates an arrival of the Direction data.")]
public class UpdateDirectionData : Update<DirectionDataDssSerializable, PortSet<DefaultUpdateResponseType, Fault>>
{
}
[DisplayName("UpdateAccelerometerData")]
[Description("Updates or indicates an arrival of the Accelerometer data.")]
public class UpdateAccelerometerData : Update<AccelerometerDataDssSerializable, PortSet<DefaultUpdateResponseType, Fault>>
{
}
[DisplayName("UpdateProximityData")]
[Description("Updates or indicates an arrival of the Proximity data.")]
public class UpdateProximityData : Update<ProximityDataDssSerializable, PortSet<DefaultUpdateResponseType, Fault>>
{
}
[DisplayName("UpdateParkingSensorData")]
[Description("Updates or indicates an arrival of the Parking Sensor data.")]
public class UpdateParkingSensorData : Update<ParkingSensorDataDssSerializable, PortSet<DefaultUpdateResponseType, Fault>>
{
}
[DisplayName("UpdateAnalogData")]
[Description("Updates or indicates an arrival of the analog data (pin 2 AN0 of PIC4550 etc.).")]
public class UpdateAnalogData : Update<AnalogDataDssSerializable, PortSet<DefaultUpdateResponseType, Fault>>
{
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.Workflow.Activities.Design
{
partial class OperationPickerDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(OperationPickerDialog));
this.operationsToolStrip = new System.Windows.Forms.ToolStrip();
this.toolStripLabel1 = new System.Windows.Forms.ToolStripLabel();
this.importContractButton = new System.Windows.Forms.ToolStripButton();
this.toolStripButton1 = new System.Windows.Forms.ToolStripButton();
this.addOperationButton = new System.Windows.Forms.ToolStripButton();
this.okButton = new System.Windows.Forms.Button();
this.cancelButton = new System.Windows.Forms.Button();
this.operationsPanel = new System.Workflow.Activities.Design.GradientPanel();
this.operationsListBox = new System.Workflow.Activities.Design.RichListBox();
this.detailsViewPanel = new System.Workflow.Activities.Design.GradientPanel();
this.footerPanel = new System.Workflow.Activities.Design.GradientPanel();
this.operationsToolStrip.SuspendLayout();
this.operationsPanel.SuspendLayout();
this.footerPanel.SuspendLayout();
this.SuspendLayout();
//
// operationsToolStrip
//
this.operationsToolStrip.BackColor = System.Drawing.SystemColors.Control;
this.operationsToolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.operationsToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripLabel1,
this.importContractButton,
this.toolStripButton1,
this.addOperationButton});
resources.ApplyResources(this.operationsToolStrip, "operationsToolStrip");
this.operationsToolStrip.Name = "operationsToolStrip";
this.operationsToolStrip.Stretch = true;
this.operationsToolStrip.TabStop = true;
//
// toolStripLabel1
//
this.toolStripLabel1.Name = "toolStripLabel1";
this.toolStripLabel1.Padding = new System.Windows.Forms.Padding(15, 0, 0, 0);
resources.ApplyResources(this.toolStripLabel1, "toolStripLabel1");
//
// importContractButton
//
this.importContractButton.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this.importContractButton.Image = global::System.ServiceModel.ImageResources.Import;
resources.ApplyResources(this.importContractButton, "importContractButton");
this.importContractButton.Name = "importContractButton";
//
// toolStripButton1
//
this.toolStripButton1.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this.toolStripButton1.Image = global::System.ServiceModel.ImageResources.AddContract;
resources.ApplyResources(this.toolStripButton1, "toolStripButton1");
this.toolStripButton1.Name = "toolStripButton1";
//
// addOperationButton
//
this.addOperationButton.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this.addOperationButton.Image = global::System.ServiceModel.ImageResources.AddOperation;
resources.ApplyResources(this.addOperationButton, "addOperationButton");
this.addOperationButton.Name = "addOperationButton";
//
// okButton
//
resources.ApplyResources(this.okButton, "okButton");
this.okButton.Name = "okButton";
this.okButton.UseVisualStyleBackColor = true;
//
// cancelButton
//
this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel;
resources.ApplyResources(this.cancelButton, "cancelButton");
this.cancelButton.Name = "cancelButton";
this.cancelButton.UseVisualStyleBackColor = true;
//
// operationsPanel
//
resources.ApplyResources(this.operationsPanel, "operationsPanel");
this.operationsPanel.BaseColor = System.Drawing.SystemColors.Window;
this.operationsPanel.BorderColor = System.Drawing.SystemColors.ControlDark;
this.operationsPanel.Controls.Add(this.operationsListBox);
this.operationsPanel.DropShadow = false;
this.operationsPanel.Glossy = false;
this.operationsPanel.LightingColor = System.Drawing.SystemColors.Window;
this.operationsPanel.Name = "operationsPanel";
this.operationsPanel.Radius = 3;
this.operationsPanel.Padding = new System.Windows.Forms.Padding(3);
//
// operationsListBox
//
this.operationsListBox.BackColor = System.Drawing.SystemColors.Window;
this.operationsListBox.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.operationsListBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.operationsListBox.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
this.operationsListBox.Editable = false;
resources.ApplyResources(this.operationsListBox, "operationsListBox");
this.operationsListBox.FormattingEnabled = true;
this.operationsListBox.Name = "operationsListBox";
this.operationsListBox.SelectedItemViewControl = null;
//
// detailsViewPanel
//
resources.ApplyResources(this.detailsViewPanel, "detailsViewPanel");
this.detailsViewPanel.BackColor = System.Drawing.Color.Transparent;
this.detailsViewPanel.BaseColor = System.Drawing.SystemColors.Control;
this.detailsViewPanel.BorderColor = System.Drawing.Color.Transparent;
this.detailsViewPanel.DropShadow = false;
this.detailsViewPanel.Glossy = false;
this.detailsViewPanel.LightingColor = System.Drawing.SystemColors.Control;
this.detailsViewPanel.Name = "detailsViewPanel";
this.detailsViewPanel.Radius = 3;
//
// footerPanel
//
this.footerPanel.BackColor = System.Drawing.SystemColors.Control;
this.footerPanel.BaseColor = System.Drawing.Color.Transparent;
this.footerPanel.BorderColor = System.Drawing.SystemColors.ControlDark;
this.footerPanel.Controls.Add(this.cancelButton);
this.footerPanel.Controls.Add(this.okButton);
resources.ApplyResources(this.footerPanel, "footerPanel");
this.footerPanel.DropShadow = false;
this.footerPanel.Glossy = false;
this.footerPanel.LightingColor = System.Drawing.Color.Transparent;
this.footerPanel.Name = "footerPanel";
this.footerPanel.Radius = 1;
//
// OperationPickerDialog
//
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13f);
this.AutoSize = true;
this.AcceptButton = this.okButton;
this.BackColor = System.Drawing.SystemColors.Control;
this.CancelButton = this.cancelButton;
resources.ApplyResources(this, "$this");
this.Controls.Add(this.operationsToolStrip);
this.Controls.Add(this.operationsPanel);
this.Controls.Add(this.detailsViewPanel);
this.Controls.Add(this.footerPanel);
this.DoubleBuffered = true;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
this.HelpButton = true;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "OperationPickerDialog";
this.ShowIcon = false;
this.ShowInTaskbar = false;
this.Load += new System.EventHandler(this.OperationPickerDialogLoad);
this.operationsToolStrip.ResumeLayout(false);
this.operationsToolStrip.PerformLayout();
this.operationsPanel.ResumeLayout(false);
this.footerPanel.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ToolStrip operationsToolStrip;
private System.Windows.Forms.ToolStripLabel toolStripLabel1;
private System.Windows.Forms.ToolStripButton importContractButton;
private System.Windows.Forms.ToolStripButton toolStripButton1;
private System.Windows.Forms.ToolStripButton addOperationButton;
private GradientPanel operationsPanel;
private RichListBox operationsListBox;
private GradientPanel detailsViewPanel;
private GradientPanel footerPanel;
private System.Windows.Forms.Button cancelButton;
private System.Windows.Forms.Button okButton;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using Castle.Components.Validator;
using Cuyahoga.Core.Service.Membership;
using Cuyahoga.Core.Util;
using Cuyahoga.Core.Validation;
namespace Cuyahoga.Core.Domain
{
/// <summary>
/// Base Class for CMS Content
/// </summary>
public abstract class ContentItem : IContentItem
{
private long _id;
private Guid _globalId;
private WorkflowStatus _workflowStatus;
private string _title;
private string _summary;
private int _version;
private string _locale;
private bool _syndicate;
private DateTime _createdAt;
private DateTime? _publishedAt;
private DateTime? _publishedUntil;
private DateTime _modifiedAt;
private User _createdBy;
private User _publishedBy;
private User _modifiedBy;
private Section _section;
private IList<Category> _categories;
private IList<ContentItemPermission> _contentItemPermissions;
private IList<Comment> _comments;
#region Properties
/// <summary>
/// Property Id (long)
/// </summary>
public virtual long Id
{
get { return this._id; }
set { this._id = value; }
}
/// <summary>
/// Property GlobalId (Guid)
/// </summary>
public virtual Guid GlobalId
{
get { return this._globalId; }
set { this._globalId = value; }
}
/// <summary>
/// Property WorkflowStatus (WorkflowStatus)
/// </summary>
public virtual WorkflowStatus WorkflowStatus
{
get { return this._workflowStatus; }
set { this._workflowStatus = value; }
}
/// <summary>
/// Property Title (string)
/// </summary>
[ValidateNonEmpty("ContentItemTitleValidatorNonEmpty")]
[ValidateLength(1, 100, "ContentItemTitleValidatorLength")]
public virtual string Title
{
get { return this._title; }
set { this._title = value; }
}
/// <summary>
/// Property Summary(string)
/// </summary>
[ValidateLength(1, 255, "ContentItemSummaryValidatorLength")]
public virtual string Summary
{
get { return this._summary; }
set { this._summary = value; }
}
/// <summary>
/// Property Version (int)
/// </summary>
public virtual int Version
{
get { return this._version; }
set { this._version = value; }
}
/// <summary>
/// Property Locale (string)
/// </summary>
public virtual string Locale
{
get{ return this._locale; }
set{ this._locale = value; }
}
/// <summary>
/// Indicates if the content item should be syndicated.
/// </summary>
public virtual bool Syndicate
{
get { return this._syndicate; }
set { this._syndicate = value; }
}
/// <summary>
/// Property CreatedAt (DateTime)
/// </summary>
public virtual DateTime CreatedAt
{
get { return this._createdAt; }
set { this._createdAt = value; }
}
/// <summary>
/// Property PublishedAt (DateTime)
/// </summary>
[CuyValidateDateTime("ContentItemPublishedAtValidatorDateTime")]
public virtual DateTime? PublishedAt
{
get { return this._publishedAt; }
set { this._publishedAt = value; }
}
/// <summary>
/// Property PublishedUntil (DateTime)
/// </summary>
[CuyValidateDateTime("ContentItemPublishedUntilValidatorDateTime")]
[ValidateIsGreater(IsGreaterValidationType.DateTime, "PublishedAt", "ContentItemPublishedUntilValidatorGreaterThanPublishedAt")]
public virtual DateTime? PublishedUntil
{
get { return this._publishedUntil; }
set { this._publishedUntil = value; }
}
/// <summary>
/// Property ModifiedAt (DateTime)
/// </summary>
public virtual DateTime ModifiedAt
{
get { return this._modifiedAt; }
set { this._modifiedAt = value; }
}
/// <summary>
/// Property CreatedBy (User)
/// </summary>
public virtual User CreatedBy
{
get { return this._createdBy; }
set { this._createdBy = value; }
}
/// <summary>
/// Property CreatedBy (User)
/// </summary>
public virtual User PublishedBy
{
get { return this._publishedBy; }
set { this._publishedBy = value; }
}
/// <summary>
/// Property ModifiedBy (User)
/// </summary>
public virtual User ModifiedBy
{
get { return this._modifiedBy; }
set { this._modifiedBy = value; }
}
/// <summary>
/// Property Section (Section)
/// </summary>
public virtual Section Section
{
get { return this._section; }
set { this._section = value; }
}
/// <summary>
/// Property Categories (Category)
/// </summary>
public virtual IList<Category> Categories
{
get { return this._categories; }
set { this._categories = value; }
}
/// <summary>
/// Comments
/// </summary>
public virtual IList<Comment> Comments
{
get { return this._comments; }
set { this._comments = value; }
}
/// <summary>
/// Property ContentItemPermissions (ContentItemPermission)
/// </summary>
public virtual IList<ContentItemPermission> ContentItemPermissions
{
get { return this._contentItemPermissions; }
set { this._contentItemPermissions = value; }
}
/// <summary>
/// Indicates if the content item is new.s
/// </summary>
public virtual bool IsNew
{
get { return this._id == -1; }
}
/// <summary>
/// Indicates if the content item supports item-level permissions. If not, the permissions for the related section
/// are used.
/// </summary>
public virtual bool SupportsItemLevelPermissions
{
get { return false; }
}
/// <summary>
/// The roles that are allowed to view the content item.
/// </summary>
public virtual IEnumerable<Role> ViewRoles
{
get
{
if (SupportsItemLevelPermissions)
{
return this._contentItemPermissions.Where(cip => cip.ViewAllowed).Select(cip => cip.Role);
}
else
{
return this._section.SectionPermissions.Where(sp => sp.ViewAllowed).Select(sp => sp.Role);
}
}
}
#endregion
/// <summary>
/// Constructor.
/// </summary>
protected ContentItem()
{
this._id = -1;
this._globalId = Guid.NewGuid();
this._workflowStatus = WorkflowStatus.Draft;
this._createdAt = DateTime.Now;
this._modifiedAt = DateTime.Now;
this._version = 1;
this._syndicate = true;
this._categories = new List<Category>();
this._contentItemPermissions = new List<ContentItemPermission>();
this._comments = new List<Comment>();
}
/// <summary>
/// Gets the url that corresponds to the content. Inheritors can override this for custom url formatting.
/// </summary>
public virtual string GetContentUrl()
{
string defaultUrlFormat = UrlUtil.GetApplicationPath() + "{0}/section.aspx/{1}";
if (this._section == null)
{
throw new InvalidOperationException("Unable to get the url for the content because the associated section is missing.");
}
return String.Format(defaultUrlFormat, this._section.Id, this._id);
}
public virtual bool IsViewAllowed(IPrincipal currentPrincipal)
{
if (!currentPrincipal.Identity.IsAuthenticated)
{
return this.ViewRoles.Any(vr => vr.HasRight(Rights.Anonymous));
}
if (currentPrincipal is User)
{
return IsViewAllowedForUser((User) currentPrincipal);
}
return false;
}
public virtual bool IsViewAllowedForUser(User user)
{
return this.ViewRoles.Any(user.IsInRole);
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;
namespace Aurora.Framework
{
public static class MultipartForm
{
#region Helper Classes
#region Nested type: Element
public abstract class Element
{
public string Name;
}
#endregion
#region Nested type: File
public class File : Element
{
public string ContentType;
public byte[] Data;
public string Filename;
public File(string name, string filename, string contentType, byte[] data)
{
Name = name;
Filename = filename;
ContentType = contentType;
Data = data;
}
}
#endregion
#region Nested type: Parameter
public class Parameter : Element
{
public string Value;
public Parameter(string name, string value)
{
Name = name;
Value = value;
}
}
#endregion
#endregion Helper Classes
public static HttpWebResponse Post(HttpWebRequest request, List<Element> postParameters)
{
string boundary = Boundary();
// Set up the request properties
request.Method = "POST";
request.ContentType = "multipart/form-data; boundary=" + boundary;
#region Stream Writing
using (MemoryStream formDataStream = new MemoryStream())
{
foreach (var param in postParameters)
{
if (param is File)
{
File file = (File) param;
// Add just the first part of this param, since we will write the file data directly to the Stream
string header =
string.Format(
"--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n",
boundary,
file.Name,
!String.IsNullOrEmpty(file.Filename) ? file.Filename : "tempfile",
file.ContentType);
formDataStream.Write(Encoding.UTF8.GetBytes(header), 0, header.Length);
formDataStream.Write(file.Data, 0, file.Data.Length);
}
else
{
Parameter parameter = (Parameter) param;
string postData =
string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n",
boundary,
parameter.Name,
parameter.Value);
formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, postData.Length);
}
}
// Add the end of the request
byte[] footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");
formDataStream.Write(footer, 0, footer.Length);
request.ContentLength = formDataStream.Length;
// Copy the temporary stream to the network stream
formDataStream.Seek(0, SeekOrigin.Begin);
using (Stream requestStream = request.GetRequestStream())
formDataStream.CopyTo(requestStream, (int) formDataStream.Length);
}
#endregion Stream Writing
return request.GetResponse() as HttpWebResponse;
}
private static string Boundary()
{
Random rnd = new Random();
string formDataBoundary = String.Empty;
while (formDataBoundary.Length < 15)
formDataBoundary = formDataBoundary + rnd.Next();
formDataBoundary = formDataBoundary.Substring(0, 15);
formDataBoundary = "-----------------------------" + formDataBoundary;
return formDataBoundary;
}
}
public static class Extentions
{
#region Stream
/// <summary>
/// Copies the contents of one stream to another, starting at the
/// current position of each stream
/// </summary>
/// <param name = "copyFrom">The stream to copy from, at the position
/// where copying should begin</param>
/// <param name = "copyTo">The stream to copy to, at the position where
/// bytes should be written</param>
/// <param name = "maximumBytesToCopy">The maximum bytes to copy</param>
/// <returns>The total number of bytes copied</returns>
/// <remarks>
/// Copying begins at the streams' current positions. The positions are
/// NOT reset after copying is complete.
/// </remarks>
public static int CopyTo(this Stream copyFrom, Stream copyTo, int maximumBytesToCopy)
{
byte[] buffer = new byte[4096];
int readBytes;
int totalCopiedBytes = 0;
while ((readBytes = copyFrom.Read(buffer, 0, Math.Min(4096, maximumBytesToCopy))) > 0)
{
int writeBytes = Math.Min(maximumBytesToCopy, readBytes);
copyTo.Write(buffer, 0, writeBytes);
totalCopiedBytes += writeBytes;
maximumBytesToCopy -= writeBytes;
}
return totalCopiedBytes;
}
/// <summary>
/// Converts an entire stream to a string, regardless of current stream
/// position
/// </summary>
/// <param name = "stream">The stream to convert to a string</param>
/// <returns></returns>
/// <remarks>
/// When this method is done, the stream position will be
/// reset to its previous position before this method was called
/// </remarks>
public static string GetStreamString(this Stream stream)
{
string value = null;
if (stream != null && stream.CanRead)
{
long rewindPos = -1;
if (stream.CanSeek)
{
rewindPos = stream.Position;
stream.Seek(0, SeekOrigin.Begin);
}
StreamReader reader = new StreamReader(stream);
value = reader.ReadToEnd();
if (rewindPos >= 0)
stream.Seek(rewindPos, SeekOrigin.Begin);
}
return value;
}
#endregion
#region Uri
/// <summary>
/// Combines a Uri that can contain both a base Uri and relative path
/// with a second relative path fragment
/// </summary>
/// <param name = "uri">Starting (base) Uri</param>
/// <param name = "fragment">Relative path fragment to append to the end
/// of the Uri</param>
/// <returns>The combined Uri</returns>
/// <remarks>
/// This is similar to the Uri constructor that takes a base
/// Uri and the relative path, except this method can append a relative
/// path fragment on to an existing relative path
/// </remarks>
public static Uri Combine(this Uri uri, string fragment)
{
string fragment1 = uri.Fragment;
string fragment2 = fragment;
if (!fragment1.EndsWith("/"))
fragment1 = fragment1 + '/';
if (fragment2.StartsWith("/"))
fragment2 = fragment2.Substring(1);
return new Uri(uri, fragment1 + fragment2);
}
/// <summary>
/// Combines a Uri that can contain both a base Uri and relative path
/// with a second relative path fragment. If the fragment is absolute,
/// it will be returned without modification
/// </summary>
/// <param name = "uri">Starting (base) Uri</param>
/// <param name = "fragment">Relative path fragment to append to the end
/// of the Uri, or an absolute Uri to return unmodified</param>
/// <returns>The combined Uri</returns>
public static Uri Combine(this Uri uri, Uri fragment)
{
if (fragment.IsAbsoluteUri)
return fragment;
string fragment1 = uri.Fragment;
string fragment2 = fragment.ToString();
if (!fragment1.EndsWith("/"))
fragment1 = fragment1 + '/';
if (fragment2.StartsWith("/"))
fragment2 = fragment2.Substring(1);
return new Uri(uri, fragment1 + fragment2);
}
/// <summary>
/// Appends a query string to a Uri that may or may not have existing
/// query parameters
/// </summary>
/// <param name = "uri">Uri to append the query to</param>
/// <param name = "query">Query string to append. Can either start with ?
/// or just containg key/value pairs</param>
/// <returns>String representation of the Uri with the query string
/// appended</returns>
public static string AppendQuery(this Uri uri, string query)
{
if (String.IsNullOrEmpty(query))
return uri.ToString();
if (query[0] == '?' || query[0] == '&')
query = query.Substring(1);
string uriStr = uri.ToString();
if (uriStr.Contains("?"))
return uriStr + '&' + query;
else
return uriStr + '?' + query;
}
#endregion Uri
///<summary>
///</summary>
///<param name = "collection"></param>
///<param name = "key"></param>
///<returns></returns>
public static string GetOne(this NameValueCollection collection, string key)
{
string[] values = collection.GetValues(key);
if (values != null && values.Length > 0)
return values[0];
return null;
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class GLexData {
public static GLexData Instance { get; private set; }
private List<GLexGameObject> mGLexGameObjects;
private List<GLexGameObject> mGLexTopGameObjects;
private List<GLexComponent> mGLexComponents;
private GLexGameObject[] mGLexGameObjectsAsArray;
private GLexGameObject[] mGLexTopGameObjectsAsArray;
private GLexComponent[] mGLexComponentsAsArray;
private GLexScene mScene;
private GooProject _project;
public GLexData() {
Instance = this;
GLexMaterial .Reset();
GLexMesh .Reset();
GLexTexture .Reset();
GLexShader .Reset();
GLexSkinnedMeshRenderer.Reset();
GLexBone .Reset();
GLexAnimation .Reset();
GLexAnimationClip .Reset();
GLexAnimationState.Reset();
GooSkybox.Reset();
GLexAudioSource.Reset();
GooSkeleton.Reset();
mGLexGameObjects = new List<GLexGameObject>();
mGLexTopGameObjects = new List<GLexGameObject>();
mGLexComponents = new List<GLexComponent>();
}
public GLexGameObject FindObject(GameObject pObject) {
foreach (var obj in mGLexGameObjects) {
if (obj.GameObject == pObject) {
return obj;
}
}
return null;
}
public void AddGameObject(GLexGameObject converter) {
mGLexGameObjects.Add(converter);
Debug.Log("Added game object: " + converter.Name);
}
public void AddComponent(GLexComponent converter) {
mGLexComponents.Add(converter);
if (converter is GLexScene) {
if (mScene != null) {
mScene = converter as GLexScene;
}
else {
Debug.LogError("GLexData.AddComponent: Only one GLexScene allowed in each export!");
}
}
}
public void Remove(System.Object component, GameObject gameObject = null) {
foreach (GLexComponent glexComponent in mGLexComponents) {
if (glexComponent.Component == component) {
mGLexComponents.Remove(glexComponent);
if (gameObject != null) {
foreach (GLexGameObject glexGameObject in mGLexGameObjects) {
if (glexGameObject.GameObject == gameObject) {
mGLexGameObjects.Remove(glexGameObject);
break;
}
}
}
break;
}
}
}
private static List<GLexGameObject> _addedSettingsTo = new List<GLexGameObject>();
public static void RemoveAddedSettings() {
foreach (GLexGameObject go in _addedSettingsTo) {
GameObject.DestroyImmediate(go.GameObject.GetComponent<GLexGameObjectSettings>());
}
_addedSettingsTo.Clear();
}
public void PrepareForExport() {
if (GLexConfig.GetOption(GLexConfig.SETUNIQUENAMES)) {
Dictionary<string,int> uniqueNames = new Dictionary<string,int>();
foreach (GLexGameObject gameObject in mGLexGameObjects) {
if (gameObject.Settings == null) {
_addedSettingsTo.Add(gameObject);
gameObject.AddSettings();
}
else {
gameObject.ResetSettingsExportName();
}
}
foreach (GLexGameObject gameObject in mGLexGameObjects) {
if (uniqueNames.ContainsKey(gameObject.Settings.UniqueName)) {
gameObject.Settings.UniqueName = gameObject.Settings.UniqueName + (++uniqueNames[gameObject.Settings.UniqueName]).ToString();
}
else {
uniqueNames.Add(gameObject.Settings.UniqueName, 0);
}
}
}
// Keep preparing objects while new ones are being added
int prevGameObjectCount = 0, prevComponentCount = 0;
while (prevGameObjectCount < mGLexGameObjects.Count || prevComponentCount < mGLexComponents.Count) {
int goStart = prevGameObjectCount;
int gcStart = prevComponentCount;
prevGameObjectCount = mGLexGameObjects.Count;
prevComponentCount = mGLexComponents.Count;
for (int i = goStart; i < prevGameObjectCount; ++i) {
mGLexGameObjects[i].PrepareForExport();
}
for (int i = gcStart; i < prevComponentCount; ++i) {
mGLexComponents[i].PrepareForExport();
}
}
// find top objects
foreach (GLexGameObject gameObject in mGLexGameObjects) {
if (!gameObject.HasParent) {
mGLexTopGameObjects.Add (gameObject);
}
}
GLexMaterial .PrepareForExport();
GLexMesh .PrepareForExport();
GLexTexture .PrepareForExport();
GLexShader .PrepareForExport();
GLexSkinnedMeshRenderer.StaticPrepareForExport();
GLexBone .PrepareForExport();
// GLexAnimation .PrepareForExport();
// GLexAnimationClip .PrepareForExport();
mGLexGameObjectsAsArray = mGLexGameObjects.ToArray();
mGLexTopGameObjectsAsArray = mGLexTopGameObjects.ToArray();
mGLexComponentsAsArray = mGLexComponents .ToArray();
mScene.PrepareForExport();
}
public GLexGameObject[] GameObjects {
get {
return mGLexGameObjectsAsArray;
}
}
public GLexGameObject[] TopGameObjects {
get {
return mGLexTopGameObjectsAsArray;
}
}
public GLexComponent[] Components {
get {
return mGLexComponentsAsArray;
}
}
public GLexMaterial[] Materials {
get {
return GLexMaterial.MaterialsAsArray;
}
}
public GLexTexture[] Textures {
get {
return GLexTexture.TexturesAsArray;
}
}
public GLexShader[] Shaders {
get {
return GLexShader.ShadersAsArray;
}
}
public GLexMesh[] Meshes {
get {
return GLexMesh.MeshesAsArray;
}
}
public GLexScene Scene {
get {
return mScene;
}
set {
mScene = value;
}
}
public GooProject Project {
get {
return this._project;
}
set {
_project = value;
}
}
public List<GLexAnimation> Animations {
get {
return GLexAnimation.Animations;
}
}
public List<GLexAnimationState> AnimationStates {
get {
return GLexAnimationState.AllAnimationStates;
}
}
public List<GLexAnimationClip> AnimationClips {
get {
return GLexAnimationClip.AllClips;
}
}
public GLexSound[] SoundClips {
get {
return GLexAudioSource.ClipsAsArray;
}
}
public GLexComponent GetConverterOfType(System.Type type) {
foreach (GLexComponent converter in mGLexComponents) {
if (converter.GetType() == type) {
return converter;
}
}
Debug.LogError("GLexData.GetConverterOfType: Tried to find converter of type " + type.ToString() + " but couldn't find it!");
return null;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void CompareLessThanOrEqualDouble()
{
var test = new SimpleBinaryOpTest__CompareLessThanOrEqualDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__CompareLessThanOrEqualDouble
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Double> _fld1;
public Vector128<Double> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__CompareLessThanOrEqualDouble testClass)
{
var result = Sse2.CompareLessThanOrEqual(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareLessThanOrEqualDouble testClass)
{
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
{
var result = Sse2.CompareLessThanOrEqual(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__CompareLessThanOrEqualDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public SimpleBinaryOpTest__CompareLessThanOrEqualDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.CompareLessThanOrEqual(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.CompareLessThanOrEqual(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.CompareLessThanOrEqual(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareLessThanOrEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareLessThanOrEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareLessThanOrEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.CompareLessThanOrEqual(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Double>* pClsVar1 = &_clsVar1)
fixed (Vector128<Double>* pClsVar2 = &_clsVar2)
{
var result = Sse2.CompareLessThanOrEqual(
Sse2.LoadVector128((Double*)(pClsVar1)),
Sse2.LoadVector128((Double*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = Sse2.CompareLessThanOrEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareLessThanOrEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareLessThanOrEqual(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__CompareLessThanOrEqualDouble();
var result = Sse2.CompareLessThanOrEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__CompareLessThanOrEqualDouble();
fixed (Vector128<Double>* pFld1 = &test._fld1)
fixed (Vector128<Double>* pFld2 = &test._fld2)
{
var result = Sse2.CompareLessThanOrEqual(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.CompareLessThanOrEqual(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
{
var result = Sse2.CompareLessThanOrEqual(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.CompareLessThanOrEqual(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.CompareLessThanOrEqual(
Sse2.LoadVector128((Double*)(&test._fld1)),
Sse2.LoadVector128((Double*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(result[0]) != ((left[0] <= right[0]) ? -1 : 0))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != ((left[i] <= right[i]) ? -1 : 0))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.CompareLessThanOrEqual)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Media3D;
namespace MaterialDesignThemes.Wpf
{
public static class DataGridAssist
{
private static DataGrid _suppressComboAutoDropDown;
public static readonly DependencyProperty AutoGeneratedCheckBoxStyleProperty = DependencyProperty
.RegisterAttached(
"AutoGeneratedCheckBoxStyle", typeof (Style), typeof (DataGridAssist),
new PropertyMetadata(default(Style), AutoGeneratedCheckBoxStylePropertyChangedCallback));
private static void AutoGeneratedCheckBoxStylePropertyChangedCallback(DependencyObject dependencyObject,
DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
((DataGrid) dependencyObject).AutoGeneratingColumn += (sender, args) =>
{
var dataGridCheckBoxColumn = args.Column as DataGridCheckBoxColumn;
if (dataGridCheckBoxColumn == null) return;
dataGridCheckBoxColumn.ElementStyle = GetAutoGeneratedCheckBoxStyle(dependencyObject);
};
}
public static void SetAutoGeneratedCheckBoxStyle(DependencyObject element, Style value)
{
element.SetValue(AutoGeneratedCheckBoxStyleProperty, value);
}
public static Style GetAutoGeneratedCheckBoxStyle(DependencyObject element)
{
return (Style) element.GetValue(AutoGeneratedCheckBoxStyleProperty);
}
public static readonly DependencyProperty AutoGeneratedEditingCheckBoxStyleProperty = DependencyProperty
.RegisterAttached(
"AutoGeneratedEditingCheckBoxStyle", typeof (Style), typeof (DataGridAssist),
new PropertyMetadata(default(Style), AutoGeneratedEditingCheckBoxStylePropertyChangedCallback));
private static void AutoGeneratedEditingCheckBoxStylePropertyChangedCallback(DependencyObject dependencyObject,
DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
((DataGrid) dependencyObject).AutoGeneratingColumn += (sender, args) =>
{
var dataGridCheckBoxColumn = args.Column as DataGridCheckBoxColumn;
if (dataGridCheckBoxColumn == null) return;
dataGridCheckBoxColumn.EditingElementStyle = GetAutoGeneratedEditingCheckBoxStyle(dependencyObject);
};
}
public static void SetAutoGeneratedEditingCheckBoxStyle(DependencyObject element, Style value)
{
element.SetValue(AutoGeneratedEditingCheckBoxStyleProperty, value);
}
public static Style GetAutoGeneratedEditingCheckBoxStyle(DependencyObject element)
{
return (Style) element.GetValue(AutoGeneratedEditingCheckBoxStyleProperty);
}
public static readonly DependencyProperty AutoGeneratedEditingTextStyleProperty = DependencyProperty
.RegisterAttached(
"AutoGeneratedEditingTextStyle", typeof (Style), typeof (DataGridAssist),
new PropertyMetadata(default(Style), AutoGeneratedEditingTextStylePropertyChangedCallback));
private static void AutoGeneratedEditingTextStylePropertyChangedCallback(DependencyObject dependencyObject,
DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
((DataGrid) dependencyObject).AutoGeneratingColumn += (sender, args) =>
{
var dataGridTextColumn = args.Column as DataGridTextColumn;
if (dataGridTextColumn == null) return;
dataGridTextColumn.EditingElementStyle = GetAutoGeneratedEditingTextStyle(dependencyObject);
};
}
public static void SetAutoGeneratedEditingTextStyle(DependencyObject element, Style value)
{
element.SetValue(AutoGeneratedEditingTextStyleProperty, value);
}
public static Style GetAutoGeneratedEditingTextStyle(DependencyObject element)
{
return (Style) element.GetValue(AutoGeneratedEditingTextStyleProperty);
}
public static readonly DependencyProperty CellPaddingProperty = DependencyProperty.RegisterAttached(
"CellPadding", typeof (Thickness), typeof (DataGridAssist),
new FrameworkPropertyMetadata(new Thickness(13, 8, 8, 8), FrameworkPropertyMetadataOptions.Inherits));
public static void SetCellPadding(DependencyObject element, Thickness value)
{
element.SetValue(CellPaddingProperty, value);
}
public static Thickness GetCellPadding(DependencyObject element)
{
return (Thickness) element.GetValue(CellPaddingProperty);
}
public static readonly DependencyProperty ColumnHeaderPaddingProperty = DependencyProperty.RegisterAttached(
"ColumnHeaderPadding", typeof (Thickness), typeof (DataGridAssist),
new FrameworkPropertyMetadata(new Thickness(8), FrameworkPropertyMetadataOptions.Inherits));
public static void SetColumnHeaderPadding(DependencyObject element, Thickness value)
{
element.SetValue(ColumnHeaderPaddingProperty, value);
}
public static Thickness GetColumnHeaderPadding(DependencyObject element)
{
return (Thickness) element.GetValue(ColumnHeaderPaddingProperty);
}
public static readonly DependencyProperty EnableEditBoxAssistProperty = DependencyProperty.RegisterAttached(
"EnableEditBoxAssist", typeof (bool), typeof (DataGridAssist),
new PropertyMetadata(default(bool), EnableCheckBoxAssistPropertyChangedCallback));
public static void SetEnableEditBoxAssist(DependencyObject element, bool value)
{
element.SetValue(EnableEditBoxAssistProperty, value);
}
public static bool GetEnableEditBoxAssist(DependencyObject element)
{
return (bool) element.GetValue(EnableEditBoxAssistProperty);
}
private static void EnableCheckBoxAssistPropertyChangedCallback(DependencyObject dependencyObject,
DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
var dataGrid = dependencyObject as DataGrid;
if (dataGrid == null) return;
if ((bool) dependencyPropertyChangedEventArgs.NewValue)
dataGrid.PreviewMouseLeftButtonDown += DataGridOnPreviewMouseLeftButtonDown;
else
dataGrid.PreviewMouseLeftButtonDown -= DataGridOnPreviewMouseLeftButtonDown;
}
private static void DataGridOnPreviewMouseLeftButtonDown(object sender,
MouseButtonEventArgs mouseButtonEventArgs)
{
var dataGrid = (DataGrid) sender;
var inputHitTest =
dataGrid.InputHitTest(mouseButtonEventArgs.GetPosition((DataGrid) sender)) as DependencyObject;
while (inputHitTest != null)
{
var dataGridCell = inputHitTest as DataGridCell;
if (dataGridCell != null && dataGrid.Equals(dataGridCell.GetVisualAncestry().OfType<DataGrid>().FirstOrDefault()))
{
if (dataGridCell.IsReadOnly) return;
ToggleButton toggleButton;
ComboBox comboBox;
if (IsDirectHitOnEditComponent(dataGridCell, mouseButtonEventArgs, out toggleButton))
{
dataGrid.CurrentCell = new DataGridCellInfo(dataGridCell);
dataGrid.BeginEdit();
toggleButton.SetCurrentValue(ToggleButton.IsCheckedProperty, !toggleButton.IsChecked);
dataGrid.CommitEdit();
mouseButtonEventArgs.Handled = true;
}
else if (IsDirectHitOnEditComponent(dataGridCell, mouseButtonEventArgs, out comboBox))
{
if (_suppressComboAutoDropDown != null) return;
dataGrid.CurrentCell = new DataGridCellInfo(dataGridCell);
dataGrid.BeginEdit();
//check again, as we move to the edit template
if (IsDirectHitOnEditComponent(dataGridCell, mouseButtonEventArgs, out comboBox))
{
_suppressComboAutoDropDown = dataGrid;
comboBox.DropDownClosed += ComboBoxOnDropDownClosed;
comboBox.IsDropDownOpen = true;
}
mouseButtonEventArgs.Handled = true;
}
return;
}
inputHitTest = (inputHitTest is Visual || inputHitTest is Visual3D)
? VisualTreeHelper.GetParent(inputHitTest)
: null;
}
}
private static void ComboBoxOnDropDownClosed(object sender, EventArgs eventArgs)
{
_suppressComboAutoDropDown.CommitEdit();
_suppressComboAutoDropDown = null;
((ComboBox)sender).DropDownClosed -= ComboBoxOnDropDownClosed;
}
private static bool IsDirectHitOnEditComponent<TControl>(ContentControl contentControl, MouseEventArgs mouseButtonEventArgs, out TControl control)
where TControl : Control
{
control = contentControl.Content as TControl;
if (control == null) return false;
var frameworkElement = VisualTreeHelper.GetChild(contentControl, 0) as FrameworkElement;
if (frameworkElement == null) return false;
var transformToAncestor = (MatrixTransform) control.TransformToAncestor(frameworkElement);
var rect = new Rect(
new Point(transformToAncestor.Value.OffsetX, transformToAncestor.Value.OffsetY),
new Size(control.ActualWidth, control.ActualHeight));
return rect.Contains(mouseButtonEventArgs.GetPosition(frameworkElement));
}
}
}
| |
// A unit group in the game. This may consist of a ship and any number of crew.
// DO NOT MODIFY THIS FILE
// Never try to directly create an instance of this class, or modify its member variables.
// Instead, you should only be reading its variables and calling its functions.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// <<-- Creer-Merge: usings -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
// you can add additional using(s) here
// <<-- /Creer-Merge: usings -->>
namespace Joueur.cs.Games.Pirates
{
/// <summary>
/// A unit group in the game. This may consist of a ship and any number of crew.
/// </summary>
public class Unit : Pirates.GameObject
{
#region Properties
/// <summary>
/// Whether this Unit has performed its action this turn.
/// </summary>
public bool Acted { get; protected set; }
/// <summary>
/// How many crew are on this Tile. This number will always be <= crewHealth.
/// </summary>
public int Crew { get; protected set; }
/// <summary>
/// How much total health the crew on this Tile have.
/// </summary>
public int CrewHealth { get; protected set; }
/// <summary>
/// How much gold this Unit is carrying.
/// </summary>
public int Gold { get; protected set; }
/// <summary>
/// How many more times this Unit may move this turn.
/// </summary>
public int Moves { get; protected set; }
/// <summary>
/// The Player that owns and can control this Unit, or null if the Unit is neutral.
/// </summary>
public Pirates.Player Owner { get; protected set; }
/// <summary>
/// (Merchants only) The path this Unit will follow. The first element is the Tile this Unit will move to next.
/// </summary>
public IList<Pirates.Tile> Path { get; protected set; }
/// <summary>
/// If a ship is on this Tile, how much health it has remaining. 0 for no ship.
/// </summary>
public int ShipHealth { get; protected set; }
/// <summary>
/// (Merchants only) The number of turns this merchant ship won't be able to move. They will still attack. Merchant ships are stunned when they're attacked.
/// </summary>
public int StunTurns { get; protected set; }
/// <summary>
/// (Merchants only) The Port this Unit is moving to.
/// </summary>
public Pirates.Port TargetPort { get; protected set; }
/// <summary>
/// The Tile this Unit is on.
/// </summary>
public Pirates.Tile Tile { get; protected set; }
// <<-- Creer-Merge: properties -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
// you can add additional properties(s) here. None of them will be tracked or updated by the server.
// <<-- /Creer-Merge: properties -->>
#endregion
#region Methods
/// <summary>
/// Creates a new instance of Unit. Used during game initialization, do not call directly.
/// </summary>
protected Unit() : base()
{
this.Path = new List<Pirates.Tile>();
}
/// <summary>
/// Attacks either the 'crew' or 'ship' on a Tile in range.
/// </summary>
/// <param name="tile">The Tile to attack.</param>
/// <param name="target">Whether to attack 'crew' or 'ship'. Crew deal damage to crew and ships deal damage to ships. Consumes any remaining moves.</param>
/// <returns>True if successfully attacked, false otherwise.</returns>
public bool Attack(Pirates.Tile tile, string target)
{
return this.RunOnServer<bool>("attack", new Dictionary<string, object> {
{"tile", tile},
{"target", target}
});
}
/// <summary>
/// Buries gold on this Unit's Tile. Gold must be a certain distance away for it to get interest (Game.minInterestDistance).
/// </summary>
/// <param name="amount">How much gold this Unit should bury. Amounts <= 0 will bury as much as possible.</param>
/// <returns>True if successfully buried, false otherwise.</returns>
public bool Bury(int amount)
{
return this.RunOnServer<bool>("bury", new Dictionary<string, object> {
{"amount", amount}
});
}
/// <summary>
/// Puts gold into an adjacent Port. If that Port is the Player's port, the gold is added to that Player. If that Port is owned by merchants, it adds to that Port's investment.
/// </summary>
/// <param name="amount">The amount of gold to deposit. Amounts <= 0 will deposit all the gold on this Unit.</param>
/// <returns>True if successfully deposited, false otherwise.</returns>
public bool Deposit(int amount=0)
{
return this.RunOnServer<bool>("deposit", new Dictionary<string, object> {
{"amount", amount}
});
}
/// <summary>
/// Digs up gold on this Unit's Tile.
/// </summary>
/// <param name="amount">How much gold this Unit should take. Amounts <= 0 will dig up as much as possible.</param>
/// <returns>True if successfully dug up, false otherwise.</returns>
public bool Dig(int amount=0)
{
return this.RunOnServer<bool>("dig", new Dictionary<string, object> {
{"amount", amount}
});
}
/// <summary>
/// Moves this Unit from its current Tile to an adjacent Tile. If this Unit merges with another one, the other Unit will be destroyed and its tile will be set to null. Make sure to check that your Unit's tile is not null before doing things with it.
/// </summary>
/// <param name="tile">The Tile this Unit should move to.</param>
/// <returns>True if it moved, false otherwise.</returns>
public bool Move(Pirates.Tile tile)
{
return this.RunOnServer<bool>("move", new Dictionary<string, object> {
{"tile", tile}
});
}
/// <summary>
/// Regenerates this Unit's health. Must be used in range of a port.
/// </summary>
/// <returns>True if successfully rested, false otherwise.</returns>
public bool Rest()
{
return this.RunOnServer<bool>("rest", new Dictionary<string, object> {
});
}
/// <summary>
/// Moves a number of crew from this Unit to the given Tile. This will consume a move from those crew.
/// </summary>
/// <param name="tile">The Tile to move the crew to.</param>
/// <param name="amount">The number of crew to move onto that Tile. Amount <= 0 will move all the crew to that Tile.</param>
/// <param name="gold">The amount of gold the crew should take with them. Gold < 0 will move all the gold to that Tile.</param>
/// <returns>True if successfully split, false otherwise.</returns>
public bool Split(Pirates.Tile tile, int amount=1, int gold=0)
{
return this.RunOnServer<bool>("split", new Dictionary<string, object> {
{"tile", tile},
{"amount", amount},
{"gold", gold}
});
}
/// <summary>
/// Takes gold from the Player. You can only withdraw from your own Port.
/// </summary>
/// <param name="amount">The amount of gold to withdraw. Amounts <= 0 will withdraw everything.</param>
/// <returns>True if successfully withdrawn, false otherwise.</returns>
public bool Withdraw(int amount=0)
{
return this.RunOnServer<bool>("withdraw", new Dictionary<string, object> {
{"amount", amount}
});
}
// <<-- Creer-Merge: methods -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
// you can add additional method(s) here.
// <<-- /Creer-Merge: methods -->>
#endregion
}
}
| |
using System;
using System.IO;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria.GameContent.UI.Elements;
using Terraria.Graphics;
using Terraria.ModLoader.IO;
using Terraria.UI;
using System.Net;
using System.Net.Security;
using System.Collections.Specialized;
using System.Xml;
using System.Text;
using Terraria.ID;
using Newtonsoft.Json.Linq;
namespace Terraria.ModLoader.UI
{
internal class UIModDownloadItem : UIPanel
{
public string mod;
public string displayname;
public string version;
public string author;
public string download;
public string timeStamp;
public int downloads;
private Texture2D dividerTexture;
private Texture2D innerPanelTexture;
private UIText modName;
UITextPanel<string> button2;
public bool update = false;
public bool exists = false;
public UIModDownloadItem(string displayname, string name, string version, string author, string download, int downloads, string timeStamp, bool update, bool exists)
{
this.displayname = displayname;
this.mod = name;
this.version = version;
this.author = author;
this.download = download;
this.downloads = downloads;
this.timeStamp = timeStamp;
this.update = update;
this.exists = exists;
this.BorderColor = new Color(89, 116, 213) * 0.7f;
this.dividerTexture = TextureManager.Load("Images/UI/Divider");
this.innerPanelTexture = TextureManager.Load("Images/UI/InnerPanelBackground");
this.Height.Set(90f, 0f);
this.Width.Set(0f, 1f);
base.SetPadding(6f);
string text = displayname + " " + version + " - by " + author;
this.modName = new UIText(text, 1f, false);
this.modName.Left.Set(10f, 0f);
this.modName.Top.Set(5f, 0f);
base.Append(this.modName);
UITextPanel<string> button = new UITextPanel<string>("More info", 1f, false);
button.Width.Set(100f, 0f);
button.Height.Set(30f, 0f);
button.Left.Set(10f, 0f);
button.Top.Set(40f, 0f);
button.PaddingTop -= 2f;
button.PaddingBottom -= 2f;
button.OnMouseOver += UICommon.FadedMouseOver;
button.OnMouseOut += UICommon.FadedMouseOut;
button.OnClick += RequestMoreinfo;
base.Append(button);
if (update || !exists)
{
button2 = new UITextPanel<string>(this.update ? "Update" : "Download", 1f, false);
button2.CopyStyle(button);
button2.Width.Set(200f, 0f);
button2.Left.Set(150f, 0f);
button2.OnMouseOver += UICommon.FadedMouseOver;
button2.OnMouseOut += UICommon.FadedMouseOut;
button2.OnClick += this.DownloadMod;
base.Append(button2);
}
base.OnDoubleClick += RequestMoreinfo;
}
public override int CompareTo(object obj)
{
switch (Interface.modBrowser.sortMode)
{
case SortModes.DisplayNameAtoZ:
return this.displayname.CompareTo((obj as UIModDownloadItem).displayname);
case SortModes.DisplayNameZtoA:
return -1 * this.displayname.CompareTo((obj as UIModDownloadItem).displayname);
case SortModes.DownloadsAscending:
return this.downloads.CompareTo((obj as UIModDownloadItem).downloads);
case SortModes.DownloadsDescending:
return -1 * this.downloads.CompareTo((obj as UIModDownloadItem).downloads);
case SortModes.RecentlyUpdated:
return -1 * this.timeStamp.CompareTo((obj as UIModDownloadItem).timeStamp);
}
return base.CompareTo(obj);
}
public override bool PassFilters()
{
if(Interface.modBrowser.specialModPackFilter != null && !Interface.modBrowser.specialModPackFilter.Contains(mod))
{
return false;
}
if (Interface.modBrowser.filter.Length > 0)
{
if (Interface.modBrowser.searchFilterMode == SearchFilter.Author)
{
if (author.IndexOf(Interface.modBrowser.filter, StringComparison.OrdinalIgnoreCase) == -1)
{
return false;
}
}
else
{
if (displayname.IndexOf(Interface.modBrowser.filter, StringComparison.OrdinalIgnoreCase) == -1)
{
return false;
}
}
}
switch (Interface.modBrowser.updateFilterMode)
{
case UpdateFilter.All:
return true;
case UpdateFilter.Available:
return update || !exists;
case UpdateFilter.UpdateOnly:
return update;
}
return true;
}
protected override void DrawSelf(SpriteBatch spriteBatch)
{
base.DrawSelf(spriteBatch);
CalculatedStyle innerDimensions = base.GetInnerDimensions();
Vector2 drawPos = new Vector2(innerDimensions.X + 5f, innerDimensions.Y + 30f);
spriteBatch.Draw(this.dividerTexture, drawPos, null, Color.White, 0f, Vector2.Zero, new Vector2((innerDimensions.Width - 10f) / 8f, 1f), SpriteEffects.None, 0f);
drawPos = new Vector2(innerDimensions.X + innerDimensions.Width - 180, innerDimensions.Y + 45);
this.DrawPanel(spriteBatch, drawPos, 180f);
this.DrawTimeText(spriteBatch, drawPos + new Vector2(5f, 5f));
}
private void DrawPanel(SpriteBatch spriteBatch, Vector2 position, float width)
{
spriteBatch.Draw(this.innerPanelTexture, position, new Rectangle?(new Rectangle(0, 0, 8, this.innerPanelTexture.Height)), Color.White);
spriteBatch.Draw(this.innerPanelTexture, new Vector2(position.X + 8f, position.Y), new Rectangle?(new Rectangle(8, 0, 8, this.innerPanelTexture.Height)), Color.White, 0f, Vector2.Zero, new Vector2((width - 16f) / 8f, 1f), SpriteEffects.None, 0f);
spriteBatch.Draw(this.innerPanelTexture, new Vector2(position.X + width - 8f, position.Y), new Rectangle?(new Rectangle(16, 0, 8, this.innerPanelTexture.Height)), Color.White);
}
private void DrawTimeText(SpriteBatch spriteBatch, Vector2 drawPos)
{
if (timeStamp == "0000-00-00 00:00:00")
{
return;
}
try
{
DateTime MyDateTime = DateTime.Parse(timeStamp);
string text = TimeHelper.HumanTimeSpanString(MyDateTime);
Utils.DrawBorderString(spriteBatch, "Updated: " + text, drawPos, Color.White, 1f, 0f, 0f, -1);
}
catch
{
return;
}
}
public override void MouseOver(UIMouseEvent evt)
{
base.MouseOver(evt);
this.BackgroundColor = new Color(73, 94, 171);
this.BorderColor = new Color(89, 116, 213);
}
public override void MouseOut(UIMouseEvent evt)
{
base.MouseOut(evt);
this.BackgroundColor = new Color(63, 82, 151) * 0.7f;
this.BorderColor = new Color(89, 116, 213) * 0.7f;
}
internal void DownloadMod(UIMouseEvent evt, UIElement listeningElement)
{
Main.PlaySound(12, -1, -1, 1);
try
{
using (WebClient client = new WebClient())
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((sender, certificate, chain, policyErrors) => { return true; });
Interface.modBrowser.selectedItem = this;
Interface.downloadMod.SetDownloading(displayname);
Interface.downloadMod.SetCancel(client.CancelAsync);
client.DownloadProgressChanged += (s, e) =>
{
Interface.downloadMod.SetProgress(e);
};
client.DownloadFileCompleted += (s, e) =>
{
Main.menuMode = Interface.modBrowserID;
if (e.Error != null)
{
if (e.Cancelled)
{
}
else
{
HttpStatusCode httpStatusCode = GetHttpStatusCode(e.Error);
if (httpStatusCode == HttpStatusCode.ServiceUnavailable)
{
Interface.errorMessage.SetMessage("The Mod Browser server is under heavy load. Try again later.");
Interface.errorMessage.SetGotoMenu(0);
Interface.errorMessage.SetFile(ErrorLogger.LogPath);
Main.gameMenu = true;
Main.menuMode = Interface.errorMessageID;
}
else
{
Interface.errorMessage.SetMessage("Unknown Mod Browser Error. Try again later.");
Interface.errorMessage.SetGotoMenu(0);
Interface.errorMessage.SetFile(ErrorLogger.LogPath);
Main.gameMenu = true;
Main.menuMode = Interface.errorMessageID;
}
}
}
else if (!e.Cancelled)
{
// Downloaded OK
File.Copy(ModLoader.ModPath + Path.DirectorySeparatorChar + "temporaryDownload.tmod", ModLoader.ModPath + Path.DirectorySeparatorChar + mod + ".tmod", true);
if (!update)
{
Interface.modBrowser.aNewModDownloaded = true;
string path = ModLoader.ModPath + Path.DirectorySeparatorChar + mod + ".enabled";
using (StreamWriter writer = File.CreateText(path))
{
writer.Write("false");
}
}
else
{
Interface.modBrowser.aModUpdated = true;
}
RemoveChild(button2);
}
// Clean up: Delete temp
File.Delete(ModLoader.ModPath + Path.DirectorySeparatorChar + "temporaryDownload.tmod");
};
client.DownloadFileAsync(new Uri(download), ModLoader.ModPath + Path.DirectorySeparatorChar + "temporaryDownload.tmod");
//client.DownloadFileAsync(new Uri(download), ModLoader.ModPath + Path.DirectorySeparatorChar + mod + ".tmod");
}
Main.menuMode = Interface.downloadModID;
}
catch (WebException e)
{
ErrorLogger.LogModBrowserException(e);
}
}
internal void RequestMoreinfo(UIMouseEvent evt, UIElement listeningElement)
{
Main.PlaySound(SoundID.MenuOpen);
try
{
ServicePointManager.Expect100Continue = false;
string url = "http://javid.ddns.net/tModLoader/moddescription.php";
var values = new NameValueCollection
{
{ "modname", mod },
};
using (WebClient client = new WebClient())
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((sender, certificate, chain, policyErrors) => { return true; });
client.UploadValuesCompleted += new UploadValuesCompletedEventHandler(Moreinfo);
client.UploadValuesAsync(new Uri(url), "POST", values);
}
}
catch (Exception e)
{
ErrorLogger.LogModBrowserException(e);
return;
}
}
internal void Moreinfo(Object sender, UploadValuesCompletedEventArgs e)
{
string description = "There was a problem, try again";
string homepage = "";
if (!e.Cancelled)
{
string response = Encoding.UTF8.GetString(e.Result);
JObject joResponse = JObject.Parse(response);
description = (string)joResponse["description"];
homepage = (string)joResponse["homepage"];
}
Interface.modInfo.SetModName(this.displayname);
Interface.modInfo.SetModInfo(description);
Interface.modInfo.SetGotoMenu(Interface.modBrowserID);
Interface.modInfo.SetURL(homepage);
Main.menuMode = Interface.modInfoID;
}
HttpStatusCode GetHttpStatusCode(System.Exception err)
{
if (err is WebException)
{
WebException we = (WebException)err;
if (we.Response is HttpWebResponse)
{
HttpWebResponse response = (HttpWebResponse)we.Response;
return response.StatusCode;
}
}
return 0;
}
}
class TimeHelper
{
const int SECOND = 1;
const int MINUTE = 60 * SECOND;
const int HOUR = 60 * MINUTE;
const int DAY = 24 * HOUR;
const int MONTH = 30 * DAY;
public static string HumanTimeSpanString(DateTime yourDate)
{
var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);
double delta = Math.Abs(ts.TotalSeconds);
if (delta < 1 * MINUTE)
return ts.Seconds == 1 ? "1 second ago" : ts.Seconds + " seconds ago";
if (delta < 2 * MINUTE)
return "1 minute ago";
if (delta < 45 * MINUTE)
return ts.Minutes + " minutes ago";
if (delta < 90 * MINUTE)
return "1 hour ago";
if (delta < 24 * HOUR)
return ts.Hours + " hours ago";
if (delta < 48 * HOUR)
return "1 day ago";
if (delta < 30 * DAY)
return ts.Days + " days ago";
if (delta < 12 * MONTH)
{
int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
return months <= 1 ? "1 month ago" : months + " mnths ago";
}
else
{
int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
return years <= 1 ? "1 year ago" : years + " years ago";
}
}
}
}
| |
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.
using Avalonia.Data;
using Avalonia.Interactivity;
using Avalonia.VisualTree;
using Avalonia.Collections;
using Avalonia.Utilities;
using System;
using System.ComponentModel;
using System.Linq;
using System.Diagnostics;
using Avalonia.Controls.Templates;
using Avalonia.Controls.Utils;
using Avalonia.Layout;
using Avalonia.Markup.Xaml.MarkupExtensions;
namespace Avalonia.Controls
{
public abstract class DataGridColumn : AvaloniaObject
{
internal const int DATAGRIDCOLUMN_maximumWidth = 65536;
private const bool DATAGRIDCOLUMN_defaultIsReadOnly = false;
private DataGridLength? _width; // Null by default, null means inherit the Width from the DataGrid
private bool? _isReadOnly;
private double? _maxWidth;
private double? _minWidth;
private bool _settingWidthInternally;
private int _displayIndexWithFiller;
private object _header;
private IDataTemplate _headerTemplate;
private DataGridColumnHeader _headerCell;
private IControl _editingElement;
private ICellEditBinding _editBinding;
private IBinding _clipboardContentBinding;
private readonly Classes _cellStyleClasses = new Classes();
/// <summary>
/// Initializes a new instance of the <see cref="T:Avalonia.Controls.DataGridColumn" /> class.
/// </summary>
protected internal DataGridColumn()
{
_displayIndexWithFiller = -1;
IsInitialDesiredWidthDetermined = false;
InheritsWidth = true;
}
internal DataGrid OwningGrid
{
get;
set;
}
internal int Index
{
get;
set;
}
internal bool? CanUserReorderInternal
{
get;
set;
}
internal bool? CanUserResizeInternal
{
get;
set;
}
internal bool? CanUserSortInternal
{
get;
set;
}
internal bool ActualCanUserResize
{
get
{
if (OwningGrid == null || OwningGrid.CanUserResizeColumns == false || this is DataGridFillerColumn)
{
return false;
}
return CanUserResizeInternal ?? true;
}
}
// MaxWidth from local setting or DataGrid setting
internal double ActualMaxWidth
{
get
{
return _maxWidth ?? OwningGrid?.MaxColumnWidth ?? double.PositiveInfinity;
}
}
// MinWidth from local setting or DataGrid setting
internal double ActualMinWidth
{
get
{
double minWidth = _minWidth ?? OwningGrid?.MinColumnWidth ?? 0;
if (Width.IsStar)
{
return Math.Max(DataGrid.DATAGRID_minimumStarColumnWidth, minWidth);
}
return minWidth;
}
}
internal bool DisplayIndexHasChanged
{
get;
set;
}
internal int DisplayIndexWithFiller
{
get { return _displayIndexWithFiller; }
set { _displayIndexWithFiller = value; }
}
internal bool HasHeaderCell
{
get
{
return _headerCell != null;
}
}
internal DataGridColumnHeader HeaderCell
{
get
{
if (_headerCell == null)
{
_headerCell = CreateHeader();
}
return _headerCell;
}
}
/// <summary>
/// Tracks whether or not this column inherits its Width value from the DataGrid.
/// </summary>
internal bool InheritsWidth
{
get;
private set;
}
/// <summary>
/// When a column is initially added, we won't know its initial desired value
/// until all rows have been measured. We use this variable to track whether or
/// not the column has been fully measured.
/// </summary>
internal bool IsInitialDesiredWidthDetermined
{
get;
set;
}
internal double LayoutRoundedWidth
{
get;
private set;
}
internal ICellEditBinding CellEditBinding
{
get => _editBinding;
}
/// <summary>
/// Defines the <see cref="IsVisible"/> property.
/// </summary>
public static StyledProperty<bool> IsVisibleProperty =
Control.IsVisibleProperty.AddOwner<DataGridColumn>();
/// <summary>
/// Determines whether or not this column is visible.
/// </summary>
public bool IsVisible
{
get => GetValue(IsVisibleProperty);
set => SetValue(IsVisibleProperty, value);
}
protected override void OnPropertyChanged<T>(AvaloniaPropertyChangedEventArgs<T> change)
{
base.OnPropertyChanged(change);
if (change.Property == IsVisibleProperty)
{
OwningGrid?.OnColumnVisibleStateChanging(this);
var isVisible = (change as AvaloniaPropertyChangedEventArgs<bool>).NewValue.Value;
if (_headerCell != null)
{
_headerCell.IsVisible = isVisible;
}
OwningGrid?.OnColumnVisibleStateChanged(this);
NotifyPropertyChanged(change.Property.Name);
}
}
/// <summary>
/// Actual visible width after Width, MinWidth, and MaxWidth setting at the Column level and DataGrid level
/// have been taken into account
/// </summary>
public double ActualWidth
{
get
{
if (OwningGrid == null || double.IsNaN(Width.DisplayValue))
{
return ActualMinWidth;
}
return Width.DisplayValue;
}
}
/// <summary>
/// Gets or sets a value that indicates whether the user can change the column display position by
/// dragging the column header.
/// </summary>
/// <returns>
/// true if the user can drag the column header to a new position; otherwise, false. The default is the current <see cref="P:Avalonia.Controls.DataGrid.CanUserReorderColumns" /> property value.
/// </returns>
public bool CanUserReorder
{
get
{
return
CanUserReorderInternal ??
OwningGrid?.CanUserReorderColumns ??
DataGrid.DATAGRID_defaultCanUserResizeColumns;
}
set
{
CanUserReorderInternal = value;
}
}
/// <summary>
/// Gets or sets a value that indicates whether the user can adjust the column width using the mouse.
/// </summary>
/// <returns>
/// true if the user can resize the column; false if the user cannot resize the column. The default is the current <see cref="P:Avalonia.Controls.DataGrid.CanUserResizeColumns" /> property value.
/// </returns>
public bool CanUserResize
{
get
{
return
CanUserResizeInternal ??
OwningGrid?.CanUserResizeColumns ??
DataGrid.DATAGRID_defaultCanUserResizeColumns;
}
set
{
CanUserResizeInternal = value;
OwningGrid?.OnColumnCanUserResizeChanged(this);
}
}
/// <summary>
/// Gets or sets a value that indicates whether the user can sort the column by clicking the column header.
/// </summary>
/// <returns>
/// true if the user can sort the column; false if the user cannot sort the column. The default is the current <see cref="P:Avalonia.Controls.DataGrid.CanUserSortColumns" /> property value.
/// </returns>
public bool CanUserSort
{
get
{
if (CanUserSortInternal.HasValue)
{
return CanUserSortInternal.Value;
}
else if (OwningGrid != null)
{
string propertyPath = GetSortPropertyName();
Type propertyType = OwningGrid.DataConnection.DataType.GetNestedPropertyType(propertyPath);
// if the type is nullable, then we will compare the non-nullable type
if (TypeHelper.IsNullableType(propertyType))
{
propertyType = TypeHelper.GetNonNullableType(propertyType);
}
// return whether or not the property type can be compared
return (typeof(IComparable).IsAssignableFrom(propertyType)) ? true : false;
}
else
{
return DataGrid.DATAGRID_defaultCanUserSortColumns;
}
}
set
{
CanUserSortInternal = value;
}
}
/// <summary>
/// Gets or sets the display position of the column relative to the other columns in the <see cref="T:Avalonia.Controls.DataGrid" />.
/// </summary>
/// <returns>
/// The zero-based position of the column as it is displayed in the associated <see cref="T:Avalonia.Controls.DataGrid" />. The default is the index of the corresponding <see cref="P:System.Collections.ObjectModel.Collection`1.Item(System.Int32)" /> in the <see cref="P:Avalonia.Controls.DataGrid.Columns" /> collection.
/// </returns>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// When setting this property, the specified value is less than -1 or equal to <see cref="F:System.Int32.MaxValue" />.
///
/// -or-
///
/// When setting this property on a column in a <see cref="T:Avalonia.Controls.DataGrid" />, the specified value is less than zero or greater than or equal to the number of columns in the <see cref="T:Avalonia.Controls.DataGrid" />.
/// </exception>
/// <exception cref="T:System.InvalidOperationException">
/// When setting this property, the <see cref="T:Avalonia.Controls.DataGrid" /> is already making <see cref="P:Avalonia.Controls.DataGridColumn.DisplayIndex" /> adjustments. For example, this exception is thrown when you attempt to set <see cref="P:Avalonia.Controls.DataGridColumn.DisplayIndex" /> in a <see cref="E:Avalonia.Controls.DataGrid.ColumnDisplayIndexChanged" /> event handler.
///
/// -or-
///
/// When setting this property, the specified value would result in a frozen column being displayed in the range of unfrozen columns, or an unfrozen column being displayed in the range of frozen columns.
/// </exception>
public int DisplayIndex
{
get
{
if (OwningGrid != null && OwningGrid.ColumnsInternal.RowGroupSpacerColumn.IsRepresented)
{
return _displayIndexWithFiller - 1;
}
else
{
return _displayIndexWithFiller;
}
}
set
{
if (value == Int32.MaxValue)
{
throw DataGridError.DataGrid.ValueMustBeLessThan(nameof(value), nameof(DisplayIndex), Int32.MaxValue);
}
if (OwningGrid != null)
{
if (OwningGrid.ColumnsInternal.RowGroupSpacerColumn.IsRepresented)
{
value++;
}
if (_displayIndexWithFiller != value)
{
if (value < 0 || value >= OwningGrid.ColumnsItemsInternal.Count)
{
throw DataGridError.DataGrid.ValueMustBeBetween(nameof(value), nameof(DisplayIndex), 0, true, OwningGrid.Columns.Count, false);
}
// Will throw an error if a visible frozen column is placed inside a non-frozen area or vice-versa.
OwningGrid.OnColumnDisplayIndexChanging(this, value);
_displayIndexWithFiller = value;
try
{
OwningGrid.InDisplayIndexAdjustments = true;
OwningGrid.OnColumnDisplayIndexChanged(this);
OwningGrid.OnColumnDisplayIndexChanged_PostNotification();
}
finally
{
OwningGrid.InDisplayIndexAdjustments = false;
}
}
}
else
{
if (value < -1)
{
throw DataGridError.DataGrid.ValueMustBeGreaterThanOrEqualTo(nameof(value), nameof(DisplayIndex), -1);
}
_displayIndexWithFiller = value;
}
}
}
public Classes CellStyleClasses
{
get => _cellStyleClasses;
set
{
if(_cellStyleClasses != value)
{
_cellStyleClasses.Replace(value);
}
}
}
/// <summary>
/// Backing field for Header property
/// </summary>
public static readonly DirectProperty<DataGridColumn, object> HeaderProperty =
AvaloniaProperty.RegisterDirect<DataGridColumn, object>(
nameof(Header),
o => o.Header,
(o, v) => o.Header = v);
/// <summary>
/// Gets or sets the <see cref="DataGridColumnHeader"/> content
/// </summary>
public object Header
{
get { return _header; }
set { SetAndRaise(HeaderProperty, ref _header, value); }
}
/// <summary>
/// Backing field for Header property
/// </summary>
public static readonly DirectProperty<DataGridColumn, IDataTemplate> HeaderTemplateProperty =
AvaloniaProperty.RegisterDirect<DataGridColumn, IDataTemplate>(
nameof(HeaderTemplate),
o => o.HeaderTemplate,
(o, v) => o.HeaderTemplate = v);
/// <summary>
/// Gets or sets an <see cref="IDataTemplate"/> for the <see cref="Header"/>
/// </summary>
public IDataTemplate HeaderTemplate
{
get { return _headerTemplate; }
set { SetAndRaise(HeaderTemplateProperty, ref _headerTemplate, value); }
}
public bool IsAutoGenerated
{
get;
internal set;
}
public bool IsFrozen
{
get;
internal set;
}
public virtual bool IsReadOnly
{
get
{
if (OwningGrid == null)
{
return _isReadOnly ?? DATAGRIDCOLUMN_defaultIsReadOnly;
}
if (_isReadOnly != null)
{
return _isReadOnly.Value || OwningGrid.IsReadOnly;
}
return OwningGrid.GetColumnReadOnlyState(this, DATAGRIDCOLUMN_defaultIsReadOnly);
}
set
{
if (value != _isReadOnly)
{
OwningGrid?.OnColumnReadOnlyStateChanging(this, value);
_isReadOnly = value;
}
}
}
public double MaxWidth
{
get
{
return _maxWidth ?? double.PositiveInfinity;
}
set
{
if (value < 0)
{
throw DataGridError.DataGrid.ValueMustBeGreaterThanOrEqualTo("value", "MaxWidth", 0);
}
if (value < ActualMinWidth)
{
throw DataGridError.DataGrid.ValueMustBeGreaterThanOrEqualTo("value", "MaxWidth", "MinWidth");
}
if (!_maxWidth.HasValue || _maxWidth.Value != value)
{
double oldValue = ActualMaxWidth;
_maxWidth = value;
if (OwningGrid != null && OwningGrid.ColumnsInternal != null)
{
OwningGrid.OnColumnMaxWidthChanged(this, oldValue);
}
}
}
}
public double MinWidth
{
get
{
return _minWidth ?? 0;
}
set
{
if (double.IsNaN(value))
{
throw DataGridError.DataGrid.ValueCannotBeSetToNAN("MinWidth");
}
if (value < 0)
{
throw DataGridError.DataGrid.ValueMustBeGreaterThanOrEqualTo("value", "MinWidth", 0);
}
if (double.IsPositiveInfinity(value))
{
throw DataGridError.DataGrid.ValueCannotBeSetToInfinity("MinWidth");
}
if (value > ActualMaxWidth)
{
throw DataGridError.DataGrid.ValueMustBeLessThanOrEqualTo("value", "MinWidth", "MaxWidth");
}
if (!_minWidth.HasValue || _minWidth.Value != value)
{
double oldValue = ActualMinWidth;
_minWidth = value;
if (OwningGrid != null && OwningGrid.ColumnsInternal != null)
{
OwningGrid.OnColumnMinWidthChanged(this, oldValue);
}
}
}
}
public DataGridLength Width
{
get
{
return
_width ??
OwningGrid?.ColumnWidth ??
// We don't have a good choice here because we don't want to make this property nullable, see DevDiv Bugs 196581
DataGridLength.Auto;
}
set
{
if (!_width.HasValue || _width.Value != value)
{
if (!_settingWidthInternally)
{
InheritsWidth = false;
}
if (OwningGrid != null)
{
DataGridLength width = CoerceWidth(value);
if (width.IsStar != Width.IsStar)
{
// If a column has changed either from or to a star value, we want to recalculate all
// star column widths. They are recalculated during Measure based off what the value we set here.
SetWidthInternalNoCallback(width);
IsInitialDesiredWidthDetermined = false;
OwningGrid.OnColumnWidthChanged(this);
}
else
{
// If a column width's value is simply changing, we resize it (to the right only).
Resize(width.Value, width.UnitType, width.DesiredValue, width.DisplayValue, false);
}
}
else
{
SetWidthInternalNoCallback(value);
}
}
}
}
/// <summary>
/// The binding that will be used to get or set cell content for the clipboard.
/// </summary>
public virtual IBinding ClipboardContentBinding
{
get
{
return _clipboardContentBinding;
}
set
{
_clipboardContentBinding = value;
}
}
/// <summary>
/// Gets the value of a cell according to the the specified binding.
/// </summary>
/// <param name="item">The item associated with a cell.</param>
/// <param name="binding">The binding to get the value of.</param>
/// <returns>The resultant cell value.</returns>
internal object GetCellValue(object item, IBinding binding)
{
Debug.Assert(OwningGrid != null);
object content = null;
if (binding != null)
{
OwningGrid.ClipboardContentControl.DataContext = item;
var sub = OwningGrid.ClipboardContentControl.Bind(ContentControl.ContentProperty, binding);
content = OwningGrid.ClipboardContentControl.GetValue(ContentControl.ContentProperty);
sub.Dispose();
}
return content;
}
public IControl GetCellContent(DataGridRow dataGridRow)
{
Contract.Requires<ArgumentNullException>(dataGridRow != null);
if (OwningGrid == null)
{
throw DataGridError.DataGrid.NoOwningGrid(GetType());
}
if (dataGridRow.OwningGrid == OwningGrid)
{
DataGridCell dataGridCell = dataGridRow.Cells[Index];
if (dataGridCell != null)
{
return dataGridCell.Content as IControl;
}
}
return null;
}
public IControl GetCellContent(object dataItem)
{
Contract.Requires<ArgumentNullException>(dataItem != null);
if (OwningGrid == null)
{
throw DataGridError.DataGrid.NoOwningGrid(GetType());
}
DataGridRow dataGridRow = OwningGrid.GetRowFromItem(dataItem);
if (dataGridRow == null)
{
return null;
}
return GetCellContent(dataGridRow);
}
/// <summary>
/// Returns the column which contains the given element
/// </summary>
/// <param name="element">element contained in a column</param>
/// <returns>Column that contains the element, or null if not found
/// </returns>
public static DataGridColumn GetColumnContainingElement(IControl element)
{
// Walk up the tree to find the DataGridCell or DataGridColumnHeader that contains the element
IVisual parent = element;
while (parent != null)
{
if (parent is DataGridCell cell)
{
return cell.OwningColumn;
}
if (parent is DataGridColumnHeader columnHeader)
{
return columnHeader.OwningColumn;
}
parent = parent.GetVisualParent();
}
return null;
}
/// <summary>
/// Clears the current sort direction
/// </summary>
public void ClearSort()
{
//InvokeProcessSort is already validating if sorting is possible
_headerCell?.InvokeProcessSort(KeyboardHelper.GetPlatformCtrlOrCmdKeyModifier());
}
/// <summary>
/// Switches the current state of sort direction
/// </summary>
public void Sort()
{
//InvokeProcessSort is already validating if sorting is possible
_headerCell?.InvokeProcessSort(Input.KeyModifiers.None);
}
/// <summary>
/// Changes the sort direction of this column
/// </summary>
/// <param name="direction">New sort direction</param>
public void Sort(ListSortDirection direction)
{
//InvokeProcessSort is already validating if sorting is possible
_headerCell?.InvokeProcessSort(Input.KeyModifiers.None, direction);
}
/// <summary>
/// When overridden in a derived class, causes the column cell being edited to revert to the unedited value.
/// </summary>
/// <param name="editingElement">
/// The element that the column displays for a cell in editing mode.
/// </param>
/// <param name="uneditedValue">
/// The previous, unedited value in the cell being edited.
/// </param>
protected virtual void CancelCellEdit(IControl editingElement, object uneditedValue)
{ }
/// <summary>
/// When overridden in a derived class, gets an editing element that is bound to the column's <see cref="P:Avalonia.Controls.DataGridBoundColumn.Binding" /> property value.
/// </summary>
/// <param name="cell">
/// The cell that will contain the generated element.
/// </param>
/// <param name="dataItem">
/// The data item represented by the row that contains the intended cell.
/// </param>
/// <param name="binding">When the method returns, contains the applied binding.</param>
/// <returns>
/// A new editing element that is bound to the column's <see cref="P:Avalonia.Controls.DataGridBoundColumn.Binding" /> property value.
/// </returns>
protected abstract IControl GenerateEditingElement(DataGridCell cell, object dataItem, out ICellEditBinding binding);
/// <summary>
/// When overridden in a derived class, gets a read-only element that is bound to the column's
/// <see cref="P:Avalonia.Controls.DataGridBoundColumn.Binding" /> property value.
/// </summary>
/// <param name="cell">
/// The cell that will contain the generated element.
/// </param>
/// <param name="dataItem">
/// The data item represented by the row that contains the intended cell.
/// </param>
/// <returns>
/// A new, read-only element that is bound to the column's <see cref="P:Avalonia.Controls.DataGridBoundColumn.Binding" /> property value.
/// </returns>
protected abstract IControl GenerateElement(DataGridCell cell, object dataItem);
/// <summary>
/// Called by a specific column type when one of its properties changed,
/// and its current cells need to be updated.
/// </summary>
/// <param name="propertyName">Indicates which property changed and caused this call</param>
protected void NotifyPropertyChanged(string propertyName)
{
OwningGrid?.RefreshColumnElements(this, propertyName);
}
/// <summary>
/// When overridden in a derived class, called when a cell in the column enters editing mode.
/// </summary>
/// <param name="editingElement">
/// The element that the column displays for a cell in editing mode.
/// </param>
/// <param name="editingEventArgs">
/// Information about the user gesture that is causing a cell to enter editing mode.
/// </param>
/// <returns>
/// The unedited value.
/// </returns>
protected abstract object PrepareCellForEdit(IControl editingElement, RoutedEventArgs editingEventArgs);
/// <summary>
/// Called by the DataGrid control when a column asked for its
/// elements to be refreshed, typically because one of its properties changed.
/// </summary>
/// <param name="element">Indicates the element that needs to be refreshed</param>
/// <param name="propertyName">Indicates which property changed and caused this call</param>
protected internal virtual void RefreshCellContent(IControl element, string propertyName)
{ }
internal void CancelCellEditInternal(IControl editingElement, object uneditedValue)
{
CancelCellEdit(editingElement, uneditedValue);
}
/// <summary>
/// Coerces a DataGridLength to a valid value. If any value components are double.NaN, this method
/// coerces them to a proper initial value. For star columns, the desired width is calculated based
/// on the rest of the star columns. For pixel widths, the desired value is based on the pixel value.
/// For auto widths, the desired value is initialized as the column's minimum width.
/// </summary>
/// <param name="width">The DataGridLength to coerce.</param>
/// <returns>The resultant (coerced) DataGridLength.</returns>
internal DataGridLength CoerceWidth(DataGridLength width)
{
double desiredValue = width.DesiredValue;
if (double.IsNaN(desiredValue))
{
if (width.IsStar && OwningGrid != null && OwningGrid.ColumnsInternal != null)
{
double totalStarValues = 0;
double totalStarDesiredValues = 0;
double totalNonStarDisplayWidths = 0;
foreach (DataGridColumn column in OwningGrid.ColumnsInternal.GetDisplayedColumns(c => c.IsVisible && c != this && !double.IsNaN(c.Width.DesiredValue)))
{
if (column.Width.IsStar)
{
totalStarValues += column.Width.Value;
totalStarDesiredValues += column.Width.DesiredValue;
}
else
{
totalNonStarDisplayWidths += column.ActualWidth;
}
}
if (totalStarValues == 0)
{
// Compute the new star column's desired value based on the available space if there are no other visible star columns
desiredValue = Math.Max(ActualMinWidth, OwningGrid.CellsWidth - totalNonStarDisplayWidths);
}
else
{
// Otherwise, compute its desired value based on those of other visible star columns
desiredValue = totalStarDesiredValues * width.Value / totalStarValues;
}
}
else if (width.IsAbsolute)
{
desiredValue = width.Value;
}
else
{
desiredValue = ActualMinWidth;
}
}
double displayValue = width.DisplayValue;
if (double.IsNaN(displayValue))
{
displayValue = desiredValue;
}
displayValue = Math.Max(ActualMinWidth, Math.Min(ActualMaxWidth, displayValue));
return new DataGridLength(width.Value, width.UnitType, desiredValue, displayValue);
}
/// <summary>
/// If the DataGrid is using layout rounding, the pixel snapping will force all widths to
/// whole numbers. Since the column widths aren't visual elements, they don't go through the normal
/// rounding process, so we need to do it ourselves. If we don't, then we'll end up with some
/// pixel gaps and/or overlaps between columns.
/// </summary>
/// <param name="leftEdge"></param>
internal void ComputeLayoutRoundedWidth(double leftEdge)
{
if (OwningGrid != null && OwningGrid.UseLayoutRounding)
{
var scale = LayoutHelper.GetLayoutScale(HeaderCell);
var roundSize = LayoutHelper.RoundLayoutSize(new Size(leftEdge + ActualWidth, 1), scale, scale);
LayoutRoundedWidth = roundSize.Width - leftEdge;
}
else
{
LayoutRoundedWidth = ActualWidth;
}
}
//TODO Styles
internal virtual DataGridColumnHeader CreateHeader()
{
var result = new DataGridColumnHeader
{
OwningColumn = this
};
result[!ContentControl.ContentProperty] = this[!HeaderProperty];
result[!ContentControl.ContentTemplateProperty] = this[!HeaderTemplateProperty];
//result.EnsureStyle(null);
return result;
}
/// <summary>
/// Ensures that this column's width has been coerced to a valid value.
/// </summary>
internal void EnsureWidth()
{
SetWidthInternalNoCallback(CoerceWidth(Width));
}
internal IControl GenerateElementInternal(DataGridCell cell, object dataItem)
{
return GenerateElement(cell, dataItem);
}
internal object PrepareCellForEditInternal(IControl editingElement, RoutedEventArgs editingEventArgs)
{
var result = PrepareCellForEdit(editingElement, editingEventArgs);
editingElement.Focus();
return result;
}
/// <summary>
/// Attempts to resize the column's width to the desired DisplayValue, but limits the final size
/// to the column's minimum and maximum values. If star sizing is being used, then the column
/// can only decrease in size by the amount that the columns after it can increase in size.
/// Likewise, the column can only increase in size if other columns can spare the width.
/// </summary>
/// <param name="value">The new Value.</param>
/// <param name="unitType">The new UnitType.</param>
/// <param name="desiredValue">The new DesiredValue.</param>
/// <param name="displayValue">The new DisplayValue.</param>
/// <param name="userInitiated">Whether or not this resize was initiated by a user action.</param>
internal void Resize(double value, DataGridLengthUnitType unitType, double desiredValue, double displayValue, bool userInitiated)
{
double newValue = value;
double newDesiredValue = desiredValue;
double newDisplayValue = Math.Max(ActualMinWidth, Math.Min(ActualMaxWidth, displayValue));
DataGridLengthUnitType newUnitType = unitType;
int starColumnsCount = 0;
double totalDisplayWidth = 0;
foreach (DataGridColumn column in OwningGrid.ColumnsInternal.GetVisibleColumns())
{
column.EnsureWidth();
totalDisplayWidth += column.ActualWidth;
starColumnsCount += (column != this && column.Width.IsStar) ? 1 : 0;
}
bool hasInfiniteAvailableWidth = !OwningGrid.RowsPresenterAvailableSize.HasValue || double.IsPositiveInfinity(OwningGrid.RowsPresenterAvailableSize.Value.Width);
// If we're using star sizing, we can only resize the column as much as the columns to the
// right will allow (i.e. until they hit their max or min widths).
if (!hasInfiniteAvailableWidth && (starColumnsCount > 0 || (unitType == DataGridLengthUnitType.Star && Width.IsStar && userInitiated)))
{
double limitedDisplayValue = Width.DisplayValue;
double availableIncrease = Math.Max(0, OwningGrid.CellsWidth - totalDisplayWidth);
double desiredChange = newDisplayValue - Width.DisplayValue;
if (desiredChange > availableIncrease)
{
// The desired change is greater than the amount of available space,
// so we need to decrease the widths of columns to the right to make room.
desiredChange -= availableIncrease;
double actualChange = desiredChange + OwningGrid.DecreaseColumnWidths(DisplayIndex + 1, -desiredChange, userInitiated);
limitedDisplayValue += availableIncrease + actualChange;
}
else if (desiredChange > 0)
{
// The desired change is positive but less than the amount of available space,
// so there's no need to decrease the widths of columns to the right.
limitedDisplayValue += desiredChange;
}
else
{
// The desired change is negative, so we need to increase the widths of columns to the right.
limitedDisplayValue += desiredChange + OwningGrid.IncreaseColumnWidths(DisplayIndex + 1, -desiredChange, userInitiated);
}
if (ActualCanUserResize || (Width.IsStar && !userInitiated))
{
newDisplayValue = limitedDisplayValue;
}
}
if (userInitiated)
{
newDesiredValue = newDisplayValue;
if (!Width.IsStar)
{
InheritsWidth = false;
newValue = newDisplayValue;
newUnitType = DataGridLengthUnitType.Pixel;
}
else if (starColumnsCount > 0 && !hasInfiniteAvailableWidth)
{
// Recalculate star weight of this column based on the new desired value
InheritsWidth = false;
newValue = (Width.Value * newDisplayValue) / ActualWidth;
}
}
DataGridLength oldWidth = Width;
SetWidthInternalNoCallback(new DataGridLength(Math.Min(double.MaxValue, newValue), newUnitType, newDesiredValue, newDisplayValue));
if (Width != oldWidth)
{
OwningGrid.OnColumnWidthChanged(this);
}
}
/// <summary>
/// Sets the column's Width to a new DataGridLength with a different DesiredValue.
/// </summary>
/// <param name="desiredValue">The new DesiredValue.</param>
internal void SetWidthDesiredValue(double desiredValue)
{
SetWidthInternalNoCallback(new DataGridLength(Width.Value, Width.UnitType, desiredValue, Width.DisplayValue));
}
/// <summary>
/// Sets the column's Width to a new DataGridLength with a different DisplayValue.
/// </summary>
/// <param name="displayValue">The new DisplayValue.</param>
internal void SetWidthDisplayValue(double displayValue)
{
SetWidthInternalNoCallback(new DataGridLength(Width.Value, Width.UnitType, Width.DesiredValue, displayValue));
}
/// <summary>
/// Set the column's Width without breaking inheritance.
/// </summary>
/// <param name="width">The new Width.</param>
internal void SetWidthInternal(DataGridLength width)
{
bool originalValue = _settingWidthInternally;
_settingWidthInternally = true;
try
{
Width = width;
}
finally
{
_settingWidthInternally = originalValue;
}
}
/// <summary>
/// Sets the column's Width directly, without any callback effects.
/// </summary>
/// <param name="width">The new Width.</param>
internal void SetWidthInternalNoCallback(DataGridLength width)
{
_width = width;
}
/// <summary>
/// Set the column's star value. Whenever the star value changes, width inheritance is broken.
/// </summary>
/// <param name="value">The new star value.</param>
internal void SetWidthStarValue(double value)
{
InheritsWidth = false;
SetWidthInternalNoCallback(new DataGridLength(value, Width.UnitType, Width.DesiredValue, Width.DisplayValue));
}
//TODO Binding
internal IControl GenerateEditingElementInternal(DataGridCell cell, object dataItem)
{
if (_editingElement == null)
{
_editingElement = GenerateEditingElement(cell, dataItem, out _editBinding);
}
return _editingElement;
}
/// <summary>
/// Clears the cached editing element.
/// </summary>
//TODO Binding
internal void RemoveEditingElement()
{
_editingElement = null;
}
/// <summary>
/// Holds the name of the member to use for sorting, if not using the default.
/// </summary>
public string SortMemberPath
{
get;
set;
}
/// <summary>
/// Holds a Comparer to use for sorting, if not using the default.
/// </summary>
public System.Collections.IComparer CustomSortComparer
{
get;
set;
}
/// <summary>
/// We get the sort description from the data source. We don't worry whether we can modify sort -- perhaps the sort description
/// describes an unchangeable sort that exists on the data.
/// </summary>
internal DataGridSortDescription GetSortDescription()
{
if (OwningGrid != null
&& OwningGrid.DataConnection != null
&& OwningGrid.DataConnection.SortDescriptions != null)
{
if(CustomSortComparer != null)
{
return
OwningGrid.DataConnection.SortDescriptions
.OfType<DataGridComparerSortDesctiption>()
.FirstOrDefault(s => s.SourceComparer == CustomSortComparer);
}
string propertyName = GetSortPropertyName();
return OwningGrid.DataConnection.SortDescriptions.FirstOrDefault(s => s.HasPropertyPath && s.PropertyPath == propertyName);
}
return null;
}
internal string GetSortPropertyName()
{
string result = SortMemberPath;
if (String.IsNullOrEmpty(result))
{
if (this is DataGridBoundColumn boundColumn)
{
if (boundColumn.Binding is Binding binding)
{
result = binding.Path;
}
else if (boundColumn.Binding is CompiledBindingExtension compiledBinding)
{
result = compiledBinding.Path.ToString();
}
}
}
return result;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.Build.Framework;
using Microsoft.Build.Logging.StructuredLogger;
namespace Microsoft.Build.BackEnd
{
internal class ItemGroupLoggingHelper
{
internal static FieldInfo LineNumberField = Reflector.BuildMessageEventArgs_lineNumber;
internal static FieldInfo ColumnNumberField = Reflector.BuildMessageEventArgs_columnNumber;
internal static TaskParameterEventArgs CreateTaskParameterEventArgs(
BuildEventContext buildEventContext,
TaskParameterMessageKind messageKind,
string itemType,
IList items,
bool logItemMetadata,
DateTime timestamp,
int line,
int column)
{
var args = new TaskParameterEventArgs(
messageKind,
itemType,
items,
logItemMetadata,
timestamp);
args.BuildEventContext = buildEventContext;
// sigh this is terrible for perf
LineNumberField.SetValue(args, line);
ColumnNumberField.SetValue(args, column);
// Should probably make these public
// args.LineNumber = line;
// args.ColumnNumber = column;
return args;
}
}
}
namespace Microsoft.Build.Internal
{
internal static class Utilities
{
public static void EnumerateProperties(IEnumerable properties, Action<KeyValuePair<string, string>> callback)
{
if (properties == null)
{
return;
}
//if (properties is PropertyDictionary<ProjectPropertyInstance> propertyDictionary)
//{
// propertyDictionary.Enumerate((key, value) =>
// {
// callback(new KeyValuePair<string, string>(key, value));
// });
//}
//else
{
foreach (var item in properties)
{
if (item is DictionaryEntry dictionaryEntry && dictionaryEntry.Key is string key && !string.IsNullOrEmpty(key))
{
callback(new KeyValuePair<string, string>(key, dictionaryEntry.Value as string ?? string.Empty));
}
else if (item is KeyValuePair<string, string> kvp)
{
callback(kvp);
}
else
{
}
}
}
}
public static void EnumerateItems(IEnumerable items, Action<DictionaryEntry> callback)
{
foreach (var item in items)
{
string itemType = default;
object itemValue = null;
if (item is DictionaryEntry dictionaryEntry)
{
itemType = dictionaryEntry.Key as string;
itemValue = dictionaryEntry.Value;
}
if (string.IsNullOrEmpty(itemType))
{
continue;
}
callback(new DictionaryEntry(itemType, itemValue));
}
}
public static IEnumerable<KeyValuePair<string, string>> EnumerateMetadata(this ITaskItem taskItem)
{
// This runs if ITaskItem is Microsoft.Build.Utilities.TaskItem from Microsoft.Build.Utilities.v4.0.dll
// that is loaded from the GAC.
IDictionary customMetadata = taskItem.CloneCustomMetadata();
if (customMetadata is IEnumerable<KeyValuePair<string, string>> enumerableMetadata)
{
return enumerableMetadata;
}
// In theory this should never be reachable.
var list = new KeyValuePair<string, string>[customMetadata.Count];
int i = 0;
foreach (string metadataName in customMetadata.Keys)
{
string valueOrError;
try
{
valueOrError = taskItem.GetMetadata(metadataName);
}
// Temporarily try catch all to mitigate frequent NullReferenceExceptions in
// the logging code until CopyOnWritePropertyDictionary is replaced with
// ImmutableDictionary. Calling into Debug.Fail to crash the process in case
// the exception occurres in Debug builds.
catch (Exception e)
{
valueOrError = e.Message;
}
list[i] = new KeyValuePair<string, string>(metadataName, valueOrError);
i += 1;
}
return list;
}
public static bool EqualTo(this BuildEventContext buildEventContext, BuildEventContext other)
{
if (object.ReferenceEquals(buildEventContext, other))
{
return true;
}
if (buildEventContext == null || other == null)
{
return false;
}
return buildEventContext.TaskId == other.TaskId
&& buildEventContext.TargetId == other.TargetId
&& buildEventContext.ProjectContextId == other.ProjectContextId
&& buildEventContext.ProjectInstanceId == other.ProjectInstanceId
&& buildEventContext.NodeId == other.NodeId
&& buildEventContext.EvaluationId == other.EvaluationId
&& buildEventContext.SubmissionId == other.SubmissionId;
}
}
}
namespace Microsoft.Build.Shared
{
internal static class ItemTypeNames
{
/// <summary>
/// References to other msbuild projects
/// </summary>
internal const string ProjectReference = nameof(ProjectReference);
/// <summary>
/// Statically specifies what targets a project calls on its references
/// </summary>
internal const string ProjectReferenceTargets = nameof(ProjectReferenceTargets);
internal const string GraphIsolationExemptReference = nameof(GraphIsolationExemptReference);
/// <summary>
/// Declares a project cache plugin and its configuration.
/// </summary>
internal const string ProjectCachePlugin = nameof(ProjectCachePlugin);
/// <summary>
/// Embed specified files in the binary log
/// </summary>
internal const string EmbedInBinlog = nameof(EmbedInBinlog);
}
/// <summary>
/// Constants that we want to be shareable across all our assemblies.
/// </summary>
internal static class MSBuildConstants
{
/// <summary>
/// The name of the property that indicates the tools path
/// </summary>
internal const string ToolsPath = "MSBuildToolsPath";
/// <summary>
/// Name of the property that indicates the X64 tools path
/// </summary>
internal const string ToolsPath64 = "MSBuildToolsPath64";
/// <summary>
/// Name of the property that indicates the root of the SDKs folder
/// </summary>
internal const string SdksPath = "MSBuildSDKsPath";
/// <summary>
/// Name of the property that indicates that all warnings should be treated as errors.
/// </summary>
internal const string TreatWarningsAsErrors = "MSBuildTreatWarningsAsErrors";
/// <summary>
/// Name of the property that indicates a list of warnings to treat as errors.
/// </summary>
internal const string WarningsAsErrors = "MSBuildWarningsAsErrors";
/// <summary>
/// Name of the property that indicates the list of warnings to treat as messages.
/// </summary>
internal const string WarningsAsMessages = "MSBuildWarningsAsMessages";
/// <summary>
/// The name of the environment variable that users can specify to override where NuGet assemblies are loaded from in the NuGetSdkResolver.
/// </summary>
internal const string NuGetAssemblyPathEnvironmentVariableName = "MSBUILD_NUGET_PATH";
/// <summary>
/// The name of the target to run when a user specifies the /restore command-line argument.
/// </summary>
internal const string RestoreTargetName = "Restore";
/// <summary>
/// The most current Visual Studio Version known to this version of MSBuild.
/// </summary>
internal const string CurrentVisualStudioVersion = "16.0";
/// <summary>
/// The most current ToolsVersion known to this version of MSBuild.
/// </summary>
internal const string CurrentToolsVersion = "Current";
internal const string MSBuildDummyGlobalPropertyHeader = "MSBuildProjectInstance";
/// <summary>
/// The most current VSGeneralAssemblyVersion known to this version of MSBuild.
/// </summary>
internal const string CurrentAssemblyVersion = "15.1.0.0";
/// <summary>
/// Current version of this MSBuild Engine assembly in the form, e.g, "12.0"
/// </summary>
internal const string CurrentProductVersion = "16.0";
/// <summary>
/// Symbol used in ProjectReferenceTarget items to represent default targets
/// </summary>
internal const string DefaultTargetsMarker = ".default";
/// <summary>
/// Symbol used in ProjectReferenceTarget items to represent targets specified on the ProjectReference item
/// with fallback to default targets if the ProjectReference item has no targets specified.
/// </summary>
internal const string ProjectReferenceTargetsOrDefaultTargetsMarker = ".projectReferenceTargetsOrDefaultTargets";
// One-time allocations to avoid implicit allocations for Split(), Trim().
internal static readonly char[] SemicolonChar = { ';' };
internal static readonly char[] SpaceChar = { ' ' };
internal static readonly char[] SingleQuoteChar = { '\'' };
internal static readonly char[] EqualsChar = { '=' };
internal static readonly char[] ColonChar = { ':' };
internal static readonly char[] BackslashChar = { '\\' };
internal static readonly char[] NewlineChar = { '\n' };
internal static readonly char[] CrLf = { '\r', '\n' };
internal static readonly char[] ForwardSlash = { '/' };
internal static readonly char[] ForwardSlashBackslash = { '/', '\\' };
internal static readonly char[] WildcardChars = { '*', '?' };
internal static readonly string[] CharactersForExpansion = { "*", "?", "$(", "@(", "%" };
internal static readonly char[] CommaChar = { ',' };
internal static readonly char[] HyphenChar = { '-' };
internal static readonly char[] DirectorySeparatorChar = { Path.DirectorySeparatorChar };
internal static readonly char[] DotChar = { '.' };
internal static readonly string[] EnvironmentNewLine = { Environment.NewLine };
internal static readonly char[] PipeChar = { '|' };
internal static readonly char[] PathSeparatorChar = { Path.PathSeparator };
}
internal static class BinaryWriterExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteOptionalString(this BinaryWriter writer, string value)
{
if (value == null)
{
writer.Write((byte)0);
}
else
{
writer.Write((byte)1);
writer.Write(value);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteTimestamp(this BinaryWriter writer, DateTime timestamp)
{
writer.Write(timestamp.Ticks);
writer.Write((Int32)timestamp.Kind);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Write7BitEncodedInt(this BinaryWriter writer, int value)
{
// Write out an int 7 bits at a time. The high bit of the byte,
// when on, tells reader to continue reading more bytes.
uint v = (uint)value; // support negative numbers
while (v >= 0x80)
{
writer.Write((byte)(v | 0x80));
v >>= 7;
}
writer.Write((byte)v);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteOptionalBuildEventContext(this BinaryWriter writer, BuildEventContext context)
{
if (context == null)
{
writer.Write((byte)0);
}
else
{
writer.Write((byte)1);
writer.WriteBuildEventContext(context);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void WriteBuildEventContext(this BinaryWriter writer, BuildEventContext context)
{
writer.Write(context.NodeId);
writer.Write(context.ProjectContextId);
writer.Write(context.TargetId);
writer.Write(context.TaskId);
writer.Write(context.SubmissionId);
writer.Write(context.ProjectInstanceId);
writer.Write(context.EvaluationId);
}
}
internal static class BinaryReaderExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string ReadOptionalString(this BinaryReader reader)
{
return reader.ReadByte() == 0 ? null : reader.ReadString();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int Read7BitEncodedInt(this BinaryReader reader)
{
// Read out an Int32 7 bits at a time. The high bit
// of the byte when on means to continue reading more bytes.
int count = 0;
int shift = 0;
byte b;
do
{
// Check for a corrupted stream. Read a max of 5 bytes.
// In a future version, add a DataFormatException.
if (shift == 5 * 7) // 5 bytes max per Int32, shift += 7
{
throw new FormatException();
}
// ReadByte handles end of stream cases for us.
b = reader.ReadByte();
count |= (b & 0x7F) << shift;
shift += 7;
} while ((b & 0x80) != 0);
return count;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static DateTime ReadTimestamp(this BinaryReader reader)
{
long timestampTicks = reader.ReadInt64();
DateTimeKind kind = (DateTimeKind)reader.ReadInt32();
var timestamp = new DateTime(timestampTicks, kind);
return timestamp;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static BuildEventContext ReadOptionalBuildEventContext(this BinaryReader reader)
{
if (reader.ReadByte() == 0)
{
return null;
}
return reader.ReadBuildEventContext();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static BuildEventContext ReadBuildEventContext(this BinaryReader reader)
{
int nodeId = reader.ReadInt32();
int projectContextId = reader.ReadInt32();
int targetId = reader.ReadInt32();
int taskId = reader.ReadInt32();
int submissionId = reader.ReadInt32();
int projectInstanceId = reader.ReadInt32();
int evaluationId = reader.ReadInt32();
var buildEventContext = new BuildEventContext(submissionId, nodeId, evaluationId, projectInstanceId, projectContextId, targetId, taskId);
return buildEventContext;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.IO;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
namespace System.Diagnostics
{
public sealed partial class FileVersionInfo
{
private FileVersionInfo(string fileName)
{
_fileName = fileName;
// For managed assemblies, read the file version information from the assembly's metadata.
// This isn't quite what's done on Windows, which uses the Win32 GetFileVersionInfo to read
// the Win32 resource information from the file, and the managed compiler uses these attributes
// to fill in that resource information when compiling the assembly. It's possible
// that after compilation, someone could have modified the resource information such that it
// no longer matches what was or wasn't in the assembly. But that's a rare enough case
// that this should match for all intents and purposes. If this ever becomes a problem,
// we can implement a full-fledged Win32 resource parser; that would also enable support
// for native Win32 PE files on Unix, but that should also be an extremely rare case.
if (!TryLoadManagedAssemblyMetadata())
{
// We could try to parse Executable and Linkable Format (ELF) files, but at present
// for executables they don't store version information, which is typically just
// available in the filename itself. For now, we won't do anything special, but
// we can add more cases here as we find need and opportunity.
}
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
/// <summary>Attempt to load our fields from the metadata of the file, if it's a managed assembly.</summary>
/// <returns>true if the file is a managed assembly; otherwise, false.</returns>
private bool TryLoadManagedAssemblyMetadata()
{
try
{
// Try to load the file using the managed metadata reader
using (FileStream assemblyStream = File.OpenRead(_fileName))
using (PEReader peReader = new PEReader(assemblyStream))
{
if (peReader.HasMetadata)
{
MetadataReader metadataReader = peReader.GetMetadataReader();
if (metadataReader.IsAssembly)
{
LoadManagedAssemblyMetadata(metadataReader);
return true;
}
}
}
}
catch (BadImageFormatException) { }
return false;
}
/// <summary>Load our fields from the metadata of the file as represented by the provided metadata reader.</summary>
/// <param name="metadataReader">The metadata reader for the CLI file this represents.</param>
private void LoadManagedAssemblyMetadata(MetadataReader metadataReader)
{
AssemblyDefinition assemblyDefinition = metadataReader.GetAssemblyDefinition();
// Set the internal and original names based on the file name.
_internalName = _originalFilename = Path.GetFileName(_fileName);
// Set the product version based on the assembly's version (this may be overwritten
// later in the method).
Version productVersion = assemblyDefinition.Version;
_productVersion = productVersion.ToString(4);
_productMajor = productVersion.Major;
_productMinor = productVersion.Minor;
_productBuild = productVersion.Build;
_productPrivate = productVersion.Revision;
// "Language Neutral" is used on Win32 for unknown language identifiers.
_language = "Language Neutral";
// Set other fields to default values in case they're not overwritten by attributes
_companyName = string.Empty;
_comments = string.Empty;
_fileDescription = " "; // this is what the managed compiler outputs when value isn't set
_fileVersion = string.Empty;
_legalCopyright = " "; // this is what the managed compiler outputs when value isn't set
_legalTrademarks = string.Empty;
_productName = string.Empty;
_privateBuild = string.Empty;
_specialBuild = string.Empty;
// Be explicit about initialization to suppress warning about fields not being set
_isDebug = false;
_isPatched = false;
_isPreRelease = false;
_isPrivateBuild = false;
_isSpecialBuild = false;
// Everything else is parsed from assembly attributes
MetadataStringComparer comparer = metadataReader.StringComparer;
foreach (CustomAttributeHandle attrHandle in assemblyDefinition.GetCustomAttributes())
{
CustomAttribute attr = metadataReader.GetCustomAttribute(attrHandle);
StringHandle typeNamespaceHandle = default(StringHandle), typeNameHandle = default(StringHandle);
if (TryGetAttributeName(metadataReader, attr, out typeNamespaceHandle, out typeNameHandle) &&
comparer.Equals(typeNamespaceHandle, "System.Reflection"))
{
if (comparer.Equals(typeNameHandle, "AssemblyCompanyAttribute"))
{
GetStringAttributeArgumentValue(metadataReader, attr, ref _companyName);
}
else if (comparer.Equals(typeNameHandle, "AssemblyCopyrightAttribute"))
{
GetStringAttributeArgumentValue(metadataReader, attr, ref _legalCopyright);
}
else if (comparer.Equals(typeNameHandle, "AssemblyDescriptionAttribute"))
{
GetStringAttributeArgumentValue(metadataReader, attr, ref _comments);
}
else if (comparer.Equals(typeNameHandle, "AssemblyFileVersionAttribute"))
{
string versionString = string.Empty;
GetStringAttributeArgumentValue(metadataReader, attr, ref versionString);
Version v;
if (Version.TryParse(versionString, out v))
{
_fileVersion = v.ToString(4);
_fileMajor = v.Major;
_fileMinor = v.Minor;
_fileBuild = v.Build;
_filePrivate = v.Revision;
// When the managed compiler sees an [AssemblyVersion(...)] attribute, it uses that to set
// both the assembly version and the product version in the Win32 resources. If it doesn't
// see an [AssemblyVersion(...)], then it sets the assembly version to 0.0.0.0, however it
// sets the product version in the Win32 resources to whatever was defined in the
// [AssemblyFileVersionAttribute(...)] if there was one. Without parsing the Win32 resources,
// we can't differentiate these two cases, so given the rarity of explicitly setting an
// assembly's version number to 0.0.0.0, we assume that if it is 0.0.0.0 then the attribute
// wasn't specified and we use the file version.
if (_productVersion == "0.0.0.0")
{
_productVersion = _fileVersion;
_productMajor = _fileMajor;
_productMinor = _fileMinor;
_productBuild = _fileBuild;
_productPrivate = _filePrivate;
}
}
}
else if (comparer.Equals(typeNameHandle, "AssemblyProductAttribute"))
{
GetStringAttributeArgumentValue(metadataReader, attr, ref _productName);
}
else if (comparer.Equals(typeNameHandle, "AssemblyTrademarkAttribute"))
{
GetStringAttributeArgumentValue(metadataReader, attr, ref _legalTrademarks);
}
else if (comparer.Equals(typeNameHandle, "AssemblyTitleAttribute"))
{
GetStringAttributeArgumentValue(metadataReader, attr, ref _fileDescription);
}
}
}
}
/// <summary>Gets the name of an attribute.</summary>
/// <param name="reader">The metadata reader.</param>
/// <param name="attr">The attribute.</param>
/// <param name="typeNamespaceHandle">The namespace of the attribute.</param>
/// <param name="typeNameHandle">The name of the attribute.</param>
/// <returns>true if the name could be retrieved; otherwise, false.</returns>
private static bool TryGetAttributeName(MetadataReader reader, CustomAttribute attr, out StringHandle typeNamespaceHandle, out StringHandle typeNameHandle)
{
EntityHandle ctorHandle = attr.Constructor;
switch (ctorHandle.Kind)
{
case HandleKind.MemberReference:
EntityHandle container = reader.GetMemberReference((MemberReferenceHandle)ctorHandle).Parent;
if (container.Kind == HandleKind.TypeReference)
{
TypeReference tr = reader.GetTypeReference((TypeReferenceHandle)container);
typeNamespaceHandle = tr.Namespace;
typeNameHandle = tr.Name;
return true;
}
break;
case HandleKind.MethodDefinition:
MethodDefinition md = reader.GetMethodDefinition((MethodDefinitionHandle)ctorHandle);
TypeDefinition td = reader.GetTypeDefinition(md.GetDeclaringType());
typeNamespaceHandle = td.Namespace;
typeNameHandle = td.Name;
return true;
}
// Unusual case, potentially invalid IL
typeNamespaceHandle = default(StringHandle);
typeNameHandle = default(StringHandle);
return false;
}
/// <summary>Gets the string argument value of an attribute with a single fixed string argument.</summary>
/// <param name="reader">The metadata reader.</param>
/// <param name="attr">The attribute.</param>
/// <param name="value">The value parsed from the attribute, if it could be retrieved; otherwise, the value is left unmodified.</param>
private static void GetStringAttributeArgumentValue(MetadataReader reader, CustomAttribute attr, ref string value)
{
EntityHandle ctorHandle = attr.Constructor;
BlobHandle signature;
switch (ctorHandle.Kind)
{
case HandleKind.MemberReference:
signature = reader.GetMemberReference((MemberReferenceHandle)ctorHandle).Signature;
break;
case HandleKind.MethodDefinition:
signature = reader.GetMethodDefinition((MethodDefinitionHandle)ctorHandle).Signature;
break;
default:
// Unusual case, potentially invalid IL
return;
}
BlobReader signatureReader = reader.GetBlobReader(signature);
BlobReader valueReader = reader.GetBlobReader(attr.Value);
const ushort Prolog = 1; // two-byte "prolog" defined by Ecma 335 (II.23.3) to be at the beginning of attribute value blobs
if (valueReader.ReadUInt16() == Prolog)
{
SignatureHeader header = signatureReader.ReadSignatureHeader();
int parameterCount;
if (header.Kind == SignatureKind.Method && // attr ctor must be a method
!header.IsGeneric && // attr ctor must be non-generic
signatureReader.TryReadCompressedInteger(out parameterCount) && // read parameter count
parameterCount == 1 && // attr ctor must have 1 parameter
signatureReader.ReadSignatureTypeCode() == SignatureTypeCode.Void && // attr ctor return type must be void
signatureReader.ReadSignatureTypeCode() == SignatureTypeCode.String) // attr ctor first parameter must be string
{
value = valueReader.ReadSerializedString();
}
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
namespace Community.CsharpSqlite
{
using sqlite3_callback = Sqlite3.dxCallback;
using sqlite3_stmt = Sqlite3.Vdbe;
public partial class Sqlite3
{
/*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** Main file for the SQLite library. The routines in this file
** implement the programmer interface to the library. Routines in
** other files are for internal use by SQLite and should not be
** accessed by users of the library.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
**
*************************************************************************
*/
//#include "sqliteInt.h"
/*
** Execute SQL code. Return one of the SQLITE_ success/failure
** codes. Also write an error message into memory obtained from
** malloc() and make pzErrMsg point to that message.
**
** If the SQL is a query, then for each row in the query result
** the xCallback() function is called. pArg becomes the first
** argument to xCallback(). If xCallback=NULL then no callback
** is invoked, even for queries.
*/
//C# Alias
static public int exec( sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ int NoCallback, int NoArgs, int NoErrors )
{
string Errors = "";
return sqlite3_exec( db, zSql, null, null, ref Errors );
}
static public int exec( sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ sqlite3_callback xCallback, /* Invoke this callback routine */ object pArg, /* First argument to xCallback() */ int NoErrors )
{
string Errors = "";
return sqlite3_exec( db, zSql, xCallback, pArg, ref Errors );
}
static public int exec( sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ sqlite3_callback xCallback, /* Invoke this callback routine */ object pArg, /* First argument to xCallback() */ ref string pzErrMsg /* Write error messages here */)
{
return sqlite3_exec( db, zSql, xCallback, pArg, ref pzErrMsg );
}
//OVERLOADS
static public int sqlite3_exec(
sqlite3 db, /* The database on which the SQL executes */
string zSql, /* The SQL to be executed */
int NoCallback, int NoArgs, int NoErrors
)
{
string Errors = "";
return sqlite3_exec( db, zSql, null, null, ref Errors );
}
static public int sqlite3_exec(
sqlite3 db, /* The database on which the SQL executes */
string zSql, /* The SQL to be executed */
sqlite3_callback xCallback, /* Invoke this callback routine */
object pArg, /* First argument to xCallback() */
int NoErrors
)
{
string Errors = "";
return sqlite3_exec( db, zSql, xCallback, pArg, ref Errors );
}
static public int sqlite3_exec(
sqlite3 db, /* The database on which the SQL executes */
string zSql, /* The SQL to be executed */
sqlite3_callback xCallback, /* Invoke this callback routine */
object pArg, /* First argument to xCallback() */
ref string pzErrMsg /* Write error messages here */
)
{
int rc = SQLITE_OK; /* Return code */
string zLeftover = ""; /* Tail of unprocessed SQL */
sqlite3_stmt pStmt = null; /* The current SQL statement */
string[] azCols = null; /* Names of result columns */
int nRetry = 0; /* Number of retry attempts */
int callbackIsInit; /* True if callback data is initialized */
if ( !sqlite3SafetyCheckOk( db ) )
return SQLITE_MISUSE_BKPT();
if ( zSql == null )
zSql = "";
sqlite3_mutex_enter( db.mutex );
sqlite3Error( db, SQLITE_OK, 0 );
while ( ( rc == SQLITE_OK || ( rc == SQLITE_SCHEMA && ( ++nRetry ) < 2 ) ) && zSql != "" )
{
int nCol;
string[] azVals = null;
pStmt = null;
rc = sqlite3_prepare( db, zSql, -1, ref pStmt, ref zLeftover );
Debug.Assert( rc == SQLITE_OK || pStmt == null );
if ( rc != SQLITE_OK )
{
continue;
}
if ( pStmt == null )
{
/* this happens for a comment or white-space */
zSql = zLeftover;
continue;
}
callbackIsInit = 0;
nCol = sqlite3_column_count( pStmt );
while ( true )
{
int i;
rc = sqlite3_step( pStmt );
/* Invoke the callback function if required */
if ( xCallback != null && ( SQLITE_ROW == rc ||
( SQLITE_DONE == rc && callbackIsInit == 0
&& ( db.flags & SQLITE_NullCallback ) != 0 ) ) )
{
if ( 0 == callbackIsInit )
{
azCols = new string[nCol];//sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
//if ( azCols == null )
//{
// goto exec_out;
//}
for ( i = 0; i < nCol; i++ )
{
azCols[i] = sqlite3_column_name( pStmt, i );
/* sqlite3VdbeSetColName() installs column names as UTF8
** strings so there is no way for sqlite3_column_name() to fail. */
Debug.Assert( azCols[i] != null );
}
callbackIsInit = 1;
}
if ( rc == SQLITE_ROW )
{
azVals = new string[nCol];// azCols[nCol];
for ( i = 0; i < nCol; i++ )
{
azVals[i] = sqlite3_column_text( pStmt, i );
if ( azVals[i] == null && sqlite3_column_type( pStmt, i ) != SQLITE_NULL )
{
//db.mallocFailed = 1;
//goto exec_out;
}
}
}
if ( xCallback( pArg, nCol, azVals, azCols ) != 0 )
{
rc = SQLITE_ABORT;
sqlite3VdbeFinalize( pStmt );
pStmt = null;
sqlite3Error( db, SQLITE_ABORT, 0 );
goto exec_out;
}
}
if ( rc != SQLITE_ROW )
{
rc = sqlite3VdbeFinalize( pStmt );
pStmt = null;
if ( rc != SQLITE_SCHEMA )
{
nRetry = 0;
if ( ( zSql = zLeftover ) != "" )
{
int zindex = 0;
while ( zindex < zSql.Length && sqlite3Isspace( zSql[zindex] ) )
zindex++;
if ( zindex != 0 )
zSql = zindex < zSql.Length ? zSql.Substring( zindex ) : "";
}
}
break;
}
}
sqlite3DbFree( db, ref azCols );
azCols = null;
}
exec_out:
if ( pStmt != null )
sqlite3VdbeFinalize( pStmt );
sqlite3DbFree( db, ref azCols );
rc = sqlite3ApiExit( db, rc );
if ( rc != SQLITE_OK && ALWAYS( rc == sqlite3_errcode( db ) ) && pzErrMsg != null )
{
//int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
//pzErrMsg = sqlite3Malloc(nErrMsg);
//if (pzErrMsg)
//{
// memcpy(pzErrMsg, sqlite3_errmsg(db), nErrMsg);
//}else{
//rc = SQLITE_NOMEM;
//sqlite3Error(db, SQLITE_NOMEM, 0);
//}
pzErrMsg = sqlite3_errmsg( db );
}
else if ( pzErrMsg != "" )
{
pzErrMsg = "";
}
Debug.Assert( ( rc & db.errMask ) == rc );
sqlite3_mutex_leave( db.mutex );
return rc;
}
}
}
| |
#region License
// /*
// See license included in this library folder.
// */
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Threading;
using Sqloogle.Libs.NLog.Common;
using Sqloogle.Libs.NLog.Internal;
using Sqloogle.Libs.NLog.Layouts;
namespace Sqloogle.Libs.NLog
{
/// <summary>
/// Represents the logging event.
/// </summary>
public class LogEventInfo
{
/// <summary>
/// Gets the date of the first log event created.
/// </summary>
public static readonly DateTime ZeroDate = DateTime.UtcNow;
private static int globalSequenceId;
private string formattedMessage;
private IDictionary<Layout, string> layoutCache;
private IDictionary<object, object> properties;
private IDictionary eventContextAdapter;
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
public LogEventInfo()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Logger name.</param>
/// <param name="message">Log message including parameter placeholders.</param>
public LogEventInfo(LogLevel level, string loggerName, [Localizable(false)] string message)
: this(level, loggerName, null, message, null, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Logger name.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">Log message including parameter placeholders.</param>
/// <param name="parameters">Parameter array.</param>
public LogEventInfo(LogLevel level, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters)
: this(level, loggerName, formatProvider, message, parameters, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LogEventInfo" /> class.
/// </summary>
/// <param name="level">Log level.</param>
/// <param name="loggerName">Logger name.</param>
/// <param name="formatProvider">An IFormatProvider that supplies culture-specific formatting information.</param>
/// <param name="message">Log message including parameter placeholders.</param>
/// <param name="parameters">Parameter array.</param>
/// <param name="exception">Exception information.</param>
public LogEventInfo(LogLevel level, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters, Exception exception)
{
TimeStamp = CurrentTimeGetter.Now;
Level = level;
LoggerName = loggerName;
Message = message;
Parameters = parameters;
FormatProvider = formatProvider;
Exception = exception;
SequenceID = Interlocked.Increment(ref globalSequenceId);
if (NeedToPreformatMessage(parameters))
{
CalcFormattedMessage();
}
}
/// <summary>
/// Gets the unique identifier of log event which is automatically generated
/// and monotonously increasing.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "ID", Justification = "Backwards compatibility")]
public int SequenceID { get; private set; }
/// <summary>
/// Gets or sets the timestamp of the logging event.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "TimeStamp", Justification = "Backwards compatibility.")]
public DateTime TimeStamp { get; set; }
/// <summary>
/// Gets or sets the level of the logging event.
/// </summary>
public LogLevel Level { get; set; }
#if !NET_CF
/// <summary>
/// Gets a value indicating whether stack trace has been set for this event.
/// </summary>
public bool HasStackTrace
{
get { return StackTrace != null; }
}
/// <summary>
/// Gets the stack frame of the method that did the logging.
/// </summary>
public StackFrame UserStackFrame
{
get { return (StackTrace != null) ? StackTrace.GetFrame(UserStackFrameNumber) : null; }
}
/// <summary>
/// Gets the number index of the stack frame that represents the user
/// code (not the NLog code).
/// </summary>
public int UserStackFrameNumber { get; private set; }
/// <summary>
/// Gets the entire stack trace.
/// </summary>
public StackTrace StackTrace { get; private set; }
#endif
/// <summary>
/// Gets or sets the exception information.
/// </summary>
public Exception Exception { get; set; }
/// <summary>
/// Gets or sets the logger name.
/// </summary>
public string LoggerName { get; set; }
/// <summary>
/// Gets the logger short name.
/// </summary>
[Obsolete("This property should not be used.")]
public string LoggerShortName
{
get
{
var lastDot = LoggerName.LastIndexOf('.');
if (lastDot >= 0)
{
return LoggerName.Substring(lastDot + 1);
}
return LoggerName;
}
}
/// <summary>
/// Gets or sets the log message including any parameter placeholders.
/// </summary>
public string Message { get; set; }
/// <summary>
/// Gets or sets the parameter values or null if no parameters have been specified.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "For backwards compatibility.")]
public object[] Parameters { get; set; }
/// <summary>
/// Gets or sets the format provider that was provided while logging or <see langword="null" />
/// when no formatProvider was specified.
/// </summary>
public IFormatProvider FormatProvider { get; set; }
/// <summary>
/// Gets the formatted message.
/// </summary>
public string FormattedMessage
{
get
{
if (formattedMessage == null)
{
CalcFormattedMessage();
}
return formattedMessage;
}
}
/// <summary>
/// Gets the dictionary of per-event context properties.
/// </summary>
public IDictionary<object, object> Properties
{
get
{
if (properties == null)
{
InitEventContext();
}
return properties;
}
}
/// <summary>
/// Gets the dictionary of per-event context properties.
/// </summary>
[Obsolete("Use LogEventInfo.Properties instead.", true)]
public IDictionary Context
{
get
{
if (eventContextAdapter == null)
{
InitEventContext();
}
return eventContextAdapter;
}
}
/// <summary>
/// Creates the null event.
/// </summary>
/// <returns>Null log event.</returns>
public static LogEventInfo CreateNullEvent()
{
return new LogEventInfo(LogLevel.Off, string.Empty, string.Empty);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="message">The message.</param>
/// <returns>
/// Instance of <see cref="LogEventInfo" />.
/// </returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, [Localizable(false)] string message)
{
return new LogEventInfo(logLevel, loggerName, null, message, null);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="message">The message.</param>
/// <param name="parameters">The parameters.</param>
/// <returns>
/// Instance of <see cref="LogEventInfo" />.
/// </returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, IFormatProvider formatProvider, [Localizable(false)] string message, object[] parameters)
{
return new LogEventInfo(logLevel, loggerName, formatProvider, message, parameters);
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="formatProvider">The format provider.</param>
/// <param name="message">The message.</param>
/// <returns>
/// Instance of <see cref="LogEventInfo" />.
/// </returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, IFormatProvider formatProvider, object message)
{
return new LogEventInfo(logLevel, loggerName, formatProvider, "{0}", new[] {message});
}
/// <summary>
/// Creates the log event.
/// </summary>
/// <param name="logLevel">The log level.</param>
/// <param name="loggerName">Name of the logger.</param>
/// <param name="message">The message.</param>
/// <param name="exception">The exception.</param>
/// <returns>
/// Instance of <see cref="LogEventInfo" />.
/// </returns>
public static LogEventInfo Create(LogLevel logLevel, string loggerName, [Localizable(false)] string message, Exception exception)
{
return new LogEventInfo(logLevel, loggerName, null, message, null, exception);
}
/// <summary>
/// Creates <see cref="AsyncLogEventInfo" /> from this <see cref="LogEventInfo" /> by attaching the specified asynchronous continuation.
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <returns>
/// Instance of <see cref="AsyncLogEventInfo" /> with attached continuation.
/// </returns>
public AsyncLogEventInfo WithContinuation(AsyncContinuation asyncContinuation)
{
return new AsyncLogEventInfo(this, asyncContinuation);
}
/// <summary>
/// Returns a string representation of this log event.
/// </summary>
/// <returns>String representation of the log event.</returns>
public override string ToString()
{
return "Log Event: Logger='" + LoggerName + "' Level=" + Level + " Message='" + FormattedMessage + "' SequenceID=" + SequenceID;
}
#if !NET_CF
/// <summary>
/// Sets the stack trace for the event info.
/// </summary>
/// <param name="stackTrace">The stack trace.</param>
/// <param name="userStackFrame">Index of the first user stack frame within the stack trace.</param>
public void SetStackTrace(StackTrace stackTrace, int userStackFrame)
{
StackTrace = stackTrace;
UserStackFrameNumber = userStackFrame;
}
#endif
internal string AddCachedLayoutValue(Layout layout, string value)
{
if (layoutCache == null)
{
layoutCache = new Dictionary<Layout, string>();
}
lock (layoutCache)
{
layoutCache[layout] = value;
}
return value;
}
internal bool TryGetCachedLayoutValue(Layout layout, out string value)
{
if (layoutCache == null)
{
value = null;
return false;
}
lock (layoutCache)
{
return layoutCache.TryGetValue(layout, out value);
}
}
private static bool NeedToPreformatMessage(object[] parameters)
{
// we need to preformat message if it contains any parameters which could possibly
// do logging in their ToString()
if (parameters == null || parameters.Length == 0)
{
return false;
}
if (parameters.Length > 3)
{
// too many parameters, too costly to check
return true;
}
if (!IsSafeToDeferFormatting(parameters[0]))
{
return true;
}
if (parameters.Length >= 2)
{
if (!IsSafeToDeferFormatting(parameters[1]))
{
return true;
}
}
if (parameters.Length >= 3)
{
if (!IsSafeToDeferFormatting(parameters[2]))
{
return true;
}
}
return false;
}
private static bool IsSafeToDeferFormatting(object value)
{
if (value == null)
{
return true;
}
return value.GetType().IsPrimitive || (value is string);
}
private void CalcFormattedMessage()
{
if (Parameters == null || Parameters.Length == 0)
{
formattedMessage = Message;
}
else
{
try
{
formattedMessage = string.Format(FormatProvider ?? CultureInfo.CurrentCulture, Message, Parameters);
}
catch (Exception exception)
{
formattedMessage = Message;
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Warn("Error when formatting a message: {0}", exception);
}
}
}
private void InitEventContext()
{
properties = new Dictionary<object, object>();
eventContextAdapter = new DictionaryAdapter<object, object>(properties);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Diagnostics;
using Internal.Runtime;
using Internal.Runtime.Augments;
using Internal.Runtime.CompilerServices;
using Internal.NativeFormat;
using Internal.TypeSystem;
using Internal.TypeSystem.NoMetadata;
namespace Internal.Runtime.TypeLoader
{
//
// Wrap state required by the native layout info parsing in a structure, so that it can be conveniently passed around.
//
internal class NativeLayoutInfoLoadContext
{
public TypeSystemContext _typeSystemContext;
public NativeFormatModuleInfo _module;
private ExternalReferencesTable _staticInfoLookup;
private ExternalReferencesTable _externalReferencesLookup;
public Instantiation _typeArgumentHandles;
public Instantiation _methodArgumentHandles;
public ulong[] _debuggerPreparedExternalReferences;
private TypeDesc GetInstantiationType(ref NativeParser parser, uint arity)
{
DefType typeDefinition = (DefType)GetType(ref parser);
TypeDesc[] typeArguments = new TypeDesc[arity];
for (uint i = 0; i < arity; i++)
typeArguments[i] = GetType(ref parser);
return _typeSystemContext.ResolveGenericInstantiation(typeDefinition, new Instantiation(typeArguments));
}
private TypeDesc GetModifierType(ref NativeParser parser, TypeModifierKind modifier)
{
TypeDesc typeParameter = GetType(ref parser);
switch (modifier)
{
case TypeModifierKind.Array:
return _typeSystemContext.GetArrayType(typeParameter);
case TypeModifierKind.ByRef:
return _typeSystemContext.GetByRefType(typeParameter);
case TypeModifierKind.Pointer:
return _typeSystemContext.GetPointerType(typeParameter);
default:
parser.ThrowBadImageFormatException();
return null;
}
}
private void InitializeExternalReferencesLookup()
{
if (!_externalReferencesLookup.IsInitialized())
{
if (this._debuggerPreparedExternalReferences == null)
{
bool success = _externalReferencesLookup.InitializeNativeReferences(_module);
Debug.Assert(success);
}
else
{
_externalReferencesLookup.InitializeDebuggerReference(this._debuggerPreparedExternalReferences);
}
}
}
private IntPtr GetExternalReferencePointer(uint index)
{
InitializeExternalReferencesLookup();
return _externalReferencesLookup.GetIntPtrFromIndex(index);
}
internal TypeDesc GetExternalType(uint index)
{
InitializeExternalReferencesLookup();
RuntimeTypeHandle rtth = _externalReferencesLookup.GetRuntimeTypeHandleFromIndex(index);
return _typeSystemContext.ResolveRuntimeTypeHandle(rtth);
}
internal IntPtr GetGCStaticInfo(uint index)
{
if (!_staticInfoLookup.IsInitialized())
{
bool success = _staticInfoLookup.InitializeNativeStatics(_module);
Debug.Assert(success);
}
return _staticInfoLookup.GetIntPtrFromIndex(index);
}
private unsafe TypeDesc GetLookbackType(ref NativeParser parser, uint lookback)
{
var lookbackParser = parser.GetLookbackParser(lookback);
return GetType(ref lookbackParser);
}
internal TypeDesc GetType(ref NativeParser parser)
{
uint data;
var kind = parser.GetTypeSignatureKind(out data);
switch (kind)
{
case TypeSignatureKind.Lookback:
return GetLookbackType(ref parser, data);
case TypeSignatureKind.Variable:
uint index = data >> 1;
return (((data & 0x1) != 0) ? _methodArgumentHandles : _typeArgumentHandles)[checked((int)index)];
case TypeSignatureKind.Instantiation:
return GetInstantiationType(ref parser, data);
case TypeSignatureKind.Modifier:
return GetModifierType(ref parser, (TypeModifierKind)data);
case TypeSignatureKind.External:
return GetExternalType(data);
case TypeSignatureKind.MultiDimArray:
{
DefType elementType = (DefType)GetType(ref parser);
int rank = (int)data;
// Skip encoded bounds and lobounds
uint boundsCount = parser.GetUnsigned();
while (boundsCount > 0)
{
parser.GetUnsigned();
boundsCount--;
}
uint loBoundsCount = parser.GetUnsigned();
while (loBoundsCount > 0)
{
parser.GetUnsigned();
loBoundsCount--;
}
return _typeSystemContext.GetArrayType(elementType, rank);
}
case TypeSignatureKind.BuiltIn:
return _typeSystemContext.GetWellKnownType((WellKnownType)data);
case TypeSignatureKind.FunctionPointer:
Debug.Assert(false, "NYI!");
parser.ThrowBadImageFormatException();
return null;
default:
parser.ThrowBadImageFormatException();
return null;
}
}
internal MethodDesc GetMethod(ref NativeParser parser, out RuntimeSignature methodNameSig, out RuntimeSignature methodSig)
{
MethodFlags flags = (MethodFlags)parser.GetUnsigned();
IntPtr functionPointer = IntPtr.Zero;
if ((flags & MethodFlags.HasFunctionPointer) != 0)
functionPointer = GetExternalReferencePointer(parser.GetUnsigned());
DefType containingType = (DefType)GetType(ref parser);
MethodNameAndSignature nameAndSignature = TypeLoaderEnvironment.Instance.GetMethodNameAndSignature(ref parser, _module.Handle, out methodNameSig, out methodSig);
bool unboxingStub = (flags & MethodFlags.IsUnboxingStub) != 0;
MethodDesc retVal = null;
if ((flags & MethodFlags.HasInstantiation) != 0)
{
TypeDesc[] typeArguments = GetTypeSequence(ref parser);
Debug.Assert(typeArguments.Length > 0);
retVal = this._typeSystemContext.ResolveGenericMethodInstantiation(unboxingStub, containingType, nameAndSignature, new Instantiation(typeArguments), functionPointer, (flags & MethodFlags.FunctionPointerIsUSG) != 0);
}
else
{
retVal = this._typeSystemContext.ResolveRuntimeMethod(unboxingStub, containingType, nameAndSignature, functionPointer, (flags & MethodFlags.FunctionPointerIsUSG) != 0);
}
if ((flags & MethodFlags.FunctionPointerIsUSG) != 0)
{
// TODO, consider a change such that if a USG function pointer is passed in, but we have
// a way to get a non-usg pointer, that may be preferable
Debug.Assert(retVal.UsgFunctionPointer != IntPtr.Zero);
}
return retVal;
}
internal MethodDesc GetMethod(ref NativeParser parser)
{
RuntimeSignature methodSig;
RuntimeSignature methodNameSig;
return GetMethod(ref parser, out methodNameSig, out methodSig);
}
internal TypeDesc[] GetTypeSequence(ref NativeParser parser)
{
uint count = parser.GetSequenceCount();
TypeDesc[] sequence = new TypeDesc[count];
for (uint i = 0; i < count; i++)
{
sequence[i] = GetType(ref parser);
}
return sequence;
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Logging;
using osuTK;
using osuTK.Graphics;
using osu.Framework.Development;
using osu.Framework.Timing;
using osuTK.Input;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Input.Events;
namespace osu.Framework.Graphics.Visualisation
{
internal class LogOverlay : OverlayContainer
{
private readonly FillFlowContainer flow;
protected override bool BlockPositionalInput => false;
private StopwatchClock clock;
private readonly Box box;
private const float background_alpha = 0.6f;
public LogOverlay()
{
//todo: use Input as font
Width = 700;
AutoSizeAxes = Axes.Y;
Anchor = Anchor.BottomLeft;
Origin = Anchor.BottomLeft;
Margin = new MarginPadding(1);
Masking = true;
Children = new Drawable[]
{
box = new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black,
Alpha = background_alpha,
},
flow = new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
}
};
}
protected override void LoadComplete()
{
// custom clock is used to adjust log display speed (to freeze log display with a key).
Clock = new FramedClock(clock = new StopwatchClock(true));
base.LoadComplete();
addEntry(new LogEntry
{
Level = LogLevel.Important,
Message = "The debug log overlay is currently being displayed. You can toggle with Ctrl+F10 at any point.",
Target = LoggingTarget.Information,
});
}
private int logPosition;
private void addEntry(LogEntry entry)
{
if (!DebugUtils.IsDebugBuild && entry.Level <= LogLevel.Verbose)
return;
int pos = Interlocked.Increment(ref logPosition);
Schedule(() =>
{
const int display_length = 4000;
LoadComponentAsync(new DrawableLogEntry(entry), drawEntry =>
{
flow.Insert(pos, drawEntry);
drawEntry.FadeInFromZero(800, Easing.OutQuint).Delay(display_length).FadeOut(800, Easing.InQuint);
drawEntry.Expire();
});
});
}
protected override bool OnKeyDown(KeyDownEvent e)
{
if (!e.Repeat)
setHoldState(e.Key == Key.ControlLeft || e.Key == Key.ControlRight);
return base.OnKeyDown(e);
}
protected override void OnKeyUp(KeyUpEvent e)
{
if (!e.ControlPressed)
setHoldState(false);
base.OnKeyUp(e);
}
private void setHoldState(bool controlPressed)
{
box.Alpha = controlPressed ? 1 : background_alpha;
if (clock != null) clock.Rate = controlPressed ? 0 : 1;
}
protected override void PopIn()
{
Logger.NewEntry += addEntry;
this.FadeIn(100);
}
protected override void PopOut()
{
Logger.NewEntry -= addEntry;
setHoldState(false);
this.FadeOut(100);
}
protected override void Dispose(bool isDisposing)
{
base.Dispose(isDisposing);
Logger.NewEntry -= addEntry;
}
}
internal class DrawableLogEntry : Container
{
private const float target_box_width = 65;
private const float font_size = 14;
public DrawableLogEntry(LogEntry entry)
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Color4 col = getColourForEntry(entry);
Children = new Drawable[]
{
new Container
{
//log target coloured box
Margin = new MarginPadding(3),
Size = new Vector2(target_box_width, font_size),
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
CornerRadius = 5,
Masking = true,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = col,
},
new SpriteText
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Shadow = true,
ShadowColour = Color4.Black,
Margin = new MarginPadding { Left = 5, Right = 5 },
Font = FrameworkFont.Regular.With(size: font_size),
Text = entry.Target?.ToString() ?? entry.LoggerName,
}
}
},
new Container
{
AutoSizeAxes = Axes.Y,
RelativeSizeAxes = Axes.X,
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
Padding = new MarginPadding { Left = target_box_width + 10 },
Child = new SpriteText
{
RelativeSizeAxes = Axes.X,
Font = FrameworkFont.Regular.With(size: font_size),
Text = entry.Message
}
}
};
}
private Color4 getColourForEntry(LogEntry entry)
{
switch (entry.Target)
{
case LoggingTarget.Runtime:
return Color4.YellowGreen;
case LoggingTarget.Network:
return Color4.BlueViolet;
case LoggingTarget.Performance:
return Color4.HotPink;
case LoggingTarget.Information:
return Color4.CadetBlue;
default:
return Color4.Cyan;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace Web.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary
<Type, Func<object, string>>
{
{typeof (RequiredAttribute), a => "Required"},
{
typeof (RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute) a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}",
range.Minimum, range.Maximum);
}
},
{
typeof (MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute) a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{
typeof (MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute) a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{
typeof (StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute) a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}",
strLength.MinimumLength, strLength.MaximumLength);
}
},
{
typeof (DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute) a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}",
dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{
typeof (RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute) a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}",
regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{typeof (Int16), "integer"},
{typeof (Int32), "integer"},
{typeof (Int64), "integer"},
{typeof (UInt16), "unsigned integer"},
{typeof (UInt32), "unsigned integer"},
{typeof (UInt64), "unsigned integer"},
{typeof (Byte), "byte"},
{typeof (Char), "character"},
{typeof (SByte), "signed byte"},
{typeof (Uri), "URI"},
{typeof (Single), "decimal number"},
{typeof (Double), "decimal number"},
{typeof (Decimal), "decimal number"},
{typeof (String), "string"},
{typeof (Guid), "globally unique identifier"},
{typeof (TimeSpan), "time interval"},
{typeof (DateTime), "date"},
{typeof (DateTimeOffset), "date"},
{typeof (Boolean), "boolean"},
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider =
new Lazy<IModelDocumentationProvider>(
() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get { return _documentationProvider.Value; }
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof (IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof (IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof (KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof (NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof (string), typeof (string));
}
if (typeof (IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof (object), typeof (object));
}
if (typeof (IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof (object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum
? member.GetCustomAttribute<EnumMemberAttribute>() != null
: member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType,
Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType,
Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.CognitiveServices
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Operations operations.
/// </summary>
internal partial class Operations : IServiceOperations<CognitiveServicesManagementClient>, IOperations
{
/// <summary>
/// Initializes a new instance of the Operations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal Operations(CognitiveServicesManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the CognitiveServicesManagementClient
/// </summary>
public CognitiveServicesManagementClient Client { get; private set; }
/// <summary>
/// Lists all the available Cognitive Services account operations.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<OperationEntity>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.CognitiveServices/operations").ToString();
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<OperationEntity>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<OperationEntity>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists all the available Cognitive Services account operations.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<OperationEntity>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<OperationEntity>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<OperationEntity>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// 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.Globalization;
using Xunit;
public static class SingleTests
{
[Fact]
public static void TestCtor()
{
Single i = new Single();
Assert.True(i == 0);
i = 41;
Assert.True(i == 41);
i = (Single)41.3;
Assert.True(i == (Single)41.3);
}
[Fact]
public static void TestMaxValue()
{
Single max = Single.MaxValue;
Assert.True(max == (Single)3.40282346638528859e+38);
}
[Fact]
public static void TestMinValue()
{
Single min = Single.MinValue;
Assert.True(min == ((Single)(-3.40282346638528859e+38)));
}
[Fact]
public static void TestEpsilon()
{
// Single Single.Epsilon
Assert.Equal<Single>((Single)1.4e-45, Single.Epsilon);
}
[Fact]
public static void TestIsInfinity()
{
// Boolean Single.IsInfinity(Single)
Assert.True(Single.IsInfinity(Single.NegativeInfinity));
Assert.True(Single.IsInfinity(Single.PositiveInfinity));
}
[Fact]
public static void TestNaN()
{
// Single Single.NaN
Assert.Equal<Single>((Single)0.0 / (Single)0.0, Single.NaN);
}
[Fact]
public static void TestIsNaN()
{
// Boolean Single.IsNaN(Single)
Assert.True(Single.IsNaN(Single.NaN));
}
[Fact]
public static void TestNegativeInfinity()
{
// Single Single.NegativeInfinity
Assert.Equal<Single>((Single)(-1.0) / (Single)0.0, Single.NegativeInfinity);
}
[Fact]
public static void TestIsNegativeInfinity()
{
// Boolean Single.IsNegativeInfinity(Single)
Assert.True(Single.IsNegativeInfinity(Single.NegativeInfinity));
}
[Fact]
public static void TestPositiveInfinity()
{
// Single Single.PositiveInfinity
Assert.Equal<Single>((Single)1.0 / (Single)0.0, Single.PositiveInfinity);
}
[Fact]
public static void TestIsPositiveInfinity()
{
// Boolean Single.IsPositiveInfinity(Single)
Assert.True(Single.IsPositiveInfinity(Single.PositiveInfinity));
}
[Fact]
public static void TestCompareToObject()
{
Single i = 234;
IComparable comparable = i;
Assert.Equal(1, comparable.CompareTo(null));
Assert.Equal(0, comparable.CompareTo((Single)234));
Assert.True(comparable.CompareTo(Single.MinValue) > 0);
Assert.True(comparable.CompareTo((Single)0) > 0);
Assert.True(comparable.CompareTo((Single)(-123)) > 0);
Assert.True(comparable.CompareTo((Single)123) > 0);
Assert.True(comparable.CompareTo((Single)456) < 0);
Assert.True(comparable.CompareTo(Single.MaxValue) < 0);
Assert.Throws<ArgumentException>(() => comparable.CompareTo("a"));
}
[Fact]
public static void TestCompareTo()
{
Single i = 234;
Assert.Equal(0, i.CompareTo((Single)234));
Assert.True(i.CompareTo(Single.MinValue) > 0);
Assert.True(i.CompareTo((Single)0) > 0);
Assert.True(i.CompareTo((Single)(-123)) > 0);
Assert.True(i.CompareTo((Single)123) > 0);
Assert.True(i.CompareTo((Single)456) < 0);
Assert.True(i.CompareTo(Single.MaxValue) < 0);
Assert.True(Single.NaN.CompareTo(Single.NaN) == 0);
Assert.True(Single.NaN.CompareTo(0) < 0);
Assert.True(i.CompareTo(Single.NaN) > 0);
}
[Fact]
public static void TestEqualsObject()
{
Single i = 789;
object obj1 = (Single)789;
Assert.True(i.Equals(obj1));
object obj2 = (Single)(-789);
Assert.True(!i.Equals(obj2));
object obj3 = (Single)0;
Assert.True(!i.Equals(obj3));
}
[Fact]
public static void TestEquals()
{
Single i = -911;
Assert.True(i.Equals((Single)(-911)));
Assert.True(!i.Equals((Single)911));
Assert.True(!i.Equals((Single)0));
Assert.True(Single.NaN.Equals(Single.NaN));
}
[Fact]
public static void TestGetHashCode()
{
Single i1 = 123;
Single i2 = 654;
Assert.NotEqual(0, i1.GetHashCode());
Assert.NotEqual(i1.GetHashCode(), i2.GetHashCode());
}
[Fact]
public static void TestToString()
{
Single i1 = 6310;
Assert.Equal("6310", i1.ToString());
Single i2 = -8249;
Assert.Equal("-8249", i2.ToString());
}
[Fact]
public static void TestToStringFormatProvider()
{
var numberFormat = new System.Globalization.NumberFormatInfo();
Single i1 = 6310;
Assert.Equal("6310", i1.ToString(numberFormat));
Single i2 = -8249;
Assert.Equal("-8249", i2.ToString(numberFormat));
Single i3 = -2468;
// Changing the negative pattern doesn't do anything without also passing in a format string
numberFormat.NumberNegativePattern = 0;
Assert.Equal("-2468", i3.ToString(numberFormat));
Assert.Equal("NaN", Single.NaN.ToString(NumberFormatInfo.InvariantInfo));
Assert.Equal("Infinity", Single.PositiveInfinity.ToString(NumberFormatInfo.InvariantInfo));
Assert.Equal("-Infinity", Single.NegativeInfinity.ToString(NumberFormatInfo.InvariantInfo));
}
[Fact]
public static void TestToStringFormat()
{
Single i1 = 6310;
Assert.Equal("6310", i1.ToString("G"));
Single i2 = -8249;
Assert.Equal("-8249", i2.ToString("g"));
Single i3 = -2468;
Assert.Equal("-2,468.00", i3.ToString("N"));
}
[Fact]
public static void TestToStringFormatFormatProvider()
{
var numberFormat = new System.Globalization.NumberFormatInfo();
Single i1 = 6310;
Assert.Equal("6310", i1.ToString("G", numberFormat));
Single i2 = -8249;
Assert.Equal("-8249", i2.ToString("g", numberFormat));
numberFormat.NegativeSign = "xx"; // setting it to trash to make sure it doesn't show up
numberFormat.NumberGroupSeparator = "*";
numberFormat.NumberNegativePattern = 0;
Single i3 = -2468;
Assert.Equal("(2*468.00)", i3.ToString("N", numberFormat));
}
[Fact]
public static void TestParse()
{
Assert.Equal(123, Single.Parse("123"));
Assert.Equal(-123, Single.Parse("-123"));
//TODO: Negative tests once we get better exceptions
}
[Fact]
public static void TestParseNumberStyle()
{
Assert.Equal<Single>(123.1f, Single.Parse("123.1", NumberStyles.AllowDecimalPoint));
Assert.Equal(1000, Single.Parse("1,000", NumberStyles.AllowThousands));
//TODO: Negative tests once we get better exceptions
}
[Fact]
public static void TestParseFormatProvider()
{
var nfi = new NumberFormatInfo();
Assert.Equal(123, Single.Parse("123", nfi));
Assert.Equal(-123, Single.Parse("-123", nfi));
//TODO: Negative tests once we get better exceptions
}
[Fact]
public static void TestParseNumberStyleFormatProvider()
{
var nfi = new NumberFormatInfo();
Assert.Equal<Single>(123.123f, Single.Parse("123.123", NumberStyles.Float, nfi));
nfi.CurrencySymbol = "$";
Assert.Equal(1000, Single.Parse("$1,000", NumberStyles.Currency, nfi));
//TODO: Negative tests once we get better exception support
}
[Fact]
public static void TestTryParse()
{
// Defaults AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowDecimalPoint | AllowExponent | AllowThousands
Single i;
Assert.True(Single.TryParse("123", out i)); // Simple
Assert.Equal(123, i);
Assert.True(Single.TryParse("-385", out i)); // LeadingSign
Assert.Equal(-385, i);
Assert.True(Single.TryParse(" 678 ", out i)); // Leading/Trailing whitespace
Assert.Equal(678, i);
Assert.True(Single.TryParse("678.90", out i)); // Decimal
Assert.Equal((Single)678.90, i);
Assert.True(Single.TryParse("1E23", out i)); // Exponent
Assert.Equal((Single)1E23, i);
Assert.True(Single.TryParse("1,000", out i)); // Thousands
Assert.Equal(1000, i);
Assert.False(Single.TryParse("$1000", out i)); // Currency
Assert.False(Single.TryParse("abc", out i)); // Hex digits
Assert.False(Single.TryParse("(135)", out i)); // Parentheses
}
[Fact]
public static void TestTryParseNumberStyleFormatProvider()
{
Single i;
var nfi = new NumberFormatInfo();
Assert.True(Single.TryParse("123.123", NumberStyles.Any, nfi, out i)); // Simple positive
Assert.Equal(123.123f, i);
Assert.True(Single.TryParse("123", NumberStyles.Float, nfi, out i)); // Simple Hex
Assert.Equal(123, i);
nfi.CurrencySymbol = "$";
Assert.True(Single.TryParse("$1,000", NumberStyles.Currency, nfi, out i)); // Currency/Thousands postive
Assert.Equal(1000, i);
Assert.False(Single.TryParse("abc", NumberStyles.None, nfi, out i)); // Hex Number negative
Assert.False(Single.TryParse("678.90", NumberStyles.Integer, nfi, out i)); // Decimal
Assert.False(Single.TryParse(" 678 ", NumberStyles.None, nfi, out i)); // Trailing/Leading whitespace negative
Assert.True(Single.TryParse("(135)", NumberStyles.AllowParentheses, nfi, out i)); // Parenthese postive
Assert.Equal(-135, i);
Assert.True(Single.TryParse("Infinity", NumberStyles.Any, NumberFormatInfo.InvariantInfo, out i));
Assert.True(Single.IsPositiveInfinity(i));
Assert.True(Single.TryParse("-Infinity", NumberStyles.Any, NumberFormatInfo.InvariantInfo, out i));
Assert.True(Single.IsNegativeInfinity(i));
Assert.True(Single.TryParse("NaN", NumberStyles.Any, NumberFormatInfo.InvariantInfo, out i));
Assert.True(Single.IsNaN(i));
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Configuration;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Odbc;
using System.Data.OracleClient;
using System.IO;
namespace Rainbow.Framwork.Data
{
public class DatabaseHelper:IDisposable
{
private string strConnectionString;
private DbConnection objConnection;
private DbCommand objCommand;
private DbProviderFactory objFactory = null;
private bool boolHandleErrors;
private string strLastError;
private bool boolLogError;
private string strLogFile;
public DatabaseHelper(string connectionstring,Providers provider)
{
strConnectionString = connectionstring;
switch (provider)
{
case Providers.SqlServer:
objFactory = SqlClientFactory.Instance;
break;
case Providers.OleDb:
objFactory = OleDbFactory.Instance;
break;
case Providers.Oracle:
objFactory = OracleClientFactory.Instance;
break;
case Providers.ODBC:
objFactory = OdbcFactory.Instance;
break;
case Providers.ConfigDefined:
string providername=ConfigurationManager.ConnectionStrings["connectionstring"].ProviderName;
switch (providername)
{
case "System.Data.SqlClient":
objFactory = SqlClientFactory.Instance;
break;
case "System.Data.OleDb":
objFactory = OleDbFactory.Instance;
break;
case "System.Data.OracleClient":
objFactory = OracleClientFactory.Instance;
break;
case "System.Data.Odbc":
objFactory = OdbcFactory.Instance;
break;
}
break;
}
objConnection = objFactory.CreateConnection();
objCommand = objFactory.CreateCommand();
objConnection.ConnectionString = strConnectionString;
objCommand.Connection = objConnection;
}
public DatabaseHelper(Providers provider):this(ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString,provider)
{
}
public DatabaseHelper(string connectionstring): this(connectionstring, Providers.SqlServer)
{
}
public DatabaseHelper():this(ConfigurationManager.ConnectionStrings["connectionstring"].ConnectionString,Providers.ConfigDefined)
{
}
public bool HandleErrors
{
get
{
return boolHandleErrors;
}
set
{
boolHandleErrors = value;
}
}
public string LastError
{
get
{
return strLastError;
}
}
public bool LogErrors
{
get
{
return boolLogError;
}
set
{
boolLogError=value;
}
}
public string LogFile
{
get
{
return strLogFile;
}
set
{
strLogFile = value;
}
}
public int AddParameter(string name,object value)
{
DbParameter p = objFactory.CreateParameter();
p.ParameterName = name;
p.Value=value;
return objCommand.Parameters.Add(p);
}
public int AddParameter(DbParameter parameter)
{
return objCommand.Parameters.Add(parameter);
}
public DbCommand Command
{
get
{
return objCommand;
}
}
public void BeginTransaction()
{
if (objConnection.State == System.Data.ConnectionState.Closed)
{
objConnection.Open();
}
objCommand.Transaction = objConnection.BeginTransaction();
}
public void CommitTransaction()
{
objCommand.Transaction.Commit();
objConnection.Close();
}
public void RollbackTransaction()
{
objCommand.Transaction.Rollback();
objConnection.Close();
}
#region ExecuteNonQuery
public int ExecuteNonQuery(string spName)
{
return ExecuteNonQuery(spName, CommandType.StoredProcedure, ConnectionState.CloseOnExit);
}
public int ExecuteNonQuery(string spName, params object[] parameterValues)
{
return ExecuteNonQuery(spName, ConnectionState.CloseOnExit, parameterValues);
}
public int ExecuteNonQuery(string spName, ConnectionState connectionstate, params object[] parameterValues)
{
objCommand.CommandText = spName;
objCommand.CommandType = CommandType.StoredProcedure;
DbParameter[] parameters = ParameterCache.GetSpParameterSet(objConnection, spName);
AssignParameterValues(parameters, parameterValues);
objCommand.Parameters.AddRange(parameters);
int i = -1;
try
{
if (objConnection.State == System.Data.ConnectionState.Closed)
{
objConnection.Open();
}
i = objCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
HandleExceptions(ex);
}
finally
{
objCommand.Parameters.Clear();
if (connectionstate == ConnectionState.CloseOnExit)
{
objConnection.Close();
}
}
return i;
}
public int ExecuteNonQuery(string query, CommandType commandtype)
{
return ExecuteNonQuery(query, commandtype, ConnectionState.CloseOnExit);
}
public int ExecuteNonQuery(string query, CommandType commandtype, ConnectionState connectionstate)
{
objCommand.CommandText = query;
objCommand.CommandType = commandtype;
int i = -1;
try
{
if (objConnection.State == System.Data.ConnectionState.Closed)
{
objConnection.Open();
}
i = objCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
HandleExceptions(ex);
}
finally
{
objCommand.Parameters.Clear();
if (connectionstate == ConnectionState.CloseOnExit)
{
objConnection.Close();
}
}
return i;
}
#endregion
#region ExecuteScalar
public object ExecuteScalar(string spName)
{
return ExecuteScalar(spName, CommandType.StoredProcedure, ConnectionState.CloseOnExit);
}
public object ExecuteScalar(string spName, params object[] parameterValues)
{
return ExecuteScalar(spName, ConnectionState.CloseOnExit, parameterValues);
}
public object ExecuteScalar(string spName, ConnectionState connectionstate, params object[] parameterValues)
{
objCommand.CommandText = spName;
objCommand.CommandType = CommandType.StoredProcedure;
DbParameter[] parameters = ParameterCache.GetSpParameterSet(objConnection, spName);
AssignParameterValues(parameters, parameterValues);
objCommand.Parameters.AddRange(parameters);
object o = null;
try
{
if (objConnection.State == System.Data.ConnectionState.Closed)
{
objConnection.Open();
}
o = objCommand.ExecuteScalar();
}
catch (Exception ex)
{
HandleExceptions(ex);
}
finally
{
objCommand.Parameters.Clear();
if (connectionstate == ConnectionState.CloseOnExit)
{
objConnection.Close();
}
}
return o;
}
public object ExecuteScalar(string query, CommandType commandtype)
{
return ExecuteScalar(query, commandtype, ConnectionState.CloseOnExit);
}
public object ExecuteScalar(string query, CommandType commandtype, ConnectionState connectionstate)
{
objCommand.CommandText = query;
objCommand.CommandType = commandtype;
object o = null;
try
{
if (objConnection.State == System.Data.ConnectionState.Closed)
{
objConnection.Open();
}
o = objCommand.ExecuteScalar();
}
catch (Exception ex)
{
HandleExceptions(ex);
}
finally
{
objCommand.Parameters.Clear();
if (connectionstate == ConnectionState.CloseOnExit)
{
objConnection.Close();
}
}
return o;
}
#endregion
#region ExecuteReader
public DbDataReader ExecuteReader(string spName)
{
return ExecuteReader(spName, CommandType.StoredProcedure, ConnectionState.CloseOnExit);
}
public DbDataReader ExecuteReader(string spName, params object[] parameterValues)
{
return ExecuteReader(spName, ConnectionState.CloseOnExit, parameterValues);
}
public DbDataReader ExecuteReader(string spName, ConnectionState connectionstate, params object[] parameterValues)
{
objCommand.CommandText = spName;
objCommand.CommandType = CommandType.StoredProcedure;
DbParameter[] parameters = ParameterCache.GetSpParameterSet(objConnection, spName);
AssignParameterValues(parameters, parameterValues);
objCommand.Parameters.AddRange(parameters);
DbDataReader reader = null;
try
{
if (objConnection.State == System.Data.ConnectionState.Closed)
{
objConnection.Open();
}
if (connectionstate == ConnectionState.CloseOnExit)
{
reader = objCommand.ExecuteReader(CommandBehavior.CloseConnection);
}
else
{
reader = objCommand.ExecuteReader();
}
}
catch (Exception ex)
{
HandleExceptions(ex);
}
finally
{
objCommand.Parameters.Clear();
}
return reader;
}
public DbDataReader ExecuteReader(string query, CommandType commandtype)
{
return ExecuteReader(query, commandtype, ConnectionState.CloseOnExit);
}
public DbDataReader ExecuteReader(string query, CommandType commandtype, ConnectionState connectionstate)
{
objCommand.CommandText = query;
objCommand.CommandType = commandtype;
DbDataReader reader = null;
try
{
if (objConnection.State == System.Data.ConnectionState.Closed)
{
objConnection.Open();
}
if (connectionstate == ConnectionState.CloseOnExit)
{
reader = objCommand.ExecuteReader(CommandBehavior.CloseConnection);
}
else
{
reader = objCommand.ExecuteReader();
}
}
catch (Exception ex)
{
HandleExceptions(ex);
}
finally
{
objCommand.Parameters.Clear();
}
return reader;
}
#endregion
#region ExecuteDataSet
public DataSet ExecuteDataSet(string spName)
{
return ExecuteDataSet(spName, CommandType.StoredProcedure, ConnectionState.CloseOnExit);
}
public DataSet ExecuteDataSet(string spName, params object[] parameterValues)
{
return ExecuteDataSet(spName, ConnectionState.CloseOnExit, parameterValues);
}
public DataSet ExecuteDataSet(string spName, ConnectionState connectionstate, params object[] parameterValues)
{
DbDataAdapter adapter = objFactory.CreateDataAdapter();
DbParameter[] parameters = ParameterCache.GetSpParameterSet(objConnection, spName);
AssignParameterValues(parameters, parameterValues);
objCommand.Parameters.AddRange(parameters);
adapter.SelectCommand = objCommand;
DataSet ds = new DataSet();
try
{
adapter.Fill(ds);
}
catch (Exception ex)
{
HandleExceptions(ex);
}
finally
{
objCommand.Parameters.Clear();
if (connectionstate == ConnectionState.CloseOnExit)
{
if (objConnection.State == System.Data.ConnectionState.Open)
{
objConnection.Close();
}
}
}
return ds;
}
public DataSet ExecuteDataSet(string query, CommandType commandtype)
{
return ExecuteDataSet(query, commandtype, ConnectionState.CloseOnExit);
}
public DataSet ExecuteDataSet(string query, CommandType commandtype, ConnectionState connectionstate)
{
DbDataAdapter adapter = objFactory.CreateDataAdapter();
objCommand.CommandText = query;
objCommand.CommandType = commandtype;
adapter.SelectCommand = objCommand;
DataSet ds = new DataSet();
try
{
adapter.Fill(ds);
}
catch (Exception ex)
{
HandleExceptions(ex);
}
finally
{
objCommand.Parameters.Clear();
if (connectionstate == ConnectionState.CloseOnExit)
{
if (objConnection.State == System.Data.ConnectionState.Open)
{
objConnection.Close();
}
}
}
return ds;
}
#endregion
private void HandleExceptions(Exception ex)
{
if (LogErrors)
{
WriteToLog(ex.Message);
}
if (HandleErrors)
{
strLastError = ex.Message;
}
else
{
throw ex;
}
}
private void WriteToLog(string msg)
{
StreamWriter writer= File.AppendText(LogFile);
writer.WriteLine(DateTime.Now.ToString() + " - " + msg);
writer.Close();
}
public void Dispose()
{
objConnection.Close();
objConnection.Dispose();
objCommand.Dispose();
}
/// <summary>
/// This method assigns an array of values to an array of SqlParameters
/// </summary>
/// <param name="commandParameters">Array of SqlParameters to be assigned values</param>
/// <param name="parameterValues">Array of objects holding the values to be assigned</param>
private static void AssignParameterValues(DbParameter[] commandParameters, object[] parameterValues)
{
if ((commandParameters == null) || (parameterValues == null))
{
// Do nothing if we get no data
return;
}
// We must have the same number of values as we pave parameters to put them in
if (commandParameters.Length != parameterValues.Length)
{
throw new ArgumentException("Parameter count does not match Parameter Value count.");
}
// Iterate through the SqlParameters, assigning the values from the corresponding position in the
// value array
for (int i = 0, j = commandParameters.Length; i < j; i++)
{
// If the current array value derives from IDbDataParameter, then assign its Value property
if (parameterValues[i] is IDbDataParameter)
{
IDbDataParameter paramInstance = (IDbDataParameter)parameterValues[i];
if (paramInstance.Value == null)
{
commandParameters[i].Value = DBNull.Value;
}
else
{
commandParameters[i].Value = paramInstance.Value;
}
}
else if (parameterValues[i] == null)
{
commandParameters[i].Value = DBNull.Value;
}
else
{
commandParameters[i].Value = parameterValues[i];
}
}
}
}
/// <summary>
///
/// </summary>
public enum Providers
{
/// <summary>
///
/// </summary>
SqlServer,
/// <summary>
///
/// </summary>
OleDb,
/// <summary>
///
/// </summary>
Oracle,
/// <summary>
///
/// </summary>
ODBC,
/// <summary>
///
/// </summary>
ConfigDefined
}
/// <summary>
///
/// </summary>
public enum ConnectionState
{
/// <summary>
///
/// </summary>
KeepOpen,
/// <summary>
///
/// </summary>
CloseOnExit
}
}
| |
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using System.Text.RegularExpressions;
using System.Collections;
using DG.Tweening;
public enum CardType
{
Action,
Actor,
Context
}
public enum Place {
Deck,
Hand,
Board,
Graveyard
}
public enum PlayerID {
Player1,
Player2
}
public abstract class Card : Target {
public string description;
public string effectDesc;
public Text cardName;
public Text cardDesc;
public Text cardCost;
public Text cardEffect;
[HideInInspector]
public int attack = 1;
[HideInInspector]
public int reputation = 1;
public int baseAttack = 1;
public int baseReputation = 1;
public int corruptionCost = 0;
public int sexismeCost = 0;
public Sprite spriteNormal;
public Sprite spriteSelected;
public Sprite spriteHidden;
public bool hidden = false;
public PlayerID ownerID;
public bool InAnimation = false;
public string id;
public Player owner {
get { return ownerID == PlayerID.Player1 ? GameManager.instance.player1 : GameManager.instance.player2; }
}
public Place place = Place.Deck;
public CardType cardType = CardType.Action;
public AbstractCardEffect effect;
public void useOn(Target c) {
photonView.RPC("useOnRPC", PhotonTargets.AllBuffered, c.photonView.viewID);
}
[RPC]
protected abstract void useOnRPC(int viewID);
public abstract bool isValidTarget(Target c);
public void ChangeReputation(int value) {
reputation += value;
var color = "green";
if (value < 0) {
Shake();
color = "maroon";
}
var go = (GameObject)Instantiate(Resources.Load("FloatingText"), transform.position, Quaternion.identity);
go.GetComponent<Text>().text = "<color=" + color + ">" + value + "</color>";
if (reputation <= 0) {
reputation = 0;
destroy();
}
}
public virtual void OnTurnStart() { effect.OnTurnStart(); }
public virtual void OnTurnEnd() { effect.OnTurnEnd(); }
protected override void init()
{
base.init();
TargetType = TargetType.Card;
attack = baseAttack;
reputation = baseReputation;
cardName.text = fullName;
cardDesc.text = description;
cardEffect.text = Regex.Replace(effectDesc, "%ATTACK%", "<b>"+attack.ToString()+"</b>", RegexOptions.IgnoreCase);
cardEffect.text = Regex.Replace(cardEffect.text, "%REPUTATION%", "<b>" + reputation.ToString() + "</b>", RegexOptions.IgnoreCase);
if (GameManager.instance) {
switch (place) {
case Place.Board:
if (!owner.board.Contains(this)) {
owner.board.Add(this);
}
break;
case Place.Deck:
if (!owner.deck.Contains(this)) {
owner.deck.Add(this);
}
break;
case Place.Hand:
if (!owner.hand.Contains(this)) {
owner.hand.Add(this);
}
break;
}
}
var costText = "<color=maroon>" + corruptionCost + "</color>";
costText += "\n";
costText += "<color=#0080ffff>" + sexismeCost + "</color>";
cardCost.text = costText;
effect = GetComponent<AbstractCardEffect>();
effect.OnInit();
}
public void setSelected(bool isSelected)
{
if (isSelected)
{
SoundManager.Instance.PlayCardShove();
gameObject.GetComponent<Image>().sprite = spriteSelected;
transform.DOScale(new Vector3(1.2f, 1.2f,1f), 0.2f);
effect.OnSelected();
var outline = GetComponent<Outline>();
outline.effectColor = new Color(0f,78f/255f,128f/255f);
}
else
{
gameObject.GetComponent<Image>().sprite = spriteNormal;
transform.DOScale(new Vector3(1.0f, 1.0f, 1f), 0.2f);
effect.OnDeselected();
var outline = GetComponent<Outline>();
outline.effectColor = new Color(78f / 255f, 128f / 255f, 0f,0f);
}
}
public void hide()
{
hidden = true;
gameObject.GetComponent<Image>().sprite = spriteHidden;
foreach (Transform child in transform)
{
child.gameObject.SetActive(false);
}
}
public void show()
{
hidden = false;
gameObject.GetComponent<Image>().sprite = spriteNormal;
foreach (Transform child in transform)
{
child.gameObject.SetActive(true);
}
}
public void destroy(bool suicide = false)
{
if (place == Place.Board) {
effect.OnDeath();
}
show();
owner.RemoveCard(this);
place = Place.Graveyard;
TargetType = TargetType.Graveyard;
transform.SetParent(owner.graveyardPos);
if (cardType == CardType.Action && !suicide) {
transform.DOMove(GameObject.Find("Cards").transform.position, 0.5f);
transform.DOMove(owner.graveyardPos.transform.position, 1.5f).SetDelay(1.5f).SetEase(Ease.OutCubic);
transform.DOScale(new Vector3(1.5f, 1.5f, 1.0f), 0.5f);
transform.DOScale(Vector3.one, 1.0f).SetDelay(1.5f);
}
else {
var cross = (RectTransform)Instantiate(Resources.Load<RectTransform>("Cross"));
cross.SetParent(transform, false);
//cross.anchoredPosition = Vector2.zero;
cross.localScale = Vector3.one;
transform.DOMove(owner.graveyardPos.transform.position, 1.5f).SetDelay(1f).SetEase(Ease.OutCubic);
}
var outline = GetComponent<Outline>();
var color = outline.effectColor;
color.a = 0;
outline.effectColor = color;
//GetComponent<EventTrigger>().enabled = false;
}
public void OnCursorEnter() {
if (DeckManager.Instance) return;
if (place == Place.Deck || place == Place.Graveyard) return;
transform.DOScale(new Vector3(1.2f, 1.2f, 1f), 0.2f);
owner.HoveredCard = this;
}
public void OnCursorExit() {
if (DeckManager.Instance) return;
//if(owner.HoveredCard == this)
owner.HoveredCard = null;
if(GameManager.instance.cardSelected != this)
transform.DOScale(Vector3.one, 0.2f);
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using RestSharp;
using IO.Swagger.Client;
using IO.Swagger.Model;
namespace IO.Swagger.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IOrganizationsApi
{
/// <summary>
/// Get user tokens for existing users, create new users
/// </summary>
/// <remarks>
/// Get user tokens for existing users, create new users
/// </remarks>
/// <param name="organizationId">Organization ID</param>
/// <param name="body">Provides organization token and user ID</param>
/// <returns>UserTokenSuccessfulResponse</returns>
UserTokenSuccessfulResponse V1OrganizationsOrganizationIdUsersPost (int? organizationId, UserTokenRequest body);
/// <summary>
/// Get user tokens for existing users, create new users
/// </summary>
/// <remarks>
/// Get user tokens for existing users, create new users
/// </remarks>
/// <param name="organizationId">Organization ID</param>
/// <param name="body">Provides organization token and user ID</param>
/// <returns>UserTokenSuccessfulResponse</returns>
System.Threading.Tasks.Task<UserTokenSuccessfulResponse> V1OrganizationsOrganizationIdUsersPostAsync (int? organizationId, UserTokenRequest body);
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public class OrganizationsApi : IOrganizationsApi
{
/// <summary>
/// Initializes a new instance of the <see cref="OrganizationsApi"/> class.
/// </summary>
/// <param name="apiClient"> an instance of ApiClient (optional)</param>
/// <returns></returns>
public OrganizationsApi(ApiClient apiClient = null)
{
if (apiClient == null) // use the default one in Configuration
this.ApiClient = Configuration.DefaultApiClient;
else
this.ApiClient = apiClient;
}
/// <summary>
/// Initializes a new instance of the <see cref="OrganizationsApi"/> class.
/// </summary>
/// <returns></returns>
public OrganizationsApi(String basePath)
{
this.ApiClient = new ApiClient(basePath);
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <param name="basePath">The base path</param>
/// <value>The base path</value>
public void SetBasePath(String basePath)
{
this.ApiClient.BasePath = basePath;
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.ApiClient.BasePath;
}
/// <summary>
/// Gets or sets the API client.
/// </summary>
/// <value>An instance of the ApiClient</value>
public ApiClient ApiClient {get; set;}
/// <summary>
/// Get user tokens for existing users, create new users Get user tokens for existing users, create new users
/// </summary>
/// <param name="organizationId">Organization ID</param>
/// <param name="body">Provides organization token and user ID</param>
/// <returns>UserTokenSuccessfulResponse</returns>
public UserTokenSuccessfulResponse V1OrganizationsOrganizationIdUsersPost (int? organizationId, UserTokenRequest body)
{
// verify the required parameter 'organizationId' is set
if (organizationId == null) throw new ApiException(400, "Missing required parameter 'organizationId' when calling V1OrganizationsOrganizationIdUsersPost");
// verify the required parameter 'body' is set
if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling V1OrganizationsOrganizationIdUsersPost");
var path = "/v1/organizations/{organizationId}/users";
var pathParams = new Dictionary<String, String>();
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
// to determine the Accept header
String[] http_header_accepts = new String[] {
"application/json"
};
String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts);
if (http_header_accept != null)
headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts));
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
pathParams.Add("format", "json");
if (organizationId != null) pathParams.Add("organizationId", ApiClient.ParameterToString(organizationId)); // path parameter
postBody = ApiClient.Serialize(body); // http body (model) parameter
// authentication setting, if any
String[] authSettings = new String[] { };
// make the HTTP request
IRestResponse response = (IRestResponse) ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings);
if (((int)response.StatusCode) >= 400)
throw new ApiException ((int)response.StatusCode, "Error calling V1OrganizationsOrganizationIdUsersPost: " + response.Content, response.Content);
else if (((int)response.StatusCode) == 0)
throw new ApiException ((int)response.StatusCode, "Error calling V1OrganizationsOrganizationIdUsersPost: " + response.ErrorMessage, response.ErrorMessage);
return (UserTokenSuccessfulResponse) ApiClient.Deserialize(response.Content, typeof(UserTokenSuccessfulResponse), response.Headers);
}
/// <summary>
/// Get user tokens for existing users, create new users Get user tokens for existing users, create new users
/// </summary>
/// <param name="organizationId">Organization ID</param>
/// <param name="body">Provides organization token and user ID</param>
/// <returns>UserTokenSuccessfulResponse</returns>
public async System.Threading.Tasks.Task<UserTokenSuccessfulResponse> V1OrganizationsOrganizationIdUsersPostAsync (int? organizationId, UserTokenRequest body)
{
// verify the required parameter 'organizationId' is set
if (organizationId == null) throw new ApiException(400, "Missing required parameter 'organizationId' when calling V1OrganizationsOrganizationIdUsersPost");
// verify the required parameter 'body' is set
if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling V1OrganizationsOrganizationIdUsersPost");
var path = "/v1/organizations/{organizationId}/users";
var pathParams = new Dictionary<String, String>();
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, FileParameter>();
String postBody = null;
// to determine the Accept header
String[] http_header_accepts = new String[] {
"application/json"
};
String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts);
if (http_header_accept != null)
headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts));
// set "format" to json by default
// e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
pathParams.Add("format", "json");
if (organizationId != null) pathParams.Add("organizationId", ApiClient.ParameterToString(organizationId)); // path parameter
postBody = ApiClient.Serialize(body); // http body (model) parameter
// authentication setting, if any
String[] authSettings = new String[] { };
// make the HTTP request
IRestResponse response = (IRestResponse) await ApiClient.CallApiAsync(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams, authSettings);
if (((int)response.StatusCode) >= 400)
throw new ApiException ((int)response.StatusCode, "Error calling V1OrganizationsOrganizationIdUsersPost: " + response.Content, response.Content);
return (UserTokenSuccessfulResponse) ApiClient.Deserialize(response.Content, typeof(UserTokenSuccessfulResponse), response.Headers);
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
//#if HAVE_ASYNC
using System;
using System.Globalization;
using System.Threading;
#if HAVE_BIG_INTEGER
using System.Numerics;
#endif
using System.Threading.Tasks;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json
{
public partial class JsonTextReader
{
// It's not safe to perform the async methods here in a derived class as if the synchronous equivalent
// has been overriden then the asychronous method will no longer be doing the same operation
#if HAVE_ASYNC // Double-check this isn't included inappropriately.
private readonly bool _safeAsync;
#endif
/// <summary>
/// Asynchronously reads the next JSON token from the source.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns <c>true</c> if the next token was read successfully; <c>false</c> if there are no more tokens to read.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<bool> ReadAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsync(cancellationToken) : base.ReadAsync(cancellationToken);
}
internal Task<bool> DoReadAsync(CancellationToken cancellationToken)
{
EnsureBuffer();
switch (_currentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
return ParseValueAsync(cancellationToken);
case State.Object:
case State.ObjectStart:
return ParseObjectAsync(cancellationToken);
case State.PostValue:
return LoopReadAsync(cancellationToken);
case State.Finished:
return ReadFromFinishedAsync(cancellationToken);
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
private async Task<bool> LoopReadAsync(CancellationToken cancellationToken)
{
while (_currentState == State.PostValue)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
_currentState = State.Finished;
}
}
else
{
_charPos++;
}
break;
case '}':
_charPos++;
SetToken(JsonToken.EndObject);
return true;
case ']':
_charPos++;
SetToken(JsonToken.EndArray);
return true;
case ')':
_charPos++;
SetToken(JsonToken.EndConstructor);
return true;
case '/':
await ParseCommentAsync(true, cancellationToken).ConfigureAwait(false);
return true;
case ',':
_charPos++;
// finished parsing
SetStateBasedOnCurrent();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
_charPos++;
}
else
{
throw JsonReaderException.Create(this, "After parsing a value an unexpected character was encountered: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
}
break;
}
}
return await DoReadAsync(cancellationToken).ConfigureAwait(false);
}
private async Task<bool> ReadFromFinishedAsync(CancellationToken cancellationToken)
{
if (await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false))
{
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
if (_isEndOfFile)
{
SetToken(JsonToken.None);
return false;
}
if (_chars[_charPos] == '/')
{
await ParseCommentAsync(true, cancellationToken).ConfigureAwait(false);
return true;
}
throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
SetToken(JsonToken.None);
return false;
}
private Task<int> ReadDataAsync(bool append, CancellationToken cancellationToken)
{
return ReadDataAsync(append, 0, cancellationToken);
}
private async Task<int> ReadDataAsync(bool append, int charsRequired, CancellationToken cancellationToken)
{
if (_isEndOfFile)
{
return 0;
}
PrepareBufferForReadData(append, charsRequired);
int charsRead = await _reader.ReadAsync(_chars, _charsUsed, _chars.Length - _charsUsed - 1, cancellationToken).ConfigureAwait(false);
_charsUsed += charsRead;
if (charsRead == 0)
{
_isEndOfFile = true;
}
_chars[_charsUsed] = '\0';
return charsRead;
}
private async Task<bool> ParseValueAsync(CancellationToken cancellationToken)
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
return false;
}
}
else
{
_charPos++;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, ReadType.Read, cancellationToken).ConfigureAwait(false);
return true;
case 't':
await ParseTrueAsync(cancellationToken).ConfigureAwait(false);
return true;
case 'f':
await ParseFalseAsync(cancellationToken).ConfigureAwait(false);
return true;
case 'n':
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false))
{
switch (_chars[_charPos + 1])
{
case 'u':
await ParseNullAsync(cancellationToken).ConfigureAwait(false);
break;
case 'e':
await ParseConstructorAsync(cancellationToken).ConfigureAwait(false);
break;
default:
throw CreateUnexpectedCharacterException(_chars[_charPos]);
}
}
else
{
_charPos++;
throw CreateUnexpectedEndException();
}
return true;
case 'N':
await ParseNumberNaNAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
return true;
case 'I':
await ParseNumberPositiveInfinityAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
return true;
case '-':
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos + 1] == 'I')
{
await ParseNumberNegativeInfinityAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
}
else
{
await ParseNumberAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
}
return true;
case '/':
await ParseCommentAsync(true, cancellationToken).ConfigureAwait(false);
return true;
case 'u':
await ParseUndefinedAsync(cancellationToken).ConfigureAwait(false);
return true;
case '{':
_charPos++;
SetToken(JsonToken.StartObject);
return true;
case '[':
_charPos++;
SetToken(JsonToken.StartArray);
return true;
case ']':
_charPos++;
SetToken(JsonToken.EndArray);
return true;
case ',':
// don't increment position, the next call to read will handle comma
// this is done to handle multiple empty comma values
SetToken(JsonToken.Undefined);
return true;
case ')':
_charPos++;
SetToken(JsonToken.EndConstructor);
return true;
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
_charPos++;
break;
}
if (char.IsNumber(currentChar) || currentChar == '-' || currentChar == '.')
{
ParseNumber(ReadType.Read);
return true;
}
throw CreateUnexpectedCharacterException(currentChar);
}
}
}
private async Task ReadStringIntoBufferAsync(char quote, CancellationToken cancellationToken)
{
int charPos = _charPos;
int initialPosition = _charPos;
int lastWritePosition = _charPos;
_stringBuffer.Position = 0;
while (true)
{
switch (_chars[charPos++])
{
case '\0':
if (_charsUsed == charPos - 1)
{
charPos--;
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
_charPos = charPos;
throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote));
}
}
break;
case '\\':
_charPos = charPos;
if (!await EnsureCharsAsync(0, true, cancellationToken).ConfigureAwait(false))
{
throw JsonReaderException.Create(this, "Unterminated string. Expected delimiter: {0}.".FormatWith(CultureInfo.InvariantCulture, quote));
}
// start of escape sequence
int escapeStartPos = charPos - 1;
char currentChar = _chars[charPos];
charPos++;
char writeChar;
switch (currentChar)
{
case 'b':
writeChar = '\b';
break;
case 't':
writeChar = '\t';
break;
case 'n':
writeChar = '\n';
break;
case 'f':
writeChar = '\f';
break;
case 'r':
writeChar = '\r';
break;
case '\\':
writeChar = '\\';
break;
case '"':
case '\'':
case '/':
writeChar = currentChar;
break;
case 'u':
_charPos = charPos;
writeChar = await ParseUnicodeAsync(cancellationToken).ConfigureAwait(false);
if (StringUtils.IsLowSurrogate(writeChar))
{
// low surrogate with no preceding high surrogate; this char is replaced
writeChar = UnicodeReplacementChar;
}
else if (StringUtils.IsHighSurrogate(writeChar))
{
bool anotherHighSurrogate;
// loop for handling situations where there are multiple consecutive high surrogates
do
{
anotherHighSurrogate = false;
// potential start of a surrogate pair
if (await EnsureCharsAsync(2, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos] == '\\' && _chars[_charPos + 1] == 'u')
{
char highSurrogate = writeChar;
_charPos += 2;
writeChar = await ParseUnicodeAsync(cancellationToken).ConfigureAwait(false);
if (StringUtils.IsLowSurrogate(writeChar))
{
// a valid surrogate pair!
}
else if (StringUtils.IsHighSurrogate(writeChar))
{
// another high surrogate; replace current and start check over
highSurrogate = UnicodeReplacementChar;
anotherHighSurrogate = true;
}
else
{
// high surrogate not followed by low surrogate; original char is replaced
highSurrogate = UnicodeReplacementChar;
}
EnsureBufferNotEmpty();
WriteCharToBuffer(highSurrogate, lastWritePosition, escapeStartPos);
lastWritePosition = _charPos;
}
else
{
// there are not enough remaining chars for the low surrogate or is not follow by unicode sequence
// replace high surrogate and continue on as usual
writeChar = UnicodeReplacementChar;
}
} while (anotherHighSurrogate);
}
charPos = _charPos;
break;
default:
_charPos = charPos;
throw JsonReaderException.Create(this, "Bad JSON escape sequence: {0}.".FormatWith(CultureInfo.InvariantCulture, @"\" + currentChar));
}
EnsureBufferNotEmpty();
WriteCharToBuffer(writeChar, lastWritePosition, escapeStartPos);
lastWritePosition = charPos;
break;
case StringUtils.CarriageReturn:
_charPos = charPos - 1;
await ProcessCarriageReturnAsync(true, cancellationToken).ConfigureAwait(false);
charPos = _charPos;
break;
case StringUtils.LineFeed:
_charPos = charPos - 1;
ProcessLineFeed();
charPos = _charPos;
break;
case '"':
case '\'':
if (_chars[charPos - 1] == quote)
{
FinishReadStringIntoBuffer(charPos - 1, initialPosition, lastWritePosition);
return;
}
break;
}
}
}
private Task ProcessCarriageReturnAsync(bool append, CancellationToken cancellationToken)
{
_charPos++;
Task<bool> task = EnsureCharsAsync(1, append, cancellationToken);
switch (task.Status)
{
case TaskStatus.RanToCompletion:
SetNewLine(task.Result);
return AsyncUtils.CompletedTask;
case TaskStatus.Canceled:
case TaskStatus.Faulted:
return task;
}
return ProcessCarriageReturnAsync(task);
}
private async Task ProcessCarriageReturnAsync(Task<bool> task)
{
SetNewLine(await task.ConfigureAwait(false));
}
private async Task<char> ParseUnicodeAsync(CancellationToken cancellationToken)
{
return ConvertUnicode(await EnsureCharsAsync(4, true, cancellationToken).ConfigureAwait(false));
}
private Task<bool> EnsureCharsAsync(int relativePosition, bool append, CancellationToken cancellationToken)
{
if (_charPos + relativePosition < _charsUsed)
{
return AsyncUtils.True;
}
if (_isEndOfFile)
{
return AsyncUtils.False;
}
return ReadCharsAsync(relativePosition, append, cancellationToken);
}
private async Task<bool> ReadCharsAsync(int relativePosition, bool append, CancellationToken cancellationToken)
{
int charsRequired = _charPos + relativePosition - _charsUsed + 1;
// it is possible that the TextReader doesn't return all data at once
// repeat read until the required text is returned or the reader is out of content
do
{
int charsRead = await ReadDataAsync(append, charsRequired, cancellationToken).ConfigureAwait(false);
// no more content
if (charsRead == 0)
{
return false;
}
charsRequired -= charsRead;
} while (charsRequired > 0);
return true;
}
private async Task<bool> ParseObjectAsync(CancellationToken cancellationToken)
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
return false;
}
}
else
{
_charPos++;
}
break;
case '}':
SetToken(JsonToken.EndObject);
_charPos++;
return true;
case '/':
await ParseCommentAsync(true, cancellationToken).ConfigureAwait(false);
return true;
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
if (char.IsWhiteSpace(currentChar))
{
// eat
_charPos++;
}
else
{
return await ParsePropertyAsync(cancellationToken).ConfigureAwait(false);
}
break;
}
}
}
private async Task ParseCommentAsync(bool setToken, CancellationToken cancellationToken)
{
// should have already parsed / character before reaching this method
_charPos++;
if (!await EnsureCharsAsync(1, false, cancellationToken).ConfigureAwait(false))
{
throw JsonReaderException.Create(this, "Unexpected end while parsing comment.");
}
bool singlelineComment;
if (_chars[_charPos] == '*')
{
singlelineComment = false;
}
else if (_chars[_charPos] == '/')
{
singlelineComment = true;
}
else
{
throw JsonReaderException.Create(this, "Error parsing comment. Expected: *, got {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
_charPos++;
int initialPosition = _charPos;
while (true)
{
switch (_chars[_charPos])
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
if (!singlelineComment)
{
throw JsonReaderException.Create(this, "Unexpected end while parsing comment.");
}
EndComment(setToken, initialPosition, _charPos);
return;
}
}
else
{
_charPos++;
}
break;
case '*':
_charPos++;
if (!singlelineComment)
{
if (await EnsureCharsAsync(0, true, cancellationToken).ConfigureAwait(false))
{
if (_chars[_charPos] == '/')
{
EndComment(setToken, initialPosition, _charPos - 1);
_charPos++;
return;
}
}
}
break;
case StringUtils.CarriageReturn:
if (singlelineComment)
{
EndComment(setToken, initialPosition, _charPos);
return;
}
await ProcessCarriageReturnAsync(true, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
if (singlelineComment)
{
EndComment(setToken, initialPosition, _charPos);
return;
}
ProcessLineFeed();
break;
default:
_charPos++;
break;
}
}
}
private async Task EatWhitespaceAsync(CancellationToken cancellationToken)
{
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
return;
}
}
else
{
_charPos++;
}
break;
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
default:
if (currentChar == ' ' || char.IsWhiteSpace(currentChar))
{
_charPos++;
}
else
{
return;
}
break;
}
}
}
private async Task ParseStringAsync(char quote, ReadType readType, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
_charPos++;
ShiftBufferIfNeeded();
await ReadStringIntoBufferAsync(quote, cancellationToken).ConfigureAwait(false);
ParseReadString(quote, readType);
}
private async Task<bool> MatchValueAsync(string value, CancellationToken cancellationToken)
{
return MatchValue(await EnsureCharsAsync(value.Length - 1, true, cancellationToken).ConfigureAwait(false), value);
}
private async Task<bool> MatchValueWithTrailingSeparatorAsync(string value, CancellationToken cancellationToken)
{
// will match value and then move to the next character, checking that it is a separator character
if (!await MatchValueAsync(value, cancellationToken).ConfigureAwait(false))
{
return false;
}
if (!await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false))
{
return true;
}
return IsSeparator(_chars[_charPos]) || _chars[_charPos] == '\0';
}
private async Task MatchAndSetAsync(string value, JsonToken newToken, object tokenValue, CancellationToken cancellationToken)
{
if (await MatchValueWithTrailingSeparatorAsync(value, cancellationToken).ConfigureAwait(false))
{
SetToken(newToken, tokenValue);
}
else
{
throw JsonReaderException.Create(this, "Error parsing " + newToken.ToString().ToLowerInvariant() + " value.");
}
}
private Task ParseTrueAsync(CancellationToken cancellationToken)
{
return MatchAndSetAsync(JsonConvert.True, JsonToken.Boolean, true, cancellationToken);
}
private Task ParseFalseAsync(CancellationToken cancellationToken)
{
return MatchAndSetAsync(JsonConvert.False, JsonToken.Boolean, false, cancellationToken);
}
private Task ParseNullAsync(CancellationToken cancellationToken)
{
return MatchAndSetAsync(JsonConvert.Null, JsonToken.Null, null, cancellationToken);
}
private async Task ParseConstructorAsync(CancellationToken cancellationToken)
{
if (await MatchValueWithTrailingSeparatorAsync("new", cancellationToken).ConfigureAwait(false))
{
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
int initialPosition = _charPos;
int endPosition;
while (true)
{
char currentChar = _chars[_charPos];
if (currentChar == '\0')
{
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
throw JsonReaderException.Create(this, "Unexpected end while parsing constructor.");
}
}
else
{
endPosition = _charPos;
_charPos++;
break;
}
}
else if (char.IsLetterOrDigit(currentChar))
{
_charPos++;
}
else if (currentChar == StringUtils.CarriageReturn)
{
endPosition = _charPos;
await ProcessCarriageReturnAsync(true, cancellationToken).ConfigureAwait(false);
break;
}
else if (currentChar == StringUtils.LineFeed)
{
endPosition = _charPos;
ProcessLineFeed();
break;
}
else if (char.IsWhiteSpace(currentChar))
{
endPosition = _charPos;
_charPos++;
break;
}
else if (currentChar == '(')
{
endPosition = _charPos;
break;
}
else
{
throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, currentChar));
}
}
_stringReference = new StringReference(_chars, initialPosition, endPosition - initialPosition);
string constructorName = _stringReference.ToString();
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
if (_chars[_charPos] != '(')
{
throw JsonReaderException.Create(this, "Unexpected character while parsing constructor: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
_charPos++;
ClearRecentString();
SetToken(JsonToken.StartConstructor, constructorName);
}
else
{
throw JsonReaderException.Create(this, "Unexpected content while parsing JSON.");
}
}
private async Task<object> ParseNumberNaNAsync(ReadType readType, CancellationToken cancellationToken)
{
return ParseNumberNaN(readType, await MatchValueWithTrailingSeparatorAsync(JsonConvert.NaN, cancellationToken).ConfigureAwait(false));
}
private async Task<object> ParseNumberPositiveInfinityAsync(ReadType readType, CancellationToken cancellationToken)
{
return ParseNumberPositiveInfinity(readType, await MatchValueWithTrailingSeparatorAsync(JsonConvert.PositiveInfinity, cancellationToken).ConfigureAwait(false));
}
private async Task<object> ParseNumberNegativeInfinityAsync(ReadType readType, CancellationToken cancellationToken)
{
return ParseNumberNegativeInfinity(readType, await MatchValueWithTrailingSeparatorAsync(JsonConvert.NegativeInfinity, cancellationToken).ConfigureAwait(false));
}
private async Task ParseNumberAsync(ReadType readType, CancellationToken cancellationToken)
{
ShiftBufferIfNeeded();
char firstChar = _chars[_charPos];
int initialPosition = _charPos;
await ReadNumberIntoBufferAsync(cancellationToken).ConfigureAwait(false);
ParseReadNumber(readType, firstChar, initialPosition);
}
private Task ParseUndefinedAsync(CancellationToken cancellationToken)
{
return MatchAndSetAsync(JsonConvert.Undefined, JsonToken.Undefined, null, cancellationToken);
}
private async Task<bool> ParsePropertyAsync(CancellationToken cancellationToken)
{
char firstChar = _chars[_charPos];
char quoteChar;
if (firstChar == '"' || firstChar == '\'')
{
_charPos++;
quoteChar = firstChar;
ShiftBufferIfNeeded();
await ReadStringIntoBufferAsync(quoteChar, cancellationToken).ConfigureAwait(false);
}
else if (ValidIdentifierChar(firstChar))
{
quoteChar = '\0';
ShiftBufferIfNeeded();
await ParseUnquotedPropertyAsync(cancellationToken).ConfigureAwait(false);
}
else
{
throw JsonReaderException.Create(this, "Invalid property identifier character: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
string propertyName;
if (NameTable != null)
{
propertyName = NameTable.Get(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length)
// no match in name table
?? _stringReference.ToString();
}
else
{
propertyName = _stringReference.ToString();
}
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
if (_chars[_charPos] != ':')
{
throw JsonReaderException.Create(this, "Invalid character after parsing property name. Expected ':' but got: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
_charPos++;
SetToken(JsonToken.PropertyName, propertyName);
_quoteChar = quoteChar;
ClearRecentString();
return true;
}
private async Task ReadNumberIntoBufferAsync(CancellationToken cancellationToken)
{
int charPos = _charPos;
while (true)
{
char currentChar = _chars[charPos];
if (currentChar == '\0')
{
_charPos = charPos;
if (_charsUsed == charPos)
{
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
return;
}
}
else
{
return;
}
}
else if (ReadNumberCharIntoBuffer(currentChar, charPos))
{
return;
}
else
{
charPos++;
}
}
}
private async Task ParseUnquotedPropertyAsync(CancellationToken cancellationToken)
{
int initialPosition = _charPos;
// parse unquoted property name until whitespace or colon
while (true)
{
char currentChar = _chars[_charPos];
if (currentChar == '\0')
{
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(true, cancellationToken).ConfigureAwait(false) == 0)
{
throw JsonReaderException.Create(this, "Unexpected end while parsing unquoted property name.");
}
continue;
}
_stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);
return;
}
if (ReadUnquotedPropertyReportIfDone(currentChar, initialPosition))
{
return;
}
}
}
private async Task<bool> ReadNullCharAsync(CancellationToken cancellationToken)
{
if (_charsUsed == _charPos)
{
if (await ReadDataAsync(false, cancellationToken).ConfigureAwait(false) == 0)
{
_isEndOfFile = true;
return true;
}
}
else
{
_charPos++;
}
return false;
}
private async Task HandleNullAsync(CancellationToken cancellationToken)
{
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false))
{
if (_chars[_charPos + 1] == 'u')
{
await ParseNullAsync(cancellationToken).ConfigureAwait(false);
return;
}
_charPos += 2;
throw CreateUnexpectedCharacterException(_chars[_charPos - 1]);
}
_charPos = _charsUsed;
throw CreateUnexpectedEndException();
}
private async Task ReadFinishedAsync(CancellationToken cancellationToken)
{
if (await EnsureCharsAsync(0, false, cancellationToken).ConfigureAwait(false))
{
await EatWhitespaceAsync(cancellationToken).ConfigureAwait(false);
if (_isEndOfFile)
{
SetToken(JsonToken.None);
return;
}
if (_chars[_charPos] == '/')
{
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
}
else
{
throw JsonReaderException.Create(this, "Additional text encountered after finished reading JSON content: {0}.".FormatWith(CultureInfo.InvariantCulture, _chars[_charPos]));
}
}
SetToken(JsonToken.None);
}
private async Task<object> ReadStringValueAsync(ReadType readType, CancellationToken cancellationToken)
{
EnsureBuffer();
switch (_currentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
case State.PostValue:
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false))
{
SetToken(JsonToken.None, null, false);
return null;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, readType, cancellationToken).ConfigureAwait(false);
return FinishReadQuotedStringValue(readType);
case '-':
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos + 1] == 'I')
{
return ParseNumberNegativeInfinity(readType);
}
else
{
await ParseNumberAsync(readType, cancellationToken).ConfigureAwait(false);
return Value;
}
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
if (readType != ReadType.ReadAsString)
{
_charPos++;
throw CreateUnexpectedCharacterException(currentChar);
}
await ParseNumberAsync(ReadType.ReadAsString, cancellationToken).ConfigureAwait(false);
return Value;
case 't':
case 'f':
if (readType != ReadType.ReadAsString)
{
_charPos++;
throw CreateUnexpectedCharacterException(currentChar);
}
string expected = currentChar == 't' ? JsonConvert.True : JsonConvert.False;
if (!await MatchValueWithTrailingSeparatorAsync(expected, cancellationToken).ConfigureAwait(false))
{
throw CreateUnexpectedCharacterException(_chars[_charPos]);
}
SetToken(JsonToken.String, expected);
return expected;
case 'I':
return await ParseNumberPositiveInfinityAsync(readType, cancellationToken).ConfigureAwait(false);
case 'N':
return await ParseNumberNaNAsync(readType, cancellationToken).ConfigureAwait(false);
case 'n':
await HandleNullAsync(cancellationToken).ConfigureAwait(false);
return null;
case '/':
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
break;
case ',':
ProcessValueComma();
break;
case ']':
_charPos++;
if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue)
{
SetToken(JsonToken.EndArray);
return null;
}
throw CreateUnexpectedCharacterException(currentChar);
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
_charPos++;
if (!char.IsWhiteSpace(currentChar))
{
throw CreateUnexpectedCharacterException(currentChar);
}
// eat
break;
}
}
case State.Finished:
await ReadFinishedAsync(cancellationToken).ConfigureAwait(false);
return null;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
private async Task<object> ReadNumberValueAsync(ReadType readType, CancellationToken cancellationToken)
{
EnsureBuffer();
switch (_currentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
case State.PostValue:
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false))
{
SetToken(JsonToken.None, null, false);
return null;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, readType, cancellationToken).ConfigureAwait(false);
return FinishReadQuotedNumber(readType);
case 'n':
await HandleNullAsync(cancellationToken).ConfigureAwait(false);
return null;
case 'N':
return await ParseNumberNaNAsync(readType, cancellationToken).ConfigureAwait(false);
case 'I':
return await ParseNumberPositiveInfinityAsync(readType, cancellationToken).ConfigureAwait(false);
case '-':
if (await EnsureCharsAsync(1, true, cancellationToken).ConfigureAwait(false) && _chars[_charPos + 1] == 'I')
{
return await ParseNumberNegativeInfinityAsync(readType, cancellationToken).ConfigureAwait(false);
}
else
{
await ParseNumberAsync(readType, cancellationToken).ConfigureAwait(false);
return Value;
}
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
await ParseNumberAsync(readType, cancellationToken).ConfigureAwait(false);
return Value;
case '/':
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
break;
case ',':
ProcessValueComma();
break;
case ']':
_charPos++;
if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue)
{
SetToken(JsonToken.EndArray);
return null;
}
throw CreateUnexpectedCharacterException(currentChar);
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
_charPos++;
if (!char.IsWhiteSpace(currentChar))
{
throw CreateUnexpectedCharacterException(currentChar);
}
// eat
break;
}
}
case State.Finished:
await ReadFinishedAsync(cancellationToken).ConfigureAwait(false);
return null;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="bool"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="bool"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<bool?> ReadAsBooleanAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsBooleanAsync(cancellationToken) : base.ReadAsBooleanAsync(cancellationToken);
}
internal async Task<bool?> DoReadAsBooleanAsync(CancellationToken cancellationToken)
{
EnsureBuffer();
switch (_currentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
case State.PostValue:
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false))
{
SetToken(JsonToken.None, null, false);
return null;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, ReadType.Read, cancellationToken).ConfigureAwait(false);
return ReadBooleanString(_stringReference.ToString());
case 'n':
await HandleNullAsync(cancellationToken).ConfigureAwait(false);
return null;
case '-':
case '.':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
await ParseNumberAsync(ReadType.Read, cancellationToken).ConfigureAwait(false);
bool b;
#if HAVE_BIG_INTEGER
if (Value is BigInteger)
{
b = (BigInteger)Value != 0;
}
else
#endif
{
b = Convert.ToBoolean(Value, CultureInfo.InvariantCulture);
}
SetToken(JsonToken.Boolean, b, false);
return b;
case 't':
case 'f':
bool isTrue = currentChar == 't';
if (!await MatchValueWithTrailingSeparatorAsync(isTrue ? JsonConvert.True : JsonConvert.False, cancellationToken).ConfigureAwait(false))
{
throw CreateUnexpectedCharacterException(_chars[_charPos]);
}
SetToken(JsonToken.Boolean, isTrue);
return isTrue;
case '/':
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
break;
case ',':
ProcessValueComma();
break;
case ']':
_charPos++;
if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue)
{
SetToken(JsonToken.EndArray);
return null;
}
throw CreateUnexpectedCharacterException(currentChar);
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
_charPos++;
if (!char.IsWhiteSpace(currentChar))
{
throw CreateUnexpectedCharacterException(currentChar);
}
// eat
break;
}
}
case State.Finished:
await ReadFinishedAsync(cancellationToken).ConfigureAwait(false);
return null;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="byte"/>[].
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="byte"/>[]. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<byte[]> ReadAsBytesAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsBytesAsync(cancellationToken) : base.ReadAsBytesAsync(cancellationToken);
}
internal async Task<byte[]> DoReadAsBytesAsync(CancellationToken cancellationToken)
{
EnsureBuffer();
bool isWrapped = false;
switch (_currentState)
{
case State.Start:
case State.Property:
case State.Array:
case State.ArrayStart:
case State.Constructor:
case State.ConstructorStart:
case State.PostValue:
while (true)
{
char currentChar = _chars[_charPos];
switch (currentChar)
{
case '\0':
if (await ReadNullCharAsync(cancellationToken).ConfigureAwait(false))
{
SetToken(JsonToken.None, null, false);
return null;
}
break;
case '"':
case '\'':
await ParseStringAsync(currentChar, ReadType.ReadAsBytes, cancellationToken).ConfigureAwait(false);
byte[] data = (byte[])Value;
if (isWrapped)
{
await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false);
if (TokenType != JsonToken.EndObject)
{
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
SetToken(JsonToken.Bytes, data, false);
}
return data;
case '{':
_charPos++;
SetToken(JsonToken.StartObject);
await ReadIntoWrappedTypeObjectAsync(cancellationToken).ConfigureAwait(false);
isWrapped = true;
break;
case '[':
_charPos++;
SetToken(JsonToken.StartArray);
return await ReadArrayIntoByteArrayAsync(cancellationToken).ConfigureAwait(false);
case 'n':
await HandleNullAsync(cancellationToken).ConfigureAwait(false);
return null;
case '/':
await ParseCommentAsync(false, cancellationToken).ConfigureAwait(false);
break;
case ',':
ProcessValueComma();
break;
case ']':
_charPos++;
if (_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.PostValue)
{
SetToken(JsonToken.EndArray);
return null;
}
throw CreateUnexpectedCharacterException(currentChar);
case StringUtils.CarriageReturn:
await ProcessCarriageReturnAsync(false, cancellationToken).ConfigureAwait(false);
break;
case StringUtils.LineFeed:
ProcessLineFeed();
break;
case ' ':
case StringUtils.Tab:
// eat
_charPos++;
break;
default:
_charPos++;
if (!char.IsWhiteSpace(currentChar))
{
throw CreateUnexpectedCharacterException(currentChar);
}
// eat
break;
}
}
case State.Finished:
await ReadFinishedAsync(cancellationToken).ConfigureAwait(false);
return null;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}.".FormatWith(CultureInfo.InvariantCulture, CurrentState));
}
}
private async Task ReadIntoWrappedTypeObjectAsync(CancellationToken cancellationToken)
{
await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false);
if (Value != null && Value.ToString() == JsonTypeReflector.TypePropertyName)
{
await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false);
if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal))
{
await ReaderReadAndAssertAsync(cancellationToken).ConfigureAwait(false);
if (Value.ToString() == JsonTypeReflector.ValuePropertyName)
{
return;
}
}
}
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject));
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="DateTime"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="DateTime"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<DateTime?> ReadAsDateTimeAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsDateTimeAsync(cancellationToken) : base.ReadAsDateTimeAsync(cancellationToken);
}
internal async Task<DateTime?> DoReadAsDateTimeAsync(CancellationToken cancellationToken)
{
return (DateTime?)await ReadStringValueAsync(ReadType.ReadAsDateTime, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<DateTimeOffset?> ReadAsDateTimeOffsetAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsDateTimeOffsetAsync(cancellationToken) : base.ReadAsDateTimeOffsetAsync(cancellationToken);
}
internal async Task<DateTimeOffset?> DoReadAsDateTimeOffsetAsync(CancellationToken cancellationToken)
{
return (DateTimeOffset?)await ReadStringValueAsync(ReadType.ReadAsDateTimeOffset, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="decimal"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="decimal"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<decimal?> ReadAsDecimalAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsDecimalAsync(cancellationToken) : base.ReadAsDecimalAsync(cancellationToken);
}
internal async Task<decimal?> DoReadAsDecimalAsync(CancellationToken cancellationToken)
{
return (decimal?)await ReadNumberValueAsync(ReadType.ReadAsDecimal, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="double"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="double"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<double?> ReadAsDoubleAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsDoubleAsync(cancellationToken) : base.ReadAsDoubleAsync(cancellationToken);
}
internal async Task<double?> DoReadAsDoubleAsync(CancellationToken cancellationToken)
{
return (double?)await ReadNumberValueAsync(ReadType.ReadAsDouble, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="int"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="int"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<int?> ReadAsInt32Async(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsInt32Async(cancellationToken) : base.ReadAsInt32Async(cancellationToken);
}
internal async Task<int?> DoReadAsInt32Async(CancellationToken cancellationToken)
{
return (int?)await ReadNumberValueAsync(ReadType.ReadAsInt32, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="string"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="string"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>Derived classes must override this method to get asynchronous behaviour. Otherwise it will
/// execute synchronously, returning an already-completed task.</remarks>
public override Task<string> ReadAsStringAsync(CancellationToken cancellationToken = default(CancellationToken))
{
return _safeAsync ? DoReadAsStringAsync(cancellationToken) : base.ReadAsStringAsync(cancellationToken);
}
internal async Task<string> DoReadAsStringAsync(CancellationToken cancellationToken)
{
return (string)await ReadStringValueAsync(ReadType.ReadAsString, cancellationToken).ConfigureAwait(false);
}
}
}
//#endif
| |
/*
* WebSocketServiceManager.cs
*
* The MIT License
*
* Copyright (c) 2012-2014 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace WebSocketSharp.Server
{
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebSocketSharp.Net;
/// <summary>
/// Manages the WebSocket services provided by the <see cref="WebSocketServer"/> or
/// <see cref="WebSocketServer"/>.
/// </summary>
public class WebSocketServiceManager
{
private readonly int _fragmentSize;
private volatile bool _clean;
private readonly ConcurrentDictionary<string, WebSocketServiceHost> _hosts;
private volatile ServerState _state;
private TimeSpan _waitTime;
internal WebSocketServiceManager(int fragmentSize, bool keepClean = true)
{
_fragmentSize = fragmentSize;
_clean = keepClean;
_hosts = new ConcurrentDictionary<string, WebSocketServiceHost>();
_state = ServerState.Ready;
_waitTime = TimeSpan.FromSeconds(1);
}
/// <summary>
/// Gets the number of the WebSocket services.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents the number of the services.
/// </value>
public int Count => _hosts.Count;
/// <summary>
/// Gets the host instances for the Websocket services.
/// </summary>
/// <value>
/// An <c>IEnumerable<WebSocketServiceHost></c> instance that provides an enumerator
/// which supports the iteration over the collection of the host instances for the services.
/// </value>
public IEnumerable<WebSocketServiceHost> Hosts => _hosts.Values.ToArray();
/// <summary>
/// Gets the WebSocket service host with the specified <paramref name="path"/>.
/// </summary>
/// <value>
/// A <see cref="WebSocketServiceHost"/> instance that provides the access to
/// the information in the service, or <see langword="null"/> if it's not found.
/// </value>
/// <param name="path">
/// A <see cref="string"/> that represents the absolute path to the service to find.
/// </param>
public WebSocketServiceHost this[string path]
{
get
{
WebSocketServiceHost host;
TryGetServiceHost(path, out host);
return host;
}
}
/// <summary>
/// Gets the paths for the WebSocket services.
/// </summary>
/// <value>
/// An <c>IEnumerable<string></c> instance that provides an enumerator which supports
/// the iteration over the collection of the paths for the services.
/// </value>
public IEnumerable<string> Paths => _hosts.Keys.ToArray();
/// <summary>
/// Gets the total number of the sessions in the WebSocket services.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents the total number of the sessions in the services.
/// </value>
public int SessionCount
{
get
{
return Hosts.TakeWhile(host => _state == ServerState.Start).Sum(host => host.Sessions.Count);
}
}
/// <summary>
/// Gets the wait time for the response to the WebSocket Ping or Close.
/// </summary>
/// <value>
/// A <see cref="TimeSpan"/> that represents the wait time.
/// </value>
public TimeSpan WaitTime
{
get
{
return _waitTime;
}
internal set
{
if (value == _waitTime)
{
return;
}
_waitTime = value;
foreach (var host in _hosts.Values.ToArray())
{
host.WaitTime = value;
}
}
}
/// <summary>
/// Broadcasts a binary <paramref name="data"/> to every client in the WebSocket services.
/// </summary>
/// <param name="data">
/// An array of <see cref="byte"/> that represents the binary data to broadcast.
/// </param>
public Task<bool> Broadcast(byte[] data)
{
var msg = _state.CheckIfStart() ?? data.CheckIfValidSendData();
if (msg != null)
{
return Task.FromResult(false);
}
return data.LongLength <= _fragmentSize
? InnerBroadcast(Opcode.Binary, data)
: InnerBroadcast(Opcode.Binary, new MemoryStream(data));
}
/// <summary>
/// Broadcasts a text <paramref name="data"/> to every client in the WebSocket services.
/// </summary>
/// <param name="data">
/// A <see cref="string"/> that represents the text data to broadcast.
/// </param>
public Task<bool> Broadcast(string data)
{
var msg = _state.CheckIfStart() ?? data.CheckIfValidSendData();
if (msg != null)
{
return Task.FromResult(false);
}
var rawData = Encoding.UTF8.GetBytes(data);
return rawData.LongLength <= _fragmentSize
? InnerBroadcast(Opcode.Text, rawData)
: InnerBroadcast(Opcode.Text, new MemoryStream(rawData));
}
/// <summary>
/// Broadcasts a text <paramref name="data"/> to every client in the WebSocket services.
/// </summary>
/// <param name="data">
/// A <see cref="string"/> that represents the text data to broadcast.
/// </param>
public Task<bool> Broadcast(Stream data)
{
var msg = _state.CheckIfStart() ?? data.CheckIfValidSendData();
return msg != null ? Task.FromResult(false) : InnerBroadcast(Opcode.Binary, data);
}
/// <summary>
/// Sends a Ping to every client in the WebSocket services.
/// </summary>
/// <returns>
/// A <c>Dictionary<string, Dictionary<string, bool>></c> that contains
/// a collection of pairs of a service path and a collection of pairs of a session ID
/// and a value indicating whether the manager received a Pong from each client in a time,
/// or <see langword="null"/> if this method isn't available.
/// </returns>
public Task<IDictionary<string, IDictionary<string, bool>>> Broadping()
{
var msg = _state.CheckIfStart();
if (msg != null)
{
return Task.FromResult<IDictionary<string, IDictionary<string, bool>>>(new Dictionary<string, IDictionary<string, bool>>());
}
return Broadping(WebSocketFrame.EmptyUnmaskPingBytes, _waitTime);
}
/// <summary>
/// Sends a Ping with the specified <paramref name="message"/> to every client
/// in the WebSocket services.
/// </summary>
/// <returns>
/// A <c>Dictionary<string, Dictionary<string, bool>></c> that contains
/// a collection of pairs of a service path and a collection of pairs of a session ID
/// and a value indicating whether the manager received a Pong from each client in a time,
/// or <see langword="null"/> if this method isn't available or <paramref name="message"/>
/// is invalid.
/// </returns>
/// <param name="message">
/// A <see cref="string"/> that represents the message to send.
/// </param>
public async Task<IDictionary<string, IDictionary<string, bool>>> Broadping(string message)
{
if (string.IsNullOrEmpty(message))
{
return await Broadping().ConfigureAwait(false);
}
byte[] data = null;
var msg = _state.CheckIfStart() ??
(data = Encoding.UTF8.GetBytes(message)).CheckIfValidControlData("message");
return msg != null
? new Dictionary<string, IDictionary<string, bool>>()
: await Broadping(await WebSocketFrame.CreatePingFrame(data, false).ToByteArray().ConfigureAwait(false), _waitTime).ConfigureAwait(false);
}
/// <summary>
/// Tries to get the WebSocket service host with the specified <paramref name="path"/>.
/// </summary>
/// <returns>
/// <c>true</c> if the service is successfully found; otherwise, <c>false</c>.
/// </returns>
/// <param name="path">
/// A <see cref="string"/> that represents the absolute path to the service to find.
/// </param>
/// <param name="host">
/// When this method returns, a <see cref="WebSocketServiceHost"/> instance that provides
/// the access to the information in the service, or <see langword="null"/> if it's not found.
/// This parameter is passed uninitialized.
/// </param>
private bool TryGetServiceHost(string path, out WebSocketServiceHost host)
{
var msg = _state.CheckIfStart() ?? path.CheckIfValidServicePath();
if (msg != null)
{
host = null;
return false;
}
return InternalTryGetServiceHost(path, out host);
}
internal void Add<TBehavior>(string path, Func<TBehavior> initializer)
where TBehavior : WebSocketBehavior
{
path = HttpUtility.UrlDecode(path).TrimEndSlash();
WebSocketServiceHost host;
if (_hosts.TryGetValue(path, out host))
{
return;
}
host = new WebSocketServiceHost<TBehavior>(path, _fragmentSize, initializer);
if (!_clean)
{
host.KeepClean = false;
}
host.WaitTime = _waitTime;
if (_state == ServerState.Start)
{
host.Start();
}
if (!_hosts.TryAdd(path, host))
{
throw new Exception("Failed to add host");
}
}
internal bool InternalTryGetServiceHost(string path, out WebSocketServiceHost host)
{
path = HttpUtility.UrlDecode(path).TrimEndSlash();
return _hosts.TryGetValue(path, out host);
}
internal async Task<bool> Remove(string path)
{
WebSocketServiceHost host;
path = HttpUtility.UrlDecode(path).TrimEndSlash();
if (!_hosts.TryRemove(path, out host))
{
return false;
}
if (host.State == ServerState.Start)
{
await host.Stop((ushort)CloseStatusCode.Away, null).ConfigureAwait(false);
}
return true;
}
internal void Start()
{
foreach (var host in _hosts.Values.ToArray())
{
host.Start();
}
_state = ServerState.Start;
}
internal async Task Stop(CloseEventArgs e, bool send, bool wait)
{
_state = ServerState.ShuttingDown;
var bytes =
send ? await WebSocketFrame.CreateCloseFrame(e.PayloadData, false).ToByteArray().ConfigureAwait(false) : null;
var timeout = wait ? _waitTime : TimeSpan.Zero;
var tasks = _hosts.Values.ToArray().Select(host => host.Sessions.Stop(e, bytes, timeout));
await Task.WhenAll(tasks).ConfigureAwait(false);
_hosts.Clear();
_state = ServerState.Stop;
}
private async Task<bool> InnerBroadcast(Opcode opcode, byte[] data)
{
var results =
Hosts
.TakeWhile(host => _state == ServerState.Start)
.AsParallel()
.Select(host => host.Sessions.InnerBroadcast(opcode, data))
.ToArray();
await Task.WhenAll(results).ConfigureAwait(false);
return results.All(x => x.Result);
}
private async Task<bool> InnerBroadcast(Opcode opcode, Stream stream)
{
var tasks =
Hosts.TakeWhile(host => _state == ServerState.Start)
.AsParallel()
.Select(host => host.Sessions.InnerBroadcast(opcode, stream))
.ToArray();
await Task.WhenAll(tasks).ConfigureAwait(false);
return tasks.All(x => x.Result);
}
private async Task<IDictionary<string, IDictionary<string, bool>>> Broadping(byte[] frameAsBytes, TimeSpan timeout)
{
var tasks = Hosts.TakeWhile(host => _state == ServerState.Start)
.ToDictionary(host => host.Path, host => host.Sessions.InnerBroadping(frameAsBytes, timeout));
await Task.WhenAll(tasks.Values).ConfigureAwait(false);
return tasks.ToDictionary(x => x.Key, x => x.Value.Result);
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using Microsoft.Scripting;
namespace IronPython.Compiler {
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dedent")]
public enum TokenKind {
EndOfFile = -1,
Error = 0,
NewLine = 1,
Indent = 2,
Dedent = 3,
Comment = 4,
Name = 8,
Constant = 9,
Dot = 31,
#region Generated Token Kinds
// *** BEGIN GENERATED CODE ***
// generated by function: tokenkinds_generator from: generate_ops.py
Add = 32,
AddEqual = 33,
Subtract = 34,
SubtractEqual = 35,
Power = 36,
PowerEqual = 37,
Multiply = 38,
MultiplyEqual = 39,
FloorDivide = 40,
FloorDivideEqual = 41,
TrueDivide = 42,
TrueDivideEqual = 43,
Mod = 44,
ModEqual = 45,
LeftShift = 46,
LeftShiftEqual = 47,
RightShift = 48,
RightShiftEqual = 49,
BitwiseAnd = 50,
BitwiseAndEqual = 51,
BitwiseOr = 52,
BitwiseOrEqual = 53,
ExclusiveOr = 54,
ExclusiveOrEqual = 55,
LessThan = 56,
GreaterThan = 57,
LessThanOrEqual = 58,
GreaterThanOrEqual = 59,
Equals = 60,
NotEquals = 61,
LeftParenthesis = 62,
RightParenthesis = 63,
LeftBracket = 64,
RightBracket = 65,
LeftBrace = 66,
RightBrace = 67,
Comma = 68,
Colon = 69,
Semicolon = 70,
Assign = 71,
Twiddle = 72,
At = 73,
RightArrow = 74,
FirstKeyword = KeywordAnd,
LastKeyword = KeywordNonlocal,
KeywordAnd = 75,
KeywordAssert = 76,
KeywordBreak = 77,
KeywordClass = 78,
KeywordContinue = 79,
KeywordDef = 80,
KeywordDel = 81,
KeywordElseIf = 82,
KeywordElse = 83,
KeywordExcept = 84,
KeywordFinally = 85,
KeywordFor = 86,
KeywordFrom = 87,
KeywordGlobal = 88,
KeywordIf = 89,
KeywordImport = 90,
KeywordIn = 91,
KeywordIs = 92,
KeywordLambda = 93,
KeywordNot = 94,
KeywordOr = 95,
KeywordPass = 96,
KeywordRaise = 97,
KeywordReturn = 98,
KeywordTry = 99,
KeywordWhile = 100,
KeywordYield = 101,
KeywordAs = 102,
KeywordWith = 103,
KeywordAsync = 104,
KeywordNonlocal = 105,
// *** END GENERATED CODE ***
#endregion
NLToken,
}
public static class Tokens {
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly Token EndOfFileToken = new SymbolToken(TokenKind.EndOfFile, "<eof>");
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly Token NewLineToken = new SymbolToken(TokenKind.NewLine, "<newline>");
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly Token NLToken = new SymbolToken(TokenKind.NLToken, "<NL>"); // virtual token used for error reporting
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly Token IndentToken = new SymbolToken(TokenKind.Indent, "<indent>");
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dedent")]
public static readonly Token DedentToken = new SymbolToken(TokenKind.Dedent, "<dedent>");
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly Token CommentToken = new SymbolToken(TokenKind.Comment, "<comment>");
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly Token NoneToken = new ConstantValueToken(null);
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")]
public static readonly Token DotToken = new SymbolToken(TokenKind.Dot, ".");
#region Generated Tokens
// *** BEGIN GENERATED CODE ***
// generated by function: tokens_generator from: generate_ops.py
private static readonly Token symAddToken = new OperatorToken(TokenKind.Add, "+", 4);
private static readonly Token symAddEqualToken = new SymbolToken(TokenKind.AddEqual, "+=");
private static readonly Token symSubtractToken = new OperatorToken(TokenKind.Subtract, "-", 4);
private static readonly Token symSubtractEqualToken = new SymbolToken(TokenKind.SubtractEqual, "-=");
private static readonly Token symPowerToken = new OperatorToken(TokenKind.Power, "**", 6);
private static readonly Token symPowerEqualToken = new SymbolToken(TokenKind.PowerEqual, "**=");
private static readonly Token symMultiplyToken = new OperatorToken(TokenKind.Multiply, "*", 5);
private static readonly Token symMultiplyEqualToken = new SymbolToken(TokenKind.MultiplyEqual, "*=");
private static readonly Token symFloorDivideToken = new OperatorToken(TokenKind.FloorDivide, "//", 5);
private static readonly Token symFloorDivideEqualToken = new SymbolToken(TokenKind.FloorDivideEqual, "//=");
private static readonly Token symTrueDivideToken = new OperatorToken(TokenKind.TrueDivide, "/", 5);
private static readonly Token symTrueDivideEqualToken = new SymbolToken(TokenKind.TrueDivideEqual, "/=");
private static readonly Token symModToken = new OperatorToken(TokenKind.Mod, "%", 5);
private static readonly Token symModEqualToken = new SymbolToken(TokenKind.ModEqual, "%=");
private static readonly Token symLeftShiftToken = new OperatorToken(TokenKind.LeftShift, "<<", 3);
private static readonly Token symLeftShiftEqualToken = new SymbolToken(TokenKind.LeftShiftEqual, "<<=");
private static readonly Token symRightShiftToken = new OperatorToken(TokenKind.RightShift, ">>", 3);
private static readonly Token symRightShiftEqualToken = new SymbolToken(TokenKind.RightShiftEqual, ">>=");
private static readonly Token symBitwiseAndToken = new OperatorToken(TokenKind.BitwiseAnd, "&", 2);
private static readonly Token symBitwiseAndEqualToken = new SymbolToken(TokenKind.BitwiseAndEqual, "&=");
private static readonly Token symBitwiseOrToken = new OperatorToken(TokenKind.BitwiseOr, "|", 0);
private static readonly Token symBitwiseOrEqualToken = new SymbolToken(TokenKind.BitwiseOrEqual, "|=");
private static readonly Token symExclusiveOrToken = new OperatorToken(TokenKind.ExclusiveOr, "^", 1);
private static readonly Token symExclusiveOrEqualToken = new SymbolToken(TokenKind.ExclusiveOrEqual, "^=");
private static readonly Token symLessThanToken = new OperatorToken(TokenKind.LessThan, "<", -1);
private static readonly Token symGreaterThanToken = new OperatorToken(TokenKind.GreaterThan, ">", -1);
private static readonly Token symLessThanOrEqualToken = new OperatorToken(TokenKind.LessThanOrEqual, "<=", -1);
private static readonly Token symGreaterThanOrEqualToken = new OperatorToken(TokenKind.GreaterThanOrEqual, ">=", -1);
private static readonly Token symEqualsToken = new OperatorToken(TokenKind.Equals, "==", -1);
private static readonly Token symNotEqualsToken = new OperatorToken(TokenKind.NotEquals, "!=", -1);
private static readonly Token symLeftParenthesisToken = new SymbolToken(TokenKind.LeftParenthesis, "(");
private static readonly Token symRightParenthesisToken = new SymbolToken(TokenKind.RightParenthesis, ")");
private static readonly Token symLeftBracketToken = new SymbolToken(TokenKind.LeftBracket, "[");
private static readonly Token symRightBracketToken = new SymbolToken(TokenKind.RightBracket, "]");
private static readonly Token symLeftBraceToken = new SymbolToken(TokenKind.LeftBrace, "{");
private static readonly Token symRightBraceToken = new SymbolToken(TokenKind.RightBrace, "}");
private static readonly Token symCommaToken = new SymbolToken(TokenKind.Comma, ",");
private static readonly Token symColonToken = new SymbolToken(TokenKind.Colon, ":");
private static readonly Token symSemicolonToken = new SymbolToken(TokenKind.Semicolon, ";");
private static readonly Token symAssignToken = new SymbolToken(TokenKind.Assign, "=");
private static readonly Token symTwiddleToken = new SymbolToken(TokenKind.Twiddle, "~");
private static readonly Token symAtToken = new SymbolToken(TokenKind.At, "@");
private static readonly Token symRightArrowToken = new SymbolToken(TokenKind.RightArrow, "=>");
public static Token AddToken {
get { return symAddToken; }
}
public static Token AddEqualToken {
get { return symAddEqualToken; }
}
public static Token SubtractToken {
get { return symSubtractToken; }
}
public static Token SubtractEqualToken {
get { return symSubtractEqualToken; }
}
public static Token PowerToken {
get { return symPowerToken; }
}
public static Token PowerEqualToken {
get { return symPowerEqualToken; }
}
public static Token MultiplyToken {
get { return symMultiplyToken; }
}
public static Token MultiplyEqualToken {
get { return symMultiplyEqualToken; }
}
public static Token FloorDivideToken {
get { return symFloorDivideToken; }
}
public static Token FloorDivideEqualToken {
get { return symFloorDivideEqualToken; }
}
public static Token TrueDivideToken {
get { return symTrueDivideToken; }
}
public static Token TrueDivideEqualToken {
get { return symTrueDivideEqualToken; }
}
public static Token ModToken {
get { return symModToken; }
}
public static Token ModEqualToken {
get { return symModEqualToken; }
}
public static Token LeftShiftToken {
get { return symLeftShiftToken; }
}
public static Token LeftShiftEqualToken {
get { return symLeftShiftEqualToken; }
}
public static Token RightShiftToken {
get { return symRightShiftToken; }
}
public static Token RightShiftEqualToken {
get { return symRightShiftEqualToken; }
}
public static Token BitwiseAndToken {
get { return symBitwiseAndToken; }
}
public static Token BitwiseAndEqualToken {
get { return symBitwiseAndEqualToken; }
}
public static Token BitwiseOrToken {
get { return symBitwiseOrToken; }
}
public static Token BitwiseOrEqualToken {
get { return symBitwiseOrEqualToken; }
}
public static Token ExclusiveOrToken {
get { return symExclusiveOrToken; }
}
public static Token ExclusiveOrEqualToken {
get { return symExclusiveOrEqualToken; }
}
public static Token LessThanToken {
get { return symLessThanToken; }
}
public static Token GreaterThanToken {
get { return symGreaterThanToken; }
}
public static Token LessThanOrEqualToken {
get { return symLessThanOrEqualToken; }
}
public static Token GreaterThanOrEqualToken {
get { return symGreaterThanOrEqualToken; }
}
public static Token EqualsToken {
get { return symEqualsToken; }
}
public static Token NotEqualsToken {
get { return symNotEqualsToken; }
}
public static Token LeftParenthesisToken {
get { return symLeftParenthesisToken; }
}
public static Token RightParenthesisToken {
get { return symRightParenthesisToken; }
}
public static Token LeftBracketToken {
get { return symLeftBracketToken; }
}
public static Token RightBracketToken {
get { return symRightBracketToken; }
}
public static Token LeftBraceToken {
get { return symLeftBraceToken; }
}
public static Token RightBraceToken {
get { return symRightBraceToken; }
}
public static Token CommaToken {
get { return symCommaToken; }
}
public static Token ColonToken {
get { return symColonToken; }
}
public static Token SemicolonToken {
get { return symSemicolonToken; }
}
public static Token AssignToken {
get { return symAssignToken; }
}
public static Token TwiddleToken {
get { return symTwiddleToken; }
}
public static Token AtToken {
get { return symAtToken; }
}
public static Token RightArrowToken {
get { return symRightArrowToken; }
}
private static readonly Token kwAndToken = new SymbolToken(TokenKind.KeywordAnd, "and");
private static readonly Token kwAsToken = new SymbolToken(TokenKind.KeywordAs, "as");
private static readonly Token kwAssertToken = new SymbolToken(TokenKind.KeywordAssert, "assert");
private static readonly Token kwAsyncToken = new SymbolToken(TokenKind.KeywordAsync, "async");
private static readonly Token kwBreakToken = new SymbolToken(TokenKind.KeywordBreak, "break");
private static readonly Token kwClassToken = new SymbolToken(TokenKind.KeywordClass, "class");
private static readonly Token kwContinueToken = new SymbolToken(TokenKind.KeywordContinue, "continue");
private static readonly Token kwDefToken = new SymbolToken(TokenKind.KeywordDef, "def");
private static readonly Token kwDelToken = new SymbolToken(TokenKind.KeywordDel, "del");
private static readonly Token kwElseIfToken = new SymbolToken(TokenKind.KeywordElseIf, "elif");
private static readonly Token kwElseToken = new SymbolToken(TokenKind.KeywordElse, "else");
private static readonly Token kwExceptToken = new SymbolToken(TokenKind.KeywordExcept, "except");
private static readonly Token kwFinallyToken = new SymbolToken(TokenKind.KeywordFinally, "finally");
private static readonly Token kwForToken = new SymbolToken(TokenKind.KeywordFor, "for");
private static readonly Token kwFromToken = new SymbolToken(TokenKind.KeywordFrom, "from");
private static readonly Token kwGlobalToken = new SymbolToken(TokenKind.KeywordGlobal, "global");
private static readonly Token kwIfToken = new SymbolToken(TokenKind.KeywordIf, "if");
private static readonly Token kwImportToken = new SymbolToken(TokenKind.KeywordImport, "import");
private static readonly Token kwInToken = new SymbolToken(TokenKind.KeywordIn, "in");
private static readonly Token kwIsToken = new SymbolToken(TokenKind.KeywordIs, "is");
private static readonly Token kwLambdaToken = new SymbolToken(TokenKind.KeywordLambda, "lambda");
private static readonly Token kwNonlocalToken = new SymbolToken(TokenKind.KeywordNonlocal, "nonlocal");
private static readonly Token kwNotToken = new SymbolToken(TokenKind.KeywordNot, "not");
private static readonly Token kwOrToken = new SymbolToken(TokenKind.KeywordOr, "or");
private static readonly Token kwPassToken = new SymbolToken(TokenKind.KeywordPass, "pass");
private static readonly Token kwRaiseToken = new SymbolToken(TokenKind.KeywordRaise, "raise");
private static readonly Token kwReturnToken = new SymbolToken(TokenKind.KeywordReturn, "return");
private static readonly Token kwTryToken = new SymbolToken(TokenKind.KeywordTry, "try");
private static readonly Token kwWhileToken = new SymbolToken(TokenKind.KeywordWhile, "while");
private static readonly Token kwWithToken = new SymbolToken(TokenKind.KeywordWith, "with");
private static readonly Token kwYieldToken = new SymbolToken(TokenKind.KeywordYield, "yield");
public static Token KeywordAndToken {
get { return kwAndToken; }
}
public static Token KeywordAsToken {
get { return kwAsToken; }
}
public static Token KeywordAssertToken {
get { return kwAssertToken; }
}
public static Token KeywordAsyncToken {
get { return kwAsyncToken; }
}
public static Token KeywordBreakToken {
get { return kwBreakToken; }
}
public static Token KeywordClassToken {
get { return kwClassToken; }
}
public static Token KeywordContinueToken {
get { return kwContinueToken; }
}
public static Token KeywordDefToken {
get { return kwDefToken; }
}
public static Token KeywordDelToken {
get { return kwDelToken; }
}
public static Token KeywordElseIfToken {
get { return kwElseIfToken; }
}
public static Token KeywordElseToken {
get { return kwElseToken; }
}
public static Token KeywordExceptToken {
get { return kwExceptToken; }
}
public static Token KeywordFinallyToken {
get { return kwFinallyToken; }
}
public static Token KeywordForToken {
get { return kwForToken; }
}
public static Token KeywordFromToken {
get { return kwFromToken; }
}
public static Token KeywordGlobalToken {
get { return kwGlobalToken; }
}
public static Token KeywordIfToken {
get { return kwIfToken; }
}
public static Token KeywordImportToken {
get { return kwImportToken; }
}
public static Token KeywordInToken {
get { return kwInToken; }
}
public static Token KeywordIsToken {
get { return kwIsToken; }
}
public static Token KeywordLambdaToken {
get { return kwLambdaToken; }
}
public static Token KeywordNonlocalToken {
get { return kwNonlocalToken; }
}
public static Token KeywordNotToken {
get { return kwNotToken; }
}
public static Token KeywordOrToken {
get { return kwOrToken; }
}
public static Token KeywordPassToken {
get { return kwPassToken; }
}
public static Token KeywordRaiseToken {
get { return kwRaiseToken; }
}
public static Token KeywordReturnToken {
get { return kwReturnToken; }
}
public static Token KeywordTryToken {
get { return kwTryToken; }
}
public static Token KeywordWhileToken {
get { return kwWhileToken; }
}
public static Token KeywordWithToken {
get { return kwWithToken; }
}
public static Token KeywordYieldToken {
get { return kwYieldToken; }
}
// *** END GENERATED CODE ***
#endregion
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Lucene.Net.Analysis;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Store;
namespace Lucene.Net.Test.Index
{
/// <summary>
/// Summary description for FieldEnumeratorTest
/// </summary>
[TestFixture]
public class FieldEnumeratorTest
{
public FieldEnumeratorTest()
{
//
// TODO: Add constructor logic here
//
}
private static IndexReader reader;
#region setup/teardown methods
[TestFixtureSetUp]
public static void MyClassInitialize()
{
RAMDirectory rd = new RAMDirectory();
IndexWriter writer = new IndexWriter(rd, new WhitespaceAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);
for (int i = 0; i < 1000; i++)
{
Document doc = new Document();
doc.Add(new Field("string", i.ToString(), Field.Store.YES, Field.Index.ANALYZED));
doc.Add(new NumericField("int", Field.Store.YES, true).SetIntValue(i));
doc.Add(new NumericField("long", Field.Store.YES, true).SetLongValue(i));
doc.Add(new NumericField("double", Field.Store.YES, true).SetDoubleValue(i));
doc.Add(new NumericField("float", Field.Store.YES, true).SetFloatValue(i));
writer.AddDocument(doc);
}
writer.Close();
reader = IndexReader.Open(rd, true);
}
[TestFixtureTearDown]
public static void MyClassCleanup()
{
if (reader != null)
{
reader.Close();
reader = null;
}
}
#endregion
[Test]
public void StringEnumTest()
{
using (StringFieldEnumerator sfe = new StringFieldEnumerator(reader, "string", false))
{
int value = 0;
foreach (string s in sfe.Terms)
{
value++;
}
Assert.AreEqual(1000, value);
}
// now with the documents
using (StringFieldEnumerator sfe = new StringFieldEnumerator(reader, "string"))
{
int value = 0;
foreach (string s in sfe.Terms)
{
foreach (int doc in sfe.Docs)
{
string expected = reader.Document(doc).Get("string");
Assert.AreEqual(expected, s);
}
value++;
}
Assert.AreEqual(1000, value);
}
}
[Test]
public void IntEnumTest()
{
using (IntFieldEnumerator ife = new IntFieldEnumerator(reader, "string", FieldParser.String))
{
int value = 0;
foreach (int i in ife.Terms)
{
foreach (int doc in ife.Docs)
{
int expected = Int32.Parse(reader.Document(doc).Get("string"));
Assert.AreEqual(expected, i);
}
value++;
}
Assert.AreEqual(1000, value);
}
using (IntFieldEnumerator ife = new IntFieldEnumerator(reader, "int", FieldParser.Numeric))
{
int value = 0;
foreach (int i in ife.Terms)
{
foreach (int doc in ife.Docs)
{
int expected = Int32.Parse(reader.Document(doc).Get("int"));
Assert.AreEqual(expected, i);
}
value++;
}
Assert.AreEqual(1000, value);
}
}
[Test]
public void LongEnumTest()
{
using (LongFieldEnumerator lfe = new LongFieldEnumerator(reader, "string", FieldParser.String))
{
int value = 0;
foreach (long i in lfe.Terms)
{
foreach (int doc in lfe.Docs)
{
long expected = Int64.Parse(reader.Document(doc).Get("string"));
Assert.AreEqual(expected, i);
}
value++;
}
Assert.AreEqual(1000, value);
}
using (LongFieldEnumerator lfe = new LongFieldEnumerator(reader, "long", FieldParser.Numeric))
{
int value = 0;
foreach (int i in lfe.Terms)
{
foreach (int doc in lfe.Docs)
{
long expected = Int64.Parse(reader.Document(doc).Get("long"));
Assert.AreEqual(expected, i);
}
value++;
}
Assert.AreEqual(1000, value);
}
}
[Test]
public void FloatEnumTest()
{
using (FloatFieldEnumerator ffe = new FloatFieldEnumerator(reader, "string", FieldParser.String))
{
int value = 0;
foreach (int i in ffe.Terms)
{
foreach (int doc in ffe.Docs)
{
float expected = Single.Parse(reader.Document(doc).Get("string"));
Assert.AreEqual(expected, i);
}
value++;
}
Assert.AreEqual(1000, value);
}
using (FloatFieldEnumerator ffe = new FloatFieldEnumerator(reader, "float", FieldParser.Numeric))
{
int value = 0;
foreach (int i in ffe.Terms)
{
foreach (int doc in ffe.Docs)
{
float expected = Single.Parse(reader.Document(doc).Get("float"));
Assert.AreEqual(expected, i);
}
value++;
}
Assert.AreEqual(1000, value);
}
}
[Test]
public void DoubleEnumTest()
{
using (DoubleFieldEnumerator dfe = new DoubleFieldEnumerator(reader, "string", FieldParser.String))
{
int value = 0;
foreach (int i in dfe.Terms)
{
foreach (int doc in dfe.Docs)
{
double expected = Double.Parse(reader.Document(doc).Get("string"));
Assert.AreEqual(expected, i);
}
value++;
}
Assert.AreEqual(1000, value);
}
using (DoubleFieldEnumerator dfe = new DoubleFieldEnumerator(reader, "double", FieldParser.Numeric))
{
int value = 0;
foreach (int i in dfe.Terms)
{
foreach (int doc in dfe.Docs)
{
double expected = Double.Parse(reader.Document(doc).Get("double"));
Assert.AreEqual(expected, i);
}
value++;
}
Assert.AreEqual(1000, value);
}
}
[Test]
public void TermDocEnumeratorOnlyTestSingleTerm()
{
Term t = new Term("string", "500");
using (TermDocEnumerator tde = new TermDocEnumerator(reader.TermDocs()))
{
tde.Seek(t);
int count = 0;
foreach (int doc in tde)
{
Assert.AreEqual(500, doc);
count++;
}
Assert.AreEqual(1, count);
}
}
[Test]
public void TermDocEnumeratorOnlyTestMultipleTerms()
{
HashSet<Term> terms = new HashSet<Term>();
terms.Add(new Term("string", "500"));
terms.Add(new Term("string", "600"));
terms.Add(new Term("string", "400"));
HashSet<int> docs = new HashSet<int>();
using (TermDocEnumerator tde = new TermDocEnumerator(reader.TermDocs()))
{
foreach (Term t in terms)
{
tde.Seek(t);
foreach (int doc in tde)
{
docs.Add(doc);
}
}
}
Assert.AreEqual(3, docs.Count);
Assert.IsTrue(docs.Contains(400));
Assert.IsTrue(docs.Contains(500));
Assert.IsTrue(docs.Contains(600));
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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.
//-----------------------------------------------------------------------------
$PostFXManager::defaultPreset = "sys/postFx/default.postfxpreset.cs";
function PostFXManager::settingsSetEnabled(%this, %bEnablePostFX)
{
$PostFXManager::PostFX::Enabled = %bEnablePostFX;
//if to enable the postFX, apply the ones that are enabled
if ( %bEnablePostFX )
{
//SSAO, HDR, LightRays, DOF
if ( $PostFXManager::PostFX::EnableSSAO )
SSAOPostFx.enable();
else
SSAOPostFx.disable();
if ( $PostFXManager::PostFX::EnableHDR )
HDRPostFX.enable();
else
HDRPostFX.disable();
if ( $PostFXManager::PostFX::EnableLightRays )
LightRayPostFX.enable();
else
LightRayPostFX.disable();
if ( $PostFXManager::PostFX::EnableDOF )
DOFPostEffect.enable();
else
DOFPostEffect.disable();
postVerbose("% - PostFX Manager - PostFX enabled");
}
else
{
//Disable all postFX
SSAOPostFx.disable();
HDRPostFX.disable();
LightRayPostFX.disable();
DOFPostEffect.disable();
postVerbose("% - PostFX Manager - PostFX disabled");
}
}
function PostFXManager::settingsEffectSetEnabled(%this, %sName, %bEnable)
{
%postEffect = 0;
//Determine the postFX to enable, and apply the boolean
if(%sName $= "SSAO")
{
%postEffect = SSAOPostFx;
$PostFXManager::PostFX::EnableSSAO = %bEnable;
//$pref::PostFX::SSAO::Enabled = %bEnable;
}
else if(%sName $= "HDR")
{
%postEffect = HDRPostFX;
$PostFXManager::PostFX::EnableHDR = %bEnable;
//$pref::PostFX::HDR::Enabled = %bEnable;
}
else if(%sName $= "LightRays")
{
%postEffect = LightRayPostFX;
$PostFXManager::PostFX::EnableLightRays = %bEnable;
//$pref::PostFX::LightRays::Enabled = %bEnable;
}
else if(%sName $= "DOF")
{
%postEffect = DOFPostEffect;
$PostFXManager::PostFX::EnableDOF = %bEnable;
//$pref::PostFX::DOF::Enabled = %bEnable;
}
// Apply the change
if ( %bEnable == true )
{
%postEffect.enable();
postVerbose("% - PostFX Manager - " @ %sName @ " enabled");
}
else
{
%postEffect.disable();
postVerbose("% - PostFX Manager - " @ %sName @ " disabled");
}
}
function PostFXManager::settingsRefreshSSAO(%this)
{
//Apply the enabled flag
ppOptionsEnableSSAO.setValue($PostFXManager::PostFX::EnableSSAO);
//Add the items we need to display
ppOptionsSSAOQuality.clear();
ppOptionsSSAOQuality.add("Low", 0);
ppOptionsSSAOQuality.add("Medium", 1);
ppOptionsSSAOQuality.add("High", 2);
//Set the selected, after adding the items!
ppOptionsSSAOQuality.setSelected($SSAOPostFx::quality);
//SSAO - Set the values of the sliders, General Tab
ppOptionsSSAOOverallStrength.setValue($SSAOPostFx::overallStrength);
ppOptionsSSAOBlurDepth.setValue($SSAOPostFx::blurDepthTol);
ppOptionsSSAOBlurNormal.setValue($SSAOPostFx::blurNormalTol);
//SSAO - Set the values for the near tab
ppOptionsSSAONearDepthMax.setValue($SSAOPostFx::sDepthMax);
ppOptionsSSAONearDepthMin.setValue($SSAOPostFx::sDepthMin);
ppOptionsSSAONearRadius.setValue($SSAOPostFx::sRadius);
ppOptionsSSAONearStrength.setValue($SSAOPostFx::sStrength);
ppOptionsSSAONearToleranceNormal.setValue($SSAOPostFx::sNormalTol);
ppOptionsSSAONearTolerancePower.setValue($SSAOPostFx::sNormalPow);
//SSAO - Set the values for the far tab
ppOptionsSSAOFarDepthMax.setValue($SSAOPostFx::lDepthMax);
ppOptionsSSAOFarDepthMin.setValue($SSAOPostFx::lDepthMin);
ppOptionsSSAOFarRadius.setValue($SSAOPostFx::lRadius);
ppOptionsSSAOFarStrength.setValue($SSAOPostFx::lStrength);
ppOptionsSSAOFarToleranceNormal.setValue($SSAOPostFx::lNormalTol);
ppOptionsSSAOFarTolerancePower.setValue($SSAOPostFx::lNormalPow);
}
function PostFXManager::settingsRefreshHDR(%this)
{
//Apply the enabled flag
ppOptionsEnableHDR.setValue($PostFXManager::PostFX::EnableHDR);
ppOptionsHDRBloom.setValue($HDRPostFX::enableBloom);
ppOptionsHDRBloomBlurBrightPassThreshold.setValue($HDRPostFX::brightPassThreshold);
ppOptionsHDRBloomBlurMean.setValue($HDRPostFX::gaussMean);
ppOptionsHDRBloomBlurMultiplier.setValue($HDRPostFX::gaussMultiplier);
ppOptionsHDRBloomBlurStdDev.setValue($HDRPostFX::gaussStdDev);
ppOptionsHDRBrightnessAdaptRate.setValue($HDRPostFX::adaptRate);
ppOptionsHDREffectsBlueShift.setValue($HDRPostFX::enableBlueShift);
ppOptionsHDREffectsBlueShiftColor.BaseColor = $HDRPostFX::blueShiftColor;
ppOptionsHDREffectsBlueShiftColor.PickColor = $HDRPostFX::blueShiftColor;
ppOptionsHDRKeyValue.setValue($HDRPostFX::keyValue);
ppOptionsHDRMinLuminance.setValue($HDRPostFX::minLuminace);
ppOptionsHDRToneMapping.setValue($HDRPostFX::enableToneMapping);
ppOptionsHDRToneMappingAmount.setValue($HDRPostFX::enableToneMapping);
ppOptionsHDRWhiteCutoff.setValue($HDRPostFX::whiteCutoff);
%this-->ColorCorrectionFileName.Text = $HDRPostFX::colorCorrectionRamp;
}
function PostFXManager::settingsRefreshLightrays(%this)
{
//Apply the enabled flag
ppOptionsEnableLightRays.setValue($PostFXManager::PostFX::EnableLightRays);
ppOptionsLightRaysBrightScalar.setValue($LightRayPostFX::brightScalar);
}
function PostFXManager::settingsRefreshDOF(%this)
{
//Apply the enabled flag
ppOptionsEnableDOF.setValue($PostFXManager::PostFX::EnableDOF);
//ppOptionsDOFEnableDOF.setValue($PostFXManager::PostFX::EnableDOF);
ppOptionsDOFEnableAutoFocus.setValue($DOFPostFx::EnableAutoFocus);
ppOptionsDOFFarBlurMinSlider.setValue($DOFPostFx::BlurMin);
ppOptionsDOFFarBlurMaxSlider.setValue($DOFPostFx::BlurMax);
ppOptionsDOFFocusRangeMinSlider.setValue($DOFPostFx::FocusRangeMin);
ppOptionsDOFFocusRangeMaxSlider.setValue($DOFPostFx::FocusRangeMax);
ppOptionsDOFBlurCurveNearSlider.setValue($DOFPostFx::BlurCurveNear);
ppOptionsDOFBlurCurveFarSlider.setValue($DOFPostFx::BlurCurveFar);
}
function PostFXManager::settingsRefreshAll(%this)
{
$PostFXManager::PostFX::Enabled = $pref::enablePostEffects;
$PostFXManager::PostFX::EnableSSAO = SSAOPostFx.isEnabled();
$PostFXManager::PostFX::EnableHDR = HDRPostFX.isEnabled();
$PostFXManager::PostFX::EnableLightRays = LightRayPostFX.isEnabled();
$PostFXManager::PostFX::EnableDOF = DOFPostEffect.isEnabled();
//For all the postFX here, apply the active settings in the system
//to the gui controls.
%this.settingsRefreshSSAO();
%this.settingsRefreshHDR();
%this.settingsRefreshLightrays();
%this.settingsRefreshDOF();
ppOptionsEnable.setValue($PostFXManager::PostFX::Enabled);
postVerbose("% - PostFX Manager - GUI values updated.");
}
function PostFXManager::settingsApplyFromPreset(%this)
{
postVerbose("% - PostFX Manager - Applying from preset");
//SSAO Settings
$SSAOPostFx::blurDepthTol = $PostFXManager::Settings::SSAO::blurDepthTol;
$SSAOPostFx::blurNormalTol = $PostFXManager::Settings::SSAO::blurNormalTol;
$SSAOPostFx::lDepthMax = $PostFXManager::Settings::SSAO::lDepthMax;
$SSAOPostFx::lDepthMin = $PostFXManager::Settings::SSAO::lDepthMin;
$SSAOPostFx::lDepthPow = $PostFXManager::Settings::SSAO::lDepthPow;
$SSAOPostFx::lNormalPow = $PostFXManager::Settings::SSAO::lNormalPow;
$SSAOPostFx::lNormalTol = $PostFXManager::Settings::SSAO::lNormalTol;
$SSAOPostFx::lRadius = $PostFXManager::Settings::SSAO::lRadius;
$SSAOPostFx::lStrength = $PostFXManager::Settings::SSAO::lStrength;
$SSAOPostFx::overallStrength = $PostFXManager::Settings::SSAO::overallStrength;
$SSAOPostFx::quality = $PostFXManager::Settings::SSAO::quality;
$SSAOPostFx::sDepthMax = $PostFXManager::Settings::SSAO::sDepthMax;
$SSAOPostFx::sDepthMin = $PostFXManager::Settings::SSAO::sDepthMin;
$SSAOPostFx::sDepthPow = $PostFXManager::Settings::SSAO::sDepthPow;
$SSAOPostFx::sNormalPow = $PostFXManager::Settings::SSAO::sNormalPow;
$SSAOPostFx::sNormalTol = $PostFXManager::Settings::SSAO::sNormalTol;
$SSAOPostFx::sRadius = $PostFXManager::Settings::SSAO::sRadius;
$SSAOPostFx::sStrength = $PostFXManager::Settings::SSAO::sStrength;
//HDR settings
$HDRPostFX::adaptRate = $PostFXManager::Settings::HDR::adaptRate;
$HDRPostFX::blueShiftColor = $PostFXManager::Settings::HDR::blueShiftColor;
$HDRPostFX::brightPassThreshold = $PostFXManager::Settings::HDR::brightPassThreshold;
$HDRPostFX::enableBloom = $PostFXManager::Settings::HDR::enableBloom;
$HDRPostFX::enableBlueShift = $PostFXManager::Settings::HDR::enableBlueShift;
$HDRPostFX::enableToneMapping = $PostFXManager::Settings::HDR::enableToneMapping;
$HDRPostFX::gaussMean = $PostFXManager::Settings::HDR::gaussMean;
$HDRPostFX::gaussMultiplier = $PostFXManager::Settings::HDR::gaussMultiplier;
$HDRPostFX::gaussStdDev = $PostFXManager::Settings::HDR::gaussStdDev;
$HDRPostFX::keyValue = $PostFXManager::Settings::HDR::keyValue;
$HDRPostFX::minLuminace = $PostFXManager::Settings::HDR::minLuminace;
$HDRPostFX::whiteCutoff = $PostFXManager::Settings::HDR::whiteCutoff;
$HDRPostFX::colorCorrectionRamp = $PostFXManager::Settings::ColorCorrectionRamp;
//Light rays settings
$LightRayPostFX::brightScalar = $PostFXManager::Settings::LightRays::brightScalar;
//DOF settings
$DOFPostFx::EnableAutoFocus = $PostFXManager::Settings::DOF::EnableAutoFocus;
$DOFPostFx::BlurMin = $PostFXManager::Settings::DOF::BlurMin;
$DOFPostFx::BlurMax = $PostFXManager::Settings::DOF::BlurMax;
$DOFPostFx::FocusRangeMin = $PostFXManager::Settings::DOF::FocusRangeMin;
$DOFPostFx::FocusRangeMax = $PostFXManager::Settings::DOF::FocusRangeMax;
$DOFPostFx::BlurCurveNear = $PostFXManager::Settings::DOF::BlurCurveNear;
$DOFPostFx::BlurCurveFar = $PostFXManager::Settings::DOF::BlurCurveFar;
if ( $PostFXManager::forceEnableFromPresets )
{
$PostFXManager::PostFX::Enabled = $PostFXManager::Settings::EnablePostFX;
$PostFXManager::PostFX::EnableDOF = $PostFXManager::Settings::EnableDOF;
$PostFXManager::PostFX::EnableLightRays = $PostFXManager::Settings::EnableLightRays;
$PostFXManager::PostFX::EnableHDR = $PostFXManager::Settings::EnableHDR;
$PostFXManager::PostFX::EnableSSAO = $PostFXManager::Settings::EnabledSSAO;
%this.settingsSetEnabled( true );
}
//make sure we apply the correct settings to the DOF
ppOptionsUpdateDOFSettings();
// Update the actual GUI controls if its awake ( otherwise it will when opened ).
if ( PostFXManager.isAwake() )
%this.settingsRefreshAll();
}
function PostFXManager::settingsApplySSAO(%this)
{
$PostFXManager::Settings::SSAO::blurDepthTol = $SSAOPostFx::blurDepthTol;
$PostFXManager::Settings::SSAO::blurNormalTol = $SSAOPostFx::blurNormalTol;
$PostFXManager::Settings::SSAO::lDepthMax = $SSAOPostFx::lDepthMax;
$PostFXManager::Settings::SSAO::lDepthMin = $SSAOPostFx::lDepthMin;
$PostFXManager::Settings::SSAO::lDepthPow = $SSAOPostFx::lDepthPow;
$PostFXManager::Settings::SSAO::lNormalPow = $SSAOPostFx::lNormalPow;
$PostFXManager::Settings::SSAO::lNormalTol = $SSAOPostFx::lNormalTol;
$PostFXManager::Settings::SSAO::lRadius = $SSAOPostFx::lRadius;
$PostFXManager::Settings::SSAO::lStrength = $SSAOPostFx::lStrength;
$PostFXManager::Settings::SSAO::overallStrength = $SSAOPostFx::overallStrength;
$PostFXManager::Settings::SSAO::quality = $SSAOPostFx::quality;
$PostFXManager::Settings::SSAO::sDepthMax = $SSAOPostFx::sDepthMax;
$PostFXManager::Settings::SSAO::sDepthMin = $SSAOPostFx::sDepthMin;
$PostFXManager::Settings::SSAO::sDepthPow = $SSAOPostFx::sDepthPow;
$PostFXManager::Settings::SSAO::sNormalPow = $SSAOPostFx::sNormalPow;
$PostFXManager::Settings::SSAO::sNormalTol = $SSAOPostFx::sNormalTol;
$PostFXManager::Settings::SSAO::sRadius = $SSAOPostFx::sRadius;
$PostFXManager::Settings::SSAO::sStrength = $SSAOPostFx::sStrength;
postVerbose("% - PostFX Manager - Settings Saved - SSAO");
}
function PostFXManager::settingsApplyHDR(%this)
{
$PostFXManager::Settings::HDR::adaptRate = $HDRPostFX::adaptRate;
$PostFXManager::Settings::HDR::blueShiftColor = $HDRPostFX::blueShiftColor;
$PostFXManager::Settings::HDR::brightPassThreshold = $HDRPostFX::brightPassThreshold;
$PostFXManager::Settings::HDR::enableBloom = $HDRPostFX::enableBloom;
$PostFXManager::Settings::HDR::enableBlueShift = $HDRPostFX::enableBlueShift;
$PostFXManager::Settings::HDR::enableToneMapping = $HDRPostFX::enableToneMapping;
$PostFXManager::Settings::HDR::gaussMean = $HDRPostFX::gaussMean;
$PostFXManager::Settings::HDR::gaussMultiplier = $HDRPostFX::gaussMultiplier;
$PostFXManager::Settings::HDR::gaussStdDev = $HDRPostFX::gaussStdDev;
$PostFXManager::Settings::HDR::keyValue = $HDRPostFX::keyValue;
$PostFXManager::Settings::HDR::minLuminace = $HDRPostFX::minLuminace;
$PostFXManager::Settings::HDR::whiteCutoff = $HDRPostFX::whiteCutoff;
$PostFXManager::Settings::ColorCorrectionRamp = $HDRPostFX::colorCorrectionRamp;
postVerbose("% - PostFX Manager - Settings Saved - HDR");
}
function PostFXManager::settingsApplyLightRays(%this)
{
$PostFXManager::Settings::LightRays::brightScalar = $LightRayPostFX::brightScalar;
postVerbose("% - PostFX Manager - Settings Saved - Light Rays");
}
function PostFXManager::settingsApplyDOF(%this)
{
$PostFXManager::Settings::DOF::EnableAutoFocus = $DOFPostFx::EnableAutoFocus;
$PostFXManager::Settings::DOF::BlurMin = $DOFPostFx::BlurMin;
$PostFXManager::Settings::DOF::BlurMax = $DOFPostFx::BlurMax;
$PostFXManager::Settings::DOF::FocusRangeMin = $DOFPostFx::FocusRangeMin;
$PostFXManager::Settings::DOF::FocusRangeMax = $DOFPostFx::FocusRangeMax;
$PostFXManager::Settings::DOF::BlurCurveNear = $DOFPostFx::BlurCurveNear;
$PostFXManager::Settings::DOF::BlurCurveFar = $DOFPostFx::BlurCurveFar;
postVerbose("% - PostFX Manager - Settings Saved - DOF");
}
function PostFXManager::settingsApplyAll(%this, %sFrom)
{
// Apply settings which control if effects are on/off altogether.
$PostFXManager::Settings::EnablePostFX = $PostFXManager::PostFX::Enabled;
$PostFXManager::Settings::EnableDOF = $PostFXManager::PostFX::EnableDOF;
$PostFXManager::Settings::EnableLightRays = $PostFXManager::PostFX::EnableLightRays;
$PostFXManager::Settings::EnableHDR = $PostFXManager::PostFX::EnableHDR;
$PostFXManager::Settings::EnabledSSAO = $PostFXManager::PostFX::EnableSSAO;
// Apply settings should save the values in the system to the
// the preset structure ($PostFXManager::Settings::*)
// SSAO Settings
%this.settingsApplySSAO();
// HDR settings
%this.settingsApplyHDR();
// Light rays settings
%this.settingsApplyLightRays();
// DOF
%this.settingsApplyDOF();
postVerbose("% - PostFX Manager - All Settings applied to $PostFXManager::Settings");
}
function PostFXManager::settingsApplyDefaultPreset(%this)
{
PostFXManager::loadPresetHandler($PostFXManager::defaultPreset);
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Threading;
using System.Diagnostics;
using System.Xml.Serialization;
using HashTag.Common.Text;
using System.Collections.Specialized;
using System.Runtime.Serialization;
namespace HashTag.Common.Diagnostics
{
/// <summary>
/// Probe system for machine centric properties
/// </summary>
public sealed class MachineContext
{
/// <summary>
/// Default constructor
/// </summary>
public MachineContext()
{
getSystemProperties();
}
private static string _hostName = Environment.MachineName;
/// <summary>
/// Computer where this event occured. Can be different than the computer where
/// message is actually stored. If not explicitly set, use runtime information
/// </summary>
public string HostName
{
get
{
if (string.IsNullOrEmpty(_hostName) == true)
{
_hostName = System.Environment.MachineName;
}
return _hostName;
}
set
{
_hostName = value;
}
}
private string _identity = Environment.UserDomainName + "/" + Environment.UserName;
/// <summary>
/// Identity (usually username) process is running under when application created this
/// message.
/// </summary>
public string Identity
{
get
{
return _identity;
}
set
{
_identity = value;
}
}
private string _appDomainName;
/// <summary>
/// The <see cref="AppDomain"/> in which the program is running
/// </summary>
public string AppDomainName
{
get
{
return _appDomainName;
}
set
{
_appDomainName = value;
}
}
private string _userDomainName = Environment.UserDomainName;
/// <summary>
/// Identity domain caller of this application is running under
/// </summary>
public string UserDomainName
{
get { return _userDomainName; }
set { _userDomainName = value; }
}
private string _processId;
/// <summary>
/// The Win32 process ID for the current running process.
/// </summary>
public string ProcessId
{
get
{
return _processId;
}
set
{
_processId = value;
}
}
private string _processName;
/// <summary>
/// The name of the current running process.
/// </summary>
public string ProcessName
{
get
{
return _processName;
}
set
{
_processName = value;
}
}
private string _managedThreadName;
/// <summary>
/// The name of the .NET thread.
/// </summary>
/// <seealso cref="Win32ThreadId"/>
public string ManagedThreadName
{
get
{
return _managedThreadName;
}
set
{
_managedThreadName = value;
}
}
private string win32ThreadId;
/// <summary>
/// The Win32 Thread ID for the current thread.
/// </summary>
public string Win32ThreadId
{
get
{
return win32ThreadId;
}
set
{
win32ThreadId = value;
}
}
#region Win32 calls
string _ipAddressList;
/// <summary>
/// Gets/Set comma separated list of IP addresses for this host
/// </summary>
[Citation("20080901",Source="http://www.geekpedia.com/tutorial149_Get-the-IP-address-in-a-Windows-application.html",SourceDate="October 27th 2005")]
public string IPAddressList
{
get
{
if (string.IsNullOrEmpty(_ipAddressList))
{
string myHost = System.Net.Dns.GetHostName();
System.Net.IPHostEntry myIPs = System.Net.Dns.GetHostEntry(myHost);
// Loop through all IP addresses and display each
_ipAddressList = "";
foreach (System.Net.IPAddress myIP in myIPs.AddressList)
{
if (_ipAddressList.Length > 0)
_ipAddressList += ",";
_ipAddressList += myIP.ToString();
}
}
return _ipAddressList;
}
set
{
_ipAddressList = value;
}
}
private void getSystemProperties()
{
this.HostName = Environment.MachineName;
this.AppDomainName = AppDomain.CurrentDomain.FriendlyName;
this.ManagedThreadName = Thread.CurrentThread.Name;
this.ProcessId = Utils.Win32.GetCurrentProcessId().ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
var currentProc = System.Diagnostics.Process.GetCurrentProcess();
if (currentProc != null && currentProc.MainModule != null)
{
this.ProcessName = currentProc.MainModule.FileName;
}
this.Win32ThreadId = Utils.Win32.GetCurrentThreadId().ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
_className = ClassName;
_methodName = MethodName;
_ipAddressList = IPAddressList; //force load of lazy loaded properties
}
#endregion
private string _className;
/// <summary>
/// Name of first non-Utilities class within this stack trace. NOTE: Will return "" if called from any method within the same namespace as this method. HashTag.Diagnostics
/// </summary>
public string ClassName
{
get
{
if ((string.IsNullOrEmpty(_className) == true) || string.IsNullOrEmpty(_methodName) == true)
getStackTraceInfo();
return _className;
}
set { _className = value; }
}
private string _stackTrace = Environment.StackTrace;
/// <summary>
/// Return a string that represents the stack trace at the moment of this call
/// </summary>
public string StackTrace
{
get
{
return _stackTrace;
}
set
{
_stackTrace = value;
}
}
private void getStackTraceInfo()
{
StackTrace st = new StackTrace();
StackFrame[] frames = st.GetFrames();
string namespaceName = frames[0].GetMethod().ReflectedType.Namespace;
foreach (StackFrame sf in frames)
{
string operation = sf.GetMethod().Name;
Type t = sf.GetMethod().ReflectedType;
if (t.Namespace != namespaceName)
{
_className = t.FullName;
_methodName = operation;
break;
}
}
}
private string _methodName;
/// <summary>
/// Name of non-Utilities method that is calling this method. NOTE: Will return "" if called from any method within the same namespace as this method.
/// </summary>
public string MethodName
{
get
{
if ((string.IsNullOrEmpty(_className) == true) || string.IsNullOrEmpty(_methodName) == true)
getStackTraceInfo();
return _methodName;
}
set { _methodName = value; }
}
/// <summary>
/// Convert all RunTime fields into XML elements
/// </summary>
/// <param name="writer">Writer to write XML elements to</param>
public void ToXml(XmlWriter writer)
{
try
{
writer.WriteStartElement("MachineContext");
writer.WriteElementString("HostName", this.HostName);
writer.WriteElementString("Identity", this.Identity);
writer.WriteElementString("AppDomainName", this.AppDomainName);
writer.WriteElementString("ProcessId", this.ProcessId);
writer.WriteElementString("ProcessName", this.ProcessName);
writer.WriteElementString("ManagedThreadName", this.ManagedThreadName);
writer.WriteElementString("Win32ThreadId", this.win32ThreadId);
writer.WriteElementString("ClassName", this.ClassName);
writer.WriteElementString("MethodName", this.MethodName);
writer.WriteElementString("StackTrace", StackTrace);
}
finally
{
writer.WriteEndElement(); //runtimeContext
}
}
/// <summary>
/// Returns a list of property/values of the machine taken at the time this class was created. Used most frequently in logging scenarios
/// </summary>
/// <returns></returns>
public NameValueCollection ToList()
{
NameValueCollection nvc = new NameValueCollection();
nvc.Add("HostName", this.HostName);
nvc.Add("Identity", this.Identity);
nvc.Add("AppDomainName", this.AppDomainName);
nvc.Add("ProcessId", this.ProcessId);
nvc.Add("ProcessName", this.ProcessName);
nvc.Add("ManagedThreadName", this.ManagedThreadName);
nvc.Add("Win32ThreadId", this.win32ThreadId);
nvc.Add("ClassName", this.ClassName);
nvc.Add("MethodName", this.MethodName);
nvc.Add("StackTrace", StackTrace);
return nvc;
}
/// <summary>
/// Generate an XML representation of this class. >MachineContext< is the first node returned.
/// </summary>
/// <returns>Xml representaion of this object</returns>
public string ToXml()
{
return Serialize.To.Xml(this);
}
#region IXmlSerializable Members
/// <summary>
/// IXmlSerializable Interface Implementation
/// </summary>
/// <returns>Null</returns>
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
/// <summary>
/// Not Implemented. Class is intended for for serialization only.
/// </summary>
/// <param name="reader"></param>
public void ReadXml(XmlReader reader)
{
throw new NotImplementedException("This class is intended to be serialized only. Deserialization is not supported");
}
/// <summary>
/// Generate an XML representation of this class. >MachineContext< is the first node returned.
/// </summary>
/// <param name="writer">Writer to which Xml of this object is sent</param>
public void WriteXml(XmlWriter writer)
{
ToXml(writer);
}
#endregion
} //machine context
}
| |
namespace Nancy.Tests.Unit
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using FakeItEasy;
using Nancy.Bootstrapper;
using Nancy.Configuration;
using Nancy.Diagnostics;
using Nancy.ErrorHandling;
using Nancy.Extensions;
using Nancy.Helpers;
using Nancy.Routing;
using Nancy.Tests.Fakes;
using Xunit;
using Nancy.Responses.Negotiation;
using Nancy.Tests.xUnitExtensions;
public class NancyEngineFixture
{
private readonly INancyEngine engine;
private readonly IRouteResolver resolver;
private readonly FakeRoute route;
private readonly NancyContext context;
private readonly INancyContextFactory contextFactory;
private readonly Response response;
private readonly IStatusCodeHandler statusCodeHandler;
private readonly IRouteInvoker routeInvoker;
private readonly IRequestDispatcher requestDispatcher;
private readonly IResponseNegotiator negotiator;
private readonly INancyEnvironment environment;
public NancyEngineFixture()
{
this.environment =
new DefaultNancyEnvironment();
this.environment.Tracing(
enabled: true,
displayErrorTraces: true);
this.resolver = A.Fake<IRouteResolver>();
this.response = new Response();
this.route = new FakeRoute(response);
this.context = new NancyContext();
this.statusCodeHandler = A.Fake<IStatusCodeHandler>();
this.requestDispatcher = A.Fake<IRequestDispatcher>();
this.negotiator = A.Fake<IResponseNegotiator>();
A.CallTo(() => this.requestDispatcher.Dispatch(A<NancyContext>._, A<CancellationToken>._))
.Returns(Task.FromResult(new Response()));
A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).Returns(false);
contextFactory = A.Fake<INancyContextFactory>();
A.CallTo(() => contextFactory.Create(A<Request>._)).Returns(context);
var resolveResult = new ResolveResult { Route = route, Parameters = DynamicDictionary.Empty, Before = null, After = null, OnError = null };
A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolveResult);
var applicationPipelines = new Pipelines();
this.routeInvoker = A.Fake<IRouteInvoker>();
A.CallTo(() => this.routeInvoker.Invoke(A<Route>._, A<CancellationToken>._, A<DynamicDictionary>._, A<NancyContext>._)).ReturnsLazily(arg =>
{
return ((Route)arg.Arguments[0]).Action.Invoke((DynamicDictionary)arg.Arguments[1], A<CancellationToken>._).Result;
});
this.engine =
new NancyEngine(this.requestDispatcher, this.contextFactory, new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator, this.environment)
{
RequestPipelinesFactory = ctx => applicationPipelines
};
}
[Fact]
public void Should_throw_argumentnullexception_when_created_with_null_dispatcher()
{
// Given, When
var exception =
Record.Exception(() => new NancyEngine(null, A.Fake<INancyContextFactory>(), new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator, this.environment));
// Then
exception.ShouldBeOfType<ArgumentNullException>();
}
[Fact]
public void Should_throw_argumentnullexception_when_created_with_null_context_factory()
{
// Given, When
var exception =
Record.Exception(() => new NancyEngine(this.requestDispatcher, null, new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator, this.environment));
// Then
exception.ShouldBeOfType<ArgumentNullException>();
}
[Fact]
public void Should_throw_argumentnullexception_when_created_with_null_status_handler()
{
// Given, When
var exception =
Record.Exception(() => new NancyEngine(this.requestDispatcher, A.Fake<INancyContextFactory>(), null, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator, this.environment));
// Then
exception.ShouldBeOfType<ArgumentNullException>();
}
[Fact]
public async Task HandleRequest_Should_Throw_ArgumentNullException_When_Given_A_Null_Request()
{
// Given,
Request request = null;
// When
var exception = await RecordAsync.Exception(async () => await engine.HandleRequest(request));
// Then
exception.ShouldBeOfType<ArgumentNullException>();
}
[Fact]
public void HandleRequest_should_get_context_from_context_factory()
{
// Given
var request = new Request("GET", "/", "http");
// When
this.engine.HandleRequest(request);
// Then
A.CallTo(() => this.contextFactory.Create(request)).MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public async Task HandleRequest_should_set_correct_response_on_returned_context()
{
// Given
var request = new Request("GET", "/", "http");
A.CallTo(() => this.requestDispatcher.Dispatch(this.context, A<CancellationToken>._))
.Returns(Task.FromResult(this.response));
// When
var result = await this.engine.HandleRequest(request);
// Then
result.Response.ShouldBeSameAs(this.response);
}
[Fact]
public async Task Should_not_add_nancy_version_number_header_on_returned_response()
{
// NOTE: Regression for removal of nancy-version from response headers
// Given
var request = new Request("GET", "/", "http");
// When
var result = await this.engine.HandleRequest(request);
// Then
result.Response.Headers.ContainsKey("Nancy-Version").ShouldBeFalse();
}
[Fact]
public async Task Should_not_throw_exception_when_handlerequest_is_invoked_and_pre_request_hook_is_null()
{
// Given
var pipelines = new Pipelines { BeforeRequest = null };
engine.RequestPipelinesFactory = (ctx) => pipelines;
// When
var request = new Request("GET", "/", "http");
// Then
await this.engine.HandleRequest(request);
}
[Fact]
public async Task Should_not_throw_exception_when_handlerequest_is_invoked_and_post_request_hook_is_null()
{
// Given
var pipelines = new Pipelines { AfterRequest = null };
engine.RequestPipelinesFactory = (ctx) => pipelines;
// When
var request = new Request("GET", "/", "http");
// Then
await this.engine.HandleRequest(request);
}
[Fact]
public async Task Should_call_pre_request_hook_should_be_invoked_with_request_from_context()
{
// Given
Request passedRequest = null;
var pipelines = new Pipelines();
pipelines.BeforeRequest.AddItemToStartOfPipeline((ctx) =>
{
passedRequest = ctx.Request;
return null;
});
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
this.context.Request = request;
// When
await this.engine.HandleRequest(request);
// Then
passedRequest.ShouldBeSameAs(request);
}
[Fact]
public async Task Should_return_response_from_pre_request_hook_when_not_null()
{
// Given
var returnedResponse = A.Fake<Response>();
var pipelines = new Pipelines();
pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx => returnedResponse);
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
// When
var result = await this.engine.HandleRequest(request);
// Then
result.Response.ShouldBeSameAs(returnedResponse);
}
[Fact]
public async Task Should_allow_post_request_hook_to_modify_context_items()
{
// Given
var pipelines = new Pipelines();
pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx =>
{
ctx.Items.Add("PostReqTest", new object());
return null;
});
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
// When
var result = await this.engine.HandleRequest(request);
// Then
result.Items.ContainsKey("PostReqTest").ShouldBeTrue();
}
[Fact]
public async Task Should_allow_post_request_hook_to_replace_response()
{
// Given
var newResponse = new Response();
var pipelines = new Pipelines();
pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx => ctx.Response = newResponse);
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
// When
var result = await this.engine.HandleRequest(request);
// Then
result.Response.ShouldBeSameAs(newResponse);
}
[Fact]
public async Task HandleRequest_prereq_returns_response_should_still_run_postreq()
{
// Given
var returnedResponse = A.Fake<Response>();
var postReqCalled = false;
var pipelines = new Pipelines();
pipelines.BeforeRequest.AddItemToStartOfPipeline(ctx => returnedResponse);
pipelines.AfterRequest.AddItemToEndOfPipeline(ctx => postReqCalled = true);
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
// When
await this.engine.HandleRequest(request);
// Then
postReqCalled.ShouldBeTrue();
}
[Fact]
public async Task Should_ask_status_handler_if_it_can_handle_status_code()
{
// Given
var request = new Request("GET", "/", "http");
// When
await this.engine.HandleRequest(request);
// Then
A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public async Task Should_not_invoke_status_handler_if_not_supported_status_code()
{
// Given
var request = new Request("GET", "/", "http");
// When
await this.engine.HandleRequest(request);
// Then
A.CallTo(() => this.statusCodeHandler.Handle(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).MustNotHaveHappened();
}
[Fact]
public async Task Should_invoke_status_handler_if_supported_status_code()
{
// Given
var request = new Request("GET", "/", "http");
A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).Returns(true);
// When
await this.engine.HandleRequest(request);
// Then
A.CallTo(() => this.statusCodeHandler.Handle(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).MustHaveHappened(Repeated.Exactly.Once);
}
[Fact]
public async Task Should_set_status_code_to_500_if_route_throws()
{
// Given
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._))
.Returns(TaskHelpers.GetFaultedTask<Response>(new NotImplementedException()));
var request = new Request("GET", "/", "http");
// When
var result = await this.engine.HandleRequest(request);
// Then
result.Response.StatusCode.ShouldEqual(HttpStatusCode.InternalServerError);
}
[Fact]
public async Task Should_store_exception_details_if_dispatcher_throws()
{
// Given
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._))
.Returns(TaskHelpers.GetFaultedTask<Response>(new NotImplementedException()));
var request = new Request("GET", "/", "http");
// When
var result = await this.engine.HandleRequest(request);
// Then
result.GetExceptionDetails().ShouldContain("NotImplementedException");
}
[Fact]
public async Task Should_invoke_the_error_request_hook_if_one_exists_when_dispatcher_throws()
{
// Given
var testEx = new Exception();
var errorRoute =
new Route("GET", "/", null, (x,c) => { throw testEx; });
var resolvedRoute = new ResolveResult(
errorRoute,
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._))
.Returns(TaskHelpers.GetFaultedTask<Response>(testEx));
Exception handledException = null;
NancyContext handledContext = null;
var errorResponse = new Response();
A.CallTo(() => this.negotiator.NegotiateResponse(A<object>.Ignored, A<NancyContext>.Ignored))
.Returns(errorResponse);
Func<NancyContext, Exception, dynamic> routeErrorHook = (ctx, ex) =>
{
handledContext = ctx;
handledException = ex;
return errorResponse;
};
var pipelines = new Pipelines();
pipelines.OnError.AddItemToStartOfPipeline(routeErrorHook);
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
// When
var result = await this.engine.HandleRequest(request);
// Then
Assert.Equal(testEx, handledException);
Assert.Equal(result, handledContext);
Assert.Equal(result.Response, errorResponse);
}
[Fact]
public async Task Should_add_unhandled_exception_to_context_as_requestexecutionexception()
{
// Given
var routeUnderTest =
new Route("GET", "/", null, (x,c) => { throw new Exception(); });
var resolved =
new ResolveResult(routeUnderTest, DynamicDictionary.Empty, null, null, null);
A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolved);
A.CallTo(() => this.routeInvoker.Invoke(A<Route>._, A<CancellationToken>._, A<DynamicDictionary>._, A<NancyContext>._))
.Invokes((x) => routeUnderTest.Action.Invoke(DynamicDictionary.Empty, new CancellationToken()));
A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._))
.Returns(TaskHelpers.GetFaultedTask<Response>(new Exception()));
var pipelines = new Pipelines();
pipelines.OnError.AddItemToStartOfPipeline((ctx, exception) => null);
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
// When
var result = await this.engine.HandleRequest(request);
// Then
result.Items.Keys.Contains("ERROR_EXCEPTION").ShouldBeTrue();
result.Items["ERROR_EXCEPTION"].ShouldBeOfType<RequestExecutionException>();
}
[Fact]
public async Task Should_persist_original_exception_in_requestexecutionexception()
{
// Given
var expectedException = new Exception();
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._))
.Returns(TaskHelpers.GetFaultedTask<Response>(expectedException));
var pipelines = new Pipelines();
pipelines.OnError.AddItemToStartOfPipeline((ctx, exception) => null);
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
// When
var result = await this.engine.HandleRequest(request);
var returnedException = result.Items["ERROR_EXCEPTION"] as RequestExecutionException;
// Then
returnedException.InnerException.ShouldBeSameAs(expectedException);
}
[Fact]
public async Task Should_persist_original_exception_in_requestexecutionexception_when_pipeline_is_null()
{
// Given
var expectedException = new Exception();
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._))
.Returns(TaskHelpers.GetFaultedTask<Response>(expectedException));
var pipelines = new Pipelines { OnError = null };
engine.RequestPipelinesFactory = (ctx) => pipelines;
var request = new Request("GET", "/", "http");
// When
var result = await this.engine.HandleRequest(request);
var returnedException = result.Items["ERROR_EXCEPTION"] as RequestExecutionException;
// Then
returnedException.InnerException.ShouldBeSameAs(expectedException);
}
[Fact]
public async Task Should_return_static_content_response_if_one_returned()
{
// Given
var localResponse = new Response();
var staticContent = A.Fake<IStaticContentProvider>();
A.CallTo(() => staticContent.GetContent(A<NancyContext>._))
.Returns(localResponse);
var localEngine = new NancyEngine(
this.requestDispatcher,
this.contextFactory,
new[] { this.statusCodeHandler },
A.Fake<IRequestTracing>(),
staticContent,
this.negotiator
, this.environment);
var request = new Request("GET", "/", "http");
// When
var result = await localEngine.HandleRequest(request);
// Then
result.Response.ShouldBeSameAs(localResponse);
}
[Fact]
public async Task Should_set_status_code_to_500_if_pre_execute_response_throws()
{
// Given
var resolvedRoute = new ResolveResult(
new FakeRoute(),
DynamicDictionary.Empty,
null,
null,
null);
A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);
A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._))
.Returns(Task.FromResult<Response>(new PreExecuteFailureResponse()));
var request = new Request("GET", "/", "http");
// When
var result = await this.engine.HandleRequest(request);
// Then
result.Response.StatusCode.ShouldEqual(HttpStatusCode.InternalServerError);
}
[Fact]
public async Task Should_throw_operationcancelledexception_when_disposed_handling_request()
{
// Given
var request = new Request("GET", "/", "http");
var engine = new NancyEngine(A.Fake<IRequestDispatcher>(), A.Fake<INancyContextFactory>(),
new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(),
this.negotiator, this.environment);
engine.Dispose();
// When
var exception = await RecordAsync.Exception(async () => await engine.HandleRequest(request));
// Then
exception.ShouldBeOfType<OperationCanceledException>();
}
}
public class PreExecuteFailureResponse : Response
{
public override Task PreExecute(NancyContext context)
{
return TaskHelpers.GetFaultedTask<object>(new InvalidOperationException());
}
}
}
| |
using System;
using XPlatUtils;
namespace Toggl.Phoebe.Logging
{
public abstract class BaseLogger : ILogger
{
private readonly LogLevel threshold;
private readonly LogLevel consoleThreshold;
protected BaseLogger ()
{
#if DEBUG
threshold = LogLevel.Debug;
consoleThreshold = LogLevel.Debug;
#else
threshold = LogLevel.Info;
consoleThreshold = LogLevel.Warning;
#endif
}
protected BaseLogger (LogLevel threshold)
{
this.threshold = threshold;
}
private void Process (LogLevel level, string tag, string message, Exception exc = null)
{
LogToConsole (level, tag, message, exc);
LogToFile (level, tag, message, exc);
LogToLoggerClient (level, tag, message, exc);
}
private void LogToConsole (LogLevel level, string tag, string message, Exception exc)
{
if (level < consoleThreshold) {
return;
}
WriteConsole (level, tag, message, exc);
}
private void LogToFile (LogLevel level, string tag, string message, Exception exc)
{
var logStore = ServiceContainer.Resolve<LogStore> ();
if (logStore != null) {
logStore.Record (level, tag, message, exc);
}
}
private void LogToLoggerClient (LogLevel level, string tag, string message, Exception exc)
{
if (level >= LogLevel.Warning) {
ErrorSeverity severity;
switch (level) {
case LogLevel.Warning:
severity = ErrorSeverity.Warning;
break;
case LogLevel.Error:
severity = ErrorSeverity.Error;
break;
default:
severity = ErrorSeverity.Info;
break;
}
var md = new Metadata ();
md.AddToTab ("Logger", "Tag", tag);
md.AddToTab ("Logger", "Message", message);
AddExtraMetadata (md);
var loggerClient = ServiceContainer.Resolve<ILoggerClient> ();
if (loggerClient != null) {
loggerClient.Notify (exc, severity, md);
}
}
}
protected abstract void AddExtraMetadata (Metadata md);
protected virtual void WriteConsole (LogLevel level, string tag, string message, Exception exc)
{
Console.WriteLine ("[{1}] {0}: {2}", level, tag, message);
if (exc != null) {
Console.WriteLine (exc.ToString ());
}
}
public void Debug (string tag, string message)
{
if (threshold > LogLevel.Debug) {
return;
}
Process (LogLevel.Debug, tag, message);
}
public void Debug (string tag, string message, object arg0)
{
if (threshold > LogLevel.Debug) {
return;
}
Process (LogLevel.Debug, tag, String.Format (message, arg0));
}
public void Debug (string tag, string message, object arg0, object arg1)
{
if (threshold > LogLevel.Debug) {
return;
}
Process (LogLevel.Debug, tag, String.Format (message, arg0, arg1));
}
public void Debug (string tag, string message, object arg0, object arg1, object arg2)
{
if (threshold > LogLevel.Debug) {
return;
}
Process (LogLevel.Debug, tag, String.Format (message, arg0, arg1, arg2));
}
public void Debug (string tag, string message, params object[] args)
{
if (threshold > LogLevel.Debug) {
return;
}
Process (LogLevel.Debug, tag, String.Format (message, args));
}
public void Debug (string tag, Exception exc, string message)
{
if (threshold > LogLevel.Debug) {
return;
}
Process (LogLevel.Debug, tag, message, exc);
}
public void Debug (string tag, Exception exc, string message, object arg0)
{
if (threshold > LogLevel.Debug) {
return;
}
Process (LogLevel.Debug, tag, String.Format (message, arg0), exc);
}
public void Debug (string tag, Exception exc, string message, object arg0, object arg1)
{
if (threshold > LogLevel.Debug) {
return;
}
Process (LogLevel.Debug, tag, String.Format (message, arg0, arg1), exc);
}
public void Debug (string tag, Exception exc, string message, object arg0, object arg1, object arg2)
{
if (threshold > LogLevel.Debug) {
return;
}
Process (LogLevel.Debug, tag, String.Format (message, arg0, arg1, arg2), exc);
}
public void Debug (string tag, Exception exc, string message, params object[] args)
{
if (threshold > LogLevel.Debug) {
return;
}
Process (LogLevel.Debug, tag, String.Format (message, args), exc);
}
public void Info (string tag, string message)
{
if (threshold > LogLevel.Info) {
return;
}
Process (LogLevel.Info, tag, message);
}
public void Info (string tag, string message, object arg0)
{
if (threshold > LogLevel.Info) {
return;
}
Process (LogLevel.Info, tag, String.Format (message, arg0));
}
public void Info (string tag, string message, object arg0, object arg1)
{
if (threshold > LogLevel.Info) {
return;
}
Process (LogLevel.Info, tag, String.Format (message, arg0, arg1));
}
public void Info (string tag, string message, object arg0, object arg1, object arg2)
{
if (threshold > LogLevel.Info) {
return;
}
Process (LogLevel.Info, tag, String.Format (message, arg0, arg1, arg2));
}
public void Info (string tag, string message, params object[] args)
{
if (threshold > LogLevel.Info) {
return;
}
Process (LogLevel.Info, tag, String.Format (message, args));
}
public void Info (string tag, Exception exc, string message)
{
if (threshold > LogLevel.Info) {
return;
}
Process (LogLevel.Info, tag, message, exc);
}
public void Info (string tag, Exception exc, string message, object arg0)
{
if (threshold > LogLevel.Info) {
return;
}
Process (LogLevel.Info, tag, String.Format (message, arg0), exc);
}
public void Info (string tag, Exception exc, string message, object arg0, object arg1)
{
if (threshold > LogLevel.Info) {
return;
}
Process (LogLevel.Info, tag, String.Format (message, arg0, arg1), exc);
}
public void Info (string tag, Exception exc, string message, object arg0, object arg1, object arg2)
{
if (threshold > LogLevel.Info) {
return;
}
Process (LogLevel.Info, tag, String.Format (message, arg0, arg1, arg2), exc);
}
public void Info (string tag, Exception exc, string message, params object[] args)
{
if (threshold > LogLevel.Info) {
return;
}
Process (LogLevel.Info, tag, String.Format (message, args), exc);
}
public void Warning (string tag, string message)
{
if (threshold > LogLevel.Warning) {
return;
}
Process (LogLevel.Warning, tag, message);
}
public void Warning (string tag, string message, object arg0)
{
if (threshold > LogLevel.Warning) {
return;
}
Process (LogLevel.Warning, tag, String.Format (message, arg0));
}
public void Warning (string tag, string message, object arg0, object arg1)
{
if (threshold > LogLevel.Warning) {
return;
}
Process (LogLevel.Warning, tag, String.Format (message, arg0, arg1));
}
public void Warning (string tag, string message, object arg0, object arg1, object arg2)
{
if (threshold > LogLevel.Warning) {
return;
}
Process (LogLevel.Warning, tag, String.Format (message, arg0, arg1, arg2));
}
public void Warning (string tag, string message, params object[] args)
{
if (threshold > LogLevel.Warning) {
return;
}
Process (LogLevel.Warning, tag, String.Format (message, args));
}
public void Warning (string tag, Exception exc, string message)
{
if (threshold > LogLevel.Warning) {
return;
}
Process (LogLevel.Warning, tag, message, exc);
}
public void Warning (string tag, Exception exc, string message, object arg0)
{
if (threshold > LogLevel.Warning) {
return;
}
Process (LogLevel.Warning, tag, String.Format (message, arg0), exc);
}
public void Warning (string tag, Exception exc, string message, object arg0, object arg1)
{
if (threshold > LogLevel.Warning) {
return;
}
Process (LogLevel.Warning, tag, String.Format (message, arg0, arg1), exc);
}
public void Warning (string tag, Exception exc, string message, object arg0, object arg1, object arg2)
{
if (threshold > LogLevel.Warning) {
return;
}
Process (LogLevel.Warning, tag, String.Format (message, arg0, arg1, arg2), exc);
}
public void Warning (string tag, Exception exc, string message, params object[] args)
{
if (threshold > LogLevel.Warning) {
return;
}
Process (LogLevel.Warning, tag, String.Format (message, args), exc);
}
public void Error (string tag, string message)
{
if (threshold > LogLevel.Error) {
return;
}
Process (LogLevel.Error, tag, message);
}
public void Error (string tag, string message, object arg0)
{
if (threshold > LogLevel.Error) {
return;
}
Process (LogLevel.Error, tag, String.Format (message, arg0));
}
public void Error (string tag, string message, object arg0, object arg1)
{
if (threshold > LogLevel.Error) {
return;
}
Process (LogLevel.Error, tag, String.Format (message, arg0, arg1));
}
public void Error (string tag, string message, object arg0, object arg1, object arg2)
{
if (threshold > LogLevel.Error) {
return;
}
Process (LogLevel.Error, tag, String.Format (message, arg0, arg1, arg2));
}
public void Error (string tag, string message, params object[] args)
{
if (threshold > LogLevel.Error) {
return;
}
Process (LogLevel.Error, tag, String.Format (message, args));
}
public void Error (string tag, Exception exc, string message)
{
if (threshold > LogLevel.Error) {
return;
}
Process (LogLevel.Error, tag, message, exc);
}
public void Error (string tag, Exception exc, string message, object arg0)
{
if (threshold > LogLevel.Error) {
return;
}
Process (LogLevel.Error, tag, String.Format (message, arg0), exc);
}
public void Error (string tag, Exception exc, string message, object arg0, object arg1)
{
if (threshold > LogLevel.Error) {
return;
}
Process (LogLevel.Error, tag, String.Format (message, arg0, arg1), exc);
}
public void Error (string tag, Exception exc, string message, object arg0, object arg1, object arg2)
{
if (threshold > LogLevel.Error) {
return;
}
Process (LogLevel.Error, tag, String.Format (message, arg0, arg1, arg2), exc);
}
public void Error (string tag, Exception exc, string message, params object[] args)
{
if (threshold > LogLevel.Error) {
return;
}
Process (LogLevel.Error, tag, String.Format (message, args), exc);
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="PrologOperatorTable.cs" company="Axiom">
//
// Copyright (c) 2006 Ali Hodroj. All rights reserved.
//
// The use and distribution terms for this source code are contained in the file
// named license.txt, which can be found in the root of this distribution.
// By using this software in any fashion, you are agreeing to be bound by the
// terms of this license.
//
// You must not remove this notice, or any other, from this software.
//
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Collections;
using System.IO;
using Axiom.Compiler.CodeObjectModel;
namespace Axiom.Compiler.Framework
{
/// <summary>
/// Summary description for PrologCodeParser.
/// </summary>
public class PrologOperatorTable
{
private Hashtable _operatorTable = new Hashtable();
public PrologOperatorTable()
{
}
public void Initialize()
{
/* xfx */
AddInfixOperator(":-", false, false, 1200);
AddInfixOperator("-->", false, false, 1200);
AddInfixOperator("<=", false, false, 1190);
AddInfixOperator("<->", false, false, 1190);
AddInfixOperator("<-", false, false, 1190);
AddInfixOperator("until", false, false, 990);
AddInfixOperator("unless", false, false, 990);
AddInfixOperator("from", false, false, 800);
AddInfixOperator("=:=", false, false, 700);
AddInfixOperator("=\\=", false, false, 700);
AddInfixOperator("<", false, false, 700);
AddInfixOperator(">=", false, false, 700);
AddInfixOperator(">", false, false, 700);
AddInfixOperator("=<", false, false, 700);
AddInfixOperator("is", false, false, 700);
AddInfixOperator("=..", false, false, 700);
AddInfixOperator("==", false, false, 700);
AddInfixOperator("\\==", false, false, 700);
AddInfixOperator("=", false, false, 700);
AddInfixOperator("\\=", false, false, 700);
AddInfixOperator("@<", false, false, 700);
AddInfixOperator("@>=", false, false, 700);
AddInfixOperator("@>", false, false, 700);
AddInfixOperator("@=<", false, false, 700);
AddInfixOperator("mod", false, false, 300);
AddInfixOperator(":", false, false, 300);
/* xfy */
AddInfixOperator(",", false, true, 1000);
AddInfixOperator(";", false, true, 1100);
AddInfixOperator("->", false, true, 1050);
AddInfixOperator(".", false, true, 999);
AddInfixOperator(">>", false, true, 400);
AddInfixOperator("^", false, true, 200);
/* yfx */
AddInfixOperator("+", true, false, 500);
AddInfixOperator("-", true, false, 500);
AddInfixOperator("\\/", true, false, 500);
AddInfixOperator("/\\", true, false, 500);
AddInfixOperator("*", true, false, 400);
AddInfixOperator("/", true, false, 400);
AddInfixOperator("div", true, false, 400);
AddInfixOperator("//", true, false, 400);
AddInfixOperator("<<", true, false, 400);
/* fx */
AddPrefixOperator(":-", false, 1200);
AddPrefixOperator("?-", false, 1200);
AddPrefixOperator("gen", false, 990);
AddPrefixOperator("try", false, 980);
AddPrefixOperator("once", false, 970);
AddPrefixOperator("possible", false, 970);
AddPrefixOperator("side_effects", false, 970);
AddPrefixOperator("unit", false, 900);
AddPrefixOperator("visible", false, 900);
AddPrefixOperator("import", false, 900);
AddPrefixOperator("foreign", false, 900);
AddPrefixOperator("using", false, 900);
AddPrefixOperator("push", false, 900);
AddPrefixOperator("down", false, 900);
AddPrefixOperator("set", false, 900);
AddPrefixOperator("dynamic", false, 900);
AddPrefixOperator("+", false, 500);
AddPrefixOperator("-", false, 500);
AddPrefixOperator("\\", false, 500);
AddPrefixOperator("@", false, 10);
AddPrefixOperator("@@", false, 10);
/* fy */
AddPrefixOperator("not", true, 980);
AddPrefixOperator("\\+", true, 980);
AddPrefixOperator("spy", true, 900);
AddPrefixOperator("nospy", true, 900);
AddPrefixOperator("?", true, 800);
AddPrefixOperator(">", true, 700);
AddPrefixOperator("<", true, 700);
/* xf */
//AddPostfixOp("!", false, 999) ;
AddPostfixOperator("#", false, 999);
}
public void RemoveOperator(string name)
{
if (_operatorTable.ContainsKey(name))
{
_operatorTable.Remove(name);
}
}
public void AddInfixOperator(string name, bool left, bool right, int precedence)
{
PrologOperator op = null;
if (IsOperator(name))
{
op = GetOperator(name);
op.InfixPrecedence = precedence;
op.IsInfixLeftAssociative = left;
op.IsInfixRightAssociative = right;
}
else
{
op = new PrologOperator(name, 0, 0, precedence);
op.IsInfixLeftAssociative = left;
op.IsInfixRightAssociative = right;
_operatorTable.Add(name, op);
}
}
public void AddPrefixOperator(string name, bool left, int precedence)
{
PrologOperator op = null;
if (IsOperator(name))
{
op = GetOperator(name);
op.PrefixPrecedence = precedence;
op.IsPrefixAssociative = left;
}
else
{
op = new PrologOperator(name, precedence, 0, 0);
op.IsPrefixAssociative = left;
_operatorTable.Add(name, op);
}
}
public void AddPostfixOperator(string name, bool right, int precedence)
{
PrologOperator op = null;
if (IsOperator(name))
{
op = GetOperator(name);
op.PostfixPrecedence = precedence;
op.IsPostfixAssociative = right;
}
else
{
op = new PrologOperator(name, 0, precedence, 0);
op.IsPrefixAssociative = right;
_operatorTable.Add(name, op);
}
}
public bool IsOperator(string name)
{
return _operatorTable.ContainsKey(name);
}
public PrologOperator GetOperator(string name)
{
return (PrologOperator)_operatorTable[name];
}
public bool ExclusivelyPrefix(string name)
{
if (IsOperator(name))
{
return true;
}
PrologOperator op = GetOperator(name);
if (op != null)
{
return op.PostfixPrecedence == -1;
}
return false;
}
}
}
| |
//
// 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.Linq;
using System.Net.Http;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.SiteRecovery;
namespace Microsoft.Azure.Management.SiteRecovery
{
public partial class SiteRecoveryManagementClient : ServiceClient<SiteRecoveryManagementClient>, ISiteRecoveryManagementClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private string _cloudServiceName;
public string CloudServiceName
{
get { return this._cloudServiceName; }
set { this._cloudServiceName = value; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private string _resourceGroupName;
public string ResourceGroupName
{
get { return this._resourceGroupName; }
set { this._resourceGroupName = value; }
}
private string _resourceName;
public string ResourceName
{
get { return this._resourceName; }
set { this._resourceName = value; }
}
private IJobOperations _jobs;
/// <summary>
/// Definition for Job Operations.
/// </summary>
public virtual IJobOperations Jobs
{
get { return this._jobs; }
}
private IProtectionContainerOperations _protectionContainer;
/// <summary>
/// Definition of Protection Container operations for the Site Recovery
/// extension.
/// </summary>
public virtual IProtectionContainerOperations ProtectionContainer
{
get { return this._protectionContainer; }
}
private IProtectionEntityOperations _protectionEntity;
/// <summary>
/// Definition of protection entity operations for the Site Recovery
/// extension.
/// </summary>
public virtual IProtectionEntityOperations ProtectionEntity
{
get { return this._protectionEntity; }
}
private IProtectionProfileOperations _protectionProfile;
/// <summary>
/// Definition of Protection Profile operations for the Site Recovery
/// extension.
/// </summary>
public virtual IProtectionProfileOperations ProtectionProfile
{
get { return this._protectionProfile; }
}
private IRecoveryPlanOperations _recoveryPlan;
/// <summary>
/// Definition of recoveryplan operations for the Site Recovery
/// extension.
/// </summary>
public virtual IRecoveryPlanOperations RecoveryPlan
{
get { return this._recoveryPlan; }
}
private IServerOperations _servers;
/// <summary>
/// Definition of server operations for the Site Recovery extension.
/// </summary>
public virtual IServerOperations Servers
{
get { return this._servers; }
}
/// <summary>
/// Initializes a new instance of the SiteRecoveryManagementClient
/// class.
/// </summary>
public SiteRecoveryManagementClient()
: base()
{
this._jobs = new JobOperations(this);
this._protectionContainer = new ProtectionContainerOperations(this);
this._protectionEntity = new ProtectionEntityOperations(this);
this._protectionProfile = new ProtectionProfileOperations(this);
this._recoveryPlan = new RecoveryPlanOperations(this);
this._servers = new ServerOperations(this);
this._apiVersion = "2015-01-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the SiteRecoveryManagementClient
/// class.
/// </summary>
/// <param name='cloudServiceName'>
/// Required.
/// </param>
/// <param name='resourceName'>
/// Required.
/// </param>
/// <param name='resourceGroupName'>
/// Required.
/// </param>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public SiteRecoveryManagementClient(string cloudServiceName, string resourceName, string resourceGroupName, SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (resourceName == null)
{
throw new ArgumentNullException("resourceName");
}
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._cloudServiceName = cloudServiceName;
this._resourceName = resourceName;
this._resourceGroupName = resourceGroupName;
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SiteRecoveryManagementClient
/// class.
/// </summary>
/// <param name='cloudServiceName'>
/// Required.
/// </param>
/// <param name='resourceName'>
/// Required.
/// </param>
/// <param name='resourceGroupName'>
/// Required.
/// </param>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public SiteRecoveryManagementClient(string cloudServiceName, string resourceName, string resourceGroupName, SubscriptionCloudCredentials credentials)
: this()
{
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (resourceName == null)
{
throw new ArgumentNullException("resourceName");
}
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._cloudServiceName = cloudServiceName;
this._resourceName = resourceName;
this._resourceGroupName = resourceGroupName;
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SiteRecoveryManagementClient
/// class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
public SiteRecoveryManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._jobs = new JobOperations(this);
this._protectionContainer = new ProtectionContainerOperations(this);
this._protectionEntity = new ProtectionEntityOperations(this);
this._protectionProfile = new ProtectionProfileOperations(this);
this._recoveryPlan = new RecoveryPlanOperations(this);
this._servers = new ServerOperations(this);
this._apiVersion = "2015-01-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the SiteRecoveryManagementClient
/// class.
/// </summary>
/// <param name='cloudServiceName'>
/// Required.
/// </param>
/// <param name='resourceName'>
/// Required.
/// </param>
/// <param name='resourceGroupName'>
/// Required.
/// </param>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public SiteRecoveryManagementClient(string cloudServiceName, string resourceName, string resourceGroupName, SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (resourceName == null)
{
throw new ArgumentNullException("resourceName");
}
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._cloudServiceName = cloudServiceName;
this._resourceName = resourceName;
this._resourceGroupName = resourceGroupName;
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the SiteRecoveryManagementClient
/// class.
/// </summary>
/// <param name='cloudServiceName'>
/// Required.
/// </param>
/// <param name='resourceName'>
/// Required.
/// </param>
/// <param name='resourceGroupName'>
/// Required.
/// </param>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public SiteRecoveryManagementClient(string cloudServiceName, string resourceName, string resourceGroupName, SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (cloudServiceName == null)
{
throw new ArgumentNullException("cloudServiceName");
}
if (resourceName == null)
{
throw new ArgumentNullException("resourceName");
}
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._cloudServiceName = cloudServiceName;
this._resourceName = resourceName;
this._resourceGroupName = resourceGroupName;
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// SiteRecoveryManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of SiteRecoveryManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<SiteRecoveryManagementClient> client)
{
base.Clone(client);
if (client is SiteRecoveryManagementClient)
{
SiteRecoveryManagementClient clonedClient = ((SiteRecoveryManagementClient)client);
clonedClient._cloudServiceName = this._cloudServiceName;
clonedClient._resourceName = this._resourceName;
clonedClient._resourceGroupName = this._resourceGroupName;
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
// URLString
//
//
// Implementation of membership condition for zones
//
namespace System.Security.Util {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Runtime.Serialization;
using System.Globalization;
using System.Text;
using System.IO;
using System.Diagnostics.Contracts;
[Serializable]
internal sealed class URLString : SiteString
{
private String m_protocol;
[OptionalField(VersionAdded = 2)]
private String m_userpass;
private SiteString m_siteString;
private int m_port;
#if !PLATFORM_UNIX
private LocalSiteString m_localSite;
#endif // !PLATFORM_UNIX
private DirectoryString m_directory;
private const String m_defaultProtocol = "file";
[OptionalField(VersionAdded = 2)]
private bool m_parseDeferred;
[OptionalField(VersionAdded = 2)]
private String m_urlOriginal;
[OptionalField(VersionAdded = 2)]
private bool m_parsedOriginal;
[OptionalField(VersionAdded = 3)]
private bool m_isUncShare;
// legacy field from v1.x, not used in v2 and beyond. Retained purely for serialization compatibility.
private String m_fullurl;
[OnDeserialized]
public void OnDeserialized(StreamingContext ctx)
{
if (m_urlOriginal == null)
{
// pre-v2 deserialization. Need to fix-up fields here
m_parseDeferred = false;
m_parsedOriginal = false; // Dont care what this value is - never used
m_userpass = "";
m_urlOriginal = m_fullurl;
m_fullurl = null;
}
}
[OnSerializing]
private void OnSerializing(StreamingContext ctx)
{
if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
{
DoDeferredParse();
m_fullurl = m_urlOriginal;
}
}
[OnSerialized]
private void OnSerialized(StreamingContext ctx)
{
if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0)
{
m_fullurl = null;
}
}
public URLString()
{
m_protocol = "";
m_userpass = "";
m_siteString = new SiteString();
m_port = -1;
#if !PLATFORM_UNIX
m_localSite = null;
#endif // !PLATFORM_UNIX
m_directory = new DirectoryString();
m_parseDeferred = false;
}
private void DoDeferredParse()
{
if (m_parseDeferred)
{
ParseString(m_urlOriginal, m_parsedOriginal);
m_parseDeferred = false;
}
}
public URLString(string url) : this(url, false, false) {}
public URLString(string url, bool parsed) : this(url, parsed, false) {}
internal URLString(string url, bool parsed, bool doDeferredParsing)
{
m_port = -1;
m_userpass = "";
DoFastChecks(url);
m_urlOriginal = url;
m_parsedOriginal = parsed;
m_parseDeferred = true;
if (doDeferredParsing)
DoDeferredParse();
}
// Converts %XX and %uYYYY to the actual characters (I.e. Unesacpes any escape characters present in the URL)
private String UnescapeURL(String url)
{
StringBuilder intermediate = StringBuilderCache.Acquire(url.Length);
int Rindex = 0; // index into temp that gives the rest of the string to be processed
int index;
int braIndex = -1;
int ketIndex = -1;
braIndex = url.IndexOf('[',Rindex);
if (braIndex != -1)
ketIndex = url.IndexOf(']', braIndex);
do
{
index = url.IndexOf( '%', Rindex);
if (index == -1)
{
intermediate = intermediate.Append(url, Rindex, (url.Length - Rindex));
break;
}
// if we hit a '%' in the middle of an IPv6 address, dont process that
if (index > braIndex && index < ketIndex)
{
intermediate = intermediate.Append(url, Rindex, (ketIndex - Rindex+1));
Rindex = ketIndex+1;
continue;
}
if (url.Length - index < 2) // Check that there is at least 1 char after the '%'
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
if (url[index+1] == 'u' || url[index+1] == 'U')
{
if (url.Length - index < 6) // example: "%u004d" is 6 chars long
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
// We have a unicode character specified in hex
try
{
char c = (char)(Hex.ConvertHexDigit( url[index+2] ) << 12 |
Hex.ConvertHexDigit( url[index+3] ) << 8 |
Hex.ConvertHexDigit( url[index+4] ) << 4 |
Hex.ConvertHexDigit( url[index+5] ));
intermediate = intermediate.Append(url, Rindex, index - Rindex);
intermediate = intermediate.Append(c);
}
catch(ArgumentException) // Hex.ConvertHexDigit can throw an "out of range" ArgumentException
{
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
}
Rindex = index + 6 ; //update the 'seen' length
}
else
{
// we have a hex character.
if (url.Length - index < 3) // example: "%4d" is 3 chars long
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
try
{
char c = (char)(Hex.ConvertHexDigit( url[index+1] ) << 4 | Hex.ConvertHexDigit( url[index+2] ));
intermediate = intermediate.Append(url, Rindex, index - Rindex);
intermediate = intermediate.Append(c);
}
catch(ArgumentException) // Hex.ConvertHexDigit can throw an "out of range" ArgumentException
{
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
}
Rindex = index + 3; // update the 'seen' length
}
}
while (true);
return StringBuilderCache.GetStringAndRelease(intermediate);
}
// Helper Function for ParseString:
// Search for the end of the protocol info and grab the actual protocol string
// ex. http://www.microsoft.com/complus would have a protocol string of http
private String ParseProtocol(String url)
{
String temp;
int index = url.IndexOf( ':' );
if (index == 0)
{
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
}
else if (index == -1)
{
m_protocol = m_defaultProtocol;
temp = url;
}
else if (url.Length > index + 1)
{
if (index == m_defaultProtocol.Length &&
String.Compare(url, 0, m_defaultProtocol, 0, index, StringComparison.OrdinalIgnoreCase) == 0)
{
m_protocol = m_defaultProtocol;
temp = url.Substring( index + 1 );
// Since an explicit file:// URL could be immediately followed by a host name, we will be
// conservative and assume that it is on a share rather than a potentally relative local
// URL.
m_isUncShare = true;
}
else if (url[index+1] != '\\')
{
#if !PLATFORM_UNIX
if (url.Length > index + 2 &&
url[index+1] == '/' &&
url[index+2] == '/')
#else
if (url.Length > index + 1 &&
url[index+1] == '/' ) // UNIX style "file:/home/me" is allowed, so account for that
#endif // !PLATFORM_UNIX
{
m_protocol = url.Substring( 0, index );
for (int i = 0; i < m_protocol.Length; ++i)
{
char c = m_protocol[i];
if ((c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') ||
(c == '+') ||
(c == '.') ||
(c == '-'))
{
continue;
}
else
{
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
}
}
#if !PLATFORM_UNIX
temp = url.Substring( index + 3 );
#else
// In UNIX, we don't know how many characters we'll have to skip past.
// Skip past \, /, and :
//
for ( int j=index ; j<url.Length ; j++ )
{
if ( url[j] != '\\' && url[j] != '/' && url[j] != ':' )
{
index = j;
break;
}
}
temp = url.Substring( index );
#endif // !PLATFORM_UNIX
}
else
{
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
}
}
else
{
m_protocol = m_defaultProtocol;
temp = url;
}
}
else
{
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
}
return temp;
}
private String ParsePort(String url)
{
String temp = url;
char[] separators = new char[] { ':', '/' };
int Rindex = 0;
int userpassIndex = temp.IndexOf('@');
if (userpassIndex != -1) {
if (temp.IndexOf('/',0,userpassIndex) == -1) {
// this is a user:pass type of string
m_userpass = temp.Substring(0,userpassIndex);
Rindex = userpassIndex + 1;
}
}
int braIndex = -1;
int ketIndex = -1;
int portIndex = -1;
braIndex = url.IndexOf('[',Rindex);
if (braIndex != -1)
ketIndex = url.IndexOf(']', braIndex);
if (ketIndex != -1)
{
// IPv6 address...ignore the IPv6 block when searching for the port
portIndex = temp.IndexOfAny(separators,ketIndex);
}
else
{
portIndex = temp.IndexOfAny(separators,Rindex);
}
if (portIndex != -1 && temp[portIndex] == ':')
{
// make sure it really is a port, and has a number after the :
if ( temp[portIndex+1] >= '0' && temp[portIndex+1] <= '9' )
{
int tempIndex = temp.IndexOf( '/', Rindex);
if (tempIndex == -1)
{
m_port = Int32.Parse( temp.Substring(portIndex + 1), CultureInfo.InvariantCulture );
if (m_port < 0)
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
temp = temp.Substring( Rindex, portIndex - Rindex );
}
else if (tempIndex > portIndex)
{
m_port = Int32.Parse( temp.Substring(portIndex + 1, tempIndex - portIndex - 1), CultureInfo.InvariantCulture );
temp = temp.Substring( Rindex, portIndex - Rindex ) + temp.Substring( tempIndex );
}
else
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
}
else
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
}
else {
// Chop of the user/pass portion if any
temp = temp.Substring(Rindex);
}
return temp;
}
// This does three things:
// 1. It makes the following modifications to the start of the string:
// a. \\?\ and \\?/ => <empty>
// b. \\.\ and \\./ => <empty>
// 2. If isFileUrl is true, converts all slashes to front slashes and strips leading
// front slashes. See comment by code.
// 3. Throws a PathTooLongException if the length of the resulting URL is >= MAX_PATH.
// This is done to prevent security issues due to canonicalization truncations.
// Remove this method when the Path class supports "\\?\"
internal static String PreProcessForExtendedPathRemoval(String url, bool isFileUrl)
{
bool uncShare = false;
return PreProcessForExtendedPathRemoval(url, isFileUrl, ref uncShare);
}
private static String PreProcessForExtendedPathRemoval(String url, bool isFileUrl, ref bool isUncShare)
{
// This is the modified URL that we will return
StringBuilder modifiedUrl = new StringBuilder(url);
// ITEM 1 - remove extended path characters.
{
// Keep track of where we are in both the comparison and altered strings.
int curCmpIdx = 0;
int curModIdx = 0;
// If all the '\' have already been converted to '/', just check for //?/ or //./
if ((url.Length - curCmpIdx) >= 4 &&
(String.Compare(url, curCmpIdx, "//?/", 0, 4, StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(url, curCmpIdx, "//./", 0, 4, StringComparison.OrdinalIgnoreCase) == 0))
{
modifiedUrl.Remove(curModIdx, 4);
curCmpIdx += 4;
}
else
{
if (isFileUrl) {
// We need to handle an indefinite number of leading front slashes for file URLs since we could
// get something like:
// file://\\?\
// file:/\\?\
// file:\\?\
// etc...
while (url[curCmpIdx] == '/')
{
curCmpIdx++;
curModIdx++;
}
}
// Remove the extended path characters
if ((url.Length - curCmpIdx) >= 4 &&
(String.Compare(url, curCmpIdx, "\\\\?\\", 0, 4, StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(url, curCmpIdx, "\\\\?/", 0, 4, StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(url, curCmpIdx, "\\\\.\\", 0, 4, StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(url, curCmpIdx, "\\\\./", 0, 4, StringComparison.OrdinalIgnoreCase) == 0))
{
modifiedUrl.Remove(curModIdx, 4);
curCmpIdx += 4;
}
}
}
// ITEM 2 - convert all slashes to forward slashes, and strip leading slashes.
if (isFileUrl)
{
int slashCount = 0;
bool seenFirstBackslash = false;
while (slashCount < modifiedUrl.Length && (modifiedUrl[slashCount] == '/' || modifiedUrl[slashCount] == '\\'))
{
// Look for sets of consecutive backslashes. We can't just look for these at the start
// of the string, since file:// might come first. Instead, once we see the first \, look
// for a second one following it.
if (!seenFirstBackslash && modifiedUrl[slashCount] == '\\')
{
seenFirstBackslash = true;
if (slashCount + 1 < modifiedUrl.Length && modifiedUrl[slashCount + 1] == '\\')
isUncShare = true;
}
slashCount++;
}
modifiedUrl.Remove(0, slashCount);
modifiedUrl.Replace('\\', '/');
}
// ITEM 3 - If the path is greater than or equal (due to terminating NULL in windows) MAX_PATH, we throw.
if (modifiedUrl.Length >= Path.MaxPath)
{
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
}
// Create the result string from the StringBuilder
return modifiedUrl.ToString();
}
// Do any misc massaging of data in the URL
private String PreProcessURL(String url, bool isFileURL)
{
#if !PLATFORM_UNIX
if (isFileURL) {
// Remove when the Path class supports "\\?\"
url = PreProcessForExtendedPathRemoval(url, true, ref m_isUncShare);
}
else {
url = url.Replace('\\', '/');
}
return url;
#else
// Remove superfluous '/'
// For UNIX, the file path would look something like:
// file:///home/johndoe/here
// file:/home/johndoe/here
// file:../johndoe/here
// file:~/johndoe/here
String temp = url;
int nbSlashes = 0;
while(nbSlashes<temp.Length && '/'==temp[nbSlashes])
nbSlashes++;
// if we get a path like file:///directory/name we need to convert
// this to /directory/name.
if(nbSlashes > 2)
temp = temp.Substring(nbSlashes-1, temp.Length - (nbSlashes-1));
else if (2 == nbSlashes) /* it's a relative path */
temp = temp.Substring(nbSlashes, temp.Length - nbSlashes);
return temp;
#endif // !PLATFORM_UNIX
}
private void ParseFileURL(String url)
{
String temp = url;
#if !PLATFORM_UNIX
int index = temp.IndexOf( '/');
if (index != -1 &&
((index == 2 &&
temp[index-1] != ':' &&
temp[index-1] != '|') ||
index != 2) &&
index != temp.Length - 1)
{
// Also, if it is a UNC share, we want m_localSite to
// be of the form "computername/share", so if the first
// fileEnd character found is a slash, do some more parsing
// to find the proper end character.
int tempIndex = temp.IndexOf( '/', index+1);
if (tempIndex != -1)
index = tempIndex;
else
index = -1;
}
String localSite;
if (index == -1)
localSite = temp;
else
localSite = temp.Substring(0,index);
if (localSite.Length == 0)
throw new ArgumentException( Environment.GetResourceString( "Argument_InvalidUrl" ) );
int i;
bool spacesAllowed;
if (localSite[0] == '\\' && localSite[1] == '\\')
{
spacesAllowed = true;
i = 2;
}
else
{
i = 0;
spacesAllowed = false;
}
bool useSmallCharToUpper = true;
for (; i < localSite.Length; ++i)
{
char c = localSite[i];
if ((c >= 'A' && c <= 'Z') ||
(c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9') ||
(c == '-') || (c == '/') ||
(c == ':') || (c == '|') ||
(c == '.') || (c == '*') ||
(c == '$') || (spacesAllowed && c == ' '))
{
continue;
}
else
{
useSmallCharToUpper = false;
break;
}
}
if (useSmallCharToUpper)
localSite = String.SmallCharToUpper( localSite );
else
localSite = localSite.ToUpper(CultureInfo.InvariantCulture);
m_localSite = new LocalSiteString( localSite );
if (index == -1)
{
if (localSite[localSite.Length-1] == '*')
m_directory = new DirectoryString( "*", false );
else
m_directory = new DirectoryString();
}
else
{
String directoryString = temp.Substring( index + 1 );
if (directoryString.Length == 0)
{
m_directory = new DirectoryString();
}
else
{
m_directory = new DirectoryString( directoryString, true);
}
}
#else // !PLATFORM_UNIX
m_directory = new DirectoryString( temp, true);
#endif // !PLATFORM_UNIX
m_siteString = null;
return;
}
private void ParseNonFileURL(String url)
{
String temp = url;
int index = temp.IndexOf('/');
if (index == -1)
{
#if !PLATFORM_UNIX
m_localSite = null; // for drive letter
#endif // !PLATFORM_UNIX
m_siteString = new SiteString( temp );
m_directory = new DirectoryString();
}
else
{
#if !PLATFORM_UNIX
String site = temp.Substring( 0, index );
m_localSite = null;
m_siteString = new SiteString( site );
String directoryString = temp.Substring( index + 1 );
if (directoryString.Length == 0)
{
m_directory = new DirectoryString();
}
else
{
m_directory = new DirectoryString( directoryString, false );
}
#else
String directoryString = temp.Substring( index + 1 );
String site = temp.Substring( 0, index );
m_directory = new DirectoryString( directoryString, false );
m_siteString = new SiteString( site );
#endif //!PLATFORM_UNIX
}
return;
}
void DoFastChecks( String url )
{
if (url == null)
{
throw new ArgumentNullException( "url" );
}
Contract.EndContractBlock();
if (url.Length == 0)
{
throw new FormatException(Environment.GetResourceString("Format_StringZeroLength"));
}
}
// NOTE:
// 1. We support URLs that follow the common Internet scheme syntax
// (<scheme>://user:pass@<host>:<port>/<url-path>) and all windows file URLs.
// 2. In the general case we parse of the site and create a SiteString out of it
// (which supports our wildcarding scheme). In the case of files we don't support
// wildcarding and furthermore SiteString doesn't like ':' and '|' which can appear
// in file urls so we just keep that info in a separate string and set the
// SiteString to null.
//
// ex. http://www.microsoft.com/complus -> m_siteString = "www.microsoft.com" m_localSite = null
// ex. file:///c:/complus/mscorlib.dll -> m_siteString = null m_localSite = "c:"
// ex. file:///c|/complus/mscorlib.dll -> m_siteString = null m_localSite = "c:"
void ParseString( String url, bool parsed )
{
// If there are any escaped hex or unicode characters in the url, translate those
// into the proper character.
if (!parsed)
{
url = UnescapeURL(url);
}
// Identify the protocol and strip the protocol info from the string, if present.
String temp = ParseProtocol(url);
bool fileProtocol = (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) == 0);
// handle any special preocessing...removing extra characters, etc.
temp = PreProcessURL(temp, fileProtocol);
if (fileProtocol)
{
ParseFileURL(temp);
}
else
{
// Check if there is a port number and parse that out.
temp = ParsePort(temp);
ParseNonFileURL(temp);
// Note: that we allow DNS and Netbios names for non-file protocols (since sitestring will check
// that the hostname satisfies these two protocols. DNS-only checking can theoretically be added
// here but that would break all the programs that use '_' (which is fairly common, yet illegal).
// If this needs to be done at any point, add a call to m_siteString.IsLegalDNSName().
}
}
public String Scheme
{
get
{
DoDeferredParse();
return m_protocol;
}
}
public String Host
{
get
{
DoDeferredParse();
if (m_siteString != null)
{
return m_siteString.ToString();
}
else
{
#if !PLATFORM_UNIX
return m_localSite.ToString();
#else
return "";
#endif // !PLATFORM_UNIX
}
}
}
public String Port
{
get
{
DoDeferredParse();
if (m_port == -1)
return null;
else
return m_port.ToString(CultureInfo.InvariantCulture);
}
}
public String Directory
{
get
{
DoDeferredParse();
return m_directory.ToString();
}
}
/// <summary>
/// Make a best guess at determining if this is URL refers to a file with a relative path. Since
/// this is a guess to help out users of UrlMembershipCondition who may accidentally supply a
/// relative URL, we'd rather err on the side of absolute than relative. (We'd rather accept some
/// meaningless membership conditions rather than reject meaningful ones).
///
/// In order to be a relative file URL, the URL needs to have a protocol of file, and not be on a
/// UNC share.
///
/// If both of the above are true, then the heuristics we'll use to detect an absolute URL are:
/// 1. A host name which is:
/// a. greater than one character and ends in a colon (representing the drive letter) OR
/// b. ends with a * (so we match any file with the given prefix if any)
/// 2. Has a directory name (cannot be simply file://c:)
/// </summary>
public bool IsRelativeFileUrl
{
get
{
DoDeferredParse();
if (String.Equals(m_protocol, "file", StringComparison.OrdinalIgnoreCase) && !m_isUncShare)
{
#if !PLATFORM_UNIX
string host = m_localSite != null ? m_localSite.ToString() : null;
// If the host name ends with the * character, treat this as an absolute URL since the *
// could represent the rest of the full path.
if (host.EndsWith('*'))
return false;
#endif // !PLATFORM_UNIX
string directory = m_directory != null ? m_directory.ToString() : null;
#if !PLATFORM_UNIX
return host == null || host.Length < 2 || !host.EndsWith(':') ||
String.IsNullOrEmpty(directory);
#else
return String.IsNullOrEmpty(directory);
#endif // !PLATFORM_UNIX
}
// Since this is not a local URL, it cannot be relative
return false;
}
}
public String GetFileName()
{
DoDeferredParse();
#if !PLATFORM_UNIX
if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) != 0)
return null;
String intermediateDirectory = this.Directory.Replace( '/', '\\' );
String directory = this.Host.Replace( '/', '\\' );
int directorySlashIndex = directory.IndexOf( '\\' );
if (directorySlashIndex == -1)
{
if (directory.Length != 2 ||
!(directory[1] == ':' || directory[1] == '|'))
{
directory = "\\\\" + directory;
}
}
else if (directorySlashIndex != 2 ||
(directorySlashIndex == 2 && directory[1] != ':' && directory[1] != '|'))
{
directory = "\\\\" + directory;
}
directory += "\\" + intermediateDirectory;
return directory;
#else
// In Unix, directory contains the full pathname
// (this is what we get in Win32)
if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase ) != 0)
return null;
return this.Directory;
#endif // !PLATFORM_UNIX
}
public String GetDirectoryName()
{
DoDeferredParse();
#if !PLATFORM_UNIX
if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase ) != 0)
return null;
String intermediateDirectory = this.Directory.Replace( '/', '\\' );
int slashIndex = 0;
for (int i = intermediateDirectory.Length; i > 0; i--)
{
if (intermediateDirectory[i-1] == '\\')
{
slashIndex = i;
break;
}
}
String directory = this.Host.Replace( '/', '\\' );
int directorySlashIndex = directory.IndexOf( '\\' );
if (directorySlashIndex == -1)
{
if (directory.Length != 2 ||
!(directory[1] == ':' || directory[1] == '|'))
{
directory = "\\\\" + directory;
}
}
else if (directorySlashIndex > 2 ||
(directorySlashIndex == 2 && directory[1] != ':' && directory[1] != '|'))
{
directory = "\\\\" + directory;
}
directory += "\\";
if (slashIndex > 0)
{
directory += intermediateDirectory.Substring( 0, slashIndex );
}
return directory;
#else
if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) != 0)
return null;
String directory = this.Directory.ToString();
int slashIndex = 0;
for (int i = directory.Length; i > 0; i--)
{
if (directory[i-1] == '/')
{
slashIndex = i;
break;
}
}
if (slashIndex > 0)
{
directory = directory.Substring( 0, slashIndex );
}
return directory;
#endif // !PLATFORM_UNIX
}
public override SiteString Copy()
{
return new URLString( m_urlOriginal, m_parsedOriginal );
}
public override bool IsSubsetOf( SiteString site )
{
if (site == null)
{
return false;
}
URLString url = site as URLString;
if (url == null)
{
return false;
}
DoDeferredParse();
url.DoDeferredParse();
URLString normalUrl1 = this.SpecialNormalizeUrl();
URLString normalUrl2 = url.SpecialNormalizeUrl();
if (String.Compare( normalUrl1.m_protocol, normalUrl2.m_protocol, StringComparison.OrdinalIgnoreCase) == 0 &&
normalUrl1.m_directory.IsSubsetOf( normalUrl2.m_directory ))
{
#if !PLATFORM_UNIX
if (normalUrl1.m_localSite != null)
{
// We do a little extra processing in here for local files since we allow
// both <drive_letter>: and <drive_letter>| forms of urls.
return normalUrl1.m_localSite.IsSubsetOf( normalUrl2.m_localSite );
}
else
#endif // !PLATFORM_UNIX
{
if (normalUrl1.m_port != normalUrl2.m_port)
return false;
return normalUrl2.m_siteString != null && normalUrl1.m_siteString.IsSubsetOf( normalUrl2.m_siteString );
}
}
else
{
return false;
}
}
public override String ToString()
{
return m_urlOriginal;
}
public override bool Equals(Object o)
{
DoDeferredParse();
if (o == null || !(o is URLString))
return false;
else
return this.Equals( (URLString)o );
}
public override int GetHashCode()
{
DoDeferredParse();
TextInfo info = CultureInfo.InvariantCulture.TextInfo;
int accumulator = 0;
if (this.m_protocol != null)
accumulator = info.GetCaseInsensitiveHashCode( this.m_protocol );
#if !PLATFORM_UNIX
if (this.m_localSite != null)
{
accumulator = accumulator ^ this.m_localSite.GetHashCode();
}
else
{
accumulator = accumulator ^ this.m_siteString.GetHashCode();
}
accumulator = accumulator ^ this.m_directory.GetHashCode();
#else
accumulator = accumulator ^ info.GetCaseInsensitiveHashCode(this.m_urlOriginal);
#endif // !PLATFORM_UNIX
return accumulator;
}
public bool Equals( URLString url )
{
return CompareUrls( this, url );
}
public static bool CompareUrls( URLString url1, URLString url2 )
{
if (url1 == null && url2 == null)
return true;
if (url1 == null || url2 == null)
return false;
url1.DoDeferredParse();
url2.DoDeferredParse();
URLString normalUrl1 = url1.SpecialNormalizeUrl();
URLString normalUrl2 = url2.SpecialNormalizeUrl();
// Compare protocol (case insensitive)
if (String.Compare( normalUrl1.m_protocol, normalUrl2.m_protocol, StringComparison.OrdinalIgnoreCase) != 0)
return false;
// Do special processing for file urls
if (String.Compare( normalUrl1.m_protocol, "file", StringComparison.OrdinalIgnoreCase) == 0)
{
#if !PLATFORM_UNIX
if (!normalUrl1.m_localSite.IsSubsetOf( normalUrl2.m_localSite ) ||
!normalUrl2.m_localSite.IsSubsetOf( normalUrl1.m_localSite ))
return false;
#else
return url1.IsSubsetOf( url2 ) &&
url2.IsSubsetOf( url1 );
#endif // !PLATFORM_UNIX
}
else
{
if (String.Compare( normalUrl1.m_userpass, normalUrl2.m_userpass, StringComparison.Ordinal) != 0)
return false;
if (!normalUrl1.m_siteString.IsSubsetOf( normalUrl2.m_siteString ) ||
!normalUrl2.m_siteString.IsSubsetOf( normalUrl1.m_siteString ))
return false;
if (url1.m_port != url2.m_port)
return false;
}
if (!normalUrl1.m_directory.IsSubsetOf( normalUrl2.m_directory ) ||
!normalUrl2.m_directory.IsSubsetOf( normalUrl1.m_directory ))
return false;
return true;
}
internal String NormalizeUrl()
{
DoDeferredParse();
StringBuilder builtUrl = StringBuilderCache.Acquire();
if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) == 0)
{
#if !PLATFORM_UNIX
builtUrl = builtUrl.AppendFormat("FILE:///{0}/{1}", m_localSite.ToString(), m_directory.ToString());
#else
builtUrl = builtUrl.AppendFormat("FILE:///{0}", m_directory.ToString());
#endif // !PLATFORM_UNIX
}
else
{
builtUrl = builtUrl.AppendFormat("{0}://{1}{2}", m_protocol, m_userpass, m_siteString.ToString());
if (m_port != -1)
builtUrl = builtUrl.AppendFormat("{0}",m_port);
builtUrl = builtUrl.AppendFormat("/{0}", m_directory.ToString());
}
return StringBuilderCache.GetStringAndRelease(builtUrl).ToUpper(CultureInfo.InvariantCulture);
}
#if !PLATFORM_UNIX
[System.Security.SecuritySafeCritical] // auto-generated
internal URLString SpecialNormalizeUrl()
{
// Under WinXP, file protocol urls can be mapped to
// drives that aren't actually file protocol underneath
// due to drive mounting. This code attempts to figure
// out what a drive is mounted to and create the
// url is maps to.
DoDeferredParse();
if (String.Compare( m_protocol, "file", StringComparison.OrdinalIgnoreCase) != 0)
{
return this;
}
else
{
String localSite = m_localSite.ToString();
if (localSite.Length == 2 &&
(localSite[1] == '|' ||
localSite[1] == ':'))
{
String deviceName = null;
GetDeviceName(localSite, JitHelpers.GetStringHandleOnStack(ref deviceName));
if (deviceName != null)
{
if (deviceName.IndexOf( "://", StringComparison.Ordinal ) != -1)
{
URLString u = new URLString( deviceName + "/" + this.m_directory.ToString() );
u.DoDeferredParse(); // Presumably the caller of SpecialNormalizeUrl wants a fully parsed URL
return u;
}
else
{
URLString u = new URLString( "file://" + deviceName + "/" + this.m_directory.ToString() );
u.DoDeferredParse();// Presumably the caller of SpecialNormalizeUrl wants a fully parsed URL
return u;
}
}
else
return this;
}
else
{
return this;
}
}
}
[System.Security.SecurityCritical] // auto-generated
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetDeviceName( String driveLetter, StringHandleOnStack retDeviceName );
#else
internal URLString SpecialNormalizeUrl()
{
return this;
}
#endif // !PLATFORM_UNIX
}
[Serializable]
internal class DirectoryString : SiteString
{
private bool m_checkForIllegalChars;
private new static char[] m_separators = { '/' };
// From KB #Q177506, file/folder illegal characters are \ / : * ? " < > |
protected static char[] m_illegalDirectoryCharacters = { '\\', ':', '*', '?', '"', '<', '>', '|' };
public DirectoryString()
{
m_site = "";
m_separatedSite = new ArrayList();
}
public DirectoryString( String directory, bool checkForIllegalChars )
{
m_site = directory;
m_checkForIllegalChars = checkForIllegalChars;
m_separatedSite = CreateSeparatedString(directory);
}
private ArrayList CreateSeparatedString(String directory)
{
if (directory == null || directory.Length == 0)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
}
Contract.EndContractBlock();
ArrayList list = new ArrayList();
String[] separatedArray = directory.Split(m_separators);
for (int index = 0; index < separatedArray.Length; ++index)
{
if (separatedArray[index] == null || separatedArray[index].Equals( "" ))
{
// this case is fine, we just ignore it the extra separators.
}
else if (separatedArray[index].Equals( "*" ))
{
if (index != separatedArray.Length-1)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
}
list.Add( separatedArray[index] );
}
else if (m_checkForIllegalChars && separatedArray[index].IndexOfAny( m_illegalDirectoryCharacters ) != -1)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
}
else
{
list.Add( separatedArray[index] );
}
}
return list;
}
public virtual bool IsSubsetOf( DirectoryString operand )
{
return this.IsSubsetOf( operand, true );
}
public virtual bool IsSubsetOf( DirectoryString operand, bool ignoreCase )
{
if (operand == null)
{
return false;
}
else if (operand.m_separatedSite.Count == 0)
{
return this.m_separatedSite.Count == 0 || this.m_separatedSite.Count > 0 && String.Compare((String)this.m_separatedSite[0], "*", StringComparison.Ordinal) == 0;
}
else if (this.m_separatedSite.Count == 0)
{
return String.Compare((String)operand.m_separatedSite[0], "*", StringComparison.Ordinal) == 0;
}
else
{
return base.IsSubsetOf( operand, ignoreCase );
}
}
}
#if !PLATFORM_UNIX
[Serializable]
internal class LocalSiteString : SiteString
{
private new static char[] m_separators = { '/' };
public LocalSiteString( String site )
{
m_site = site.Replace( '|', ':');
if (m_site.Length > 2 && m_site.IndexOf( ':' ) != -1)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
m_separatedSite = CreateSeparatedString(m_site);
}
private ArrayList CreateSeparatedString(String directory)
{
if (directory == null || directory.Length == 0)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
}
Contract.EndContractBlock();
ArrayList list = new ArrayList();
String[] separatedArray = directory.Split(m_separators);
for (int index = 0; index < separatedArray.Length; ++index)
{
if (separatedArray[index] == null || separatedArray[index].Equals( "" ))
{
if (index < 2 &&
directory[index] == '/')
{
list.Add( "//" );
}
else if (index != separatedArray.Length-1)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
}
}
else if (separatedArray[index].Equals( "*" ))
{
if (index != separatedArray.Length-1)
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDirectoryOnUrl"));
}
list.Add( separatedArray[index] );
}
else
{
list.Add( separatedArray[index] );
}
}
return list;
}
public virtual bool IsSubsetOf( LocalSiteString operand )
{
return this.IsSubsetOf( operand, true );
}
public virtual bool IsSubsetOf( LocalSiteString operand, bool ignoreCase )
{
if (operand == null)
{
return false;
}
else if (operand.m_separatedSite.Count == 0)
{
return this.m_separatedSite.Count == 0 || this.m_separatedSite.Count > 0 && String.Compare((String)this.m_separatedSite[0], "*", StringComparison.Ordinal) == 0;
}
else if (this.m_separatedSite.Count == 0)
{
return String.Compare((String)operand.m_separatedSite[0], "*", StringComparison.Ordinal) == 0;
}
else
{
return base.IsSubsetOf( operand, ignoreCase );
}
}
}
#endif // !PLATFORM_UNIX
}
| |
// Copyright (c) Winton. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENCE in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using Winton.Extensions.Threading.Actor.Tests.Utilities;
using Xunit;
namespace Winton.Extensions.Threading.Actor.Tests.Unit
{
public sealed class ActorTests : IDisposable
{
public enum ResumeTestCase
{
AwaitOnSecondActor,
AwaitOnTaskFactoryScheduledTask
}
public enum StopTaskCancellationTestCase
{
CancelPriorToInvoke,
CancelDuringWork
}
public enum StopWorkOutcome
{
Completes,
Faults
}
private readonly List<IActor> _createdActors = new List<IActor>();
private readonly TimeSpan _waitTimeout = TimeSpan.FromSeconds(30);
public void Dispose()
{
if (_createdActors.Any())
{
try
{
Task.WaitAll(_createdActors.Select(x => x.Stop()).ToArray(), _waitTimeout);
}
catch (AggregateException exception)
{
Console.WriteLine($"One or more errors occurred whilst stopping the test actor(s):\n{string.Join("\n", exception.InnerExceptions)}");
}
}
}
[Fact]
public void ShouldBeAbleToEnqueueBasicNonVoidTaskAndAwaitItsReturn()
{
var actor = CreateActor();
actor.Enqueue(() => true).AwaitingShouldCompleteIn(_waitTimeout).And.Should().BeTrue();
}
[Fact]
public async Task ShouldBeAbleToEnqueueBasicVoidTaskAndAwaitItsReturn()
{
var actor = CreateActor();
var ran = false;
await actor.Enqueue(() => { ran = true; });
ran.Should().BeTrue();
}
[Fact]
public void ShouldRunMultipleNonVoidTasksInTheOrderTheyAreEnqueued()
{
var actor = CreateActor();
var output = new List<int>();
var tasks =
Enumerable.Range(1, 50)
.Select(x => actor.Enqueue(() =>
{
// Without this the test will usually pass even
// with a dodgy implementation
Thread.Sleep(1);
return x;
})
.ContinueWith(y => output.Add(y.Result), TaskContinuationOptions.ExecuteSynchronously))
.ToArray();
Task.WhenAll(tasks).AwaitingShouldCompleteIn(_waitTimeout);
output.Should().Equal(Enumerable.Range(1, 50));
}
[Fact]
public void ShouldRunMultipleVoidTasksInTheOrderTheyAreEnqueued()
{
var actor = CreateActor();
var output = new List<int>();
var tasks =
Enumerable.Range(1, 50)
.Select(x => actor.Enqueue(() =>
{
// Without this the test will usually pass even
// with a dodgy implementation
Thread.Sleep(1);
output.Add(x);
}))
.ToArray();
Task.WhenAll(tasks).AwaitingShouldCompleteIn(_waitTimeout);
output.Should().Equal(Enumerable.Range(1, 50));
}
[Fact]
public void ShouldHideSchedulerFromPotentialChildTasksOfBasicNonVoidTask()
{
var actor = CreateActor();
var task = actor.Enqueue(() => TaskScheduler.Current);
task.AwaitingShouldCompleteIn(_waitTimeout).And.Should().Be(TaskScheduler.Default);
}
[Fact]
public void ShouldHideSchedulerFromPotentialChildTasksOfBasicVoidTask()
{
var actor = CreateActor();
var taskScheduler = default(TaskScheduler);
actor.Enqueue(() => { taskScheduler = TaskScheduler.Current; }).AwaitingShouldCompleteIn(_waitTimeout);
taskScheduler.Should().Be(TaskScheduler.Default);
}
[Theory]
[InlineData(ResumeTestCase.AwaitOnTaskFactoryScheduledTask)]
[InlineData(ResumeTestCase.AwaitOnSecondActor)]
public void ShouldBeAbleToResumeAsyncNonVoidTask(ResumeTestCase testCase)
{
var actor1 = CreateActor();
var actor2 = CreateActor();
var stageOrder = new List<string>();
var expectedStageOrder =
new List<string>
{
"PreActor2Call",
"PreTrigger",
"PostTrigger",
"Slept",
"PostActor2Call"
};
var trigger = new TaskCompletionSource<bool>();
var suspendWork = default(Func<Task<int>>);
var actor1TaskSchedulers = new List<TaskScheduler>();
var actor1CurrentActorIds = new List<ActorId>();
var nonActor1CurrentActorIds = new List<ActorId>();
switch (testCase)
{
case ResumeTestCase.AwaitOnSecondActor:
suspendWork = () => actor2.Enqueue(() =>
{
nonActor1CurrentActorIds.Add(Actor.CurrentId);
ThrowIfWaitTimesOut(trigger.Task);
return 345;
});
break;
case ResumeTestCase.AwaitOnTaskFactoryScheduledTask:
suspendWork = () => Task.Factory.StartNew(() =>
{
nonActor1CurrentActorIds.Add(Actor.CurrentId);
ThrowIfWaitTimesOut(trigger.Task);
return 345;
});
break;
default:
throw new Exception($"Unhandled test case {testCase}.");
}
var task1 =
actor1.Enqueue(async () =>
{
actor1CurrentActorIds.Add(Actor.CurrentId);
stageOrder.Add("PreActor2Call");
actor1TaskSchedulers.Add(TaskScheduler.Current);
var value = await suspendWork();
stageOrder.Add("PostActor2Call");
actor1TaskSchedulers.Add(TaskScheduler.Current);
actor1CurrentActorIds.Add(Actor.CurrentId);
return value * 37;
});
var task2 =
actor1.Enqueue(() =>
{
actor1CurrentActorIds.Add(Actor.CurrentId);
actor1TaskSchedulers.Add(TaskScheduler.Current);
stageOrder.Add("PreTrigger");
trigger.SetResult(true);
stageOrder.Add("PostTrigger");
Thread.Sleep(TimeSpan.FromSeconds(0.5));
stageOrder.Add("Slept");
});
Task.WhenAll(task1, task2).AwaitingShouldCompleteIn(_waitTimeout);
actor1TaskSchedulers.Should().NotBeEmpty().And.OnlyContain(x => ReferenceEquals(x, TaskScheduler.Default));
stageOrder.Should().Equal(expectedStageOrder);
actor1CurrentActorIds.Should().NotBeEmpty().And.OnlyContain(x => x == actor1.Id);
nonActor1CurrentActorIds.Should().NotBeEmpty().And.OnlyContain(x => x != actor1.Id);
task1.Result.Should().Be(37 * 345);
}
[Theory]
[InlineData(ResumeTestCase.AwaitOnTaskFactoryScheduledTask)]
[InlineData(ResumeTestCase.AwaitOnSecondActor)]
public void ShouldBeAbleToResumeAsyncVoidTask(ResumeTestCase testCase)
{
var actor1 = CreateActor();
var actor2 = CreateActor();
var stageOrder = new List<string>();
var expectedStageOrder =
new List<string>
{
"PreActor2Call",
"PreTrigger",
"PostTrigger",
"Slept",
"PostActor2Call",
"Result=345"
};
var trigger = new TaskCompletionSource<bool>();
var suspendWork = default(Func<Task<int>>);
var actor1TaskSchedulers = new List<TaskScheduler>();
var actor1CurrentActorIds = new List<ActorId>();
var nonActor1CurrentActorIds = new List<ActorId>();
switch (testCase)
{
case ResumeTestCase.AwaitOnSecondActor:
suspendWork = () => actor2.Enqueue(() =>
{
nonActor1CurrentActorIds.Add(Actor.CurrentId);
ThrowIfWaitTimesOut(trigger.Task);
return 345;
});
break;
case ResumeTestCase.AwaitOnTaskFactoryScheduledTask:
suspendWork = () => Task.Factory.StartNew(() =>
{
nonActor1CurrentActorIds.Add(Actor.CurrentId);
ThrowIfWaitTimesOut(trigger.Task);
return 345;
});
break;
default:
throw new Exception($"Unhandled test case {testCase}.");
}
var task1 =
actor1.Enqueue(async () =>
{
actor1CurrentActorIds.Add(Actor.CurrentId);
actor1TaskSchedulers.Add(TaskScheduler.Current);
stageOrder.Add("PreActor2Call");
var value = await suspendWork();
stageOrder.Add("PostActor2Call");
Thread.Sleep(TimeSpan.FromSeconds(0.5));
stageOrder.Add($"Result={value}");
actor1TaskSchedulers.Add(TaskScheduler.Current);
actor1CurrentActorIds.Add(Actor.CurrentId);
});
var task2 =
actor1.Enqueue(() =>
{
actor1CurrentActorIds.Add(Actor.CurrentId);
actor1TaskSchedulers.Add(TaskScheduler.Current);
stageOrder.Add("PreTrigger");
trigger.SetResult(true);
stageOrder.Add("PostTrigger");
Thread.Sleep(TimeSpan.FromSeconds(0.5));
stageOrder.Add("Slept");
});
Task.WhenAll(task1, task2).AwaitingShouldCompleteIn(_waitTimeout);
actor1TaskSchedulers.Should().NotBeEmpty().And.OnlyContain(x => ReferenceEquals(x, TaskScheduler.Default));
stageOrder.Should().Equal(expectedStageOrder);
actor1CurrentActorIds.Should().NotBeEmpty().And.OnlyContain(x => x == actor1.Id);
nonActor1CurrentActorIds.Should().NotBeEmpty().And.OnlyContain(x => x != actor1.Id);
}
[Theory]
[InlineData(ActorEnqueueOptions.WorkIsLongRunning)]
[InlineData(ActorEnqueueOptions.Default)]
public async Task ShouldScheduleTaskAsLongRunningIfRequested(ActorEnqueueOptions enqueueOptions)
{
var actor = new Actor();
await actor.Start();
actor.Awaiting(async x => await x.Enqueue(() => ValidateActorThread(enqueueOptions), enqueueOptions)).ShouldNotThrow();
actor.Awaiting(
async x => await x.Enqueue(
() =>
{
ValidateActorThread(enqueueOptions);
return 676;
}, enqueueOptions)).ShouldNotThrow();
actor.Awaiting(
async x => await x.Enqueue(
async () =>
{
await Task.Yield();
ValidateActorThread(enqueueOptions);
}, enqueueOptions)).ShouldNotThrow();
actor.Awaiting(
async x => await x.Enqueue(
async () =>
{
await Task.Yield();
ValidateActorThread(enqueueOptions);
return "moose";
}, enqueueOptions)).ShouldNotThrow();
}
[Fact]
public void ShouldBeAbleToSpecifyWorkToRunAtStartUpWhichIsGuaranteedToBeTheFirstThingRun()
{
var numbers = new List<int>();
var actor = CreateActor(x => x.StartWork = new ActorStartWork(() => { numbers.Add(1); }), ActorCreateOptions.None);
_createdActors.Add(actor);
actor.Enqueue(() => numbers.Add(2));
var task = actor.Enqueue(() => numbers.Add(3));
var startTask = actor.Start();
startTask.AwaitingShouldCompleteIn(_waitTimeout);
task.AwaitingShouldCompleteIn(_waitTimeout);
numbers.Should().Equal(Enumerable.Range(1, 3));
}
[Fact]
public void ShouldNotEnqueueAnyMoreWorkAfterAskedToStop()
{
var stageOrder = new List<string>();
var expectedStageOrder =
new List<string>
{
"Start",
"Work1",
"Work2",
"Stop"
};
var actor = CreateActor(x =>
{
x.StartWork = new ActorStartWork(() => stageOrder.Add("Start"));
x.StopWork = new ActorStopWork(() => stageOrder.Add("Stop"));
},
ActorCreateOptions.None);
actor.Enqueue(() => stageOrder.Add("Work1"));
actor.Enqueue(() => stageOrder.Add("Work2"));
actor.Start().AwaitingShouldCompleteIn(_waitTimeout);
var stopTask = actor.Stop();
var lateWork = actor.Enqueue(() => stageOrder.Add("Work3"));
MarkAlreadyStopped();
ShouldBeCancelled(lateWork);
stopTask.AwaitingShouldCompleteIn(_waitTimeout);
stageOrder.Should().Equal(expectedStageOrder);
}
[Fact]
public async Task ShouldCompleteStoppedTaskWhenStopCompleted()
{
var stageOrder = new List<string>();
var expectedStageOrder =
new List<string>
{
"Start",
"Stop",
"Stopped"
};
var actor = CreateActor(x =>
{
x.StartWork = new ActorStartWork(() => stageOrder.Add("Start"));
x.StopWork = new ActorStopWork(
() =>
{
Thread.Sleep(TimeSpan.FromMilliseconds(250));
stageOrder.Add("Stop");
});
},
ActorCreateOptions.None);
await actor.Start();
var stopTask = actor.Stop();
await actor.StoppedTask;
stageOrder.Add("Stopped");
await stopTask;
stageOrder.Should().Equal(expectedStageOrder);
}
[Fact]
public async Task ShouldCancelStoppedTokenWhenStopCompleted()
{
var actor = CreateActor(x => { }, ActorCreateOptions.None);
await actor.Start();
var cancelledPromise = new TaskCompletionSource<object>();
var cancellationRegistrationToken = actor.StoppedToken().Register(() => cancelledPromise.SetResult(null));
await actor.Stop();
cancelledPromise.Task.Wait(TimeSpan.FromMilliseconds(1000)).Should().BeTrue();
cancellationRegistrationToken.Dispose();
}
[Theory]
[InlineData(ResumeTestCase.AwaitOnTaskFactoryScheduledTask, StopWorkOutcome.Completes)]
[InlineData(ResumeTestCase.AwaitOnTaskFactoryScheduledTask, StopWorkOutcome.Faults)]
[InlineData(ResumeTestCase.AwaitOnSecondActor, StopWorkOutcome.Completes)]
[InlineData(ResumeTestCase.AwaitOnSecondActor, StopWorkOutcome.Faults)]
public void ShouldNotBeAbleToResumeWorkAfterStop(ResumeTestCase resumeTestCase, StopWorkOutcome stopWorkOutcome)
{
var actor1 = CreateActor(
x => x.StopWork = new ActorStopWork(
() =>
{
if (stopWorkOutcome == StopWorkOutcome.Faults)
{
throw new InvalidOperationException("Never meant to be");
}
}));
var actor2 = CreateActor();
var pretrigger = new TaskCompletionSource<bool>();
var trigger = new TaskCompletionSource<bool>();
var suspendWork = default(Func<Task<int>>);
var stages = new List<string>();
var expectedStageOrder =
new List<string>
{
"PreSuspend",
"PreTriggerWait",
"PostTriggerWait"
};
int OffActorWork()
{
stages.Add("PreTriggerWait");
pretrigger.SetResult(true);
ThrowIfWaitTimesOut(trigger.Task);
stages.Add("PostTriggerWait");
return 345;
}
switch (resumeTestCase)
{
case ResumeTestCase.AwaitOnSecondActor:
suspendWork = () => actor2.Enqueue((Func<int>)OffActorWork);
break;
case ResumeTestCase.AwaitOnTaskFactoryScheduledTask:
suspendWork = () => new TaskFactory(TaskScheduler.Default).StartNew(OffActorWork);
break;
default:
throw new Exception($"Unhandled test case {resumeTestCase}.");
}
//var task1 =
actor1.Enqueue(
async () =>
{
stages.Add("PreSuspend");
var value = await suspendWork();
stages.Add("PostSuspend");
return value * 37;
});
pretrigger.Task.AwaitingShouldCompleteIn(_waitTimeout);
stages.Should().Equal(expectedStageOrder.Take(2));
var stopTask = actor1.Stop();
MarkAlreadyStopped();
switch (stopWorkOutcome)
{
case StopWorkOutcome.Completes:
stopTask.AwaitingShouldCompleteIn(_waitTimeout);
break;
case StopWorkOutcome.Faults:
((Func<Task>)(async () => await stopTask)).ShouldThrow<InvalidOperationException>().WithMessage("Never meant to be");
break;
default:
throw new Exception($"Unhandled test case {stopWorkOutcome}.");
}
trigger.SetResult(true);
Within.OneSecond(() => stages.Should().Equal(expectedStageOrder));
For.OneSecond(() => stages.Should().Equal(expectedStageOrder));
// The below would be nice but has proved intractable to achieve.
//task1.Awaiting(async x => await x).ShouldThrow<TaskCanceledException>();
actor2.Stop().Wait();
}
[Fact]
public void ShouldNotProcessAnyWorkUntilAsyncStartUpWorkIsComplete()
{
var trigger = new TaskCompletionSource<object>();
var numbers = new List<int>();
var actor = CreateActor(x => x.StartWork = new ActorStartWork(async () =>
{
await trigger.Task;
numbers.Add(1);
}),
ActorCreateOptions.None);
_createdActors.Add(actor);
actor.Enqueue(() => numbers.Add(2));
var task = actor.Enqueue(() => numbers.Add(3));
var startTask = actor.Start();
startTask.IsCompleted.Should().BeFalse();
trigger.SetResult(null);
startTask.AwaitingShouldCompleteIn(_waitTimeout);
task.AwaitingShouldCompleteIn(_waitTimeout);
numbers.Should().Equal(Enumerable.Range(1, 3));
}
[Fact]
public void ShouldNotStartProcessingIfStopAlreadyCalled()
{
var stageOrder = new List<string>();
var actor = CreateActor(x =>
{
x.StartWork = new ActorStartWork(() => stageOrder.Add("Start"));
x.StopWork = new ActorStopWork(() => stageOrder.Add("Stop"));
},
ActorCreateOptions.None);
var shouldBeCancelled =
new List<Task>
{
actor.Enqueue(() => stageOrder.Add("Work1")),
actor.Enqueue(() => stageOrder.Add("Work2"))
};
var stopTask = actor.Stop();
var startTask = actor.Start();
MarkAlreadyStopped();
startTask.AwaitingShouldCompleteIn(_waitTimeout);
stopTask.AwaitingShouldCompleteIn(_waitTimeout);
stageOrder.Should().BeEmpty();
ShouldBeCancelled(shouldBeCancelled[0]);
ShouldBeCancelled(shouldBeCancelled[1]);
}
[Fact]
public void ShouldProcessAlreadyQueuedWorkBeforeSignallingStoppedWhenAskedToStop()
{
var stageOrder = new List<string>();
var expectedStageOrder =
new List<string>
{
"Start",
"Work1",
"Work2",
"Stop"
};
var actor = CreateActor(x =>
{
x.StartWork = new ActorStartWork(() => stageOrder.Add("Start"));
x.StopWork = new ActorStopWork(() => stageOrder.Add("Stop"));
},
ActorCreateOptions.None);
actor.Enqueue(() => stageOrder.Add("Work1"));
actor.Enqueue(() => stageOrder.Add("Work2"));
actor.Start().AwaitingShouldCompleteIn(_waitTimeout);
actor.Stop().AwaitingShouldCompleteIn(_waitTimeout);
stageOrder.Should().Equal(expectedStageOrder);
}
[Fact]
public void ShouldProcessAlreadyQueuedWorkBeforeSignallingStoppedWhenAskedToStopWhilstStartWorkStillBeingProcessed()
{
var stageOrder = new List<string>();
var expectedStageOrder =
new List<string>
{
"Start",
"Work1",
"Work2",
"Stop"
};
var actor = CreateActor(x =>
{
x.StartWork = new ActorStartWork(() => stageOrder.Add("Start"));
x.StopWork = new ActorStopWork(() => stageOrder.Add("Stop"));
},
ActorCreateOptions.None);
actor.Enqueue(() => stageOrder.Add("Work1"));
actor.Enqueue(() => stageOrder.Add("Work2"));
var startTask = actor.Start();
var stopTask = actor.Stop();
startTask.AwaitingShouldCompleteIn(_waitTimeout);
stopTask.AwaitingShouldCompleteIn(_waitTimeout);
stageOrder.Should().Equal(expectedStageOrder);
}
[Theory]
[InlineData(ActorEnqueueOptions.WorkIsLongRunning)]
[InlineData(ActorEnqueueOptions.Default)]
public void ShouldScheduleStartTaskAsLongRunningIfRequested(ActorEnqueueOptions startOptions)
{
var actor = new Actor
{
StartWork = new ActorStartWork(() => ValidateActorThread(startOptions))
{
Options = startOptions
}
};
actor.Awaiting(async x => await x.Start()).ShouldNotThrow();
}
[Theory]
[InlineData(ActorEnqueueOptions.WorkIsLongRunning)]
[InlineData(ActorEnqueueOptions.Default)]
public async Task ShouldScheduleStopTaskAsLongRunningIfRequested(ActorEnqueueOptions stopOptions)
{
var actor = new Actor
{
StopWork = new ActorStopWork(() => ValidateActorThread(stopOptions))
{
Options = stopOptions
}
};
await actor.Start();
actor.Awaiting(async x => await x.Stop()).ShouldNotThrow();
}
[Fact]
public void ShouldSilentlyCompleteCallsToStartAfterTheFirstButOnlyOnceActorHasFinallyStarted()
{
var barrier = new TaskCompletionSource<bool>();
var attempts = 0;
var actor = CreateActor(x => x.StartWork = new ActorStartWork(() =>
{
Interlocked.Increment(ref attempts);
ThrowIfWaitTimesOut(barrier.Task);
}),
ActorCreateOptions.None);
var task1 = actor.Start();
var task2 = actor.Start();
task2.Wait(TimeSpan.FromSeconds(1)).Should().BeFalse("Should not have already completed.");
barrier.SetResult(true);
Task.WhenAll(task1, task2).AwaitingShouldCompleteIn(_waitTimeout);
attempts.Should().Be(1);
}
[Fact]
public void ShouldSilentlyCompleteCallsToStopAfterTheFirstButOnlyOnceActorHasFinallyStopped()
{
var barrier = new TaskCompletionSource<bool>();
var attempts = 0;
var actor = CreateActor(x => x.StopWork = new ActorStopWork(() =>
{
Interlocked.Increment(ref attempts);
ThrowIfWaitTimesOut(barrier.Task);
}));
var task1 = actor.Stop();
MarkAlreadyStopped();
var task2 = actor.Stop();
task2.Wait(TimeSpan.FromSeconds(1)).Should().BeFalse("Should not have already completed.");
barrier.SetResult(true);
Task.WhenAll(task1, task2).AwaitingShouldCompleteIn(_waitTimeout);
attempts.Should().Be(1);
}
[Fact]
public void ShouldOnlyBeAbleToSpecifyStartWorkOnce()
{
var actor = CreateActor(ActorCreateOptions.None);
actor.StartWork = new ActorStartWork(() => { });
Action action = () => actor.StartWork = new ActorStartWork(() => { });
action.ShouldThrow<InvalidOperationException>().WithMessage("Start work already specified.");
}
[Fact]
public void ShouldOnlyBeAbleToSpecifyStopWorkOnce()
{
var actor = CreateActor(ActorCreateOptions.None);
actor.StopWork = new ActorStopWork(() => { });
Action action = () => actor.StopWork = new ActorStopWork(() => { });
action.ShouldThrow<InvalidOperationException>().WithMessage("Stop work already specified.");
}
[Fact]
public void ShouldNotBeAbleToSpecifyStartWorkOnceActorStarted()
{
var actor = CreateActor();
Action action = () => actor.StartWork = new ActorStartWork(() => { });
action.ShouldThrow<InvalidOperationException>().WithMessage("Start work cannot be specified after starting an actor.");
}
[Fact]
public void ShouldNotBeAbleToSpecifyStopWorkOnceActorStarted()
{
var actor = CreateActor();
Action action = () => actor.StopWork = new ActorStopWork(() => { });
action.ShouldThrow<InvalidOperationException>()
.WithMessage("Stop work cannot be specified after starting an actor.");
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task ShouldBeAbleToCancelAnyEnqueuedWork(bool delayStart)
{
var actor = CreateActor(delayStart ? ActorCreateOptions.None : ActorCreateOptions.Start);
var cancellationTokenSource1 = new CancellationTokenSource();
var cancellationTokenSource2 = new CancellationTokenSource();
var cancellationTokenSource3 = new CancellationTokenSource();
var cancellationTokenSource4 = new CancellationTokenSource();
cancellationTokenSource3.Cancel();
var task1 = actor.Enqueue(() => { cancellationTokenSource1.Cancel(); });
var task2 = actor.Enqueue(() =>
{
cancellationTokenSource1.Token.ThrowIfCancellationRequested();
return 28282;
}, cancellationTokenSource1.Token);
var task3 = actor.Enqueue(() =>
{
cancellationTokenSource2.Cancel();
cancellationTokenSource2.Token.ThrowIfCancellationRequested();
}, cancellationTokenSource2.Token);
var task4 = actor.Enqueue(() =>
{
cancellationTokenSource4.Cancel();
return 676;
});
var task5 = actor.Enqueue(async () =>
{
await Task.Delay(100);
cancellationTokenSource3.Token.ThrowIfCancellationRequested();
}, cancellationTokenSource3.Token);
var task6 = actor.Enqueue(async () => await Task.Delay(100));
var task7 = actor.Enqueue(async () =>
{
await Task.Delay(100);
cancellationTokenSource4.Token.ThrowIfCancellationRequested();
return "moose";
}, cancellationTokenSource4.Token);
var task8 = actor.Enqueue(async () =>
{
await Task.Delay(100);
return "moose";
});
if (delayStart)
{
await actor.Start();
}
await task1;
await task4;
await task6;
await task8;
ShouldBeCancelled(task2);
ShouldBeCancelled(task3);
ShouldBeCancelled(task5);
ShouldBeCancelled(task7);
}
[Theory]
[InlineData(StopTaskCancellationTestCase.CancelDuringWork)]
[InlineData(StopTaskCancellationTestCase.CancelPriorToInvoke)]
public void ShouldBeAbleToCancelStopWorkButNotTermination(StopTaskCancellationTestCase testCase)
{
var cancellationTokenSource = new CancellationTokenSource();
var startedStopWorkFlag = new TaskCompletionSource<bool>();
var actor = CreateActor(x => x.StopWork = new ActorStopWork(() =>
{
startedStopWorkFlag.SetResult(true);
Task.Delay(TimeSpan.FromMinutes(1)).Wait(cancellationTokenSource.Token);
},
cancellationTokenSource.Token));
var barrier = new TaskCompletionSource<bool>();
actor.Enqueue(() => ThrowIfWaitTimesOut(barrier.Task));
var stopTask = actor.Stop();
MarkAlreadyStopped();
switch (testCase)
{
case StopTaskCancellationTestCase.CancelPriorToInvoke:
cancellationTokenSource.Cancel();
barrier.SetResult(true);
break;
case StopTaskCancellationTestCase.CancelDuringWork:
barrier.SetResult(true);
startedStopWorkFlag.Task.AwaitingShouldCompleteIn(_waitTimeout);
cancellationTokenSource.Cancel();
break;
default:
throw new Exception($"Unhandled test case {testCase}.");
}
ShouldBeCancelled(stopTask);
if (testCase == StopTaskCancellationTestCase.CancelPriorToInvoke)
{
startedStopWorkFlag.Task.Wait(TimeSpan.FromSeconds(1)).Should().BeFalse();
}
ShouldBeCancelled(actor.Enqueue(() => { }));
}
[Fact]
public void ShouldNotFailEnqueuingWorkAlreadyCancelled()
{
var actor = CreateActor();
var cancellationTokenSource1 = new CancellationTokenSource();
var cancellationTokenSource2 = new CancellationTokenSource();
var cancellationTokenSource3 = new CancellationTokenSource();
var cancellationTokenSource4 = new CancellationTokenSource();
cancellationTokenSource1.Cancel();
cancellationTokenSource2.Cancel();
cancellationTokenSource3.Cancel();
cancellationTokenSource4.Cancel();
var task1 = actor.Enqueue(() => 28282, cancellationTokenSource1.Token);
var task2 = actor.Enqueue(() => { }, cancellationTokenSource2.Token);
var task3 = actor.Enqueue(async () => { await Task.Delay(100); }, cancellationTokenSource3.Token);
var task4 = actor.Enqueue(async () =>
{
await Task.Delay(100);
return "moose";
}, cancellationTokenSource4.Token);
ShouldBeCancelled(task1);
ShouldBeCancelled(task2);
ShouldBeCancelled(task3);
ShouldBeCancelled(task4);
}
[Fact]
public void ShouldStopActorAndNotProcessAnyAlreadyEnqueuedWorkIfStartWorkCancelled()
{
var cancellationTokenSource = new CancellationTokenSource();
var actor = CreateActor(x => x.StartWork = new ActorStartWork(() => { Task.Delay(TimeSpan.FromMinutes(1)).Wait(cancellationTokenSource.Token); }, cancellationTokenSource.Token),
ActorCreateOptions.None);
var attempts = 0;
var startTask = actor.Start();
var task = actor.Enqueue(() => Interlocked.Increment(ref attempts));
MarkAlreadyStopped();
cancellationTokenSource.Cancel();
ShouldBeCancelled(startTask);
ShouldBeCancelled(task);
ShouldBeCancelled(actor.Enqueue(() => { }));
attempts.Should().Be(0);
}
[Theory]
[InlineData(ActorEnqueueOptions.Default, ActorEnqueueOptions.Default)]
[InlineData(ActorEnqueueOptions.WorkIsLongRunning, ActorEnqueueOptions.Default)]
[InlineData(ActorEnqueueOptions.WorkIsLongRunning, ActorEnqueueOptions.WorkIsLongRunning)]
[InlineData(ActorEnqueueOptions.Default, ActorEnqueueOptions.WorkIsLongRunning)]
public async Task ShouldBeAbleToPauseActorUntilResumeFromAwait(ActorEnqueueOptions awaiterOptions, ActorEnqueueOptions otherOptions)
{
// Do this repeatedly to try to expose race conditions in the pausing logic
for (var i = 0; i < 1000; i++)
{
var actor = new Actor();
var numbers = new List<int>();
await actor.Start();
var tasks = new Task[3];
tasks[0] =
actor.Enqueue(
async () =>
{
numbers.Add(i);
var task = Task.Run(() => numbers.Add(i + 1));
await task.WhileActorPaused();
numbers.Add(i + 2);
}, awaiterOptions);
tasks[1] = actor.Enqueue(() => numbers.Add(i + 3), otherOptions);
tasks[2] = actor.Enqueue(() => numbers.Add(i + 4), otherOptions);
await Task.WhenAll(tasks);
await actor.Stop();
numbers.Should().Equal(i, i + 1, i + 2, i + 3, i + 4);
}
}
[Theory]
[InlineData(ActorEnqueueOptions.Default, ActorEnqueueOptions.Default)]
[InlineData(ActorEnqueueOptions.WorkIsLongRunning, ActorEnqueueOptions.Default)]
[InlineData(ActorEnqueueOptions.WorkIsLongRunning, ActorEnqueueOptions.WorkIsLongRunning)]
[InlineData(ActorEnqueueOptions.Default, ActorEnqueueOptions.WorkIsLongRunning)]
public async Task ShouldBeAbleToPauseActorUntilResumeFromAwaitReturningData(ActorEnqueueOptions awaiterOptions, ActorEnqueueOptions otherOptions)
{
// Do this repeatedly to try to expose race conditions in the pausing logic
for (var i = 0; i < 1000; i++)
{
var actor = CreateActor();
var numbers = new List<int>();
await actor.Start();
var tasks = new Task[4];
tasks[0] =
actor.Enqueue(
async () =>
{
numbers.Add(i);
var next = await Task.Run(() => i + 1).WhileActorPaused();
numbers.Add(next);
}, awaiterOptions);
tasks[1] = actor.Enqueue(() => numbers.Add(i + 2), otherOptions);
tasks[2] = actor.Enqueue(() => numbers.Add(i + 3), otherOptions);
tasks[3] = actor.Enqueue(() => numbers.Add(i + 4), otherOptions);
foreach (var task in tasks)
{
await task;
}
await actor.Stop();
numbers.Should().Equal(i, i + 1, i + 2, i + 3, i + 4);
}
}
[Fact]
public async Task StopShouldNotRunStopWorkIfStartWorkFails()
{
var stopWorkCalled = false;
var actor =
new Actor
{
StartWork = new ActorStartWork(() => throw new Exception("Error.")),
StopWork = new ActorStopWork(() => stopWorkCalled = true)
};
actor.Awaiting(async x => await x.Start()).ShouldThrow<Exception>().WithMessage("Error.");
await actor.Stop();
stopWorkCalled.Should().BeFalse();
}
[Flags]
private enum ActorCreateOptions
{
None = 0,
Start = 0x01,
Default = Start
}
private IActor CreateActor(ActorCreateOptions options = ActorCreateOptions.Default)
{
return CreateActor(_ => { }, options);
}
private IActor CreateActor(Action<IActor> setup, ActorCreateOptions options = ActorCreateOptions.Default)
{
var actor = new Actor();
setup(actor);
_createdActors.Add(actor);
if (options.HasFlag(ActorCreateOptions.Start))
{
actor.Start().AwaitingShouldCompleteIn(_waitTimeout);
}
return actor;
}
private static void ShouldBeCancelled(Task task)
{
Expect.That(async () => await task).ShouldThrow<TaskCanceledException>();
}
private void MarkAlreadyStopped()
{
_createdActors.Clear(); // To avoid errors in TearDown when it fails to stop a second time.
}
private void ThrowIfWaitTimesOut(Task task)
{
if (!task.Wait(_waitTimeout))
{
throw new TimeoutException();
}
}
private static void ValidateActorThread(ActorEnqueueOptions enqueueOptions)
{
if (enqueueOptions.HasFlag(ActorEnqueueOptions.WorkIsLongRunning))
{
ActorThreadAssertions.CurrentThreadShouldNotBeThreadPoolThread();
}
else
{
ActorThreadAssertions.CurrentThreadShouldBeThreadPoolThread();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Reactive.Disposables;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Controls.Platform;
using Avalonia.FreeDesktop.DBusMenu;
using Avalonia.Input;
using Avalonia.Platform;
using Avalonia.Threading;
using Tmds.DBus;
#pragma warning disable 1998
namespace Avalonia.FreeDesktop
{
public class DBusMenuExporter
{
public static ITopLevelNativeMenuExporter TryCreateTopLevelNativeMenu(IntPtr xid)
{
if (DBusHelper.Connection == null)
return null;
return new DBusMenuExporterImpl(DBusHelper.Connection, xid);
}
public static INativeMenuExporter TryCreateDetachedNativeMenu(ObjectPath path, Connection currentConection)
{
return new DBusMenuExporterImpl(currentConection, path);
}
public static ObjectPath GenerateDBusMenuObjPath => "/net/avaloniaui/dbusmenu/"
+ Guid.NewGuid().ToString("N");
private class DBusMenuExporterImpl : ITopLevelNativeMenuExporter, IDBusMenu, IDisposable
{
private readonly Connection _dbus;
private readonly uint _xid;
private IRegistrar _registrar;
private bool _disposed;
private uint _revision = 1;
private NativeMenu _menu;
private readonly Dictionary<int, NativeMenuItemBase> _idsToItems = new Dictionary<int, NativeMenuItemBase>();
private readonly Dictionary<NativeMenuItemBase, int> _itemsToIds = new Dictionary<NativeMenuItemBase, int>();
private readonly HashSet<NativeMenu> _menus = new HashSet<NativeMenu>();
private bool _resetQueued;
private int _nextId = 1;
private bool _appMenu = true;
public DBusMenuExporterImpl(Connection dbus, IntPtr xid)
{
_dbus = dbus;
_xid = (uint)xid.ToInt32();
ObjectPath = GenerateDBusMenuObjPath;
SetNativeMenu(new NativeMenu());
Init();
}
public DBusMenuExporterImpl(Connection dbus, ObjectPath path)
{
_dbus = dbus;
_appMenu = false;
ObjectPath = path;
SetNativeMenu(new NativeMenu());
Init();
}
async void Init()
{
try
{
if (_appMenu)
{
await _dbus.RegisterObjectAsync(this);
_registrar = DBusHelper.Connection.CreateProxy<IRegistrar>(
"com.canonical.AppMenu.Registrar",
"/com/canonical/AppMenu/Registrar");
if (!_disposed)
await _registrar.RegisterWindowAsync(_xid, ObjectPath);
}
else
{
await _dbus.RegisterObjectAsync(this);
}
}
catch (Exception e)
{
Logging.Logger.TryGet(Logging.LogEventLevel.Error, Logging.LogArea.X11Platform)
?.Log(this, e.Message);
// It's not really important if this code succeeds,
// and it's not important to know if it succeeds
// since even if we register the window it's not guaranteed that
// menu will be actually exported
}
}
public void Dispose()
{
if (_disposed)
return;
_disposed = true;
_dbus.UnregisterObject(this);
// Fire and forget
_registrar?.UnregisterWindowAsync(_xid);
}
public bool IsNativeMenuExported { get; private set; }
public event EventHandler OnIsNativeMenuExportedChanged;
public void SetNativeMenu(NativeMenu menu)
{
if (menu == null)
menu = new NativeMenu();
if (_menu != null)
((INotifyCollectionChanged)_menu.Items).CollectionChanged -= OnMenuItemsChanged;
_menu = menu;
((INotifyCollectionChanged)_menu.Items).CollectionChanged += OnMenuItemsChanged;
DoLayoutReset();
}
/*
This is basic initial implementation, so we don't actually track anything and
just reset the whole layout on *ANY* change
This is not how it should work and will prevent us from implementing various features,
but that's the fastest way to get things working, so...
*/
void DoLayoutReset()
{
_resetQueued = false;
foreach (var i in _idsToItems.Values)
i.PropertyChanged -= OnItemPropertyChanged;
foreach(var menu in _menus)
((INotifyCollectionChanged)menu.Items).CollectionChanged -= OnMenuItemsChanged;
_menus.Clear();
_idsToItems.Clear();
_itemsToIds.Clear();
_revision++;
LayoutUpdated?.Invoke((_revision, 0));
}
void QueueReset()
{
if(_resetQueued)
return;
_resetQueued = true;
Dispatcher.UIThread.Post(DoLayoutReset, DispatcherPriority.Background);
}
private (NativeMenuItemBase item, NativeMenu menu) GetMenu(int id)
{
if (id == 0)
return (null, _menu);
_idsToItems.TryGetValue(id, out var item);
return (item, (item as NativeMenuItem)?.Menu);
}
private void EnsureSubscribed(NativeMenu menu)
{
if(menu!=null && _menus.Add(menu))
((INotifyCollectionChanged)menu.Items).CollectionChanged += OnMenuItemsChanged;
}
private int GetId(NativeMenuItemBase item)
{
if (_itemsToIds.TryGetValue(item, out var id))
return id;
id = _nextId++;
_idsToItems[id] = item;
_itemsToIds[item] = id;
item.PropertyChanged += OnItemPropertyChanged;
if (item is NativeMenuItem nmi)
EnsureSubscribed(nmi.Menu);
return id;
}
private void OnMenuItemsChanged(object sender, NotifyCollectionChangedEventArgs e)
{
QueueReset();
}
private void OnItemPropertyChanged(object sender, AvaloniaPropertyChangedEventArgs e)
{
QueueReset();
}
public ObjectPath ObjectPath { get; }
async Task<object> IFreeDesktopDBusProperties.GetAsync(string prop)
{
if (prop == "Version")
return 2;
if (prop == "Status")
return "normal";
return 0;
}
async Task<DBusMenuProperties> IFreeDesktopDBusProperties.GetAllAsync()
{
return new DBusMenuProperties
{
Version = 2,
Status = "normal",
};
}
private static string[] AllProperties = new[]
{
"type", "label", "enabled", "visible", "shortcut", "toggle-type", "children-display", "toggle-state", "icon-data"
};
object GetProperty((NativeMenuItemBase item, NativeMenu menu) i, string name)
{
var (it, menu) = i;
if (it is NativeMenuItemSeparator)
{
if (name == "type")
return "separator";
}
else if (it is NativeMenuItem item)
{
if (name == "type")
{
return null;
}
if (name == "label")
return item?.Header ?? "<null>";
if (name == "enabled")
{
if (item == null)
return null;
if (item.Menu != null && item.Menu.Items.Count == 0)
return false;
if (item.IsEnabled == false)
return false;
return null;
}
if (name == "shortcut")
{
if (item?.Gesture == null)
return null;
if (item.Gesture.KeyModifiers == 0)
return null;
var lst = new List<string>();
var mod = item.Gesture;
if (mod.KeyModifiers.HasAllFlags(KeyModifiers.Control))
lst.Add("Control");
if (mod.KeyModifiers.HasAllFlags(KeyModifiers.Alt))
lst.Add("Alt");
if (mod.KeyModifiers.HasAllFlags(KeyModifiers.Shift))
lst.Add("Shift");
if (mod.KeyModifiers.HasAllFlags(KeyModifiers.Meta))
lst.Add("Super");
lst.Add(item.Gesture.Key.ToString());
return new[] { lst.ToArray() };
}
if (name == "toggle-type")
{
if (item.ToggleType == NativeMenuItemToggleType.CheckBox)
return "checkmark";
if (item.ToggleType == NativeMenuItemToggleType.Radio)
return "radio";
}
if (name == "toggle-state")
{
if (item.ToggleType != NativeMenuItemToggleType.None)
return item.IsChecked ? 1 : 0;
}
if (name == "icon-data")
{
if (item.Icon != null)
{
var loader = AvaloniaLocator.Current.GetService<IPlatformIconLoader>();
if (loader != null)
{
var icon = loader.LoadIcon(item.Icon.PlatformImpl.Item);
using var ms = new MemoryStream();
icon.Save(ms);
return ms.ToArray();
}
}
}
if (name == "children-display")
return menu != null ? "submenu" : null;
}
return null;
}
private List<KeyValuePair<string, object>> _reusablePropertyList = new List<KeyValuePair<string, object>>();
KeyValuePair<string, object>[] GetProperties((NativeMenuItemBase item, NativeMenu menu) i, string[] names)
{
if (names?.Length > 0 != true)
names = AllProperties;
_reusablePropertyList.Clear();
foreach (var n in names)
{
var v = GetProperty(i, n);
if (v != null)
_reusablePropertyList.Add(new KeyValuePair<string, object>(n, v));
}
return _reusablePropertyList.ToArray();
}
public Task SetAsync(string prop, object val) => Task.CompletedTask;
public Task<(uint revision, (int, KeyValuePair<string, object>[], object[]) layout)> GetLayoutAsync(
int ParentId, int RecursionDepth, string[] PropertyNames)
{
var menu = GetMenu(ParentId);
var rv = (_revision, GetLayout(menu.item, menu.menu, RecursionDepth, PropertyNames));
if (!IsNativeMenuExported)
{
IsNativeMenuExported = true;
Dispatcher.UIThread.Post(() =>
{
OnIsNativeMenuExportedChanged?.Invoke(this, EventArgs.Empty);
});
}
return Task.FromResult(rv);
}
(int, KeyValuePair<string, object>[], object[]) GetLayout(NativeMenuItemBase item, NativeMenu menu, int depth, string[] propertyNames)
{
var id = item == null ? 0 : GetId(item);
var props = GetProperties((item, menu), propertyNames);
var children = (depth == 0 || menu == null) ? new object[0] : new object[menu.Items.Count];
if(menu != null)
for (var c = 0; c < children.Length; c++)
{
var ch = menu.Items[c];
children[c] = GetLayout(ch, (ch as NativeMenuItem)?.Menu, depth == -1 ? -1 : depth - 1, propertyNames);
}
return (id, props, children);
}
public Task<(int, KeyValuePair<string, object>[])[]> GetGroupPropertiesAsync(int[] Ids, string[] PropertyNames)
{
var arr = new (int, KeyValuePair<string, object>[])[Ids.Length];
for (var c = 0; c < Ids.Length; c++)
{
var id = Ids[c];
var item = GetMenu(id);
var props = GetProperties(item, PropertyNames);
arr[c] = (id, props);
}
return Task.FromResult(arr);
}
public async Task<object> GetPropertyAsync(int Id, string Name)
{
return GetProperty(GetMenu(Id), Name) ?? 0;
}
public void HandleEvent(int id, string eventId, object data, uint timestamp)
{
if (eventId == "clicked")
{
var item = GetMenu(id).item;
if (item is NativeMenuItem menuItem && item is INativeMenuItemExporterEventsImplBridge bridge)
{
if (menuItem?.IsEnabled == true)
bridge?.RaiseClicked();
}
}
}
public Task EventAsync(int Id, string EventId, object Data, uint Timestamp)
{
HandleEvent(Id, EventId, Data, Timestamp);
return Task.CompletedTask;
}
public Task<int[]> EventGroupAsync((int id, string eventId, object data, uint timestamp)[] Events)
{
foreach (var e in Events)
HandleEvent(e.id, e.eventId, e.data, e.timestamp);
return Task.FromResult(new int[0]);
}
public async Task<bool> AboutToShowAsync(int Id)
{
return false;
}
public async Task<(int[] updatesNeeded, int[] idErrors)> AboutToShowGroupAsync(int[] Ids)
{
return (new int[0], new int[0]);
}
#region Events
private event Action<((int, IDictionary<string, object>)[] updatedProps, (int, string[])[] removedProps)>
ItemsPropertiesUpdated { add { } remove { } }
private event Action<(uint revision, int parent)> LayoutUpdated;
private event Action<(int id, uint timestamp)> ItemActivationRequested { add { } remove { } }
private event Action<PropertyChanges> PropertiesChanged { add { } remove { } }
async Task<IDisposable> IDBusMenu.WatchItemsPropertiesUpdatedAsync(Action<((int, IDictionary<string, object>)[] updatedProps, (int, string[])[] removedProps)> handler, Action<Exception> onError)
{
ItemsPropertiesUpdated += handler;
return Disposable.Create(() => ItemsPropertiesUpdated -= handler);
}
async Task<IDisposable> IDBusMenu.WatchLayoutUpdatedAsync(Action<(uint revision, int parent)> handler, Action<Exception> onError)
{
LayoutUpdated += handler;
return Disposable.Create(() => LayoutUpdated -= handler);
}
async Task<IDisposable> IDBusMenu.WatchItemActivationRequestedAsync(Action<(int id, uint timestamp)> handler, Action<Exception> onError)
{
ItemActivationRequested+= handler;
return Disposable.Create(() => ItemActivationRequested -= handler);
}
async Task<IDisposable> IFreeDesktopDBusProperties.WatchPropertiesAsync(Action<PropertyChanges> handler)
{
PropertiesChanged += handler;
return Disposable.Create(() => PropertiesChanged -= handler);
}
#endregion
}
}
}
| |
// CqlSharp.Linq - CqlSharp.Linq
// Copyright (c) 2014 Joost Reuzel
//
// 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 CqlSharp.Linq.Expressions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
namespace CqlSharp.Linq.Query
{
/// <summary>
/// Distills CQL Select Statement query strings from an expression tree
/// </summary>
internal class CqlTextBuilder : CqlExpressionVisitor
{
private readonly Dictionary<Expression, string> _translations = new Dictionary<Expression, string>();
/// <summary>
/// Builds selectStatement queries from the specified expression, and returns the first instance
/// </summary>
/// <param name="expression"> The expression. </param>
/// <returns> </returns>
public string Build(Expression expression)
{
Expression expr = Visit(expression);
return _translations[expr];
}
public override Expression VisitSelectStatement(SelectStatementExpression selectStatement)
{
base.VisitSelectStatement(selectStatement);
var builder = new StringBuilder();
builder.Append("SELECT ");
builder.Append(_translations[selectStatement.SelectClause]);
builder.Append(" FROM \"");
builder.Append(selectStatement.TableName.Replace("\"", "\"\"").Replace(".","\".\""));
builder.Append("\"");
if (selectStatement.WhereClause != null && selectStatement.WhereClause.Any())
{
builder.Append(" WHERE ");
var wheres = selectStatement.WhereClause.Select(relation => _translations[relation]);
builder.Append(string.Join(" AND ", wheres));
}
if (selectStatement.OrderBy != null && selectStatement.OrderBy.Any())
{
builder.Append(" ORDER BY ");
var orders = selectStatement.OrderBy.Select(order => _translations[order]);
builder.Append(string.Join(",", orders));
}
if (selectStatement.Limit.HasValue)
{
builder.Append(" LIMIT ");
builder.Append(selectStatement.Limit);
}
if (selectStatement.AllowFiltering)
{
builder.Append(" ALLOW FILTERING");
}
builder.Append(";");
_translations[selectStatement] = builder.ToString();
return selectStatement;
}
public override Expression VisitSelectClause(SelectClauseExpression selectClauseExpression)
{
base.VisitSelectClause(selectClauseExpression);
string translation;
switch ((CqlExpressionType)selectClauseExpression.NodeType)
{
case CqlExpressionType.SelectAll:
translation = "*";
break;
case CqlExpressionType.SelectCount:
translation = "COUNT(*)";
break;
case CqlExpressionType.SelectColumns:
translation = selectClauseExpression.Distinct ? "DISTINCT " : "";
var selectors = selectClauseExpression.Selectors.Select(arg => _translations[arg]);
translation += string.Join(",", selectors);
break;
default:
throw new Exception("Unexpected type of select clause encountered : " +
selectClauseExpression.NodeType);
}
_translations[selectClauseExpression] = translation;
return selectClauseExpression;
}
public override Expression VisitSelector(SelectorExpression selector)
{
base.VisitSelector(selector);
string value;
switch ((CqlExpressionType)selector.NodeType)
{
case CqlExpressionType.IdentifierSelector:
value = "\"" + selector.Identifier.Replace("\"", "\"\"") + "\"";
break;
case CqlExpressionType.FunctionSelector:
var builder = new StringBuilder();
builder.Append(selector.Function.Name.ToLower());
builder.Append("(");
var argsAsString = selector.Arguments.Select(arg => _translations[arg]);
builder.Append(string.Join(",", argsAsString));
builder.Append(")");
value = builder.ToString();
break;
default:
throw new CqlLinqException("Unexpected Selector type encountered");
}
_translations[selector] = value;
return selector;
}
public override Expression VisitRelation(RelationExpression relation)
{
base.VisitRelation(relation);
var builder = new StringBuilder();
builder.Append(_translations[relation.Selector]);
switch ((CqlExpressionType)relation.NodeType)
{
case CqlExpressionType.Equal:
builder.Append("=");
builder.Append(_translations[relation.Term]);
break;
case CqlExpressionType.LargerEqualThan:
builder.Append(">=");
builder.Append(_translations[relation.Term]);
break;
case CqlExpressionType.LargerThan:
builder.Append(">");
builder.Append(_translations[relation.Term]);
break;
case CqlExpressionType.SmallerEqualThan:
builder.Append("<=");
builder.Append(_translations[relation.Term]);
break;
case CqlExpressionType.SmallerThan:
builder.Append("<");
builder.Append(_translations[relation.Term]);
break;
case CqlExpressionType.In:
builder.Append(" IN ");
if(((CqlExpressionType)relation.Term.NodeType == CqlExpressionType.Variable))
{
builder.Append(_translations[relation.Term]);
}
else
{
builder.Append("(");
var elements = relation.Term.Terms.Select(term => _translations[term]);
builder.Append(string.Join(",", elements));
builder.Append(")");
}
break;
default:
throw new CqlLinqException("Unexpected relation encountered in where: " +
relation.NodeType.ToString());
}
_translations[relation] = builder.ToString();
return relation;
}
public override Expression VisitTerm(TermExpression term)
{
base.VisitTerm(term);
var builder = new StringBuilder();
switch ((CqlExpressionType)term.NodeType)
{
case CqlExpressionType.Variable:
builder.Append("?");
break;
case CqlExpressionType.Constant:
builder.Append(TypeSystem.ToStringValue(term.Value, term.Type.ToCqlType()));
break;
case CqlExpressionType.List:
{
builder.Append("[");
var elements = term.Terms.Select(value => _translations[value]).ToList();
builder.Append(string.Join(",", elements));
builder.Append("]");
}
break;
case CqlExpressionType.Set:
{
builder.Append("{");
var elements = term.Terms.Select(value => _translations[value]).ToList();
builder.Append(string.Join(",", elements));
builder.Append("}");
}
break;
case CqlExpressionType.Map:
{
builder.Append("{");
var elements =
term.DictionaryTerms.Select(
pair => string.Format("{0}:{1}", _translations[pair.Key], _translations[pair.Value])).
ToList();
builder.Append(string.Join(",", elements));
builder.Append("}");
}
break;
case CqlExpressionType.Function:
builder.Append(term.Function.Name.ToLower());
builder.Append("(");
builder.Append(string.Join(",", term.Terms.Select(arg => _translations[arg])));
builder.Append(")");
break;
default:
throw new CqlLinqException("Unexpected type of term encountered: " + term.NodeType.ToString());
}
_translations[term] = builder.ToString();
return term;
}
public override Expression VisitOrdering(OrderingExpression ordering)
{
string value;
switch ((CqlExpressionType)ordering.NodeType)
{
case CqlExpressionType.OrderDescending:
value = _translations[ordering.Selector] + " DESC";
break;
case CqlExpressionType.OrderAscending:
value = _translations[ordering.Selector] + " ASC";
break;
default:
throw new CqlLinqException("Unexpected ordering type encountered: " + ordering.NodeType.ToString());
}
_translations[ordering] = value;
return ordering;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using SendSMS.WebAPI.Areas.HelpPage.ModelDescriptions;
using SendSMS.WebAPI.Areas.HelpPage.Models;
namespace SendSMS.WebAPI.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
/*
* Copyright (c) 2007-2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.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.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Text;
namespace OpenMetaverse.StructuredData
{
/// <summary>
///
/// </summary>
public static partial class OSDParser
{
private static XmlSchema XmlSchema;
private static XmlTextReader XmlTextReader;
private static string LastXmlErrors = String.Empty;
private static object XmlValidationLock = new object();
/// <summary>
///
/// </summary>
/// <param name="xmlData"></param>
/// <returns></returns>
public static OSD DeserializeLLSDXml(byte[] xmlData)
{
return DeserializeLLSDXml(new XmlTextReader(new MemoryStream(xmlData, false)));
}
public static OSD DeserializeLLSDXml(Stream xmlStream)
{
return DeserializeLLSDXml(new XmlTextReader(xmlStream));
}
/// <summary>
///
/// </summary>
/// <param name="xmlData"></param>
/// <returns></returns>
public static OSD DeserializeLLSDXml(string xmlData)
{
byte[] bytes = Utils.StringToBytes(xmlData);
return DeserializeLLSDXml(new XmlTextReader(new MemoryStream(bytes, false)));
}
/// <summary>
///
/// </summary>
/// <param name="xmlData"></param>
/// <returns></returns>
public static OSD DeserializeLLSDXml(XmlTextReader xmlData)
{
try
{
xmlData.Read();
SkipWhitespace(xmlData);
xmlData.Read();
OSD ret = ParseLLSDXmlElement(xmlData);
return ret;
}
catch
{
return new OSD();
}
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static byte[] SerializeLLSDXmlBytes(OSD data)
{
return Encoding.UTF8.GetBytes(SerializeLLSDXmlString(data));
}
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static string SerializeLLSDXmlString(OSD data)
{
StringWriter sw = new StringWriter();
XmlTextWriter writer = new XmlTextWriter(sw);
writer.Formatting = Formatting.None;
writer.WriteStartElement(String.Empty, "llsd", String.Empty);
SerializeLLSDXmlElement(writer, data);
writer.WriteEndElement();
writer.Close();
return sw.ToString();
}
/// <summary>
///
/// </summary>
/// <param name="writer"></param>
/// <param name="data"></param>
public static void SerializeLLSDXmlElement(XmlTextWriter writer, OSD data)
{
switch (data.Type)
{
case OSDType.Unknown:
writer.WriteStartElement(String.Empty, "undef", String.Empty);
writer.WriteEndElement();
break;
case OSDType.Boolean:
writer.WriteStartElement(String.Empty, "boolean", String.Empty);
writer.WriteString(data.AsString());
writer.WriteEndElement();
break;
case OSDType.Integer:
writer.WriteStartElement(String.Empty, "integer", String.Empty);
writer.WriteString(data.AsString());
writer.WriteEndElement();
break;
case OSDType.Real:
writer.WriteStartElement(String.Empty, "real", String.Empty);
writer.WriteString(data.AsString());
writer.WriteEndElement();
break;
case OSDType.String:
writer.WriteStartElement(String.Empty, "string", String.Empty);
writer.WriteString(data.AsString());
writer.WriteEndElement();
break;
case OSDType.UUID:
writer.WriteStartElement(String.Empty, "uuid", String.Empty);
writer.WriteString(data.AsString());
writer.WriteEndElement();
break;
case OSDType.Date:
writer.WriteStartElement(String.Empty, "date", String.Empty);
writer.WriteString(data.AsString());
writer.WriteEndElement();
break;
case OSDType.URI:
writer.WriteStartElement(String.Empty, "uri", String.Empty);
writer.WriteString(data.AsString());
writer.WriteEndElement();
break;
case OSDType.Binary:
writer.WriteStartElement(String.Empty, "binary", String.Empty);
writer.WriteStartAttribute(String.Empty, "encoding", String.Empty);
writer.WriteString("base64");
writer.WriteEndAttribute();
writer.WriteString(data.AsString());
writer.WriteEndElement();
break;
case OSDType.Map:
OSDMap map = (OSDMap)data;
writer.WriteStartElement(String.Empty, "map", String.Empty);
foreach (KeyValuePair<string, OSD> kvp in map)
{
writer.WriteStartElement(String.Empty, "key", String.Empty);
writer.WriteString(kvp.Key);
writer.WriteEndElement();
SerializeLLSDXmlElement(writer, kvp.Value);
}
writer.WriteEndElement();
break;
case OSDType.Array:
OSDArray array = (OSDArray)data;
writer.WriteStartElement(String.Empty, "array", String.Empty);
for (int i = 0; i < array.Count; i++)
{
SerializeLLSDXmlElement(writer, array[i]);
}
writer.WriteEndElement();
break;
}
}
/// <summary>
///
/// </summary>
/// <param name="xmlData"></param>
/// <param name="error"></param>
/// <returns></returns>
public static bool TryValidateLLSDXml(XmlTextReader xmlData, out string error)
{
lock (XmlValidationLock)
{
LastXmlErrors = String.Empty;
XmlTextReader = xmlData;
CreateLLSDXmlSchema();
XmlReaderSettings readerSettings = new XmlReaderSettings();
readerSettings.ValidationType = ValidationType.Schema;
readerSettings.Schemas.Add(XmlSchema);
readerSettings.ValidationEventHandler += new ValidationEventHandler(LLSDXmlSchemaValidationHandler);
XmlReader reader = XmlReader.Create(xmlData, readerSettings);
try
{
while (reader.Read()) { }
}
catch (XmlException)
{
error = LastXmlErrors;
return false;
}
if (LastXmlErrors == String.Empty)
{
error = null;
return true;
}
else
{
error = LastXmlErrors;
return false;
}
}
}
/// <summary>
///
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
private static OSD ParseLLSDXmlElement(XmlTextReader reader)
{
SkipWhitespace(reader);
if (reader.NodeType != XmlNodeType.Element)
throw new OSDException("Expected an element");
string type = reader.LocalName;
OSD ret;
switch (type)
{
case "undef":
if (reader.IsEmptyElement)
{
reader.Read();
return new OSD();
}
reader.Read();
SkipWhitespace(reader);
ret = new OSD();
break;
case "boolean":
if (reader.IsEmptyElement)
{
reader.Read();
return OSD.FromBoolean(false);
}
if (reader.Read())
{
string s = reader.ReadString().Trim();
if (!String.IsNullOrEmpty(s) && (s == "true" || s == "1"))
{
ret = OSD.FromBoolean(true);
break;
}
}
ret = OSD.FromBoolean(false);
break;
case "integer":
if (reader.IsEmptyElement)
{
reader.Read();
return OSD.FromInteger(0);
}
if (reader.Read())
{
int value = 0;
Int32.TryParse(reader.ReadString().Trim(), out value);
ret = OSD.FromInteger(value);
break;
}
ret = OSD.FromInteger(0);
break;
case "real":
if (reader.IsEmptyElement)
{
reader.Read();
return OSD.FromReal(0d);
}
if (reader.Read())
{
double value = 0d;
string str = reader.ReadString().Trim().ToLower();
if (str == "nan")
value = Double.NaN;
else
Utils.TryParseDouble(str, out value);
ret = OSD.FromReal(value);
break;
}
ret = OSD.FromReal(0d);
break;
case "uuid":
if (reader.IsEmptyElement)
{
reader.Read();
return OSD.FromUUID(UUID.Zero);
}
if (reader.Read())
{
UUID value = UUID.Zero;
UUID.TryParse(reader.ReadString().Trim(), out value);
ret = OSD.FromUUID(value);
break;
}
ret = OSD.FromUUID(UUID.Zero);
break;
case "date":
if (reader.IsEmptyElement)
{
reader.Read();
return OSD.FromDate(Utils.Epoch);
}
if (reader.Read())
{
DateTime value = Utils.Epoch;
DateTime.TryParse(reader.ReadString().Trim(), out value);
ret = OSD.FromDate(value);
break;
}
ret = OSD.FromDate(Utils.Epoch);
break;
case "string":
if (reader.IsEmptyElement)
{
reader.Read();
return OSD.FromString(String.Empty);
}
if (reader.Read())
{
ret = OSD.FromString(reader.ReadString());
break;
}
ret = OSD.FromString(String.Empty);
break;
case "binary":
if (reader.IsEmptyElement)
{
reader.Read();
return OSD.FromBinary(Utils.EmptyBytes);
}
if (reader.GetAttribute("encoding") != null && reader.GetAttribute("encoding") != "base64")
throw new OSDException("Unsupported binary encoding: " + reader.GetAttribute("encoding"));
if (reader.Read())
{
try
{
ret = OSD.FromBinary(Convert.FromBase64String(reader.ReadString().Trim()));
break;
}
catch (FormatException ex)
{
throw new OSDException("Binary decoding exception: " + ex.Message);
}
}
ret = OSD.FromBinary(Utils.EmptyBytes);
break;
case "uri":
if (reader.IsEmptyElement)
{
reader.Read();
return OSD.FromUri(new Uri(String.Empty, UriKind.RelativeOrAbsolute));
}
if (reader.Read())
{
ret = OSD.FromUri(new Uri(reader.ReadString(), UriKind.RelativeOrAbsolute));
break;
}
ret = OSD.FromUri(new Uri(String.Empty, UriKind.RelativeOrAbsolute));
break;
case "map":
return ParseLLSDXmlMap(reader);
case "array":
return ParseLLSDXmlArray(reader);
default:
reader.Read();
ret = null;
break;
}
if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != type)
{
throw new OSDException("Expected </" + type + ">");
}
else
{
reader.Read();
return ret;
}
}
private static OSDMap ParseLLSDXmlMap(XmlTextReader reader)
{
if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "map")
throw new NotImplementedException("Expected <map>");
OSDMap map = new OSDMap();
if (reader.IsEmptyElement)
{
reader.Read();
return map;
}
if (reader.Read())
{
while (true)
{
SkipWhitespace(reader);
if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "map")
{
reader.Read();
break;
}
if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "key")
throw new OSDException("Expected <key>");
string key = reader.ReadString();
if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != "key")
throw new OSDException("Expected </key>");
if (reader.Read())
map[key] = ParseLLSDXmlElement(reader);
else
throw new OSDException("Failed to parse a value for key " + key);
}
}
return map;
}
private static OSDArray ParseLLSDXmlArray(XmlTextReader reader)
{
if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "array")
throw new OSDException("Expected <array>");
OSDArray array = new OSDArray();
if (reader.IsEmptyElement)
{
reader.Read();
return array;
}
if (reader.Read())
{
while (true)
{
SkipWhitespace(reader);
if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "array")
{
reader.Read();
break;
}
array.Add(ParseLLSDXmlElement(reader));
}
}
return array;
}
private static void SkipWhitespace(XmlTextReader reader)
{
while (
reader.NodeType == XmlNodeType.Comment ||
reader.NodeType == XmlNodeType.Whitespace ||
reader.NodeType == XmlNodeType.SignificantWhitespace ||
reader.NodeType == XmlNodeType.XmlDeclaration)
{
reader.Read();
}
}
private static void CreateLLSDXmlSchema()
{
if (XmlSchema == null)
{
#region XSD
string schemaText = @"
<?xml version=""1.0"" encoding=""utf-8""?>
<xs:schema elementFormDefault=""qualified"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"">
<xs:import schemaLocation=""xml.xsd"" namespace=""http://www.w3.org/XML/1998/namespace"" />
<xs:element name=""uri"" type=""xs:string"" />
<xs:element name=""uuid"" type=""xs:string"" />
<xs:element name=""KEYDATA"">
<xs:complexType>
<xs:sequence>
<xs:element ref=""key"" />
<xs:element ref=""DATA"" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name=""date"" type=""xs:string"" />
<xs:element name=""key"" type=""xs:string"" />
<xs:element name=""boolean"" type=""xs:string"" />
<xs:element name=""undef"">
<xs:complexType>
<xs:sequence>
<xs:element ref=""EMPTY"" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name=""map"">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs=""0"" maxOccurs=""unbounded"" ref=""KEYDATA"" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name=""real"" type=""xs:string"" />
<xs:element name=""ATOMIC"">
<xs:complexType>
<xs:choice>
<xs:element ref=""undef"" />
<xs:element ref=""boolean"" />
<xs:element ref=""integer"" />
<xs:element ref=""real"" />
<xs:element ref=""uuid"" />
<xs:element ref=""string"" />
<xs:element ref=""date"" />
<xs:element ref=""uri"" />
<xs:element ref=""binary"" />
</xs:choice>
</xs:complexType>
</xs:element>
<xs:element name=""DATA"">
<xs:complexType>
<xs:choice>
<xs:element ref=""ATOMIC"" />
<xs:element ref=""map"" />
<xs:element ref=""array"" />
</xs:choice>
</xs:complexType>
</xs:element>
<xs:element name=""llsd"">
<xs:complexType>
<xs:sequence>
<xs:element ref=""DATA"" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name=""binary"">
<xs:complexType>
<xs:simpleContent>
<xs:extension base=""xs:string"">
<xs:attribute default=""base64"" name=""encoding"" type=""xs:string"" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
<xs:element name=""array"">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs=""0"" maxOccurs=""unbounded"" ref=""DATA"" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name=""integer"" type=""xs:string"" />
<xs:element name=""string"">
<xs:complexType>
<xs:simpleContent>
<xs:extension base=""xs:string"">
<xs:attribute ref=""xml:space"" />
</xs:extension>
</xs:simpleContent>
</xs:complexType>
</xs:element>
</xs:schema>
";
#endregion XSD
MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(schemaText));
XmlSchema = new XmlSchema();
XmlSchema = XmlSchema.Read(stream, new ValidationEventHandler(LLSDXmlSchemaValidationHandler));
}
}
private static void LLSDXmlSchemaValidationHandler(object sender, ValidationEventArgs args)
{
string error = String.Format("Line: {0} - Position: {1} - {2}", XmlTextReader.LineNumber, XmlTextReader.LinePosition,
args.Message);
if (LastXmlErrors == String.Empty)
LastXmlErrors = error;
else
LastXmlErrors += Environment.NewLine + error;
}
}
}
| |
// Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
using Avalonia.Input;
using Avalonia.Layout;
namespace Avalonia.Controls
{
/// <summary>
/// A panel that displays child controls at arbitrary locations.
/// </summary>
/// <remarks>
/// Unlike other <see cref="Panel"/> implementations, the <see cref="Canvas"/> doesn't lay out
/// its children in any particular layout. Instead, the positioning of each child control is
/// defined by the <code>Canvas.Left</code>, <code>Canvas.Top</code>, <code>Canvas.Right</code>
/// and <code>Canvas.Bottom</code> attached properties.
/// </remarks>
public class Canvas : Panel, INavigableContainer
{
/// <summary>
/// Defines the Left attached property.
/// </summary>
public static readonly AttachedProperty<double> LeftProperty =
AvaloniaProperty.RegisterAttached<Canvas, Control, double>("Left", double.NaN);
/// <summary>
/// Defines the Top attached property.
/// </summary>
public static readonly AttachedProperty<double> TopProperty =
AvaloniaProperty.RegisterAttached<Canvas, Control, double>("Top", double.NaN);
/// <summary>
/// Defines the Right attached property.
/// </summary>
public static readonly AttachedProperty<double> RightProperty =
AvaloniaProperty.RegisterAttached<Canvas, Control, double>("Right", double.NaN);
/// <summary>
/// Defines the Bottom attached property.
/// </summary>
public static readonly AttachedProperty<double> BottomProperty =
AvaloniaProperty.RegisterAttached<Canvas, Control, double>("Bottom", double.NaN);
/// <summary>
/// Initializes static members of the <see cref="Canvas"/> class.
/// </summary>
static Canvas()
{
ClipToBoundsProperty.OverrideDefaultValue<Canvas>(false);
AffectsParentArrange<Canvas>(LeftProperty, TopProperty, RightProperty, BottomProperty);
}
/// <summary>
/// Gets the value of the Left attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <returns>The control's left coordinate.</returns>
public static double GetLeft(AvaloniaObject element)
{
return element.GetValue(LeftProperty);
}
/// <summary>
/// Sets the value of the Left attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <param name="value">The left value.</param>
public static void SetLeft(AvaloniaObject element, double value)
{
element.SetValue(LeftProperty, value);
}
/// <summary>
/// Gets the value of the Top attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <returns>The control's top coordinate.</returns>
public static double GetTop(AvaloniaObject element)
{
return element.GetValue(TopProperty);
}
/// <summary>
/// Sets the value of the Top attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <param name="value">The top value.</param>
public static void SetTop(AvaloniaObject element, double value)
{
element.SetValue(TopProperty, value);
}
/// <summary>
/// Gets the value of the Right attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <returns>The control's right coordinate.</returns>
public static double GetRight(AvaloniaObject element)
{
return element.GetValue(RightProperty);
}
/// <summary>
/// Sets the value of the Right attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <param name="value">The right value.</param>
public static void SetRight(AvaloniaObject element, double value)
{
element.SetValue(RightProperty, value);
}
/// <summary>
/// Gets the value of the Bottom attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <returns>The control's bottom coordinate.</returns>
public static double GetBottom(AvaloniaObject element)
{
return element.GetValue(BottomProperty);
}
/// <summary>
/// Sets the value of the Bottom attached property for a control.
/// </summary>
/// <param name="element">The control.</param>
/// <param name="value">The bottom value.</param>
public static void SetBottom(AvaloniaObject element, double value)
{
element.SetValue(BottomProperty, value);
}
/// <summary>
/// Gets the next control in the specified direction.
/// </summary>
/// <param name="direction">The movement direction.</param>
/// <param name="from">The control from which movement begins.</param>
/// <param name="wrap">Whether to wrap around when the first or last item is reached.</param>
/// <returns>The control.</returns>
IInputElement INavigableContainer.GetControl(NavigationDirection direction, IInputElement from, bool wrap)
{
// TODO: Implement this
return null;
}
/// <summary>
/// Measures the control.
/// </summary>
/// <param name="availableSize">The available size.</param>
/// <returns>The desired size of the control.</returns>
protected override Size MeasureOverride(Size availableSize)
{
availableSize = new Size(double.PositiveInfinity, double.PositiveInfinity);
foreach (Control child in Children)
{
child.Measure(availableSize);
}
return new Size();
}
/// <summary>
/// Arranges the control's children.
/// </summary>
/// <param name="finalSize">The size allocated to the control.</param>
/// <returns>The space taken.</returns>
protected override Size ArrangeOverride(Size finalSize)
{
foreach (Control child in Children)
{
double x = 0.0;
double y = 0.0;
double elementLeft = GetLeft(child);
if (!double.IsNaN(elementLeft))
{
x = elementLeft;
}
else
{
// Arrange with right.
double elementRight = GetRight(child);
if (!double.IsNaN(elementRight))
{
x = finalSize.Width - child.DesiredSize.Width - elementRight;
}
}
double elementTop = GetTop(child);
if (!double.IsNaN(elementTop) )
{
y = elementTop;
}
else
{
double elementBottom = GetBottom(child);
if (!double.IsNaN(elementBottom))
{
y = finalSize.Height - child.DesiredSize.Height - elementBottom;
}
}
child.Arrange(new Rect(new Point(x, y), child.DesiredSize));
}
return finalSize;
}
}
}
| |
using System;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.esriSystem;
using System.Runtime.InteropServices;
using ESRI.ArcGIS.DataSourcesGDB;
using System.IO;
namespace FGDB_Crawler_CSVGen
{
class Program
{
[STAThread()]
static void Main(string[] args)
{
// Don't show the "program stopped working" popup if a file/path cannot be opened
AppDomain.CurrentDomain.UnhandledException += (sender, eargs) =>
{
Console.Error.WriteLine("Unhandled exception: " + eargs.ExceptionObject);
Environment.Exit(1);
};
// The user must specify the root path to be explored (i.e. a path containing File GeoDatabases (*.gdb)
// as well as an output csv file
if (args.Length != 3)
{
usageExit();
}
else
{
// Bind this ArcObjects application to this machine's ArcGIS license
ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop);
// Fetch the License
ESRI.ArcGIS.esriSystem.IAoInitialize ao = new ESRI.ArcGIS.esriSystem.AoInitialize();
esriLicenseStatus status = ao.Initialize(ESRI.ArcGIS.esriSystem.esriLicenseProductCode.esriLicenseProductCodeStandard);
string option = args[0];
string rootPath = args[1]; // Target path is the first argument of the console application
string outfile = args[2]; // Output CSV file is the second argument
outfile = toCSVPath(outfile);
switch (option)
{
case "-p": // Path to a File GeoDatabase
testFGDBPath(rootPath);
Console.WriteLine("Processing... please wait.");
printCSVHeader(outfile);
exploreFGDB(rootPath, outfile);
break;
case "-P": // Path to a File GeoDatabase
testFGDBPath(rootPath);
Console.WriteLine("Processing... please wait.");
printCSVHeader(outfile);
exploreFGDB(rootPath, outfile);
break;
case "-r": // Root directory that contains File GeoDatabases
exploreRootDirectory(rootPath, outfile);
break;
case "-R": // Root directory that contains File GeoDatabases
exploreRootDirectory(rootPath, outfile);
break;
default:
usageExit();
break;
}
Console.WriteLine("Done Processing.");
System.Environment.Exit(0);
}
}
// If there is no '.csv' file extension, then append '.csv' to the end of the path.
// Otherwise, return the original string
private static string toCSVPath(string path)
{
string fileExt = Path.GetExtension(path); // Get this folder's file extension
if (fileExt != ".csv") return path + ".csv";
else return path;
}
private static void testFGDBPath(string path)
{
string fileExt = Path.GetExtension(path); // Get this folder's file extension
if (fileExt != ".gdb")
{
Console.Error.WriteLine("Error: \"" + path + "\" : No .gdb extension found!");
Console.Error.WriteLine("Aborting.");
System.Environment.Exit(1);
}
if (!(Directory.Exists(path)))
{
Console.Error.WriteLine("Error: \"" + path + "\" : No such directory!");
Console.Error.WriteLine("Aborting.");
System.Environment.Exit(1);
}
}
private static void exploreRootDirectory(string rootPath, string outfile)
{
string[] folders = null;
try
{
folders = Directory.GetDirectories(rootPath);
}
catch (Exception exc)
{
Console.WriteLine("Error: Could not find the specified path: \"" + rootPath + "\"");
Console.WriteLine(exc.InnerException.Message);
System.Environment.Exit(1);
}
Console.WriteLine();
Console.WriteLine("Processing... please wait.");
// Print the CSV Header
printCSVHeader(outfile);
foreach (string folder in folders) // For each folder in the root path
{
try
{
string fileExt = Path.GetExtension(folder); // Get this folder's file extension
if (fileExt != ".gdb") continue; // If the folder is not a File GeoDatabase, skip it
exploreFGDB(folder, outfile); // Process the File GeoDatabase
}
catch (Exception)
{
continue;
}
}
}
private static void usageExit()
{
Console.Error.WriteLine("Usage: Use one of the following:");
Console.Error.WriteLine("\t.\\FGDB-Crawler-CSVGen.exe -p path.gdb outputFile.csv");
Console.Error.WriteLine("\t.\\FGDB-Crawler-CSVGen.exe -r targetPath outputFile.csv");
Console.Error.WriteLine("Aborting.");
System.Environment.Exit(1);
}
// Print the CSV Header to the output CSV file 'outfile'
private static void printCSVHeader(string outfile)
{
string csvHeader = "Full Path,Local Path,Name,Category,Type,Full Name,Last Accessed (GMT),Time Created (GMT),Date Modified (GMT),File Size on Disk";
csvHeader += Environment.NewLine;
System.IO.File.WriteAllText(outfile, csvHeader);
}
// Append string 'str' to output CSV file 'filename'
private static void appendToFile(string filename, string str)
{
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(filename, true))
{
file.Write(str);
file.Flush();
file.Close();
}
}
// Explore the File GeoDatabase specified in fgdbPath, print information about its contents to the CSV file 'outfile'
private static void exploreFGDB(string fgdbPath, string outfile)
{
IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(typeof(FileGDBWorkspaceFactoryClass));
IFeatureWorkspace ifw = (IFeatureWorkspace)workspaceFactory.OpenFromFile(fgdbPath, 0);
if (ifw == null) return;
IWorkspace fw = workspaceFactory.OpenFromFile(fgdbPath, 0);
IEnumDataset datasets = fw.Datasets[esriDatasetType.esriDTAny];
processIEnumDataset(outfile, ifw, datasets, 0, "", fgdbPath);
}
// Recursively explore an IEnumDataset
private static void processIEnumDataset(string outfile, IFeatureWorkspace ifw, IEnumDataset datasets, int depth, string localPath, string fgdbPath)
{
if (datasets == null) return;
datasets.Reset();
IDataset dataset;
// Iterate through the entire dataset
while (null != (dataset = datasets.Next()))
{
// Process the current dataset
processIDataset(outfile, ifw, dataset, depth, localPath, fgdbPath);
}
}
private static void processIDataset(string outfile, IFeatureWorkspace ifw, IDataset dataset, int depth, string localPath, string fgdbPath)
{
string newLocalPath = localPath + "/" + dataset.Name.ToString();
// Print information about this dataset to the CSV
appendToFile(outfile, fgdbPath + ",");
appendToFile(outfile, newLocalPath + ",");
appendToFile(outfile, dataset.Name.ToString() + ",");
appendToFile(outfile, dataset.Category.ToString() + ",");
appendToFile(outfile, dataset.Type.ToString() + ",");
appendToFile(outfile, dataset.FullName.ToString() + ",");
printIDatasetSizeAndTime(outfile, ifw, dataset.Name.ToString(), depth);
// If this dataset has children, iterate through its children
IEnumDataset children = dataset.Subsets;
processIEnumDataset(outfile, ifw, children, depth + 1, newLocalPath, fgdbPath);
}
// Print the IDataset's size and time. If it doesn't have any, print a message and then return
private static void printIDatasetSizeAndTime(string outfile, IFeatureWorkspace ifw, string name, int depth)
{
try
{
var pTable = ifw.OpenTable(name);
if (pTable == null) return;
var pDFS = (IDatasetFileStat)pTable;
if (pDFS == null) return;
// Date Modified
var unixtimestmap = pDFS.StatTime[esriDatasetFileStatTimeMode.esriDatasetFileStatTimeLastModification];
appendToFile(outfile, unixTimeStampToString(unixtimestmap) + ",");
// Time Created
unixtimestmap = pDFS.StatTime[esriDatasetFileStatTimeMode.esriDatasetFileStatTimeCreation];
appendToFile(outfile, unixTimeStampToString(unixtimestmap) + ",");
// Last Accessed
unixtimestmap = pDFS.StatTime[esriDatasetFileStatTimeMode.esriDatasetFileStatTimeLastAccess];
appendToFile(outfile, unixTimeStampToString(unixtimestmap) + ",");
// File Size on Disk
string sizeBytes = pDFS.StatSize.ToString();
appendToFile(outfile, convertBytes(sizeBytes) + Environment.NewLine);
}
catch (COMException e)
{
// Can't open table ; can't get info about date modified / time created / last accessed / file size on disk
// so fields will be left blank in the CSV
appendToFile(outfile, ",,," + Environment.NewLine);
return;
}
}
// Convert a Unix timestaop to a readable string
private static string unixTimeStampToString(int timestamp)
{
DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
DateTime dtResult = dt.AddSeconds(Convert.ToDouble(timestamp));
return dtResult.ToString();
}
// Given a number of bytes, return a readable string to 2 decimal places
private static string convertBytes(string numBytes)
{
double bytes = double.Parse(numBytes);
string result;
if (bytes >= 1099511627776)
{
double terabytes = bytes / 1099511627776;
result = Math.Round(Convert.ToDecimal(terabytes), 2).ToString() + " TB";
}
else if (bytes >= 1073741824)
{
double gigabytes = bytes / 1073741824;
result = Math.Round(Convert.ToDecimal(gigabytes), 2).ToString() + " GB";
}
else if (bytes >= 1048576)
{
double megabytes = bytes / 1048576;
result = Math.Round(Convert.ToDecimal(megabytes), 2).ToString() + " MB";
}
else if (bytes >= 1024)
{
double kilobytes = bytes / 1024;
result = Math.Round(Convert.ToDecimal(kilobytes), 2).ToString() + " KB";
}
else
{
result = Math.Round(Convert.ToDecimal(bytes), 2).ToString() + " bytes";
}
return result;
}
}
}
| |
using Microsoft.VisualStudio.Services.Agent.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
namespace Microsoft.VisualStudio.Services.Agent.Worker.Build
{
[ServiceLocator(Default = typeof(GitCommandManager))]
public interface IGitCommandManager : IAgentService
{
bool EnsureGitVersion(Version requiredVersion, bool throwOnNotMatch);
// setup git execution info, git location, version, useragent, execpath
Task LoadGitExecutionInfo(IExecutionContext context, bool useBuiltInGit);
// git init <LocalDir>
Task<int> GitInit(IExecutionContext context, string repositoryPath);
// git fetch --tags --prune --progress --no-recurse-submodules [--depth=15] origin [+refs/pull/*:refs/remote/pull/*]
Task<int> GitFetch(IExecutionContext context, string repositoryPath, string remoteName, int fetchDepth, List<string> refSpec, string additionalCommandLine, CancellationToken cancellationToken);
// git lfs fetch origin [ref]
Task<int> GitLFSFetch(IExecutionContext context, string repositoryPath, string remoteName, string refSpec, string additionalCommandLine, CancellationToken cancellationToken);
// git checkout -f --progress <commitId/branch>
Task<int> GitCheckout(IExecutionContext context, string repositoryPath, string committishOrBranchSpec, CancellationToken cancellationToken);
// git clean -fdx
Task<int> GitClean(IExecutionContext context, string repositoryPath);
// git reset --hard HEAD
Task<int> GitReset(IExecutionContext context, string repositoryPath);
// get remote add <origin> <url>
Task<int> GitRemoteAdd(IExecutionContext context, string repositoryPath, string remoteName, string remoteUrl);
// get remote set-url <origin> <url>
Task<int> GitRemoteSetUrl(IExecutionContext context, string repositoryPath, string remoteName, string remoteUrl);
// get remote set-url --push <origin> <url>
Task<int> GitRemoteSetPushUrl(IExecutionContext context, string repositoryPath, string remoteName, string remoteUrl);
// git submodule foreach git clean -fdx
Task<int> GitSubmoduleClean(IExecutionContext context, string repositoryPath);
// git submodule foreach git reset --hard HEAD
Task<int> GitSubmoduleReset(IExecutionContext context, string repositoryPath);
// git submodule update --init --force [--recursive]
Task<int> GitSubmoduleUpdate(IExecutionContext context, string repositoryPath, string additionalCommandLine, bool recursive, CancellationToken cancellationToken);
// git submodule sync [--recursive]
Task<int> GitSubmoduleSync(IExecutionContext context, string repositoryPath, bool recursive, CancellationToken cancellationToken);
// git config --get remote.origin.url
Task<Uri> GitGetFetchUrl(IExecutionContext context, string repositoryPath);
// git config <key> <value>
Task<int> GitConfig(IExecutionContext context, string repositoryPath, string configKey, string configValue);
// git config --get-all <key>
Task<bool> GitConfigExist(IExecutionContext context, string repositoryPath, string configKey);
// git config --unset-all <key>
Task<int> GitConfigUnset(IExecutionContext context, string repositoryPath, string configKey);
// git config gc.auto 0
Task<int> GitDisableAutoGC(IExecutionContext context, string repositoryPath);
// git lfs version
Task<int> GitLFSVersion(IExecutionContext context, string repositoryPath);
// git lfs install --local
Task<int> GitLFSInstall(IExecutionContext context, string repositoryPath);
// git lfs logs last
Task<int> GitLFSLogs(IExecutionContext context, string repositoryPath);
// git version
Task<Version> GitVersion(IExecutionContext context);
}
public class GitCommandManager : AgentService, IGitCommandManager
{
#if OS_WINDOWS
private static readonly Encoding s_encoding = Encoding.UTF8;
#else
private static readonly Encoding s_encoding = null;
#endif
private string _gitHttpUserAgentEnv = null;
private string _gitPath = null;
private Version _version = null;
public bool EnsureGitVersion(Version requiredVersion, bool throwOnNotMatch)
{
ArgUtil.NotNull(_gitPath, nameof(_gitPath));
ArgUtil.NotNull(_version, nameof(_version));
if (_version < requiredVersion && throwOnNotMatch)
{
throw new NotSupportedException(StringUtil.Loc("MinRequiredGitVersion", requiredVersion, _gitPath, _version));
}
return _version >= requiredVersion;
}
public async Task LoadGitExecutionInfo(IExecutionContext context, bool useBuiltInGit)
{
// Resolve the location of git.
if (useBuiltInGit)
{
#if OS_WINDOWS
_gitPath = Path.Combine(IOUtil.GetExternalsPath(), "git", "cmd", $"git{IOUtil.ExeExtension}");
// Prepend the PATH.
context.Output(StringUtil.Loc("Prepending0WithDirectoryContaining1", Constants.PathVariable, Path.GetFileName(_gitPath)));
var varUtil = HostContext.GetService<IVarUtil>();
varUtil.PrependPath(Path.GetDirectoryName(_gitPath));
context.Debug($"{Constants.PathVariable}: '{Environment.GetEnvironmentVariable(Constants.PathVariable)}'");
#else
// There is no built-in git for OSX/Linux
_gitPath = null;
#endif
}
else
{
var whichUtil = HostContext.GetService<IWhichUtil>();
_gitPath = whichUtil.Which("git", require: true);
}
ArgUtil.File(_gitPath, nameof(_gitPath));
// Get the Git version.
_version = await GitVersion(context);
ArgUtil.NotNull(_version, nameof(_version));
context.Debug($"Detect git version: {_version.ToString()}.");
// required 2.0, all git operation commandline args need min git version 2.0
Version minRequiredGitVersion = new Version(2, 0);
EnsureGitVersion(minRequiredGitVersion, throwOnNotMatch: true);
// suggest user upgrade to 2.9 for better git experience
Version recommendGitVersion = new Version(2, 9);
if (!EnsureGitVersion(recommendGitVersion, throwOnNotMatch: false))
{
context.Output(StringUtil.Loc("UpgradeToLatestGit", recommendGitVersion, _version));
}
// Set the user agent.
_gitHttpUserAgentEnv = $"git/{_version.ToString()} (vsts-agent-git/{Constants.Agent.Version})";
context.Debug($"Set git useragent to: {_gitHttpUserAgentEnv}.");
}
// git init <LocalDir>
public async Task<int> GitInit(IExecutionContext context, string repositoryPath)
{
context.Debug($"Init git repository at: {repositoryPath}.");
string repoRootEscapeSpace = StringUtil.Format(@"""{0}""", repositoryPath.Replace(@"""", @"\"""));
return await ExecuteGitCommandAsync(context, repositoryPath, "init", StringUtil.Format($"{repoRootEscapeSpace}"));
}
// git fetch --tags --prune --progress --no-recurse-submodules [--depth=15] origin [+refs/pull/*:refs/remote/pull/*]
public async Task<int> GitFetch(IExecutionContext context, string repositoryPath, string remoteName, int fetchDepth, List<string> refSpec, string additionalCommandLine, CancellationToken cancellationToken)
{
context.Debug($"Fetch git repository at: {repositoryPath} remote: {remoteName}.");
if (refSpec != null && refSpec.Count > 0)
{
refSpec = refSpec.Where(r => !string.IsNullOrEmpty(r)).ToList();
}
// default options for git fetch.
string options = StringUtil.Format($"--tags --prune --progress --no-recurse-submodules {remoteName} {string.Join(" ", refSpec)}");
// If shallow fetch add --depth arg
// If the local repository is shallowed but there is no fetch depth provide for this build,
// add --unshallow to convert the shallow repository to a complete repository
if (fetchDepth > 0)
{
options = StringUtil.Format($"--tags --prune --progress --no-recurse-submodules --depth={fetchDepth} {remoteName} {string.Join(" ", refSpec)}");
}
else
{
if (File.Exists(Path.Combine(repositoryPath, ".git", "shallow")))
{
options = StringUtil.Format($"--tags --prune --progress --no-recurse-submodules --unshallow {remoteName} {string.Join(" ", refSpec)}");
}
}
return await ExecuteGitCommandAsync(context, repositoryPath, "fetch", options, additionalCommandLine, cancellationToken);
}
// git lfs fetch origin [ref]
public async Task<int> GitLFSFetch(IExecutionContext context, string repositoryPath, string remoteName, string refSpec, string additionalCommandLine, CancellationToken cancellationToken)
{
context.Debug($"Fetch LFS objects for git repository at: {repositoryPath} remote: {remoteName}.");
// default options for git lfs fetch.
string options = StringUtil.Format($"fetch origin {refSpec}");
return await ExecuteGitCommandAsync(context, repositoryPath, "lfs", options, additionalCommandLine, cancellationToken);
}
// git checkout -f --progress <commitId/branch>
public async Task<int> GitCheckout(IExecutionContext context, string repositoryPath, string committishOrBranchSpec, CancellationToken cancellationToken)
{
context.Debug($"Checkout {committishOrBranchSpec}.");
// Git 2.7 support report checkout progress to stderr during stdout/err redirect.
string options;
if (_version >= new Version(2, 7))
{
options = StringUtil.Format("--progress --force {0}", committishOrBranchSpec);
}
else
{
options = StringUtil.Format("--force {0}", committishOrBranchSpec);
}
return await ExecuteGitCommandAsync(context, repositoryPath, "checkout", options, cancellationToken);
}
// git clean -fdx
public async Task<int> GitClean(IExecutionContext context, string repositoryPath)
{
context.Debug($"Delete untracked files/folders for repository at {repositoryPath}.");
return await ExecuteGitCommandAsync(context, repositoryPath, "clean", "-fdx");
}
// git reset --hard HEAD
public async Task<int> GitReset(IExecutionContext context, string repositoryPath)
{
context.Debug($"Undo any changes to tracked files in the working tree for repository at {repositoryPath}.");
return await ExecuteGitCommandAsync(context, repositoryPath, "reset", "--hard HEAD");
}
// get remote set-url <origin> <url>
public async Task<int> GitRemoteAdd(IExecutionContext context, string repositoryPath, string remoteName, string remoteUrl)
{
context.Debug($"Add git remote: {remoteName} to url: {remoteUrl} for repository under: {repositoryPath}.");
return await ExecuteGitCommandAsync(context, repositoryPath, "remote", StringUtil.Format($"add {remoteName} {remoteUrl}"));
}
// get remote set-url <origin> <url>
public async Task<int> GitRemoteSetUrl(IExecutionContext context, string repositoryPath, string remoteName, string remoteUrl)
{
context.Debug($"Set git fetch url to: {remoteUrl} for remote: {remoteName}.");
return await ExecuteGitCommandAsync(context, repositoryPath, "remote", StringUtil.Format($"set-url {remoteName} {remoteUrl}"));
}
// get remote set-url --push <origin> <url>
public async Task<int> GitRemoteSetPushUrl(IExecutionContext context, string repositoryPath, string remoteName, string remoteUrl)
{
context.Debug($"Set git push url to: {remoteUrl} for remote: {remoteName}.");
return await ExecuteGitCommandAsync(context, repositoryPath, "remote", StringUtil.Format($"set-url --push {remoteName} {remoteUrl}"));
}
// git submodule foreach git clean -fdx
public async Task<int> GitSubmoduleClean(IExecutionContext context, string repositoryPath)
{
context.Debug($"Delete untracked files/folders for submodules at {repositoryPath}.");
return await ExecuteGitCommandAsync(context, repositoryPath, "submodule", "foreach git clean -fdx");
}
// git submodule foreach git reset --hard HEAD
public async Task<int> GitSubmoduleReset(IExecutionContext context, string repositoryPath)
{
context.Debug($"Undo any changes to tracked files in the working tree for submodules at {repositoryPath}.");
return await ExecuteGitCommandAsync(context, repositoryPath, "submodule", "foreach git reset --hard HEAD");
}
// git submodule update --init --force [--recursive]
public async Task<int> GitSubmoduleUpdate(IExecutionContext context, string repositoryPath, string additionalCommandLine, bool recursive, CancellationToken cancellationToken)
{
context.Debug("Update the registered git submodules.");
string options = "update --init --force";
if (recursive)
{
options = options + " --recursive";
}
return await ExecuteGitCommandAsync(context, repositoryPath, "submodule", options, additionalCommandLine, cancellationToken);
}
// git submodule sync [--recursive]
public async Task<int> GitSubmoduleSync(IExecutionContext context, string repositoryPath, bool recursive, CancellationToken cancellationToken)
{
context.Debug("Synchronizes submodules' remote URL configuration setting.");
string options = "sync";
if (recursive)
{
options = options + " --recursive";
}
return await ExecuteGitCommandAsync(context, repositoryPath, "submodule", options, cancellationToken);
}
// git config --get remote.origin.url
public async Task<Uri> GitGetFetchUrl(IExecutionContext context, string repositoryPath)
{
context.Debug($"Inspect remote.origin.url for repository under {repositoryPath}");
Uri fetchUrl = null;
List<string> outputStrings = new List<string>();
int exitCode = await ExecuteGitCommandAsync(context, repositoryPath, "config", "--get remote.origin.url", outputStrings);
if (exitCode != 0)
{
context.Warning($"'git config --get remote.origin.url' failed with exit code: {exitCode}, output: '{string.Join(Environment.NewLine, outputStrings)}'");
}
else
{
// remove empty strings
outputStrings = outputStrings.Where(o => !string.IsNullOrEmpty(o)).ToList();
if (outputStrings.Count == 1 && !string.IsNullOrEmpty(outputStrings.First()))
{
string remoteFetchUrl = outputStrings.First();
if (Uri.IsWellFormedUriString(remoteFetchUrl, UriKind.Absolute))
{
context.Debug($"Get remote origin fetch url from git config: {remoteFetchUrl}");
fetchUrl = new Uri(remoteFetchUrl);
}
else
{
context.Debug($"The Origin fetch url from git config: {remoteFetchUrl} is not a absolute well formed url.");
}
}
else
{
context.Debug($"Unable capture git remote fetch uri from 'git config --get remote.origin.url' command's output, the command's output is not expected: {string.Join(Environment.NewLine, outputStrings)}.");
}
}
return fetchUrl;
}
// git config <key> <value>
public async Task<int> GitConfig(IExecutionContext context, string repositoryPath, string configKey, string configValue)
{
context.Debug($"Set git config {configKey} {configValue}");
return await ExecuteGitCommandAsync(context, repositoryPath, "config", StringUtil.Format($"{configKey} {configValue}"));
}
// git config --get-all <key>
public async Task<bool> GitConfigExist(IExecutionContext context, string repositoryPath, string configKey)
{
// git config --get-all {configKey} will return 0 and print the value if the config exist.
context.Debug($"Checking git config {configKey} exist or not");
// ignore any outputs by redirect them into a string list, since the output might contains secrets.
List<string> outputStrings = new List<string>();
int exitcode = await ExecuteGitCommandAsync(context, repositoryPath, "config", StringUtil.Format($"--get-all {configKey}"), outputStrings);
return exitcode == 0;
}
// git config --unset-all <key>
public async Task<int> GitConfigUnset(IExecutionContext context, string repositoryPath, string configKey)
{
context.Debug($"Unset git config --unset-all {configKey}");
return await ExecuteGitCommandAsync(context, repositoryPath, "config", StringUtil.Format($"--unset-all {configKey}"));
}
// git config gc.auto 0
public async Task<int> GitDisableAutoGC(IExecutionContext context, string repositoryPath)
{
context.Debug("Disable git auto garbage collection.");
return await ExecuteGitCommandAsync(context, repositoryPath, "config", "gc.auto 0");
}
// git lfs version
public async Task<int> GitLFSVersion(IExecutionContext context, string repositoryPath)
{
context.Debug("Get git-lfs version.");
return await ExecuteGitCommandAsync(context, repositoryPath, "lfs", "version");
}
// git lfs install --local
public async Task<int> GitLFSInstall(IExecutionContext context, string repositoryPath)
{
context.Debug("Ensure git-lfs installed.");
return await ExecuteGitCommandAsync(context, repositoryPath, "lfs", "install --local");
}
// git lfs logs last
public async Task<int> GitLFSLogs(IExecutionContext context, string repositoryPath)
{
context.Debug("Get git-lfs logs.");
return await ExecuteGitCommandAsync(context, repositoryPath, "lfs", "logs last");
}
// git version
public async Task<Version> GitVersion(IExecutionContext context)
{
context.Debug("Get git version.");
Version version = null;
List<string> outputStrings = new List<string>();
int exitCode = await ExecuteGitCommandAsync(context, IOUtil.GetWorkPath(HostContext), "version", null, outputStrings);
context.Output($"{string.Join(Environment.NewLine, outputStrings)}");
if (exitCode == 0)
{
// remove any empty line.
outputStrings = outputStrings.Where(o => !string.IsNullOrEmpty(o)).ToList();
if (outputStrings.Count == 1 && !string.IsNullOrEmpty(outputStrings.First()))
{
string verString = outputStrings.First();
// we interested about major.minor.patch version
Regex verRegex = new Regex("\\d+\\.\\d+(\\.\\d+)?", RegexOptions.IgnoreCase);
var matchResult = verRegex.Match(verString);
if (matchResult.Success && !string.IsNullOrEmpty(matchResult.Value))
{
if (!Version.TryParse(matchResult.Value, out version))
{
version = null;
}
}
}
}
return version;
}
private async Task<int> ExecuteGitCommandAsync(IExecutionContext context, string repoRoot, string command, string options, CancellationToken cancellationToken = default(CancellationToken))
{
string arg = StringUtil.Format($"{command} {options}").Trim();
context.Command($"git {arg}");
var processInvoker = HostContext.CreateService<IProcessInvoker>();
processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
context.Output(message.Data);
};
processInvoker.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
context.Output(message.Data);
};
return await processInvoker.ExecuteAsync(
workingDirectory: repoRoot,
fileName: _gitPath,
arguments: arg,
environment: GetGitEnvironmentVariables(context),
requireExitCodeZero: false,
outputEncoding: s_encoding,
cancellationToken: cancellationToken);
}
private async Task<int> ExecuteGitCommandAsync(IExecutionContext context, string repoRoot, string command, string options, IList<string> output)
{
string arg = StringUtil.Format($"{command} {options}").Trim();
context.Command($"git {arg}");
if (output == null)
{
output = new List<string>();
}
object outputLock = new object();
var processInvoker = HostContext.CreateService<IProcessInvoker>();
processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
lock (outputLock)
{
output.Add(message.Data);
}
};
processInvoker.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
lock (outputLock)
{
output.Add(message.Data);
}
};
return await processInvoker.ExecuteAsync(
workingDirectory: repoRoot,
fileName: _gitPath,
arguments: arg,
environment: GetGitEnvironmentVariables(context),
requireExitCodeZero: false,
outputEncoding: s_encoding,
cancellationToken: default(CancellationToken));
}
private async Task<int> ExecuteGitCommandAsync(IExecutionContext context, string repoRoot, string command, string options, string additionalCommandLine, CancellationToken cancellationToken)
{
string arg = StringUtil.Format($"{additionalCommandLine} {command} {options}").Trim();
context.Command($"git {arg}");
var processInvoker = HostContext.CreateService<IProcessInvoker>();
processInvoker.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
context.Output(message.Data);
};
processInvoker.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs message)
{
context.Output(message.Data);
};
return await processInvoker.ExecuteAsync(
workingDirectory: repoRoot,
fileName: _gitPath,
arguments: arg,
environment: GetGitEnvironmentVariables(context),
requireExitCodeZero: false,
outputEncoding: s_encoding,
cancellationToken: cancellationToken);
}
private IDictionary<string, string> GetGitEnvironmentVariables(IExecutionContext context)
{
Dictionary<string, string> gitEnv = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "GIT_TERMINAL_PROMPT", "0" },
};
if (!string.IsNullOrEmpty(_gitHttpUserAgentEnv))
{
gitEnv["GIT_HTTP_USER_AGENT"] = _gitHttpUserAgentEnv;
}
// Add the public variables.
foreach (KeyValuePair<string, string> pair in context.Variables.Public)
{
// Add the variable using the formatted name.
string formattedKey = (pair.Key ?? string.Empty).Replace('.', '_').Replace(' ', '_').ToUpperInvariant();
// Skip any GIT_TRACE variable since GIT_TRACE will affect ouput from every git command.
// This will fail the parse logic for detect git version, remote url, etc.
// Ex.
// SET GIT_TRACE=true
// git version
// 11:39:58.295959 git.c:371 trace: built-in: git 'version'
// git version 2.11.1.windows.1
if (formattedKey == "GIT_TRACE" || formattedKey.StartsWith("GIT_TRACE_"))
{
continue;
}
gitEnv[formattedKey] = pair.Value ?? string.Empty;
}
return gitEnv;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Scintilla.Enums;
using Scintilla.Configuration;
using System.Resources;
using System.Reflection;
using System.Text.RegularExpressions;
namespace Scintilla
{
internal enum VOID
{
NULL
}
public partial class ScintillaControl : Control
{
static ScintillaControl()
{
// setup Enum-based-indexers
Collection<IndicatorStyle>.Setup(2080, 2081);
}
public const string DefaultDllName = "SciLexer.dll";
private static readonly object _nativeEventKey = new object();
private const int WM_KEYDOWN = 0x0100;
private const int WM_SYSKEYDOWN = 0x0104;
private Encoding _encoding;
private string _sciLexerDllName = null;
private Scintilla.Legacy.Configuration.Scintilla _legacyConfiguration;
private EventHandler<CharAddedEventArgs> _smartIndenting = null;
private IScintillaConfig _configuration;
private string _configurationLanguage = null;
private Dictionary<int, int> _ignoredKeys = new Dictionary<int, int>();
public ScintillaControl()
: this(DefaultDllName)
{
}
public ScintillaControl(string sciLexerDllName)
{
_sciLexerDllName = sciLexerDllName;
// Instantiate the indexers for this instance
IndicatorStyle = new Collection<IndicatorStyle>(this);
IndicatorForegroundColor = new IntCollection(this);
MarkerForegroundColor = new CachingIntCollection(this);
MarkerBackgroundColor = new CachingIntCollection(this);
Line = new ReadOnlyStringCollection(this);
// setup instance-based-indexers
IndicatorForegroundColor.Setup(2082, 2083);
MarkerForegroundColor.Setup(2041);
MarkerBackgroundColor.Setup(2042);
Line.Setup(2153,2350);
// Set up default encoding
_encoding = Encoding.GetEncoding(this.CodePage);
InitializeComponent();
}
public override string Text
{
get
{
return this.GetText();
}
set
{
this.SetText(value);
}
}
public void UseMonospaceFont()
{
UseMonospaceFont("font:Courier New,size:10");
}
public void UseMonospaceFont(string fontinfo)
{
this.StyleResetDefault();
Regex regex = new Regex("font:(.*),size:(.*)");
Match match = regex.Match(fontinfo);
if (match.Success)
{
string fontname = match.Groups[1].Value;
int fontsize = Int32.Parse(match.Groups[2].Value);
for (int style = 0; style <= (int)Scintilla.Enums.StylesCommon.Max; ++style)
{
if (style != (int)Scintilla.Enums.StylesCommon.LineNumber)
{
this.StyleSetFont(style, fontname);
this.StyleSetSize(style, fontsize);
}
}
}
}
protected override CreateParams CreateParams
{
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
get
{
// Otherwise Scintilla won't paint. When UserPaint is set to
// true the base Class (Control) eats the WM_PAINT message.
// Of course when this set to false we can't use the Paint
// events. This is why I'm relying on the Paint notification
// sent from scintilla to paint the Marker Arrows.
SetStyle(ControlStyles.UserPaint, false);
// Registers the Scintilla Window Class
// I'm relying on the fact that a version specific renamed
// SciLexer exists either in the Current Dir or a global path
// (See LoadLibrary Windows API Search Rules)
IntPtr handle = NativeMethods.LoadLibrary(_sciLexerDllName);
if (handle == IntPtr.Zero)
{
throw new Exception(
"Could not load Scintilla Lexer DLL '" + _sciLexerDllName
+ "'; current working directory is:\r\n" + System.IO.Directory.GetCurrentDirectory());
}
// Tell Windows Forms to create a Scintilla
// derived Window Class for this control
CreateParams cp = base.CreateParams;
cp.ClassName = "Scintilla";
return cp;
}
}
#region Event Dispatch Mechanism
[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
protected override void WndProc(ref Message m)
{
// Uh-oh. Code based on undocumented unsupported .NET behavior coming up!
// Windows Forms Sends Notify messages back to the originating
// control ORed with 0x2000. This is way cool becuase we can listen for
// WM_NOTIFY messages originating form our own hWnd (from Scintilla)
if ((m.Msg ^ 0x2000) != NativeMethods.WM_NOTIFY)
{
base.WndProc(ref m);
return;
}
SCNotification scnotification = (SCNotification)Marshal.PtrToStructure(m.LParam, typeof(SCNotification));
// dispatch to listeners of the native event first
// this allows listeners to get the raw event if they really wish
// but ideally, they'd just use the .NET event
if (Events[_nativeEventKey] != null)
((EventHandler<NativeScintillaEventArgs>)Events[_nativeEventKey])(this, new NativeScintillaEventArgs(m, scnotification));
DispatchScintillaEvent(scnotification);
base.WndProc(ref m);
}
protected event EventHandler<NativeScintillaEventArgs> NativeScintillaEvent
{
add { Events.AddHandler(_nativeEventKey, value); }
remove { Events.RemoveHandler(_nativeEventKey, value); }
}
#endregion
#region SendMessageDirect
/// <summary>
/// This is the primary Native communication method with Scintilla
/// used by this control. All the other overloads call into this one.
/// </summary>
internal IntPtr SendMessageDirect(uint msg, IntPtr wParam, IntPtr lParam)
{
Message m = new Message();
m.Msg = (int)msg;
m.WParam = wParam;
m.LParam = lParam;
m.HWnd = Handle;
// DefWndProc is the Window Proc associated with the window
// class for this control created by Windows Forms. It will
// in turn call Scintilla's DefWndProc Directly. This has
// the same net effect as using Scintilla's DirectFunction
// in that SendMessage isn't used to get the message to
// Scintilla but requires 1 less PInvoke and I don't have
// to maintain the FunctionPointer and "this" reference
DefWndProc(ref m);
return m.Result;
}
// Various overloads provided for syntactical convinience.
// note that the return value is int (32 bit signed Integer).
// If you are invoking a message that returns a pointer or
// handle like SCI_GETDIRECTFUNCTION or SCI_GETDOCPOINTER
// you MUST use the IntPtr overload to ensure 64bit compatibility
/// <summary>
/// Handles Scintilla Call Style:
/// (,)
/// </summary>
/// <param name="msg">Scintilla Message Number</param>
/// <returns></returns>
internal int SendMessageDirect(uint msg)
{
return (int)SendMessageDirect(msg, IntPtr.Zero, IntPtr.Zero);
}
/// <summary>
/// Handles Scintilla Call Style:
/// (int,int)
/// </summary>
/// <param name="msg">Scintilla Message Number</param>
/// <param name="wParam">wParam</param>
/// <param name="lParam">lParam</param>
/// <returns></returns>
internal int SendMessageDirect(uint msg, int wParam, int lParam)
{
return (int)SendMessageDirect(msg, (IntPtr)wParam, (IntPtr)lParam);
}
/// <summary>
/// Handles Scintilla Call Style:
/// (int,)
/// </summary>
/// <param name="msg">Scintilla Message Number</param>
/// <param name="wParam">wParam</param>
/// <returns></returns>
internal int SendMessageDirect(uint msg, int wParam)
{
return (int)SendMessageDirect(msg, (IntPtr)wParam, IntPtr.Zero);
}
/// <summary>
/// Handles Scintilla Call Style:
/// (,int)
/// </summary>
/// <param name="msg">Scintilla Message Number</param>
/// <param name="NULL">always pass null--Unused parameter</param>
/// <param name="lParam">lParam</param>
/// <returns></returns>
internal int SendMessageDirect(uint msg, VOID NULL, int lParam)
{
return (int)SendMessageDirect(msg, IntPtr.Zero, (IntPtr)lParam);
}
/// <summary>
/// Handles Scintilla Call Style:
/// (bool,int)
/// </summary>
/// <param name="msg">Scintilla Message Number</param>
/// <param name="wParam">boolean wParam</param>
/// <param name="lParam">int lParam</param>
/// <returns></returns>
internal int SendMessageDirect(uint msg, bool wParam, int lParam)
{
return (int)SendMessageDirect(msg, (IntPtr)(wParam ? 1 : 0), (IntPtr)lParam);
}
/// <summary>
/// Handles Scintilla Call Style:
/// (bool,)
/// </summary>
/// <param name="msg">Scintilla Message Number</param>
/// <param name="wParam">boolean wParam</param>
/// <returns></returns>
internal int SendMessageDirect(uint msg, bool wParam)
{
return (int)SendMessageDirect(msg, (IntPtr)(wParam ? 1 : 0), IntPtr.Zero);
}
/// <summary>
/// Handles Scintilla Call Style:
/// (int,bool)
/// </summary>
/// <param name="msg">Scintilla Message Number</param>
/// <param name="wParam">int wParam</param>
/// <param name="lParam">boolean lParam</param>
/// <returns></returns>
internal int SendMessageDirect(uint msg, int wParam, bool lParam)
{
return (int)SendMessageDirect(msg, (IntPtr)wParam, (IntPtr)(lParam ? 1 : 0));
}
/// <summary>
/// Handles Scintilla Call Style:
/// (,stringresult)
/// Notes:
/// Helper method to wrap all calls to messages that take a char*
/// in the lParam and returns a regular .NET String. This overload
/// assumes there will be no wParam and obtains the string length
/// by calling the message with a 0 lParam.
/// </summary>
/// <param name="msg">Scintilla Message Number</param>
/// <param name="text">String output</param>
/// <returns></returns>
internal int SendMessageDirect(uint msg, out string text)
{
int length = SendMessageDirect(msg, 0, 0);
return SendMessageDirect(msg, IntPtr.Zero, out text, length);
}
/// <summary>
/// Handles Scintilla Call Style:
/// (int,stringresult)
/// Notes:
/// Helper method to wrap all calls to messages that take a char*
/// in the lParam and returns a regular .NET String. This overload
/// assumes there will be no wParam and obtains the string length
/// by calling the message with a 0 lParam.
/// </summary>
/// <param name="msg">Scintilla Message Number</param>
/// <param name="text">String output</param>
/// <returns></returns>
internal int SendMessageDirect(uint msg, int wParam, out string text)
{
int length = SendMessageDirect(msg, 0, 0);
return SendMessageDirect(msg, (IntPtr)wParam, out text, length);
}
/// <summary>
/// Handles Scintilla Call Style:
/// (?)
/// Notes:
/// Helper method to wrap all calls to messages that take a char*
/// in the wParam and set a regular .NET String in the lParam.
/// Both the length of the string and an additional wParam are used
/// so that various string Message styles can be acommodated.
/// </summary>
/// <param name="msg">Scintilla Message Number</param>
/// <param name="wParam">int wParam</param>
/// <param name="text">String output</param>
/// <param name="length">length of the input buffer</param>
/// <returns></returns>
internal unsafe int SendMessageDirect(uint msg, IntPtr wParam, out string text, int length)
{
IntPtr ret;
// Allocate a buffer the size of the string + 1 for
// the NULL terminator. Scintilla always sets this
// regardless of the encoding
byte[] buffer = new byte[length + 1];
// Get a direct pointer to the the head of the buffer
// to pass to the message along with the wParam.
// Scintilla will fill the buffer with string data.
fixed (byte* bp = buffer)
{
ret = SendMessageDirect(msg, wParam, (IntPtr)bp);
// If this string is NULL terminated we want to trim the
// NULL before converting it to a .NET String
if (bp[length - 1] == 0)
length--;
}
// We always assume UTF8 encoding to ensure maximum
// compatibility. Manually changing the encoding to
// something else will cuase 2 Byte characters to
// be interpreted as junk.
text = _encoding.GetString(buffer, 0, length);
return (int)ret;
}
/// <summary>
/// Handles Scintilla Call Style:
/// (int,string)
/// Notes:
/// This helper method handles all messages that take
/// const char* as an input string in the lParam. In
/// some messages Scintilla expects a NULL terminated string
/// and in others it depends on the string length passed in
/// as wParam. This method handles both situations and will
/// NULL terminate the string either way.
///
/// </summary>
/// <param name="msg">Scintilla Message Number</param>
/// <param name="wParam">int wParam</param>
/// <param name="lParam">string lParam</param>
/// <returns></returns>
internal unsafe int SendMessageDirect(uint msg, int wParam, string lParam)
{
// Just as when retrieving we make to convert .NET's
// UTF-16 strings into a UTF-8 encoded byte array.
fixed (byte* bp = _encoding.GetBytes(ZeroTerminated(lParam)))
return (int)SendMessageDirect(msg, (IntPtr)wParam, (IntPtr)bp);
}
/// <summary>
/// Handles Scintilla Call Style:
/// (,string)
///
/// Notes:
/// This helper method handles all messages that take
/// const char* as an input string in the lParam. In
/// some messages Scintilla expects a NULL terminated string
/// and in others it depends on the string length passed in
/// as wParam. This method handles both situations and will
/// NULL terminate the string either way.
///
/// </summary>
/// <param name="msg">Scintilla Message Number</param>
/// <param name="NULL">always pass null--Unused parameter</param>
/// <param name="lParam">string lParam</param>
/// <returns></returns>
internal unsafe int SendMessageDirect(uint msg, VOID NULL, string lParam)
{
// Just as when retrieving we make to convert .NET's
// UTF-16 strings into a UTF-8 encoded byte array.
fixed (byte* bp = _encoding.GetBytes(ZeroTerminated(lParam)))
return (int)SendMessageDirect(msg, IntPtr.Zero, (IntPtr)bp);
}
/// <summary>
/// Handles Scintilla Call Style:
/// (string,string)
///
/// Notes:
/// Used by SCI_SETPROPERTY
/// </summary>
/// <param name="msg">Scintilla Message Number</param>
/// <param name="wParam">string wParam</param>
/// <param name="lParam">string lParam</param>
/// <returns></returns>
internal unsafe int SendMessageDirect(uint msg, string wParam, string lParam)
{
fixed (byte* bpw = _encoding.GetBytes(ZeroTerminated(wParam)))
fixed (byte* bpl = _encoding.GetBytes(ZeroTerminated(lParam)))
return (int)SendMessageDirect(msg, (IntPtr)bpw, (IntPtr)bpl);
}
/// <summary>
/// Handles Scintilla Call Style:
/// (string,stringresult)
///
/// Notes:
/// This one is used specifically by SCI_GETPROPERTY and SCI_GETPROPERTYEXPANDED
/// so it assumes it's usage
///
/// </summary>
/// <param name="msg">Scintilla Message Number</param>
/// <param name="wParam">string wParam</param>
/// <param name="stringResult">Stringresult output</param>
/// <returns></returns>
internal unsafe int SendMessageDirect(uint msg, string wParam, out string stringResult)
{
IntPtr ret;
fixed (byte* bpw = _encoding.GetBytes(ZeroTerminated(wParam)))
{
int length = (int)SendMessageDirect(msg, (IntPtr)bpw, IntPtr.Zero);
byte[] buffer = new byte[length + 1];
fixed (byte* bpl = buffer)
ret = SendMessageDirect(msg, (IntPtr)bpw, (IntPtr)bpl);
stringResult = _encoding.GetString(buffer, 0, length);
}
return (int)ret;
}
/// <summary>
/// Handles Scintilla Call Style:
/// (string,int)
/// </summary>
/// <param name="msg">Scintilla Message Number</param>
/// <param name="wParam">string wParam</param>
/// <param name="lParam">int lParam</param>
/// <returns></returns>
internal unsafe int SendMessageDirect(uint msg, string wParam, int lParam)
{
fixed (byte* bp = _encoding.GetBytes(ZeroTerminated(wParam)))
return (int)SendMessageDirect(msg, (IntPtr)bp, (IntPtr)lParam);
}
/// <summary>
/// Handles Scintilla Call Style:
/// (string,)
/// </summary>
/// <param name="msg">Scintilla Message Number</param>
/// <param name="wParam">string wParam</param>
/// <returns></returns>
internal unsafe int SendMessageDirect(uint msg, string wParam)
{
fixed (byte* bp = _encoding.GetBytes(ZeroTerminated(wParam)))
return (int)SendMessageDirect(msg, (IntPtr)bp, IntPtr.Zero);
}
private static String ZeroTerminated(string param)
{
if (string.IsNullOrEmpty(param))
return "\0";
else if (!param.EndsWith("\0"))
return param + "\0";
return param;
}
#endregion
#region Hand crafted members
// Function void AddStyledText(int,cells) skipped.
unsafe public void AddStyledText(int length, byte[] s)
{
fixed(byte* bp = s)
SendMessageDirect(2002, (IntPtr)length, (IntPtr)bp);
}
// Function int GetStyledText(,textrange) skipped.
unsafe public void GetStyledText(ref TextRange tr)
{
fixed(TextRange* trp = &tr)
SendMessageDirect(2015, IntPtr.Zero, (IntPtr)trp);
}
// Function position FindText(int,findtext) skipped.
unsafe public int FindText(int searchFlags, ref TextToFind ttf)
{
fixed(TextToFind* ttfp = &ttf)
return (int)SendMessageDirect(2150, IntPtr.Zero, (IntPtr)ttfp);
}
// Function position FormatRange(bool,formatrange) skipped.
unsafe public void FormatRange(bool bDraw, ref RangeToFormat pfr)
{
fixed(RangeToFormat* rtfp = &pfr)
SendMessageDirect(2151, IntPtr.Zero, (IntPtr)rtfp);
}
// Function int GetTextRange(,textrange) skipped.
unsafe public int GetTextRange(ref TextRange tr)
{
fixed(TextRange* trp = &tr)
return (int)SendMessageDirect(2162, IntPtr.Zero, (IntPtr)trp);
}
public char CharAt(int position)
{
return (char)SendMessageDirect(2007, position, 0);
}
public IntPtr DocPointer()
{
return SendMessageDirect(2357, IntPtr.Zero, IntPtr.Zero);
}
public IntPtr CreateDocument()
{
return SendMessageDirect(2375, IntPtr.Zero, IntPtr.Zero);
}
public void AddRefDocument(IntPtr pDoc)
{
SendMessageDirect(2376, IntPtr.Zero, pDoc);
}
public void ReleaseDocument(IntPtr pDoc)
{
SendMessageDirect(2377, IntPtr.Zero, pDoc);
}
public void AssignCmdKey(System.Windows.Forms.Keys keyDefinition, uint sciCommand)
{
SendMessageDirect(2070, (int)keyDefinition, (int)sciCommand);
}
public void ClearCmdKey(System.Windows.Forms.Keys keyDefinition)
{
SendMessageDirect(2071, (int)keyDefinition, 0);
}
/// <summary>
/// Retrieve all the text in the document. Returns number of characters retrieved.
/// </summary>
public virtual string GetText()
{
string result;
int length = SendMessageDirect(2182, 0, 0);
this.SendMessageDirect(2182, length, out result);
return result;
}
/// <summary>
/// Get the code page used to interpret the bytes of the document as characters.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual int CodePage
{
get
{
return this.SendMessageDirect(2137);
}
set
{
this.SendMessageDirect(2037, value);
this._encoding = Encoding.GetEncoding(value);
}
}
/// <summary>
/// Are white space characters currently visible? Returns one of SCWS_* constants.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual Enums.WhiteSpace ViewWhitespace
{
get
{
return (Enums.WhiteSpace)this.SendMessageDirect(2020);
}
set
{
this.SendMessageDirect(2021, (int)value);
}
}
/// <summary>
/// Retrieve the current end of line mode - one of CRLF, CR, or LF.
/// </summary>
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual Enums.EndOfLine EndOfLineMode
{
get
{
return (Enums.EndOfLine)this.SendMessageDirect(2030);
}
set
{
this.SendMessageDirect(2031, (int)value);
}
}
/// <summary>
/// Convert all line endings in the document to one mode.
/// </summary>
public void ConvertEOLs(Enums.EndOfLine eolMode)
{
this.SendMessageDirect(2029, (int) eolMode);
}
/// <summary>
/// Set the symbol used for a particular marker number.
/// </summary>
public void MarkerDefine(int markerNumber, Enums.MarkerSymbol markerSymbol)
{
this.SendMessageDirect(2040, markerNumber, (int) markerSymbol);
}
/// <summary>
/// Set the character set of the font in a style.
/// </summary>
public void StyleSetCharacterSet(int style, Enums.CharacterSet characterSet)
{
this.SendMessageDirect(2066, style, (int)characterSet);
}
/// <summary>
/// Set a style to be mixed case, or to force upper or lower case.
/// </summary>
public void StyleSetCase(int style, Enums.CaseVisible caseForce)
{
this.SendMessageDirect(2060, style, (int)caseForce);
}
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public readonly Collection<IndicatorStyle> IndicatorStyle;
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public readonly IntCollection IndicatorForegroundColor;
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public readonly CachingIntCollection MarkerBackgroundColor;
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public readonly CachingIntCollection MarkerForegroundColor;
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public readonly ReadOnlyStringCollection Line;
#endregion
#region Legacy Configuration Code
/// <summary>
/// Get or set the legacy configuration object
/// </summary>
public Scintilla.Legacy.Configuration.Scintilla LegacyConfiguration
{
get
{
return this._legacyConfiguration;
}
set
{
this._legacyConfiguration = value;
}
}
/// <summary>
/// Set the Configuration Language for the Legacy Config Support
/// </summary>
public String LegacyConfigurationLanguage
{
set
{
if (value == null || value.Equals(""))
return;
Scintilla.Legacy.Configuration.Language lang = _legacyConfiguration.GetLanguage(value);
if (lang == null)
return;
StyleClearAll();
System.Type enumtype = typeof(Enums.Lexer);
try
{
Lexer = (int)Enum.Parse(typeof(Enums.Lexer), lang.lexer.name, true);
}
catch (Exception)
{
// try by key instead
Lexer = lang.lexer.key;
}
if (lang.lexer.stylebits > 0)
StyleBits = lang.lexer.stylebits;
for (int j = 0; j < lang.usestyles.Length; j++)
{
Scintilla.Legacy.Configuration.UseStyle usestyle = lang.usestyles[j];
if (usestyle.HasForegroundColor)
StyleSetFore(usestyle.key, usestyle.ForegroundColor);
if (usestyle.HasBackgroundColor)
StyleSetBack(usestyle.key, usestyle.BackgroundColor);
if (usestyle.HasFontName)
StyleSetFont(usestyle.key, usestyle.FontName);
if (usestyle.HasFontSize)
StyleSetSize(usestyle.key, usestyle.FontSize);
if (usestyle.HasBold)
StyleSetBold(usestyle.key, usestyle.IsBold);
if (usestyle.HasItalics)
StyleSetItalic(usestyle.key, usestyle.IsItalics);
if (usestyle.HasEolFilled)
StyleSetEOLFilled(usestyle.key, usestyle.IsEolFilled);
}
// clear the keywords lists
for (int j = 0; j < 9; j++)
KeyWords(j, "");
for (int j = 0; j < lang.usekeywords.Length; j++)
{
Scintilla.Legacy.Configuration.UseKeyword usekeyword = lang.usekeywords[j];
Scintilla.Legacy.Configuration.KeywordClass kc = _legacyConfiguration.GetKeywordClass(usekeyword.cls);
if (kc != null)
KeyWords(usekeyword.key, kc.val);
}
}
}
#endregion
#region Configuration Code
/// <summary>
/// Get or set the configuration object
/// </summary>
public IScintillaConfig Configuration
{
get
{
return this._configuration;
}
set
{
this._configuration = value;
}
}
/// <summary>
/// Set the Configuration Language
/// </summary>
public String ConfigurationLanguage
{
get
{
return _configurationLanguage;
}
set
{
if ((Configuration != null) && !string.IsNullOrEmpty(value) && (_configurationLanguage != value))
{
_configurationLanguage = value;
StyleClearAll();
MarginClick -= new EventHandler<MarginClickEventArgs>(ScintillaControl_MarginClick);
IScintillaConfig conf = Configuration;
//if (conf.CodePage.HasValue) this.CodePage = conf.CodePage;
if (conf.SelectionAlpha.HasValue) this.SelectionAlpha = conf.SelectionAlpha.Value;
if (conf.SelectionBackColor != Color.Empty) this.SetSelectionBackground(true, Utilities.ColorToRgb(conf.SelectionBackColor));
if (conf.TabSize.HasValue) this.TabWidth = conf.TabSize.Value;
if (conf.IndentSize.HasValue) this.Indent = conf.IndentSize.Value;
if (conf.UseTabs.HasValue) this.IsUseTabs = conf.UseTabs.Value;
// Enable line numbers
this.MarginWidthN(0, 40);
bool enableFolding = false;
if (conf.Fold.HasValue) enableFolding = conf.Fold.Value;
if (enableFolding)
{
this.Property("fold", "1");
if (conf.FoldCompact.HasValue) this.Property("fold.compact", (conf.FoldCompact.Value ? "1" : "0"));
if (conf.FoldComment.HasValue) this.Property("fold.comment", (conf.FoldComment.Value ? "1" : "0"));
if (conf.FoldPreprocessor.HasValue) this.Property("fold.preprocessor", (conf.FoldPreprocessor.Value ? "1" : "0"));
if (conf.FoldHTML.HasValue) this.Property("fold.html", (conf.FoldHTML.Value ? "1" : "0"));
if (conf.FoldHTMLPreprocessor.HasValue) this.Property("fold.html.preprocessor", (conf.FoldHTMLPreprocessor.Value ? "1" : "0"));
this.MarginWidthN(2, 0);
this.MarginTypeN(2, (int)MarginType.Symbol);
this.MarginMaskN(2, unchecked((int)0xFE000000));
this.MarginSensitiveN(2, true);
if (conf.FoldMarginWidth.HasValue) this.MarginWidthN(2, conf.FoldMarginWidth.Value);
else this.MarginWidthN(2, 20);
if (conf.FoldMarginColor != Color.Empty) this.SetFoldMarginColor(true, Utilities.ColorToRgb(conf.FoldMarginColor));
if (conf.FoldMarginHighlightColor != Color.Empty) this.SetFoldMarginHiColor(true, Utilities.ColorToRgb(conf.FoldMarginHighlightColor));
if (conf.FoldFlags.HasValue) this.SetFoldFlags(conf.FoldFlags.Value);
this.MarkerDefine((int)MarkerOutline.Folder, MarkerSymbol.Plus);
this.MarkerDefine((int)MarkerOutline.FolderOpen, MarkerSymbol.Minus);
this.MarkerDefine((int)MarkerOutline.FolderEnd, MarkerSymbol.Empty);
this.MarkerDefine((int)MarkerOutline.FolderMidTail, MarkerSymbol.Empty);
this.MarkerDefine((int)MarkerOutline.FolderOpenMid, MarkerSymbol.Minus);
this.MarkerDefine((int)MarkerOutline.FolderSub, MarkerSymbol.Empty);
this.MarkerDefine((int)MarkerOutline.FolderTail, MarkerSymbol.Empty);
this.MarginClick += new EventHandler<MarginClickEventArgs>(ScintillaControl_MarginClick);
}
ILanguageConfig lang = conf.Languages[value];
if (lang != null)
{
if (!string.IsNullOrEmpty(lang.WhitespaceCharacters))
this.WhitespaceChars(lang.WhitespaceCharacters);
if (!string.IsNullOrEmpty(lang.WordCharacters))
this.WordChars(lang.WordCharacters);
ILexerConfig lex = lang.Lexer;
this.Lexer = lex.LexerID;
foreach (ILexerStyle style in lex.Styles.Values)
{
if (style.ForeColor != Color.Empty)
StyleSetFore(style.StyleIndex, Utilities.ColorToRgb(style.ForeColor));
if (style.BackColor != Color.Empty)
StyleSetBack(style.StyleIndex, Utilities.ColorToRgb(style.BackColor));
if (!string.IsNullOrEmpty(style.FontName))
StyleSetFont(style.StyleIndex, style.FontName);
if (style.FontSize.HasValue)
StyleSetSize(style.StyleIndex, style.FontSize.Value);
if (style.Bold.HasValue)
StyleSetBold(style.StyleIndex, style.Bold.Value);
if (style.Italics.HasValue)
StyleSetItalic(style.StyleIndex, style.Italics.Value);
if (style.EOLFilled.HasValue)
StyleSetEOLFilled(style.StyleIndex, style.EOLFilled.Value);
StyleSetCase(style.StyleIndex, style.CaseVisibility);
}
this.StyleBits = this.StyleBitsNeeded;
for (int j = 0; j < 9; j++)
{
if (lang.KeywordLists.ContainsKey(j))
KeyWords(j, lang.KeywordLists[j]);
else
KeyWords(j, string.Empty);
}
}
this.Colorize(0, this.Length);
}
}
}
private void ScintillaControl_MarginClick(object sender, MarginClickEventArgs e)
{
if (e.Margin == 2)
{
int lineNumber = this.LineFromPosition(e.Position);
ToggleFold(lineNumber);
}
}
#endregion
#region Smart indenting support
/// <summary>
/// Enable or disable Smart Indenting
/// </summary>
public bool SmartIndentingEnabled
{
get
{
return _smartIndenting != null;
}
set
{
if (value)
{
if (_smartIndenting == null)
{
_smartIndenting = new EventHandler<CharAddedEventArgs>(SmartIndenting_CharAdded);
CharAdded += SmartIndenting_CharAdded;
}
}
else
{
if (_smartIndenting != null)
{
CharAdded -= SmartIndenting_CharAdded;
_smartIndenting = null;
}
}
}
}
/// <summary>
/// If Smart Indenting is enabled, this delegate will be added to the CharAdded multicast event.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SmartIndenting_CharAdded(object sender, CharAddedEventArgs e)
{
if (e.Ch == '\n')
{
int curLine = this.CurrentPos;
curLine = this.LineFromPosition(curLine);
int previousIndent = this.LineIndentation(curLine - 1);
this.IndentLine(curLine, previousIndent);
}
}
/// <summary>
/// Smart Indenting helper method
/// </summary>
/// <param name="line"></param>
/// <param name="indent"></param>
private void IndentLine(int line, int indent)
{
if (indent < 0)
{
return;
}
int selStart = this.SelectionStart;
int selEnd = this.SelectionEnd;
int posBefore = this.LineIndentPosition(line);
this.LineIndentation(line, indent);
int posAfter = LineIndentPosition(line);
int posDifference = posAfter - posBefore;
if (posAfter > posBefore)
{
// Move selection on
if (selStart >= posBefore)
{
selStart += posDifference;
}
if (selEnd >= posBefore)
{
selEnd += posDifference;
}
}
else if (posAfter < posBefore)
{
// Move selection back
if (selStart >= posAfter)
{
if (selStart >= posBefore)
selStart += posDifference;
else
selStart = posAfter;
}
if (selEnd >= posAfter)
{
if (selEnd >= posBefore)
selEnd += posDifference;
else
selEnd = posAfter;
}
}
this.SetSelection(selStart, selEnd);
}
#endregion
#region Add Shortcuts from form to Scintilla control
public virtual void AddShortcuts(Form parentForm)
{
if ((parentForm != null) && (parentForm.MainMenuStrip != null))
{
AddShortcuts(parentForm.MainMenuStrip.Items);
}
}
public virtual void AddShortcuts(ToolStripItemCollection m)
{
foreach (ToolStripItem tmi in m)
{
if (tmi is ToolStripMenuItem)
{
ToolStripMenuItem mi = tmi as ToolStripMenuItem;
if (mi.ShortcutKeys != System.Windows.Forms.Keys.None)
{
AddIgnoredKey(mi.ShortcutKeys);
}
if (mi.DropDownItems.Count > 0)
{
AddShortcuts(mi.DropDownItems);
}
}
}
}
public virtual void AddIgnoredKey(System.Windows.Forms.Keys shortcutkey)
{
int key = (int)shortcutkey;
this._ignoredKeys.Add(key, key);
}
public override bool PreProcessMessage(ref Message m)
{
switch (m.Msg)
{
case WM_SYSKEYDOWN: // This traps F10
case WM_KEYDOWN:
{
// Let Windows Forms process the message first, before it is dispatched to the Scintilla control
if (base.PreProcessMessage(ref m) == true)
return true;
}
break;
}
return false;
}
protected override bool ProcessCmdKey(ref Message msg, System.Windows.Forms.Keys keyData)
{
return base.ProcessCmdKey(ref msg, keyData);
}
#endregion
#region Range
public Range Range(int position)
{
return Range(position, position);
}
public Range Range(int start, int end)
{
return new Range(start, end, this);
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Xml;
using System.Collections;
namespace System.Data.Common
{
internal sealed class UInt32Storage : DataStorage
{
private const uint DefaultValue = uint.MinValue;
private uint[] _values;
public UInt32Storage(DataColumn column)
: base(column, typeof(uint), DefaultValue, StorageType.UInt32)
{
}
public override object Aggregate(int[] records, AggregateType kind)
{
bool hasData = false;
try
{
switch (kind)
{
case AggregateType.Sum:
ulong sum = DefaultValue;
foreach (int record in records)
{
if (HasValue(record))
{
checked { sum += _values[record]; }
hasData = true;
}
}
if (hasData)
{
return sum;
}
return _nullValue;
case AggregateType.Mean:
long meanSum = DefaultValue;
int meanCount = 0;
foreach (int record in records)
{
if (HasValue(record))
{
checked { meanSum += _values[record]; }
meanCount++;
hasData = true;
}
}
if (hasData)
{
uint mean;
checked { mean = (uint)(meanSum / meanCount); }
return mean;
}
return _nullValue;
case AggregateType.Var:
case AggregateType.StDev:
int count = 0;
double var = 0.0f;
double prec = 0.0f;
double dsum = 0.0f;
double sqrsum = 0.0f;
foreach (int record in records)
{
if (HasValue(record))
{
dsum += _values[record];
sqrsum += _values[record] * (double)_values[record];
count++;
}
}
if (count > 1)
{
var = count * sqrsum - (dsum * dsum);
prec = var / (dsum * dsum);
// we are dealing with the risk of a cancellation error
// double is guaranteed only for 15 digits so a difference
// with a result less than 1e-15 should be considered as zero
if ((prec < 1e-15) || (var < 0))
var = 0;
else
var = var / (count * (count - 1));
if (kind == AggregateType.StDev)
{
return Math.Sqrt(var);
}
return var;
}
return _nullValue;
case AggregateType.Min:
uint min = uint.MaxValue;
for (int i = 0; i < records.Length; i++)
{
int record = records[i];
if (HasValue(record))
{
min = Math.Min(_values[record], min);
hasData = true;
}
}
if (hasData)
{
return min;
}
return _nullValue;
case AggregateType.Max:
uint max = uint.MinValue;
for (int i = 0; i < records.Length; i++)
{
int record = records[i];
if (HasValue(record))
{
max = Math.Max(_values[record], max);
hasData = true;
}
}
if (hasData)
{
return max;
}
return _nullValue;
case AggregateType.First:
if (records.Length > 0)
{
return _values[records[0]];
}
return null;
case AggregateType.Count:
count = 0;
for (int i = 0; i < records.Length; i++)
{
if (HasValue(records[i]))
count++;
}
return count;
}
}
catch (OverflowException)
{
throw ExprException.Overflow(typeof(uint));
}
throw ExceptionBuilder.AggregateException(kind, _dataType);
}
public override int Compare(int recordNo1, int recordNo2)
{
uint valueNo1 = _values[recordNo1];
uint valueNo2 = _values[recordNo2];
if (valueNo1 == DefaultValue || valueNo2 == DefaultValue)
{
int bitCheck = CompareBits(recordNo1, recordNo2);
if (0 != bitCheck)
{
return bitCheck;
}
}
//return valueNo1.CompareTo(valueNo2);
return (valueNo1 < valueNo2 ? -1 : (valueNo1 > valueNo2 ? 1 : 0)); // similar to UInt32.CompareTo(UInt32)
}
public override int CompareValueTo(int recordNo, object value)
{
System.Diagnostics.Debug.Assert(0 <= recordNo, "Invalid record");
System.Diagnostics.Debug.Assert(null != value, "null value");
if (_nullValue == value)
{
return (HasValue(recordNo) ? 1 : 0);
}
uint valueNo1 = _values[recordNo];
if ((DefaultValue == valueNo1) && !HasValue(recordNo))
{
return -1;
}
return valueNo1.CompareTo((uint)value);
//return(valueNo1 < valueNo2 ? -1 : (valueNo1 > valueNo2 ? 1 : 0)); // similar to UInt32.CompareTo(UInt32)
}
public override object ConvertValue(object value)
{
if (_nullValue != value)
{
if (null != value)
{
value = ((IConvertible)value).ToUInt32(FormatProvider);
}
else
{
value = _nullValue;
}
}
return value;
}
public override void Copy(int recordNo1, int recordNo2)
{
CopyBits(recordNo1, recordNo2);
_values[recordNo2] = _values[recordNo1];
}
public override object Get(int record)
{
uint value = _values[record];
if (!value.Equals(DefaultValue))
{
return value;
}
return GetBits(record);
}
public override void Set(int record, object value)
{
System.Diagnostics.Debug.Assert(null != value, "null value");
if (_nullValue == value)
{
_values[record] = DefaultValue;
SetNullBit(record, true);
}
else
{
_values[record] = ((IConvertible)value).ToUInt32(FormatProvider);
SetNullBit(record, false);
}
}
public override void SetCapacity(int capacity)
{
uint[] newValues = new uint[capacity];
if (null != _values)
{
Array.Copy(_values, 0, newValues, 0, Math.Min(capacity, _values.Length));
}
_values = newValues;
base.SetCapacity(capacity);
}
public override object ConvertXmlToObject(string s)
{
return XmlConvert.ToUInt32(s);
}
public override string ConvertObjectToXml(object value)
{
return XmlConvert.ToString((uint)value);
}
protected override object GetEmptyStorage(int recordCount)
{
return new uint[recordCount];
}
protected override void CopyValue(int record, object store, BitArray nullbits, int storeIndex)
{
uint[] typedStore = (uint[])store;
typedStore[storeIndex] = _values[record];
nullbits.Set(storeIndex, !HasValue(record));
}
protected override void SetStorage(object store, BitArray nullbits)
{
_values = (uint[])store;
SetNullStorage(nullbits);
}
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using Google.Protobuf.Collections;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace Google.Protobuf.Reflection
{
/// <summary>
/// Describes a message type.
/// </summary>
public sealed class MessageDescriptor : DescriptorBase
{
private static readonly HashSet<string> WellKnownTypeNames = new HashSet<string>
{
"google/protobuf/any.proto",
"google/protobuf/api.proto",
"google/protobuf/duration.proto",
"google/protobuf/empty.proto",
"google/protobuf/wrappers.proto",
"google/protobuf/timestamp.proto",
"google/protobuf/field_mask.proto",
"google/protobuf/source_context.proto",
"google/protobuf/struct.proto",
"google/protobuf/type.proto",
};
private readonly IList<FieldDescriptor> fieldsInDeclarationOrder;
private readonly IList<FieldDescriptor> fieldsInNumberOrder;
private readonly IDictionary<string, FieldDescriptor> jsonFieldMap;
internal MessageDescriptor(DescriptorProto proto, FileDescriptor file, MessageDescriptor parent, int typeIndex, GeneratedClrTypeInfo generatedCodeInfo)
: base(file, file.ComputeFullName(parent, proto.Name), typeIndex)
{
Proto = proto;
Parser = generatedCodeInfo == null ? null : generatedCodeInfo.Parser;
ClrType = generatedCodeInfo == null ? null : generatedCodeInfo.ClrType;
ContainingType = parent;
// Note use of generatedCodeInfo. rather than generatedCodeInfo?. here... we don't expect
// to see any nested oneofs, types or enums in "not actually generated" code... we do
// expect fields though (for map entry messages).
Oneofs = DescriptorUtil.ConvertAndMakeReadOnly(
proto.OneofDecl,
(oneof, index) =>
new OneofDescriptor(oneof, file, this, index, generatedCodeInfo.OneofNames[index]));
NestedTypes = DescriptorUtil.ConvertAndMakeReadOnly(
proto.NestedType,
(type, index) =>
new MessageDescriptor(type, file, this, index, generatedCodeInfo.NestedTypes[index]));
EnumTypes = DescriptorUtil.ConvertAndMakeReadOnly(
proto.EnumType,
(type, index) =>
new EnumDescriptor(type, file, this, index, generatedCodeInfo.NestedEnums[index]));
fieldsInDeclarationOrder = DescriptorUtil.ConvertAndMakeReadOnly(
proto.Field,
(field, index) =>
new FieldDescriptor(field, file, this, index, generatedCodeInfo == null ? null : generatedCodeInfo.PropertyNames[index]));
fieldsInNumberOrder = new ReadOnlyCollection<FieldDescriptor>(fieldsInDeclarationOrder.OrderBy(field => field.FieldNumber).ToArray());
// TODO: Use field => field.Proto.JsonName when we're confident it's appropriate. (And then use it in the formatter, too.)
jsonFieldMap = CreateJsonFieldMap(fieldsInNumberOrder);
file.DescriptorPool.AddSymbol(this);
Fields = new FieldCollection(this);
}
private static ReadOnlyDictionary<string, FieldDescriptor> CreateJsonFieldMap(IList<FieldDescriptor> fields)
{
var map = new Dictionary<string, FieldDescriptor>();
foreach (var field in fields)
{
map[field.Name] = field;
map[field.JsonName] = field;
}
return new ReadOnlyDictionary<string, FieldDescriptor>(map);
}
/// <summary>
/// The brief name of the descriptor's target.
/// </summary>
public override string Name
{
get
{
return Proto.Name;
}
}
internal readonly DescriptorProto Proto;
/// <summary>
/// The CLR type used to represent message instances from this descriptor.
/// </summary>
/// <remarks>
/// <para>
/// The value returned by this property will be non-null for all regular fields. However,
/// if a message containing a map field is introspected, the list of nested messages will include
/// an auto-generated nested key/value pair message for the field. This is not represented in any
/// generated type, so this property will return null in such cases.
/// </para>
/// <para>
/// For wrapper types (<see cref="Google.Protobuf.WellKnownTypes.StringValue"/> and the like), the type returned here
/// will be the generated message type, not the native type used by reflection for fields of those types. Code
/// using reflection should call <see cref="IsWrapperType"/> to determine whether a message descriptor represents
/// a wrapper type, and handle the result appropriately.
/// </para>
/// </remarks>
public readonly Type ClrType;
/// <summary>
/// A parser for this message type.
/// </summary>
/// <remarks>
/// <para>
/// As <see cref="MessageDescriptor"/> is not generic, this cannot be statically
/// typed to the relevant type, but it should produce objects of a type compatible with <see cref="ClrType"/>.
/// </para>
/// <para>
/// The value returned by this property will be non-null for all regular fields. However,
/// if a message containing a map field is introspected, the list of nested messages will include
/// an auto-generated nested key/value pair message for the field. No message parser object is created for
/// such messages, so this property will return null in such cases.
/// </para>
/// <para>
/// For wrapper types (<see cref="Google.Protobuf.WellKnownTypes.StringValue"/> and the like), the parser returned here
/// will be the generated message type, not the native type used by reflection for fields of those types. Code
/// using reflection should call <see cref="IsWrapperType"/> to determine whether a message descriptor represents
/// a wrapper type, and handle the result appropriately.
/// </para>
/// </remarks>
public readonly MessageParser Parser;
/// <summary>
/// Returns whether this message is one of the "well known types" which may have runtime/protoc support.
/// </summary>
internal bool IsWellKnownType
{
get
{
return File.Package == "google.protobuf" && WellKnownTypeNames.Contains(File.Name);
}
}
/// <summary>
/// Returns whether this message is one of the "wrapper types" used for fields which represent primitive values
/// with the addition of presence.
/// </summary>
internal bool IsWrapperType
{
get
{
return File.Package == "google.protobuf" && File.Name == "google/protobuf/wrappers.proto";
}
}
/// <value>
/// If this is a nested type, get the outer descriptor, otherwise null.
/// </value>
public readonly MessageDescriptor ContainingType;
/// <value>
/// A collection of fields, which can be retrieved by name or field number.
/// </value>
public readonly FieldCollection Fields;
/// <value>
/// An unmodifiable list of this message type's nested types.
/// </value>
public readonly IList<MessageDescriptor> NestedTypes;
/// <value>
/// An unmodifiable list of this message type's enum types.
/// </value>
public readonly IList<EnumDescriptor> EnumTypes;
/// <value>
/// An unmodifiable list of the "oneof" field collections in this message type.
/// </value>
public readonly IList<OneofDescriptor> Oneofs;
/// <summary>
/// Finds a field by field name.
/// </summary>
/// <param name="name">The unqualified name of the field (e.g. "foo").</param>
/// <returns>The field's descriptor, or null if not found.</returns>
public FieldDescriptor FindFieldByName(String name)
{
return File.DescriptorPool.FindSymbol<FieldDescriptor>(FullName + "." + name);
}
/// <summary>
/// Finds a field by field number.
/// </summary>
/// <param name="number">The field number within this message type.</param>
/// <returns>The field's descriptor, or null if not found.</returns>
public FieldDescriptor FindFieldByNumber(int number)
{
return File.DescriptorPool.FindFieldByNumber(this, number);
}
/// <summary>
/// Finds a nested descriptor by name. The is valid for fields, nested
/// message types, oneofs and enums.
/// </summary>
/// <param name="name">The unqualified name of the descriptor, e.g. "Foo"</param>
/// <returns>The descriptor, or null if not found.</returns>
public T FindDescriptor<T>(string name) where T : class, IDescriptor
{
return File.DescriptorPool.FindSymbol<T>(FullName + "." + name);
}
/// <summary>
/// The (possibly empty) set of custom options for this message.
/// </summary>
//public CustomOptions CustomOptions => Proto.Options?.CustomOptions ?? CustomOptions.Empty;
public CustomOptions CustomOptions
{
get
{
return Proto.Options == null ? null : Proto.Options.CustomOptions ?? CustomOptions.Empty;
}
}
/// <summary>
/// Looks up and cross-links all fields and nested types.
/// </summary>
internal void CrossLink()
{
foreach (MessageDescriptor message in NestedTypes)
{
message.CrossLink();
}
foreach (FieldDescriptor field in fieldsInDeclarationOrder)
{
field.CrossLink();
}
foreach (OneofDescriptor oneof in Oneofs)
{
oneof.CrossLink();
}
}
/// <summary>
/// A collection to simplify retrieving the field accessor for a particular field.
/// </summary>
public sealed class FieldCollection
{
private readonly MessageDescriptor messageDescriptor;
internal FieldCollection(MessageDescriptor messageDescriptor)
{
this.messageDescriptor = messageDescriptor;
}
/// <value>
/// Returns the fields in the message as an immutable list, in the order in which they
/// are declared in the source .proto file.
/// </value>
public IList<FieldDescriptor> InDeclarationOrder() { return messageDescriptor.fieldsInDeclarationOrder; }
/// <value>
/// Returns the fields in the message as an immutable list, in ascending field number
/// order. Field numbers need not be contiguous, so there is no direct mapping from the
/// index in the list to the field number; to retrieve a field by field number, it is better
/// to use the <see cref="FieldCollection"/> indexer.
/// </value>
public IList<FieldDescriptor> InFieldNumberOrder()
{
return messageDescriptor.fieldsInNumberOrder;
}
// TODO: consider making this public in the future. (Being conservative for now...)
/// <value>
/// Returns a read-only dictionary mapping the field names in this message as they're available
/// in the JSON representation to the field descriptors. For example, a field <c>foo_bar</c>
/// in the message would result two entries, one with a key <c>fooBar</c> and one with a key
/// <c>foo_bar</c>, both referring to the same field.
/// </value>
internal IDictionary<string, FieldDescriptor> ByJsonName()
{
return messageDescriptor.jsonFieldMap;
}
/// <summary>
/// Retrieves the descriptor for the field with the given number.
/// </summary>
/// <param name="number">Number of the field to retrieve the descriptor for</param>
/// <returns>The accessor for the given field</returns>
/// <exception cref="KeyNotFoundException">The message descriptor does not contain a field
/// with the given number</exception>
public FieldDescriptor this[int number]
{
get
{
var fieldDescriptor = messageDescriptor.FindFieldByNumber(number);
if (fieldDescriptor == null)
{
throw new KeyNotFoundException("No such field number");
}
return fieldDescriptor;
}
}
/// <summary>
/// Retrieves the descriptor for the field with the given name.
/// </summary>
/// <param name="name">Name of the field to retrieve the descriptor for</param>
/// <returns>The descriptor for the given field</returns>
/// <exception cref="KeyNotFoundException">The message descriptor does not contain a field
/// with the given name</exception>
public FieldDescriptor this[string name]
{
get
{
var fieldDescriptor = messageDescriptor.FindFieldByName(name);
if (fieldDescriptor == null)
{
throw new KeyNotFoundException("No such field name");
}
return fieldDescriptor;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HTLib2.Bioinfo
{
public partial class Universe
{
public int Minimize_ConjugateGradient_Parallel(List<ForceField.IForceField> frcflds
, double? k = null
, double max_atom_movement = 0.1
, int? max_iteration = null
, double threshold = 0.001
, int randomPurturb = 0
, bool[] atomsMovable = null
, IMinimizeLogger logger = null // new Universe.MinimizeLogger_PrintEnergyForceMag(logpath)
, InfoPack extra = null
, bool? doSteepDeescent = null // null or true for default
)
{
if(doSteepDeescent == null)
doSteepDeescent = true;
if(k == null)
{
k = double.MaxValue;
foreach(ForceField.IForceField frcfld in frcflds)
{
double? kk = frcfld.GetDefaultMinimizeStep();
if(kk.HasValue)
k = Math.Min(k.Value, kk.Value);
}
}
// double k = 0.0001;
int iter = 0;
// 0. Initial configuration of atoms
Vectors coords = GetCoords();
if(atomsMovable == null)
{
atomsMovable = new bool[size];
for(int i=0; i<size; i++)
atomsMovable[i] = true;
}
Vectors h = GetVectorsZero();
Vectors forces = GetVectorsZero();
Dictionary<string,object> cache = new Dictionary<string, object>();
double energy = GetPotentialParallel(frcflds, coords, forces, cache);
double forces_NormInf = NormInf(forces, atomsMovable);
double forces_Norm1 = Norm(1, forces, atomsMovable);
double forces_Norm2 = Norm(2, forces, atomsMovable);
Vectors forces0 = forces;
double energy0 = energy;
while(true)
{
if(forces.IsComputable == false)
{
System.Console.Error.WriteLine("non-computable components while doing steepest-descent");
HEnvironment.Exit(0);
}
if(logger != null)
{
logger.log(iter, coords, energy, forces, atomsMovable);
logger.logTrajectory(this, iter, coords);
//if(iter %10 == 0)
//{
// System.IO.Directory.CreateDirectory("output");
// string pdbname = string.Format("mini.conju.{0:D5}.pdb", iter);
// pdb.ToFile("output\\"+pdbname, coords.ToArray());
// System.IO.File.AppendAllLines("output\\mini.conju.[animation].pml", new string[] { "load "+pdbname+", 1A6G" });
//}
}
// 1. Save the position of atoms
// 2. Calculate the potential energy of system and the net forces on atoms
// 3. Check if every force reaches to zero,
// , and END if yes
bool stopIteration = false;
if(forces_NormInf < threshold) stopIteration = true;
if((max_iteration != null) && (iter>=max_iteration.Value)) stopIteration = true;
if(stopIteration)
{
// double check
cache = new Dictionary<string, object>(); // reset cache
forces = GetVectorsZero();
energy = GetPotentialParallel(frcflds, coords, forces, cache);
forces_NormInf = NormInf(forces, atomsMovable);
forces_Norm1 = Norm(1, forces, atomsMovable);
forces_Norm2 = Norm(2, forces, atomsMovable);
// This is already checked by "if(forces_NormInf < threshold) stopIteration = true;"
//if(forces_NormInf < threshold)
/////////////////////////////////////////////////////
{
if(iter != 1)
{
SetCoords((Vector[])coords);
}
//{
// string pdbname = string.Format("mini.conju.{0:D5}.pdb", iter);
// pdb.ToFile("output\\"+pdbname, coords.ToArray());
// System.IO.File.AppendAllLines("output\\mini.conju.[animation].pml", new string[] { "load "+pdbname+", 1A6G" });
//}
if(extra != null)
{
extra.SetValue("energy", energy);
extra.SetValue("forces", forces);
extra.SetValue("forces norm-1", forces_Norm1);
extra.SetValue("forces norm-2", forces_Norm2);
extra.SetValue("forces norm-inf", forces_NormInf);
extra.SetValue("iter", iter);
}
return iter;
}
}
// 4. Move atoms with conjugated gradient
Vectors coords_prd;
{
if((iter > 0) && (iter % 100 == 0))
{
cache = new Dictionary<string, object>(); // reset cache
}
if((randomPurturb > 0) && (iter % randomPurturb == 0))
{
Vectors dcoords = GetVectorsRandom();
dcoords *= max_atom_movement;
coords = AddConditional(coords, dcoords, atomsMovable);
}
if(iter > 1)
{
HDebug.Assert(forces0 != null);
double r = Vectors.VtV(forces, forces).Sum() / Vectors.VtV(forces0, forces0).Sum();
h = forces + r * h;
double kk = k.Value;
double hNormInf = NormInf(h, atomsMovable);
if(kk*hNormInf > max_atom_movement)
// make the maximum movement as atomsMovable
kk = max_atom_movement/(hNormInf);
//double kk = (k*h.NormsInf().NormInf() < max_atom_movement) ? k : (max_atom_movement/h.NormsInf().NormInf());
//double kk = (k.Value*NormInf(h,atomsMovable) < max_atom_movement)? k.Value : (max_atom_movement/NormInf(h,atomsMovable));
coords_prd = AddConditional(coords, kk * h, atomsMovable);
}
else
{
// same to the steepest descent for the first iteration
h = forces;
double kk = k.Value;
double hNormInf = NormInf(h, atomsMovable);
if(kk*hNormInf > max_atom_movement)
// make the maximum movement as atomsMovable
kk = max_atom_movement/(hNormInf);
//double kk = (k*h.NormsInf().NormInf() < max_atom_movement) ? k : (max_atom_movement/h.NormsInf().NormInf());
//double kk = (k.Value*NormInf(h,atomsMovable) < max_atom_movement)? k.Value : (max_atom_movement/NormInf(h, atomsMovable));
coords_prd = AddConditional(coords, kk * h, atomsMovable);
}
}
// 5. Predict energy or forces on atoms
Vectors forces_prd = GetVectorsZero();
double energy_prd = GetPotentialParallel(frcflds, coords_prd, forces_prd, cache); iter++;
double forces_prd_NormInf = NormInf(forces_prd, atomsMovable);
double forces_prd_Norm1 = Norm(1, forces_prd, atomsMovable);
double forces_prd_Norm2 = Norm(2, forces_prd, atomsMovable);
// 6. Check if the predicted forces or energy will exceed over the limit
// , and goto 1 if no
doSteepDeescent = true;
//if((doSteepDeescent == false) || ((energy_prd <= energy) && (forces_prd_NormInf < forces_NormInf+1.0))
if((energy_prd < energy+0.1) && (forces_prd_NormInf < forces_NormInf+0.0001))
{
energy0 = energy;
forces0 = forces;
coords = coords_prd;
forces = forces_prd;
energy = energy_prd;
forces_NormInf = forces_prd_NormInf;
forces_Norm1 = forces_prd_Norm1;
forces_Norm2 = forces_prd_Norm2;
continue;
}
if(logger != null)
logger.log(iter, coords_prd, energy_prd, forces_prd, atomsMovable, "will do steepest");
// 7. Back to saved configuration
// 8. Move atoms with simple gradient
{
// same to the steepest descent
h = forces;
double kk = k.Value;
double hNormInf = NormInf(h, atomsMovable);
if(kk*hNormInf > max_atom_movement)
// make the maximum movement as atomsMovable
kk = max_atom_movement/(hNormInf);
//double kk = (k*h.NormsInf().NormInf() < max_atom_movement) ? k : (max_atom_movement/h.NormsInf().NormInf());
//double kk = (k.Value*NormInf(h,atomsMovable) < max_atom_movement)? k.Value : (max_atom_movement/NormInf(h, atomsMovable));
coords_prd = AddConditional(coords, kk * h, atomsMovable);
//if(randomPurturb)
//{
// Vectors dcoords = GetForcesRandom();
// dcoords *= (0.1*max_atom_movement);
// coords += dcoords;
//}
}
forces_prd = GetVectorsZero();
energy_prd = GetPotentialParallel(frcflds, coords_prd, forces_prd, cache);
forces_prd_NormInf = NormInf(forces_prd, atomsMovable);
forces_prd_Norm1 = Norm(1, forces_prd, atomsMovable);
forces_prd_Norm2 = Norm(2, forces_prd, atomsMovable);
energy0 = energy;
forces0 = forces;
coords = coords_prd;
forces = forces_prd;
energy = energy_prd;
forces_NormInf = forces_prd_NormInf;
forces_Norm1 = forces_prd_Norm1;
forces_Norm2 = forces_prd_Norm2;
// 9. goto 1
}
}
}
}
| |
//! \file ImagePB3.cs
//! \date Wed Dec 02 13:55:45 2015
//! \brief Cmvs engine image format.
//
// Copyright (C) 2015 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 GameRes.Utility;
using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Windows.Media;
namespace GameRes.Formats.Purple
{
internal class Pb3MetaData : ImageMetaData
{
public int Type;
public int SubType;
public int InputSize;
}
[Export(typeof(ImageFormat))]
public class Pb3Format : ImageFormat
{
public override string Tag { get { return "PB3"; } }
public override string Description { get { return "Purple Software image format"; } }
public override uint Signature { get { return 0x42334250; } } // 'PB3B'
public override ImageMetaData ReadMetaData (Stream stream)
{
stream.Position = 4;
using (var reader = new ArcView.Reader (stream))
{
int input_size = reader.ReadInt32();
stream.Position = 0x18;
int t2 = reader.ReadInt32();
int t1 = reader.ReadUInt16();
uint width = reader.ReadUInt16();
uint height = reader.ReadUInt16();
int bpp = reader.ReadUInt16();
return new Pb3MetaData
{
Width = width,
Height = height,
BPP = bpp,
Type = t1,
SubType = t2,
InputSize = input_size,
};
}
}
public override ImageData Read (Stream stream, ImageMetaData info)
{
var reader = new Pb3Reader (stream, (Pb3MetaData)info);
reader.Unpack();
return ImageData.Create (info, reader.Format, null, reader.Data);
}
public override void Write (Stream file, ImageData image)
{
throw new System.NotImplementedException ("Pb3Format.Write not implemented");
}
}
internal sealed class Pb3Reader
{
byte[] m_input;
Pb3MetaData m_info;
int m_channels;
int m_stride;
byte[] m_output;
byte[] m_lzss_frame;
public PixelFormat Format { get; private set; }
public byte[] Data { get { return m_output; } }
public Pb3Reader (Stream input, Pb3MetaData info)
{
if (info.Type == 1 && info.SubType != 0x10)
throw new NotSupportedException();
m_info = info;
m_input = new byte[m_info.InputSize];
if (m_input.Length != input.Read (m_input, 0, m_input.Length))
throw new EndOfStreamException();
m_channels = m_info.BPP / 8;
m_stride = 4 * (int)m_info.Width;
m_lzss_frame = new byte[0x800];
Format = m_channels < 4 ? PixelFormats.Bgr32 : PixelFormats.Bgra32;
// output array created by unpack methods as needed.
}
public void Unpack ()
{
switch (m_info.Type)
{
default: throw new InvalidEncryptionScheme();
case 1: UnpackV1(); break;
case 5: UnpackV5(); break;
case 8:
case 6: UnpackV6(); break;
case 2:
case 3:
case 4:
case 7: throw new NotSupportedException(string.Format ("PB3 v{0} images not supported", m_info.Type));
// V3 is pain in the ass to implement, machine code is full of unrolled loops resulting in a
// thousands lines of spaghetti code.
}
}
void UnpackV1 ()
{
int width = (int)m_info.Width;
int height = (int)m_info.Height;
m_output = new byte[m_stride * height];
int plane_size = width * height;
byte[] plane = new byte[plane_size];
int data1 = LittleEndian.ToInt32 (m_input, 0x2C);
int data2 = LittleEndian.ToInt32 (m_input, 0x30);
for (int channel = 0; channel < m_channels; ++channel)
{
int channel_offset = 4 * m_channels;
for (int i = 0; i < channel; ++i)
channel_offset += LittleEndian.ToInt32 (m_input, data1 + 4*i);
int v21 = data1 + channel_offset;
int bit_src = v21 + 12 + LittleEndian.ToInt32 (m_input, v21) + LittleEndian.ToInt32 (m_input, v21+4);
int channel_size = LittleEndian.ToInt32 (m_input, v21 + 8);
channel_offset = 4 * m_channels;
for (int i = 0; i < channel; ++i)
channel_offset += LittleEndian.ToInt32 (m_input, data2 + 4*i);
int data_src = data2 + channel_offset;
for (int i = 0; i < 0x7DE; ++i)
m_lzss_frame[i] = 0;
LzssUnpack (bit_src, data_src, plane, channel_size);
int x_blocks = width >> 4;
if (0 != (width & 0xF))
++x_blocks;
int y_blocks = height >> 4;
if (0 != (height & 0xF))
++y_blocks;
if (0 == y_blocks || 0 == x_blocks)
continue;
int plane_src = 0;
bit_src = v21 + 12;
int bit_mask = 128;
data_src = bit_src + LittleEndian.ToInt32 (m_input, v21);
int v68 = 16;
for (int y = 0; y < y_blocks; ++y)
{
int row = 16 * y;
int v66 = 16;
int dst_origin = m_stride * row + channel; // within m_output
for (int x = 0; x < x_blocks; ++x)
{
int dst = dst_origin;
int block_width = v66 > width ? width - 16 * x : 16;
int block_height = v68 > height ? height - row : 16;
if (0 == bit_mask)
{
++bit_src;
bit_mask = 128;
}
if (0 != (bit_mask & m_input[bit_src]))
{
byte b = m_input[data_src++];
for (int j = 0; j < block_height; ++j)
{
int v49 = dst;
for (int i = 0; i < block_width; ++i)
{
m_output[v49] = b;
v49 += 4;
}
dst += m_stride;
}
}
else
{
for (int j = 0; j < block_height; ++j)
{
int v49 = dst;
for (int i = 0; i < block_width; ++i)
{
m_output[v49] = plane[plane_src++];
v49 += 4;
}
dst += m_stride;
}
}
bit_mask >>= 1;
v66 += 16;
dst_origin += 64;
}
v68 += 16;
}
}
}
void UnpackV5 ()
{
m_output = new byte[m_stride * (int)m_info.Height];
for (int i = 0; i < 4; ++i)
{
int bit_src = 0x54 + LittleEndian.ToInt32 (m_input, 8 * i + 0x34);
int data_src = 0x54 + LittleEndian.ToInt32 (m_input, 8 * i + 0x38);
for (int j = 0; j < 0x7DE; ++j)
m_lzss_frame[j] = 0;
int frame_offset = 0x7DE;
byte accum = 0;
int bit_mask = 128;
int dst = i;
while (dst < m_output.Length)
{
if (0 == bit_mask)
{
++bit_src;
bit_mask = 128;
}
if (0 != (bit_mask & m_input[bit_src]))
{
int v = LittleEndian.ToUInt16 (m_input, data_src);
data_src += 2;
int count = (v & 0x1F) + 3;
int offset = v >> 5;
for (int k = 0; k < count; ++k)
{
byte b = m_lzss_frame[(k + offset) & 0x7FF];
m_lzss_frame[frame_offset++] = b;
accum += b;
m_output[dst] = accum;
dst += 4;
frame_offset &= 0x7FF;
}
}
else
{
byte b = m_input[data_src++];
m_lzss_frame[frame_offset++] = b;
accum += b;
m_output[dst] = accum;
dst += 4;
frame_offset &= 0x7FF;
}
bit_mask >>= 1;
}
}
}
static readonly byte[] NameKeyV6 = {
0xA6, 0x75, 0xF3, 0x9C, 0xC5, 0x69, 0x78, 0xA3, 0x3E, 0xA5, 0x4F, 0x79, 0x59, 0xFE, 0x3A, 0xC7,
};
void UnpackV6 ()
{
var name_bytes = new byte[0x20];
int name_offset = 0x34;
int i;
for (i = 0; i < 0x20; ++i)
{
name_bytes[i] = (byte)(m_input[name_offset+i] ^ NameKeyV6[i & 0xF]);
if (0 == name_bytes[i])
break;
}
m_output = LoadBaseImage (Encodings.cp932.GetString (name_bytes, 0, i) + ".pb3");
BlendInput();
}
byte[] LoadBaseImage (string name)
{
// judging by the code, files with "pb3" extension could as well contain PNG or BMP images,
// so we couldn't just shortcut to another instance of Pb3Reader here.
var path = Path.GetDirectoryName (m_info.FileName);
name = VFS.CombinePath (path, name);
if (name.Equals (m_info.FileName, StringComparison.InvariantCultureIgnoreCase))
throw new InvalidFormatException();
// two files referencing each other still could create infinite recursion
using (var base_file = VFS.OpenSeekableStream (name))
{
var image_data = ImageFormat.Read (name, base_file);
int stride = image_data.Bitmap.PixelWidth * 4;
var pixels = new byte[stride * image_data.Bitmap.PixelHeight];
image_data.Bitmap.CopyPixels (pixels, stride, 0);
return pixels;
}
}
void LzssUnpack (int bit_src, int data_src, byte[] output, int output_size)
{
int dst = 0;
int bit_mask = 0x80;
int frame_offset = 0x7DE;
while (dst < output_size)
{
if (0 == bit_mask)
{
bit_mask = 0x80;
++bit_src;
}
if (0 != (bit_mask & m_input[bit_src]))
{
int v = LittleEndian.ToUInt16 (m_input, data_src);
data_src += 2;
int count = (v & 0x1F) + 3;
int offset = v >> 5;
for (int i = 0; i < count; ++i)
{
byte b = m_lzss_frame[(i + offset) & 0x7FF];
output[dst++] = b;
m_lzss_frame[frame_offset++] = b;
frame_offset &= 0x7FF;
}
}
else
{
byte b = m_input[data_src++];
output[dst++] = b;
m_lzss_frame[frame_offset++] = b;
frame_offset &= 0x7FF;
}
bit_mask >>= 1;
}
}
void BlendInput ()
{
int bit_src = 0x20 + LittleEndian.ToInt32 (m_input, 0xC);
int data_src = bit_src + LittleEndian.ToInt32 (m_input, 0x2C);
int overlay_size = LittleEndian.ToInt32 (m_input, 0x18);
var overlay = new byte[overlay_size];
LzssUnpack (bit_src, data_src, overlay, overlay_size);
int width = (int)m_info.Width;
int height = (int)m_info.Height;
bit_src = 8; // within overlay
data_src = 8 + LittleEndian.ToInt32 (overlay, 0); // within overlay
int bit_mask = 0x80;
int x_blocks = width >> 3;
if (0 != (width & 7))
++x_blocks;
int y_blocks = height >> 3;
if (0 != (height & 7))
++y_blocks;
if (0 == x_blocks)
return;
int h = 0;
int dst_origin = 0;
while (y_blocks > 0)
{
int w = 0;
for (int x = 0; x < x_blocks; ++x)
{
if (0 == bit_mask)
{
++bit_src;
bit_mask = 0x80;
}
if (0 == (bit_mask & overlay[bit_src]))
{
int dst = 8 * (dst_origin + 4 * x); // within m_output
int x_count = Math.Min (8, width - w);
int y_count = Math.Min (8, height - h);
for (int v30 = y_count; v30 > 0; --v30)
{
int count = 4 * x_count;
Buffer.BlockCopy (overlay, data_src, m_output, dst, count);
data_src += count;
dst += m_stride;
}
}
bit_mask >>= 1;
w += 8;
}
dst_origin += m_stride;
h += 8;
--y_blocks;
}
}
}
}
| |
namespace ApiTemplate
{
using System;
#if ResponseCompression
using System.IO.Compression;
#endif
using System.Linq;
#if Swagger
using System.Reflection;
#endif
#if CORS
using ApiTemplate.Constants;
#endif
#if Swagger && Versioning
using ApiTemplate.OperationFilters;
#endif
using ApiTemplate.Options;
using Boxed.AspNetCore;
#if Swagger
using Boxed.AspNetCore.Swagger;
using Boxed.AspNetCore.Swagger.OperationFilters;
using Boxed.AspNetCore.Swagger.SchemaFilters;
#endif
using Microsoft.AspNetCore.Builder;
#if (!ForwardedHeaders && HostFiltering)
using Microsoft.AspNetCore.HostFiltering;
#endif
#if Versioning
using Microsoft.AspNetCore.Mvc.ApiExplorer;
#endif
#if ResponseCompression
using Microsoft.AspNetCore.ResponseCompression;
#endif
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
#if Swagger
using Microsoft.OpenApi.Models;
#endif
/// <summary>
/// <see cref="IServiceCollection"/> extension methods which extend ASP.NET Core services.
/// </summary>
internal static class CustomServiceCollectionExtensions
{
/// <summary>
/// Configures caching for the application. Registers the <see cref="IDistributedCache"/> and
/// <see cref="IMemoryCache"/> types with the services collection or IoC container. The
/// <see cref="IDistributedCache"/> is intended to be used in cloud hosted scenarios where there is a shared
/// cache, which is shared between multiple instances of the application. Use the <see cref="IMemoryCache"/>
/// otherwise.
/// </summary>
/// <param name="services">The services.</param>
/// <returns>The services with caching services added.</returns>
public static IServiceCollection AddCustomCaching(this IServiceCollection services) =>
services
.AddMemoryCache()
// Adds IDistributedCache which is a distributed cache shared between multiple servers. This adds a
// default implementation of IDistributedCache which is not distributed. You probably want to use the
// Redis cache provider by calling AddDistributedRedisCache.
.AddDistributedMemoryCache();
#if CORS
/// <summary>
/// Add cross-origin resource sharing (CORS) services and configures named CORS policies. See
/// https://docs.asp.net/en/latest/security/cors.html
/// </summary>
/// <param name="services">The services.</param>
/// <returns>The services with CORS services added.</returns>
public static IServiceCollection AddCustomCors(this IServiceCollection services) =>
services.AddCors(
options =>
// Create named CORS policies here which you can consume using application.UseCors("PolicyName")
// or a [EnableCors("PolicyName")] attribute on your controller or action.
options.AddPolicy(
CorsPolicyName.AllowAny,
x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()));
#endif
/// <summary>
/// Configures the settings by binding the contents of the appsettings.json file to the specified Plain Old CLR
/// Objects (POCO) and adding <see cref="IOptions{T}"/> objects to the services collection.
/// </summary>
/// <param name="services">The services.</param>
/// <param name="configuration">The configuration.</param>
/// <returns>The services with options services added.</returns>
public static IServiceCollection AddCustomOptions(
this IServiceCollection services,
IConfiguration configuration) =>
services
// ConfigureAndValidateSingleton registers IOptions<T> and also T as a singleton to the services collection.
.ConfigureAndValidateSingleton<ApplicationOptions>(configuration)
#if ResponseCompression
.ConfigureAndValidateSingleton<CompressionOptions>(configuration.GetSection(nameof(ApplicationOptions.Compression)))
#endif
#if ForwardedHeaders
.ConfigureAndValidateSingleton<ForwardedHeadersOptions>(configuration.GetSection(nameof(ApplicationOptions.ForwardedHeaders)))
.Configure<ForwardedHeadersOptions>(
options =>
{
options.KnownNetworks.Clear();
options.KnownProxies.Clear();
})
#elif HostFiltering
.ConfigureAndValidateSingleton<HostFilteringOptions>(configuration.GetSection(nameof(ApplicationOptions.HostFiltering)))
#endif
.ConfigureAndValidateSingleton<CacheProfileOptions>(configuration.GetSection(nameof(ApplicationOptions.CacheProfiles)))
.ConfigureAndValidateSingleton<KestrelServerOptions>(configuration.GetSection(nameof(ApplicationOptions.Kestrel)));
#if ResponseCompression
/// <summary>
/// Adds dynamic response compression to enable GZIP compression of responses. This is turned off for HTTPS
/// requests by default to avoid the BREACH security vulnerability.
/// </summary>
/// <param name="services">The services.</param>
/// <param name="configuration">The configuration.</param>
/// <returns>The services with response compression services added.</returns>
public static IServiceCollection AddCustomResponseCompression(
this IServiceCollection services,
IConfiguration configuration) =>
services
.Configure<BrotliCompressionProviderOptions>(options => options.Level = CompressionLevel.Optimal)
.Configure<GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Optimal)
.AddResponseCompression(
options =>
{
// Add additional MIME types (other than the built in defaults) to enable GZIP compression for.
var customMimeTypes = configuration
.GetSection(nameof(ApplicationOptions.Compression))
.Get<CompressionOptions>()
?.MimeTypes ?? Enumerable.Empty<string>();
options.MimeTypes = customMimeTypes.Concat(ResponseCompressionDefaults.MimeTypes);
options.Providers.Add<BrotliCompressionProvider>();
options.Providers.Add<GzipCompressionProvider>();
});
#endif
/// <summary>
/// Add custom routing settings which determines how URL's are generated.
/// </summary>
/// <param name="services">The services.</param>
/// <returns>The services with routing services added.</returns>
public static IServiceCollection AddCustomRouting(this IServiceCollection services) =>
services.AddRouting(options => options.LowercaseUrls = true);
#if HttpsEverywhere
/// <summary>
/// Adds the Strict-Transport-Security HTTP header to responses. This HTTP header is only relevant if you are
/// using TLS. It ensures that content is loaded over HTTPS and refuses to connect in case of certificate
/// errors and warnings.
/// See https://developer.mozilla.org/en-US/docs/Web/Security/HTTP_strict_transport_security and
/// http://www.troyhunt.com/2015/06/understanding-http-strict-transport.html
/// Note: Including subdomains and a minimum maxage of 18 weeks is required for preloading.
/// Note: You can refer to the following article to clear the HSTS cache in your browser:
/// http://classically.me/blogs/how-clear-hsts-settings-major-browsers
/// </summary>
/// <param name="services">The services.</param>
/// <returns>The services with HSTS services added.</returns>
public static IServiceCollection AddCustomStrictTransportSecurity(this IServiceCollection services) =>
services
.AddHsts(
options =>
{
// Preload the HSTS HTTP header for better security. See https://hstspreload.org/
#if HstsPreload
options.IncludeSubDomains = true;
options.MaxAge = TimeSpan.FromSeconds(31536000); // 1 Year
options.Preload = true;
#else
// options.IncludeSubDomains = true;
// options.MaxAge = TimeSpan.FromSeconds(31536000); // 1 Year
// options.Preload = true;
#endif
});
#endif
#if HealthCheck
public static IServiceCollection AddCustomHealthChecks(this IServiceCollection services) =>
services
.AddHealthChecks()
// Add health checks for external dependencies here. See https://github.com/Xabaril/AspNetCore.Diagnostics.HealthChecks
.Services;
#endif
#if Versioning
public static IServiceCollection AddCustomApiVersioning(this IServiceCollection services) =>
services
.AddApiVersioning(
options =>
{
options.AssumeDefaultVersionWhenUnspecified = true;
options.ReportApiVersions = true;
})
.AddVersionedApiExplorer(x => x.GroupNameFormat = "'v'VVV"); // Version format: 'v'major[.minor][-status]
#endif
#if Swagger
/// <summary>
/// Adds Swagger services and configures the Swagger services.
/// </summary>
/// <param name="services">The services.</param>
/// <returns>The services with Swagger services added.</returns>
public static IServiceCollection AddCustomSwagger(this IServiceCollection services) =>
services.AddSwaggerGen(
options =>
{
var assembly = typeof(Startup).Assembly;
var assemblyProduct = assembly.GetCustomAttribute<AssemblyProductAttribute>().Product;
var assemblyDescription = assembly.GetCustomAttribute<AssemblyDescriptionAttribute>().Description;
options.DescribeAllParametersInCamelCase();
options.EnableAnnotations();
// Add the XML comment file for this assembly, so its contents can be displayed.
options.IncludeXmlCommentsIfExists(assembly);
#if Versioning
options.OperationFilter<ApiVersionOperationFilter>();
#endif
options.OperationFilter<ClaimsOperationFilter>();
options.OperationFilter<ForbiddenResponseOperationFilter>();
options.OperationFilter<UnauthorizedResponseOperationFilter>();
// Show a default and example model for JsonPatchDocument<T>.
options.SchemaFilter<JsonPatchDocumentSchemaFilter>();
#if Versioning
var provider = services.BuildServiceProvider().GetRequiredService<IApiVersionDescriptionProvider>();
foreach (var apiVersionDescription in provider.ApiVersionDescriptions)
{
var info = new OpenApiInfo()
{
Title = assemblyProduct,
Description = apiVersionDescription.IsDeprecated ?
$"{assemblyDescription} This API version has been deprecated." :
assemblyDescription,
Version = apiVersionDescription.ApiVersion.ToString(),
};
options.SwaggerDoc(apiVersionDescription.GroupName, info);
}
#else
var info = new Info()
{
Title = assemblyProduct,
Description = assemblyDescription,
Version = "v1"
};
options.SwaggerDoc("v1", info);
#endif
});
#endif
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: CultureInfo-specific collection of resources.
**
**
===========================================================*/
namespace System.Resources {
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Runtime.Versioning;
using System.Diagnostics;
using System.Diagnostics.Contracts;
// A RuntimeResourceSet stores all the resources defined in one
// particular CultureInfo, with some loading optimizations.
//
// It is expected that nearly all the runtime's users will be satisfied with the
// default resource file format, and it will be more efficient than most simple
// implementations. Users who would consider creating their own ResourceSets and/or
// ResourceReaders and ResourceWriters are people who have to interop with a
// legacy resource file format, are creating their own resource file format
// (using XML, for instance), or require doing resource lookups at runtime over
// the network. This group will hopefully be small, but all the infrastructure
// should be in place to let these users write & plug in their own tools.
//
// The Default Resource File Format
//
// The fundamental problems addressed by the resource file format are:
//
// * Versioning - A ResourceReader could in theory support many different
// file format revisions.
// * Storing intrinsic datatypes (ie, ints, Strings, DateTimes, etc) in a compact
// format
// * Support for user-defined classes - Accomplished using Serialization
// * Resource lookups should not require loading an entire resource file - If you
// look up a resource, we only load the value for that resource, minimizing working set.
//
//
// There are four sections to the default file format. The first
// is the Resource Manager header, which consists of a magic number
// that identifies this as a Resource file, and a ResourceSet class name.
// The class name is written here to allow users to provide their own
// implementation of a ResourceSet (and a matching ResourceReader) to
// control policy. If objects greater than a certain size or matching a
// certain naming scheme shouldn't be stored in memory, users can tweak that
// with their own subclass of ResourceSet.
//
// The second section in the system default file format is the
// RuntimeResourceSet specific header. This contains a version number for
// the .resources file, the number of resources in this file, the number of
// different types contained in the file, followed by a list of fully
// qualified type names. After this, we include an array of hash values for
// each resource name, then an array of virtual offsets into the name section
// of the file. The hashes allow us to do a binary search on an array of
// integers to find a resource name very quickly without doing many string
// compares (except for once we find the real type, of course). If a hash
// matches, the index into the array of hash values is used as the index
// into the name position array to find the name of the resource. The type
// table allows us to read multiple different classes from the same file,
// including user-defined types, in a more efficient way than using
// Serialization, at least when your .resources file contains a reasonable
// proportion of base data types such as Strings or ints. We use
// Serialization for all the non-instrinsic types.
//
// The third section of the file is the name section. It contains a
// series of resource names, written out as byte-length prefixed little
// endian Unicode strings (UTF-16). After each name is a four byte virtual
// offset into the data section of the file, pointing to the relevant
// string or serialized blob for this resource name.
//
// The fourth section in the file is the data section, which consists
// of a type and a blob of bytes for each item in the file. The type is
// an integer index into the type table. The data is specific to that type,
// but may be a number written in binary format, a String, or a serialized
// Object.
//
// The system default file format (V1) is as follows:
//
// What Type of Data
// ==================================================== ===========
//
// Resource Manager header
// Magic Number (0xBEEFCACE) Int32
// Resource Manager header version Int32
// Num bytes to skip from here to get past this header Int32
// Class name of IResourceReader to parse this file String
// Class name of ResourceSet to parse this file String
//
// RuntimeResourceReader header
// ResourceReader version number Int32
// [Only in debug V2 builds - "***DEBUG***"] String
// Number of resources in the file Int32
// Number of types in the type table Int32
// Name of each type Set of Strings
// Padding bytes for 8-byte alignment (use PAD) Bytes (0-7)
// Hash values for each resource name Int32 array, sorted
// Virtual offset of each resource name Int32 array, coupled with hash values
// Absolute location of Data section Int32
//
// RuntimeResourceReader Name Section
// Name & virtual offset of each resource Set of (UTF-16 String, Int32) pairs
//
// RuntimeResourceReader Data Section
// Type and Value of each resource Set of (Int32, blob of bytes) pairs
//
// This implementation, when used with the default ResourceReader class,
// loads only the strings that you look up for. It can do string comparisons
// without having to create a new String instance due to some memory mapped
// file optimizations in the ResourceReader and FastResourceComparer
// classes. This keeps the memory we touch to a minimum when loading
// resources.
//
// If you use a different IResourceReader class to read a file, or if you
// do case-insensitive lookups (and the case-sensitive lookup fails) then
// we will load all the names of each resource and each resource value.
// This could probably use some optimization.
//
// In addition, this supports object serialization in a similar fashion.
// We build an array of class types contained in this file, and write it
// to RuntimeResourceReader header section of the file. Every resource
// will contain its type (as an index into the array of classes) with the data
// for that resource. We will use the Runtime's serialization support for this.
//
// All strings in the file format are written with BinaryReader and
// BinaryWriter, which writes out the length of the String in bytes as an
// Int32 then the contents as Unicode chars encoded in UTF-8. In the name
// table though, each resource name is written in UTF-16 so we can do a
// string compare byte by byte against the contents of the file, without
// allocating objects. Ideally we'd have a way of comparing UTF-8 bytes
// directly against a String object, but that may be a lot of work.
//
// The offsets of each resource string are relative to the beginning
// of the Data section of the file. This way, if a tool decided to add
// one resource to a file, it would only need to increment the number of
// resources, add the hash & location of last byte in the name section
// to the array of resource hashes and resource name positions (carefully
// keeping these arrays sorted), add the name to the end of the name &
// offset list, possibly add the type list of types types (and increase
// the number of items in the type table), and add the resource value at
// the end of the file. The other offsets wouldn't need to be updated to
// reflect the longer header section.
//
// Resource files are currently limited to 2 gigabytes due to these
// design parameters. A future version may raise the limit to 4 gigabytes
// by using unsigned integers, or may use negative numbers to load items
// out of an assembly manifest. Also, we may try sectioning the resource names
// into smaller chunks, each of size sqrt(n), would be substantially better for
// resource files containing thousands of resources.
//
internal sealed class RuntimeResourceSet : ResourceSet, IEnumerable
{
internal const int Version = 2; // File format version number
// Cache for resources. Key is the resource name, which can be cached
// for arbitrarily long times, since the object is usually a string
// literal that will live for the lifetime of the appdomain. The
// value is a ResourceLocator instance, which might cache the object.
private Dictionary<String, ResourceLocator> _resCache;
// For our special load-on-demand reader, cache the cast. The
// RuntimeResourceSet's implementation knows how to treat this reader specially.
private ResourceReader _defaultReader;
// This is a lookup table for case-insensitive lookups, and may be null.
// Consider always using a case-insensitive resource cache, as we don't
// want to fill this out if we can avoid it. The problem is resource
// fallback will somewhat regularly cause us to look up resources that
// don't exist.
private Dictionary<String, ResourceLocator> _caseInsensitiveTable;
// If we're not using our custom reader, then enumerate through all
// the resources once, adding them into the table.
private bool _haveReadFromReader;
internal RuntimeResourceSet(String fileName) : base(false)
{
BCLDebug.Log("RESMGRFILEFORMAT", "RuntimeResourceSet .ctor(String)");
_resCache = new Dictionary<String, ResourceLocator>(FastResourceComparer.Default);
Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
_defaultReader = new ResourceReader(stream, _resCache);
Reader = _defaultReader;
}
#if LOOSELY_LINKED_RESOURCE_REFERENCE
internal RuntimeResourceSet(Stream stream, Assembly assembly) : base(false)
{
BCLDebug.Log("RESMGRFILEFORMAT", "RuntimeResourceSet .ctor(Stream)");
_resCache = new Dictionary<String, ResourceLocator>(FastResourceComparer.Default);
_defaultReader = new ResourceReader(stream, _resCache);
Reader = _defaultReader;
Assembly = assembly;
}
#else
internal RuntimeResourceSet(Stream stream) : base(false)
{
BCLDebug.Log("RESMGRFILEFORMAT", "RuntimeResourceSet .ctor(Stream)");
_resCache = new Dictionary<String, ResourceLocator>(FastResourceComparer.Default);
_defaultReader = new ResourceReader(stream, _resCache);
Reader = _defaultReader;
}
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
protected override void Dispose(bool disposing)
{
if (Reader == null)
return;
if (disposing) {
lock(Reader) {
_resCache = null;
if (_defaultReader != null) {
_defaultReader.Close();
_defaultReader = null;
}
_caseInsensitiveTable = null;
// Set Reader to null to avoid a race in GetObject.
base.Dispose(disposing);
}
}
else {
// Just to make sure we always clear these fields in the future...
_resCache = null;
_caseInsensitiveTable = null;
_defaultReader = null;
base.Dispose(disposing);
}
}
public override IDictionaryEnumerator GetEnumerator()
{
return GetEnumeratorHelper();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumeratorHelper();
}
private IDictionaryEnumerator GetEnumeratorHelper()
{
IResourceReader copyOfReader = Reader;
if (copyOfReader == null || _resCache == null)
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ResourceSet"));
return copyOfReader.GetEnumerator();
}
public override String GetString(String key)
{
Object o = GetObject(key, false, true);
return (String) o;
}
public override String GetString(String key, bool ignoreCase)
{
Object o = GetObject(key, ignoreCase, true);
return (String) o;
}
public override Object GetObject(String key)
{
return GetObject(key, false, false);
}
public override Object GetObject(String key, bool ignoreCase)
{
return GetObject(key, ignoreCase, false);
}
private Object GetObject(String key, bool ignoreCase, bool isString)
{
if (key==null)
throw new ArgumentNullException(nameof(key));
if (Reader == null || _resCache == null)
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ResourceSet"));
Contract.EndContractBlock();
Object value = null;
ResourceLocator resLocation;
lock(Reader) {
if (Reader == null)
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ResourceSet"));
if (_defaultReader != null) {
BCLDebug.Log("RESMGRFILEFORMAT", "Going down fast path in RuntimeResourceSet::GetObject");
// Find the offset within the data section
int dataPos = -1;
if (_resCache.TryGetValue(key, out resLocation)) {
value = resLocation.Value;
dataPos = resLocation.DataPosition;
}
if (dataPos == -1 && value == null) {
dataPos = _defaultReader.FindPosForResource(key);
}
if (dataPos != -1 && value == null) {
Debug.Assert(dataPos >= 0, "data section offset cannot be negative!");
// Normally calling LoadString or LoadObject requires
// taking a lock. Note that in this case, we took a
// lock on the entire RuntimeResourceSet, which is
// sufficient since we never pass this ResourceReader
// to anyone else.
ResourceTypeCode typeCode;
if (isString) {
value = _defaultReader.LoadString(dataPos);
typeCode = ResourceTypeCode.String;
}
else {
value = _defaultReader.LoadObject(dataPos, out typeCode);
}
resLocation = new ResourceLocator(dataPos, (ResourceLocator.CanCache(typeCode)) ? value : null);
lock(_resCache) {
_resCache[key] = resLocation;
}
}
if (value != null || !ignoreCase) {
#if LOOSELY_LINKED_RESOURCE_REFERENCE
if (Assembly != null && (value is LooselyLinkedResourceReference)) {
LooselyLinkedResourceReference assRef = (LooselyLinkedResourceReference) value;
value = assRef.Resolve(Assembly);
}
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
return value; // may be null
}
} // if (_defaultReader != null)
// At this point, we either don't have our default resource reader
// or we haven't found the particular resource we're looking for
// and may have to search for it in a case-insensitive way.
if (!_haveReadFromReader) {
// If necessary, init our case insensitive hash table.
if (ignoreCase && _caseInsensitiveTable == null) {
_caseInsensitiveTable = new Dictionary<String, ResourceLocator>(StringComparer.OrdinalIgnoreCase);
}
#if _DEBUG
BCLDebug.Perf(!ignoreCase, "Using case-insensitive lookups is bad perf-wise. Consider capitalizing "+key+" correctly in your source");
#endif
if (_defaultReader == null) {
IDictionaryEnumerator en = Reader.GetEnumerator();
while (en.MoveNext()) {
DictionaryEntry entry = en.Entry;
String readKey = (String) entry.Key;
ResourceLocator resLoc = new ResourceLocator(-1, entry.Value);
_resCache.Add(readKey, resLoc);
if (ignoreCase)
_caseInsensitiveTable.Add(readKey, resLoc);
}
// Only close the reader if it is NOT our default one,
// since we need it around to resolve ResourceLocators.
if (!ignoreCase)
Reader.Close();
}
else {
Debug.Assert(ignoreCase, "This should only happen for case-insensitive lookups");
ResourceReader.ResourceEnumerator en = _defaultReader.GetEnumeratorInternal();
while (en.MoveNext()) {
// Note: Always ask for the resource key before the data position.
String currentKey = (String) en.Key;
int dataPos = en.DataPosition;
ResourceLocator resLoc = new ResourceLocator(dataPos, null);
_caseInsensitiveTable.Add(currentKey, resLoc);
}
}
_haveReadFromReader = true;
}
Object obj = null;
bool found = false;
bool keyInWrongCase = false;
if (_defaultReader != null) {
if (_resCache.TryGetValue(key, out resLocation)) {
found = true;
obj = ResolveResourceLocator(resLocation, key, _resCache, keyInWrongCase);
}
}
if (!found && ignoreCase) {
if (_caseInsensitiveTable.TryGetValue(key, out resLocation)) {
found = true;
keyInWrongCase = true;
obj = ResolveResourceLocator(resLocation, key, _resCache, keyInWrongCase);
}
}
return obj;
} // lock(Reader)
}
// The last parameter indicates whether the lookup required a
// case-insensitive lookup to succeed, indicating we shouldn't add
// the ResourceLocation to our case-sensitive cache.
private Object ResolveResourceLocator(ResourceLocator resLocation, String key, Dictionary<String, ResourceLocator> copyOfCache, bool keyInWrongCase)
{
// We need to explicitly resolve loosely linked manifest
// resources, and we need to resolve ResourceLocators with null objects.
Object value = resLocation.Value;
if (value == null) {
ResourceTypeCode typeCode;
lock(Reader) {
value = _defaultReader.LoadObject(resLocation.DataPosition, out typeCode);
}
if (!keyInWrongCase && ResourceLocator.CanCache(typeCode)) {
resLocation.Value = value;
copyOfCache[key] = resLocation;
}
}
#if LOOSELY_LINKED_RESOURCE_REFERENCE
if (Assembly != null && value is LooselyLinkedResourceReference) {
LooselyLinkedResourceReference assRef = (LooselyLinkedResourceReference) value;
value = assRef.Resolve(Assembly);
}
#endif // LOOSELY_LINKED_RESOURCE_REFERENCE
return value;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Plugins.CountlySDK.Enums;
using Plugins.CountlySDK.Helpers;
using Plugins.CountlySDK.Models;
using UnityEngine;
namespace Plugins.CountlySDK.Services
{
public class DeviceIdCountlyService : AbstractBaseService
{
private readonly CountlyUtils _countlyUtils;
private readonly EventCountlyService _eventCountlyService;
internal readonly RequestCountlyHelper _requestCountlyHelper;
private readonly SessionCountlyService _sessionCountlyService;
internal DeviceIdCountlyService(CountlyConfiguration configuration, CountlyLogHelper logHelper, SessionCountlyService sessionCountlyService,
RequestCountlyHelper requestCountlyHelper, EventCountlyService eventCountlyService, CountlyUtils countlyUtils, ConsentCountlyService consentService) : base(configuration, logHelper, consentService)
{
Log.Debug("[DeviceIdCountlyService] Initializing.");
_countlyUtils = countlyUtils;
_eventCountlyService = eventCountlyService;
_requestCountlyHelper = requestCountlyHelper;
_sessionCountlyService = sessionCountlyService;
}
/// <summary>
/// Returns the Device ID that is currently used by the SDK
/// </summary>
public string DeviceId { get; private set; }
/// <summary>
/// Initialize <code>DeviceId</code> field with device id provided in configuration or with Randome generated Id and Cache it.
/// </summary>
/// <param name="deviceId">new device id provided in configuration</param>
internal void InitDeviceId(string deviceId = null)
{
//**Priority is**
//Cached DeviceID (remains even after after app kill)
//Static DeviceID (only when the app is running or in the background)
//User provided DeviceID
//Generate Random DeviceID
string storedDeviceId = PlayerPrefs.GetString(Constants.DeviceIDKey);
if (!_countlyUtils.IsNullEmptyOrWhitespace(storedDeviceId)) {
DeviceId = storedDeviceId;
} else {
if (_countlyUtils.IsNullEmptyOrWhitespace(DeviceId)) {
if (!_countlyUtils.IsNullEmptyOrWhitespace(deviceId)) {
DeviceId = deviceId;
} else {
DeviceId = _countlyUtils.GetUniqueDeviceId();
}
}
}
//Set DeviceID in Cache if it doesn't already exists in Cache
if (_countlyUtils.IsNullEmptyOrWhitespace(storedDeviceId)) {
PlayerPrefs.SetString(Constants.DeviceIDKey, DeviceId);
}
}
/// <summary>
/// Changes Device Id.
/// Adds currently recorded but not queued events to request queue.
/// Clears all started timed-events
/// Ends current session with old Device Id.
/// Begins a new session with new Device Id
/// </summary>
/// <param name="deviceId">new device id</param>
[Obsolete("ChangeDeviceIdAndEndCurrentSessionAsync is deprecated, please use ChangeDeviceIdWithoutMerge method instead.")]
public async Task ChangeDeviceIdAndEndCurrentSessionAsync(string deviceId)
{
Log.Info("[DeviceIdCountlyService] ChangeDeviceIdAndEndCurrentSessionAsync: deviceId = " + deviceId);
if (!_consentService.AnyConsentGiven()) {
Log.Debug("[DeviceIdCountlyService] ChangeDeviceIdAndEndCurrentSessionAsync: Please set at least a single consent before calling this!");
return;
}
await ChangeDeviceIdWithoutMerge(deviceId);
}
/// <summary>
/// Changes Device Id.
/// Adds currently recorded but not queued events to request queue.
/// Clears all started timed-events
/// Ends current session with old Device Id.
/// Begins a new session with new Device Id
/// </summary>
/// <param name="deviceId">new device id</param>
public async Task ChangeDeviceIdWithoutMerge(string deviceId)
{
lock (LockObj) {
Log.Info("[DeviceIdCountlyService] ChangeDeviceIdWithoutMerge: deviceId = " + deviceId);
//Ignore call if new and old device id are same
if (DeviceId == deviceId) {
return;
}
//Add currently recorded events to request queue-----------------------------------
_eventCountlyService.AddEventsToRequestQueue();
//Ends current session
//Do not dispose timer object
if (!_configuration.IsAutomaticSessionTrackingDisabled) {
_ = _sessionCountlyService.EndSessionAsync();
}
//Update device id
UpdateDeviceId(deviceId);
if (_consentService.RequiresConsent) {
_consentService.SetConsentInternal(_consentService.CountlyConsents.Keys.ToArray(), false, sendRequest: false, ConsentChangedAction.DeviceIDChangedNotMerged);
}
//Begin new session with new device id
//Do not initiate timer again, it is already initiated
if (!_configuration.IsAutomaticSessionTrackingDisabled) {
_ = _sessionCountlyService.BeginSessionAsync();
}
NotifyListeners(false);
_ = _requestCountlyHelper.ProcessQueue();
}
}
/// <summary>
/// Changes DeviceId.
/// Continues with the current session.
/// Merges data for old and new Device Id.
/// </summary>
/// <param name="deviceId">new device id</param>
[Obsolete("ChangeDeviceIdAndMergeSessionDataAsync is deprecated, please use ChangeDeviceIdWithMerge method instead.")]
public async Task ChangeDeviceIdAndMergeSessionDataAsync(string deviceId)
{
Log.Info("[DeviceIdCountlyService] ChangeDeviceIdAndMergeSessionDataAsync: deviceId = " + deviceId);
if (!_consentService.AnyConsentGiven()) {
Log.Debug("[DeviceIdCountlyService] ChangeDeviceIdAndMergeSessionDataAsync: Please set at least a single consent before calling this!");
return;
}
await ChangeDeviceIdWithMerge(deviceId);
}
/// <summary>
/// Changes DeviceId.
/// Continues with the current session.
/// Merges data for old and new Device Id.
/// </summary>
/// <param name="deviceId">new device id</param>
public async Task ChangeDeviceIdWithMerge(string deviceId)
{
lock (LockObj) {
Log.Info("[DeviceIdCountlyService] ChangeDeviceIdWithMerge: deviceId = " + deviceId);
//Ignore call if new and old device id are same
if (DeviceId == deviceId) {
return;
}
//Keep old device id
string oldDeviceId = DeviceId;
//Update device id
UpdateDeviceId(deviceId);
//Merge user data for old and new device
Dictionary<string, object> requestParams =
new Dictionary<string, object> { { "old_device_id", oldDeviceId } };
_requestCountlyHelper.AddToRequestQueue(requestParams);
_ = _requestCountlyHelper.ProcessQueue();
NotifyListeners(true);
}
}
/// <summary>
/// Updates Device ID both in app and in cache
/// </summary>
/// <param name="newDeviceId">new device id</param>
private void UpdateDeviceId(string newDeviceId)
{
//Change device id
DeviceId = newDeviceId;
//Updating Cache
PlayerPrefs.SetString(Constants.DeviceIDKey, DeviceId);
Log.Debug("[DeviceIdCountlyService] UpdateDeviceId: " + newDeviceId);
}
/// <summary>
/// Call <code>DeviceIdChanged</code> on all listeners.
/// </summary>
/// <param name="merged">If passed "true" if will perform a device ID merge serverside of the old and new device ID. This will merge their data</param>
private void NotifyListeners(bool merged)
{
if (Listeners == null) {
return;
}
foreach (AbstractBaseService listener in Listeners) {
listener.DeviceIdChanged(DeviceId, merged);
}
}
#region override Methods
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace WebApiDocumentation.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
//
// System.Runtime.Remoting.Channels.Http.HttpClientChannel
//
// Summary: Implements a client channel that transmits method calls over HTTP.
//
// Classes: public HttpClientChannel
// internal HttpClientTransportSink
// Authors:
// Martin Willemoes Hansen (mwh@sysrq.dk)
// Ahmad Tantawy (popsito82@hotmail.com)
// Ahmad Kadry (kadrianoz@hotmail.com)
// Hussein Mehanna (hussein_mehanna@hotmail.com)
//
// (C) 2003 Martin Willemoes Hansen
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Messaging;
using System.Threading;
using System.Text;
namespace System.Runtime.Remoting.Channels.Http
{
public class HttpClientChannel : BaseChannelWithProperties, IChannelSender,IChannel
{
// Property Keys (purposely all lower-case)
private const String ProxyNameKey = "proxyname";
private const String ProxyPortKey = "proxyport";
// Settings
private int _channelPriority = 1; // channel priority
private String _channelName = "http"; // channel name
// Proxy settings (_proxyObject gets recreated when _proxyName and _proxyPort are updated)
//private IWebProxy _proxyObject = WebProxy.GetDefaultProxy(); // proxy object for request, can be overridden in transport sink
private IWebProxy _proxyObject = null;
private String _proxyName = null;
private int _proxyPort = -1;
private int _clientConnectionLimit = 0; // bump connection limit to at least this number (only meaningful if > 0)
private bool _bUseDefaultCredentials = false; // should default credentials be used?
private IClientChannelSinkProvider _sinkProvider = null; // sink chain provider
public HttpClientChannel()
{
SetupProvider (null,null);
}
public HttpClientChannel(String name, IClientChannelSinkProvider sinkProvider)
{
if(name != null)
_channelName = name;
SetupProvider (sinkProvider, null);
}
// constructor used by config file
public HttpClientChannel(IDictionary properties, IClientChannelSinkProvider sinkProvider)
{
if (properties != null)
{
foreach(DictionaryEntry Dict in properties)
{
switch(Dict.Key.ToString())
{
case "name":
_channelName = Dict.Value.ToString();
break;
case "priority":
_channelPriority = Convert.ToInt32(Dict.Value);
break;
case "clientConnectionLimit":
_clientConnectionLimit = Convert.ToInt32(Dict.Value);
break;
case "proxyName":
_proxyName = Dict.Value.ToString();
break;
case "proxyPort":
_proxyPort = Convert.ToInt32(Dict.Value);
break;
case "useDefaultCredentials":
_bUseDefaultCredentials = Convert.ToBoolean(Dict.Value);
break;
}
}
}
SetupProvider (sinkProvider, properties);
}
public int ChannelPriority
{
get { return _channelPriority; }
}
public String ChannelName
{
get { return _channelName; }
}
// returns channelURI and places object uri into out parameter
public String Parse(String url, out String objectURI)
{
return HttpHelper.Parse(url,out objectURI);
}
//
// end of IChannel implementation
//
//
// IChannelSender implementation
//
public virtual IMessageSink CreateMessageSink(String url, Object remoteChannelData, out String objectURI)
{
if ((url == null || !HttpHelper.StartsWithHttp (url)) && remoteChannelData != null && remoteChannelData as IChannelDataStore != null )
{
IChannelDataStore ds = (IChannelDataStore) remoteChannelData;
url = ds.ChannelUris[0];
}
if(url != null && HttpHelper.StartsWithHttp(url))
{
HttpHelper.Parse(url, out objectURI);
IMessageSink msgSink = (IMessageSink) _sinkProvider.CreateSink(this,url,remoteChannelData);
if(msgSink !=null )
SetServicePoint(url);
return msgSink;
}
else
{
objectURI = null;
return null;
}
}
private void UpdateProxy()
{
// If the user values for the proxy object are valid , then the proxy
// object will be created based on these values , if not it'll have the
// value given when declared , as a default proxy object
if(_proxyName!=null && _proxyPort !=-1)
_proxyObject = new WebProxy(_proxyName,_proxyPort);
// Either it's default or not it'll have this property
((WebProxy)_proxyObject).BypassProxyOnLocal = true;
}
private void SetServicePoint(string channelURI)
{
// Find a ServicePoint for the given url and assign the connection limit
// to the user given value only if it valid
ServicePoint sp = ServicePointManager.FindServicePoint(channelURI,ProxyObject);
if(_clientConnectionLimit> 0)
sp.ConnectionLimit = _clientConnectionLimit;
}
internal IWebProxy ProxyObject { get { return _proxyObject; } }
internal bool UseDefaultCredentials { get { return _bUseDefaultCredentials; } }
private void SetupProvider (IClientChannelSinkProvider sinkProvider, IDictionary properties)
{
if (properties == null) properties = new Hashtable ();
HttpClientTransportSinkProvider httpSink = new HttpClientTransportSinkProvider (properties);
SinksWithProperties = httpSink;
if(sinkProvider == null)
{
_sinkProvider = new SoapClientFormatterSinkProvider();
_sinkProvider.Next = httpSink;
}
else
{
IClientChannelSinkProvider dummySinkProvider;
dummySinkProvider = sinkProvider;
_sinkProvider = sinkProvider;
while(dummySinkProvider.Next != null)
{
dummySinkProvider = dummySinkProvider.Next;
}
dummySinkProvider.Next = httpSink;
}
}
public override object this [object key]
{
get { return Properties[key]; }
set { Properties[key] = value; }
}
public override ICollection Keys
{
get { return Properties.Keys; }
}
}
internal class HttpClientTransportSinkProvider : IClientChannelSinkProvider, IChannelSinkBase
{
IDictionary _properties;
internal HttpClientTransportSinkProvider (IDictionary properties)
{
_properties = properties;
}
public IClientChannelSink CreateSink(IChannelSender channel, String url,
Object remoteChannelData)
{
// url is set to the channel uri in CreateMessageSink
return new HttpClientTransportSink((HttpClientChannel)channel, url);
}
public IClientChannelSinkProvider Next
{
get { return null; }
set { throw new NotSupportedException(); }
}
public IDictionary Properties
{
get { return _properties; }
}
} // class HttpClientTransportSinkProvider
// transport sender sink used by HttpClientChannel
internal class HttpClientTransportSink : BaseChannelSinkWithProperties, IClientChannelSink
{
private const String s_defaultVerb = "POST";
private static String s_userAgent =
"Mono Remoting Client (Mono CLR " + System.Environment.Version.ToString() + ")";
// Property keys (purposely all lower-case)
private const String UserNameKey = "username";
private const String PasswordKey = "password";
private const String DomainKey = "domain";
private const String PreAuthenticateKey = "preauthenticate";
private const String CredentialsKey = "credentials";
private const String ClientCertificatesKey = "clientcertificates";
private const String ProxyNameKey = "proxyname";
private const String ProxyPortKey = "proxyport";
private const String TimeoutKey = "timeout";
private const String AllowAutoRedirectKey = "allowautoredirect";
// If above keys get modified be sure to modify, the KeySet property on this
// class.
private static ICollection s_keySet = null;
// Property values
private String _securityUserName = null;
private String _securityPassword = null;
private String _securityDomain = null;
private bool _bSecurityPreAuthenticate = false;
private ICredentials _credentials = null; // this overrides all of the other security settings
private int _timeout = System.Threading.Timeout.Infinite; // timeout value in milliseconds (only used if greater than 0)
private bool _bAllowAutoRedirect = false;
// Proxy settings (_proxyObject gets recreated when _proxyName and _proxyPort are updated)
private IWebProxy _proxyObject = null; // overrides channel proxy object if non-null
private String _proxyName = null;
private int _proxyPort = -1;
// Other members
private HttpClientChannel _channel; // channel that created this sink
private String _channelURI; // complete url to remote object
// settings
private bool _useChunked = false;
// private bool _useKeepAlive = true;
internal HttpClientTransportSink(HttpClientChannel channel, String channelURI) : base()
{
string dummy;
_channel = channel;
_channelURI = HttpHelper.Parse(channelURI,out dummy);
}
public void ProcessMessage(IMessage msg,
ITransportHeaders requestHeaders, Stream requestStream,
out ITransportHeaders responseHeaders, out Stream responseStream)
{
string url = null;
string uri = ((IMethodCallMessage)msg).Uri;
requestHeaders [CommonTransportKeys.RequestUri] = uri;
CreateUrl(uri,out url);
HttpWebRequest httpWebRequest = CreateWebRequest (url,requestHeaders,requestStream);
SendAndRecieve (httpWebRequest,out responseHeaders,out responseStream);
}
public void AsyncProcessRequest(IClientChannelSinkStack sinkStack, IMessage msg,
ITransportHeaders headers, Stream stream)
{
string url = null;
string uri = ((IMethodCallMessage)msg).Uri;
headers [CommonTransportKeys.RequestUri] = uri;
CreateUrl(uri,out url);
HttpWebRequest httpWebRequest = CreateWebRequest(url,headers,stream);
RequestState reqState = new RequestState(httpWebRequest,sinkStack);
httpWebRequest.BeginGetResponse(new AsyncCallback(AsyncRequestHandler),reqState);
}
private void AsyncRequestHandler(IAsyncResult ar)
{
HttpWebResponse httpWebResponse = null;
RequestState reqState = (RequestState) ar.AsyncState;
HttpWebRequest httpWebRequest = reqState.webRquest;
IClientChannelSinkStack sinkStack = reqState.sinkStack;
try
{
httpWebResponse = (HttpWebResponse) httpWebRequest.EndGetResponse(ar);
}
catch (WebException ex)
{
httpWebResponse = ex.Response as HttpWebResponse;
if (httpWebResponse == null) sinkStack.DispatchException (ex);
}
Stream responseStream;
ITransportHeaders responseHeaders;
try
{
ReceiveResponse (httpWebResponse, out responseHeaders, out responseStream);
sinkStack.AsyncProcessResponse(responseHeaders,responseStream);
}
catch (Exception ex)
{
sinkStack.DispatchException (ex);
}
}
public void AsyncProcessResponse(IClientResponseChannelSinkStack sinkStack, Object state,
ITransportHeaders headers, Stream stream)
{
// We don't have to implement this since we are always last in the chain.
} // AsyncProcessRequest
public Stream GetRequestStream(IMessage msg, ITransportHeaders headers)
{
return null;
} // GetRequestStream
public IClientChannelSink NextChannelSink
{
get { return null; }
}
public override Object this[Object key]
{
get
{
String keyStr = key as String;
if (keyStr == null)
return null;
switch (keyStr.ToLower())
{
case UserNameKey: return _securityUserName;
case PasswordKey: return null; // Intentionally refuse to return password.
case DomainKey: return _securityDomain;
case PreAuthenticateKey: return _bSecurityPreAuthenticate;
case CredentialsKey: return _credentials;
case ClientCertificatesKey: return null; // Intentionally refuse to return certificates
case ProxyNameKey: return _proxyName;
case ProxyPortKey: return _proxyPort;
case TimeoutKey: return _timeout;
case AllowAutoRedirectKey: return _bAllowAutoRedirect;
} // switch (keyStr.ToLower())
return null;
}
set
{
String keyStr = key as String;
if (keyStr == null)
return;
switch (keyStr.ToLower())
{
case UserNameKey: _securityUserName = (String)value; break;
case PasswordKey: _securityPassword = (String)value; break;
case DomainKey: _securityDomain = (String)value; break;
case PreAuthenticateKey: _bSecurityPreAuthenticate = Convert.ToBoolean(value); break;
case CredentialsKey: _credentials = (ICredentials)value; break;
case ProxyNameKey: _proxyName = (String)value; UpdateProxy(); break;
case ProxyPortKey: _proxyPort = Convert.ToInt32(value); UpdateProxy(); break;
case TimeoutKey:
{
if (value is TimeSpan)
_timeout = (int)((TimeSpan)value).TotalMilliseconds;
else
_timeout = Convert.ToInt32(value);
break;
} // case TimeoutKey
case AllowAutoRedirectKey: _bAllowAutoRedirect = Convert.ToBoolean(value); break;
} // switch (keyStr.ToLower())
}
} // this[]
public override ICollection Keys
{
get
{
if (s_keySet == null)
{
// No need for synchronization
ArrayList keys = new ArrayList(6);
keys.Add(UserNameKey);
keys.Add(PasswordKey);
keys.Add(DomainKey);
keys.Add(PreAuthenticateKey);
keys.Add(CredentialsKey);
keys.Add(ClientCertificatesKey);
keys.Add(ProxyNameKey);
keys.Add(ProxyPortKey);
keys.Add(TimeoutKey);
keys.Add(AllowAutoRedirectKey);
s_keySet = keys;
}
return s_keySet;
}
}
private void UpdateProxy()
{
// If the user values for the proxy object are valid , then the proxy
// object will be created based on these values , if not it'll have the
// value given when declared , as a default proxy object
if(_proxyName!=null && _proxyPort !=-1)
_proxyObject = new WebProxy(_proxyName,_proxyPort);
// Either it's default or not it'll have this property
((WebProxy)_proxyObject).BypassProxyOnLocal = true;
}
internal static String UserAgent
{
get { return s_userAgent; }
}
private void CreateUrl(string uri, out string fullURL)
{
if(HttpHelper.StartsWithHttp(uri)) //this is a full url
{
fullURL = uri;
return;
}
if(_channelURI.EndsWith("/") && uri.StartsWith("/"))
{
fullURL = _channelURI + uri.Substring(1);
return;
}
else
if(_channelURI.EndsWith("/") && !uri.StartsWith("/") ||
!_channelURI.EndsWith("/") && uri.StartsWith("/") )
{
fullURL = _channelURI +uri;
return;
}
else
{
fullURL = _channelURI +'/'+ uri;
return;
}
}
private HttpWebRequest CreateWebRequest(string url, ITransportHeaders requestHeaders, Stream requestStream)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);;
request.AllowAutoRedirect = _bAllowAutoRedirect;
request.ContentLength = requestStream.Length;
request.Credentials = GetCredenentials();
//request.Expect = "100-Continue";
//This caused us some troubles with the HttpWebResponse class
//maybe its fixed now. TODO
//request.KeepAlive = _useKeepAlive;
request.KeepAlive = false;;
request.Method = s_defaultVerb;
request.Pipelined = false;
request.SendChunked = _useChunked;
request.UserAgent = s_userAgent;
// write the remoting headers
IEnumerator headerenum = requestHeaders.GetEnumerator();
while (headerenum.MoveNext())
{
DictionaryEntry entry = (DictionaryEntry) headerenum.Current;
String key = entry.Key as String;
if(key == "Content-Type")
{
request.ContentType = entry.Value.ToString();
continue;
}
if (key == null || key.StartsWith("__"))
{
continue;
}
request.Headers.Add(entry.Key.ToString(),entry.Value.ToString());
}
Stream reqStream = request.GetRequestStream();
try {
HttpHelper.CopyStream(requestStream, reqStream);
} finally {
reqStream.Close();
}
return request;
}
private void SendAndRecieve(HttpWebRequest httpRequest,out ITransportHeaders responseHeaders,out Stream responseStream)
{
responseStream = null;
responseHeaders = null;
HttpWebResponse httpWebResponse = null;
try
{
httpWebResponse = (HttpWebResponse)httpRequest.GetResponse();
}
catch (WebException ex)
{
httpWebResponse = ex.Response as HttpWebResponse;
if (httpWebResponse == null || httpWebResponse.StatusCode == HttpStatusCode.InternalServerError) throw ex;
}
ReceiveResponse (httpWebResponse, out responseHeaders, out responseStream);
}
private void ReceiveResponse (HttpWebResponse httpWebResponse, out ITransportHeaders responseHeaders, out Stream responseStream)
{
responseHeaders = new TransportHeaders();
Stream webStream = httpWebResponse.GetResponseStream();
try
{
if (httpWebResponse.ContentLength != -1)
{
byte[] buffer = new byte [httpWebResponse.ContentLength];
int nr = 0;
while (nr < buffer.Length) {
int pr = webStream.Read (buffer, nr, buffer.Length - nr);
if (pr == 0) throw new RemotingException ("Connection closed");
nr += pr;
}
responseStream = new MemoryStream (buffer);
}
else
{
responseStream = new MemoryStream();
HttpHelper.CopyStream(webStream, responseStream);
}
//Use the two commented lines below instead of the 3 below lines when HttpWebResponse
//class is fully implemented in order to support custom headers
//for(int i=0; i < httpWebResponse.Headers.Count; ++i)
// responseHeaders[httpWebResponse.Headers.Keys[i].ToString()] = httpWebResponse.Headers[i].ToString();
responseHeaders["Content-Type"] = httpWebResponse.ContentType;
responseHeaders["Server"] = httpWebResponse.Server;
responseHeaders["Content-Length"] = httpWebResponse.ContentLength;
}
finally
{
webStream.Close ();
httpWebResponse.Close();
}
}
private void ProcessErrorCode()
{
}
private ICredentials GetCredenentials()
{
if(_credentials!=null)
return _credentials;
//Now use the username , password and domain if provided
if(_securityUserName==null ||_securityUserName=="")
if(_channel.UseDefaultCredentials)
return CredentialCache.DefaultCredentials;
else
return null;
return new NetworkCredential(_securityUserName,_securityPassword,_securityDomain);
}
} // class HttpClientTransportSink
internal class RequestState
{
public HttpWebRequest webRquest;
public IClientChannelSinkStack sinkStack;
public RequestState(HttpWebRequest wr,IClientChannelSinkStack ss)
{
webRquest = wr;
sinkStack = ss;
}
}
} // namespace System.Runtime.Remoting.Channels.Http
| |
using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
namespace UMA
{
/// <summary>
/// Class links UMA's bone data with Unity's transform hierarchy.
/// </summary>
[Serializable]
public class UMASkeleton
{
/// <summary>
/// Internal class for storing bone and transform information.
/// </summary>
[Serializable]
public class BoneData
{
public int boneNameHash;
public int parentBoneNameHash;
public Transform boneTransform;
public UMATransform umaTransform;
public Quaternion rotation;
public Vector3 position;
public Vector3 scale;
public int accessedFrame;
}
public IEnumerable<int> BoneHashes { get { return GetBoneHashes(); } }
//DynamicUMADna:: DynamicUMADnaConverterCustomizer Editor interface needs to have an array of bone names
public string[] BoneNames { get { return GetBoneNames(); } }
protected bool updating;
protected int frame;
/// <value>The hash for the root bone of the skeleton.</value>
public int rootBoneHash { get; protected set; }
/// <value>The bone count.</value>
public virtual int boneCount { get { return boneHashData.Count; } }
private List<BoneData> boneHashDataBackup = new List<BoneData>();
private Dictionary<int, BoneData> boneHashDataLookup;
private Dictionary<int, BoneData> boneHashData
{
get
{
if (boneHashDataLookup == null)
{
boneHashDataLookup = new Dictionary<int, BoneData>();
foreach (BoneData tData in boneHashDataBackup)
{
boneHashDataLookup.Add(tData.boneNameHash, tData);
}
}
return boneHashDataLookup;
}
set
{
boneHashDataLookup = value;
boneHashDataBackup = new List<BoneData>(value.Values);
}
}
/// <summary>
/// Initializes a new UMASkeleton from a transform hierarchy.
/// </summary>
/// <param name="rootBone">Root transform.</param>
public UMASkeleton(Transform rootBone)
{
rootBoneHash = UMAUtils.StringToHash(rootBone.name);
this.boneHashData = new Dictionary<int, BoneData>();
BeginSkeletonUpdate();
AddBonesRecursive(rootBone);
EndSkeletonUpdate();
}
protected UMASkeleton()
{
}
/// <summary>
/// Marks the skeleton as being updated.
/// </summary>
public virtual void BeginSkeletonUpdate()
{
frame++;
if (frame < 0) frame = 0;
updating = true;
}
/// <summary>
/// Marks the skeleton update as complete.
/// </summary>
public virtual void EndSkeletonUpdate()
{
foreach (var bd in boneHashData.Values)
{
bd.rotation = bd.boneTransform.localRotation;
bd.position = bd.boneTransform.localPosition;
bd.scale = bd.boneTransform.localScale;
}
updating = false;
}
public virtual void SetAnimatedBone(int nameHash)
{
// The default MeshCombiner is ignoring the animated bones, virtual method added to share common interface.
}
public virtual void SetAnimatedBoneHierachy(int nameHash)
{
// The default MeshCombiner is ignoring the animated bones, virtual method added to share common interface.
}
public virtual void ClearAnimatedBoneHierachy(int nameHash, bool recursive)
{
// The default MeshCombiner is ignoring the animated bones, virtual method added to share common interface.
}
private void AddBonesRecursive(Transform transform)
{
var hash = UMAUtils.StringToHash(transform.name);
var parentHash = transform.parent != null ? UMAUtils.StringToHash(transform.parent.name) : 0;
BoneData data = new BoneData()
{
parentBoneNameHash = parentHash,
boneNameHash = hash,
accessedFrame = frame,
boneTransform = transform,
umaTransform = new UMATransform(transform, hash, parentHash)
};
boneHashData.Add(hash, data);
boneHashDataBackup.Add(data);
for (int i = 0; i < transform.childCount; i++)
{
var child = transform.GetChild(i);
AddBonesRecursive(child);
}
}
protected virtual BoneData GetBone(int nameHash)
{
BoneData data = null;
boneHashData.TryGetValue(nameHash, out data);
return data;
}
/// <summary>
/// Does this skeleton contains bone with specified name hash?
/// </summary>
/// <returns><c>true</c> if this instance has bone the specified name hash; otherwise, <c>false</c>.</returns>
/// <param name="nameHash">Name hash.</param>
public virtual bool HasBone(int nameHash)
{
return boneHashData.ContainsKey(nameHash);
}
/// <summary>
/// Adds the transform into the skeleton.
/// </summary>
/// <param name="parentHash">Hash of parent transform name.</param>
/// <param name="hash">Hash of transform name.</param>
/// <param name="transform">Transform.</param>
public virtual void AddBone(int parentHash, int hash, Transform transform)
{
BoneData newBone = new BoneData()
{
accessedFrame = frame,
parentBoneNameHash = parentHash,
boneNameHash = hash,
boneTransform = transform,
umaTransform = new UMATransform(transform, hash, parentHash),
};
boneHashDataBackup.Add(newBone);
boneHashData.Add(hash, newBone);
}
/// <summary>
/// Adds the transform into the skeleton.
/// </summary>
/// <param name="transform">Transform.</param>
public virtual void AddBone(UMATransform transform)
{
var go = new GameObject(transform.name);
BoneData newBone = new BoneData()
{
accessedFrame = -1,
parentBoneNameHash = transform.parent,
boneNameHash = transform.hash,
boneTransform = go.transform,
umaTransform = transform.Duplicate(),
};
boneHashDataBackup.Add(newBone);
boneHashData.Add(transform.hash, newBone);
}
/// <summary>
/// Removes the bone with the given name hash.
/// </summary>
/// <param name="nameHash">Name hash.</param>
public virtual void RemoveBone(int nameHash)
{
BoneData bd = GetBone(nameHash);
if (bd != null)
{
boneHashDataBackup.Remove(bd);
boneHashData.Remove(nameHash);
}
}
/// <summary>
/// Tries to find bone transform in skeleton.
/// </summary>
/// <returns><c>true</c>, if transform was found, <c>false</c> otherwise.</returns>
/// <param name="nameHash">Name hash.</param>
/// <param name="boneTransform">Bone transform.</param>
/// <param name="transformDirty">Transform is dirty.</param>
/// <param name="parentBoneNameHash">Name hash of parent bone.</param>
public virtual bool TryGetBoneTransform(int nameHash, out Transform boneTransform, out bool transformDirty, out int parentBoneNameHash)
{
BoneData res;
if (boneHashData.TryGetValue(nameHash, out res))
{
transformDirty = res.accessedFrame != frame;
res.accessedFrame = frame;
boneTransform = res.boneTransform;
parentBoneNameHash = res.parentBoneNameHash;
return true;
}
transformDirty = false;
boneTransform = null;
parentBoneNameHash = 0;
return false;
}
/// <summary>
/// Gets the game object for a transform in the skeleton.
/// </summary>
/// <returns>The game object or null, if not found.</returns>
/// <param name="nameHash">Name hash.</param>
public virtual GameObject GetBoneGameObject(int nameHash)
{
BoneData res;
if (boneHashData.TryGetValue(nameHash, out res))
{
res.accessedFrame = frame;
return res.boneTransform.gameObject;
}
return null;
}
protected virtual IEnumerable<int> GetBoneHashes()
{
foreach (int hash in boneHashData.Keys)
{
yield return hash;
}
}
//DynamicUMADna:: a method to return a string of bonenames for use in editor intefaces
private string[] GetBoneNames()
{
string[] boneNames = new string[boneHashData.Count];
int index = 0;
foreach (KeyValuePair<int, BoneData> kp in boneHashData)
{
boneNames[index] = kp.Value.boneTransform.gameObject.name;
index++;
}
return boneNames;
}
public virtual void Set(int nameHash, Vector3 position, Vector3 scale, Quaternion rotation)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db))
{
db.accessedFrame = frame;
db.boneTransform.localPosition = position;
db.boneTransform.localRotation = rotation;
db.boneTransform.localScale = scale;
}
else
{
throw new Exception("Bone not found.");
}
}
/// <summary>
/// Sets the position of a bone.
/// This method silently fails if the bone doesn't exist! (Desired behaviour in DNA converters due to LOD/Occlusion)
/// </summary>
/// <param name="nameHash">Name hash.</param>
/// <param name="position">Position.</param>
public virtual void SetPosition(int nameHash, Vector3 position)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db))
{
db.accessedFrame = frame;
db.boneTransform.localPosition = position;
}
}
/// <summary>
/// Sets the position of a bone relative to it's old position.
/// This method silently fails if the bone doesn't exist! (Desired behaviour in DNA converters due to LOD/Occlusion)
/// </summary>
/// <param name="nameHash">Name hash.</param>
/// <param name="delta">Position delta.</param>
public virtual void SetPositionRelative(int nameHash, Vector3 delta)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db))
{
db.accessedFrame = frame;
db.boneTransform.localPosition = db.boneTransform.localPosition + delta;
}
}
/// <summary>
/// Sets the scale of a bone.
/// This method silently fails if the bone doesn't exist! (Desired behaviour in DNA converters due to LOD/Occlusion)
/// </summary>
/// <param name="nameHash">Name hash.</param>
/// <param name="scale">Scale.</param>
public virtual void SetScale(int nameHash, Vector3 scale)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db))
{
db.accessedFrame = frame;
db.boneTransform.localScale = scale;
}
}
/// <summary>
/// DynamicUMADnaConverterBahaviour:: Sets the scale of a bone relatively.
/// This method silently fails if the bone doesn't exist! (Desired behaviour in DNA converters due to LOD/Occlusion)
/// </summary>
/// <param name="nameHash">Name hash.</param>
/// <param name="scale">Scale.</param>
public virtual void SetScaleRelative(int nameHash, Vector3 scale)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db))
{
db.accessedFrame = frame;
var fullScale = scale;
fullScale.Scale(db.boneTransform.localScale);
db.boneTransform.localScale = fullScale;
}
}
/// <summary>
/// Sets the rotation of a bone.
/// This method silently fails if the bone doesn't exist! (Desired behaviour in DNA converters due to LOD/Occlusion)
/// </summary>
/// <param name="nameHash">Name hash.</param>
/// <param name="rotation">Rotation.</param>
public virtual void SetRotation(int nameHash, Quaternion rotation)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db))
{
db.accessedFrame = frame;
db.boneTransform.localRotation = rotation;
}
}
/// <summary>
/// DynamicUMADnaConverterBahaviour:: Sets the rotation of a bone relative to its initial rotation.
/// This method silently fails if the bone doesn't exist! (Desired behaviour in DNA converters due to LOD/Occlusion)
/// </summary>
/// <param name="nameHash">Name hash.</param>
/// <param name="rotation">Rotation.</param>
public virtual void SetRotationRelative(int nameHash, Quaternion rotation, float weight /*, bool hasAnimator = true*/)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db))
{
db.accessedFrame = frame;
Quaternion fullRotation = db.boneTransform.localRotation * rotation;
db.boneTransform.localRotation = Quaternion.Slerp(db.boneTransform.localRotation, fullRotation, weight);
}
}
/// <summary>
/// Lerp the specified bone toward a new position, rotation, and scale.
/// This method silently fails if the bone doesn't exist! (Desired behaviour in DNA converters due to LOD/Occlusion)
/// </summary>
/// <param name="nameHash">Name hash.</param>
/// <param name="position">Position.</param>
/// <param name="scale">Scale.</param>
/// <param name="rotation">Rotation.</param>
/// <param name="weight">Weight.</param>
public virtual void Lerp(int nameHash, Vector3 position, Vector3 scale, Quaternion rotation, float weight)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db))
{
db.accessedFrame = frame;
db.boneTransform.localPosition = Vector3.Lerp(db.boneTransform.localPosition, position, weight);
db.boneTransform.localRotation = Quaternion.Slerp(db.boneTransform.localRotation, db.boneTransform.localRotation, weight);
db.boneTransform.localScale = Vector3.Lerp(db.boneTransform.localScale, scale, weight);
}
}
/// <summary>
/// Lerp the specified bone toward a new position, rotation, and scale.
/// This method silently fails if the bone doesn't exist! (Desired behaviour in DNA converters due to LOD/Occlusion)
/// </summary>
/// <param name="nameHash">Name hash.</param>
/// <param name="position">Position.</param>
/// <param name="scale">Scale.</param>
/// <param name="rotation">Rotation.</param>
/// <param name="weight">Weight.</param>
public virtual void Morph(int nameHash, Vector3 position, Vector3 scale, Quaternion rotation, float weight)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db))
{
db.accessedFrame = frame;
db.boneTransform.localPosition += position * weight;
Quaternion fullRotation = db.boneTransform.localRotation * rotation;
db.boneTransform.localRotation = Quaternion.Slerp(db.boneTransform.localRotation, fullRotation, weight);
var fullScale = scale;
fullScale.Scale(db.boneTransform.localScale);
db.boneTransform.localScale = Vector3.Lerp(db.boneTransform.localScale, fullScale, weight);
}
}
/// <summary>
/// Reset the specified transform to the pre-dna state.
/// </summary>
/// <param name="nameHash">Name hash.</param>
public virtual bool Reset(int nameHash)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db) && (db.boneTransform != null))
{
db.accessedFrame = frame;
db.boneTransform.localPosition = db.umaTransform.position;
db.boneTransform.localRotation = db.umaTransform.rotation;
db.boneTransform.localScale = db.umaTransform.scale;
return true;
}
return false;
}
/// <summary>
/// Reset all transforms to the pre-dna state.
/// </summary>
public virtual void ResetAll()
{
foreach (BoneData db in boneHashData.Values)
{
if (db.boneTransform != null)
{
db.accessedFrame = frame;
db.boneTransform.localPosition = db.umaTransform.position;
db.boneTransform.localRotation = db.umaTransform.rotation;
db.boneTransform.localScale = db.umaTransform.scale;
}
}
}
/// <summary>
/// Restore the specified transform to the post-dna state.
/// </summary>
/// <param name="nameHash">Name hash.</param>
public virtual bool Restore(int nameHash)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db) && (db.boneTransform != null))
{
db.accessedFrame = frame;
db.boneTransform.localPosition = db.position;
db.boneTransform.localRotation = db.rotation;
db.boneTransform.localScale = db.scale;
return true;
}
return false;
}
/// <summary>
/// Restore all transforms to the post-dna state.
/// </summary>
public virtual void RestoreAll()
{
foreach (BoneData db in boneHashData.Values)
{
if (db.boneTransform != null)
{
db.accessedFrame = frame;
db.boneTransform.localPosition = db.position;
db.boneTransform.localRotation = db.rotation;
db.boneTransform.localScale = db.scale;
}
}
}
/// <summary>
/// Gets the position of a bone.
/// </summary>
/// <returns>The position.</returns>
/// <param name="nameHash">Name hash.</param>
public virtual Vector3 GetPosition(int nameHash)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db))
{
db.accessedFrame = frame;
return db.boneTransform.localPosition;
}
else
{
throw new Exception("Bone not found.");
}
}
/// <summary>
/// Gets the scale of a bone.
/// </summary>
/// <returns>The scale.</returns>
/// <param name="nameHash">Name hash.</param>
public virtual Vector3 GetScale(int nameHash)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db))
{
db.accessedFrame = frame;
return db.boneTransform.localScale;
}
else
{
throw new Exception("Bone not found.");
}
}
/// <summary>
/// Gets the rotation of a bone.
/// </summary>
/// <returns>The rotation.</returns>
/// <param name="nameHash">Name hash.</param>
public virtual Quaternion GetRotation(int nameHash)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db))
{
db.accessedFrame = frame;
return db.boneTransform.localRotation;
}
else
{
throw new Exception("Bone not found.");
}
}
public static int StringToHash(string name) { return UMAUtils.StringToHash(name); }
public virtual Transform[] HashesToTransforms(int[] boneNameHashes)
{
Transform[] res = new Transform[boneNameHashes.Length];
for (int i = 0; i < boneNameHashes.Length; i++)
{
res[i] = boneHashData[boneNameHashes[i]].boneTransform;
}
return res;
}
public virtual Transform[] HashesToTransforms(List<int> boneNameHashes)
{
Transform[] res = new Transform[boneNameHashes.Count];
for (int i = 0; i < boneNameHashes.Count; i++)
{
res[i] = boneHashData[boneNameHashes[i]].boneTransform;
}
return res;
}
/// <summary>
/// Ensures the bone exists in the skeleton.
/// </summary>
/// <param name="umaTransform">UMA transform.</param>
public virtual void EnsureBone(UMATransform umaTransform)
{
BoneData res;
if (boneHashData.TryGetValue(umaTransform.hash, out res))
{
res.accessedFrame = -1;
res.umaTransform.Assign(umaTransform);
}
else
{
AddBone(umaTransform);
}
}
/// <summary>
/// Ensures all bones are properly initialized and parented.
/// </summary>
public virtual void EnsureBoneHierarchy()
{
foreach (var entry in boneHashData.Values)
{
if (entry.accessedFrame == -1)
{
entry.boneTransform.parent = boneHashData[entry.umaTransform.parent].boneTransform;
entry.boneTransform.localPosition = entry.umaTransform.position;
entry.boneTransform.localRotation = entry.umaTransform.rotation;
entry.boneTransform.localScale = entry.umaTransform.scale;
entry.accessedFrame = frame;
}
}
}
public virtual Quaternion GetTPoseCorrectedRotation(int nameHash, Quaternion tPoseRotation)
{
return tPoseRotation;
}
}
}
| |
//
// Copyright (c) Microsoft. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System.Collections.Generic;
using System.Net;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Management.Resources.Models;
using Hyak.Common.TransientFaultHandling;
using Microsoft.Azure.Test;
using Xunit;
namespace ResourceGroups.Tests
{
public class LiveResourceTests : TestBase
{
const string WebResourceProviderVersion = "2014-04-01";
const string StoreResourceProviderVersion = "2014-04-01-preview";
string ResourceGroupLocation
{
get { return "South Central US"; }
}
public static ResourceIdentity CreateResourceIdentity(GenericResourceExtended resource)
{
string[] parts = resource.Type.Split('/');
return new ResourceIdentity { ResourceType = parts[1], ResourceProviderNamespace = parts[0], ResourceName = resource.Name, ResourceProviderApiVersion = WebResourceProviderVersion };
}
public ResourceManagementClient GetResourceManagementClient(RecordedDelegatingHandler handler)
{
handler.IsPassThrough = true;
return this.GetResourceManagementClient().WithHandler(handler);
}
public string GetWebsiteLocation(ResourceManagementClient client)
{
return ResourcesManagementTestUtilities.GetResourceLocation(client, "Microsoft.Web/sites");
}
public string GetMySqlLocation(ResourceManagementClient client)
{
return ResourcesManagementTestUtilities.GetResourceLocation(client, "SuccessBricks.ClearDB/databases");
}
[Fact]
public void CleanupAllResources()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
using (UndoContext context = UndoContext.Current)
{
context.Start();
var client = GetResourceManagementClient(handler);
client.SetRetryPolicy(new RetryPolicy<DefaultHttpErrorDetectionStrategy>(1));
var groups = client.ResourceGroups.List(null);
foreach (var group in groups.ResourceGroups)
{
TracingAdapter.Information("Deleting resources for RG {0}", group.Name);
var resources = client.Resources.List(new ResourceListParameters { ResourceGroupName = group.Name, ResourceType = "Microsoft.Web/sites" });
foreach (var resource in resources.Resources)
{
var response = client.Resources.Delete(group.Name, CreateResourceIdentity(resource));
}
var groupResponse = client.ResourceGroups.BeginDeleting(group.Name);
}
}
}
[Fact]
public void CreateResourceWithPlan()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
using (UndoContext context = UndoContext.Current)
{
context.Start();
string groupName = TestUtilities.GenerateName("csmrg");
string resourceName = TestUtilities.GenerateName("csmr");
var client = GetResourceManagementClient(handler);
string mySqlLocation = GetMySqlLocation(client);
var groupIdentity = new ResourceIdentity
{
ResourceName = resourceName,
ResourceProviderNamespace = "SuccessBricks.ClearDB",
ResourceType = "databases",
ResourceProviderApiVersion = StoreResourceProviderVersion
};
client.SetRetryPolicy(new RetryPolicy<DefaultHttpErrorDetectionStrategy>(1));
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = this.ResourceGroupLocation });
var createOrUpdateResult = client.Resources.CreateOrUpdate(groupName, groupIdentity,
new GenericResource
{
Location = mySqlLocation,
Plan = new Plan {Name = "Free"},
Tags = new Dictionary<string, string> { { "provision_source", "RMS" } }
}
);
Assert.Equal(HttpStatusCode.OK, createOrUpdateResult.StatusCode);
Assert.Equal(resourceName, createOrUpdateResult.Resource.Name);
Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(mySqlLocation, createOrUpdateResult.Resource.Location),
string.Format("Resource location for resource '{0}' does not match expected location '{1}'", createOrUpdateResult.Resource.Location, mySqlLocation));
Assert.NotNull(createOrUpdateResult.Resource.Plan);
Assert.Equal("Mercury", createOrUpdateResult.Resource.Plan.Name);
var getResult = client.Resources.Get(groupName, groupIdentity);
Assert.Equal(HttpStatusCode.OK, getResult.StatusCode);
Assert.Equal(resourceName, getResult.Resource.Name);
Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(mySqlLocation, getResult.Resource.Location),
string.Format("Resource location for resource '{0}' does not match expected location '{1}'", getResult.Resource.Location, mySqlLocation));
Assert.NotNull(getResult.Resource.Plan);
Assert.Equal("Mercury", getResult.Resource.Plan.Name);
}
}
[Fact]
public void CreatedResourceIsAvailableInList()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
using (UndoContext context = UndoContext.Current)
{
context.Start();
string groupName = TestUtilities.GenerateName("csmrg");
string resourceName = TestUtilities.GenerateName("csmr");
var client = GetResourceManagementClient(handler);
string websiteLocation = GetWebsiteLocation(client);
client.SetRetryPolicy(new RetryPolicy<DefaultHttpErrorDetectionStrategy>(1));
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = this.ResourceGroupLocation });
var createOrUpdateResult = client.Resources.CreateOrUpdate(groupName, new ResourceIdentity
{
ResourceName = resourceName,
ResourceProviderNamespace = "Microsoft.Web",
ResourceType = "sites",
ResourceProviderApiVersion = WebResourceProviderVersion
},
new GenericResource
{
Location = websiteLocation,
Properties = "{'name':'" + resourceName + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}",
}
);
Assert.Equal(HttpStatusCode.OK, createOrUpdateResult.StatusCode);
Assert.NotNull(createOrUpdateResult.Resource.Id);
Assert.Equal(resourceName, createOrUpdateResult.Resource.Name);
Assert.Equal("Microsoft.Web/sites", createOrUpdateResult.Resource.Type);
Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(websiteLocation, createOrUpdateResult.Resource.Location),
string.Format("Resource location for website '{0}' does not match expected location '{1}'", createOrUpdateResult.Resource.Location, websiteLocation));
var listResult = client.Resources.List(new ResourceListParameters
{
ResourceGroupName = groupName
});
Assert.Equal(1, listResult.Resources.Count);
Assert.Equal(resourceName, listResult.Resources[0].Name);
Assert.Equal("Microsoft.Web/sites", listResult.Resources[0].Type);
Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(websiteLocation, listResult.Resources[0].Location),
string.Format("Resource list location for website '{0}' does not match expected location '{1}'", listResult.Resources[0].Location, websiteLocation));
listResult = client.Resources.List(new ResourceListParameters
{
ResourceGroupName = groupName,
Top = 10
});
Assert.Equal(1, listResult.Resources.Count);
Assert.Equal(resourceName, listResult.Resources[0].Name);
Assert.Equal("Microsoft.Web/sites", listResult.Resources[0].Type);
Assert.True(ResourcesManagementTestUtilities.LocationsAreEqual(websiteLocation, listResult.Resources[0].Location),
string.Format("Resource list location for website '{0}' does not match expected location '{1}'", listResult.Resources[0].Location, websiteLocation));
}
}
[Fact]
public void CreatedResourceIsAvailableInListFilteredByTagName()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
using (UndoContext context = UndoContext.Current)
{
context.Start();
string groupName = TestUtilities.GenerateName("csmrg");
string resourceName = TestUtilities.GenerateName("csmr");
string resourceNameNoTags = TestUtilities.GenerateName("csmr");
string tagName = TestUtilities.GenerateName("csmtn");
var client = GetResourceManagementClient(handler);
string websiteLocation = GetWebsiteLocation(client);
client.SetRetryPolicy(new RetryPolicy<DefaultHttpErrorDetectionStrategy>(1));
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = this.ResourceGroupLocation });
client.Resources.CreateOrUpdate(groupName, new ResourceIdentity
{
ResourceName = resourceName,
ResourceProviderNamespace = "Microsoft.Web",
ResourceType = "sites",
ResourceProviderApiVersion = WebResourceProviderVersion
},
new GenericResource
{
Tags = new Dictionary<string, string> { { tagName, "" } },
Location = websiteLocation,
Properties = "{'name':'" + resourceName + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}"
}
);
client.Resources.CreateOrUpdate(groupName, new ResourceIdentity
{
ResourceName = resourceNameNoTags,
ResourceProviderNamespace = "Microsoft.Web",
ResourceType = "sites",
ResourceProviderApiVersion = WebResourceProviderVersion
},
new GenericResource
{
Location = websiteLocation,
Properties = "{'name':'" + resourceNameNoTags + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}"
}
);
var listResult = client.Resources.List(new ResourceListParameters
{
ResourceGroupName = groupName,
TagName = tagName
});
Assert.Equal(1, listResult.Resources.Count);
Assert.Equal(resourceName, listResult.Resources[0].Name);
var getResult = client.Resources.Get(groupName, new ResourceIdentity
{
ResourceName = resourceName,
ResourceProviderNamespace = "Microsoft.Web",
ResourceType = "sites",
ResourceProviderApiVersion = WebResourceProviderVersion
});
Assert.Equal(resourceName, getResult.Resource.Name);
Assert.True(getResult.Resource.Tags.Keys.Contains(tagName));
}
}
[Fact]
public void CreatedResourceIsAvailableInListFilteredByTagNameAndValue()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
using (UndoContext context = UndoContext.Current)
{
context.Start();
string groupName = TestUtilities.GenerateName("csmrg");
string resourceName = TestUtilities.GenerateName("csmr");
string resourceNameNoTags = TestUtilities.GenerateName("csmr");
string tagName = TestUtilities.GenerateName("csmtn");
string tagValue = TestUtilities.GenerateName("csmtv");
var client = GetResourceManagementClient(handler);
string websiteLocation = GetWebsiteLocation(client);
client.SetRetryPolicy(new RetryPolicy<DefaultHttpErrorDetectionStrategy>(1));
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = this.ResourceGroupLocation });
client.Resources.CreateOrUpdate(groupName, new ResourceIdentity
{
ResourceName = resourceName,
ResourceProviderNamespace = "Microsoft.Web",
ResourceType = "sites",
ResourceProviderApiVersion = WebResourceProviderVersion
},
new GenericResource
{
Tags = new Dictionary<string, string> { { tagName, tagValue } },
Location = websiteLocation,
Properties = "{'name':'" + resourceName + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}"
}
);
client.Resources.CreateOrUpdate(groupName, new ResourceIdentity
{
ResourceName = resourceNameNoTags,
ResourceProviderNamespace = "Microsoft.Web",
ResourceType = "sites",
ResourceProviderApiVersion = WebResourceProviderVersion
},
new GenericResource
{
Location = websiteLocation,
Properties = "{'name':'" + resourceNameNoTags + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}"
}
);
var listResult = client.Resources.List(new ResourceListParameters
{
ResourceGroupName = groupName,
TagName = tagName,
TagValue = tagValue
});
Assert.Equal(1, listResult.Resources.Count);
Assert.Equal(resourceName, listResult.Resources[0].Name);
var getResult = client.Resources.Get(groupName, new ResourceIdentity
{
ResourceName = resourceName,
ResourceProviderNamespace = "Microsoft.Web",
ResourceType = "sites",
ResourceProviderApiVersion = WebResourceProviderVersion
});
Assert.Equal(resourceName, getResult.Resource.Name);
Assert.True(getResult.Resource.Tags.Keys.Contains(tagName));
}
}
[Fact]
public void CreatedAndDeleteResource()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
using (UndoContext context = UndoContext.Current)
{
context.Start();
string groupName = TestUtilities.GenerateName("csmrg");
string resourceName = TestUtilities.GenerateName("csmr");
var client = GetResourceManagementClient(handler);
client.SetRetryPolicy(new RetryPolicy<DefaultHttpErrorDetectionStrategy>(1));
string location = this.GetWebsiteLocation(client);
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = location });
var createOrUpdateResult = client.Resources.CreateOrUpdate(groupName, new ResourceIdentity
{
ResourceName = resourceName,
ResourceProviderNamespace = "Microsoft.Web",
ResourceType = "sites",
ResourceProviderApiVersion = WebResourceProviderVersion
},
new GenericResource
{
Location = location,
Properties = "{'name':'" + resourceName + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}"
}
);
Assert.Equal(HttpStatusCode.OK, createOrUpdateResult.StatusCode);
var listResult = client.Resources.List(new ResourceListParameters
{
ResourceGroupName = groupName
});
Assert.Equal(resourceName, listResult.Resources[0].Name);
var deleteResult = client.Resources.Delete(groupName, new ResourceIdentity
{
ResourceName = resourceName,
ResourceProviderNamespace = "Microsoft.Web",
ResourceType = "sites",
ResourceProviderApiVersion = WebResourceProviderVersion
});
Assert.Equal(HttpStatusCode.OK, deleteResult.StatusCode);
}
}
[Fact]
public void CreatedAndListResource()
{
var handler = new RecordedDelegatingHandler() { StatusCodeToReturn = HttpStatusCode.OK };
using (UndoContext context = UndoContext.Current)
{
context.Start();
string groupName = TestUtilities.GenerateName("csmrg");
string resourceName = TestUtilities.GenerateName("csmr");
var client = GetResourceManagementClient(handler);
string location = this.GetWebsiteLocation(client);
client.ResourceGroups.CreateOrUpdate(groupName, new ResourceGroup { Location = location });
var createOrUpdateResult = client.Resources.CreateOrUpdate(groupName, new ResourceIdentity
{
ResourceName = resourceName,
ResourceProviderNamespace = "Microsoft.Web",
ResourceType = "sites",
ResourceProviderApiVersion = WebResourceProviderVersion
},
new GenericResource
{
Location = location,
Tags = new Dictionary<string, string>() { { "department", "finance" }, { "tagname", "tagvalue" } },
Properties = "{'name':'" + resourceName + "','siteMode':'Limited','computeMode':'Shared', 'sku':'Free', 'workerSize': 0}"
}
);
Assert.Equal(HttpStatusCode.OK, createOrUpdateResult.StatusCode);
var listResult = client.Resources.List(new ResourceListParameters
{
ResourceType = "Microsoft.Web/sites"
});
Assert.NotEmpty(listResult.Resources);
Assert.Equal(2, listResult.Resources[0].Tags.Count);
}
}
}
}
| |
//------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation.
// All rights reserved.
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Android.Accounts;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Content.PM;
using Android.Util;
using Java.Security;
using Java.Util.Concurrent;
using OperationCanceledException = Android.Accounts.OperationCanceledException;
using Permission = Android.Content.PM.Permission;
using Signature = Android.Content.PM.Signature;
namespace Microsoft.IdentityModel.Clients.ActiveDirectory
{
internal class BrokerProxy
{
private const string RedirectUriScheme = "msauth";
private Context mContext;
private AccountManager mAcctManager;
private string mBrokerTag;
public const string DATA_USER_INFO = "com.microsoft.workaccount.user.info";
public BrokerProxy()
{
mBrokerTag = BrokerConstants.Signature;
}
public BrokerProxy(Context ctx)
{
mContext = ctx;
mAcctManager = AccountManager.Get(mContext);
mBrokerTag = BrokerConstants.Signature;
}
public bool CanSwitchToBroker()
{
string packageName = mContext.PackageName;
// ADAL switches broker for following conditions:
// 1- app is not skipping the broker
// 2- permissions are set in the manifest,
// 3- if package is not broker itself for both company portal and azure
// authenticator
// 4- signature of the broker is valid
// 5- account exists
return VerifyManifestPermissions()
&& VerifyAuthenticator(mAcctManager)
&& CheckAccount(mAcctManager, "", "")
&& !packageName.Equals(BrokerConstants.PackageName, StringComparison.OrdinalIgnoreCase)
&& !packageName
.Equals(BrokerConstants.AzureAuthenticatorAppPackageName, StringComparison.OrdinalIgnoreCase);
}
public bool VerifyUser(string username, string uniqueid)
{
return CheckAccount(mAcctManager, username, uniqueid);
}
// App needs to give permission to AccountManager to use broker.
private bool VerifyManifestPermissions()
{
return VerifyManifestPermission("android.permission.GET_ACCOUNTS") &&
VerifyManifestPermission("android.permission.MANAGE_ACCOUNTS") &&
VerifyManifestPermission("android.permission.USE_CREDENTIALS");
}
private bool VerifyManifestPermission(string permission)
{
if (Permission.Granted !=
Application.Context.PackageManager.CheckPermission(permission, Application.Context.PackageName))
{
PlatformPlugin.Logger.Information(null,
string.Format(AdalErrorMessageAndroidEx.MissingPackagePermissionTemplate, permission));
return false;
}
return true;
}
private void VerifyNotOnMainThread()
{
Looper looper = Looper.MyLooper();
if (looper != null && looper == mContext.MainLooper)
{
Exception exception = new Exception(
"calling this from your main thread can lead to deadlock");
PlatformPlugin.Logger.Error(null, exception);
if (mContext.ApplicationInfo.TargetSdkVersion >= BuildVersionCodes.Froyo)
{
throw exception;
}
}
}
private Account FindAccount(string accountName, Account[] accountList)
{
if (accountList != null)
{
foreach (Account account in accountList)
{
if (account != null && account.Name != null
&& account.Name.Equals(accountName, StringComparison.OrdinalIgnoreCase))
{
return account;
}
}
}
return null;
}
private UserInfo FindUserInfo(string userid, UserInfo[] userList)
{
if (userList != null)
{
foreach (UserInfo user in userList)
{
if (user != null && !string.IsNullOrEmpty(user.UniqueId)
&& user.UniqueId.Equals(userid, StringComparison.OrdinalIgnoreCase))
{
return user;
}
}
}
return null;
}
public AuthenticationResultEx GetAuthTokenInBackground(AuthenticationRequest request, Activity callerActivity)
{
AuthenticationResultEx authResult = null;
VerifyNotOnMainThread();
// if there is not any user added to account, it returns empty
Account targetAccount = null;
Account[] accountList = mAcctManager
.GetAccountsByType(BrokerConstants.BrokerAccountType);
if (!string.IsNullOrEmpty(request.BrokerAccountName))
{
targetAccount = FindAccount(request.BrokerAccountName, accountList);
}
else
{
try
{
UserInfo[] users = GetBrokerUsers();
UserInfo matchingUser = FindUserInfo(request.UserId, users);
if (matchingUser != null)
{
targetAccount = FindAccount(matchingUser.DisplayableId, accountList);
}
}
catch (Exception e)
{
PlatformPlugin.Logger.Error(null, e);
}
}
if (targetAccount != null)
{
Bundle brokerOptions = GetBrokerOptions(request);
// blocking call to get token from cache or refresh request in
// background at Authenticator
IAccountManagerFuture result = null;
try
{
// It does not expect activity to be launched.
// AuthenticatorService is handling the request at
// AccountManager.
//
result = mAcctManager.GetAuthToken(targetAccount,
BrokerConstants.AuthtokenType, brokerOptions, false,
null /*
* set to null to avoid callback
*/, new Handler(callerActivity.MainLooper));
// Making blocking request here
PlatformPlugin.Logger.Verbose(null, "Received result from Authenticator");
Bundle bundleResult = (Bundle) result.GetResult(10000, TimeUnit.Milliseconds);
// Authenticator should throw OperationCanceledException if
// token is not available
authResult = GetResultFromBrokerResponse(bundleResult);
}
catch (OperationCanceledException e)
{
PlatformPlugin.Logger.Error(null, e);
}
catch (AuthenticatorException e)
{
PlatformPlugin.Logger.Error(null, e);
}
catch (Exception e)
{
// Authenticator gets problem from webrequest or file read/write
/* Logger.e(TAG, "Authenticator cancels the request", "",
ADALError.BROKER_AUTHENTICATOR_IO_EXCEPTION);*/
PlatformPlugin.Logger.Error(null, e);
}
PlatformPlugin.Logger.Verbose(null, "Returning result from Authenticator");
return authResult;
}
else
{
PlatformPlugin.Logger.Verbose(null, "Target account is not found");
}
return null;
}
private AuthenticationResultEx GetResultFromBrokerResponse(Bundle bundleResult)
{
if (bundleResult == null)
{
throw new Exception("bundleResult");
}
int errCode = bundleResult.GetInt(AccountManager.KeyErrorCode);
string msg = bundleResult.GetString(AccountManager.KeyErrorMessage);
if (!string.IsNullOrEmpty(msg))
{
throw new AdalException(errCode.ToString(), msg);
}
else
{
bool initialRequest = bundleResult.ContainsKey(BrokerConstants.AccountInitialRequest);
if (initialRequest)
{
// Initial request from app to Authenticator needs to launch
// prompt. null resultEx means initial request
return null;
}
// IDtoken is not present in the current broker user model
UserInfo userinfo = GetUserInfoFromBrokerResult(bundleResult);
AuthenticationResult result =
new AuthenticationResult("Bearer", bundleResult.GetString(AccountManager.KeyAuthtoken),
ConvertFromTimeT(bundleResult.GetLong("account.expiredate", 0)))
{
UserInfo = userinfo
};
result.UpdateTenantAndUserInfo(bundleResult.GetString(BrokerConstants.AccountUserInfoTenantId), null,
userinfo);
return new AuthenticationResultEx
{
Result = result,
RefreshToken = null,
ResourceInResponse = null,
};
}
}
internal static DateTimeOffset ConvertFromTimeT(long seconds)
{
var startTime = new DateTimeOffset(1970, 1, 1, 0, 0, 0, 0, TimeSpan.Zero);
return startTime.AddMilliseconds(seconds);
}
internal static UserInfo GetUserInfoFromBrokerResult(Bundle bundle)
{
// Broker has one user and related to ADFS WPJ user. It does not return
// idtoken
string userid = bundle.GetString(BrokerConstants.AccountUserInfoUserId);
string givenName = bundle
.GetString(BrokerConstants.AccountUserInfoGivenName);
string familyName = bundle
.GetString(BrokerConstants.AccountUserInfoFamilyName);
string identityProvider = bundle
.GetString(BrokerConstants.AccountUserInfoIdentityProvider);
string displayableId = bundle
.GetString(BrokerConstants.AccountUserInfoUserIdDisplayable);
return new UserInfo
{
UniqueId = userid,
GivenName = givenName,
FamilyName = familyName,
IdentityProvider = identityProvider,
DisplayableId = displayableId
};
}
public Intent GetIntentForBrokerActivity(AuthenticationRequest request, Activity callerActivity)
{
Intent intent = null;
IAccountManagerFuture result = null;
try
{
// Callback is not passed since it is making a blocking call to get
// intent. Activity needs to be launched from calling app
// to get the calling app's metadata if needed at BrokerActivity.
Bundle addAccountOptions = GetBrokerOptions(request);
result = mAcctManager.AddAccount(BrokerConstants.BrokerAccountType,
BrokerConstants.AuthtokenType, null, addAccountOptions, null,
null, new Handler(callerActivity.MainLooper));
// Making blocking request here
Bundle bundleResult = (Bundle) result.Result;
// Authenticator should throw OperationCanceledException if
// token is not available
intent = (Intent) bundleResult.GetParcelable(AccountManager.KeyIntent);
// Add flag to this intent to signal that request is for broker
// logic
if (intent != null)
{
intent.PutExtra(BrokerConstants.BrokerRequest, BrokerConstants.BrokerRequest);
}
}
catch (OperationCanceledException e)
{
PlatformPlugin.Logger.Error(null, e);
}
catch (Exception e)
{
// Authenticator gets problem from webrequest or file read/write
PlatformPlugin.Logger.Error(null, new AdalException("Authenticator cancels the request", e));
}
return intent;
}
private string GetRedirectUriForBroker()
{
string packageName = Application.Context.PackageName;
// First available signature. Applications can be signed with multiple
// signatures.
string signatureDigest = this.GetCurrentSignatureForPackage(packageName);
if (!string.IsNullOrEmpty(signatureDigest))
{
return string.Format(CultureInfo.CurrentCulture, "{0}://{1}/{2}", RedirectUriScheme,
packageName.ToLower(), signatureDigest);
}
return string.Empty;
}
private string GetCurrentSignatureForPackage(string packageName)
{
try
{
PackageInfo info = Application.Context.PackageManager.GetPackageInfo(packageName,
PackageInfoFlags.Signatures);
if (info != null && info.Signatures != null && info.Signatures.Count > 0)
{
Signature signature = info.Signatures[0];
MessageDigest md = MessageDigest.GetInstance("SHA");
md.Update(signature.ToByteArray());
return Convert.ToBase64String(md.Digest(), Base64FormattingOptions.None);
// Server side needs to register all other tags. ADAL will
// send one of them.
}
}
catch (PackageManager.NameNotFoundException)
{
PlatformPlugin.Logger.Information(null, "Calling App's package does not exist in PackageManager");
}
catch (NoSuchAlgorithmException)
{
PlatformPlugin.Logger.Information(null, "Digest SHA algorithm does not exists");
}
return null;
}
private Bundle GetBrokerOptions(AuthenticationRequest request)
{
Bundle brokerOptions = new Bundle();
// request needs to be parcelable to send across process
brokerOptions.PutInt("com.microsoft.aad.adal:RequestId", request.RequestId);
brokerOptions.PutString(BrokerConstants.AccountAuthority,
request.Authority);
brokerOptions.PutInt("json", 1);
brokerOptions.PutString(BrokerConstants.AccountResource,
request.Resource);
string computedRedirectUri = GetRedirectUriForBroker();
if (!string.IsNullOrEmpty(request.RedirectUri) && !string.Equals(computedRedirectUri, request.RedirectUri))
{
throw new ArgumentException("redirect uri for broker invocation should be set to" + computedRedirectUri);
}
brokerOptions.PutString(BrokerConstants.AccountRedirect, request.RedirectUri);
brokerOptions.PutString(BrokerConstants.AccountClientIdKey,
request.ClientId);
brokerOptions.PutString(BrokerConstants.AdalVersionKey,
request.Version);
brokerOptions.PutString(BrokerConstants.AccountExtraQueryParam,
request.ExtraQueryParamsAuthentication);
if (request.CorrelationId != null)
{
brokerOptions.PutString(BrokerConstants.AccountCorrelationId, request
.CorrelationId.ToString());
}
string username = request.BrokerAccountName;
if (string.IsNullOrEmpty(username))
{
username = request.LoginHint;
}
brokerOptions.PutString(BrokerConstants.AccountLoginHint, username);
brokerOptions.PutString(BrokerConstants.AccountName, username);
return brokerOptions;
}
private bool CheckAccount(AccountManager am, string username, string uniqueId)
{
AuthenticatorDescription[] authenticators = am.GetAuthenticatorTypes();
foreach (AuthenticatorDescription authenticator in authenticators)
{
if (authenticator.Type.Equals(BrokerConstants.BrokerAccountType))
{
Account[] accountList = mAcctManager
.GetAccountsByType(BrokerConstants.BrokerAccountType);
// Authenticator installed from Company portal
// This supports only one account
if (authenticator.PackageName
.Equals(BrokerConstants.PackageName, StringComparison.OrdinalIgnoreCase))
{
// Adal should not connect if given username does not match
if (accountList != null && accountList.Length > 0)
{
return VerifyAccount(accountList, username, uniqueId);
}
return false;
// Check azure authenticator and allow calls for test
// versions
}
else if (authenticator.PackageName
.Equals(BrokerConstants.AzureAuthenticatorAppPackageName, StringComparison.OrdinalIgnoreCase)
|| authenticator.PackageName
.Equals(BrokerConstants.PackageName, StringComparison.OrdinalIgnoreCase))
{
// Existing broker logic only connects to broker for token
// requests if account exists. New version can allow to
// add accounts through Adal.
if (HasSupportToAddUserThroughBroker())
{
PlatformPlugin.Logger.Verbose(null, "Broker supports to add user through app");
return true;
}
else if (accountList != null && accountList.Length > 0)
{
return VerifyAccount(accountList, username, uniqueId);
}
}
}
}
return false;
}
private bool VerifyAccount(Account[] accountList, string username, string uniqueId)
{
if (!string.IsNullOrEmpty(username))
{
return username.Equals(accountList[0].Name, StringComparison.OrdinalIgnoreCase);
}
if (!string.IsNullOrEmpty(uniqueId))
{
// Uniqueid for account at authenticator is not available with
// Account
UserInfo[] users;
try
{
users = GetBrokerUsers();
UserInfo matchingUser = FindUserInfo(uniqueId, users);
return matchingUser != null;
}
catch (Exception e)
{
PlatformPlugin.Logger.Error(null, e);
}
PlatformPlugin.Logger.Verbose(null,
"It could not check the uniqueid from broker. It is not using broker");
return false;
}
// if username or uniqueid not specified, it should use the broker
// account.
return true;
}
private bool HasSupportToAddUserThroughBroker()
{
Intent intent = new Intent();
intent.SetPackage(BrokerConstants.AzureAuthenticatorAppPackageName);
intent.SetClassName(BrokerConstants.AzureAuthenticatorAppPackageName,
BrokerConstants.AzureAuthenticatorAppPackageName
+ ".ui.AccountChooserActivity");
PackageManager packageManager = mContext.PackageManager;
IList<ResolveInfo> infos = packageManager.QueryIntentActivities(intent, 0);
return infos.Count > 0;
}
private bool VerifySignature(string brokerPackageName)
{
List< X509Certificate2> certs = ReadCertDataForBrokerApp(brokerPackageName);
VerifySignatureHash(certs);
if (certs.Count > 1)
{
// Verify the certificate chain is chained correctly.
VerifyCertificateChain(certs);
}
return true;
}
private void VerifySignatureHash(List<X509Certificate2> certs)
{
bool validSignatureFound = false;
foreach (var signerCert in certs)
{
MessageDigest messageDigest = MessageDigest.GetInstance("SHA");
messageDigest.Update(signerCert.RawData);
// Check the hash for signer cert is the same as what we hardcoded.
string signatureHash = Base64.EncodeToString(messageDigest.Digest(), Base64Flags.NoWrap);
if (mBrokerTag.Equals(signatureHash) ||
BrokerConstants.AzureAuthenticatorAppSignature.Equals(signatureHash))
{
validSignatureFound = true;
}
}
if (!validSignatureFound)
{
throw new AdalException(AdalErrorAndroidEx.SignatureVerificationFailed, "No matching signature found");
}
}
private void VerifyCertificateChain(List<X509Certificate2> certificates)
{
X509Certificate2Collection collection = new X509Certificate2Collection(certificates.ToArray());
X509Chain chain = new X509Chain();
chain.ChainPolicy = new X509ChainPolicy()
{
RevocationMode = X509RevocationMode.NoCheck
};
chain.ChainPolicy.ExtraStore.AddRange(collection);
foreach (X509Certificate2 certificate in certificates)
{
var chainBuilt = chain.Build(certificate);
if (!chainBuilt)
{
foreach (X509ChainStatus chainStatus in chain.ChainStatus)
{
if (chainStatus.Status != X509ChainStatusFlags.UntrustedRoot)
{
throw new AdalException(AdalErrorAndroidEx.SignatureVerificationFailed,
string.Format(CultureInfo.InvariantCulture,
"app certificate validation failed with {0}", chainStatus.Status));
}
}
}
}
}
private List<X509Certificate2> ReadCertDataForBrokerApp(string brokerPackageName)
{
PackageInfo packageInfo = mContext.PackageManager.GetPackageInfo(brokerPackageName,
PackageInfoFlags.Signatures);
if (packageInfo == null)
{
throw new AdalException(AdalErrorAndroidEx.SignatureVerificationFailed,
"No broker package found.");
}
if (packageInfo.Signatures == null || packageInfo.Signatures.Count == 0)
{
throw new AdalException(AdalErrorAndroidEx.SignatureVerificationFailed,
"No signature associated with the broker package.");
}
List<X509Certificate2> certificates = new List<X509Certificate2>(packageInfo.Signatures.Count);
foreach (Signature signature in packageInfo.Signatures)
{
byte[] rawCert = signature.ToByteArray();
X509Certificate2 x509Certificate = null;
x509Certificate = new X509Certificate2(rawCert);
certificates.Add(x509Certificate);
}
return certificates;
}
private bool VerifyAuthenticator(AccountManager am)
{
// there may be multiple authenticators from same package
// , but there is only one entry for an authenticator type in
// AccountManager.
// If another app tries to install same authenticator type, it will
// queue up and will be active after first one is uninstalled.
AuthenticatorDescription[] authenticators = am.GetAuthenticatorTypes();
foreach (AuthenticatorDescription authenticator in authenticators)
{
if (authenticator.Type.Equals(BrokerConstants.BrokerAccountType)
&& VerifySignature(authenticator.PackageName))
{
return true;
}
}
return false;
}
public UserInfo[] GetBrokerUsers()
{
// Calling this on main thread will cause exception since this is
// waiting on AccountManagerFuture
if (Looper.MyLooper() == Looper.MainLooper)
{
throw new Exception("Calling getBrokerUsers on main thread");
}
Account[] accountList = mAcctManager
.GetAccountsByType(BrokerConstants.BrokerAccountType);
Bundle bundle = new Bundle();
bundle.PutBoolean(DATA_USER_INFO, true);
if (accountList != null)
{
// get info for each user
UserInfo[] users = new UserInfo[accountList.Length];
for (int i = 0; i < accountList.Length; i++)
{
// Use AccountManager Api method to get extended user info
IAccountManagerFuture result = mAcctManager.UpdateCredentials(
accountList[i], BrokerConstants.AuthtokenType, bundle,
null, null, null);
PlatformPlugin.Logger.Verbose(null, "Waiting for the result");
Bundle userInfoBundle = (Bundle) result.Result;
users[i] = new UserInfo
{
UniqueId = userInfoBundle
.GetString(BrokerConstants.AccountUserInfoUserId),
GivenName = userInfoBundle
.GetString(BrokerConstants.AccountUserInfoGivenName),
FamilyName = userInfoBundle
.GetString(BrokerConstants.AccountUserInfoFamilyName),
IdentityProvider = userInfoBundle
.GetString(BrokerConstants.AccountUserInfoIdentityProvider),
DisplayableId = userInfoBundle
.GetString(BrokerConstants.AccountUserInfoUserIdDisplayable),
};
}
return users;
}
return null;
}
}
}
| |
using System;
using System.Runtime.Serialization;
using System.Collections;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
using System.IO;
using SpiffLib;
namespace m
{
[Serializable]
public class TemplateDoc : Document, ISerializable, IDeserializationCallback {
Template m_tmplBackground = null;
int m_cookie = 5000;
ArrayList m_alsTemplates = new ArrayList();
string m_strNameBackground = null;
Size m_sizTile;
Palette m_pal;
public delegate void BackgroundChangedHandler(TemplateDoc tmpd);
public event BackgroundChangedHandler BackgroundChanged;
public delegate void NameChangedHandler(Document doc);
public event NameChangedHandler NameChanged;
public TemplateDoc(DocTemplate doct, string strFile, Object[] aobj) : base(doct, strFile) {
if (aobj != null) {
m_sizTile = (Size)aobj[0];
} else {
m_sizTile = AskTileSize();
}
m_doct = (TemplateDocTemplate)doct;
InitCommon();
}
public TemplateDoc(SerializationInfo info, StreamingContext ctx) : base((DocTemplate)(((Hashtable)ctx.Context)["DocTemplate"]), (string)(((Hashtable)ctx.Context)["Filename"])) {
m_cookie = info.GetInt32("Cookie");
// Backwards compat
try {
m_strNameBackground = info.GetInt32("CookieBackground").ToString();
} catch {
m_strNameBackground = "0";
try {
m_strNameBackground = info.GetString("NameBackground");
} catch {
}
}
// Get tile size. If none, default 16,16
try {
m_sizTile = (Size)info.GetValue("TileSize", typeof(Size));
} catch {
m_sizTile = new Size(16, 16);
}
// Get palette
try {
m_pal = (Palette)info.GetValue("Palette", typeof(Palette));
} catch {
m_pal = null;
}
m_alsTemplates = (ArrayList)info.GetValue("TileTemplates", typeof(ArrayList));
}
public void OnDeserialization(object obSender) {
foreach (Template tmpl in m_alsTemplates)
tmpl.Doc = this;
SetModified(false);
InitCommon();
}
void InitCommon() {
TemplateDocTemplate doct = (TemplateDocTemplate)m_doct;
doct.TemplateChanged += new TemplateDocTemplate.TemplateChangedHandler(TemplateDocTemplate_TemplateChanged);
}
public void GetObjectData(SerializationInfo info, StreamingContext context) {
info.AddValue("Cookie", m_cookie);
info.AddValue("TileTemplates", m_alsTemplates);
string strNameBackground = "";
if (m_tmplBackground != null)
strNameBackground = m_tmplBackground.Name;
info.AddValue("NameBackground", strNameBackground);
info.AddValue("TileSize", m_sizTile);
if (m_pal != null)
info.AddValue("Palette", m_pal);
}
Size AskTileSize() {
TileSizeForm form = new TileSizeForm();
form.ShowDialog(DocManager.GetFrameParent());
return form.GetTileSize();
}
public override void SetPath(string strFile) {
string strDir = m_strDir;
string strFileName = m_strFileName;
base.SetPath(strFile);
if (strDir != m_strDir || strFileName != m_strFileName) {
if (NameChanged != null)
NameChanged(this);
}
}
public override string GetName() {
if (m_strFileName == null)
return base.GetName();
return Path.ChangeExtension(m_strFileName, null);
}
public void AddTemplates(string[] astrFileBitmap) {
ArrayList alsNamesAdded = new ArrayList();
foreach (string strFileBitmap in astrFileBitmap) {
Template tmpl = new Template(this, "tmpl" + m_cookie);
m_cookie++;
if (tmpl.Import(strFileBitmap)) {
alsNamesAdded.Add(tmpl.Name);
m_alsTemplates.Add(tmpl);
}
}
if (alsNamesAdded.Count != 0) {
TemplateDocTemplate doct = (TemplateDocTemplate)m_doct;
doct.OnTemplatesAdded(this, (string[])alsNamesAdded.ToArray(typeof(string)));
}
SetModified(true);
}
public void AddTemplates(Template[] atmpl) {
if (atmpl.Length == 0)
return;
ArrayList alsNamesAdded = new ArrayList();
foreach (Template tmpl in atmpl) {
m_alsTemplates.Add(tmpl);
alsNamesAdded.Add(tmpl.Name);
}
TemplateDocTemplate doct = (TemplateDocTemplate)m_doct;
doct.OnTemplatesAdded(this, (string[])alsNamesAdded.ToArray(typeof(string)));
SetModified(true);
}
public void RemoveTemplates(Template[] atmpl) {
if (atmpl.Length == 0)
return;
ArrayList alsNames = new ArrayList();
foreach (Template tmpl in atmpl) {
m_alsTemplates.Remove(tmpl);
alsNames.Add(tmpl.Name);
if (tmpl == m_tmplBackground)
SetBackgroundTemplate(null);
}
TemplateDocTemplate doct = (TemplateDocTemplate)m_doct;
doct.OnTemplatesRemoved(this, (string[])alsNames.ToArray(typeof(string)));
SetModified(true);
}
public Template[] GetTemplates() {
return (Template[])m_alsTemplates.ToArray(typeof(Template));
}
void TemplateDocTemplate_TemplateChanged(TemplateDoc tmpd, string strProperty, string strName, string strParam) {
if (tmpd == this)
SetModified(true);
}
public Template FindTemplate(string strName) {
foreach (Template tmpl in m_alsTemplates) {
if (tmpl.Name != null && tmpl.Name == strName)
return tmpl;
}
return null;
}
public void Dispose() {
RemoveTemplates((Template[])m_alsTemplates.ToArray(typeof(Template)));
}
public Template GetBackgroundTemplate() {
if (m_tmplBackground == null && m_strNameBackground != null)
m_tmplBackground = FindTemplate(m_strNameBackground);
return m_tmplBackground;
}
public void SetBackgroundTemplate(Template tmpl) {
if (m_tmplBackground == tmpl)
return;
m_tmplBackground = tmpl;
if (BackgroundChanged != null)
BackgroundChanged(this);
SetModified(true);
}
public void SetPalette(Palette pal, bool fColorMatch) {
m_pal = pal;
SetModified(true);
if (!fColorMatch)
return;
ArrayList alsColors = new ArrayList();
foreach (Template tmpl in m_alsTemplates) {
Bitmap bm = tmpl.Bitmap;
bool[,] afOccupancy = tmpl.OccupancyMap;
int ctx = afOccupancy.GetLength(1);
int cty = afOccupancy.GetLength(0);
for (int ty = 0; ty < cty; ty++) {
for (int tx = 0; tx < ctx; tx++) {
if (!afOccupancy[ty, tx])
continue;
int xOrigin = tx * m_sizTile.Width;
int yOrigin = ty * m_sizTile.Height;
for (int y = yOrigin; y < yOrigin + m_sizTile.Height; y++) {
for (int x = xOrigin; x < xOrigin + m_sizTile.Width; x++) {
Color clrOld = bm.GetPixel(x, y);
Color clrNew = pal[pal.FindClosestEntry(clrOld)];
bm.SetPixel(x, y, clrNew);
}
}
}
}
TemplateDocTemplate doct = (TemplateDocTemplate)m_doct;
doct.OnTemplateChanged(this, "Bitmap", tmpl.Name, null);
}
}
public Palette GetPalette() {
return m_pal;
}
public bool IsNameUnique(string strName) {
foreach (Template tmpl in m_alsTemplates) {
if (tmpl.Name == strName)
return false;
}
return true;
}
public Size TileSize {
get {
return m_sizTile;
}
set {
// This is only done in special circumstances that don't require notification
m_sizTile = value;
}
}
}
public enum TerrainTypes { Start = 0, Open = 0, Blocked, Area, Wall, End };
public enum TerrainColors { Grass, Cliff, Water, Road };
[Serializable]
public class Template : ISerializable {
public string ImportPath = null;
private string m_strName = null;
public bool[,] OccupancyMap = null;
public TerrainTypes[,] TerrainMap = null;
public TerrainColors[,] TerrainColors = null;
public Bitmap Bitmap = null;
public TemplateDoc Doc = null;
TemplateDocTemplate m_doct = (TemplateDocTemplate)DocManager.FindDocTemplate(typeof(TemplateDoc));
public Template(TemplateDoc doc, string strName) {
Doc = doc;
m_strName = strName;
}
public Template(TemplateDoc doc, Bitmap bm, string strName) {
m_strName = strName;
Doc = doc;
if (!SetBitmap(bm))
throw new Exception("Invalid tile template");
}
public Template(SerializationInfo info, StreamingContext ctx) {
// Backwards compat
try {
m_strName = info.GetInt32("Cookie").ToString();
} catch {
m_strName = info.GetString("Name");
}
try {
TerrainColors = (TerrainColors[,])info.GetValue("TerrainColors", typeof(TerrainColors[,]));
} catch {
TerrainColors = null;
}
OccupancyMap = (bool[,])info.GetValue("OccupancyMap", typeof(bool[,]));
TerrainMap = (TerrainTypes[,])info.GetValue("TerrainMap", typeof(TerrainTypes[,]));
Bitmap = (Bitmap)info.GetValue("Bitmap", typeof(Bitmap));
}
public void GetObjectData(SerializationInfo info, StreamingContext context) {
info.AddValue("Name", m_strName);
info.AddValue("OccupancyMap", OccupancyMap);
info.AddValue("TerrainMap", TerrainMap);
info.AddValue("Bitmap", Bitmap);
info.AddValue("TerrainColors", TerrainColors);
}
public bool Import(string strFileBitmap) {
try {
Bitmap bm = new Bitmap(strFileBitmap);
if (SetBitmap(bm)) {
ImportPath = strFileBitmap;
return true;
}
return false;
} catch {
MessageBox.Show("Error opening tile bitmap");
return false;
}
}
private bool SetBitmap(Bitmap bm) {
if ((bm.Width % Doc.TileSize.Width) != 0 && (bm.Height % Doc.TileSize.Height) != 0) {
MessageBox.Show("Tile dimensions not a multiple of tile size");
return false;
}
bm.MakeTransparent(Color.FromArgb(255, 0, 255));
Bitmap = bm;
UpdateMaps();
m_doct.OnTemplateChanged(Doc, "Bitmap", m_strName, null);
return true;
}
// Update the map sizes to reflect the new bitmap
private void UpdateMaps() {
int ctx = Bitmap.Width / Doc.TileSize.Width;
int cty = Bitmap.Height / Doc.TileSize.Height;
// Try to copy what we can of the old terrain map
TerrainTypes[,] ater = new TerrainTypes[cty, ctx];
if (TerrainMap != null) {
int ctyOld = TerrainMap.GetLength(0);
int ctxOld = TerrainMap.GetLength(1);
for (int tx = 0; tx < ctx && tx < ctxOld; tx++) {
for (int ty = 0; ty < cty && ty < ctyOld; ty++) {
ater[ty, tx] = TerrainMap[ty, tx];
}
}
}
TerrainMap = ater;
// Create a new occupancy map. Old one not relevant.
bool[,] afOcc = new bool[cty, ctx];
for (int tx = 0; tx < ctx; tx++) {
for (int ty = 0; ty < cty; ty++) {
afOcc[ty, tx] = true;
Color clr = Bitmap.GetPixel(tx * Doc.TileSize.Width, ty * Doc.TileSize.Height);
if (clr.A == 0)
afOcc[ty, tx] = false;
}
}
OccupancyMap = afOcc;
}
// Properties
public string Name {
get {
return m_strName;
}
set {
// Only if unique
if (value == m_strName)
return;
if (!Doc.IsNameUnique(value)) {
MessageBox.Show("The name " + value + " is not unique. Not assigned.");
return;
}
string strNameOld = m_strName;
m_strName = value;
m_doct.OnTemplateChanged(Doc, "Name", strNameOld, m_strName);
}
}
public int Ctx {
get {
return Bitmap.Width / Doc.TileSize.Width;
}
}
public int Cty {
get {
return Bitmap.Height / Doc.TileSize.Height;
}
}
}
// A doc template for (tile) templates.
public class TemplateDocTemplate : DocTemplate {
static string[] astr = { "Template Collection", "Untitled", "Templates", "tc" };
public delegate void TemplatesAddedHandler(TemplateDoc tmpd, string[] astrName);
public event TemplatesAddedHandler TemplatesAdded;
public delegate void TemplatesRemovedHandler(TemplateDoc tmpd, string[] astrName);
public event TemplatesRemovedHandler TemplatesRemoved;
public delegate void TemplateChangedHandler(TemplateDoc tmpd, string strProperty, string strName, string strParam);
public event TemplateChangedHandler TemplateChanged;
public TemplateDocTemplate() : base(astr, typeof(TemplateDoc), null, null, new TemplateDocBinder()) {
}
public override Document OpenDocument(string strFile) {
// Don't support loading the same templates twice
string strPathLower = null;
if (strFile != null)
strPathLower = Path.GetFullPath(strFile).ToLower();
foreach (Document doc in m_alsDocuments) {
string strPath = doc.GetPath();
if (strPath == null)
continue;
if (strPath.ToLower() == strPathLower) {
SetActiveDocument(doc);
return doc;
}
}
return base.OpenDocument(strFile);
}
public void OnTemplatesAdded(TemplateDoc tmpd, string[] astrName) {
if (TemplatesAdded != null)
TemplatesAdded(tmpd, astrName);
}
public void OnTemplateChanged(TemplateDoc tmpd, string strProperty, string strName, string strParam) {
if (TemplateChanged != null)
TemplateChanged(tmpd, strProperty, strName, strParam);
}
public void OnTemplatesRemoved(TemplateDoc tmpd, string[] astrName) {
if (TemplatesRemoved != null)
TemplatesRemoved(tmpd, astrName);
}
}
// Compatibility goo
public class TemplateDocBinder : SerializationBinder {
public override Type BindToType(string strAssembly, string strType) {
if (strType == "m.TileTemplateCollection")
return typeof(TemplateDoc);
if (strType == "m.TileTemplate")
return typeof(Template);
return Type.GetType(strType);
}
}
}
| |
//
// SourceRowRenderer.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2005-2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Gtk;
using Gdk;
using Pango;
using Hyena.Gui;
using Hyena.Gui.Theming;
using Hyena.Gui.Theatrics;
using Banshee.ServiceStack;
namespace Banshee.Sources.Gui
{
public class SourceRowRenderer : CellRendererText
{
public static void CellDataHandler (CellLayout layout, CellRenderer cell, TreeModel model, TreeIter iter)
{
SourceRowRenderer renderer = cell as SourceRowRenderer;
if (renderer == null) {
return;
}
var type = model.GetValue (iter, (int)SourceModel.Columns.Type);
if (type == null || (SourceModel.EntryType) type != SourceModel.EntryType.Source) {
renderer.Visible = false;
return;
}
Source source = model.GetValue (iter, 0) as Source;
renderer.Source = source;
renderer.Iter = iter;
if (source == null) {
return;
}
renderer.Visible = true;
renderer.Text = source.Name;
renderer.Sensitive = source.CanActivate;
}
private Source source;
public Source Source {
get { return source; }
set { source = value; }
}
private SourceView view;
private Widget parent_widget;
public Widget ParentWidget {
get { return parent_widget; }
set { parent_widget = value; }
}
private TreeIter iter = TreeIter.Zero;
public TreeIter Iter {
get { return iter; }
set { iter = value; }
}
private int row_height = 22;
public int RowHeight {
get { return row_height; }
set { row_height = value; }
}
public SourceRowRenderer ()
{
}
private StateType RendererStateToWidgetState (Widget widget, CellRendererState flags)
{
if (!Sensitive) {
return StateType.Insensitive;
} else if ((flags & CellRendererState.Selected) == CellRendererState.Selected) {
return widget.HasFocus ? StateType.Selected : StateType.Active;
} else if ((flags & CellRendererState.Prelit) == CellRendererState.Prelit) {
ComboBox box = parent_widget as ComboBox;
return box != null && box.PopupShown ? StateType.Prelight : StateType.Normal;
} else if (widget.State == StateType.Insensitive) {
return StateType.Insensitive;
} else {
return StateType.Normal;
}
}
private int Depth {
get {
return Source.Parent != null ? 1 : 0;
}
}
public override void GetSize (Widget widget, ref Gdk.Rectangle cell_area,
out int x_offset, out int y_offset, out int width, out int height)
{
int text_x, text_y, text_w, text_h;
base.GetSize (widget, ref cell_area, out text_x, out text_y, out text_w, out text_h);
x_offset = 0;
y_offset = 0;
if (!(widget is TreeView)) {
width = 200;
} else {
width = 0;
}
height = (int)Math.Max (RowHeight, text_h);
}
private int expander_right_x;
public bool InExpander (int x)
{
return x < expander_right_x;
}
protected override void Render (Gdk.Drawable drawable, Widget widget, Gdk.Rectangle background_area,
Gdk.Rectangle cell_area, Gdk.Rectangle expose_area, CellRendererState flags)
{
if (source == null || source is SourceManager.GroupSource) {
return;
}
view = widget as SourceView;
bool selected = view != null && view.Selection.IterIsSelected (iter);
StateType state = RendererStateToWidgetState (widget, flags);
RenderSelection (drawable, background_area, selected, state);
int title_layout_width = 0, title_layout_height = 0;
int count_layout_width = 0, count_layout_height = 0;
int max_title_layout_width;
int img_padding = 6;
int expander_icon_spacing = 3;
int x = cell_area.X;
bool np_etc = (source.Order + Depth * 100) < 40;
if (!np_etc) {
x += Depth * img_padding + (int)Xpad;
} else {
// Don't indent NowPlaying and Play Queue as much
x += Math.Max (0, (int)Xpad - 2);
}
Gdk.GC main_gc = widget.Style.TextGC (state);
// Draw the expander if the source has children
double exp_h = (cell_area.Height - 2.0*Ypad) / 3.2;
double exp_w = exp_h * 1.6;
if (view != null && view.Cr != null && source.Children != null && source.Children.Count > 0) {
var r = new Gdk.Rectangle (x, cell_area.Y + (int)((cell_area.Height - exp_h) / 2.0), (int)exp_w, (int)exp_h);
view.Theme.DrawArrow (view.Cr, r, source.Expanded ? Math.PI/2.0 : 0.0);
}
if (!np_etc) {
x += (int) exp_w;
x += 2; // a little spacing after the expander
expander_right_x = x;
}
// Draw icon
Pixbuf icon = SourceIconResolver.ResolveIcon (source, RowHeight);
bool dispose_icon = false;
if (state == StateType.Insensitive) {
// Code ported from gtk_cell_renderer_pixbuf_render()
var icon_source = new IconSource () {
Pixbuf = icon,
Size = IconSize.SmallToolbar,
SizeWildcarded = false
};
icon = widget.Style.RenderIcon (icon_source, widget.Direction, state,
(IconSize)(-1), widget, "SourceRowRenderer");
dispose_icon = true;
icon_source.Dispose ();
}
if (icon != null) {
x += expander_icon_spacing;
drawable.DrawPixbuf (main_gc, icon, 0, 0,
x, Middle (cell_area, icon.Height),
icon.Width, icon.Height, RgbDither.None, 0, 0);
x += icon.Width;
if (dispose_icon) {
icon.Dispose ();
}
}
// Setup font info for the title/count, and see if we should show the count
bool hide_count = source.EnabledCount <= 0 || source.Properties.Get<bool> ("SourceView.HideCount");
FontDescription fd = widget.PangoContext.FontDescription.Copy ();
fd.Weight = (ISource)ServiceManager.PlaybackController.NextSource == (ISource)source
? Pango.Weight.Bold
: Pango.Weight.Normal;
if (view != null && source == view.NewPlaylistSource) {
fd.Style = Pango.Style.Italic;
hide_count = true;
}
Pango.Layout title_layout = new Pango.Layout (widget.PangoContext);
Pango.Layout count_layout = null;
// If we have a count to draw, setup its fonts and see how wide it is to see if we have room
if (!hide_count) {
count_layout = new Pango.Layout (widget.PangoContext);
count_layout.FontDescription = fd;
count_layout.SetMarkup (String.Format ("<span size=\"small\">{0}</span>", source.EnabledCount));
count_layout.GetPixelSize (out count_layout_width, out count_layout_height);
}
// Hide the count if the title has no space
max_title_layout_width = cell_area.Width - x - count_layout_width;//(icon == null ? 0 : icon.Width) - count_layout_width - 10;
if (!hide_count && max_title_layout_width <= 0) {
hide_count = true;
}
// Draw the source Name
title_layout.FontDescription = fd;
title_layout.Width = (int)(max_title_layout_width * Pango.Scale.PangoScale);
title_layout.Ellipsize = EllipsizeMode.End;
title_layout.SetText (source.Name);
title_layout.GetPixelSize (out title_layout_width, out title_layout_height);
x += img_padding;
drawable.DrawLayout (main_gc, x, Middle (cell_area, title_layout_height), title_layout);
title_layout.Dispose ();
// Draw the count
if (!hide_count) {
if (view != null && view.Cr != null) {
view.Cr.Color = state == StateType.Normal || (view != null && state == StateType.Prelight)
? view.Theme.TextMidColor
: view.Theme.Colors.GetWidgetColor (GtkColorClass.Text, state);
view.Cr.MoveTo (
cell_area.X + cell_area.Width - count_layout_width - 2,
cell_area.Y + 0.5 + (double)(cell_area.Height - count_layout_height) / 2.0);
PangoCairoHelper.ShowLayout (view.Cr, count_layout);
}
count_layout.Dispose ();
}
fd.Dispose ();
}
private void RenderSelection (Gdk.Drawable drawable, Gdk.Rectangle background_area,
bool selected, StateType state)
{
if (view == null) {
return;
}
if (selected && view.Cr != null) {
Gdk.Rectangle rect = background_area;
rect.X -= 2;
rect.Width += 4;
// clear the standard GTK selection and focus
drawable.DrawRectangle (view.Style.BaseGC (StateType.Normal), true, rect);
// draw the hot cairo selection
if (!view.EditingRow) {
view.Theme.DrawRowSelection (view.Cr, background_area.X + 1, background_area.Y + 1,
background_area.Width - 2, background_area.Height - 2);
}
} else if (!TreeIter.Zero.Equals (iter) && iter.Equals (view.HighlightedIter) && view.Cr != null) {
view.Theme.DrawRowSelection (view.Cr, background_area.X + 1, background_area.Y + 1,
background_area.Width - 2, background_area.Height - 2, false);
} else if (view.NotifyStage.ActorCount > 0 && view.Cr != null) {
if (!TreeIter.Zero.Equals (iter) && view.NotifyStage.Contains (iter)) {
Actor<TreeIter> actor = view.NotifyStage[iter];
Cairo.Color color = view.Theme.Colors.GetWidgetColor (GtkColorClass.Background, StateType.Active);
color.A = Math.Sin (actor.Percent * Math.PI);
view.Theme.DrawRowSelection (view.Cr, background_area.X + 1, background_area.Y + 1,
background_area.Width - 2, background_area.Height - 2, true, true, color);
}
}
}
private int Middle (Gdk.Rectangle area, int height)
{
return area.Y + (int)Math.Round ((double)(area.Height - height) / 2.0, MidpointRounding.AwayFromZero);
}
public override CellEditable StartEditing (Gdk.Event evnt, Widget widget, string path,
Gdk.Rectangle background_area, Gdk.Rectangle cell_area, CellRendererState flags)
{
CellEditEntry text = new CellEditEntry ();
text.EditingDone += OnEditDone;
text.Text = source.Name;
text.path = path;
text.Show ();
view.EditingRow = true;
return text;
}
private void OnEditDone (object o, EventArgs args)
{
CellEditEntry edit = (CellEditEntry)o;
if (view == null) {
return;
}
view.EditingRow = false;
using (var tree_path = new TreePath (edit.path)) {
view.UpdateRow (tree_path, edit.Text);
}
}
}
}
| |
// 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.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
namespace System.Threading.Tasks.Tests.Status
{
#region Helper Classes / Enum
public class TestParameters
{
public readonly TestAction TestAction;
public MyTaskCreationOptions ChildTaskCreationOptions;
public bool CreateChildTask;
public bool IsPromise;
public TaskStatus? FinalTaskStatus;
public TaskStatus? FinalChildTaskStatus;
public TaskStatus? FinalPromiseStatus;
public TestParameters(TestAction testAction)
{
TestAction = testAction;
}
}
public enum TestAction
{
None,
CompletedTask,
CancelTask,
CancelTaskAndAcknowledge,
CancelScheduledTask,
CancelCreatedTask,
FailedTask,
FailedChildTask
}
public enum MyTaskCreationOptions
{
None = TaskCreationOptions.None,
RespectParentCancellation = -2,
AttachedToParent = TaskCreationOptions.AttachedToParent
}
public class StatusTestException : Exception { }
#endregion
public sealed class TaskStatusTest
{
#region Private Fields
private Task _task;
private Task _childTask;
private TaskCompletionSource<int> _promise;
private CancellationToken _childTaskToken;
private readonly MyTaskCreationOptions _childCreationOptions;
private readonly bool _createChildTask;
private readonly bool _isPromise;
private TaskStatus? _finalTaskStatus;
private TaskStatus? _finalChildTaskStatus;
private TaskStatus? _finalPromiseStatus;
private volatile TestAction _testAction;
private readonly ManualResetEventSlim _mre;
private readonly CancellationTokenSource _taskCts;
#endregion
public TaskStatusTest(TestParameters parameters)
{
_testAction = parameters.TestAction;
_childCreationOptions = parameters.ChildTaskCreationOptions;
_createChildTask = parameters.CreateChildTask;
_isPromise = parameters.IsPromise;
_finalTaskStatus = parameters.FinalTaskStatus;
_finalChildTaskStatus = parameters.FinalChildTaskStatus;
_finalPromiseStatus = parameters.FinalPromiseStatus;
_mre = new ManualResetEventSlim(false);
_taskCts = new CancellationTokenSource();
_childTaskToken = new CancellationToken(false);
}
internal void RealRun()
{
if (_isPromise)
{
_promise = new TaskCompletionSource<int>();
}
else
{
_task = new Task(TaskRun, _taskCts.Token);
}
if (_testAction != TestAction.None)
{
try
{
bool executeTask = false;
if (_isPromise)
{
switch (_testAction)
{
case TestAction.CompletedTask:
_promise.SetResult(1);
break;
case TestAction.FailedTask:
_promise.SetException(new StatusTestException());
break;
}
}
else
{
if (_testAction == TestAction.CancelScheduledTask)
{
CancelWaitingToRunTaskScheduler scheduler = new CancelWaitingToRunTaskScheduler();
CancellationTokenSource cts = new CancellationTokenSource();
scheduler.Cancellation = cts;
// Replace _task with a task that has a cutoms scheduler
_task = Task.Factory.StartNew(() => { }, cts.Token, TaskCreationOptions.None, scheduler);
try { _task.GetAwaiter().GetResult(); }
catch (Exception ex)
{
if (ex is OperationCanceledException)
Debug.WriteLine("OperationCanceledException Exception was thrown as expected");
else
Assert.True(false, string.Format("Unexpected exception was thrown: \n{0}", ex.ToString()));
}
}
else if (_testAction == TestAction.CancelCreatedTask)
{
_taskCts.Cancel();
}
else //When the TestAction is CompletedTask and IsPromise is false, the code will reach this point
{
executeTask = true;
_task.Start();
}
}
if (_task != null && executeTask)
{
_mre.Wait();
//
// Current Task status is WaitingForChildrenToComplete if Task didn't Cancel/Faulted and Child was created
// without Detached options and current status of the child isn't RanToCompletion or Faulted yet
//
Task.Delay(100).Wait();
if (_createChildTask &&
_childTask != null &&
_testAction != TestAction.CancelTask &&
_testAction != TestAction.CancelTaskAndAcknowledge &&
_testAction != TestAction.FailedTask &&
_childCreationOptions == MyTaskCreationOptions.AttachedToParent &&
_childTask.Status != TaskStatus.RanToCompletion &&
_childTask.Status != TaskStatus.Faulted)
{
//we may have reach this point too soon, let's keep spinning until the status changes.
while (_task.Status == TaskStatus.Running)
;
//
// If we're still waiting for children our Status should reflect so
//
if (_task.Status != TaskStatus.WaitingForChildrenToComplete)
{
Assert.True(false, string.Format("Expecting currrent Task status to be WaitingForChildren but getting {0}", _task.Status.ToString()));
}
}
_task.Wait();
}
}
catch (AggregateException exp)
{
if ((_testAction == TestAction.CancelTaskAndAcknowledge || _testAction == TestAction.CancelScheduledTask || _testAction == TestAction.CancelCreatedTask) &&
exp.Flatten().InnerException.GetType() == typeof(TaskCanceledException))
{
Debug.WriteLine("TaskCanceledException Exception was thrown as expected");
}
else if ((_testAction == TestAction.FailedTask || _testAction == TestAction.FailedChildTask) && _task.IsFaulted &&
exp.Flatten().InnerException.GetType() == typeof(StatusTestException))
{
Debug.WriteLine("StatusTestException Exception was thrown as expected");
}
else
{
Assert.True(false, string.Format("Unexpected exception was thrown: \n{0}", exp.ToString()));
}
}
try
{
//
// Need to wait for Children task if it was created with Default option (Detached by default),
// or current task was either canceled or failed
//
if (_createChildTask &&
(_childCreationOptions == MyTaskCreationOptions.None ||
_testAction == TestAction.CancelTask ||
_testAction == TestAction.CancelTaskAndAcknowledge ||
_testAction == TestAction.FailedTask))
{
_childTask.Wait();
}
}
catch (AggregateException exp)
{
if (((_testAction == TestAction.CancelTask || _testAction == TestAction.CancelTaskAndAcknowledge) &&
_childCreationOptions == MyTaskCreationOptions.RespectParentCancellation) &&
exp.Flatten().InnerException.GetType() == typeof(TaskCanceledException))
{
Debug.WriteLine("TaskCanceledException Exception was thrown as expected");
}
else if (_testAction == TestAction.FailedChildTask && _childTask.IsFaulted &&
exp.Flatten().InnerException.GetType() == typeof(StatusTestException))
{
Debug.WriteLine("StatusTestException Exception was thrown as expected");
}
else
{
Assert.True(false, string.Format("Unexpected exception was thrown: \n{0}", exp.ToString()));
}
}
}
//
// Verification
//
if (_finalTaskStatus != null && _finalTaskStatus.Value != _task.Status)
{
Assert.True(false, string.Format("Expecting Task final Status to be {0}, while getting {1}", _finalTaskStatus.Value, _task.Status));
}
if (_finalChildTaskStatus != null && _finalChildTaskStatus.Value != _childTask.Status)
{
Assert.True(false, string.Format("Expecting Child Task final Status to be {0}, while getting {1}", _finalChildTaskStatus.Value, _childTask.Status));
}
if (_finalPromiseStatus != null && _finalPromiseStatus.Value != _promise.Task.Status)
{
Assert.True(false, string.Format("Expecting Promise Status to be {0}, while getting {1}", _finalPromiseStatus.Value, _promise.Task.Status));
}
//
// Extra verifications for Cancel Task
//
if (_task != null && _task.Status == TaskStatus.Canceled && _task.IsCanceled != true)
{
Assert.True(false, string.Format("Task final Status is Canceled, expecting IsCanceled property to be True as well"));
}
if (_childTask != null && _childTask.Status == TaskStatus.Canceled && _childTask.IsCanceled != true)
{
Assert.True(false, string.Format("Child Task final Status is Canceled, expecting IsCanceled property to be True as well"));
}
//
// Extra verification for faulted Promise
//
if (_isPromise && _testAction == TestAction.FailedTask)
{
//
// If promise with Exception, read the exception so we don't
// crash on Finalizer
//
AggregateException exp = _promise.Task.Exception;
if (!_promise.Task.IsFaulted || exp == null)
{
Assert.True(false, string.Format("No Exception found on promise"));
}
else if (exp.Flatten().InnerException.GetType() == typeof(StatusTestException))
{
Debug.WriteLine("StatusTestException Exception was thrown as expected");
}
else
{
Assert.True(false, string.Format("Exception on promise has mismatched type, expecting StatusTestException, actual: {0}", exp.Flatten().InnerException.GetType()));
}
}
}
private void TaskRun()
{
try
{
if (_createChildTask)
{
TaskCreationOptions childTCO = (TaskCreationOptions)(int)_childCreationOptions;
//
// Pass the same token used by parent to child Task to simulate RespectParentCancellation
//
if (_childCreationOptions == MyTaskCreationOptions.RespectParentCancellation)
{
_childTaskToken = _taskCts.Token;
childTCO = TaskCreationOptions.AttachedToParent;
}
_childTask = new Task(ChildTaskRun, null, _childTaskToken, childTCO);
if (_childTask.Status != TaskStatus.Created)
{
Assert.True(false, string.Format("Expecting Child Task status to be Created while getting {0}", _childTask.Status.ToString()));
}
if (_testAction != TestAction.CancelTask && _testAction != TestAction.CancelTaskAndAcknowledge)
{
//
// if cancel action, start the child task after calling Cancel()
//
_childTask.Start();
}
}
if (_task.Status != TaskStatus.Running)
{
Assert.True(false, string.Format("Expecting Current Task status to be Running while getting {0}", _task.Status.ToString()));
}
switch (_testAction)
{
case TestAction.CancelTask:
if (_createChildTask)
{
_childTask.Start();
}
_taskCts.Cancel();
break;
case TestAction.CancelTaskAndAcknowledge:
if (_createChildTask)
{
_childTask.Start();
}
_taskCts.Cancel();
if (_taskCts.Token.IsCancellationRequested)
{
throw new OperationCanceledException(_taskCts.Token);
}
break;
case TestAction.FailedTask:
throw new StatusTestException();
}
}
finally
{
_mre.Set();
}
return;
}
private void ChildTaskRun(object o)
{
if (_childTask.Status != TaskStatus.Running)
{
Assert.True(false, string.Format("Expecting Child Task status to be Running while getting {0}", _childTask.Status.ToString()));
}
switch (_testAction)
{
case TestAction.FailedChildTask:
throw new StatusTestException();
}
//
// Sleep for 5 sec to simulate long running child task
//
Task t = Task.Delay(5000);
t.Wait();
if (_childTaskToken.IsCancellationRequested)
{
throw new OperationCanceledException(_childTaskToken);
}
return;
}
}
// Custom task scheduler that allows a task to be cancelled before queuing it
internal class CancelWaitingToRunTaskScheduler : TaskScheduler
{
public CancellationTokenSource Cancellation;
protected override void QueueTask(Task task)
{
Cancellation.Cancel();
TryExecuteTask(task);
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued) { return false; }
protected override IEnumerable<Task> GetScheduledTasks() { return null; }
}
public sealed class TaskStatusTests
{
[Fact]
public static void TaskStatus0()
{
TestParameters parameters = new TestParameters(TestAction.None)
{
FinalTaskStatus = TaskStatus.Created,
};
TaskStatusTest test = new TaskStatusTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskStatus1()
{
TestParameters parameters = new TestParameters(TestAction.None)
{
IsPromise = true,
FinalPromiseStatus = TaskStatus.WaitingForActivation,
};
TaskStatusTest test = new TaskStatusTest(parameters);
test.RealRun();
}
[Fact]
[OuterLoop]
public static void TaskStatus2()
{
TestParameters parameters = new TestParameters(TestAction.CompletedTask)
{
FinalTaskStatus = TaskStatus.RanToCompletion,
};
TaskStatusTest test = new TaskStatusTest(parameters);
test.RealRun();
}
[Fact]
[OuterLoop]
public static void TaskStatus3()
{
TestParameters parameters = new TestParameters(TestAction.CompletedTask)
{
ChildTaskCreationOptions = MyTaskCreationOptions.AttachedToParent,
CreateChildTask = true,
FinalTaskStatus = TaskStatus.RanToCompletion,
FinalChildTaskStatus = TaskStatus.RanToCompletion,
};
TaskStatusTest test = new TaskStatusTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskStatus4()
{
TestParameters parameters = new TestParameters(TestAction.CompletedTask)
{
IsPromise = true,
FinalPromiseStatus = TaskStatus.RanToCompletion,
};
TaskStatusTest test = new TaskStatusTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskStatus5()
{
TestParameters parameters = new TestParameters(TestAction.FailedTask)
{
IsPromise = true,
FinalPromiseStatus = TaskStatus.Faulted,
};
TaskStatusTest test = new TaskStatusTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskStatus6()
{
TestParameters parameters = new TestParameters(TestAction.CancelCreatedTask)
{
FinalTaskStatus = TaskStatus.Canceled,
};
TaskStatusTest test = new TaskStatusTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskStatus7()
{
TestParameters parameters = new TestParameters(TestAction.CancelScheduledTask)
{
FinalTaskStatus = TaskStatus.Canceled,
};
TaskStatusTest test = new TaskStatusTest(parameters);
test.RealRun();
}
[Fact]
[OuterLoop]
public static void TaskStatus8()
{
TestParameters parameters = new TestParameters(TestAction.CancelTask)
{
FinalTaskStatus = TaskStatus.RanToCompletion,
};
TaskStatusTest test = new TaskStatusTest(parameters);
test.RealRun();
}
[Fact]
[OuterLoop]
public static void TaskStatus9()
{
TestParameters parameters = new TestParameters(TestAction.CancelTask)
{
ChildTaskCreationOptions = MyTaskCreationOptions.AttachedToParent,
CreateChildTask = true,
FinalTaskStatus = TaskStatus.RanToCompletion,
FinalChildTaskStatus = TaskStatus.RanToCompletion,
};
TaskStatusTest test = new TaskStatusTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskStatus10()
{
TestParameters parameters = new TestParameters(TestAction.CancelTask)
{
ChildTaskCreationOptions = MyTaskCreationOptions.RespectParentCancellation,
CreateChildTask = true,
FinalTaskStatus = TaskStatus.RanToCompletion,
FinalChildTaskStatus = TaskStatus.Canceled,
};
TaskStatusTest test = new TaskStatusTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskStatus11()
{
TestParameters parameters = new TestParameters(TestAction.FailedTask)
{
FinalTaskStatus = TaskStatus.Faulted,
};
TaskStatusTest test = new TaskStatusTest(parameters);
test.RealRun();
}
[Fact]
[OuterLoop]
public static void TaskStatus12()
{
TestParameters parameters = new TestParameters(TestAction.FailedTask)
{
ChildTaskCreationOptions = MyTaskCreationOptions.AttachedToParent,
CreateChildTask = true,
FinalTaskStatus = TaskStatus.Faulted,
FinalChildTaskStatus = TaskStatus.RanToCompletion,
};
TaskStatusTest test = new TaskStatusTest(parameters);
test.RealRun();
}
[Fact]
[OuterLoop]
public static void TaskStatus13()
{
TestParameters parameters = new TestParameters(TestAction.FailedTask)
{
CreateChildTask = true,
FinalTaskStatus = TaskStatus.Faulted,
FinalChildTaskStatus = TaskStatus.RanToCompletion,
};
TaskStatusTest test = new TaskStatusTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskStatus14()
{
TestParameters parameters = new TestParameters(TestAction.FailedChildTask)
{
ChildTaskCreationOptions = MyTaskCreationOptions.AttachedToParent,
CreateChildTask = true,
FinalTaskStatus = TaskStatus.Faulted,
FinalChildTaskStatus = TaskStatus.Faulted,
};
TaskStatusTest test = new TaskStatusTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskStatus15()
{
TestParameters parameters = new TestParameters(TestAction.FailedChildTask)
{
CreateChildTask = true,
FinalTaskStatus = TaskStatus.RanToCompletion,
FinalChildTaskStatus = TaskStatus.Faulted,
};
TaskStatusTest test = new TaskStatusTest(parameters);
test.RealRun();
}
[Fact]
[OuterLoop]
public static void TaskStatus16()
{
TestParameters parameters = new TestParameters(TestAction.CancelTaskAndAcknowledge)
{
ChildTaskCreationOptions = MyTaskCreationOptions.AttachedToParent,
CreateChildTask = true,
FinalTaskStatus = TaskStatus.Canceled,
FinalChildTaskStatus = TaskStatus.RanToCompletion,
};
TaskStatusTest test = new TaskStatusTest(parameters);
test.RealRun();
}
[Fact]
public static void TaskStatus17()
{
TestParameters parameters = new TestParameters(TestAction.CancelTaskAndAcknowledge)
{
ChildTaskCreationOptions = MyTaskCreationOptions.RespectParentCancellation,
CreateChildTask = true,
FinalTaskStatus = TaskStatus.Canceled,
FinalChildTaskStatus = TaskStatus.Canceled,
};
TaskStatusTest test = new TaskStatusTest(parameters);
test.RealRun();
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="HttpResponseInternalWrapper.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Web {
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Web.Caching;
internal sealed class HttpResponseInternalWrapper : HttpResponseInternalBase {
private HttpResponse _httpResponse;
public HttpResponseInternalWrapper(HttpResponse httpResponse) {
Debug.Assert(httpResponse != null);
_httpResponse = httpResponse;
}
public override HttpCachePolicyBase Cache {
get {
return new HttpCachePolicyWrapper(_httpResponse.Cache);
}
}
public override string ContentType {
get {
return _httpResponse.ContentType;
}
set {
_httpResponse.ContentType = value;
}
}
public override Stream Filter {
get {
return _httpResponse.Filter;
}
set {
_httpResponse.Filter = value;
}
}
public override TextWriter Output {
get {
return _httpResponse.Output;
}
}
public override void Clear() {
_httpResponse.Clear();
}
public override void End() {
_httpResponse.End();
}
public override void Write(string s) {
_httpResponse.Write(s);
}
public override bool Buffer {
get {
return _httpResponse.Buffer;
}
set {
_httpResponse.Buffer = value;
}
}
public override bool BufferOutput {
get {
return _httpResponse.BufferOutput;
}
set {
_httpResponse.BufferOutput = value;
}
}
public override string CacheControl {
get {
return _httpResponse.CacheControl;
}
set {
_httpResponse.CacheControl = value;
}
}
public override string Charset {
get {
return _httpResponse.Charset;
}
set {
_httpResponse.Charset = value;
}
}
public override Encoding ContentEncoding {
get {
return _httpResponse.ContentEncoding;
}
set {
_httpResponse.ContentEncoding = value;
}
}
public override HttpCookieCollection Cookies {
get {
return _httpResponse.Cookies;
}
}
public override int Expires {
get {
return _httpResponse.Expires;
}
set {
_httpResponse.Expires = value;
}
}
public override DateTime ExpiresAbsolute {
get {
return _httpResponse.ExpiresAbsolute;
}
set {
_httpResponse.ExpiresAbsolute = value;
}
}
public override NameValueCollection Headers {
get {
return _httpResponse.Headers;
}
}
public override Encoding HeaderEncoding {
get {
return _httpResponse.HeaderEncoding;
}
set {
_httpResponse.HeaderEncoding = value;
}
}
public override bool IsClientConnected {
get {
return _httpResponse.IsClientConnected;
}
}
public override bool IsRequestBeingRedirected {
get {
return _httpResponse.IsRequestBeingRedirected;
}
}
public override string RedirectLocation {
get {
return _httpResponse.RedirectLocation;
}
set {
_httpResponse.RedirectLocation = value;
}
}
public override string Status {
get {
return _httpResponse.Status;
}
set {
_httpResponse.Status = value;
}
}
public override int StatusCode {
get {
return _httpResponse.StatusCode;
}
set {
_httpResponse.StatusCode = value;
}
}
public override string StatusDescription {
get {
return _httpResponse.StatusDescription;
}
set {
_httpResponse.StatusDescription = value;
}
}
public override int SubStatusCode {
get {
return _httpResponse.SubStatusCode;
}
set {
_httpResponse.SubStatusCode = value;
}
}
public override bool SuppressContent {
get {
return _httpResponse.SuppressContent;
}
set {
_httpResponse.SuppressContent = value;
}
}
public override bool TrySkipIisCustomErrors {
get {
return _httpResponse.TrySkipIisCustomErrors;
}
set {
_httpResponse.TrySkipIisCustomErrors = value;
}
}
public override void AddCacheItemDependency(string cacheKey) {
_httpResponse.AddCacheItemDependency(cacheKey);
}
public override void AddCacheItemDependencies(ArrayList cacheKeys) {
_httpResponse.AddCacheItemDependencies(cacheKeys);
}
public override void AddCacheItemDependencies(string[] cacheKeys) {
_httpResponse.AddCacheItemDependencies(cacheKeys);
}
public override void AddCacheDependency(params CacheDependency[] dependencies) {
_httpResponse.AddCacheDependency(dependencies);
}
public override void AddFileDependency(string filename) {
_httpResponse.AddFileDependency(filename);
}
public override void AddFileDependencies(ArrayList filenames) {
_httpResponse.AddFileDependencies(filenames);
}
public override void AddFileDependencies(string[] filenames) {
_httpResponse.AddFileDependencies(filenames);
}
public override void AppendCookie(HttpCookie cookie) {
_httpResponse.AppendCookie(cookie);
}
public override void AppendHeader(string name, string value) {
_httpResponse.AppendHeader(name, value);
}
public override void AppendToLog(string param) {
_httpResponse.AppendToLog(param);
}
public override string ApplyAppPathModifier(string virtualPath) {
return _httpResponse.ApplyAppPathModifier(virtualPath);
}
public override void BinaryWrite(byte[] buffer) {
_httpResponse.BinaryWrite(buffer);
}
public override void ClearContent() {
_httpResponse.ClearContent();
}
public override void ClearHeaders() {
_httpResponse.ClearHeaders();
}
public override void DisableKernelCache() {
_httpResponse.DisableKernelCache();
}
public override void Flush() {
_httpResponse.Flush();
}
public override void Pics(string value) {
_httpResponse.Pics(value);
}
public override void Redirect(string url) {
_httpResponse.Redirect(url);
}
public override void Redirect(string url, bool endResponse) {
_httpResponse.Redirect(url, endResponse);
}
public override void SetCookie(HttpCookie cookie) {
_httpResponse.SetCookie(cookie);
}
public override TextWriter SwitchWriter(TextWriter writer) {
return _httpResponse.SwitchWriter(writer);
}
public override void TransmitFile(string filename) {
_httpResponse.TransmitFile(filename);
}
public override void TransmitFile(string filename, long offset, long length) {
_httpResponse.TransmitFile(filename, offset, length);
}
public override void Write(char[] buffer, int index, int count) {
_httpResponse.Write(buffer, index, count);
}
public override void Write(object obj) {
_httpResponse.Write(obj);
}
public override void WriteFile(string filename) {
_httpResponse.WriteFile(filename);
}
public override void WriteFile(string filename, bool readIntoMemory) {
_httpResponse.WriteFile(filename, readIntoMemory);
}
public override void WriteFile(string filename, long offset, long size) {
_httpResponse.WriteFile(filename, offset, size);
}
public override void WriteFile(IntPtr fileHandle, long offset, long size) {
_httpResponse.WriteFile(fileHandle, offset, size);
}
public override void WriteSubstitution(HttpResponseSubstitutionCallback callback) {
_httpResponse.WriteSubstitution(callback);
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Globalization;
using System.IO;
using System.Linq;
namespace QuantConnect.Data.Custom
{
/// <summary>
/// FXCM Real FOREX Volume and Transaction data from its clients base, available for the following pairs:
/// - EURUSD, USDJPY, GBPUSD, USDCHF, EURCHF, AUDUSD, USDCAD,
/// NZDUSD, EURGBP, EURJPY, GBPJPY, EURAUD, EURCAD, AUDJPY
/// FXCM only provides support for FX symbols which produced over 110 million average daily volume (ADV) during 2013.
/// This limit is imposed to ensure we do not highlight low volume/low ticket symbols in addition to other financial
/// reporting concerns.
/// </summary>
/// <seealso cref="QuantConnect.Data.BaseData" />
public class FxcmVolume : BaseData
{
/// <summary>
/// Auxiliary enum used to map the pair symbol into FXCM request code.
/// </summary>
private enum FxcmSymbolId
{
EURUSD = 1,
USDJPY = 2,
GBPUSD = 3,
USDCHF = 4,
EURCHF = 5,
AUDUSD = 6,
USDCAD = 7,
NZDUSD = 8,
EURGBP = 9,
EURJPY = 10,
GBPJPY = 11,
EURAUD = 14,
EURCAD = 15,
AUDJPY = 17
}
/// <summary>
/// The request base URL.
/// </summary>
private readonly string _baseUrl = " http://marketsummary2.fxcorporate.com/ssisa/servlet?RT=SSI";
/// <summary>
/// FXCM session id.
/// </summary>
private readonly string _sid = "quantconnect";
/// <summary>
/// The columns index which should be added to obtain the transactions.
/// </summary>
private readonly long[] _transactionsIdx = { 27, 29, 31, 33 };
/// <summary>
/// Integer representing client version.
/// </summary>
private readonly int _ver = 1;
/// <summary>
/// The columns index which should be added to obtain the volume.
/// </summary>
private readonly int[] _volumeIdx = { 26, 28, 30, 32 };
/// <summary>
/// Sum of opening and closing Transactions for the entire time interval.
/// </summary>
/// <value>
/// The transactions.
/// </value>
public int Transactions { get; set; }
/// <summary>
/// Sum of opening and closing Volume for the entire time interval.
/// The volume measured in the QUOTE CURRENCY.
/// </summary>
/// <remarks>Please remember to convert this data to a common currency before making comparison between different pairs.</remarks>
public long Volume { get; set; }
/// <summary>
/// Return the URL string source of the file. This will be converted to a stream
/// </summary>
/// <param name="config">Configuration object</param>
/// <param name="date">Date of this source file</param>
/// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param>
/// <returns>
/// String URL of source file.
/// </returns>
/// <exception cref="System.NotImplementedException">FOREX Volume data is not available in live mode, yet.</exception>
public override SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode)
{
var interval = GetIntervalFromResolution(config.Resolution);
var symbolId = GetFxcmIDFromSymbol(config.Symbol.Value.Split('_').First());
if (isLiveMode)
{
var source = string.Format("{0}&ver={1}&sid={2}&interval={3}&offerID={4}", _baseUrl, _ver, _sid,
interval, symbolId);
return new SubscriptionDataSource(source, SubscriptionTransportMedium.Rest, FileFormat.Csv);
}
else
{
var source = GenerateZipFilePath(config, date);
return new SubscriptionDataSource(source, SubscriptionTransportMedium.LocalFile);
}
}
/// <summary>
/// Reader converts each line of the data source into BaseData objects. Each data type creates its own factory method,
/// and returns a new instance of the object
/// each time it is called. The returned object is assumed to be time stamped in the config.ExchangeTimeZone.
/// </summary>
/// <param name="config">Subscription data config setup object</param>
/// <param name="line">Line of the source document</param>
/// <param name="date">Date of the requested data</param>
/// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param>
/// <returns>
/// Instance of the T:BaseData object generated by this line of the CSV
/// </returns>
public override BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode)
{
var fxcmVolume = new FxcmVolume { DataType = MarketDataType.Base, Symbol = config.Symbol };
if (isLiveMode)
{
try
{
var obs = line.Split('\n')[2].Split(';');
var stringDate = obs[0].Substring(startIndex: 3);
fxcmVolume.Time = DateTime.ParseExact(stringDate, "yyyyMMddHHmm", DateTimeFormatInfo.InvariantInfo);
fxcmVolume.Volume = _volumeIdx.Select(x => long.Parse(obs[x])).Sum();
fxcmVolume.Transactions = _transactionsIdx.Select(x => int.Parse(obs[x])).Sum();
fxcmVolume.Value = fxcmVolume.Volume;
}
catch (Exception exception)
{
Logging.Log.Error($"Invalid data. Line: {line}. Exception: {exception.Message}");
return null;
}
}
else
{
var obs = line.Split(',');
if (config.Resolution == Resolution.Minute)
{
fxcmVolume.Time = date.Date.AddMilliseconds(int.Parse(obs[0]));
}
else
{
fxcmVolume.Time = DateTime.ParseExact(obs[0], "yyyyMMdd HH:mm", CultureInfo.InvariantCulture);
}
fxcmVolume.Volume = long.Parse(obs[1]);
fxcmVolume.Transactions = int.Parse(obs[2]);
fxcmVolume.Value = fxcmVolume.Volume;
}
return fxcmVolume;
}
private static string GenerateZipFilePath(SubscriptionDataConfig config, DateTime date)
{
var source = Path.Combine(new[] { Globals.DataFolder, "forex", "fxcm", config.Resolution.ToLower() });
string filename;
var symbol = config.Symbol.Value.Split('_').First().ToLower();
if (config.Resolution == Resolution.Minute)
{
filename = string.Format("{0:yyyyMMdd}_volume.zip", date);
source = Path.Combine(source, symbol, filename);
}
else
{
filename = string.Format("{0}_volume.zip", symbol);
source = Path.Combine(source, filename);
}
return source;
}
/// <summary>
/// Gets the FXCM identifier from a FOREX pair ticker.
/// </summary>
/// <param name="ticker">The pair ticker.</param>
/// <returns></returns>
/// <exception cref="System.ArgumentException">Volume data is not available for the selected ticker. - ticker</exception>
private int GetFxcmIDFromSymbol(string ticker)
{
int symbolId;
try
{
symbolId = (int)Enum.Parse(typeof(FxcmSymbolId), ticker);
}
catch (ArgumentException)
{
throw new ArgumentOutOfRangeException(nameof(ticker), ticker,
"Volume data is not available for the selected ticker.");
}
return symbolId;
}
/// <summary>
/// Gets the string interval representation from the resolution.
/// </summary>
/// <param name="resolution">The requested resolution.</param>
/// <returns></returns>
/// <exception cref="System.ArgumentOutOfRangeException">
/// resolution - tick or second resolution are not supported for Forex
/// Volume.
/// </exception>
private string GetIntervalFromResolution(Resolution resolution)
{
string interval;
switch (resolution)
{
case Resolution.Minute:
interval = "M1";
break;
case Resolution.Hour:
interval = "H1";
break;
case Resolution.Daily:
interval = "D1";
break;
default:
throw new ArgumentOutOfRangeException(nameof(resolution), resolution,
"Tick or second resolution are not supported for Forex Volume. Available resolutions are Minute, Hour and Daily.");
}
return interval;
}
}
}
| |
#define CLIENT6017
using System;
using Server;
using Server.Gumps;
using Server.Network;
using Server.Mobiles;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using Server.Targeting;
using Server.Engines.PartySystem;
using System.Data;
using System.Xml;
using Server.Engines.XmlSpawner2;
/*
** XmlQuestHolder class
**
**
** Version 1.0
** updated 9/17/04
** - based on the XmlQuestToken class, but derived from the Container instead of Item class in order to support reward holding and display
*/
namespace Server.Items
{
public abstract class XmlQuestHolder : Container, IXmlQuest
{
// public const PlayerFlag CarriedXmlQuestFlag = (PlayerFlag)0x00100000;
private double m_ExpirationDuration;
private DateTime m_TimeCreated;
private string m_Objective1;
private string m_Objective2;
private string m_Objective3;
private string m_Objective4;
private string m_Objective5;
private string m_Description1;
private string m_Description2;
private string m_Description3;
private string m_Description4;
private string m_Description5;
private bool m_Completed1 = false;
private bool m_Completed2 = false;
private bool m_Completed3 = false;
private bool m_Completed4 = false;
private bool m_Completed5 = false;
private string m_State1;
private string m_State2;
private string m_State3;
private string m_State4;
private string m_State5;
private bool m_PartyEnabled = false;
private int m_PartyRange = -1;
private string m_ConfigFile;
private string m_NoteString;
private string m_TitleString;
private string m_RewardString;
private string m_AttachmentString;
private PlayerMobile m_Owner;
private string m_SkillTrigger = null;
private bool m_Repeatable = true;
private TimeSpan m_NextRepeatable;
private Item m_RewardItem;
private XmlAttachment m_RewardAttachment;
private int m_RewardAttachmentSerialNumber;
private bool m_AutoReward = false;
private bool m_CanSeeReward = true;
private bool m_PlayerMade = false;
private PlayerMobile m_Creator;
private Container m_ReturnContainer;
private string m_status_str;
private int m_QuestDifficulty = 1;
public static int JournalNotifyColor = 0;
public static int JournalEchoColor = 6;
public XmlQuestHolder(Serial serial)
: base(serial)
{
}
public XmlQuestHolder()
: this(3643)
{
}
public XmlQuestHolder(int itemID)
: base(itemID)
{
Weight = 0;
Hue = 500;
//LootType = LootType.Blessed;
TimeCreated = DateTime.Now;
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)6); // version
// version 6
if (m_Journal == null || m_Journal.Count == 0)
{
writer.Write((int)0);
}
else
{
writer.Write((int)m_Journal.Count);
foreach (XmlQuest.JournalEntry e in m_Journal)
{
writer.Write(e.EntryID);
writer.Write(e.EntryText);
}
}
// version 5
writer.Write(m_Repeatable);
// version 4
writer.Write(m_QuestDifficulty);
// version 3
writer.Write(m_AttachmentString);
// version 2
writer.Write(m_NextRepeatable);
// version 1
if (m_RewardAttachment != null)
writer.Write(m_RewardAttachment.Serial.Value);
else
writer.Write((int)0);
// version 0
writer.Write(m_ReturnContainer);
writer.Write(m_RewardItem);
writer.Write(m_AutoReward);
writer.Write(m_CanSeeReward);
writer.Write(m_PlayerMade);
writer.Write(m_Creator);
writer.Write(m_Description1);
writer.Write(m_Description2);
writer.Write(m_Description3);
writer.Write(m_Description4);
writer.Write(m_Description5);
writer.Write(m_Owner);
writer.Write(m_RewardString);
writer.Write(m_ConfigFile);
writer.Write(m_NoteString); // moved from the QuestNote class
writer.Write(m_TitleString); // moved from the QuestNote class
writer.Write(m_PartyEnabled);
writer.Write(m_PartyRange);
writer.Write(m_State1);
writer.Write(m_State2);
writer.Write(m_State3);
writer.Write(m_State4);
writer.Write(m_State5);
writer.Write(m_ExpirationDuration);
writer.Write(m_TimeCreated);
writer.Write(m_Objective1);
writer.Write(m_Objective2);
writer.Write(m_Objective3);
writer.Write(m_Objective4);
writer.Write(m_Objective5);
writer.Write(m_Completed1);
writer.Write(m_Completed2);
writer.Write(m_Completed3);
writer.Write(m_Completed4);
writer.Write(m_Completed5);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
switch (version)
{
case 6:
{
int nentries = reader.ReadInt();
if (nentries > 0)
{
m_Journal = new ArrayList();
for (int i = 0; i < nentries; i++)
{
string entryID = reader.ReadString();
string entryText = reader.ReadString();
m_Journal.Add(new XmlQuest.JournalEntry(entryID, entryText));
}
}
goto case 5;
}
case 5:
{
m_Repeatable = reader.ReadBool();
goto case 4;
}
case 4:
{
m_QuestDifficulty = reader.ReadInt();
goto case 3;
}
case 3:
{
m_AttachmentString = reader.ReadString();
goto case 2;
}
case 2:
{
m_NextRepeatable = reader.ReadTimeSpan();
goto case 1;
}
case 1:
{
m_RewardAttachmentSerialNumber = reader.ReadInt();
goto case 0;
}
case 0:
{
this.m_ReturnContainer = (Container)reader.ReadItem();
this.m_RewardItem = reader.ReadItem();
this.m_AutoReward = reader.ReadBool();
this.m_CanSeeReward = reader.ReadBool();
this.m_PlayerMade = reader.ReadBool();
this.m_Creator = reader.ReadMobile() as PlayerMobile;
this.m_Description1 = reader.ReadString();
this.m_Description2 = reader.ReadString();
this.m_Description3 = reader.ReadString();
this.m_Description4 = reader.ReadString();
this.m_Description5 = reader.ReadString();
this.m_Owner = reader.ReadMobile() as PlayerMobile;
this.m_RewardString = reader.ReadString();
this.m_ConfigFile = reader.ReadString();
this.m_NoteString = reader.ReadString();
this.m_TitleString = reader.ReadString();
this.m_PartyEnabled = reader.ReadBool();
this.m_PartyRange = reader.ReadInt();
this.m_State1 = reader.ReadString();
this.m_State2 = reader.ReadString();
this.m_State3 = reader.ReadString();
this.m_State4 = reader.ReadString();
this.m_State5 = reader.ReadString();
this.Expiration = reader.ReadDouble();
this.m_TimeCreated = reader.ReadDateTime();
this.m_Objective1 = reader.ReadString();
this.m_Objective2 = reader.ReadString();
this.m_Objective3 = reader.ReadString();
this.m_Objective4 = reader.ReadString();
this.m_Objective5 = reader.ReadString();
this.m_Completed1 = reader.ReadBool();
this.m_Completed2 = reader.ReadBool();
this.m_Completed3 = reader.ReadBool();
this.m_Completed4 = reader.ReadBool();
this.m_Completed5 = reader.ReadBool();
}
break;
}
}
private static Item PlaceHolderItem = null;
public static void Initialize()
{
// create a temporary placeholder item used to force allocation empty Items lists used to hold hidden rewards.
PlaceHolderItem = new Item(1);
foreach (Item item in World.Items.Values)
{
if (item is XmlQuestHolder)
{
XmlQuestHolder t = item as XmlQuestHolder;
t.UpdateWeight();
t.RestoreRewardAttachment();
}
}
// remove the temporary placeholder item
PlaceHolderItem.Delete();
}
private void HideRewards()
{
if (m_RewardItem != null)
{
// remove the item from the containers item list
if (Items.Contains(m_RewardItem))
{
Items.Remove(m_RewardItem);
}
}
}
private void UnHideRewards()
{
if (m_RewardItem == null) return;
Item tmpitem = null;
if (Items == Item.EmptyItems)
{
tmpitem = PlaceHolderItem;
if (tmpitem == null || tmpitem.Deleted)
{
tmpitem = new Item(1);
}
// need to get it to allocate a new list by adding an item
DropItem(tmpitem);
}
if (!Items.Contains(m_RewardItem))
{
m_RewardItem.Parent = this;
m_RewardItem.Map = Map;
// restore the item to the containers item list
Items.Add(m_RewardItem);
}
// remove the placeholder
if (tmpitem != null && Items.Contains(tmpitem))
{
Items.Remove(tmpitem);
tmpitem.Map = Map.Internal;
}
if (tmpitem != null && tmpitem != PlaceHolderItem)
{
tmpitem.Delete();
}
}
public override bool CheckItemUse(Mobile from, Item item)
{
if (!(item is Container))
return false;
else
return base.CheckItemUse(from, item);
}
public override void DisplayTo(Mobile to)
{
if (to == null) return;
// add the reward item back into the container list for display
UnHideRewards();
to.Send(new ContainerDisplay(this));
#if(CLIENT6017)
// add support for new client container packets
if (to.NetState != null && to.NetState.ContainerGridLines)
to.Send(new ContainerContent6017(to, this));
else
#endif
to.Send(new ContainerContent(to, this)); ;
if (ObjectPropertyList.Enabled)
{
List<Item> items = this.Items;
for (int i = 0; i < items.Count; ++i)
to.Send(((Item)items[i]).OPLPacket);
}
// move the reward item out of container to protect it from use
HideRewards();
}
public override void GetProperties(ObjectPropertyList list)
{
list.Add(Name);
if (LootType == LootType.Blessed)
{
list.Add(1038021);
}
if (PlayerMade && Owner != null && !(RootParent is PlayerVendor))
{
list.Add(1050044, "{0}\t{1}", this.TotalItems, this.TotalWeight); // ~1_COUNT~items,~2_WEIGHT~stones
}
// add any playervendor price/description information
if (RootParent is PlayerVendor)
{
((PlayerVendor)RootParent).GetChildProperties(list, this);
}
}
public override bool CheckHold(Mobile m, Item item, bool message, bool checkItems, int plusItems, int plusWeight)
{
if (m.AccessLevel == AccessLevel.Player) return false;
return base.CheckHold(m, item, message, checkItems, plusItems, plusWeight);
}
public override bool TryDropItem(Mobile from, Item dropped, bool sendFullMessage)
{
if (from.AccessLevel == AccessLevel.Player) return false;
return base.TryDropItem(from, dropped, sendFullMessage);
}
public override bool OnDragDrop(Mobile from, Item dropped)
{
return false;
}
public override bool OnDragDropInto(Mobile from, Item item, Point3D p)
{
return false;
}
public override bool CheckTarget(Mobile from, Server.Targeting.Target targ, object targeted)
{
if (from.AccessLevel == AccessLevel.Player) return false;
return true;
}
public override void OnDoubleClick(Mobile from)
{
//base.OnDoubleClick(from);
if (!(from is PlayerMobile)) return;
if (PlayerMade && (from == Creator) && (from == Owner))
{
from.SendGump(new XmlPlayerQuestGump((PlayerMobile)from, this));
}
}
public override bool OnDroppedToWorld(Mobile from, Point3D point)
{
bool returnvalue = base.OnDroppedToWorld(from, point);
from.SendGump(new XmlConfirmDeleteGump(from, this));
return false;
}
public override void OnDelete()
{
// remove any temporary quest attachments associated with this quest and quest owner
XmlQuest.RemoveTemporaryQuestObjects(Owner, Name);
base.OnDelete();
// remove any reward items that might be attached to this
ReturnReward();
// determine whether the owner needs to be flagged with a quest attachment indicating completion of this quest
QuestCompletionAttachment();
CheckOwnerFlag();
}
public override void OnItemLifted(Mobile from, Item item)
{
base.OnItemLifted(from, item);
if (from is PlayerMobile && PlayerMade && (Owner != null) && (Owner == Creator))
{
LootType = LootType.Regular;
}
else
if (from is PlayerMobile && Owner == null)
{
Owner = from as PlayerMobile;
LootType = LootType.Blessed;
// flag the owner as carrying a questtoken
Owner.SetFlag(XmlQuest.CarriedXmlQuestFlag, true);
}
}
public override void OnAdded(object target)
{
base.OnAdded(target);
if ((target != null) && target is Container)
{
// find the parent of the container
// note, the only valid additions are to the player pack or a questbook. Anything else is invalid.
// This is to avoid exploits involving storage or transfer of questtokens
// make an exception for playermade quests that can be put on playervendors
object parentOfTarget = ((Container)target).Parent;
// if this is a QuestBook then allow additions if it is in a players pack or it is a player quest
if ((parentOfTarget != null) && parentOfTarget is Container && target is XmlQuestBook)
{
parentOfTarget = ((Container)parentOfTarget).Parent;
}
// check to see if it can be added.
// allow playermade quests to be placed in playervendors or in xmlquestbooks that are in the world (supports the playerquestboards)
if (PlayerMade && (((parentOfTarget != null) && parentOfTarget is PlayerVendor) ||
((parentOfTarget == null) && target is XmlQuestBook)))
{
CheckOwnerFlag();
Owner = null;
LootType = LootType.Regular;
}
else
if ((parentOfTarget != null) && (parentOfTarget is PlayerMobile) && PlayerMade && (Owner != null) && ((Owner == Creator) || (Creator == null)))
{
// check the old owner
CheckOwnerFlag();
Owner = parentOfTarget as PlayerMobile;
// first owner will become creator by default
if (Creator == null)
Creator = Owner;
LootType = LootType.Blessed;
// flag the new owner as carrying a questtoken
Owner.SetFlag(XmlQuest.CarriedXmlQuestFlag, true);
}
else
if ((parentOfTarget != null) && (parentOfTarget is PlayerMobile))
{
if (Owner == null)
{
Owner = parentOfTarget as PlayerMobile;
LootType = LootType.Blessed;
// flag the owner as carrying a questtoken
Owner.SetFlag(XmlQuest.CarriedXmlQuestFlag, true);
}
else
if ((parentOfTarget as PlayerMobile != Owner) || (target is BankBox))
{
// tried to give it to another player or placed it in the players bankbox. try to return it to the owners pack
Owner.AddToBackpack(this);
}
}
else
{
if (Owner != null)
{
// try to return it to the owners pack
Owner.AddToBackpack(this);
}
// allow placement into containers in the world, npcs or drop on their corpses when owner is null
else
if (!(parentOfTarget is Mobile) && !(target is Corpse) && parentOfTarget != null)
{
// invalidate the token
CheckOwnerFlag();
Invalidate();
}
}
}
}
private ArrayList m_Journal;
public ArrayList Journal { get { return m_Journal; } set { m_Journal = value; } }
private static char[] colondelim = new char[1] { ':' };
public string EchoAddJournalEntry
{
set
{
// notify and echo journal text
VerboseAddJournalEntry(value, true, true);
}
}
public string NotifyAddJournalEntry
{
set
{
// notify
VerboseAddJournalEntry(value, true, false);
}
}
public string AddJournalEntry
{
set
{
// silent
VerboseAddJournalEntry(value, false, false);
}
}
private void VerboseAddJournalEntry(string entrystring, bool notify, bool echo)
{
if (entrystring == null) return;
// parse the value
string[] args = entrystring.Split(colondelim, 2);
if (args == null) return;
string entryID = null;
string entryText = null;
if (args.Length > 0)
{
entryID = args[0].Trim();
}
if (entryID == null || entryID.Length == 0) return;
if (args.Length > 1)
{
entryText = args[1].Trim();
}
// allocate a new journal if none exists
if (m_Journal == null) m_Journal = new ArrayList();
// go through the existing journal to find a matching ID
XmlQuest.JournalEntry foundEntry = null;
foreach (XmlQuest.JournalEntry e in m_Journal)
{
if (e.EntryID == entryID)
{
foundEntry = e;
break;
}
}
if (foundEntry != null)
{
// modify an existing entry
if (entryText == null || entryText.Length == 0)
{
// delete the entry
m_Journal.Remove(foundEntry);
}
else
{
// just replace the text
foundEntry.EntryText = entryText;
Mobile holder = RootParent as Mobile;
if (holder != null)
{
if (notify)
{
// notify the player holding the questholder
holder.SendMessage(JournalNotifyColor, "Journal entry '{0}' of quest '{1}' has been modified.", entryID, Name);
}
if (echo)
{
// echo the journal text to the player holding the questholder
holder.SendMessage(JournalEchoColor, "{0}", entryText);
}
}
}
}
else
{
// add a new entry
if (entryText != null && entryText.Length != 0)
{
// add the new entry
m_Journal.Add(new XmlQuest.JournalEntry(entryID, entryText));
Mobile holder = RootParent as Mobile;
if (holder != null)
{
if (notify)
{
// notify the player holding the questholder
holder.SendMessage(JournalNotifyColor, "Journal entry '{0}' has been added to quest '{1}'.", entryID, Name);
}
if (echo)
{
// echo the journal text to the player holding the questholder
holder.SendMessage(JournalEchoColor, "{0}", entryText);
}
}
}
}
}
private void QuestCompletionAttachment()
{
bool complete = IsCompleted;
// is this quest repeatable
if ((!Repeatable || NextRepeatable > TimeSpan.Zero) && complete)
{
double expiresin = Repeatable ? NextRepeatable.TotalMinutes : 0;
// then add an attachment indicating that it has already been done
XmlAttach.AttachTo(Owner, new XmlQuestAttachment(this.Name, expiresin));
}
// have quest points been enabled?
if (XmlQuest.QuestPointsEnabled && complete && !PlayerMade)
{
XmlQuestPoints.GiveQuestPoints(Owner, this);
}
}
private void PackItem(Item item)
{
if (item != null)
{
DropItem(item);
}
PackItemsMovable(this, false);
// make sure the weight and gold of the questtoken is updated to reflect the weight of added rewards in playermade quests to avoid
// exploits where quests are used as zero weight containers
UpdateWeight();
}
private void CalculateWeight(Item target)
{
if (target is Container)
{
int gold = 0;
int weight = 0;
int nitems = 0;
foreach (Item i in ((Container)target).Items)
{
// make sure gold amount is consistent with totalgold
if (i is Gold)
{
UpdateTotal(i, TotalType.Gold, i.Amount);
}
if (i is Container)
{
CalculateWeight(i);
weight += i.TotalWeight + (int)i.Weight;
gold += i.TotalGold;
nitems += i.TotalItems + 1;
}
else
{
weight += (int)(i.Weight * i.Amount);
gold += i.TotalGold;
nitems += 1;
}
}
UpdateTotal((Container)target, TotalType.Weight, weight);
UpdateTotal((Container)target, TotalType.Gold, gold);
UpdateTotal((Container)target, TotalType.Items, nitems);
}
}
private void UpdateWeight()
{
// decide whether to hide the weight, gold, and number of the reward from the totals calculation
if (PlayerMade)
{
UnHideRewards();
}
else
{
HideRewards();
}
// update the container totals
UpdateTotals();
// and the parent totals
if (RootParent is Mobile)
{
((Mobile)RootParent).UpdateTotals();
}
// hide the reward item
HideRewards();
}
private void ReturnReward()
{
if (m_RewardItem != null)
{
CheckRewardItem();
// if this was player made, then return the item to the creator
if (PlayerMade && (Creator != null) && !Creator.Deleted)
{
m_RewardItem.Movable = true;
// make sure all of the items in the pack are movable as well
PackItemsMovable(this, true);
bool returned = false;
if ((ReturnContainer != null) && !ReturnContainer.Deleted)
{
returned = ReturnContainer.TryDropItem(Creator, m_RewardItem, false);
//ReturnContainer.DropItem(m_RewardItem);
}
if (!returned)
{
returned = Creator.AddToBackpack(m_RewardItem);
}
if (returned)
{
Creator.SendMessage("Your reward {0} was returned from quest {1}", m_RewardItem.GetType().Name, Name);
//AddMobileWeight(Creator, m_RewardItem);
}
else
{
Creator.SendMessage("Attempted to return reward {0} from quest {1} : containers full.", m_RewardItem.GetType().Name, Name);
}
}
else
{
// just delete it
m_RewardItem.Delete();
}
m_RewardItem = null;
UpdateWeight();
}
if (m_RewardAttachment != null)
{
// delete any remaining attachments
m_RewardAttachment.Delete();
}
}
[CommandProperty(AccessLevel.GameMaster)]
public PlayerMobile Owner
{
get { return m_Owner; }
set { m_Owner = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public new string Name
{
get
{
if (PlayerMade)
{
return "PQ: " + base.Name;
}
else
{
return base.Name;
}
}
set
{
base.Name = value;
InvalidateProperties();
}
}
[CommandProperty(AccessLevel.GameMaster)]
public PlayerMobile Creator
{
get { return m_Creator; }
set { m_Creator = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public int Difficulty
{
get { return m_QuestDifficulty; }
set { m_QuestDifficulty = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public string Status
{
get { return m_status_str; }
set { m_status_str = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public string NoteString
{
get { return m_NoteString; }
set { m_NoteString = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public bool AutoReward
{
get { return m_AutoReward; }
set { m_AutoReward = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public bool CanSeeReward
{
get { return m_CanSeeReward; }
set { m_CanSeeReward = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public bool PlayerMade
{
get { return m_PlayerMade; }
set { m_PlayerMade = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public Container ReturnContainer
{
get { return m_ReturnContainer; }
set { m_ReturnContainer = value; }
}
private void PackItemsMovable(Container pack, bool canmove)
{
if (pack == null) return;
UnHideRewards();
Item[] itemlist = pack.FindItemsByType(typeof(Item), true);
if (itemlist != null)
{
for (int i = 0; i < itemlist.Length; i++)
{
itemlist[i].Movable = canmove;
}
}
}
private void RestoreRewardAttachment()
{
m_RewardAttachment = XmlAttach.FindAttachmentBySerial(m_RewardAttachmentSerialNumber);
}
public XmlAttachment RewardAttachment
{
get
{
// if the reward item is not set, and the reward string is specified, then use the reward string to construct and assign the
// reward item
// dont allow player made quests to use the rewardstring creation feature
if (m_RewardAttachment != null && m_RewardAttachment.Deleted) m_RewardAttachment = null;
if ((m_RewardAttachment == null || m_RewardAttachment.Deleted) &&
(m_AttachmentString != null) && !PlayerMade)
{
object o = XmlQuest.CreateItem(this, m_AttachmentString, out m_status_str, typeof(XmlAttachment));
if (o is Item)
{
((Item)o).Delete();
}
else
if (o is XmlAttachment)
{
m_RewardAttachment = o as XmlAttachment;
m_RewardAttachment.OwnedBy = this;
}
}
return m_RewardAttachment;
}
set
{
// get rid of any existing attachment
if (m_RewardAttachment != null && !m_RewardAttachment.Deleted)
{
m_RewardAttachment.Delete();
}
m_RewardAttachment = value;
}
}
[CommandProperty(AccessLevel.GameMaster)]
public Item RewardItem
{
get
{
// if the reward item is not set, and the reward string is specified, then use the reward string to construct and assign the
// reward item
// dont allow player made quests to use the rewardstring creation feature
if ((m_RewardItem == null || m_RewardItem.Deleted) &&
(m_RewardString != null) && !PlayerMade)
{
object o = XmlQuest.CreateItem(this, m_RewardString, out m_status_str, typeof(Item));
if (o is Item)
{
m_RewardItem = o as Item;
PackItem(m_RewardItem);
}
else
if (o is XmlAttachment)
{
((XmlAttachment)o).Delete();
}
}
return m_RewardItem;
}
set
{
// get rid of any existing reward item if it has been assigned
if (m_RewardItem != null && !m_RewardItem.Deleted)
{
ReturnReward();
}
// and assign the new item
m_RewardItem = value;
/*
// is this currently carried by a mobile?
if(m_RewardItem.RootParent != null && m_RewardItem.RootParent is Mobile)
{
// if so then remove it
((Mobile)(m_RewardItem.RootParent)).RemoveItem(m_RewardItem);
}
*/
// and put it in the pack
if (m_RewardItem != null && !m_RewardItem.Deleted)
{
PackItem(m_RewardItem);
}
}
}
[CommandProperty(AccessLevel.GameMaster)]
public string TitleString
{
get { return m_TitleString; }
set { m_TitleString = value; InvalidateProperties(); }
}
[CommandProperty(AccessLevel.GameMaster)]
public string RewardString
{
get { return m_RewardString; }
set { m_RewardString = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public string AttachmentString
{
get { return m_AttachmentString; }
set { m_AttachmentString = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public string ConfigFile
{
get { return m_ConfigFile; }
set { m_ConfigFile = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public bool LoadConfig
{
get { return false; }
set { if (value == true) LoadXmlConfig(ConfigFile); }
}
[CommandProperty(AccessLevel.GameMaster)]
public bool PartyEnabled
{
get { return m_PartyEnabled; }
set { m_PartyEnabled = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public int PartyRange
{
get { return m_PartyRange; }
set { m_PartyRange = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public string State1
{
get { return m_State1; }
set { m_State1 = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public string State2
{
get { return m_State2; }
set { m_State2 = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public string State3
{
get { return m_State3; }
set { m_State3 = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public string State4
{
get { return m_State4; }
set { m_State4 = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public string State5
{
get { return m_State5; }
set { m_State5 = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public string Description1
{
get { return m_Description1; }
set { m_Description1 = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public string Description2
{
get { return m_Description2; }
set { m_Description2 = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public string Description3
{
get { return m_Description3; }
set { m_Description3 = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public string Description4
{
get { return m_Description4; }
set { m_Description4 = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public string Description5
{
get { return m_Description5; }
set { m_Description5 = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public string Objective1
{
get { return m_Objective1; }
set { m_Objective1 = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public string Objective2
{
get { return m_Objective2; }
set { m_Objective2 = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public string Objective3
{
get { return m_Objective3; }
set { m_Objective3 = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public string Objective4
{
get { return m_Objective4; }
set { m_Objective4 = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public string Objective5
{
get { return m_Objective5; }
set { m_Objective5 = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public bool Completed1
{
get { return m_Completed1; }
set
{
m_Completed1 = value;
CheckAutoReward();
}
}
[CommandProperty(AccessLevel.GameMaster)]
public bool Completed2
{
get { return m_Completed2; }
set
{
m_Completed2 = value;
CheckAutoReward();
}
}
[CommandProperty(AccessLevel.GameMaster)]
public bool Completed3
{
get { return m_Completed3; }
set
{
m_Completed3 = value;
CheckAutoReward();
}
}
[CommandProperty(AccessLevel.GameMaster)]
public bool Completed4
{
get { return m_Completed4; }
set
{
m_Completed4 = value;
CheckAutoReward();
}
}
[CommandProperty(AccessLevel.GameMaster)]
public bool Completed5
{
get { return m_Completed5; }
set
{
m_Completed5 = value;
CheckAutoReward();
}
}
[CommandProperty(AccessLevel.GameMaster)]
public DateTime TimeCreated
{
get { return m_TimeCreated; }
set { m_TimeCreated = value; }
}
[CommandProperty(AccessLevel.GameMaster)]
public double Expiration
{
get
{
return m_ExpirationDuration;
}
set
{
// cap the max value at 100 years
if (value > 876000)
{
m_ExpirationDuration = 876000;
}
else
{
m_ExpirationDuration = value;
}
}
}
[CommandProperty(AccessLevel.GameMaster)]
public TimeSpan ExpiresIn
{
get
{
if (m_ExpirationDuration > 0)
{
// if this is a player created quest, then refresh the expiration time until it is in someone elses possession
/*
if(PlayerMade && ((Owner == Creator) || (Owner == null)))
{
m_TimeCreated = DateTime.Now;
}
*/
return (m_TimeCreated + TimeSpan.FromHours(m_ExpirationDuration) - DateTime.Now);
}
else
{
return TimeSpan.FromHours(0);
}
}
}
[CommandProperty(AccessLevel.GameMaster)]
public virtual bool IsExpired
{
get
{
if (((m_ExpirationDuration > 0) && (ExpiresIn <= TimeSpan.FromHours(0))))
{
return true;
}
else
return false;
}
}
[CommandProperty(AccessLevel.GameMaster)]
public virtual bool Repeatable
{
get
{
return m_Repeatable;
}
set
{
m_Repeatable = value;
}
}
[CommandProperty(AccessLevel.GameMaster)]
public virtual TimeSpan NextRepeatable
{
get
{
return m_NextRepeatable;
}
set
{
m_NextRepeatable = value;
}
}
[CommandProperty(AccessLevel.GameMaster)]
public virtual bool AlreadyDone
{
get
{
// look for a quest attachment with the current quest name
if (XmlAttach.FindAttachment(Owner, typeof(XmlQuestAttachment), Name) == null)
return false;
return true;
}
}
public virtual string ExpirationString
{
get
{
if (AlreadyDone)
{
return "Already done";
}
else
if (m_ExpirationDuration <= 0)
{
return "Never expires";
}
else
if (IsExpired)
{
return "Expired";
}
else
{
TimeSpan ts = ExpiresIn;
int days = (int)ts.TotalDays;
int hours = (int)(ts - TimeSpan.FromDays(days)).TotalHours;
int minutes = (int)(ts - TimeSpan.FromHours(hours)).TotalMinutes;
int seconds = (int)(ts - TimeSpan.FromMinutes(minutes)).TotalSeconds;
if (days > 0)
{
return String.Format("Expires in {0} days {1} hrs", days, hours);
}
else
if (hours > 0)
{
return String.Format("Expires in {0} hrs {1} mins", hours, minutes);
}
else
{
return String.Format("Expires in {0} mins {1} secs", minutes, seconds);
}
}
}
}
[CommandProperty(AccessLevel.GameMaster)]
public virtual bool IsValid
{
get
{
if (IsExpired)
{
// eliminate reward definitions
RewardString = null;
AttachmentString = null;
// return any reward items
ReturnReward();
return false;
}
else
if (AlreadyDone)
{
return false;
}
else
return true;
}
}
[CommandProperty(AccessLevel.GameMaster)]
public virtual bool IsCompleted
{
get
{
if (IsValid &&
(Completed1 || Objective1 == null || (Objective1.Length == 0)) &&
(Completed2 || Objective2 == null || (Objective2.Length == 0)) &&
(Completed3 || Objective3 == null || (Objective3.Length == 0)) &&
(Completed4 || Objective4 == null || (Objective4.Length == 0)) &&
(Completed5 || Objective5 == null || (Objective5.Length == 0))
)
return true;
else
return false;
}
}
public Container Pack
{
get { return this; }
}
// this is the handler for skill use
// not yet implemented, just a hook for now
public void OnSkillUse(Mobile m, Skill skill, bool success)
{
if (m == m_Owner && IsValid)
{
//m_skillTriggerActivated = false;
// do a location test for the skill use
/*
if ( !Utility.InRange( m.Location, this.Location, m_ProximityRange ) )
return;
*/
int testskill = -1;
// check the skill trigger conditions, Skillname,min,max
try
{
testskill = (int)Enum.Parse(typeof(SkillName), m_SkillTrigger);
}
catch { }
if (m_SkillTrigger != null && (int)skill.SkillName == testskill)
{
// have a skill trigger so flag it and test it
//m_skillTriggerActivated = true;
}
}
}
public bool HandlesOnSkillUse { get { return (IsValid && m_SkillTrigger != null && m_SkillTrigger.Length > 0); } }
private void CheckOwnerFlag()
{
if (Owner != null && !Owner.Deleted)
{
// need to check to see if any other questtoken items are owned
// search the Owners top level pack for an xmlquest
ArrayList list = XmlQuest.FindXmlQuest(Owner);
if (list == null || list.Count == 0)
{
// if none remain then flag the ower as having none
Owner.SetFlag(XmlQuest.CarriedXmlQuestFlag, false);
}
}
}
public virtual void Invalidate()
{
//Hue = 32;
//LootType = LootType.Regular;
if (Owner != null)
{
Owner.SendMessage(String.Format("Quest invalidated - '{0}' removed", Name));
}
this.Delete();
}
public void CheckRewardItem()
{
// go through all reward items and delete anything that is movable. This blocks any exploits where players might
// try to add items themselves
if (m_RewardItem != null && !m_RewardItem.Deleted && m_RewardItem is Container)
{
foreach (Item i in ((Container)m_RewardItem).FindItemsByType(typeof(Item), true))
{
if (i.Movable)
{
i.Delete();
}
}
}
}
public void CheckAutoReward()
{
if (!this.Deleted && AutoReward && IsCompleted && Owner != null &&
((RewardItem != null && !m_RewardItem.Deleted) || (RewardAttachment != null && !m_RewardAttachment.Deleted)))
{
if (RewardItem != null)
{
// make sure nothing has been added to the pack other than the original reward items
CheckRewardItem();
m_RewardItem.Movable = true;
// make sure all of the items in the pack are movable as well
PackItemsMovable(this, true);
Owner.AddToBackpack(m_RewardItem);
//AddMobileWeight(Owner,m_RewardItem);
m_RewardItem = null;
}
if (RewardAttachment != null)
{
Timer.DelayCall(TimeSpan.Zero, new TimerStateCallback(AttachToCallback), new object[] { Owner, m_RewardAttachment });
m_RewardAttachment = null;
}
Owner.SendMessage(String.Format("{0} completed. You receive the quest reward!", Name));
this.Delete();
}
}
public void AttachToCallback(object state)
{
object[] args = (object[])state;
XmlAttach.AttachTo(args[0], (XmlAttachment)args[1]);
}
private const string XmlTableName = "Properties";
private const string XmlDataSetName = "XmlQuestHolder";
public void LoadXmlConfig(string filename)
{
if (filename == null || filename.Length <= 0) return;
// Check if the file exists
if (System.IO.File.Exists(filename) == true)
{
FileStream fs = null;
try
{
fs = File.Open(filename, FileMode.Open, FileAccess.Read);
}
catch { }
if (fs == null)
{
Status = String.Format("Unable to open {0} for loading", filename);
return;
}
// Create the data set
DataSet ds = new DataSet(XmlDataSetName);
// Read in the file
//ds.ReadXml( e.Arguments[0].ToString() );
bool fileerror = false;
try
{
ds.ReadXml(fs);
}
catch { fileerror = true; }
// close the file
fs.Close();
if (fileerror)
{
Console.WriteLine("XmlQuestHolder: Error in XML config file '{0}'", filename);
return;
}
// Check that at least a single table was loaded
if (ds.Tables != null && ds.Tables.Count > 0)
{
if (ds.Tables[XmlTableName] != null && ds.Tables[XmlTableName].Rows.Count > 0)
{
foreach (DataRow dr in ds.Tables[XmlTableName].Rows)
{
bool valid_entry;
string strEntry = null;
bool boolEntry = true;
double doubleEntry = 0;
int intEntry = 0;
TimeSpan timespanEntry = TimeSpan.Zero;
valid_entry = true;
try { strEntry = (string)dr["Name"]; }
catch { valid_entry = false; }
if (valid_entry)
{
this.Name = strEntry;
}
valid_entry = true;
strEntry = null;
try { strEntry = (string)dr["Title"]; }
catch { valid_entry = false; }
if (valid_entry)
{
this.TitleString = strEntry;
}
valid_entry = true;
strEntry = null;
try { strEntry = (string)dr["Note"]; }
catch { valid_entry = false; }
if (valid_entry)
{
this.NoteString = strEntry;
}
valid_entry = true;
strEntry = null;
try { strEntry = (string)dr["Reward"]; }
catch { valid_entry = false; }
if (valid_entry)
{
this.RewardString = strEntry;
}
valid_entry = true;
strEntry = null;
try { strEntry = (string)dr["Attachment"]; }
catch { valid_entry = false; }
if (valid_entry)
{
this.AttachmentString = strEntry;
}
valid_entry = true;
strEntry = null;
try { strEntry = (string)dr["Objective1"]; }
catch { valid_entry = false; }
if (valid_entry)
{
this.Objective1 = strEntry;
}
valid_entry = true;
strEntry = null;
try { strEntry = (string)dr["Objective2"]; }
catch { valid_entry = false; }
if (valid_entry)
{
this.Objective2 = strEntry;
}
valid_entry = true;
strEntry = null;
try { strEntry = (string)dr["Objective3"]; }
catch { valid_entry = false; }
if (valid_entry)
{
this.Objective3 = strEntry;
}
valid_entry = true;
strEntry = null;
try { strEntry = (string)dr["Objective4"]; }
catch { valid_entry = false; }
if (valid_entry)
{
this.Objective4 = strEntry;
}
valid_entry = true;
strEntry = null;
try { strEntry = (string)dr["Objective5"]; }
catch { valid_entry = false; }
if (valid_entry)
{
this.Objective5 = strEntry;
}
valid_entry = true;
strEntry = null;
try { strEntry = (string)dr["Description1"]; }
catch { valid_entry = false; }
if (valid_entry)
{
this.Description1 = strEntry;
}
valid_entry = true;
strEntry = null;
try { strEntry = (string)dr["Description2"]; }
catch { valid_entry = false; }
if (valid_entry)
{
this.Description2 = strEntry;
}
valid_entry = true;
strEntry = null;
try { strEntry = (string)dr["Description3"]; }
catch { valid_entry = false; }
if (valid_entry)
{
this.Description3 = strEntry;
}
valid_entry = true;
strEntry = null;
try { strEntry = (string)dr["Description4"]; }
catch { valid_entry = false; }
if (valid_entry)
{
this.Description4 = strEntry;
}
valid_entry = true;
strEntry = null;
try { strEntry = (string)dr["Description5"]; }
catch { valid_entry = false; }
if (valid_entry)
{
this.Description5 = strEntry;
}
valid_entry = true;
boolEntry = false;
try { boolEntry = bool.Parse((string)dr["PartyEnabled"]); }
catch { valid_entry = false; }
if (valid_entry)
{
this.PartyEnabled = boolEntry;
}
valid_entry = true;
boolEntry = false;
try { boolEntry = bool.Parse((string)dr["AutoReward"]); }
catch { valid_entry = false; }
if (valid_entry)
{
this.AutoReward = boolEntry;
}
valid_entry = true;
boolEntry = true;
try { boolEntry = bool.Parse((string)dr["CanSeeReward"]); }
catch { valid_entry = false; }
if (valid_entry)
{
this.CanSeeReward = boolEntry;
}
valid_entry = true;
boolEntry = true;
try { boolEntry = bool.Parse((string)dr["Repeatable"]); }
catch { valid_entry = false; }
if (valid_entry)
{
this.m_Repeatable = boolEntry;
}
valid_entry = true;
timespanEntry = TimeSpan.Zero;
try { timespanEntry = TimeSpan.Parse((string)dr["NextRepeatable"]); }
catch { valid_entry = false; }
if (valid_entry)
{
this.m_NextRepeatable = timespanEntry;
}
valid_entry = true;
boolEntry = false;
try { boolEntry = bool.Parse((string)dr["PlayerMade"]); }
catch { valid_entry = false; }
if (valid_entry)
{
this.PlayerMade = boolEntry;
}
valid_entry = true;
intEntry = 0;
try { intEntry = int.Parse((string)dr["PartyRange"]); }
catch { valid_entry = false; }
if (valid_entry)
{
this.PartyRange = intEntry;
}
valid_entry = true;
doubleEntry = 0;
try { doubleEntry = double.Parse((string)dr["Expiration"]); }
catch { valid_entry = false; }
if (valid_entry)
{
this.Expiration = doubleEntry;
}
}
}
}
}
}
}
}
| |
// This file was created automatically, do not modify the contents of this file.
// ReSharper disable InvalidXmlDocComment
// ReSharper disable InconsistentNaming
// ReSharper disable CheckNamespace
// ReSharper disable MemberCanBePrivate.Global
namespace UnrealEngine
{
/// <summary>
/// Enum defining if BeginPlay has started or finished
/// </summary>
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\Actor.h:349
public enum EActorBeginPlayState : byte
{
HasNotBegunPlay,
BeginningPlay,
HasBegunPlay,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\Tasks\AITask.h:13
public enum EAITaskPriority : byte
{
Lowest = 0,
Low = 64,
AutonomousAI = 127,
High = 192,
Ultimate = 254,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\SkeletalMeshComponent.h:175
public enum EAllowKinematicDeferral : byte
{
AllowDeferral,
DisallowDeferral,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\SkeletalMeshComponent.h:58
public enum EAnimCurveType : byte
{
AttributeCurve,
MaterialCurve,
MorphTargetCurve,
MaxAnimCurveType,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\Scene.h:32
public enum EAntiAliasingMethod : byte
{
AAM_None,
AAM_FXAA,
AAM_TemporalAA,
AAM_MSAA,
AAM_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:32
public enum EAspectRatioAxisConstraint : byte
{
AspectRatio_MaintainYFOV,
AspectRatio_MaintainXFOV,
AspectRatio_MajorAxisFOV,
AspectRatio_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:56
public enum EAttachmentRule : byte
{
KeepRelative,
KeepWorld,
SnapToTarget,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\Scene.h:44
public enum EAutoExposureMethod : byte
{
AEM_Histogram,
AEM_Basic,
AEM_Manual,
AEM_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:2777
public enum EAutoPossessAI : byte
{
Disabled,
PlacedInWorld,
Spawned,
PlacedInWorldOrSpawned,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:239
public enum EBlendMode : byte
{
BLEND_Opaque,
BLEND_Masked,
BLEND_Translucent,
BLEND_Additive,
BLEND_Modulate,
BLEND_AlphaComposite,
BLEND_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\Scene.h:56
public enum EBloomMethod : byte
{
BM_SOG,
BM_FFT,
BM_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\SkinnedMeshComponent.h:32
public enum EBoneVisibilityStatus : byte
{
BVS_HiddenByParent,
BVS_Visible,
BVS_ExplicitlyHidden,
BVS_MAX,
}
/// <summary>
/// Holds the dynamic delegate to call.
/// </summary>
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\InputComponent.h:279
public enum EBoundDelegate : byte
{
Unbound,
Delegate,
DelegateWithKey,
DynamicDelegate,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\PrimitiveComponent.h:36
public enum ECanBeCharacterBase : byte
{
ECB_No,
ECB_Yes,
ECB_Owner,
ECB_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:605
public enum ECollisionChannel : byte
{
ECC_WorldStatic,
ECC_WorldDynamic,
ECC_Pawn,
ECC_Visibility,
ECC_Camera,
ECC_PhysicsBody,
ECC_Vehicle,
ECC_Destructible,
ECC_EngineTraceChannel1,
ECC_EngineTraceChannel2,
ECC_EngineTraceChannel3,
ECC_EngineTraceChannel4,
ECC_EngineTraceChannel5,
ECC_EngineTraceChannel6,
ECC_GameTraceChannel1,
ECC_GameTraceChannel2,
ECC_GameTraceChannel3,
ECC_GameTraceChannel4,
ECC_GameTraceChannel5,
ECC_GameTraceChannel6,
ECC_GameTraceChannel7,
ECC_GameTraceChannel8,
ECC_GameTraceChannel9,
ECC_GameTraceChannel10,
ECC_GameTraceChannel11,
ECC_GameTraceChannel12,
ECC_GameTraceChannel13,
ECC_GameTraceChannel14,
ECC_GameTraceChannel15,
ECC_GameTraceChannel16,
ECC_GameTraceChannel17,
ECC_GameTraceChannel18,
ECC_OverlapAll_Deprecated,
ECC_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:755
public enum ECollisionResponse : byte
{
ECR_Ignore,
ECR_Overlap,
ECR_Block,
ECR_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\Engine.h:106
public enum EConsoleType : byte
{
CONSOLE_Any,
CONSOLE_Mobile,
CONSOLE_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\Navigation\CrowdFollowingComponent.h:29
public enum ECrowdSimulationState : byte
{
Enabled,
ObstacleOnly,
Disabled,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\Scene.h:22
public enum EDepthOfFieldMethod : byte
{
DOFM_BokehDOF,
DOFM_Gaussian,
DOFM_CircleDOF,
DOFM_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:106
public enum EDetachmentRule : byte
{
KeepRelative,
KeepWorld,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\SceneComponent.h:50
public enum EDetailMode : byte
{
DM_Low,
DM_Medium,
DM_High,
DM_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\Engine.h:114
public enum EDynamicResolutionStatus : byte
{
Unsupported,
Disabled,
Paused,
Enabled,
DebugForceEnabled,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:765
public enum EFilterInterpolationType : byte
{
BSIT_Average,
BSIT_Linear,
BSIT_Cubic,
BSIT_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:808
public enum EFlushLevelStreamingType : byte
{
None,
Full,
Visibility,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\Engine.h:72
public enum EFullyLoadPackageType : byte
{
FULLYLOAD_Map,
FULLYLOAD_Game_PreLoadClass,
FULLYLOAD_Game_PostLoadClass,
FULLYLOAD_Always,
FULLYLOAD_Mutator,
FULLYLOAD_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Core\Public\Math\Color.h:17
public enum EGammaSpace : byte
{
Linear,
Pow22,
sRGB,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\AITypes.h:590
public enum EGenericAICheck : byte
{
Less,
LessOrEqual,
Equal,
NotEqual,
GreaterOrEqual,
Greater,
IsTrue,
MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\Engine.h:56
public enum EGetWorldErrorMode : byte
{
ReturnNull,
LogAndReturnNull,
Assert,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\ProjectileMovementComponent.h:342
public enum EHandleBlockingHitResult : byte
{
Deflect,
AdvanceNextSubstep,
Abort,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\TextRenderComponent.h:17
public enum EHorizTextAligment : byte
{
EHTA_Left,
EHTA_Center,
EHTA_Right,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:192
public enum EIndirectLightingCacheQuality : byte
{
ILCQ_Off,
ILCQ_Point,
ILCQ_Volume,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Camera\CameraShake.h:31
public enum EInitialOscillatorOffset : byte
{
EOO_OffsetRandom,
EOO_OffsetZero,
EOO_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineBaseTypes.h:26
public enum EInputEvent : byte
{
IE_Pressed = 0,
IE_Released = 1,
IE_Repeat = 2,
IE_DoubleClick = 3,
IE_Axis = 4,
IE_MAX = 5,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Core\Public\Math\InterpCurvePoint.h:15
public enum EInterpCurveMode : byte
{
CIM_Linear,
CIM_CurveAuto,
CIM_Constant,
CIM_CurveUser,
CIM_CurveBreak,
CIM_CurveAutoClamped,
CIM_Unknown,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\InterpToMovementComponent.h:14
public enum EInterpToBehaviourType : byte
{
OneShot,
OneShot_Reverse,
Loop_Reset,
PingPong,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineBaseTypes.h:65
public enum ELevelTick : byte
{
LEVELTICK_TimeOnly = 0,
LEVELTICK_ViewportsOnly = 1,
LEVELTICK_All = 2,
LEVELTICK_PauseTick = 3,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:507
public enum ELightingBuildQuality : byte
{
Quality_Preview,
Quality_Medium,
Quality_High,
Quality_Production,
Quality_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:1775
public enum ELightMapPaddingType : byte
{
LMPT_NormalPadding,
LMPT_PrePadding,
LMPT_NoPadding,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:204
public enum ELightmapType : byte
{
Default,
ForceSurface,
ForceVolumetric,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\Scene.h:66
public enum ELightUnits : byte
{
Unitless,
Candelas,
Lumens,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:491
public enum EMaterialSamplerType : byte
{
SAMPLERTYPE_Color,
SAMPLERTYPE_Grayscale,
SAMPLERTYPE_Alpha,
SAMPLERTYPE_Normal,
SAMPLERTYPE_Masks,
SAMPLERTYPE_DistanceFieldFont,
SAMPLERTYPE_LinearColor,
SAMPLERTYPE_LinearGrayscale,
SAMPLERTYPE_External,
SAMPLERTYPE_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:461
public enum EMaterialShadingModel : byte
{
MSM_Unlit,
MSM_DefaultLit,
MSM_Subsurface,
MSM_PreintegratedSkin,
MSM_ClearCoat,
MSM_SubsurfaceProfile,
MSM_TwoSidedFoliage,
MSM_Hair,
MSM_Cloth,
MSM_Eye,
MSM_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:478
public enum EMaterialTessellationMode : byte
{
MTM_NoTessellation,
MTM_FlatTessellation,
MTM_PNTriangles,
MTM_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\Navigation\MetaNavMeshPath.h:14
public enum EMetaPathUpdateReason : byte
{
PathFinished,
MoveTick,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineBaseTypes.h:37
public enum EMouseCaptureMode : byte
{
NoCapture,
CapturePermanently,
CapturePermanently_IncludingInitialMouseDown,
CaptureDuringMouseDown,
CaptureDuringRightMouseDown,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineBaseTypes.h:52
public enum EMouseLockMode : byte
{
DoNotLock,
LockOnCapture,
LockAlways,
LockInFullscreen,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\SceneComponent.h:73
public enum EMoveComponentFlags : byte
{
MOVECOMP_NoFlags = 0x0000,
MOVECOMP_IgnoreBases = 0x0001,
MOVECOMP_SkipPhysicsMove = 0x0002,
MOVECOMP_NeverIgnoreBlockingOverlaps = 0x0004,
MOVECOMP_DisableBlockingOverlapDispatch = 0x0008,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:518
public enum EMovementMode : byte
{
MOVE_None,
MOVE_Walking,
MOVE_NavWalking,
MOVE_Falling,
MOVE_Swimming,
MOVE_Flying,
MOVE_Custom,
MOVE_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:2741
public enum ENetDormancy : byte
{
DORM_Never,
DORM_Awake,
DORM_DormantAll,
DORM_DormantPartial,
DORM_Initial,
DORM_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineBaseTypes.h:904
public enum ENetMode : byte
{
NM_Standalone,
NM_DedicatedServer,
NM_ListenServer,
NM_Client,
NM_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:2726
public enum ENetRole : byte
{
ROLE_None,
ROLE_SimulatedProxy,
ROLE_AutonomousProxy,
ROLE_Authority,
ROLE_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:550
public enum ENetworkSmoothingMode : byte
{
Disabled,
Linear,
Exponential,
Replay,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:675
public enum EObjectTypeQuery : byte
{
ObjectTypeQuery1,
ObjectTypeQuery2,
ObjectTypeQuery3,
ObjectTypeQuery4,
ObjectTypeQuery5,
ObjectTypeQuery6,
ObjectTypeQuery7,
ObjectTypeQuery8,
ObjectTypeQuery9,
ObjectTypeQuery10,
ObjectTypeQuery11,
ObjectTypeQuery12,
ObjectTypeQuery13,
ObjectTypeQuery14,
ObjectTypeQuery15,
ObjectTypeQuery16,
ObjectTypeQuery17,
ObjectTypeQuery18,
ObjectTypeQuery19,
ObjectTypeQuery20,
ObjectTypeQuery21,
ObjectTypeQuery22,
ObjectTypeQuery23,
ObjectTypeQuery24,
ObjectTypeQuery25,
ObjectTypeQuery26,
ObjectTypeQuery27,
ObjectTypeQuery28,
ObjectTypeQuery29,
ObjectTypeQuery30,
ObjectTypeQuery31,
ObjectTypeQuery32,
ObjectTypeQuery_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:220
public enum EOcclusionCombineMode : byte
{
OCM_Minimum,
OCM_Multiply,
OCM_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:2220
public enum EOptimizeMode : byte
{
TrailMode,
LookAheadMode,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Camera\CameraShake.h:20
public enum EOscillatorWaveform : byte
{
SineWave,
PerlinNoise,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:663
public enum EOverlapFilterOption : byte
{
OverlapFilter_All,
OverlapFilter_DynamicOnly,
OverlapFilter_StaticOnly,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\SkinnedMeshComponent.h:45
public enum EPhysBodyOp : byte
{
PBO_None,
PBO_Term,
PBO_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\MovementComponent.h:28
public enum EPlaneConstraintAxisSetting : byte
{
Custom,
X,
Y,
Z,
UseGlobalPhysicsSetting,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\GenericTeamAgentInterface.h:28
public enum EPredefinedId : byte
{
NoTeamId = 255,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\World.h:730
public enum EProcessReason : byte
{
Add,
Reevaluate,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Public\CollisionQueryParams.h:18
public enum EQueryMobilityType : byte
{
Any,
Static,
Dynamic,
}
/// <summary>
/// static variable for default data to be used without reconstructing everytime
/// </summary>
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:1063
public enum ERadialImpulseFalloff : byte
{
RIF_Constant,
RIF_Linear,
RIF_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\Scene.h:88
public enum EReflectedAndRefractedRayTracedShadows : byte
{
Disabled,
Hard_shadows,
Area_shadows,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\ReflectionCaptureComponent.h:18
public enum EReflectionSourceType : byte
{
CapturedScene,
SpecifiedCubemap,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\Scene.h:74
public enum EReflectionsType : byte
{
ScreenSpace,
RayTracing,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:309
public enum ERefractionMode : byte
{
RM_IndexOfRefraction,
RM_PixelNormalOffset,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\SceneComponent.h:60
public enum ERelativeTransformSpace : byte
{
RTS_World,
RTS_Actor,
RTS_Component,
RTS_ParentBoneSpace,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\PrimitiveComponent.h:91
public enum ERendererStencilMask : byte
{
ERSM_Default,
ERSM_255,
ERSM_1,
ERSM_2,
ERSM_4,
ERSM_8,
ERSM_16,
ERSM_32,
ERSM_64,
ERSM_128,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\RootMotionSource.h:32
public enum ERootMotionAccumulateMode : byte
{
Override = 0,
Additive = 1,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\RootMotionSource.h:134
public enum ERootMotionFinishVelocityMode : byte
{
MaintainLastRootMotionVelocity = 0,
SetVelocity,
ClampVelocity,
}
/// <summary>
/// Collection of the most recent ID mappings
/// </summary>
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\CharacterMovementComponent.h:2327
public enum ERootMotionMapping : byte
{
MapSize = 16,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\RootMotionSource.h:71
public enum ERootMotionSourceID : byte
{
Invalid = 0,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\RootMotionSource.h:58
public enum ERootMotionSourceSettingsFlags : byte
{
UseSensitiveLiftoffCheck = 0x01,
DisablePartialEndTick = 0x02,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\RootMotionSource.h:44
public enum ERootMotionSourceStatusFlags : byte
{
Prepared = 0x01,
Finished = 0x02,
MarkedForRemoval = 0x04,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:252
public enum ESamplerSourceMode : byte
{
SSM_FromTextureAsset,
SSM_Wrap_WorldGroupSettings,
SSM_Clamp_WorldGroupSettings,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:362
public enum ESceneCaptureCompositeMode : byte
{
SCCM_Overwrite,
SCCM_Additive,
SCCM_Composite,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\SceneCaptureComponent.h:48
public enum ESceneCapturePrimitiveRenderMode : byte
{
PRM_LegacySceneCapture,
PRM_RenderScenePrimitives,
PRM_UseShowOnlyList,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:348
public enum ESceneCaptureSource : byte
{
SCS_SceneColorHDR,
SCS_SceneColorHDRNoAlpha,
SCS_FinalColorLDR,
SCS_SceneColorSceneDepth,
SCS_SceneDepth,
SCS_DeviceDepth,
SCS_Normal,
SCS_BaseColor,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:181
public enum ESceneDepthPriorityGroup : byte
{
SDPG_World,
SDPG_Foreground,
SDPG_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:1784
public enum EShadowMapFlags : byte
{
SMF_None = 0,
SMF_Streamed = 0x00000001,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\ShapeComponent.h:105
public enum EShapeBodySetupHelper : byte
{
InvalidateSharingIfStale,
UpdateBodySetup,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\SkyLightComponent.h:86
public enum ESkyLightSourceType : byte
{
SLS_CapturedScene,
SLS_SpecifiedCubemap,
SLS_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:1167
public enum ESleepEvent : byte
{
SET_Wakeup,
SET_Sleep,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:1074
public enum ESleepFamily : byte
{
Normal,
Sensitive,
Custom,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\GameNetworkManager.h:13
public enum EStandbyType : byte
{
STDBY_Rx,
STDBY_Tx,
STDBY_BadPing,
STDBY_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\BrainComponent.h:28
public enum EStatus : byte
{
Failure,
Success,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\StereoLayerComponent.h:30
public enum EStereoLayerShape : byte
{
SLSH_QuadLayer,
SLSH_CylinderLayer,
SLSH_CubemapLayer,
SLSH_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\StereoLayerComponent.h:14
public enum EStereoLayerType : byte
{
SLT_WorldLocked,
SLT_TrackerLocked,
SLT_FaceLocked,
SLT_MAX,
}
/// <summary>
/// Flags controlling how this tag should be shown in the UI
/// </summary>
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\CoreUObject\Public\UObject\Object.h:641
public enum ETagDisplay : byte
{
TD_None = 0,
TD_Date = 1<<0,
TD_Time = 1<<1,
TD_InvariantTz = 1<<2,
TD_Memory = 1<<3,
}
/// <summary>
/// Enum specifying the type of this tag
/// </summary>
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\CoreUObject\Public\UObject\Object.h:626
public enum ETagType : byte
{
TT_Hidden,
TT_Alphabetical,
TT_Numerical,
TT_Dimensional,
TT_Chronological,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:2089
public enum ETeleportType : byte
{
None,
TeleportPhysics,
ResetPhysics,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\ApplicationLifecycleComponent.h:15
public enum ETemperatureSeverityType : byte
{
Unknown,
Good,
Bad,
Serious,
Critical,
NumSeverities,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineBaseTypes.h:79
public enum ETickingGroup : byte
{
TG_PrePhysics,
TG_StartPhysics,
TG_DuringPhysics,
TG_EndPhysics,
TG_PostPhysics,
TG_PostUpdateWork,
TG_LastDemotable,
TG_NewlySpawned,
TG_MAX,
}
/// <summary>
/// Cache whether this function was rescheduled as an interval function during StartParallel
/// </summary>
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineBaseTypes.h:230
public enum ETickState : byte
{
Disabled,
Enabled,
CoolingDown,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\TimelineComponent.h:34
public enum ETimelineLengthMode : byte
{
TL_TimelineLength,
TL_LastKeyFrame,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:1086
public enum ETimelineSigType : byte
{
ETS_EventSignature,
ETS_FloatSignature,
ETS_VectorSignature,
ETS_LinearColorSignature,
ETS_InvalidSignature,
ETS_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:715
public enum ETraceTypeQuery : byte
{
TraceTypeQuery1,
TraceTypeQuery2,
TraceTypeQuery3,
TraceTypeQuery4,
TraceTypeQuery5,
TraceTypeQuery6,
TraceTypeQuery7,
TraceTypeQuery8,
TraceTypeQuery9,
TraceTypeQuery10,
TraceTypeQuery11,
TraceTypeQuery12,
TraceTypeQuery13,
TraceTypeQuery14,
TraceTypeQuery15,
TraceTypeQuery16,
TraceTypeQuery17,
TraceTypeQuery18,
TraceTypeQuery19,
TraceTypeQuery20,
TraceTypeQuery21,
TraceTypeQuery22,
TraceTypeQuery23,
TraceTypeQuery24,
TraceTypeQuery25,
TraceTypeQuery26,
TraceTypeQuery27,
TraceTypeQuery28,
TraceTypeQuery29,
TraceTypeQuery30,
TraceTypeQuery31,
TraceTypeQuery32,
TraceTypeQuery_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:438
public enum ETrailWidthMode : byte
{
ETrailWidthMode_FromCentre,
ETrailWidthMode_FromFirst,
ETrailWidthMode_FromSecond,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\Engine.h:92
public enum ETransitionType : byte
{
TT_None,
TT_Paused,
TT_Loading,
TT_Saving,
TT_Connecting,
TT_Precaching,
TT_WaitingToConnect,
TT_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:264
public enum ETranslucencyLightingMode : byte
{
TLM_VolumetricNonDirectional,
TLM_VolumetricDirectional,
TLM_VolumetricPerVertexNonDirectional,
TLM_VolumetricPerVertexDirectional,
TLM_Surface,
TLM_SurfacePerPixelLighting,
TLM_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\Scene.h:81
public enum ETranslucencyType : byte
{
Raster,
RayTracing,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineBaseTypes.h:701
public enum ETravelType : byte
{
TRAVEL_Absolute,
TRAVEL_Partial,
TRAVEL_Relative,
TRAVEL_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\SkeletalMeshComponent.h:671
public enum EType : byte
{
AddImpulse,
AddForce,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Core\Public\Math\UnitConversion.h:17
public enum EUnit : byte
{
Micrometers,
Millimeters,
Centimeters,
Meters,
Kilometers,
Inches,
Feet,
Yards,
Miles,
Lightyears,
Degrees,
Radians,
MetersPerSecond,
KilometersPerHour,
MilesPerHour,
Celsius,
Farenheit,
Kelvin,
Micrograms,
Milligrams,
Grams,
Kilograms,
MetricTons,
Ounces,
Pounds,
Stones,
Newtons,
PoundsForce,
KilogramsForce,
Hertz,
Kilohertz,
Megahertz,
Gigahertz,
RevolutionsPerMinute,
Bytes,
Kilobytes,
Megabytes,
Gigabytes,
Terabytes,
Lumens,
Candela,
Lux,
CandelaPerMeter2,
Milliseconds,
Seconds,
Minutes,
Hours,
Days,
Months,
Years,
PixelsPerInch,
Percentage,
Multiplier,
Unspecified,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Core\Public\Math\UnitConversion.h:63
public enum EUnitType : byte
{
Distance,
Angle,
Speed,
Temperature,
Mass,
Force,
Frequency,
DataSize,
LuminousFlux,
LuminousIntensity,
Illuminance,
Luminance,
Time,
PixelDensity,
Multipliers,
Arbitrary,
NumberOf,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\InstancedStaticMeshComponent.h:34
public enum EUpdateCommandType : byte
{
Add,
Update,
Hide,
EditorData,
LightmapData,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:2201
public enum EUpdateRateShiftBucket : byte
{
ShiftBucket0 = 0,
ShiftBucket1,
ShiftBucket2,
ShiftBucket3,
ShiftBucket4,
ShiftBucket5,
ShiftBucketMax,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\ActorComponent.h:35
public enum EUpdateTransformFlags : byte
{
None = 0x0,
SkipPhysicsUpdate = 0x1,
PropagateFromParent = 0x2,
OnlyUpdateIfUsingSocket = 0x4,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\TextRenderComponent.h:28
public enum EVerticalTextAligment : byte
{
EVRTA_TextTop,
EVRTA_TextCenter,
EVRTA_TextBottom,
EVRTA_QuadTop,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineBaseTypes.h:929
public enum EViewModeIndex : byte
{
VMI_BrushWireframe = 0,
VMI_Wireframe = 1,
VMI_Unlit = 2,
VMI_Lit = 3,
VMI_Lit_DetailLighting = 4,
VMI_LightingOnly = 5,
VMI_LightComplexity = 6,
VMI_ShaderComplexity = 8,
VMI_LightmapDensity = 9,
VMI_LitLightmapDensity = 10,
VMI_ReflectionOverride = 11,
VMI_VisualizeBuffer = 12,
VMI_StationaryLightOverlap = 14,
VMI_CollisionPawn = 15,
VMI_CollisionVisibility = 16,
VMI_LODColoration = 18,
VMI_QuadOverdraw = 19,
VMI_PrimitiveDistanceAccuracy = 20,
VMI_MeshUVDensityAccuracy = 21,
VMI_ShaderComplexityWithQuadOverdraw = 22,
VMI_HLODColoration = 23,
VMI_GroupLODColoration = 24,
VMI_MaterialTextureScaleAccuracy = 25,
VMI_RequiredTextureResolution = 26,
VMI_PathTracing = 27,
VMI_RayTracingDebug = 28,
VMI_Max,
VMI_Unknown = 255,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Camera\PlayerCameraManager.h:23
public enum EViewTargetBlendFunction : byte
{
VTBlend_Linear,
VTBlend_Cubic,
VTBlend_EaseIn,
VTBlend_EaseOut,
VTBlend_EaseInOut,
VTBlend_MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\WorldSettings.h:22
public enum EVisibilityAggressiveness : byte
{
VIS_LeastAggressive,
VIS_ModeratelyAggressive,
VIS_MostAggressive,
VIS_Max,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\SkinnedMeshComponent.h:56
public enum EVisibilityBasedAnimTickOption : byte
{
AlwaysTickPoseAndRefreshBones,
AlwaysTickPose,
OnlyTickMontagesWhenNotRendered,
OnlyTickPoseWhenRendered,
}
/// <summary>
/// Enum that dictates what propagation policy to follow when calling SetVisibility or SetHiddenInGame recursively
/// </summary>
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\SceneComponent.h:797
public enum EVisibilityPropagation : byte
{
NoPropagation,
DirtyOnly,
Propagate,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\GameFramework\WorldSettings.h:31
public enum EVolumeLightingMethod : byte
{
VLM_VolumetricLightmap,
VLM_SparseVolumeLightingSamples,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Components\WindDirectionalSourceComponent.h:12
public enum EWindSourceType : byte
{
Directional,
Point,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\AITypes.h:69
public enum FAIDistanceType : byte
{
Distance3D,
Distance2D,
DistanceZ,
MAX,
}
// Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Public\CollisionQueryParams.h:348
public enum InitType : byte
{
AllObjects,
AllStaticObjects,
AllDynamicObjects,
}
}
| |
// Copyright (c) 2013, SIL International.
// Distributable under the terms of the MIT license (http://opensource.org/licenses/MIT).
#if __MonoCS__
using System;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using IBusDotNet;
using Palaso.UI.WindowsForms.Extensions;
using Palaso.UI.WindowsForms.Keyboarding.Interfaces;
namespace Palaso.UI.WindowsForms.Keyboarding.Linux
{
/// <summary>
/// Default event handler for IBUS events that works with a WinForms text box.
/// </summary>
public class IbusDefaultEventHandler: IIbusEventHandler
{
private TextBox m_TextBox;
/// <summary>
/// The start of the selection in the textbox before we insert a temporary composition string.
/// </summary>
private int m_SelectionStart;
/// <summary>
/// The initial length of the selection in the textbox.
/// </summary>
private int m_SelectionLength;
/// <summary>
/// Number of characters that got inserted temporarily as composition string.
/// </summary>
private int m_PreeditLength;
/// <summary>
/// <c>true</c> while we're inside of Reset(bool).
/// </summary>
private bool m_InReset;
public IbusDefaultEventHandler(TextBox textBox)
{
m_TextBox = textBox;
m_SelectionStart = -1;
m_SelectionLength = -1;
}
/// <summary>
/// Reset the selection and optionally cancel any open compositions.
/// </summary>
/// <param name="cancel">Set to <c>true</c> to also cancel the open composition.</param>
/// <returns><c>true</c> if there was an open composition that we cancelled, otherwise
/// <c>false</c>.</returns>
private bool Reset(bool cancel)
{
if (m_InReset)
return false;
bool retVal = false;
m_InReset = true;
if (cancel && m_SelectionStart > -1)
{
var preeditStart = m_SelectionStart + m_SelectionLength;
m_TextBox.Text = RemoveChars(m_TextBox.Text, preeditStart, m_PreeditLength);
m_TextBox.SelectionStart = m_SelectionStart;
m_TextBox.SelectionLength = m_SelectionLength;
retVal = true;
}
m_SelectionStart = -1;
m_SelectionLength = -1;
m_PreeditLength = 0;
m_InReset = false;
return retVal;
}
/// <summary>
/// Removes the characters from the preedit part of <paramref name="text"/>.
/// </summary>
/// <returns>The new string.</returns>
/// <param name="text">Text.</param>
/// <param name="removePos">Position inside of <paramref name="text"/> where the
/// temporary preedit characters start and where we should start to remove the
/// characters.</param>
/// <param name="preeditTextLen">Length of the preedit text part.</param>
private static string RemoveChars(string text, int removePos, int preeditTextLen)
{
var toRemove = preeditTextLen;
if (removePos + toRemove > text.Length)
toRemove = Math.Max(text.Length - removePos, 0);
if (toRemove > 0)
return text.Remove(removePos, toRemove);
return text;
}
/// <summary>
/// Trim beginning backspaces, if any. Return number trimmed.
/// </summary>
private static int TrimBeginningBackspaces(ref string text)
{
const char backSpace = '\b'; // 0x0008
if (!text.StartsWith(backSpace.ToString()))
return 0;
int count = text.Length - text.TrimStart(backSpace).Length;
text = text.TrimStart(backSpace);
return count;
}
private void OnCommitText(string text)
{
// Replace 'toRemove' characters starting at 'insertPos' with 'text'.
int insertPos, toRemove;
if (m_SelectionStart > -1)
{
insertPos = m_SelectionStart;
toRemove = m_SelectionLength + m_PreeditLength;
}
else
{
// IPA Unicode 6.2 ibus keyboard doesn't call OnUpdatPreeditText,
// only OnCommitText, so we don't have a m_SelectionStart stored.
insertPos = m_TextBox.SelectionStart;
toRemove = m_TextBox.SelectionLength;
}
var countBackspace = TrimBeginningBackspaces(ref text);
insertPos -= countBackspace;
if (insertPos < 0)
insertPos = 0;
toRemove += countBackspace;
var boxText = RemoveChars(m_TextBox.Text, insertPos, toRemove);
m_TextBox.Text = boxText.Insert(insertPos, text);
m_TextBox.SelectionStart = insertPos + text.Length;
m_TextBox.SelectionLength = 0;
Reset(false);
}
// When the application loses focus the user expects different behavior for different
// ibus keyboards: for some keyboards (those that do the editing in-place and don't display
// a selection window, e.g. "Danish - post (m17n)") the user expects that what he
// typed remains, i.e. gets committed. Otherwise (e.g. with the Danish keyboard) it's not
// possible to type an "a" and then click in a different field or switch applications.
//
// For other keyboards (e.g. Chinese Pinyin) the commit is made when the user selects
// one of the possible characters in the pop-up window. If he clicks in a different
// field while the pop-up window is open the composition should be deleted.
//
// There doesn't seem to be a way to ask an IME keyboard if it shows a pop-up window or
// if we should commit or reset the composition. One indirect way however seems to be to
// check the attributes: it seems that keyboards where we can/should commit set the
// underline attribute to IBusAttrUnderline.None.
private bool IsCommittingKeyboard { get; set; }
private void CheckAttributesForCommittingKeyboard(IBusText text)
{
IsCommittingKeyboard = false;
foreach (var attribute in text.Attributes)
{
var iBusUnderlineAttribute = attribute as IBusUnderlineAttribute;
if (iBusUnderlineAttribute != null && iBusUnderlineAttribute.Underline == IBusAttrUnderline.None)
IsCommittingKeyboard = true;
}
}
#region IIbusEventHandler implementation
/// <summary>
/// This method gets called when the IBus CommitText event is raised and indicates that
/// the composition is ending. The temporarily inserted composition string will be
/// replaced with <paramref name="ibusText"/>.
/// </summary>
/// <seealso cref="IBusKeyboardAdaptor.HandleKeyPress"/>
public void OnCommitText(object ibusText)
{
// Note: when we try to pass IBusText as ibusText parameter we get a compiler crash
// in FW.
if (m_TextBox.InvokeRequired)
{
m_TextBox.BeginInvoke(() => OnCommitText(ibusText));
return;
}
if (!m_TextBox.Focused)
return;
OnCommitText(((IBusText)ibusText).Text);
}
/// <summary>
/// Called when the IBus UpdatePreeditText event is raised to update the composition.
/// </summary>
/// <param name="obj">New composition string that will replace the existing
/// composition string.</param>
/// <param name="cursorPos">0-based position where the cursor should be put after
/// updating the composition (pre-edit window). This position is relative to the
/// composition/preedit text.</param>
/// <seealso cref="IBusKeyboardAdaptor.HandleKeyPress"/>
public void OnUpdatePreeditText(object obj, int cursorPos)
{
if (m_TextBox.InvokeRequired)
{
m_TextBox.BeginInvoke(() => OnUpdatePreeditText(obj, cursorPos));
return;
}
if (!m_TextBox.Focused)
return;
var text = obj as IBusText;
CheckAttributesForCommittingKeyboard(text);
var compositionText = text.Text;
if (m_SelectionStart == -1 || m_SelectionStart + m_SelectionLength > m_TextBox.Text.Length)
{
// Remember selection in textbox prior to inserting composition text.
m_SelectionStart = m_TextBox.SelectionStart;
m_SelectionLength = m_TextBox.SelectionLength;
}
var preeditStart = m_SelectionStart + m_SelectionLength;
m_TextBox.SelectionStart = preeditStart;
m_TextBox.SelectionLength = 0;
// Remove the previous composition text starting at preeditStart
m_TextBox.Text = RemoveChars(m_TextBox.Text, preeditStart, m_PreeditLength);
if (preeditStart >= m_TextBox.Text.Length)
{
preeditStart = m_TextBox.Text.Length;
m_TextBox.AppendText(compositionText);
}
else
m_TextBox.Text = m_TextBox.Text.Insert(preeditStart, compositionText);
m_PreeditLength = compositionText.Length;
if (m_SelectionLength > 0)
{
// We want to keep the range selection. It gets deleted in the CommitTextHandler.
// This mimics the behavior in gedit.
m_TextBox.SelectionStart = m_SelectionStart;
m_TextBox.SelectionLength = m_SelectionLength;
}
else
{
m_TextBox.SelectionStart = m_SelectionStart + cursorPos;
m_TextBox.SelectionLength = 0;
}
}
/// <summary>
/// Called when the IBus DeleteSurroundingText is raised to delete surrounding
/// characters.
/// </summary>
/// <param name="offset">The character offset from the cursor position of the text to be
/// deleted. A negative value indicates a position before the cursor.</param>
/// <param name="nChars">The number of characters to be deleted.</param>
public void OnDeleteSurroundingText(int offset, int nChars)
{
if (m_TextBox.InvokeRequired)
{
m_TextBox.BeginInvoke(() => OnDeleteSurroundingText(offset, nChars));
return;
}
if (!m_TextBox.Focused || nChars <= 0)
return;
var selectionStart = m_TextBox.SelectionStart;
var startIndex = selectionStart + offset;
if (startIndex + nChars <= 0)
return;
startIndex = Math.Max(startIndex, 0);
startIndex = Math.Min(startIndex, m_TextBox.Text.Length);
if (startIndex + nChars > m_TextBox.Text.Length)
nChars = m_TextBox.Text.Length - startIndex;
if (startIndex < selectionStart)
selectionStart = Math.Max(selectionStart - nChars, 0);
m_TextBox.Text = m_TextBox.Text.Remove(startIndex, nChars);
m_TextBox.SelectionStart = selectionStart;
m_TextBox.SelectionLength = 0;
}
/// <summary>
/// Called when the IBus HidePreeditText event is raised to cancel/remove the composition.
/// </summary>
public void OnHidePreeditText()
{
if (m_TextBox.InvokeRequired)
{
m_TextBox.BeginInvoke(OnHidePreeditText);
return;
}
if (!m_TextBox.Focused)
return;
Reset(true);
}
/// <summary>
/// Called when the IBus ForwardKeyEvent (as in: forwarding key event) is raised.
/// </summary>
/// <param name="keySym">Key symbol.</param>
/// <param name="scanCode">Scan code.</param>
/// <param name="index">Index into a vector of keycodes associated with a given key
/// depending on which modifier keys are pressed. 0 is always unmodified, and 1 is with
/// shift alone.
/// </param>
/// <seealso cref="IBusKeyboardAdaptor.HandleKeyPress"/>
public void OnIbusKeyPress(int keySym, int scanCode, int index)
{
if (m_TextBox.InvokeRequired)
{
m_TextBox.BeginInvoke(() => OnIbusKeyPress(keySym, scanCode, index));
return;
}
if (!m_TextBox.Focused)
return;
var inChar = (char)(0x00FF & keySym);
OnCommitText(inChar.ToString());
}
/// <summary>
/// Called by the IBusKeyboardAdapter to cancel any open compositions.
/// </summary>
/// <returns><c>true</c> if there was an open composition that got cancelled, otherwise
/// <c>false</c>.</returns>
public bool Reset()
{
Debug.Assert(!m_TextBox.InvokeRequired);
return Reset(true);
}
/// <summary>
/// Called by the IbusKeyboardAdapter to commit or cancel any open compositions, e.g.
/// after the application loses focus.
/// </summary>
/// <returns><c>true</c> if there was an open composition that got cancelled, otherwise
/// <c>false</c>.</returns>
public bool CommitOrReset()
{
// don't check if we have focus - we won't if this gets called from OnLostFocus.
// However, the IbusKeyboardAdapter calls this method only for the control that just
// lost focus, so it's ok not to check :-)
if (IsCommittingKeyboard)
{
m_SelectionStart = -1;
m_SelectionLength = -1;
m_PreeditLength = 0;
return false;
}
return Reset(true);
}
/// <summary>
/// Called by the IBusKeyboardAdapter to get the position (in pixels) and line height of
/// the end of the selection. The position is relative to the screen in the
/// PointToScreen sense, that is (0,0) is the top left of the primary monitor.
/// IBus will use this information when it opens a pop-up window to present a list of
/// composition choices.
/// </summary>
public Rectangle SelectionLocationAndHeight
{
get
{
Debug.Assert(!m_TextBox.InvokeRequired);
var posInTextBox = m_TextBox.GetPositionFromCharIndex(m_TextBox.SelectionStart + m_TextBox.SelectionLength);
var posScreen = m_TextBox.PointToScreen(posInTextBox);
return new Rectangle(posScreen, new Size(0, m_TextBox.Font.Height));
}
}
/// <summary>
/// Called by the IbusKeyboardAdapter to find out if a preedit is active.
/// </summary>
public bool IsPreeditActive
{
get { return m_SelectionStart > -1; }
}
#endregion
}
}
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.