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.
*/
#pragma warning disable 618 // Ignore obsolete, we still need to test them.
namespace Apache.Ignite.Core.Tests
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
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.Client;
using Apache.Ignite.Core.Client.Cache;
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.Discovery.Tcp;
using Apache.Ignite.Core.Discovery.Tcp.Multicast;
using Apache.Ignite.Core.Discovery.Tcp.Static;
using Apache.Ignite.Core.Encryption.Keystore;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.PersistentStore;
using Apache.Ignite.Core.Tests.Plugin;
using Apache.Ignite.Core.Transactions;
using NUnit.Framework;
using WalMode = Apache.Ignite.Core.PersistentStore.WalMode;
/// <summary>
/// Tests code-based configuration.
/// </summary>
public class IgniteConfigurationTest
{
/// <summary>
/// Fixture tear down.
/// </summary>
[TestFixtureSetUp]
public void FixtureTearDown()
{
Ignition.StopAll(true);
}
/// <summary>
/// Tests the default configuration properties.
/// </summary>
[Test]
public void TestDefaultConfigurationProperties()
{
CheckDefaultProperties(new IgniteConfiguration());
CheckDefaultProperties(new PersistentStoreConfiguration());
CheckDefaultProperties(new DataStorageConfiguration());
CheckDefaultProperties(new DataRegionConfiguration());
CheckDefaultProperties(new ClientConnectorConfiguration());
CheckDefaultProperties(new SqlConnectorConfiguration());
}
/// <summary>
/// Tests the default value attributes.
/// </summary>
[Test]
public void TestDefaultValueAttributes()
{
CheckDefaultValueAttributes(new IgniteConfiguration());
CheckDefaultValueAttributes(new BinaryConfiguration());
CheckDefaultValueAttributes(new TcpDiscoverySpi());
CheckDefaultValueAttributes(new KeystoreEncryptionSpi());
CheckDefaultValueAttributes(new CacheConfiguration());
CheckDefaultValueAttributes(new TcpDiscoveryMulticastIpFinder());
CheckDefaultValueAttributes(new TcpCommunicationSpi());
CheckDefaultValueAttributes(new RendezvousAffinityFunction());
CheckDefaultValueAttributes(new NearCacheConfiguration());
CheckDefaultValueAttributes(new FifoEvictionPolicy());
CheckDefaultValueAttributes(new LruEvictionPolicy());
CheckDefaultValueAttributes(new AtomicConfiguration());
CheckDefaultValueAttributes(new TransactionConfiguration());
CheckDefaultValueAttributes(new MemoryEventStorageSpi());
CheckDefaultValueAttributes(new MemoryConfiguration());
CheckDefaultValueAttributes(new MemoryPolicyConfiguration());
CheckDefaultValueAttributes(new SqlConnectorConfiguration());
CheckDefaultValueAttributes(new ClientConnectorConfiguration());
CheckDefaultValueAttributes(new PersistentStoreConfiguration());
CheckDefaultValueAttributes(new IgniteClientConfiguration());
CheckDefaultValueAttributes(new QueryIndex());
CheckDefaultValueAttributes(new DataStorageConfiguration());
CheckDefaultValueAttributes(new DataRegionConfiguration());
CheckDefaultValueAttributes(new CacheClientConfiguration());
}
/// <summary>
/// Tests all configuration properties.
/// </summary>
[Test]
public void TestAllConfigurationProperties()
{
var cfg = new IgniteConfiguration(GetCustomConfig());
using (var ignite = Ignition.Start(cfg))
{
var resCfg = ignite.GetConfiguration();
var disco = (TcpDiscoverySpi) cfg.DiscoverySpi;
var resDisco = (TcpDiscoverySpi) resCfg.DiscoverySpi;
Assert.AreEqual(disco.NetworkTimeout, resDisco.NetworkTimeout);
Assert.AreEqual(disco.AckTimeout, resDisco.AckTimeout);
Assert.AreEqual(disco.MaxAckTimeout, resDisco.MaxAckTimeout);
Assert.AreEqual(disco.SocketTimeout, resDisco.SocketTimeout);
Assert.AreEqual(disco.JoinTimeout, resDisco.JoinTimeout);
Assert.AreEqual(disco.LocalAddress, resDisco.LocalAddress);
Assert.AreEqual(disco.LocalPort, resDisco.LocalPort);
Assert.AreEqual(disco.LocalPortRange, resDisco.LocalPortRange);
Assert.AreEqual(disco.ReconnectCount, resDisco.ReconnectCount);
Assert.AreEqual(disco.StatisticsPrintFrequency, resDisco.StatisticsPrintFrequency);
Assert.AreEqual(disco.ThreadPriority, resDisco.ThreadPriority);
Assert.AreEqual(disco.TopologyHistorySize, resDisco.TopologyHistorySize);
var enc = (KeystoreEncryptionSpi) cfg.EncryptionSpi;
var resEnc = (KeystoreEncryptionSpi) resCfg.EncryptionSpi;
Assert.AreEqual(enc.MasterKeyName, resEnc.MasterKeyName);
Assert.AreEqual(enc.KeySize, resEnc.KeySize);
Assert.AreEqual(enc.KeyStorePath, resEnc.KeyStorePath);
Assert.AreEqual(enc.KeyStorePassword, resEnc.KeyStorePassword);
var ip = (TcpDiscoveryStaticIpFinder) disco.IpFinder;
var resIp = (TcpDiscoveryStaticIpFinder) resDisco.IpFinder;
// There can be extra IPv6 endpoints
Assert.AreEqual(ip.Endpoints, resIp.Endpoints.Take(2).Select(x => x.Trim('/')).ToArray());
Assert.AreEqual(cfg.IgniteInstanceName, resCfg.IgniteInstanceName);
Assert.AreEqual(cfg.IgniteHome, resCfg.IgniteHome);
Assert.AreEqual(cfg.IncludedEventTypes, resCfg.IncludedEventTypes);
Assert.AreEqual(cfg.MetricsExpireTime, resCfg.MetricsExpireTime);
Assert.AreEqual(cfg.MetricsHistorySize, resCfg.MetricsHistorySize);
Assert.AreEqual(cfg.MetricsLogFrequency, resCfg.MetricsLogFrequency);
Assert.AreEqual(cfg.MetricsUpdateFrequency, resCfg.MetricsUpdateFrequency);
Assert.AreEqual(cfg.NetworkSendRetryCount, resCfg.NetworkSendRetryCount);
Assert.AreEqual(cfg.NetworkTimeout, resCfg.NetworkTimeout);
Assert.AreEqual(cfg.NetworkSendRetryDelay, resCfg.NetworkSendRetryDelay);
Assert.AreEqual(cfg.WorkDirectory.Trim(Path.DirectorySeparatorChar),
resCfg.WorkDirectory.Trim(Path.DirectorySeparatorChar));
Assert.AreEqual(cfg.JvmClasspath, resCfg.JvmClasspath);
Assert.AreEqual(cfg.JvmOptions, resCfg.JvmOptions);
Assert.AreEqual(cfg.JvmDllPath, resCfg.JvmDllPath);
Assert.AreEqual(cfg.Localhost, resCfg.Localhost);
Assert.AreEqual(cfg.IsDaemon, resCfg.IsDaemon);
Assert.AreEqual(IgniteConfiguration.DefaultIsLateAffinityAssignment, resCfg.IsLateAffinityAssignment);
Assert.AreEqual(cfg.UserAttributes, resCfg.UserAttributes);
var atm = cfg.AtomicConfiguration;
var resAtm = resCfg.AtomicConfiguration;
Assert.AreEqual(atm.AtomicSequenceReserveSize, resAtm.AtomicSequenceReserveSize);
Assert.AreEqual(atm.Backups, resAtm.Backups);
Assert.AreEqual(atm.CacheMode, resAtm.CacheMode);
var tx = cfg.TransactionConfiguration;
var resTx = resCfg.TransactionConfiguration;
Assert.AreEqual(tx.DefaultTimeout, resTx.DefaultTimeout);
Assert.AreEqual(tx.DefaultTransactionConcurrency, resTx.DefaultTransactionConcurrency);
Assert.AreEqual(tx.DefaultTransactionIsolation, resTx.DefaultTransactionIsolation);
Assert.AreEqual(tx.PessimisticTransactionLogLinger, resTx.PessimisticTransactionLogLinger);
Assert.AreEqual(tx.PessimisticTransactionLogSize, resTx.PessimisticTransactionLogSize);
Assert.AreEqual(tx.DefaultTimeoutOnPartitionMapExchange, resTx.DefaultTimeoutOnPartitionMapExchange);
var com = (TcpCommunicationSpi) cfg.CommunicationSpi;
var resCom = (TcpCommunicationSpi) resCfg.CommunicationSpi;
Assert.AreEqual(com.AckSendThreshold, resCom.AckSendThreshold);
Assert.AreEqual(com.ConnectionsPerNode, resCom.ConnectionsPerNode);
Assert.AreEqual(com.ConnectTimeout, resCom.ConnectTimeout);
Assert.AreEqual(com.DirectBuffer, resCom.DirectBuffer);
Assert.AreEqual(com.DirectSendBuffer, resCom.DirectSendBuffer);
Assert.AreEqual(com.FilterReachableAddresses, resCom.FilterReachableAddresses);
Assert.AreEqual(com.IdleConnectionTimeout, resCom.IdleConnectionTimeout);
Assert.AreEqual(com.LocalAddress, resCom.LocalAddress);
Assert.AreEqual(com.LocalPort, resCom.LocalPort);
Assert.AreEqual(com.LocalPortRange, resCom.LocalPortRange);
Assert.AreEqual(com.MaxConnectTimeout, resCom.MaxConnectTimeout);
Assert.AreEqual(com.MessageQueueLimit, resCom.MessageQueueLimit);
Assert.AreEqual(com.ReconnectCount, resCom.ReconnectCount);
Assert.AreEqual(com.SelectorsCount, resCom.SelectorsCount);
Assert.AreEqual(com.SelectorSpins, resCom.SelectorSpins);
Assert.AreEqual(com.SharedMemoryPort, resCom.SharedMemoryPort);
Assert.AreEqual(com.SlowClientQueueLimit, resCom.SlowClientQueueLimit);
Assert.AreEqual(com.SocketReceiveBufferSize, resCom.SocketReceiveBufferSize);
Assert.AreEqual(com.SocketSendBufferSize, resCom.SocketSendBufferSize);
Assert.AreEqual(com.SocketWriteTimeout, resCom.SocketWriteTimeout);
Assert.AreEqual(com.TcpNoDelay, resCom.TcpNoDelay);
Assert.AreEqual(com.UnacknowledgedMessagesBufferSize, resCom.UnacknowledgedMessagesBufferSize);
Assert.AreEqual(com.UsePairedConnections, resCom.UsePairedConnections);
Assert.AreEqual(cfg.FailureDetectionTimeout, resCfg.FailureDetectionTimeout);
Assert.AreEqual(cfg.SystemWorkerBlockedTimeout, resCfg.SystemWorkerBlockedTimeout);
Assert.AreEqual(cfg.ClientFailureDetectionTimeout, resCfg.ClientFailureDetectionTimeout);
Assert.AreEqual(cfg.LongQueryWarningTimeout, resCfg.LongQueryWarningTimeout);
Assert.AreEqual(cfg.PublicThreadPoolSize, resCfg.PublicThreadPoolSize);
Assert.AreEqual(cfg.StripedThreadPoolSize, resCfg.StripedThreadPoolSize);
Assert.AreEqual(cfg.ServiceThreadPoolSize, resCfg.ServiceThreadPoolSize);
Assert.AreEqual(cfg.SystemThreadPoolSize, resCfg.SystemThreadPoolSize);
Assert.AreEqual(cfg.AsyncCallbackThreadPoolSize, resCfg.AsyncCallbackThreadPoolSize);
Assert.AreEqual(cfg.ManagementThreadPoolSize, resCfg.ManagementThreadPoolSize);
Assert.AreEqual(cfg.DataStreamerThreadPoolSize, resCfg.DataStreamerThreadPoolSize);
Assert.AreEqual(cfg.UtilityCacheThreadPoolSize, resCfg.UtilityCacheThreadPoolSize);
Assert.AreEqual(cfg.QueryThreadPoolSize, resCfg.QueryThreadPoolSize);
Assert.AreEqual(cfg.ConsistentId, resCfg.ConsistentId);
var binCfg = cfg.BinaryConfiguration;
Assert.IsFalse(binCfg.CompactFooter);
var typ = binCfg.TypeConfigurations.Single();
Assert.AreEqual("myType", typ.TypeName);
Assert.IsTrue(typ.IsEnum);
Assert.AreEqual("affKey", typ.AffinityKeyFieldName);
Assert.AreEqual(false, typ.KeepDeserialized);
Assert.IsNotNull(resCfg.PluginConfigurations);
Assert.AreEqual(cfg.PluginConfigurations, resCfg.PluginConfigurations);
var eventCfg = cfg.EventStorageSpi as MemoryEventStorageSpi;
var resEventCfg = resCfg.EventStorageSpi as MemoryEventStorageSpi;
Assert.IsNotNull(eventCfg);
Assert.IsNotNull(resEventCfg);
Assert.AreEqual(eventCfg.ExpirationTimeout, resEventCfg.ExpirationTimeout);
Assert.AreEqual(eventCfg.MaxEventCount, resEventCfg.MaxEventCount);
var sql = cfg.SqlConnectorConfiguration;
var resSql = resCfg.SqlConnectorConfiguration;
Assert.AreEqual(sql.Host, resSql.Host);
Assert.AreEqual(sql.Port, resSql.Port);
Assert.AreEqual(sql.PortRange, resSql.PortRange);
Assert.AreEqual(sql.MaxOpenCursorsPerConnection, resSql.MaxOpenCursorsPerConnection);
Assert.AreEqual(sql.SocketReceiveBufferSize, resSql.SocketReceiveBufferSize);
Assert.AreEqual(sql.SocketSendBufferSize, resSql.SocketSendBufferSize);
Assert.AreEqual(sql.TcpNoDelay, resSql.TcpNoDelay);
Assert.AreEqual(sql.ThreadPoolSize, resSql.ThreadPoolSize);
AssertExtensions.ReflectionEqual(cfg.DataStorageConfiguration, resCfg.DataStorageConfiguration);
Assert.AreEqual(cfg.MvccVacuumFrequency, resCfg.MvccVacuumFrequency);
Assert.AreEqual(cfg.MvccVacuumThreadCount, resCfg.MvccVacuumThreadCount);
Assert.AreEqual(cfg.SqlQueryHistorySize, resCfg.SqlQueryHistorySize);
Assert.IsNotNull(resCfg.SqlSchemas);
Assert.AreEqual(2, resCfg.SqlSchemas.Count);
Assert.IsTrue(resCfg.SqlSchemas.Contains("SCHEMA_3"));
Assert.IsTrue(resCfg.SqlSchemas.Contains("schema_4"));
}
}
/// <summary>
/// Tests the spring XML.
/// </summary>
[Test]
public void TestSpringXml()
{
// When Spring XML is used, .NET overrides Spring.
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
DataStorageConfiguration = null,
SpringConfigUrl = Path.Combine("Config", "spring-test.xml"),
NetworkSendRetryDelay = TimeSpan.FromSeconds(45),
MetricsHistorySize = 57
};
using (var ignite = Ignition.Start(cfg))
{
var resCfg = ignite.GetConfiguration();
Assert.AreEqual(45, resCfg.NetworkSendRetryDelay.TotalSeconds); // .NET overrides XML
Assert.AreEqual(2999, resCfg.NetworkTimeout.TotalMilliseconds); // Not set in .NET -> comes from XML
Assert.AreEqual(57, resCfg.MetricsHistorySize); // Only set in .NET
var disco = resCfg.DiscoverySpi as TcpDiscoverySpi;
Assert.IsNotNull(disco);
Assert.AreEqual(TimeSpan.FromMilliseconds(300), disco.SocketTimeout);
// DataStorage defaults.
CheckDefaultProperties(resCfg.DataStorageConfiguration);
CheckDefaultProperties(resCfg.DataStorageConfiguration.DefaultDataRegionConfiguration);
// Connector defaults.
CheckDefaultProperties(resCfg.ClientConnectorConfiguration);
}
}
/// <summary>
/// Tests the client mode.
/// </summary>
[Test]
public void TestClientMode()
{
using (var ignite = Ignition.Start(new IgniteConfiguration
{
Localhost = "127.0.0.1",
DiscoverySpi = TestUtils.GetStaticDiscovery()
}))
using (var ignite2 = Ignition.Start(new IgniteConfiguration
{
Localhost = "127.0.0.1",
DiscoverySpi = TestUtils.GetStaticDiscovery(),
IgniteInstanceName = "client",
ClientMode = true
}))
{
const string cacheName = "cache";
ignite.CreateCache<int, int>(cacheName);
Assert.AreEqual(2, ignite2.GetCluster().GetNodes().Count);
Assert.AreEqual(1, ignite.GetCluster().ForCacheNodes(cacheName).GetNodes().Count);
Assert.AreEqual(false, ignite.GetConfiguration().ClientMode);
Assert.AreEqual(true, ignite2.GetConfiguration().ClientMode);
}
}
/// <summary>
/// Tests the default spi.
/// </summary>
[Test]
public void TestDefaultSpi()
{
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
DiscoverySpi =
new TcpDiscoverySpi
{
AckTimeout = TimeSpan.FromDays(2),
MaxAckTimeout = TimeSpan.MaxValue,
JoinTimeout = TimeSpan.MaxValue,
NetworkTimeout = TimeSpan.MaxValue,
SocketTimeout = TimeSpan.MaxValue
}
};
using (var ignite = Ignition.Start(cfg))
{
cfg.IgniteInstanceName = "ignite2";
using (var ignite2 = Ignition.Start(cfg))
{
Assert.AreEqual(2, ignite.GetCluster().GetNodes().Count);
Assert.AreEqual(2, ignite2.GetCluster().GetNodes().Count);
}
}
}
/// <summary>
/// Tests the invalid timeouts.
/// </summary>
[Test]
public void TestInvalidTimeouts()
{
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
DiscoverySpi =
new TcpDiscoverySpi
{
AckTimeout = TimeSpan.FromMilliseconds(-5),
JoinTimeout = TimeSpan.MinValue
}
};
Assert.Throws<IgniteException>(() => Ignition.Start(cfg));
}
/// <summary>
/// Tests the static ip finder.
/// </summary>
[Test]
public void TestStaticIpFinder()
{
TestIpFinders(new TcpDiscoveryStaticIpFinder
{
Endpoints = new[] {"127.0.0.1:47500"}
}, new TcpDiscoveryStaticIpFinder
{
Endpoints = new[] {"127.0.0.1:47501"}
});
}
/// <summary>
/// Tests the multicast ip finder.
/// </summary>
[Test]
public void TestMulticastIpFinder()
{
TestIpFinders(
new TcpDiscoveryMulticastIpFinder {MulticastGroup = "228.111.111.222", MulticastPort = 54522},
new TcpDiscoveryMulticastIpFinder {MulticastGroup = "228.111.111.223", MulticastPort = 54522});
}
/// <summary>
/// Tests the work directory.
/// </summary>
[Test]
public void TestWorkDirectory()
{
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
WorkDirectory = TestUtils.GetTempDirectoryName()
};
using (Ignition.Start(cfg))
{
var marshDir = Path.Combine(cfg.WorkDirectory, "marshaller");
Assert.IsTrue(Directory.Exists(marshDir));
}
Directory.Delete(cfg.WorkDirectory, true);
}
/// <summary>
/// Tests the consistent id.
/// </summary>
[Test]
[NUnit.Framework.Category(TestUtils.CategoryIntensive)]
public void TestConsistentId()
{
var ids = new object[]
{
null, new MyConsistentId {Data = "foo"}, "str", 1, 1.1, DateTime.Now, Guid.NewGuid()
};
var cfg = TestUtils.GetTestConfiguration();
foreach (var id in ids)
{
cfg.ConsistentId = id;
using (var ignite = Ignition.Start(cfg))
{
Assert.AreEqual(id, ignite.GetConfiguration().ConsistentId);
Assert.AreEqual(id ?? "127.0.0.1:47500", ignite.GetCluster().GetLocalNode().ConsistentId);
}
}
}
/// <summary>
/// Tests the ip finders.
/// </summary>
/// <param name="ipFinder">The ip finder.</param>
/// <param name="ipFinder2">The ip finder2.</param>
private static void TestIpFinders(TcpDiscoveryIpFinderBase ipFinder, TcpDiscoveryIpFinderBase ipFinder2)
{
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
DiscoverySpi =
new TcpDiscoverySpi
{
IpFinder = ipFinder
}
};
using (var ignite = Ignition.Start(cfg))
{
// Start with the same endpoint
cfg.IgniteInstanceName = "ignite2";
using (var ignite2 = Ignition.Start(cfg))
{
Assert.AreEqual(2, ignite.GetCluster().GetNodes().Count);
Assert.AreEqual(2, ignite2.GetCluster().GetNodes().Count);
}
// Start with incompatible endpoint and check that there are 2 topologies
((TcpDiscoverySpi) cfg.DiscoverySpi).IpFinder = ipFinder2;
using (var ignite2 = Ignition.Start(cfg))
{
Assert.AreEqual(1, ignite.GetCluster().GetNodes().Count);
Assert.AreEqual(1, ignite2.GetCluster().GetNodes().Count);
}
}
}
/// <summary>
/// Checks the default properties.
/// </summary>
/// <param name="cfg">The CFG.</param>
private static void CheckDefaultProperties(IgniteConfiguration cfg)
{
Assert.AreEqual(IgniteConfiguration.DefaultMetricsExpireTime, cfg.MetricsExpireTime);
Assert.AreEqual(IgniteConfiguration.DefaultMetricsHistorySize, cfg.MetricsHistorySize);
Assert.AreEqual(IgniteConfiguration.DefaultMetricsLogFrequency, cfg.MetricsLogFrequency);
Assert.AreEqual(IgniteConfiguration.DefaultMetricsUpdateFrequency, cfg.MetricsUpdateFrequency);
Assert.AreEqual(IgniteConfiguration.DefaultNetworkTimeout, cfg.NetworkTimeout);
Assert.AreEqual(IgniteConfiguration.DefaultNetworkSendRetryCount, cfg.NetworkSendRetryCount);
Assert.AreEqual(IgniteConfiguration.DefaultNetworkSendRetryDelay, cfg.NetworkSendRetryDelay);
Assert.AreEqual(IgniteConfiguration.DefaultFailureDetectionTimeout, cfg.FailureDetectionTimeout);
Assert.AreEqual(IgniteConfiguration.DefaultClientFailureDetectionTimeout,
cfg.ClientFailureDetectionTimeout);
Assert.AreEqual(IgniteConfiguration.DefaultLongQueryWarningTimeout, cfg.LongQueryWarningTimeout);
Assert.AreEqual(IgniteConfiguration.DefaultIsLateAffinityAssignment, cfg.IsLateAffinityAssignment);
Assert.AreEqual(IgniteConfiguration.DefaultIsActiveOnStart, cfg.IsActiveOnStart);
Assert.AreEqual(IgniteConfiguration.DefaultClientConnectorConfigurationEnabled,
cfg.ClientConnectorConfigurationEnabled);
Assert.AreEqual(IgniteConfiguration.DefaultRedirectJavaConsoleOutput, cfg.RedirectJavaConsoleOutput);
Assert.AreEqual(IgniteConfiguration.DefaultAuthenticationEnabled, cfg.AuthenticationEnabled);
Assert.AreEqual(IgniteConfiguration.DefaultMvccVacuumFrequency, cfg.MvccVacuumFrequency);
Assert.AreEqual(IgniteConfiguration.DefaultMvccVacuumThreadCount, cfg.MvccVacuumThreadCount);
// Thread pools.
Assert.AreEqual(IgniteConfiguration.DefaultManagementThreadPoolSize, cfg.ManagementThreadPoolSize);
Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.PublicThreadPoolSize);
Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.StripedThreadPoolSize);
Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.ServiceThreadPoolSize);
Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.SystemThreadPoolSize);
Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.AsyncCallbackThreadPoolSize);
Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.DataStreamerThreadPoolSize);
Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.UtilityCacheThreadPoolSize);
Assert.AreEqual(IgniteConfiguration.DefaultThreadPoolSize, cfg.QueryThreadPoolSize);
}
/// <summary>
/// Checks the default properties.
/// </summary>
/// <param name="cfg">Config.</param>
private static void CheckDefaultProperties(PersistentStoreConfiguration cfg)
{
Assert.AreEqual(PersistentStoreConfiguration.DefaultTlbSize, cfg.TlbSize);
Assert.AreEqual(PersistentStoreConfiguration.DefaultCheckpointingFrequency, cfg.CheckpointingFrequency);
Assert.AreEqual(PersistentStoreConfiguration.DefaultCheckpointingThreads, cfg.CheckpointingThreads);
Assert.AreEqual(default(long), cfg.CheckpointingPageBufferSize);
Assert.AreEqual(PersistentStoreConfiguration.DefaultLockWaitTime, cfg.LockWaitTime);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWalFlushFrequency, cfg.WalFlushFrequency);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWalFsyncDelayNanos, cfg.WalFsyncDelayNanos);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWalHistorySize, cfg.WalHistorySize);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWalRecordIteratorBufferSize,
cfg.WalRecordIteratorBufferSize);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWalSegmentSize, cfg.WalSegmentSize);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWalSegments, cfg.WalSegments);
Assert.AreEqual(WalMode.Default, cfg.WalMode);
Assert.IsFalse(cfg.MetricsEnabled);
Assert.AreEqual(PersistentStoreConfiguration.DefaultSubIntervals, cfg.SubIntervals);
Assert.AreEqual(PersistentStoreConfiguration.DefaultRateTimeInterval, cfg.RateTimeInterval);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWalStorePath, cfg.WalStorePath);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWalArchivePath, cfg.WalArchivePath);
Assert.AreEqual(PersistentStoreConfiguration.DefaultCheckpointWriteOrder, cfg.CheckpointWriteOrder);
Assert.AreEqual(PersistentStoreConfiguration.DefaultWriteThrottlingEnabled, cfg.WriteThrottlingEnabled);
}
/// <summary>
/// Checks the default properties.
/// </summary>
/// <param name="cfg">Config.</param>
private static void CheckDefaultProperties(DataStorageConfiguration cfg)
{
Assert.AreEqual(DataStorageConfiguration.DefaultTlbSize, cfg.WalThreadLocalBufferSize);
Assert.AreEqual(DataStorageConfiguration.DefaultCheckpointFrequency, cfg.CheckpointFrequency);
Assert.AreEqual(DataStorageConfiguration.DefaultCheckpointThreads, cfg.CheckpointThreads);
Assert.AreEqual(DataStorageConfiguration.DefaultLockWaitTime, cfg.LockWaitTime);
Assert.AreEqual(DataStorageConfiguration.DefaultWalFlushFrequency, cfg.WalFlushFrequency);
Assert.AreEqual(DataStorageConfiguration.DefaultWalFsyncDelayNanos, cfg.WalFsyncDelayNanos);
Assert.AreEqual(DataStorageConfiguration.DefaultWalHistorySize, cfg.WalHistorySize);
Assert.AreEqual(DataStorageConfiguration.DefaultWalRecordIteratorBufferSize,
cfg.WalRecordIteratorBufferSize);
Assert.AreEqual(DataStorageConfiguration.DefaultWalSegmentSize, cfg.WalSegmentSize);
Assert.AreEqual(DataStorageConfiguration.DefaultWalSegments, cfg.WalSegments);
Assert.AreEqual(DataStorageConfiguration.DefaultWalMode, cfg.WalMode);
Assert.IsFalse(cfg.MetricsEnabled);
Assert.AreEqual(DataStorageConfiguration.DefaultMetricsSubIntervalCount, cfg.MetricsSubIntervalCount);
Assert.AreEqual(DataStorageConfiguration.DefaultMetricsRateTimeInterval, cfg.MetricsRateTimeInterval);
Assert.AreEqual(DataStorageConfiguration.DefaultWalPath, cfg.WalPath);
Assert.AreEqual(DataStorageConfiguration.DefaultWalArchivePath, cfg.WalArchivePath);
Assert.AreEqual(DataStorageConfiguration.DefaultCheckpointWriteOrder, cfg.CheckpointWriteOrder);
Assert.AreEqual(DataStorageConfiguration.DefaultWriteThrottlingEnabled, cfg.WriteThrottlingEnabled);
Assert.AreEqual(DataStorageConfiguration.DefaultSystemRegionInitialSize, cfg.SystemRegionInitialSize);
Assert.AreEqual(DataStorageConfiguration.DefaultSystemRegionMaxSize, cfg.SystemRegionMaxSize);
Assert.AreEqual(DataStorageConfiguration.DefaultPageSize, cfg.PageSize);
Assert.AreEqual(DataStorageConfiguration.DefaultConcurrencyLevel, cfg.ConcurrencyLevel);
Assert.AreEqual(DataStorageConfiguration.DefaultWalAutoArchiveAfterInactivity,
cfg.WalAutoArchiveAfterInactivity);
}
/// <summary>
/// Checks the default properties.
/// </summary>
/// <param name="cfg">Config.</param>
private static void CheckDefaultProperties(DataRegionConfiguration cfg)
{
Assert.AreEqual(DataRegionConfiguration.DefaultEmptyPagesPoolSize, cfg.EmptyPagesPoolSize);
Assert.AreEqual(DataRegionConfiguration.DefaultEvictionThreshold, cfg.EvictionThreshold);
Assert.AreEqual(DataRegionConfiguration.DefaultInitialSize, cfg.InitialSize);
Assert.AreEqual(DataRegionConfiguration.DefaultMaxSize, cfg.MaxSize);
Assert.AreEqual(DataRegionConfiguration.DefaultPersistenceEnabled, cfg.PersistenceEnabled);
Assert.AreEqual(DataRegionConfiguration.DefaultMetricsRateTimeInterval, cfg.MetricsRateTimeInterval);
Assert.AreEqual(DataRegionConfiguration.DefaultMetricsSubIntervalCount, cfg.MetricsSubIntervalCount);
Assert.AreEqual(default(long), cfg.CheckpointPageBufferSize);
}
/// <summary>
/// Checks the default properties.
/// </summary>
/// <param name="cfg">Config.</param>
private static void CheckDefaultProperties(ClientConnectorConfiguration cfg)
{
Assert.AreEqual(ClientConnectorConfiguration.DefaultPort, cfg.Port);
Assert.AreEqual(ClientConnectorConfiguration.DefaultPortRange, cfg.PortRange);
Assert.AreEqual(ClientConnectorConfiguration.DefaultMaxOpenCursorsPerConnection,
cfg.MaxOpenCursorsPerConnection);
Assert.AreEqual(ClientConnectorConfiguration.DefaultSocketBufferSize, cfg.SocketReceiveBufferSize);
Assert.AreEqual(ClientConnectorConfiguration.DefaultSocketBufferSize, cfg.SocketSendBufferSize);
Assert.AreEqual(ClientConnectorConfiguration.DefaultTcpNoDelay, cfg.TcpNoDelay);
Assert.AreEqual(ClientConnectorConfiguration.DefaultThreadPoolSize, cfg.ThreadPoolSize);
Assert.AreEqual(ClientConnectorConfiguration.DefaultIdleTimeout, cfg.IdleTimeout);
Assert.AreEqual(ClientConnectorConfiguration.DefaultThinClientEnabled, cfg.ThinClientEnabled);
Assert.AreEqual(ClientConnectorConfiguration.DefaultJdbcEnabled, cfg.JdbcEnabled);
Assert.AreEqual(ClientConnectorConfiguration.DefaultOdbcEnabled, cfg.OdbcEnabled);
}
/// <summary>
/// Checks the default properties.
/// </summary>
/// <param name="cfg">Config.</param>
private static void CheckDefaultProperties(SqlConnectorConfiguration cfg)
{
Assert.AreEqual(ClientConnectorConfiguration.DefaultPort, cfg.Port);
Assert.AreEqual(ClientConnectorConfiguration.DefaultPortRange, cfg.PortRange);
Assert.AreEqual(ClientConnectorConfiguration.DefaultMaxOpenCursorsPerConnection,
cfg.MaxOpenCursorsPerConnection);
Assert.AreEqual(ClientConnectorConfiguration.DefaultSocketBufferSize, cfg.SocketReceiveBufferSize);
Assert.AreEqual(ClientConnectorConfiguration.DefaultSocketBufferSize, cfg.SocketSendBufferSize);
Assert.AreEqual(ClientConnectorConfiguration.DefaultTcpNoDelay, cfg.TcpNoDelay);
Assert.AreEqual(ClientConnectorConfiguration.DefaultThreadPoolSize, cfg.ThreadPoolSize);
}
/// <summary>
/// Checks the default value attributes.
/// </summary>
/// <param name="obj">The object.</param>
private static void CheckDefaultValueAttributes(object obj)
{
var props = obj.GetType().GetProperties();
foreach (var prop in props.Where(p => p.Name != "SelectorsCount" && p.Name != "ReadStripesNumber" &&
!p.Name.Contains("ThreadPoolSize") && p.Name != "MaxSize" &&
p.Name != "HandshakeTimeout" && p.Name != "ConcurrencyLevel"))
{
var attr = prop.GetCustomAttributes(true).OfType<DefaultValueAttribute>().FirstOrDefault();
var propValue = prop.GetValue(obj, null);
if (attr != null)
Assert.AreEqual(attr.Value, propValue, string.Format("{0}.{1}", obj.GetType(), prop.Name));
else if (prop.PropertyType.IsValueType)
Assert.AreEqual(Activator.CreateInstance(prop.PropertyType), propValue, prop.Name);
else
Assert.IsNull(propValue);
}
}
/// <summary>
/// Gets the custom configuration.
/// </summary>
private static IgniteConfiguration GetCustomConfig()
{
// CacheConfiguration is not tested here - see CacheConfigurationTest
return new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
DiscoverySpi = new TcpDiscoverySpi
{
NetworkTimeout = TimeSpan.FromSeconds(1),
AckTimeout = TimeSpan.FromSeconds(2),
MaxAckTimeout = TimeSpan.FromSeconds(3),
SocketTimeout = TimeSpan.FromSeconds(4),
JoinTimeout = TimeSpan.FromSeconds(5),
IpFinder = new TcpDiscoveryStaticIpFinder
{
Endpoints = new[] {"127.0.0.1:49900", "127.0.0.1:49901"}
},
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
},
EncryptionSpi = new KeystoreEncryptionSpi()
{
KeySize = 192,
KeyStorePassword = "love_sex_god",
KeyStorePath = "tde.jks",
MasterKeyName = KeystoreEncryptionSpi.DefaultMasterKeyName
},
IgniteInstanceName = "gridName1",
IgniteHome = IgniteHome.Resolve(null),
IncludedEventTypes = EventType.DiscoveryAll,
MetricsExpireTime = TimeSpan.FromMinutes(7),
MetricsHistorySize = 125,
MetricsLogFrequency = TimeSpan.FromMinutes(8),
MetricsUpdateFrequency = TimeSpan.FromMinutes(9),
NetworkSendRetryCount = 54,
NetworkTimeout = TimeSpan.FromMinutes(10),
NetworkSendRetryDelay = TimeSpan.FromMinutes(11),
WorkDirectory = Path.GetTempPath(),
Localhost = "127.0.0.1",
IsDaemon = false,
IsLateAffinityAssignment = false,
UserAttributes = Enumerable.Range(1, 10).ToDictionary(x => x.ToString(), x => (object) x),
AtomicConfiguration = new AtomicConfiguration
{
CacheMode = CacheMode.Replicated,
Backups = 2,
AtomicSequenceReserveSize = 200
},
TransactionConfiguration = new TransactionConfiguration
{
DefaultTransactionConcurrency = TransactionConcurrency.Optimistic,
DefaultTimeout = TimeSpan.FromSeconds(25),
DefaultTransactionIsolation = TransactionIsolation.Serializable,
PessimisticTransactionLogLinger = TimeSpan.FromHours(1),
PessimisticTransactionLogSize = 240,
DefaultTimeoutOnPartitionMapExchange = TimeSpan.FromSeconds(25)
},
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,
ConnectionsPerNode = 12,
UsePairedConnections = true,
SharedMemoryPort = 1234,
SocketWriteTimeout = 2222,
SelectorSpins = 12,
FilterReachableAddresses = true
},
FailureDetectionTimeout = TimeSpan.FromSeconds(3.5),
SystemWorkerBlockedTimeout = TimeSpan.FromSeconds(8.5),
ClientFailureDetectionTimeout = TimeSpan.FromMinutes(12.3),
LongQueryWarningTimeout = TimeSpan.FromMinutes(1.23),
IsActiveOnStart = true,
BinaryConfiguration = new BinaryConfiguration
{
CompactFooter = false,
TypeConfigurations = new[]
{
new BinaryTypeConfiguration
{
TypeName = "myType",
IsEnum = true,
AffinityKeyFieldName = "affKey",
KeepDeserialized = false
}
}
},
// Skip cache check because with persistence the grid is not active by default.
PluginConfigurations = new[] {new TestIgnitePluginConfiguration {SkipCacheCheck = true}},
EventStorageSpi = new MemoryEventStorageSpi
{
ExpirationTimeout = TimeSpan.FromSeconds(5),
MaxEventCount = 10
},
PublicThreadPoolSize = 3,
StripedThreadPoolSize = 5,
ServiceThreadPoolSize = 6,
SystemThreadPoolSize = 7,
AsyncCallbackThreadPoolSize = 8,
ManagementThreadPoolSize = 9,
DataStreamerThreadPoolSize = 10,
UtilityCacheThreadPoolSize = 11,
QueryThreadPoolSize = 12,
SqlConnectorConfiguration = new SqlConnectorConfiguration
{
Host = "127.0.0.2",
Port = 1081,
PortRange = 3,
SocketReceiveBufferSize = 2048,
MaxOpenCursorsPerConnection = 5,
ThreadPoolSize = 4,
TcpNoDelay = false,
SocketSendBufferSize = 4096
},
ConsistentId = new MyConsistentId {Data = "abc"},
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 = Configuration.WalMode.LogOnly,
WalRecordIteratorBufferSize = 32 * 1024 * 1024,
WalSegments = 6,
WalSegmentSize = 5 * 1024 * 1024,
WalPath = Path.GetTempPath(),
MetricsEnabled = true,
MetricsSubIntervalCount = 7,
MetricsRateTimeInterval = TimeSpan.FromSeconds(9),
CheckpointWriteOrder = Configuration.CheckpointWriteOrder.Random,
WriteThrottlingEnabled = true,
SystemRegionInitialSize = 64 * 1024 * 1024,
SystemRegionMaxSize = 128 * 1024 * 1024,
ConcurrencyLevel = 1,
PageSize = 8 * 1024,
WalAutoArchiveAfterInactivity = TimeSpan.FromMinutes(5),
CheckpointReadLockTimeout = TimeSpan.FromSeconds(9.5),
DefaultDataRegionConfiguration = new DataRegionConfiguration
{
Name = "reg1",
EmptyPagesPoolSize = 50,
EvictionThreshold = 0.8,
InitialSize = 100 * 1024 * 1024,
MaxSize = 150 * 1024 * 1024,
MetricsEnabled = true,
PageEvictionMode = Configuration.DataPageEvictionMode.Random2Lru,
PersistenceEnabled = false,
MetricsRateTimeInterval = TimeSpan.FromMinutes(2),
MetricsSubIntervalCount = 6,
SwapPath = TestUtils.GetTempDirectoryName(),
CheckpointPageBufferSize = 28 * 1024 * 1024
},
DataRegionConfigurations = new[]
{
new DataRegionConfiguration
{
Name = "reg2",
EmptyPagesPoolSize = 51,
EvictionThreshold = 0.7,
InitialSize = 101 * 1024 * 1024,
MaxSize = 151 * 1024 * 1024,
MetricsEnabled = false,
PageEvictionMode = Configuration.DataPageEvictionMode.RandomLru,
PersistenceEnabled = false,
MetricsRateTimeInterval = TimeSpan.FromMinutes(3),
MetricsSubIntervalCount = 7,
SwapPath = TestUtils.GetTempDirectoryName()
}
}
},
AuthenticationEnabled = false,
MvccVacuumFrequency = 20000,
MvccVacuumThreadCount = 8,
SqlQueryHistorySize = 99,
SqlSchemas = new List<string> { "SCHEMA_3", "schema_4" }
};
}
private class MyConsistentId
{
public string Data { get; set; }
private bool Equals(MyConsistentId other)
{
return string.Equals(Data, other.Data);
}
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 Equals((MyConsistentId) obj);
}
public override int GetHashCode()
{
return (Data != null ? Data.GetHashCode() : 0);
}
public static bool operator ==(MyConsistentId left, MyConsistentId right)
{
return Equals(left, right);
}
public static bool operator !=(MyConsistentId left, MyConsistentId right)
{
return !Equals(left, right);
}
}
}
}
| |
using System.Collections.Generic;
using NUnit.Framework;
using ServiceStack.Common.Extensions;
using ServiceStack.Common.Tests.Models;
namespace ServiceStack.OrmLite.MySql.Tests
{
[TestFixture]
public class OrmLiteSelectTests
: OrmLiteTestBase
{
[Test]
public void Can_GetById_int_from_ModelWithFieldsOfDifferentTypes_table()
{
using (var db = ConnectionString.OpenDbConnection())
using (var dbCmd = db.CreateCommand())
{
dbCmd.CreateTable<ModelWithFieldsOfDifferentTypes>(true);
var rowIds = new List<int>(new[] { 1, 2, 3 });
rowIds.ForEach(x => dbCmd.Insert(ModelWithFieldsOfDifferentTypes.Create(x)));
var row = dbCmd.GetById<ModelWithFieldsOfDifferentTypes>(1);
Assert.That(row.Id, Is.EqualTo(1));
}
}
[Test]
public void Can_GetById_string_from_ModelWithOnlyStringFields_table()
{
using (var db = ConnectionString.OpenDbConnection())
using (var dbCmd = db.CreateCommand())
{
dbCmd.CreateTable<ModelWithOnlyStringFields>(true);
var rowIds = new List<string>(new[] { "id-1", "id-2", "id-3" });
rowIds.ForEach(x => dbCmd.Insert(ModelWithOnlyStringFields.Create(x)));
var row = dbCmd.GetById<ModelWithOnlyStringFields>("id-1");
Assert.That(row.Id, Is.EqualTo("id-1"));
}
}
[Test]
public void Can_GetByIds_int_from_ModelWithFieldsOfDifferentTypes_table()
{
using (var db = ConnectionString.OpenDbConnection())
using (var dbCmd = db.CreateCommand())
{
dbCmd.CreateTable<ModelWithFieldsOfDifferentTypes>(true);
var rowIds = new List<int>(new[] { 1, 2, 3 });
rowIds.ForEach(x => dbCmd.Insert(ModelWithFieldsOfDifferentTypes.Create(x)));
var rows = dbCmd.GetByIds<ModelWithFieldsOfDifferentTypes>(rowIds);
var dbRowIds = rows.ConvertAll(x => x.Id);
Assert.That(dbRowIds, Is.EquivalentTo(rowIds));
}
}
[Test]
public void Can_GetByIds_string_from_ModelWithOnlyStringFields_table()
{
using (var db = ConnectionString.OpenDbConnection())
using (var dbCmd = db.CreateCommand())
{
dbCmd.CreateTable<ModelWithOnlyStringFields>(true);
var rowIds = new List<string>(new[] { "id-1", "id-2", "id-3" });
rowIds.ForEach(x => dbCmd.Insert(ModelWithOnlyStringFields.Create(x)));
var rows = dbCmd.GetByIds<ModelWithOnlyStringFields>(rowIds);
var dbRowIds = rows.ConvertAll(x => x.Id);
Assert.That(dbRowIds, Is.EquivalentTo(rowIds));
}
}
[Test]
public void Can_select_with_filter_from_ModelWithOnlyStringFields_table()
{
using (var db = ConnectionString.OpenDbConnection())
using (var dbCmd = db.CreateCommand())
{
dbCmd.CreateTable<ModelWithOnlyStringFields>(true);
var rowIds = new List<string>(new[] { "id-1", "id-2", "id-3" });
rowIds.ForEach(x => dbCmd.Insert(ModelWithOnlyStringFields.Create(x)));
var filterRow = ModelWithOnlyStringFields.Create("id-4");
filterRow.AlbumName = "FilteredName";
dbCmd.Insert(filterRow);
var rows = dbCmd.Select<ModelWithOnlyStringFields>("AlbumName = {0}", filterRow.AlbumName);
var dbRowIds = rows.ConvertAll(x => x.Id);
Assert.That(dbRowIds, Has.Count.EqualTo(1));
Assert.That(dbRowIds[0], Is.EqualTo(filterRow.Id));
}
}
[Test]
public void Can_select_scalar_value()
{
const int n = 5;
using (var db = ConnectionString.OpenDbConnection())
using (var dbCmd = db.CreateCommand())
{
dbCmd.CreateTable<ModelWithIdAndName>(true);
n.Times(x => dbCmd.Insert(ModelWithIdAndName.Create(x)));
var count = dbCmd.GetScalar<int>("SELECT COUNT(*) FROM ModelWithIdAndName");
Assert.That(count, Is.EqualTo(n));
}
}
[Test]
public void Can_loop_each_string_from_ModelWithOnlyStringFields_table()
{
using (var db = ConnectionString.OpenDbConnection())
using (var dbCmd = db.CreateCommand())
{
dbCmd.CreateTable<ModelWithOnlyStringFields>(true);
var rowIds = new List<string>(new[] { "id-1", "id-2", "id-3" });
rowIds.ForEach(x => dbCmd.Insert(ModelWithOnlyStringFields.Create(x)));
var dbRowIds = new List<string>();
foreach (var row in dbCmd.Each<ModelWithOnlyStringFields>())
{
dbRowIds.Add(row.Id);
}
Assert.That(dbRowIds, Is.EquivalentTo(rowIds));
}
}
[Test]
public void Can_loop_each_with_filter_from_ModelWithOnlyStringFields_table()
{
using (var db = ConnectionString.OpenDbConnection())
using (var dbCmd = db.CreateCommand())
{
dbCmd.CreateTable<ModelWithOnlyStringFields>(true);
var rowIds = new List<string>(new[] { "id-1", "id-2", "id-3" });
rowIds.ForEach(x => dbCmd.Insert(ModelWithOnlyStringFields.Create(x)));
var filterRow = ModelWithOnlyStringFields.Create("id-4");
filterRow.AlbumName = "FilteredName";
dbCmd.Insert(filterRow);
var dbRowIds = new List<string>();
var rows = dbCmd.Each<ModelWithOnlyStringFields>("AlbumName = {0}", filterRow.AlbumName);
foreach (var row in rows)
{
dbRowIds.Add(row.Id);
}
Assert.That(dbRowIds, Has.Count.EqualTo(1));
Assert.That(dbRowIds[0], Is.EqualTo(filterRow.Id));
}
}
[Test]
public void Can_GetFirstColumn()
{
const int n = 5;
using (var db = ConnectionString.OpenDbConnection())
using (var dbCmd = db.CreateCommand())
{
dbCmd.CreateTable<ModelWithIdAndName>(true);
n.Times(x => dbCmd.Insert(ModelWithIdAndName.Create(x)));
var ids = dbCmd.GetFirstColumn<int>("SELECT Id FROM ModelWithIdAndName");
Assert.That(ids.Count, Is.EqualTo(n));
}
}
[Test]
public void Can_GetFirstColumnDistinct()
{
const int n = 5;
using (var db = ConnectionString.OpenDbConnection())
using (var dbCmd = db.CreateCommand())
{
dbCmd.CreateTable<ModelWithIdAndName>(true);
n.Times(x => dbCmd.Insert(ModelWithIdAndName.Create(x)));
var ids = dbCmd.GetFirstColumnDistinct<int>("SELECT Id FROM ModelWithIdAndName");
Assert.That(ids.Count, Is.EqualTo(n));
}
}
[Test]
public void Can_GetLookup()
{
const int n = 5;
using (var db = ConnectionString.OpenDbConnection())
using (var dbCmd = db.CreateCommand())
{
dbCmd.CreateTable<ModelWithIdAndName>(true);
n.Times(x => {
var row = ModelWithIdAndName.Create(x);
row.Name = x % 2 == 0 ? "OddGroup" : "EvenGroup";
dbCmd.Insert(row);
});
var lookup = dbCmd.GetLookup<string, int>("SELECT Name, Id FROM ModelWithIdAndName");
Assert.That(lookup, Has.Count.EqualTo(2));
Assert.That(lookup["OddGroup"], Has.Count.EqualTo(3));
Assert.That(lookup["EvenGroup"], Has.Count.EqualTo(2));
}
}
[Test]
public void Can_GetDictionary()
{
const int n = 5;
using (var db = ConnectionString.OpenDbConnection())
using (var dbCmd = db.CreateCommand())
{
dbCmd.CreateTable<ModelWithIdAndName>(true);
n.Times(x => dbCmd.Insert(ModelWithIdAndName.Create(x)));
var dictionary = dbCmd.GetDictionary<int, string>("SELECT Id, Name FROM ModelWithIdAndName");
Assert.That(dictionary, Has.Count.EqualTo(5));
//Console.Write(dictionary.Dump());
}
}
[Test]
public void Can_Select_subset_ModelWithIdAndName_from_ModelWithFieldsOfDifferentTypes_table()
{
using (var db = ConnectionString.OpenDbConnection())
using (var dbCmd = db.CreateCommand())
{
dbCmd.CreateTable<ModelWithFieldsOfDifferentTypes>(true);
var rowIds = new List<int>(new[] { 1, 2, 3 });
rowIds.ForEach(x => dbCmd.Insert(ModelWithFieldsOfDifferentTypes.Create(x)));
var rows = dbCmd.Select<ModelWithIdAndName>("SELECT Id, Name FROM ModelWithFieldsOfDifferentTypes");
var dbRowIds = rows.ConvertAll(x => x.Id);
Assert.That(dbRowIds, Is.EquivalentTo(rowIds));
}
}
[Test]
public void Can_Select_Into_ModelWithIdAndName_from_ModelWithFieldsOfDifferentTypes_table()
{
using (var db = ConnectionString.OpenDbConnection())
using (var dbCmd = db.CreateCommand())
{
dbCmd.CreateTable<ModelWithFieldsOfDifferentTypes>(true);
var rowIds = new List<int>(new[] { 1, 2, 3 });
rowIds.ForEach(x => dbCmd.Insert(ModelWithFieldsOfDifferentTypes.Create(x)));
var rows = dbCmd.Select<ModelWithIdAndName>(typeof(ModelWithFieldsOfDifferentTypes));
var dbRowIds = rows.ConvertAll(x => x.Id);
Assert.That(dbRowIds, Is.EquivalentTo(rowIds));
}
}
[Test]
public void Can_Select_In_for_string_value()
{
const int n = 5;
using (var db = ConnectionString.OpenDbConnection())
using (var dbCmd = db.CreateCommand())
{
dbCmd.CreateTable<ModelWithIdAndName>(true);
n.Times(x => dbCmd.Insert(ModelWithIdAndName.Create(x)));
var selectInNames = new[] {"Name1", "Name2"};
var rows = dbCmd.Select<ModelWithIdAndName>("Name IN ({0})", selectInNames.SqlInValues());
Assert.That(rows.Count, Is.EqualTo(selectInNames.Length));
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyrightD
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using OMV = OpenMetaverse;
namespace OpenSim.Region.Physics.BulletSPlugin
{
public sealed class BSLinksetCompound : BSLinkset
{
#pragma warning disable 414
private static string LogHeader = "[BULLETSIM LINKSET COMPOUND]";
#pragma warning restore 414
// Called before the simulation step to make sure the compound based linkset
// is all initialized.
// Constraint linksets are rebuilt every time.
// Note that this works for rebuilding just the root after a linkset is taken apart.
// Called at taint time!!
private bool UseBulletSimRootOffsetHack = false;
public BSLinksetCompound(BSScene scene, BSPrimLinkable parent)
: base(scene, parent)
{
LinksetImpl = LinksetImplementation.Compound;
}
public override void AddToPhysicalCollisionFlags(CollisionFlags collFlags)
{
if (LinksetRoot.PhysBody.HasPhysicalBody)
m_physicsScene.PE.AddToCollisionFlags(LinksetRoot.PhysBody, collFlags);
}
public override void ComputeAndSetLocalInertia(OMV.Vector3 inertiaFactor, float linksetMass)
{
OMV.Vector3 inertia = m_physicsScene.PE.CalculateLocalInertia(LinksetRoot.PhysShape.physShapeInfo, linksetMass);
LinksetRoot.Inertia = inertia * inertiaFactor;
m_physicsScene.PE.SetMassProps(LinksetRoot.PhysBody, linksetMass, LinksetRoot.Inertia);
m_physicsScene.PE.UpdateInertiaTensor(LinksetRoot.PhysBody);
}
// The object is going dynamic (physical). Do any setup necessary for a dynamic linkset.
// Only the state of the passed object can be modified. The rest of the linkset
// has not yet been fully constructed.
// Return 'true' if any properties updated on the passed object.
// Called at taint-time!
public override bool MakeDynamic(BSPrimLinkable child)
{
bool ret = false;
DetailLog("{0},BSLinksetCompound.MakeDynamic,call,IsRoot={1}", child.LocalID, IsRoot(child));
if (IsRoot(child))
{
// The root is going dynamic. Rebuild the linkset so parts and mass get computed properly.
Refresh(LinksetRoot);
}
return ret;
}
// The object is going static (non-physical). We do not do anything for static linksets.
// Return 'true' if any properties updated on the passed object.
// Called at taint-time!
public override bool MakeStatic(BSPrimLinkable child)
{
bool ret = false;
DetailLog("{0},BSLinksetCompound.MakeStatic,call,IsRoot={1}", child.LocalID, IsRoot(child));
child.ClearDisplacement();
if (IsRoot(child))
{
// Schedule a rebuild to verify that the root shape is set to the real shape.
Refresh(LinksetRoot);
}
return ret;
}
// When physical properties are changed the linkset needs to recalculate
// its internal properties.
public override void Refresh(BSPrimLinkable requestor)
{
// Something changed so do the rebuilding thing
ScheduleRebuild(requestor);
base.Refresh(requestor);
}
// Routine called when rebuilding the body of some member of the linkset.
// If one of the bodies is being changed, the linkset needs rebuilding.
// For instance, a linkset is built and then a mesh asset is read in and the mesh is recreated.
// Returns 'true' of something was actually removed and would need restoring
// Called at taint-time!!
public override bool RemoveDependencies(BSPrimLinkable child)
{
bool ret = false;
DetailLog("{0},BSLinksetCompound.RemoveDependencies,refreshIfChild,rID={1},rBody={2},isRoot={3}",
child.LocalID, LinksetRoot.LocalID, LinksetRoot.PhysBody, IsRoot(child));
Refresh(child);
return ret;
}
public override void RemoveFromPhysicalCollisionFlags(CollisionFlags collFlags)
{
if (LinksetRoot.PhysBody.HasPhysicalBody)
m_physicsScene.PE.RemoveFromCollisionFlags(LinksetRoot.PhysBody, collFlags);
}
public override void SetPhysicalCollisionFlags(CollisionFlags collFlags)
{
if (LinksetRoot.PhysBody.HasPhysicalBody)
m_physicsScene.PE.SetCollisionFlags(LinksetRoot.PhysBody, collFlags);
}
// ================================================================
// Changing the physical property of the linkset only needs to change the root
public override void SetPhysicalFriction(float friction)
{
if (LinksetRoot.PhysBody.HasPhysicalBody)
m_physicsScene.PE.SetFriction(LinksetRoot.PhysBody, friction);
}
public override void SetPhysicalGravity(OMV.Vector3 gravity)
{
if (LinksetRoot.PhysBody.HasPhysicalBody)
m_physicsScene.PE.SetGravity(LinksetRoot.PhysBody, gravity);
}
public override void SetPhysicalRestitution(float restitution)
{
if (LinksetRoot.PhysBody.HasPhysicalBody)
m_physicsScene.PE.SetRestitution(LinksetRoot.PhysBody, restitution);
}
// 'physicalUpdate' is true if these changes came directly from the physics engine. Don't need to rebuild then.
// Called at taint-time.
public override void UpdateProperties(UpdatedProperties whichUpdated, BSPrimLinkable updated)
{
if (!LinksetRoot.IsPhysicallyActive)
{
// No reason to do this physical stuff for static linksets.
DetailLog("{0},BSLinksetCompound.UpdateProperties,notPhysical", LinksetRoot.LocalID);
return;
}
// The user moving a child around requires the rebuilding of the linkset compound shape
// One problem is this happens when a border is crossed -- the simulator implementation
// stores the position into the group which causes the move of the object
// but it also means all the child positions get updated.
// What would cause an unnecessary rebuild so we make sure the linkset is in a
// region before bothering to do a rebuild.
if (!IsRoot(updated) && m_physicsScene.TerrainManager.IsWithinKnownTerrain(LinksetRoot.RawPosition))
{
// If a child of the linkset is updating only the position or rotation, that can be done
// without rebuilding the linkset.
// If a handle for the child can be fetch, we update the child here. If a rebuild was
// scheduled by someone else, the rebuild will just replace this setting.
bool updatedChild = false;
// Anything other than updating position or orientation usually means a physical update
// and that is caused by us updating the object.
if ((whichUpdated & ~(UpdatedProperties.Position | UpdatedProperties.Orientation)) == 0)
{
// Find the physical instance of the child
if (LinksetRoot.PhysShape.HasPhysicalShape && m_physicsScene.PE.IsCompound(LinksetRoot.PhysShape.physShapeInfo))
{
// It is possible that the linkset is still under construction and the child is not yet
// inserted into the compound shape. A rebuild of the linkset in a pre-step action will
// build the whole thing with the new position or rotation.
// The index must be checked because Bullet references the child array but does no validity
// checking of the child index passed.
int numLinksetChildren = m_physicsScene.PE.GetNumberOfCompoundChildren(LinksetRoot.PhysShape.physShapeInfo);
if (updated.LinksetChildIndex < numLinksetChildren)
{
BulletShape linksetChildShape = m_physicsScene.PE.GetChildShapeFromCompoundShapeIndex(LinksetRoot.PhysShape.physShapeInfo, updated.LinksetChildIndex);
if (linksetChildShape.HasPhysicalShape)
{
// Found the child shape within the compound shape
m_physicsScene.PE.UpdateChildTransform(LinksetRoot.PhysShape.physShapeInfo, updated.LinksetChildIndex,
updated.RawPosition - LinksetRoot.RawPosition,
updated.RawOrientation * OMV.Quaternion.Inverse(LinksetRoot.RawOrientation),
true /* shouldRecalculateLocalAabb */);
updatedChild = true;
DetailLog("{0},BSLinksetCompound.UpdateProperties,changeChildPosRot,whichUpdated={1},pos={2},rot={3}",
updated.LocalID, whichUpdated, updated.RawPosition, updated.RawOrientation);
}
else // DEBUG DEBUG
{ // DEBUG DEBUG
DetailLog("{0},BSLinksetCompound.UpdateProperties,couldNotUpdateChild,noChildShape,shape={1}",
updated.LocalID, linksetChildShape);
} // DEBUG DEBUG
}
else // DEBUG DEBUG
{ // DEBUG DEBUG
// the child is not yet in the compound shape. This is non-fatal.
DetailLog("{0},BSLinksetCompound.UpdateProperties,couldNotUpdateChild,childNotInCompoundShape,numChildren={1},index={2}",
updated.LocalID, numLinksetChildren, updated.LinksetChildIndex);
} // DEBUG DEBUG
}
else // DEBUG DEBUG
{ // DEBUG DEBUG
DetailLog("{0},BSLinksetCompound.UpdateProperties,couldNotUpdateChild,noBodyOrNotCompound", updated.LocalID);
} // DEBUG DEBUG
if (!updatedChild)
{
// If couldn't do the individual child, the linkset needs a rebuild to incorporate the new child info.
// Note: there are several ways through this code that will not update the child if
// the linkset is being rebuilt. In this case, scheduling a rebuild is a NOOP since
// there will already be a rebuild scheduled.
DetailLog("{0},BSLinksetCompound.UpdateProperties,couldNotUpdateChild.schedulingRebuild,whichUpdated={1}",
updated.LocalID, whichUpdated);
Refresh(updated);
}
}
}
}
// Add a new child to the linkset.
// Called while LinkActivity is locked.
protected override void AddChildToLinkset(BSPrimLinkable child)
{
if (!HasChild(child))
{
m_children.Add(child, new BSLinkInfo(child));
DetailLog("{0},BSLinksetCompound.AddChildToLinkset,call,child={1}", LinksetRoot.LocalID, child.LocalID);
// Rebuild the compound shape with the new child shape included
Refresh(child);
}
return;
}
// ================================================================
// Remove the specified child from the linkset.
// Safe to call even if the child is not really in the linkset.
protected override void RemoveChildFromLinkset(BSPrimLinkable child, bool inTaintTime)
{
child.ClearDisplacement();
if (m_children.Remove(child))
{
DetailLog("{0},BSLinksetCompound.RemoveChildFromLinkset,call,rID={1},rBody={2},cID={3},cBody={4}",
child.LocalID,
LinksetRoot.LocalID, LinksetRoot.PhysBody.AddrString,
child.LocalID, child.PhysBody.AddrString);
// Cause the child's body to be rebuilt and thus restored to normal operation
child.ForceBodyShapeRebuild(inTaintTime);
if (!HasAnyChildren)
{
// The linkset is now empty. The root needs rebuilding.
LinksetRoot.ForceBodyShapeRebuild(inTaintTime);
}
else
{
// Rebuild the compound shape with the child removed
Refresh(LinksetRoot);
}
}
return;
}
private void RecomputeLinksetCompound()
{
try
{
Rebuilding = true;
// No matter what is being done, force the root prim's PhysBody and PhysShape to get set
// to what they should be as if the root was not in a linkset.
// Not that bad since we only get into this routine if there are children in the linkset and
// something has been updated/changed.
// Have to do the rebuild before checking for physical because this might be a linkset
// being destructed and going non-physical.
LinksetRoot.ForceBodyShapeRebuild(true);
// There is no reason to build all this physical stuff for a non-physical or empty linkset.
if (!LinksetRoot.IsPhysicallyActive || !HasAnyChildren)
{
DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,notPhysicalOrNoChildren", LinksetRoot.LocalID);
return; // Note the 'finally' clause at the botton which will get executed.
}
// Get a new compound shape to build the linkset shape in.
BSShape linksetShape = BSShapeCompound.GetReference(m_physicsScene);
// Compute a displacement for each component so it is relative to the center-of-mass.
// Bullet presumes an object's origin (relative <0,0,0>) is its center-of-mass
OMV.Vector3 centerOfMassW = ComputeLinksetCenterOfMass();
OMV.Quaternion invRootOrientation = OMV.Quaternion.Normalize(OMV.Quaternion.Inverse(LinksetRoot.RawOrientation));
OMV.Vector3 origRootPosition = LinksetRoot.RawPosition;
// 'centerDisplacementV' is the vehicle relative distance from the simulator root position to the center-of-mass
OMV.Vector3 centerDisplacementV = (centerOfMassW - LinksetRoot.RawPosition) * invRootOrientation;
if (UseBulletSimRootOffsetHack || !BSParam.LinksetOffsetCenterOfMass)
{
// Zero everything if center-of-mass displacement is not being done.
centerDisplacementV = OMV.Vector3.Zero;
LinksetRoot.ClearDisplacement();
}
else
{
// The actual center-of-mass could have been set by the user.
centerDisplacementV = LinksetRoot.SetEffectiveCenterOfMassDisplacement(centerDisplacementV);
}
DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,COM,rootPos={1},com={2},comDisp={3}",
LinksetRoot.LocalID, origRootPosition, centerOfMassW, centerDisplacementV);
// Add the shapes of all the components of the linkset
int memberIndex = 1;
ForEachMember((cPrim) =>
{
if (IsRoot(cPrim))
{
// Root shape is always index zero.
cPrim.LinksetChildIndex = 0;
}
else
{
cPrim.LinksetChildIndex = memberIndex;
memberIndex++;
}
// Get a reference to the shape of the child for adding of that shape to the linkset compound shape
BSShape childShape = cPrim.PhysShape.GetReference(m_physicsScene, cPrim);
// Offset the child shape from the center-of-mass and rotate it to vehicle relative.
OMV.Vector3 offsetPos = (cPrim.RawPosition - origRootPosition) * invRootOrientation - centerDisplacementV;
OMV.Quaternion offsetRot = OMV.Quaternion.Normalize(cPrim.RawOrientation) * invRootOrientation;
// Add the child shape to the compound shape being built
m_physicsScene.PE.AddChildShapeToCompoundShape(linksetShape.physShapeInfo, childShape.physShapeInfo, offsetPos, offsetRot);
DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,addChild,indx={1},cShape={2},offPos={3},offRot={4}",
LinksetRoot.LocalID, cPrim.LinksetChildIndex, childShape, offsetPos, offsetRot);
// Since we are borrowing the shape of the child, disable the origional child body
if (!IsRoot(cPrim))
{
m_physicsScene.PE.AddToCollisionFlags(cPrim.PhysBody, CollisionFlags.CF_NO_CONTACT_RESPONSE);
m_physicsScene.PE.ForceActivationState(cPrim.PhysBody, ActivationState.DISABLE_SIMULATION);
// We don't want collisions from the old linkset children.
m_physicsScene.PE.RemoveFromCollisionFlags(cPrim.PhysBody, CollisionFlags.BS_SUBSCRIBE_COLLISION_EVENTS);
cPrim.PhysBody.collisionType = CollisionType.LinksetChild;
}
return false; // 'false' says to move onto the next child in the list
});
// Replace the root shape with the built compound shape.
// Object removed and added to world to get collision cache rebuilt for new shape.
LinksetRoot.PhysShape.Dereference(m_physicsScene);
LinksetRoot.PhysShape = linksetShape;
m_physicsScene.PE.RemoveObjectFromWorld(m_physicsScene.World, LinksetRoot.PhysBody);
m_physicsScene.PE.SetCollisionShape(m_physicsScene.World, LinksetRoot.PhysBody, linksetShape.physShapeInfo);
m_physicsScene.PE.AddObjectToWorld(m_physicsScene.World, LinksetRoot.PhysBody);
DetailLog("{0},BSLinksetCompound.RecomputeLinksetCompound,addBody,body={1},shape={2}",
LinksetRoot.LocalID, LinksetRoot.PhysBody, linksetShape);
// With all of the linkset packed into the root prim, it has the mass of everyone.
LinksetMass = ComputeLinksetMass();
LinksetRoot.UpdatePhysicalMassProperties(LinksetMass, true);
if (UseBulletSimRootOffsetHack)
{
// Enable the physical position updator to return the position and rotation of the root shape.
// This enables a feature in the C++ code to return the world coordinates of the first shape in the
// compound shape. This aleviates the need to offset the returned physical position by the
// center-of-mass offset.
// TODO: either debug this feature or remove it.
m_physicsScene.PE.AddToCollisionFlags(LinksetRoot.PhysBody, CollisionFlags.BS_RETURN_ROOT_COMPOUND_SHAPE);
}
}
finally
{
Rebuilding = false;
}
// See that the Aabb surrounds the new shape
m_physicsScene.PE.RecalculateCompoundShapeLocalAabb(LinksetRoot.PhysShape.physShapeInfo);
}
// ================================================================
// Schedule a refresh to happen after all the other taint processing.
private void ScheduleRebuild(BSPrimLinkable requestor)
{
DetailLog("{0},BSLinksetCompound.ScheduleRebuild,,rebuilding={1},hasChildren={2},actuallyScheduling={3}",
requestor.LocalID, Rebuilding, HasAnyChildren, (!Rebuilding && HasAnyChildren));
// When rebuilding, it is possible to set properties that would normally require a rebuild.
// If already rebuilding, don't request another rebuild.
// If a linkset with just a root prim (simple non-linked prim) don't bother rebuilding.
if (!Rebuilding && HasAnyChildren)
{
m_physicsScene.PostTaintObject("BSLinksetCompound.ScheduleRebuild", LinksetRoot.LocalID, delegate()
{
if (HasAnyChildren)
RecomputeLinksetCompound();
});
}
}
// Attempt to have Bullet track the coords of root compound shape
}
}
| |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Stratus;
using UnityEngine.Events;
using UnityEngine.AI;
using Stratus.Interfaces;
namespace Stratus.Gameplay
{
/// <summary>
/// Handles the logic for a gameplay segment
/// </summary>
[ExecuteInEditMode]
public class StratusSegmentBehaviour : StratusBehaviour, IStratusDebuggable, IStratusValidatorAggregator
{
//------------------------------------------------------------------------/
// Declarations
//------------------------------------------------------------------------/
public enum EventType
{
Enter,
Exit
}
public enum State
{
Inactive,
Entered,
Exited
}
public class BaseSegmentEvent : Stratus.StratusEvent
{
public StratusSegmentBehaviour segment { get; protected set; }
}
/// <summary>
/// Signals that this segment has been entered
/// </summary>
public class EnteredEvent : BaseSegmentEvent
{
public bool restarted = false;
public EnteredEvent(StratusSegmentBehaviour segment)
{
this.segment = segment;
}
}
/// <summary>
/// Signals that this segment has been exited
/// </summary>
public class ExitedEvent : BaseSegmentEvent
{
public ExitedEvent(StratusSegmentBehaviour segment)
{
this.segment = segment;
}
}
//------------------------------------------------------------------------/
// Fields
//------------------------------------------------------------------------/
[Tooltip("Whether to log debug output")]
public bool debug = false;
[Tooltip("The string identifier for this segment")]
public string label;
[Tooltip("The trigger system used by this segment")]
public StratusTriggerSystem triggerSystem;
[Tooltip("Whether the triggers on the trigger system are controlled by this segment")]
public bool controlTriggers = true;
[Tooltip("Whether selected objects are toggled by this segment")]
public bool toggleObjects = false;
[Tooltip("Whether to load the initial state of the objects in this segment, if already entered")]
public bool restart = true;
[Tooltip("The list of checkpoints within this segment")]
public List<StratusPositionCheckpoint> checkpoints = new List<StratusPositionCheckpoint>();
[Tooltip("Objects to be toggled on and off by this segment")]
public List<GameObject> toggledObjects = new List<GameObject>();
/// <summary>
/// Any methods to invoke when enabled
/// </summary>
[Space]
[Tooltip("Any methods to invoke when entered")]
public UnityEvent onEntered = new UnityEvent();
/// <summary>
/// Any methods to invoke when disabled
/// </summary>
[Tooltip("Any methods to invoke when exited")]
public UnityEvent onExited = new UnityEvent();
[SerializeField]
private StratusEpisodeBehaviour episode_;
//------------------------------------------------------------------------/
// Properties
//------------------------------------------------------------------------/
/// <summary>
/// The currently active segment
/// </summary>
public static StratusSegmentBehaviour current { get; protected set; }
/// <summary>
/// The initial checkpoint for this segment
/// </summary>
public StratusPositionCheckpoint initialCheckpoint => checkpoints[0];
/// <summary>
/// All currently active segments, indexed by their labels
/// </summary>
public static Dictionary<string, StratusSegmentBehaviour> available { get; private set; } = new Dictionary<string, StratusSegmentBehaviour>();
/// <summary>
/// A list of all available segments, by their labels
/// </summary>
public string[] availableLabels
{
get
{
List<string> labels = new List<string>();
foreach (var segment in available)
labels.Add(segment.Value.label);
return labels.ToArray();
}
}
/// <summary>
/// All currently active segments, unordered
/// </summary>
public static List<StratusSegmentBehaviour> availableList = new List<StratusSegmentBehaviour>();
/// <summary>
/// Whether there are any available segments
/// </summary>
public static bool hasAvailable => availableList.Count > 0;
/// <summary>
/// The episode this segment belongs to
/// </summary>
public StratusEpisodeBehaviour episode { get { return episode_; } internal set { episode_ = value; } }
/// <summary>
/// The list of stateful objects in this segment
/// </summary>
public StratusStatefulObject[] statefulObjects { get; private set; }
/// <summary>
/// The current state of this segment
/// </summary>
public State state { get; protected set; } = State.Inactive;
//------------------------------------------------------------------------/
// Messages
//------------------------------------------------------------------------/
private void OnEnable()
{
if (Application.isPlaying && !string.IsNullOrEmpty(label))
{
if (!available.ContainsKey(label))
available.Add(label, this);
}
availableList.Add(this);
}
private void OnDisable()
{
if (Application.isPlaying && !string.IsNullOrEmpty(label))
{
available.Remove(label);
}
availableList.Remove(this);
}
private void Awake()
{
if (!Application.isPlaying)
return;
statefulObjects = GetComponentsInChildren<StratusStatefulObject>();
Subscribe();
}
private void OnDestroy()
{
// If an episode has susbcribed
episode?.segments.Remove(this);
available.Remove(label);
availableList.Remove(this);
}
private void Reset()
{
triggerSystem = GetComponent<StratusTriggerSystem>();
checkpoints.AddRange(GetComponentsInChildren<StratusPositionCheckpoint>());
}
void IStratusDebuggable.Toggle(bool toggle)
{
debug = toggle;
}
StratusObjectValidation[] IStratusValidatorAggregator.Validate()
{
return StratusObjectValidation.Aggregate(triggerSystem);
}
//------------------------------------------------------------------------/
// Events
//------------------------------------------------------------------------/
private void Subscribe()
{
gameObject.Connect<EnteredEvent>(OnEnteredEvent);
gameObject.Connect<ExitedEvent>(OnExitedEvent);
}
private void OnEnteredEvent(EnteredEvent e)
{
}
private void OnExitedEvent(ExitedEvent e)
{
}
//------------------------------------------------------------------------/
// Methods
//------------------------------------------------------------------------/
/// <summary>
/// Toggles this segment on and off
/// </summary>
/// <param name="toggle"></param>
public void Toggle(bool toggle)
{
ToggleTriggers(toggle);
ToggleObjects(toggle);
}
/// <summary>
/// Suspends the behaviors in this system
/// </summary>
/// <param name="suspend"></param>
private void ToggleTriggers(bool toggle)
{
if (triggerSystem != null && controlTriggers)
triggerSystem.ToggleTriggers(toggle);
}
/// <summary>
/// Toggles the objects on/off
/// </summary>
/// <param name="toggle"></param>
private void ToggleObjects(bool toggle)
{
if (!toggleObjects)
return;
foreach (var go in toggledObjects)
{
if (go)
go.SetActive(toggle);
}
}
/// <summary>
/// Enters this segment
/// </summary>
public virtual void Enter(bool suspend = false)
{
// We will announce that this segment has been entered in a moment...
EnteredEvent e = new EnteredEvent(this);
// Inform the previous segment its been exited
if (current != null && current != this)
current.Exit();
// If the segment is currently active, let's do a restart instead
// This will set everything back to the initial state at this segment
if (state != State.Inactive && restart)
{
Restart();
e.restarted = true;
}
if (debug)
StratusDebug.Log($"Entering", this);
// Invoke the optional callbacks
if (onEntered != null) onEntered.Invoke();
// If not suspended, toggle this segment
Toggle(!suspend);
// This is now the current segment
StratusScene.Dispatch<EnteredEvent>(e);
state = State.Entered;
current = this;
}
/// <summary>
/// Exits this segment
/// </summary>
public void Exit()
{
StratusScene.Dispatch<ExitedEvent>(new ExitedEvent(this));
if (onExited != null) onExited?.Invoke();
Toggle(false);
state = State.Exited;
if (debug)
StratusDebug.Log($"Exiting", this);
}
/// <summary>
/// Restarts to the initial state of this segment, as if recently entered
/// </summary>
public virtual void Restart()
{
if (debug)
StratusDebug.Log($"Restarting", this);
// Restart the trigger system' triggers back to their initial state
if (controlTriggers)
triggerSystem.Restart();
// Load the initial state of all registered stateful objects for this segment
foreach (var stateful in statefulObjects)
stateful.LoadInitialState();
//state = State.Inactive;
}
/// <summary>
/// Translates the given object onto one of the checkpoints
/// </summary>
/// <param name="obj"></param>
public void TranslateToCheckpoint(Transform target, int index)
{
if (checkpoints.Count - 1 < index || checkpoints[index] == null)
{
StratusDebug.LogError($"No checkpoint available at index {index}", this);
return;
}
TranslateToCheckpoint(target, checkpoints[index]);
}
/// <summary>
/// Translates the given object onto one of the checkpoints
/// </summary>
/// <param name="obj"></param>
public void TranslateToCheckpoint(Transform target, StratusPositionCheckpoint checkpoint)
{
Vector3 position = checkpoint.transform.position;
var navigation = target.GetComponent<NavMeshAgent>();
if (navigation != null)
navigation.Warp(position);
else
target.position = position;
}
/// <summary>
/// Saves the state of the objects within this segment
/// </summary>
private void SaveState()
{
}
}
}
| |
// Lucene version compatibility level 4.8.1
using System;
using System.Text;
using Lucene.Net.Analysis.TokenAttributes;
using Lucene.Net.Analysis.Util;
using Lucene.Net.Util;
namespace Lucene.Net.Analysis.Miscellaneous
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Old Broken version of <see cref="WordDelimiterFilter"/>
/// </summary>
[Obsolete]
public sealed class Lucene47WordDelimiterFilter : TokenFilter
{
public const int LOWER = 0x01;
public const int UPPER = 0x02;
public const int DIGIT = 0x04;
public const int SUBWORD_DELIM = 0x08;
// combinations: for testing, not for setting bits
public const int ALPHA = 0x03;
public const int ALPHANUM = 0x07;
// LUCENENET specific - made flags into their own [Flags] enum named WordDelimiterFlags and de-nested from this type
/// <summary>
/// If not null is the set of tokens to protect from being delimited
///
/// </summary>
private readonly CharArraySet protWords;
private readonly WordDelimiterFlags flags;
private readonly ICharTermAttribute termAttribute;
private readonly IOffsetAttribute offsetAttribute;
private readonly IPositionIncrementAttribute posIncAttribute;
private readonly ITypeAttribute typeAttribute;
// used for iterating word delimiter breaks
private readonly WordDelimiterIterator iterator;
// used for concatenating runs of similar typed subwords (word,number)
private readonly WordDelimiterConcatenation concat;
// number of subwords last output by concat.
private int lastConcatCount = 0;
// used for catenate all
private readonly WordDelimiterConcatenation concatAll;
// used for accumulating position increment gaps
private int accumPosInc = 0;
private char[] savedBuffer = new char[1024];
private int savedStartOffset;
private int savedEndOffset;
private string savedType;
private bool hasSavedState = false;
// if length by start + end offsets doesn't match the term text then assume
// this is a synonym and don't adjust the offsets.
private bool hasIllegalOffsets = false;
// for a run of the same subword type within a word, have we output anything?
private bool hasOutputToken = false;
// when preserve original is on, have we output any token following it?
// this token must have posInc=0!
private bool hasOutputFollowingOriginal = false;
/// <summary>
/// Creates a new <see cref="Lucene47WordDelimiterFilter"/>
/// </summary>
/// <param name="in"> <see cref="TokenStream"/> to be filtered </param>
/// <param name="charTypeTable"> table containing character types </param>
/// <param name="configurationFlags"> Flags configuring the filter </param>
/// <param name="protWords"> If not null is the set of tokens to protect from being delimited </param>
public Lucene47WordDelimiterFilter(TokenStream @in, byte[] charTypeTable, WordDelimiterFlags configurationFlags, CharArraySet protWords)
: base(@in)
{
termAttribute = AddAttribute<ICharTermAttribute>();
offsetAttribute = AddAttribute<IOffsetAttribute>();
posIncAttribute = AddAttribute<IPositionIncrementAttribute>();
typeAttribute = AddAttribute<ITypeAttribute>();
concat = new WordDelimiterConcatenation(this);
concatAll = new WordDelimiterConcatenation(this);
this.flags = configurationFlags;
this.protWords = protWords;
this.iterator = new WordDelimiterIterator(charTypeTable, Has(WordDelimiterFlags.SPLIT_ON_CASE_CHANGE), Has(WordDelimiterFlags.SPLIT_ON_NUMERICS), Has(WordDelimiterFlags.STEM_ENGLISH_POSSESSIVE));
}
/// <summary>
/// Creates a new <see cref="Lucene47WordDelimiterFilter"/> using <see cref="WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE"/>
/// as its charTypeTable
/// </summary>
/// <param name="in"> <see cref="TokenStream"/> to be filtered </param>
/// <param name="configurationFlags"> Flags configuring the filter </param>
/// <param name="protWords"> If not null is the set of tokens to protect from being delimited </param>
public Lucene47WordDelimiterFilter(TokenStream @in, WordDelimiterFlags configurationFlags, CharArraySet protWords)
: this(@in, WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE, configurationFlags, protWords)
{
}
public override bool IncrementToken()
{
while (true)
{
if (!hasSavedState)
{
// process a new input word
if (!m_input.IncrementToken())
{
return false;
}
int termLength = termAttribute.Length;
char[] termBuffer = termAttribute.Buffer;
accumPosInc += posIncAttribute.PositionIncrement;
iterator.SetText(termBuffer, termLength);
iterator.Next();
// word of no delimiters, or protected word: just return it
if ((iterator.current == 0 && iterator.end == termLength) || (protWords != null && protWords.Contains(termBuffer, 0, termLength)))
{
posIncAttribute.PositionIncrement = accumPosInc;
accumPosInc = 0;
return true;
}
// word of simply delimiters
if (iterator.end == WordDelimiterIterator.DONE && !Has(WordDelimiterFlags.PRESERVE_ORIGINAL))
{
// if the posInc is 1, simply ignore it in the accumulation
if (posIncAttribute.PositionIncrement == 1)
{
accumPosInc--;
}
continue;
}
SaveState();
hasOutputToken = false;
hasOutputFollowingOriginal = !Has(WordDelimiterFlags.PRESERVE_ORIGINAL);
lastConcatCount = 0;
if (Has(WordDelimiterFlags.PRESERVE_ORIGINAL))
{
posIncAttribute.PositionIncrement = accumPosInc;
accumPosInc = 0;
return true;
}
}
// at the end of the string, output any concatenations
if (iterator.end == WordDelimiterIterator.DONE)
{
if (!concat.IsEmpty)
{
if (FlushConcatenation(concat))
{
return true;
}
}
if (!concatAll.IsEmpty)
{
// only if we haven't output this same combo above!
if (concatAll.subwordCount > lastConcatCount)
{
concatAll.WriteAndClear();
return true;
}
concatAll.Clear();
}
// no saved concatenations, on to the next input word
hasSavedState = false;
continue;
}
// word surrounded by delimiters: always output
if (iterator.IsSingleWord())
{
GeneratePart(true);
iterator.Next();
return true;
}
int wordType = iterator.Type;
// do we already have queued up incompatible concatenations?
if (!concat.IsEmpty && (concat.type & wordType) == 0)
{
if (FlushConcatenation(concat))
{
hasOutputToken = false;
return true;
}
hasOutputToken = false;
}
// add subwords depending upon options
if (ShouldConcatenate(wordType))
{
if (concat.IsEmpty)
{
concat.type = wordType;
}
Concatenate(concat);
}
// add all subwords (catenateAll)
if (Has(WordDelimiterFlags.CATENATE_ALL))
{
Concatenate(concatAll);
}
// if we should output the word or number part
if (ShouldGenerateParts(wordType))
{
GeneratePart(false);
iterator.Next();
return true;
}
iterator.Next();
}
}
/// <summary>
/// This method is called by a consumer before it begins consumption using
/// <see cref="IncrementToken()"/>.
/// <para/>
/// Resets this stream to a clean state. Stateful implementations must implement
/// this method so that they can be reused, just as if they had been created fresh.
/// <para/>
/// If you override this method, always call <c>base.Reset()</c>, otherwise
/// some internal state will not be correctly reset (e.g., <see cref="Tokenizer"/> will
/// throw <see cref="InvalidOperationException"/> on further usage).
/// </summary>
/// <remarks>
/// <b>NOTE:</b>
/// The default implementation chains the call to the input <see cref="TokenStream"/>, so
/// be sure to call <c>base.Reset()</c> when overriding this method.
/// </remarks>
public override void Reset()
{
base.Reset();
hasSavedState = false;
concat.Clear();
concatAll.Clear();
accumPosInc = 0;
}
// ================================================= Helper Methods ================================================
/// <summary>
/// Saves the existing attribute states
/// </summary>
private void SaveState()
{
// otherwise, we have delimiters, save state
savedStartOffset = offsetAttribute.StartOffset;
savedEndOffset = offsetAttribute.EndOffset;
// if length by start + end offsets doesn't match the term text then assume this is a synonym and don't adjust the offsets.
hasIllegalOffsets = (savedEndOffset - savedStartOffset != termAttribute.Length);
savedType = typeAttribute.Type;
if (savedBuffer.Length < termAttribute.Length)
{
savedBuffer = new char[ArrayUtil.Oversize(termAttribute.Length, RamUsageEstimator.NUM_BYTES_CHAR)];
}
Array.Copy(termAttribute.Buffer, 0, savedBuffer, 0, termAttribute.Length);
iterator.text = savedBuffer;
hasSavedState = true;
}
/// <summary>
/// Flushes the given <see cref="WordDelimiterConcatenation"/> by either writing its concat and then clearing, or just clearing.
/// </summary>
/// <param name="concatenation"> <see cref="WordDelimiterConcatenation"/> that will be flushed </param>
/// <returns> <c>true</c> if the concatenation was written before it was cleared, <c>false</c> otherwise </returns>
private bool FlushConcatenation(WordDelimiterConcatenation concatenation)
{
lastConcatCount = concatenation.subwordCount;
if (concatenation.subwordCount != 1 || !ShouldGenerateParts(concatenation.type))
{
concatenation.WriteAndClear();
return true;
}
concatenation.Clear();
return false;
}
/// <summary>
/// Determines whether to concatenate a word or number if the current word is the given type
/// </summary>
/// <param name="wordType"> Type of the current word used to determine if it should be concatenated </param>
/// <returns> <c>true</c> if concatenation should occur, <c>false</c> otherwise </returns>
private bool ShouldConcatenate(int wordType)
{
return (Has(WordDelimiterFlags.CATENATE_WORDS) && IsAlpha(wordType)) || (Has(WordDelimiterFlags.CATENATE_NUMBERS) && IsDigit(wordType));
}
/// <summary>
/// Determines whether a word/number part should be generated for a word of the given type
/// </summary>
/// <param name="wordType"> Type of the word used to determine if a word/number part should be generated </param>
/// <returns> <c>true</c> if a word/number part should be generated, <c>false</c> otherwise </returns>
private bool ShouldGenerateParts(int wordType)
{
return (Has(WordDelimiterFlags.GENERATE_WORD_PARTS) && IsAlpha(wordType)) || (Has(WordDelimiterFlags.GENERATE_NUMBER_PARTS) && IsDigit(wordType));
}
/// <summary>
/// Concatenates the saved buffer to the given WordDelimiterConcatenation
/// </summary>
/// <param name="concatenation"> WordDelimiterConcatenation to concatenate the buffer to </param>
private void Concatenate(WordDelimiterConcatenation concatenation)
{
if (concatenation.IsEmpty)
{
concatenation.startOffset = savedStartOffset + iterator.current;
}
concatenation.Append(savedBuffer, iterator.current, iterator.end - iterator.current);
concatenation.endOffset = savedStartOffset + iterator.end;
}
/// <summary>
/// Generates a word/number part, updating the appropriate attributes
/// </summary>
/// <param name="isSingleWord"> <c>true</c> if the generation is occurring from a single word, <c>false</c> otherwise </param>
private void GeneratePart(bool isSingleWord)
{
ClearAttributes();
termAttribute.CopyBuffer(savedBuffer, iterator.current, iterator.end - iterator.current);
int startOffset = savedStartOffset + iterator.current;
int endOffset = savedStartOffset + iterator.end;
if (hasIllegalOffsets)
{
// historically this filter did this regardless for 'isSingleWord',
// but we must do a sanity check:
if (isSingleWord && startOffset <= savedEndOffset)
{
offsetAttribute.SetOffset(startOffset, savedEndOffset);
}
else
{
offsetAttribute.SetOffset(savedStartOffset, savedEndOffset);
}
}
else
{
offsetAttribute.SetOffset(startOffset, endOffset);
}
posIncAttribute.PositionIncrement = Position(false);
typeAttribute.Type = savedType;
}
/// <summary>
/// Get the position increment gap for a subword or concatenation
/// </summary>
/// <param name="inject"> true if this token wants to be injected </param>
/// <returns> position increment gap </returns>
private int Position(bool inject)
{
int posInc = accumPosInc;
if (hasOutputToken)
{
accumPosInc = 0;
return inject ? 0 : Math.Max(1, posInc);
}
hasOutputToken = true;
if (!hasOutputFollowingOriginal)
{
// the first token following the original is 0 regardless
hasOutputFollowingOriginal = true;
return 0;
}
// clear the accumulated position increment
accumPosInc = 0;
return Math.Max(1, posInc);
}
/// <summary>
/// Checks if the given word type includes <see cref="ALPHA"/>
/// </summary>
/// <param name="type"> Word type to check </param>
/// <returns> <c>true</c> if the type contains <see cref="ALPHA"/>, <c>false</c> otherwise </returns>
private static bool IsAlpha(int type)
{
return (type & ALPHA) != 0;
}
/// <summary>
/// Checks if the given word type includes <see cref="DIGIT"/>
/// </summary>
/// <param name="type"> Word type to check </param>
/// <returns> <c>true</c> if the type contains <see cref="DIGIT"/>, <c>false</c> otherwise </returns>
private static bool IsDigit(int type)
{
return (type & DIGIT) != 0;
}
/// <summary>
/// Checks if the given word type includes <see cref="SUBWORD_DELIM"/>
/// </summary>
/// <param name="type"> Word type to check </param>
/// <returns> <c>true</c> if the type contains <see cref="SUBWORD_DELIM"/>, <c>false</c> otherwise </returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("CodeQuality", "IDE0051:Remove unused private members", Justification = "Obsolete class, anyway")]
private static bool IsSubwordDelim(int type)
{
return (type & SUBWORD_DELIM) != 0;
}
/// <summary>
/// Checks if the given word type includes <see cref="UPPER"/>
/// </summary>
/// <param name="type"> Word type to check </param>
/// <returns> <c>true</c> if the type contains <see cref="UPPER"/>, <c>false</c> otherwise </returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("CodeQuality", "IDE0051:Remove unused private members", Justification = "Obsolete class, anyway")]
private static bool IsUpper(int type)
{
return (type & UPPER) != 0;
}
/// <summary>
/// Determines whether the given flag is set
/// </summary>
/// <param name="flag"> Flag to see if set </param>
/// <returns> <c>true</c> if flag is set </returns>
private bool Has(WordDelimiterFlags flag)
{
return (flags & flag) != 0;
}
// ================================================= Inner Classes =================================================
/// <summary>
/// A WDF concatenated 'run'
/// </summary>
internal sealed class WordDelimiterConcatenation
{
private readonly Lucene47WordDelimiterFilter outerInstance;
public WordDelimiterConcatenation(Lucene47WordDelimiterFilter outerInstance)
{
this.outerInstance = outerInstance;
}
internal readonly StringBuilder buffer = new StringBuilder();
internal int startOffset;
internal int endOffset;
internal int type;
internal int subwordCount;
/// <summary>
/// Appends the given text of the given length, to the concetenation at the given offset
/// </summary>
/// <param name="text"> Text to append </param>
/// <param name="offset"> Offset in the concetenation to add the text </param>
/// <param name="length"> Length of the text to append </param>
internal void Append(char[] text, int offset, int length)
{
buffer.Append(text, offset, length);
subwordCount++;
}
/// <summary>
/// Writes the concatenation to the attributes
/// </summary>
private void Write()
{
outerInstance.ClearAttributes();
if (outerInstance.termAttribute.Length < buffer.Length)
{
outerInstance.termAttribute.ResizeBuffer(buffer.Length);
}
var termbuffer = outerInstance.termAttribute.Buffer;
//buffer.GetChars(0, buffer.Length, termbuffer, 0);
buffer.CopyTo(0, termbuffer, 0, buffer.Length);
outerInstance.termAttribute.Length = buffer.Length;
if (outerInstance.hasIllegalOffsets)
{
outerInstance.offsetAttribute.SetOffset(outerInstance.savedStartOffset, outerInstance.savedEndOffset);
}
else
{
outerInstance.offsetAttribute.SetOffset(startOffset, endOffset);
}
outerInstance.posIncAttribute.PositionIncrement = outerInstance.Position(true);
outerInstance.typeAttribute.Type = outerInstance.savedType;
outerInstance.accumPosInc = 0;
}
/// <summary>
/// Determines if the concatenation is empty
/// </summary>
/// <returns> <c>true</c> if the concatenation is empty, <c>false</c> otherwise </returns>
internal bool IsEmpty => buffer.Length == 0;
/// <summary>
/// Clears the concatenation and resets its state
/// </summary>
internal void Clear()
{
buffer.Length = 0;
startOffset = endOffset = type = subwordCount = 0;
}
/// <summary>
/// Convenience method for the common scenario of having to write the concetenation and then clearing its state
/// </summary>
internal void WriteAndClear()
{
Write();
Clear();
}
}
// questions:
// negative numbers? -42 indexed as just 42?
// dollar sign? $42
// percent sign? 33%
// downsides: if source text is "powershot" then a query of "PowerShot" won't match!
}
}
| |
using UnityEngine;
using UnityEditor;
public partial class SplineEditor : InstantInspector
{
private GUIStyle sceneGUIStyle = null;
private GUIStyle sceneGUIStyleToolLabel = null;
private float toolSphereAlpha = 0f;
private float toolSphereSize = 1f;
private float toolTargetSphereSize = 0f;
private float lastRealTime = 0f;
private float deltaTime = 0f;
public void OnSceneGUI( )
{
Spline spline = target as Spline;
InitSceneGUIStyles( );
CalculateTimeDelta( );
DrawSplineInfo( spline );
DrawHandles( spline );
HandleMouseInput( spline );
RegisterChanges( );
}
private void HandleMouseInput( Spline spline )
{
if( !EditorGUI.actionKey )
{
toolSphereSize = 10f;
toolSphereAlpha = 0f;
return;
}
else
{
toolSphereAlpha = Mathf.Lerp( toolSphereAlpha, 0.75f, deltaTime * 4f );
toolSphereSize = Mathf.Lerp( toolSphereSize, toolTargetSphereSize + Mathf.Sin( Time.realtimeSinceStartup * 2f ) * 0.1f, deltaTime * 15f );
}
Ray mouseRay = Camera.current.ScreenPointToRay( new Vector2( Event.current.mousePosition.x, Screen.height - Event.current.mousePosition.y - 32f ) );
float splineParam = spline.GetClosestPointParamToRay( mouseRay, 3 );
Vector3 position = spline.GetPositionOnSpline( splineParam );
float currentDistance = Vector3.Cross( mouseRay.direction, position - mouseRay.origin ).magnitude;
SplineNode selectedNode = null;
foreach( SplineNode node in spline.SplineNodes )
{
float newDistance = Vector3.Distance( node.Position, position );
if( newDistance < currentDistance || newDistance < 0.2f * HandleUtility.GetHandleSize( node.Position ) )
{
currentDistance = newDistance;
selectedNode = node;
}
}
if( selectedNode != null )
{
position = selectedNode.Position;
Handles.color = new Color( .7f, 0.15f, 0.1f, toolSphereAlpha );
Handles.SphereCap( 0, position, Quaternion.identity, HandleUtility.GetHandleSize( position ) * 0.25f * toolSphereSize );
Handles.color = Color.white;
Handles.Label( LabelPosition2D( position, 0.3f ), "Delete Node (" + selectedNode.gameObject.name + ")", sceneGUIStyleToolLabel );
toolTargetSphereSize = 1.35f;
}
else
{
Handles.color = new Color( .5f, 1f, .1f, toolSphereAlpha );
Handles.SphereCap( 0, position, Quaternion.identity, HandleUtility.GetHandleSize( position ) * 0.25f * toolSphereSize );
Handles.color = Color.white;
Handles.Label( LabelPosition2D( position, 0.3f ), "Insert Node", sceneGUIStyleToolLabel );
toolTargetSphereSize = 0.8f;
}
if( Event.current.type == EventType.mouseDown && Event.current.button == 1 )
{
Undo.RegisterSceneUndo( ( selectedNode != null ) ? "Delete Spline Node (" + selectedNode.name + ")" : "Insert Spline Node" );
if( selectedNode != null )
{
spline.RemoveSplineNode( selectedNode.gameObject );
DestroyImmediate( selectedNode.gameObject );
}
else
InsertNode( spline, splineParam );
ApplyChangesToTarget( spline );
}
HandleUtility.Repaint( );
}
private void DrawHandles( Spline spline )
{
if( Event.current.alt || EditorGUI.actionKey )
return;
if( Tools.current == Tool.None || Tools.current == Tool.View )
return;
Handles.lighting = true;
foreach( SplineNode node in spline.SplineNodes )
{
switch( Tools.current )
{
case Tool.Rotate:
Undo.SetSnapshotTarget( node.transform, "Rotate Spline Node: " + node.name );
Quaternion newRotation = Handles.RotationHandle( node.Rotation, node.Position );
Handles.color = new Color( .2f, 0.4f, 1f, 1 );
Handles.ArrowCap( 0, node.Position, Quaternion.LookRotation( node.transform.forward ), HandleUtility.GetHandleSize( node.Position ) * 0.5f );
Handles.color = new Color( .3f, 1f, .20f, 1 );
Handles.ArrowCap( 0, node.Position, Quaternion.LookRotation( node.transform.up ), HandleUtility.GetHandleSize( node.Position ) * 0.5f );
Handles.color = Color.white;
if( !GUI.changed )
break;
node.Rotation = newRotation;
EditorUtility.SetDirty( target );
break;
case Tool.Move:
case Tool.Scale:
Undo.SetSnapshotTarget( node.transform, "Move Spline Node: " + node.name );
Vector3 newPosition = Handles.PositionHandle( node.Position, (Tools.pivotRotation == PivotRotation.Global) ? Quaternion.identity : node.transform.rotation );
if( !GUI.changed )
break;
node.Position = newPosition;
EditorUtility.SetDirty( target );
break;
}
CreateSnapshot( );
}
}
private void DrawSplineInfo( Spline spline )
{
if( Event.current.alt && !Event.current.shift )
{
foreach( SplineNode splineNode in spline.SplineNodes )
Handles.Label( LabelPosition2D( splineNode.Position, -0.2f), splineNode.name, sceneGUIStyle );
foreach( SplineSegment segment in spline.SplineSegments )
{
for( int i = 0; i < 10; i++ )
{
float splineParam = segment.ConvertSegmentToSplineParamter( i/10f );
Vector3 position = spline.GetPositionOnSpline( splineParam );
Vector3 normal = spline.GetNormalToSpline( splineParam );
Handles.color = new Color( .3f, 1f, .20f, 0.75f );
Handles.ArrowCap( 0, position, Quaternion.LookRotation( normal ), HandleUtility.GetHandleSize( position ) * 0.5f );
}
}
Vector3 tangentPosition0 = spline.GetPositionOnSpline( 0 );
Handles.color = new Color( .2f, 0.4f, 1f, 1 );
Handles.ArrowCap( 0, tangentPosition0, Quaternion.LookRotation( spline.GetTangentToSpline( 0 ) ), HandleUtility.GetHandleSize( tangentPosition0 ) * 0.5f );
Vector3 tangentPosition1 = spline.GetPositionOnSpline( 1 );
Handles.ArrowCap( 0, tangentPosition1, Quaternion.LookRotation( spline.GetTangentToSpline( 1 ) ), HandleUtility.GetHandleSize( tangentPosition1 ) * 0.5f );
}
else if( Event.current.alt && Event.current.shift )
{
foreach( SplineSegment item in spline.SplineSegments )
{
Vector3 positionOnSpline = spline.GetPositionOnSpline( item.ConvertSegmentToSplineParamter( 0.5f ) );
Handles.Label( LabelPosition2D( positionOnSpline, -0.2f), item.Length.ToString( ), sceneGUIStyle );
}
Handles.Label( LabelPosition2D( spline.transform.position, -0.3f), "Length: " + spline.Length.ToString( ), sceneGUIStyle );
}
}
private void CreateSnapshot( )
{
if( Input.GetMouseButtonDown( 0 ) )
{
Undo.CreateSnapshot( );
Undo.RegisterSnapshot( );
}
}
private void InsertNode( Spline spline, float splineParam )
{
SplineNode splineNode = CreateSplineNode( "New Node", spline.GetPositionOnSpline( splineParam ), spline.GetOrientationOnSpline( splineParam ), spline.transform );
SplineSegment segment = spline.GetSplineSegment( splineParam );
int startNodeIndex = spline.splineNodesArray.IndexOf( segment.StartNode );
spline.splineNodesArray.Insert( startNodeIndex + 1, splineNode );
}
private SplineNode CreateSplineNode( string nodeName, Vector3 position, Quaternion rotation, Transform parent )
{
GameObject gameObject= new GameObject( nodeName );
gameObject.transform.position = position;
gameObject.transform.rotation = rotation;
gameObject.transform.parent = parent;
SplineNode splineNode = gameObject.AddComponent<SplineNode>( );
return splineNode;
}
private void RegisterChanges( )
{
if( GUI.changed )
ApplyChangesToTarget( target );
}
private Vector3 LabelPosition2D( Vector3 position, float offset )
{
return position - Camera.current.transform.up * HandleUtility.GetHandleSize( position ) * offset;
}
private void CalculateTimeDelta( )
{
deltaTime = Time.realtimeSinceStartup - lastRealTime;
lastRealTime = Time.realtimeSinceStartup;
deltaTime = Mathf.Clamp( deltaTime, 0, 0.1f );
}
private void InitSceneGUIStyles( )
{
if( sceneGUIStyle == null )
{
sceneGUIStyle = new GUIStyle( EditorStyles.miniTextField );
sceneGUIStyle.alignment = TextAnchor.MiddleCenter;
}
if( sceneGUIStyleToolLabel == null )
{
sceneGUIStyleToolLabel = new GUIStyle( EditorStyles.textField );
sceneGUIStyleToolLabel.alignment = TextAnchor.MiddleCenter;
sceneGUIStyleToolLabel.padding = new RectOffset( -8, -8, -2, 0 );
sceneGUIStyleToolLabel.fontSize = 20;
}
}
}
| |
namespace SagiriBot.Objects.Nsfw
{
using System;
using System.Reflection;
/// <summary>
/// The Rule34 Image Class
/// </summary>
public class Rule34Image : INsfwImage
{
/// <summary>
/// The inner preview URL.
/// </summary>
private string innerPreviewUrl;
/// <summary>
/// The inner file URL.
/// </summary>
private string innerFileUrl;
/// <summary>
/// The inner sample URL.
/// </summary>
private string innerSampleUrl;
/// <summary>
/// Gets or sets the height.
/// </summary>
/// <value>The height.</value>
public int Height { get; set; }
/// <summary>
/// Gets or sets the score.
/// </summary>
/// <value>The score.</value>
public int Score { get; set; }
/// <summary>
/// Gets or sets the file URL.
/// </summary>
/// <value>The file URL.</value>
public string File_url
{
get
{
return this.innerFileUrl;
}
set
{
this.innerFileUrl = "http:" + value;
}
}
/// <summary>
/// Gets or sets the parent identifier.
/// </summary>
/// <value>The parent identifier.</value>
public long Parent_id { get; set; }
/// <summary>
/// Gets or sets the sample URL.
/// </summary>
/// <value>The sample URL.</value>
public string Sample_url
{
get
{
return this.innerSampleUrl;
}
set
{
this.innerSampleUrl = "http:" + value;
}
}
/// <summary>
/// Gets or sets the width of the sample.
/// </summary>
/// <value>The width of the sample.</value>
public int Sample_width { get; set; }
/// <summary>
/// Gets or sets the height of the sample.
/// </summary>
/// <value>The height of the sample.</value>
public int Sample_height { get; set; }
/// <summary>
/// Gets or sets the preview URL.
/// </summary>
/// <value>The preview URL.</value>
public string Preview_url
{
get
{
return this.innerPreviewUrl;
}
set
{
this.innerPreviewUrl = "http:" + value;
}
}
/// <summary>
/// Gets or sets the rating.
/// </summary>
/// <value>The rating.</value>
public string Rating { get; set; }
/// <summary>
/// Gets or sets the tags.
/// </summary>
/// <value>The tags.</value>
public string Tags { get; set; }
/// <summary>
/// Gets or sets the identifier.
/// </summary>
/// <value>The identifier.</value>
public long Id { get; set; }
/// <summary>
/// Gets or sets the width.
/// </summary>
/// <value>The width.</value>
public int Width { get; set; }
/// <summary>
/// Gets or sets the change.
/// </summary>
/// <value>The change.</value>
public long Change { get; set; }
/// <summary>
/// Gets or sets the md5.
/// </summary>
/// <value>The md5.</value>
public string Md5 { get; set; }
/// <summary>
/// Gets or sets the creator identifier.
/// </summary>
/// <value>The creator identifier.</value>
public long Creator_id { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="T:StultBot.Objects.Rule34Image"/> has children.
/// </summary>
/// <value><c>true</c> if has children; otherwise, <c>false</c>.</value>
public bool Has_children { get; set; }
/// <summary>
/// Gets or sets the created at.
/// </summary>
/// <value>The created at.</value>
public DateTime Created_at { get; set; }
/// <summary>
/// Gets or sets the status.
/// </summary>
/// <value>The status.</value>
public string Status { get; set; }
/// <summary>
/// Gets or sets the source.
/// </summary>
/// <value>The source.</value>
public Uri Source { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="T:StultBot.Objects.Rule34Image"/> has notes.
/// </summary>
/// <value><c>true</c> if has notes; otherwise, <c>false</c>.</value>
public bool Has_notes { get; set; }
/// <summary>
/// Gets or sets a value indicating whether this <see cref="T:StultBot.Objects.Rule34Image"/> has comments.
/// </summary>
/// <value><c>true</c> if has comments; otherwise, <c>false</c>.</value>
public bool Has_comments { get; set; }
/// <summary>
/// Gets or sets the width of the preview.
/// </summary>
/// <value>The width of the preview.</value>
public int Preview_width { get; set; }
/// <summary>
/// Gets or sets the height of the preview.
/// </summary>
/// <value>The height of the preview.</value>
public int Preview_height { get; set; }
string INsfwImage.Rating => this.Rating;
string INsfwImage.FileUrl => this.File_url;
string INsfwImage.Type => "Rule34";
/// <summary>
/// Gets or sets the <see cref="T:StultBot.Objects.Rule34Image"/> with the specified propertyName.
/// </summary>
/// <param name="propertyName">Property name.</param>
/// <returns>a property</returns>
public object this[string propertyName]
{
get
{
Type rule34ImageType = typeof(Rule34Image);
PropertyInfo propInfo = rule34ImageType.GetProperty(propertyName[0].ToString().ToUpper() + propertyName.Substring(1));
return propInfo.GetValue(this, null);
}
set
{
Type rule34ImageType = typeof(Rule34Image);
PropertyInfo propInfo = rule34ImageType.GetProperty(propertyName[0].ToString().ToUpper() + propertyName.Substring(1));
if (propInfo.PropertyType == typeof(int))
{
try
{
int val = int.Parse(value.ToString());
propInfo.SetValue(this, val, null);
return;
}
catch
{
return;
}
}
if (propInfo.PropertyType == typeof(bool))
{
try
{
var val = bool.Parse(value.ToString());
propInfo.SetValue(this, val, null);
return;
}
catch
{
return;
}
}
if (propInfo.PropertyType == typeof(DateTime))
{
try
{
var val = DateTime.Parse(value.ToString());
propInfo.SetValue(this, val, null);
return;
}
catch
{
return;
}
}
if (propInfo.PropertyType == typeof(Uri))
{
try
{
var val = new Uri(value.ToString());
propInfo.SetValue(this, val, null);
return;
}
catch
{
return;
}
}
if (propInfo.PropertyType == typeof(long))
{
try
{
var val = long.Parse(value.ToString());
propInfo.SetValue(this, val, null);
return;
}
catch
{
return;
}
}
propInfo.SetValue(this, value, null);
}
}
}
}
| |
/*
* Copyright (c) 2007-2008, Second Life Reverse Engineering Team
* 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 Second Life Reverse Engineering Team nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using libsecondlife.StructuredData;
namespace libsecondlife.Packets
{
public abstract partial class Packet
{
#region Serialization/Deserialization
public static string ToXmlString(Packet packet)
{
return LLSDParser.SerializeXmlString(ToLLSD(packet));
}
public static LLSD ToLLSD(Packet packet)
{
LLSDMap body = new LLSDMap();
Type type = packet.GetType();
foreach (FieldInfo field in type.GetFields())
{
if (field.IsPublic)
{
Type blockType = field.FieldType;
if (blockType.IsArray)
{
object blockArray = field.GetValue(packet);
Array array = (Array)blockArray;
LLSDArray blockList = new LLSDArray(array.Length);
IEnumerator ie = array.GetEnumerator();
while (ie.MoveNext())
{
object block = ie.Current;
blockList.Add(BuildLLSDBlock(block));
}
body[field.Name] = blockList;
}
else
{
object block = field.GetValue(packet);
body[field.Name] = BuildLLSDBlock(block);
}
}
}
return body;
}
public static byte[] ToBinary(Packet packet)
{
return LLSDParser.SerializeBinary(ToLLSD(packet));
}
public static Packet FromXmlString(string xml)
{
System.Xml.XmlTextReader reader =
new System.Xml.XmlTextReader(new System.IO.MemoryStream(Helpers.StringToField(xml)));
return FromLLSD(LLSDParser.DeserializeXml(reader));
}
public static Packet FromLLSD(LLSD llsd)
{
// FIXME: Need the inverse of the reflection magic above done here
throw new NotImplementedException();
}
#endregion Serialization/Deserialization
/// <summary>
/// Attempts to convert an LLSD structure to a known Packet type
/// </summary>
/// <param name="capsEventName">Event name, this must match an actual
/// packet name for a Packet to be successfully built</param>
/// <param name="body">LLSD to convert to a Packet</param>
/// <returns>A Packet on success, otherwise null</returns>
public static Packet BuildPacket(string capsEventName, LLSDMap body)
{
Assembly assembly = Assembly.GetExecutingAssembly();
// Check if we have a subclass of packet with the same name as this event
Type type = assembly.GetType("libsecondlife.Packets." + capsEventName + "Packet", false);
if (type == null)
return null;
Packet packet = null;
try
{
// Create an instance of the object
packet = (Packet)Activator.CreateInstance(type);
// Iterate over all of the fields in the packet class, looking for matches in the LLSD
foreach (FieldInfo field in type.GetFields())
{
if (body.ContainsKey(field.Name))
{
Type blockType = field.FieldType;
if (blockType.IsArray)
{
LLSDArray array = (LLSDArray)body[field.Name];
Type elementType = blockType.GetElementType();
object[] blockArray = (object[])Array.CreateInstance(elementType, array.Count);
for (int i = 0; i < array.Count; i++)
{
LLSDMap map = (LLSDMap)array[i];
blockArray[i] = ParseLLSDBlock(map, elementType);
}
field.SetValue(packet, blockArray);
}
else
{
LLSDMap map = (LLSDMap)((LLSDArray)body[field.Name])[0];
field.SetValue(packet, ParseLLSDBlock(map, blockType));
}
}
}
}
catch (Exception e)
{
Logger.Log(e.Message, Helpers.LogLevel.Error, e);
}
return packet;
}
private static object ParseLLSDBlock(LLSDMap blockData, Type blockType)
{
object block = Activator.CreateInstance(blockType);
// Iterate over each field and set the value if a match was found in the LLSD
foreach (FieldInfo field in blockType.GetFields())
{
if (blockData.ContainsKey(field.Name))
{
Type fieldType = field.FieldType;
if (fieldType == typeof(ulong))
{
// ulongs come in as a byte array, convert it manually here
byte[] bytes = blockData[field.Name].AsBinary();
ulong value = Helpers.BytesToUInt64(bytes);
field.SetValue(block, value);
}
else if (fieldType == typeof(uint))
{
// uints come in as a byte array, convert it manually here
byte[] bytes = blockData[field.Name].AsBinary();
uint value = Helpers.BytesToUIntBig(bytes);
field.SetValue(block, value);
}
else if (fieldType == typeof(ushort))
{
// Just need a bit of manual typecasting love here
field.SetValue(block, (ushort)blockData[field.Name].AsInteger());
}
else if (fieldType == typeof(byte))
{
// Just need a bit of manual typecasting love here
field.SetValue(block, (byte)blockData[field.Name].AsInteger());
}
else if (fieldType == typeof(short))
{
field.SetValue(block, (short)blockData[field.Name].AsInteger());
}
else if (fieldType == typeof(string))
{
field.SetValue(block, blockData[field.Name].AsString());
}
else if (fieldType == typeof(bool))
{
field.SetValue(block, blockData[field.Name].AsBoolean());
}
else if (fieldType == typeof(float))
{
field.SetValue(block, (float)blockData[field.Name].AsReal());
}
else if (fieldType == typeof(double))
{
field.SetValue(block, blockData[field.Name].AsReal());
}
else if (fieldType == typeof(int))
{
field.SetValue(block, blockData[field.Name].AsInteger());
}
else if (fieldType == typeof(LLUUID))
{
field.SetValue(block, blockData[field.Name].AsUUID());
}
else if (fieldType == typeof(LLVector3))
{
LLVector3 vec = (LLVector3)field.GetValue(block);
vec.FromLLSD(blockData[field.Name]);
field.SetValue(block, vec);
}
else if (fieldType == typeof(LLVector4))
{
LLVector4 vec = (LLVector4)field.GetValue(block);
vec.FromLLSD(blockData[field.Name]);
field.SetValue(block, vec);
}
else if (fieldType == typeof(LLQuaternion))
{
LLQuaternion quat = (LLQuaternion)field.GetValue(block);
quat.FromLLSD(blockData[field.Name]);
field.SetValue(block, quat);
}
}
}
// Additional fields come as properties, Handle those as well.
foreach (PropertyInfo property in blockType.GetProperties())
{
if (blockData.ContainsKey(property.Name))
{
LLSDType proptype = blockData[property.Name].Type;
MethodInfo set = property.GetSetMethod();
if (proptype.Equals(LLSDType.Binary))
{
byte[] bytes = blockData[property.Name].AsBinary();
set.Invoke(block, new object[] { blockData[property.Name].AsBinary() });
}
else
set.Invoke(block, new object[] { Helpers.StringToField(blockData[property.Name].AsString()) });
}
}
return block;
}
private static LLSD BuildLLSDBlock(object block)
{
LLSDMap map = new LLSDMap();
Type blockType = block.GetType();
foreach (FieldInfo field in blockType.GetFields())
{
if (field.IsPublic)
map[field.Name] = LLSD.FromObject(field.GetValue(block));
}
foreach (PropertyInfo property in blockType.GetProperties())
{
if (property.Name != "Length")
{
map[property.Name] = LLSD.FromObject(property.GetValue(block, null));
}
}
return map;
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using System;
using System.Reflection;
namespace OpenSim.Region.CoreModules.Avatar.Dialog
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "DialogModule")]
public class DialogModule : IDialogModule, INonSharedRegionModule
{
protected Scene m_scene;
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public string Name { get { return "Dialog Module"; } }
public Type ReplaceableInterface { get { return null; } }
public void AddRegion(Scene scene)
{
m_scene = scene;
m_scene.RegisterModuleInterface<IDialogModule>(this);
}
public void Close()
{
}
/// <summary>
/// Handle an alert command from the console.
/// </summary>
/// <param name="module"></param>
/// <param name="cmdparams"></param>
public void HandleAlertConsoleCommand(string module,
string[] cmdparams)
{
if (m_scene.ConsoleScene() != null &&
m_scene.ConsoleScene() != m_scene)
{
return;
}
string message = string.Empty;
if (cmdparams[0].ToLower().Equals("alert"))
{
message = CombineParams(cmdparams, 1);
m_log.InfoFormat("[DIALOG]: Sending general alert in region {0} with message {1}",
m_scene.RegionInfo.RegionName, message);
SendGeneralAlert(message);
}
else if (cmdparams.Length > 3)
{
string firstName = cmdparams[1];
string lastName = cmdparams[2];
message = CombineParams(cmdparams, 3);
m_log.InfoFormat("[DIALOG]: Sending alert in region {0} to {1} {2} with message {3}",
m_scene.RegionInfo.RegionName, firstName, lastName,
message);
SendAlertToUser(firstName, lastName, message, false);
}
else
{
MainConsole.Instance.Output(
"Usage: alert <message> | alert-user <first> <last> <message>");
return;
}
}
public void Initialise(IConfigSource source)
{
}
public void RegionLoaded(Scene scene)
{
if (scene != m_scene)
return;
m_scene.AddCommand(
"Users", this, "alert", "alert <message>",
"Send an alert to everyone",
HandleAlertConsoleCommand);
m_scene.AddCommand(
"Users", this, "alert-user",
"alert-user <first> <last> <message>",
"Send an alert to a user",
HandleAlertConsoleCommand);
}
public void RemoveRegion(Scene scene)
{
if (scene != m_scene)
return;
m_scene.UnregisterModuleInterface<IDialogModule>(this);
}
public void SendAlertToUser(IClientAPI client, string message)
{
SendAlertToUser(client, message, false);
}
public void SendAlertToUser(IClientAPI client, string message,
bool modal)
{
client.SendAgentAlertMessage(message, modal);
}
public void SendAlertToUser(UUID agentID, string message)
{
SendAlertToUser(agentID, message, false);
}
public void SendAlertToUser(UUID agentID, string message, bool modal)
{
ScenePresence sp = m_scene.GetScenePresence(agentID);
if (sp != null)
sp.ControllingClient.SendAgentAlertMessage(message, modal);
}
public void SendAlertToUser(string firstName, string lastName,
string message, bool modal)
{
ScenePresence presence = m_scene.GetScenePresence(firstName,
lastName);
if (presence != null)
{
presence.ControllingClient.SendAgentAlertMessage(message,
modal);
}
}
public void SendDialogToUser(UUID avatarID, string objectName,
UUID objectID, UUID ownerID, string message, UUID textureID,
int ch, string[] buttonlabels)
{
UserAccount account = m_scene.UserAccountService.GetUserAccount(
m_scene.RegionInfo.ScopeID, ownerID);
string ownerFirstName, ownerLastName;
if (account != null)
{
ownerFirstName = account.FirstName;
ownerLastName = account.LastName;
}
else
{
ownerFirstName = "(unknown";
ownerLastName = "user)";
}
ScenePresence sp = m_scene.GetScenePresence(avatarID);
if (sp != null)
{
sp.ControllingClient.SendDialog(objectName, objectID, ownerID,
ownerFirstName, ownerLastName, message, textureID, ch,
buttonlabels);
}
}
public void SendGeneralAlert(string message)
{
m_scene.ForEachRootClient(delegate(IClientAPI client)
{
client.SendAlertMessage(message);
});
}
public void SendNotificationToUsersInRegion(UUID fromAvatarID,
string fromAvatarName, string message)
{
m_scene.ForEachRootClient(delegate(IClientAPI client)
{
client.SendBlueBoxMessage(fromAvatarID, fromAvatarName,
message);
});
}
public void SendTextBoxToUser(UUID avatarid, string message,
int chatChannel, string name, UUID objectid, UUID ownerid)
{
UserAccount account = m_scene.UserAccountService.GetUserAccount(
m_scene.RegionInfo.ScopeID, ownerid);
string ownerFirstName, ownerLastName;
UUID ownerID = UUID.Zero;
if (account != null)
{
ownerFirstName = account.FirstName;
ownerLastName = account.LastName;
ownerID = account.PrincipalID;
}
else
{
ownerFirstName = "(unknown";
ownerLastName = "user)";
}
ScenePresence sp = m_scene.GetScenePresence(avatarid);
if (sp != null)
{
sp.ControllingClient.SendTextBoxRequest(message, chatChannel,
name, ownerID, ownerFirstName, ownerLastName,
objectid);
}
}
public void SendUrlToUser(UUID avatarID, string objectName,
UUID objectID, UUID ownerID, bool groupOwned, string message,
string url)
{
ScenePresence sp = m_scene.GetScenePresence(avatarID);
if (sp != null)
{
sp.ControllingClient.SendLoadURL(objectName, objectID,
ownerID, groupOwned, message, url);
}
}
private string CombineParams(string[] commandParams, int pos)
{
string result = string.Empty;
for (int i = pos; i < commandParams.Length; i++)
{
result += commandParams[i] + " ";
}
return result;
}
}
}
| |
//------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------------------------
// This code was produced by a tool, ConfigPropertyGenerator.exe, by reflecting over
// System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089.
// Please add this file to the project that built the assembly.
// Doing so will provide better performance for retrieving the ConfigurationElement Properties.
// If compilation errors occur, make sure that the Properties property has not
// already been provided. If it has, decide if you want the version produced by
// this tool or by the developer.
// If build errors result, make sure the config class is marked with the partial keyword.
// To regenerate a new Properties.cs after changes to the configuration OM for
// this assembly, simply run Indigo\Suites\Configuration\Infrastructure\ConfigPropertyGenerator.
// If any changes affect this file, the suite will fail. Instructions on how to
// update Properties.cs will be included in the tests output file (ConfigPropertyGenerator.out).
using System.Configuration;
using System.Globalization;
// configType.Name: AudienceUriElement
namespace System.IdentityModel.Configuration
{
public sealed partial class AudienceUriElement
{
ConfigurationPropertyCollection properties;
protected override ConfigurationPropertyCollection Properties
{
get
{
if (this.properties == null)
{
ConfigurationPropertyCollection properties = new ConfigurationPropertyCollection();
properties.Add(new ConfigurationProperty("value", typeof(System.String), " ", null, new System.Configuration.StringValidator(1, 2147483647, null), System.Configuration.ConfigurationPropertyOptions.IsRequired | System.Configuration.ConfigurationPropertyOptions.IsKey));
this.properties = properties;
}
return this.properties;
}
}
}
}
// configType.Name: AudienceUriElementCollection
namespace System.IdentityModel.Configuration
{
public sealed partial class AudienceUriElementCollection
{
ConfigurationPropertyCollection properties;
protected override ConfigurationPropertyCollection Properties
{
get
{
if (this.properties == null)
{
ConfigurationPropertyCollection properties = new ConfigurationPropertyCollection();
properties.Add(new ConfigurationProperty("mode", typeof(System.IdentityModel.Selectors.AudienceUriMode), System.IdentityModel.Selectors.AudienceUriMode.Always, null, new System.IdentityModel.Configuration.StandardRuntimeEnumValidator(typeof(System.IdentityModel.Selectors.AudienceUriMode)), System.Configuration.ConfigurationPropertyOptions.None));
this.properties = properties;
}
return this.properties;
}
}
}
}
// configType.Name: CustomTypeElement
namespace System.IdentityModel.Configuration
{
public sealed partial class CustomTypeElement
{
ConfigurationPropertyCollection properties;
protected override ConfigurationPropertyCollection Properties
{
get
{
if (this.properties == null)
{
ConfigurationPropertyCollection properties = new ConfigurationPropertyCollection();
properties.Add(new ConfigurationProperty("type", typeof(System.Type), null, new System.Configuration.TypeNameConverter(), null, System.Configuration.ConfigurationPropertyOptions.IsRequired | System.Configuration.ConfigurationPropertyOptions.IsKey));
this.properties = properties;
}
return this.properties;
}
}
}
}
// configType.Name: IdentityModelCachesElement
namespace System.IdentityModel.Configuration
{
public sealed partial class IdentityModelCachesElement
{
ConfigurationPropertyCollection properties;
protected override ConfigurationPropertyCollection Properties
{
get
{
if (this.properties == null)
{
ConfigurationPropertyCollection properties = new ConfigurationPropertyCollection();
properties.Add(new ConfigurationProperty("tokenReplayCache", typeof(System.IdentityModel.Configuration.CustomTypeElement), null, null, null, System.Configuration.ConfigurationPropertyOptions.None));
properties.Add(new ConfigurationProperty("sessionSecurityTokenCache", typeof(System.IdentityModel.Configuration.CustomTypeElement), null, null, null, System.Configuration.ConfigurationPropertyOptions.None));
this.properties = properties;
}
return this.properties;
}
}
}
}
// configType.Name: IssuerNameRegistryElement
namespace System.IdentityModel.Configuration
{
public sealed partial class IssuerNameRegistryElement
{
ConfigurationPropertyCollection properties;
protected override ConfigurationPropertyCollection Properties
{
get
{
if (this.properties == null)
{
ConfigurationPropertyCollection properties = new ConfigurationPropertyCollection();
properties.Add(new ConfigurationProperty("type", typeof(System.String), string.Empty, null, new System.Configuration.StringValidator(0, 2147483647, null), System.Configuration.ConfigurationPropertyOptions.None));
this.properties = properties;
}
return this.properties;
}
}
}
}
// configType.Name: X509CertificateValidationElement
namespace System.IdentityModel.Configuration
{
public sealed partial class X509CertificateValidationElement
{
ConfigurationPropertyCollection properties;
protected override ConfigurationPropertyCollection Properties
{
get
{
if (this.properties == null)
{
ConfigurationPropertyCollection properties = new ConfigurationPropertyCollection();
properties.Add(new ConfigurationProperty("certificateValidationMode", typeof(System.ServiceModel.Security.X509CertificateValidationMode), System.ServiceModel.Security.X509CertificateValidationMode.PeerOrChainTrust, null, new System.IdentityModel.Configuration.StandardRuntimeEnumValidator(typeof(System.ServiceModel.Security.X509CertificateValidationMode)), System.Configuration.ConfigurationPropertyOptions.None));
properties.Add(new ConfigurationProperty("revocationMode", typeof(System.Security.Cryptography.X509Certificates.X509RevocationMode), System.Security.Cryptography.X509Certificates.X509RevocationMode.Online, null, new System.IdentityModel.Configuration.StandardRuntimeEnumValidator(typeof(System.Security.Cryptography.X509Certificates.X509RevocationMode)), System.Configuration.ConfigurationPropertyOptions.None));
properties.Add(new ConfigurationProperty("trustedStoreLocation", typeof(System.Security.Cryptography.X509Certificates.StoreLocation), System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine, null, new System.IdentityModel.Configuration.StandardRuntimeEnumValidator(typeof(System.Security.Cryptography.X509Certificates.StoreLocation)), System.Configuration.ConfigurationPropertyOptions.None));
properties.Add(new ConfigurationProperty("certificateValidator", typeof(System.IdentityModel.Configuration.CustomTypeElement), null, null, null, System.Configuration.ConfigurationPropertyOptions.None));
this.properties = properties;
}
return this.properties;
}
}
}
}
// configType.Name: SecurityTokenHandlerConfigurationElement
namespace System.IdentityModel.Configuration
{
public sealed partial class SecurityTokenHandlerConfigurationElement
{
ConfigurationPropertyCollection properties;
protected override ConfigurationPropertyCollection Properties
{
get
{
if (this.properties == null)
{
ConfigurationPropertyCollection properties = new ConfigurationPropertyCollection();
properties.Add(new ConfigurationProperty("audienceUris", typeof(System.IdentityModel.Configuration.AudienceUriElementCollection), null, null, null, System.Configuration.ConfigurationPropertyOptions.None));
properties.Add(new ConfigurationProperty("caches", typeof(System.IdentityModel.Configuration.IdentityModelCachesElement), null, null, null, System.Configuration.ConfigurationPropertyOptions.None));
properties.Add(new ConfigurationProperty("certificateValidation", typeof(System.IdentityModel.Configuration.X509CertificateValidationElement), null, null, null, System.Configuration.ConfigurationPropertyOptions.None));
properties.Add(new ConfigurationProperty("issuerNameRegistry", typeof(System.IdentityModel.Configuration.IssuerNameRegistryElement), null, null, null, System.Configuration.ConfigurationPropertyOptions.None));
properties.Add(new ConfigurationProperty("issuerTokenResolver", typeof(System.IdentityModel.Configuration.CustomTypeElement), null, null, null, System.Configuration.ConfigurationPropertyOptions.None));
properties.Add(new ConfigurationProperty("name", typeof(System.String), string.Empty, null, new System.Configuration.StringValidator(0, 2147483647, null), System.Configuration.ConfigurationPropertyOptions.IsKey));
properties.Add(new ConfigurationProperty("saveBootstrapContext", typeof(System.Boolean), false, null, null, System.Configuration.ConfigurationPropertyOptions.None));
properties.Add(new ConfigurationProperty("maximumClockSkew", typeof(System.TimeSpan), System.TimeSpan.Parse("00:05:00", CultureInfo.InvariantCulture), new System.IdentityModel.Configuration.TimeSpanOrInfiniteConverter(), new System.IdentityModel.Configuration.TimeSpanOrInfiniteValidator(System.TimeSpan.Parse("00:00:00", CultureInfo.InvariantCulture), System.TimeSpan.Parse("24.20:31:23.6470000", CultureInfo.InvariantCulture)), System.Configuration.ConfigurationPropertyOptions.None));
properties.Add(new ConfigurationProperty("serviceTokenResolver", typeof(System.IdentityModel.Configuration.CustomTypeElement), null, null, null, System.Configuration.ConfigurationPropertyOptions.None));
properties.Add(new ConfigurationProperty("tokenReplayDetection", typeof(System.IdentityModel.Configuration.TokenReplayDetectionElement), null, null, null, System.Configuration.ConfigurationPropertyOptions.None));
this.properties = properties;
}
return this.properties;
}
}
}
}
// configType.Name: SecurityTokenHandlerElementCollection
namespace System.IdentityModel.Configuration
{
public sealed partial class SecurityTokenHandlerElementCollection
{
ConfigurationPropertyCollection properties;
protected override ConfigurationPropertyCollection Properties
{
get
{
if (this.properties == null)
{
ConfigurationPropertyCollection properties = new ConfigurationPropertyCollection();
properties.Add(new ConfigurationProperty("name", typeof(System.String), string.Empty, null, new System.Configuration.StringValidator(0, 2147483647, null), System.Configuration.ConfigurationPropertyOptions.IsKey));
properties.Add(new ConfigurationProperty("securityTokenHandlerConfiguration", typeof(System.IdentityModel.Configuration.SecurityTokenHandlerConfigurationElement), null, null, null, System.Configuration.ConfigurationPropertyOptions.None));
this.properties = properties;
}
return this.properties;
}
}
}
}
// configType.Name: TokenReplayDetectionElement
namespace System.IdentityModel.Configuration
{
public sealed partial class TokenReplayDetectionElement
{
ConfigurationPropertyCollection properties;
protected override ConfigurationPropertyCollection Properties
{
get
{
if (this.properties == null)
{
ConfigurationPropertyCollection properties = new ConfigurationPropertyCollection();
properties.Add(new ConfigurationProperty("enabled", typeof(System.Boolean), false, null, null, System.Configuration.ConfigurationPropertyOptions.None));
properties.Add(new ConfigurationProperty("expirationPeriod", typeof(System.TimeSpan), System.TimeSpan.Parse("10675199.02:48:05.4775807", CultureInfo.InvariantCulture), new System.IdentityModel.Configuration.TimeSpanOrInfiniteConverter(), new System.IdentityModel.Configuration.TimeSpanOrInfiniteValidator(System.TimeSpan.Parse("00:00:00", CultureInfo.InvariantCulture), System.TimeSpan.Parse("10675199.02:48:05.4775807", CultureInfo.InvariantCulture)), System.Configuration.ConfigurationPropertyOptions.None));
this.properties = properties;
}
return this.properties;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Enumeration;
using Windows.Devices.Enumeration.Pnp;
using Windows.Storage.Streams;
using WPCordovaClassLib.Cordova;
using WPCordovaClassLib.Cordova.Commands;
using WPCordovaClassLib.Cordova.JSON;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Windows.Threading;
using System.Threading;
using System.Windows;
using Windows.UI.Core;
using System.Diagnostics;
namespace Cordova.Extension.Commands
{
public class BluetoothLePlugin : BaseCommand
{
DeviceInformationCollection bleDevices;
BluetoothLEDevice bleDevice;
int waiting_time=50;
string callbackId_sub="";
struct DeviceServices
{
public string StrUuid;
}
public struct JavaScriptServiceArgs
{
public string service;
public string[] characteristics;
public string CCCD;
public byte[] value;
public JavaScriptServiceArgs(string service,int CharaCount)
{
this.service = service;
this.characteristics = new string[CharaCount];
this.CCCD = null;
this.value = null;
}
public JavaScriptServiceArgs(string service, int CharaCount,string CCCD)
{
this.service = service;
this.characteristics = new string[CharaCount];
this.CCCD = CCCD;
this.value = null;
}
public JavaScriptServiceArgs(string service, int CharaCount, byte [] value)
{
this.service = service;
this.characteristics = new string[CharaCount];
this.CCCD = null;
this.value = new byte[value.Length];
this.value = value;
}
}
JavaScriptServiceArgs[] CurrentJSGattProfileArgs;
struct CharacteristicWithValue
{
public GattCharacteristic GattCharacteristic { get; set; }
public string Value;
}
CharacteristicWithValue [] currentDeviceCharacteristic;
BluetoothLEDevice currentDevice { get; set; }
DeviceServices[] currentDeviceServices;
public async void initialize(string options)
{
bleDevices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.GenericAccess));
if (bleDevices.Count == 0)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "{\"error\":\"No BLE devices were found or bluetooth disabled\",\"message\":\"Pair the device\"}"));
await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:", UriKind.RelativeOrAbsolute));
}
else
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, "{\"status\":\"initialized\"}"));
}
}
public async void startScan(string options)
{
bleDevice = await BluetoothLEDevice.FromIdAsync(bleDevices[0].Id);
currentDevice = bleDevice;
string CurrentDeviceAddress = currentDevice.BluetoothAddress.ToString();
string CurrentDeviceName = currentDevice.Name.ToString();
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, "{\"status\":\"scanResult\",\"address\":\"" + CurrentDeviceAddress + "\",\"name\":\"" + CurrentDeviceName + "\"}"));
}
public async void connect(string options)
{
string[] args = null;
try
{
args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(options);
}
catch (FormatException)
{
}
bleDevice = await BluetoothLEDevice.FromIdAsync(bleDevices[0].Id);
currentDevice = bleDevice;
string status;
string CurrentDeviceName=null;
string CurrentDeviceAddress = null;
PluginResult result;
if (currentDevice.ConnectionStatus.ToString() == "Disconnected")
{
await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:", UriKind.RelativeOrAbsolute));
status = "connecting";
CurrentDeviceAddress = currentDevice.BluetoothAddress.ToString();
CurrentDeviceName = currentDevice.Name.ToString();
callbackId_sub = args[args.Length-1];
result = new PluginResult(PluginResult.Status.OK, "{\"status\":\"" + status + "\",\"address\":\"" + CurrentDeviceAddress + "\",\"name\":\"" + CurrentDeviceName + "\"}");
result.KeepCallback = true;
DispatchCommandResult(result, callbackId_sub);
}
while(currentDevice.ConnectionStatus.ToString() != "Connected")
{}
status = "connected";
CurrentDeviceAddress = currentDevice.BluetoothAddress.ToString();
CurrentDeviceName = currentDevice.Name.ToString();
result = new PluginResult(PluginResult.Status.OK, "{\"status\":\"" + status + "\",\"address\":\"" + CurrentDeviceAddress + "\",\"name\":\"" + CurrentDeviceName + "\"}");
result.KeepCallback = false;
DispatchCommandResult(result, callbackId_sub);
}
public async void disconnect(string options)
{
string[] args = null;
try
{
args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(options);
}
catch (FormatException)
{
}
string status;
PluginResult result;
await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:", UriKind.RelativeOrAbsolute));
if (currentDevice.ConnectionStatus.ToString() == "Connected")
{
status = "disconnecting";
callbackId_sub = args[args.Length - 1];
result = new PluginResult(PluginResult.Status.OK, "{\"status\":\"" + status + "\"}");
result.KeepCallback = true;
DispatchCommandResult(result, callbackId_sub);
}
while (currentDevice.ConnectionStatus.ToString() != "Disconnected")
{ }
currentDevice = null;
status = "disconnected";
result = new PluginResult(PluginResult.Status.OK, "{\"status\":\"" + status + "\"}");
result.KeepCallback = false;
DispatchCommandResult(result, callbackId_sub);
}
public async void reconnect(string options)
{
string[] args = null;
try
{
args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(options);
}
catch (FormatException)
{
}
string status;
string CurrentDeviceName = null;
string CurrentDeviceAddress = null;
PluginResult result;
bleDevice = await BluetoothLEDevice.FromIdAsync(bleDevices[0].Id);
currentDevice = bleDevice;
if (currentDevice.ConnectionStatus.ToString() == "Disconnected")
{
await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:", UriKind.RelativeOrAbsolute));
status = "connecting";
CurrentDeviceAddress = currentDevice.BluetoothAddress.ToString();
CurrentDeviceName = currentDevice.Name.ToString();
callbackId_sub = args[args.Length - 1];
result = new PluginResult(PluginResult.Status.OK, "{\"status\":\"" + status + "\",\"address\":\"" + CurrentDeviceAddress + "\",\"name\":\"" + CurrentDeviceName + "\"}");
result.KeepCallback = true;
DispatchCommandResult(result, callbackId_sub);
}
while (currentDevice.ConnectionStatus.ToString() != "Connected")
{ }
status = "connected";
CurrentDeviceAddress = currentDevice.BluetoothAddress.ToString();
CurrentDeviceName = currentDevice.Name.ToString();
result = new PluginResult(PluginResult.Status.OK, "{\"status\":\"" + status + "\",\"address\":\"" + CurrentDeviceAddress + "\",\"name\":\"" + CurrentDeviceName + "\"}");
result.KeepCallback = false;
DispatchCommandResult(result, callbackId_sub);
}
public void services(string options)
{
//string DeviceAddress = currentDevice.BluetoothAddress.ToString();
//string DeviceName = currentDevice.Name.ToString();
currentDeviceServices = new DeviceServices[currentDevice.GattServices.Count];
string args = null;
try
{
args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(options)[0];
}
catch (FormatException)
{
}
string JsonString = null;
//char[] trimarray = { '\\', '[', ']', '"', ':' };
//string regex_servuuid = Regex.Match(args, @":\[""([0-9a-zA-Z_\-\s]+)""").Value.Trim(trimarray);
bool ShortUuidFlag=false;
string servuuid = null;
JavaScriptArgs(args);
for (int servJSindex = 0; servJSindex < CurrentJSGattProfileArgs.Length; servJSindex++)
{
if (CurrentJSGattProfileArgs[servJSindex].service.Length == 4)
{
servuuid = GattCharacteristic.ConvertShortIdToUuid(Convert.ToUInt16(CurrentJSGattProfileArgs[servJSindex].service, 16)).ToString();
ShortUuidFlag = true;
}
else
{
servuuid = CurrentJSGattProfileArgs[servJSindex].service;
}
for (int i = 0; i < currentDevice.GattServices.Count; i++)
{
currentDeviceServices[i].StrUuid = currentDevice.GattServices[i].Uuid.ToString();
if (servuuid == currentDeviceServices[i].StrUuid)
{
if (servJSindex == CurrentJSGattProfileArgs.Length - 1)
{
if (ShortUuidFlag)
{
JsonString = JsonString + "\"" + currentDeviceServices[i].StrUuid.Substring(4, 4) +"\"";
}
else
{
JsonString = JsonString + "\"" + currentDeviceServices[i].StrUuid + "\"";
}
}
else
{
if (ShortUuidFlag)
{
JsonString = JsonString + "\"" + currentDeviceServices[i].StrUuid.Substring(4, 4)+ "\",";
}
else
{
JsonString = JsonString + "\"" + currentDeviceServices[i].StrUuid + "\",";
}
}
}
}
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, "{\"status\":\"discoveredServices\",\"serviceUuids\":[" + JsonString + "]}"));
}
public void characteristics(string options)
{
string args = null;
try
{
args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(options)[0];
}
catch (FormatException)
{
}
string JsonString = null;
int index = 0;
string servuuid = null;
JavaScriptArgs(args);
bool ShortUuidFlag = false;
if (CurrentJSGattProfileArgs[0].service.Length == 4)
{
servuuid = GattCharacteristic.ConvertShortIdToUuid(Convert.ToUInt16(CurrentJSGattProfileArgs[0].service, 16)).ToString();
ShortUuidFlag = true;
}
else
{
servuuid = CurrentJSGattProfileArgs[0].service;
}
for (int i = 0; i < currentDeviceServices.Length; i++)
{
if (currentDeviceServices[i].StrUuid == servuuid)
{
index = i;
}
}
currentDeviceCharacteristic = new CharacteristicWithValue[CurrentJSGattProfileArgs[0].characteristics.Length];
for (int i = 0; i < CurrentJSGattProfileArgs[0].characteristics.Length; i++)
{
if (ShortUuidFlag)
{
currentDeviceCharacteristic[i].GattCharacteristic = currentDevice.GattServices[index].
GetCharacteristics(GattCharacteristic.ConvertShortIdToUuid(Convert.ToUInt16(CurrentJSGattProfileArgs[0].characteristics[i], 16)))[0];
}
else
{
currentDeviceCharacteristic[i].GattCharacteristic = currentDevice.GattServices[index].GetCharacteristics(new Guid(CurrentJSGattProfileArgs[0].characteristics[i]))[0];
}
if (i == CurrentJSGattProfileArgs[0].characteristics.Length - 1)
{
if (ShortUuidFlag)
{
JsonString = JsonString + "\"" + currentDeviceCharacteristic[i].GattCharacteristic.Uuid.ToString().Substring(4, 4) + "\"";
}
else
{
JsonString = JsonString + "\"" + currentDeviceCharacteristic[i].GattCharacteristic.Uuid.ToString() + "\"";
}
}
else
{
if (ShortUuidFlag)
{
JsonString = JsonString + "\"" + currentDeviceCharacteristic[i].GattCharacteristic.Uuid.ToString().Substring(4, 4) + "\",";
}
else
{
JsonString = JsonString + "\"" + currentDeviceCharacteristic[i].GattCharacteristic.Uuid.ToString() + "\",";
}
}
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, "{\"status\":\"discoveredCharacteristics\",\"serviceUuids\":\"" + CurrentJSGattProfileArgs[0].service + "\",\"characteristicUuids\":[" + JsonString + "]}"));
}
public void descriptors(string options)
{
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, "{\"status\":\"discoveredDescriptors\"}"));
}
public void subscribe(string options)
{
string[] args = null;
try
{
args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(options);
}
catch (FormatException)
{
}
JavaScriptArgs(args[0]);
bool ShortUuidFlag = false;
string servuuid = null;
int index = 0;
if (CurrentJSGattProfileArgs[0].service.Length == 4)
{
servuuid = GattCharacteristic.ConvertShortIdToUuid(Convert.ToUInt16(CurrentJSGattProfileArgs[0].service, 16)).ToString();
ShortUuidFlag = true;
}
else
{
servuuid = CurrentJSGattProfileArgs[0].service;
}
for (int i = 0; i < currentDeviceServices.Length; i++)
{
if (currentDeviceServices[i].StrUuid == servuuid)
{
index = i;
}
}
currentDeviceCharacteristic = new CharacteristicWithValue[CurrentJSGattProfileArgs[0].characteristics.Length];
for (int i = 0; i < CurrentJSGattProfileArgs[0].characteristics.Length; i++)
{
if (ShortUuidFlag)
{
currentDeviceCharacteristic[i].GattCharacteristic = currentDevice.GattServices[index].
GetCharacteristics(GattCharacteristic.ConvertShortIdToUuid(Convert.ToUInt16(CurrentJSGattProfileArgs[0].characteristics[i], 16)))[0];
}
else
{
currentDeviceCharacteristic[i].GattCharacteristic = currentDevice.GattServices[index].GetCharacteristics(new Guid(CurrentJSGattProfileArgs[0].characteristics[i]))[0];
}
if (currentDeviceCharacteristic[i].GattCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify))
{
Deployment.Current.Dispatcher.BeginInvoke(async () =>
{
await currentDeviceCharacteristic[i].GattCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
Thread.Sleep(waiting_time);
currentDeviceCharacteristic[i].GattCharacteristic.ValueChanged += this.characteristics_ValueChanged;
});
callbackId_sub = args[args.Length - 1];
PluginResult result = new PluginResult(PluginResult.Status.OK, "{\"status\":\"subscribed\",\"value\":\"\"}");
result.KeepCallback = true;
DispatchCommandResult(result, callbackId_sub);
break;
}
}
}
public async void write(string options)
{
string[] args = null;
try
{
args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(options);
}
catch (FormatException)
{
}
JavaScriptArgs(args[0]);
bool ShortUuidFlag = false;
string servuuid = null;
int index = 0;
if (CurrentJSGattProfileArgs[0].service.Length == 4)
{
servuuid = GattCharacteristic.ConvertShortIdToUuid(Convert.ToUInt16(CurrentJSGattProfileArgs[0].service, 16)).ToString();
ShortUuidFlag = true;
}
else
{
servuuid = CurrentJSGattProfileArgs[0].service;
}
for (int i = 0; i < currentDeviceServices.Length; i++)
{
if (currentDeviceServices[i].StrUuid == servuuid)
{
index = i;
}
}
currentDeviceCharacteristic = new CharacteristicWithValue[CurrentJSGattProfileArgs[0].characteristics.Length];
for (int i = 0; i < CurrentJSGattProfileArgs[0].characteristics.Length; i++)
{
if (ShortUuidFlag)
{
currentDeviceCharacteristic[i].GattCharacteristic = currentDevice.GattServices[index].
GetCharacteristics(GattCharacteristic.ConvertShortIdToUuid(Convert.ToUInt16(CurrentJSGattProfileArgs[0].characteristics[i], 16)))[0];
}
else
{
currentDeviceCharacteristic[i].GattCharacteristic = currentDevice.GattServices[index].GetCharacteristics(new Guid(CurrentJSGattProfileArgs[0].characteristics[i]))[0];
}
if (currentDeviceCharacteristic[i].GattCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.WriteWithoutResponse))
{
await currentDeviceCharacteristic[i].GattCharacteristic.WriteValueAsync(CurrentJSGattProfileArgs[0].value.AsBuffer(), GattWriteOption.WriteWithoutResponse);
Thread.Sleep(waiting_time);
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, "{\"status\":\"written\",\"value\":\"\"}"));
}
}
}
public void characteristics_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs EventArgs)
{
string base64String = null;
string JsonString=null;
byte[] forceData = new byte[EventArgs.CharacteristicValue.Length];
DataReader.FromBuffer(EventArgs.CharacteristicValue).ReadBytes(forceData);
Thread.Sleep(waiting_time);
base64String = System.Convert.ToBase64String(forceData, 0, forceData.Length);
//currentDeviceCharacteristic[NotifyCharaIndex].Value = currentDeviceCharacteristic[NotifyCharaIndex].Value + System.Text.Encoding.UTF8.GetString(data, 0, (int)EventArgs.CharacteristicValue.Length);
//JsonString = "\"" + System.Text.Encoding.UTF8.GetString(data, 0, (int)EventArgs.CharacteristicValue.Length)+ "\"";
JsonString = "\"" + base64String + "\"";
//JsonString = Regex.Replace(JsonString, "\n", "\\n");
//JsonString = Regex.Replace(JsonString, "\r", "\\r");
PluginResult result = new PluginResult(PluginResult.Status.OK, "{\"status\":\"subscribedResult\",\"value\":" + JsonString + "}");
result.KeepCallback = true;
DispatchCommandResult(result, callbackId_sub);
}
public async void unsubscribe(string options)
{
string[] args = null;
try
{
args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(options);
}
catch (FormatException)
{
}
JavaScriptArgs(args[0]);
bool ShortUuidFlag = false;
string servuuid = null;
int index = 0;
if (CurrentJSGattProfileArgs[0].service.Length == 4)
{
servuuid = GattCharacteristic.ConvertShortIdToUuid(Convert.ToUInt16(CurrentJSGattProfileArgs[0].service, 16)).ToString();
ShortUuidFlag = true;
}
else
{
servuuid = CurrentJSGattProfileArgs[0].service;
}
for (int i = 0; i < currentDeviceServices.Length; i++)
{
if (currentDeviceServices[i].StrUuid == servuuid)
{
index = i;
}
}
currentDeviceCharacteristic = new CharacteristicWithValue[CurrentJSGattProfileArgs[0].characteristics.Length];
for (int i = 0; i < CurrentJSGattProfileArgs[0].characteristics.Length; i++)
{
if (ShortUuidFlag)
{
currentDeviceCharacteristic[i].GattCharacteristic = currentDevice.GattServices[index].
GetCharacteristics(GattCharacteristic.ConvertShortIdToUuid(Convert.ToUInt16(CurrentJSGattProfileArgs[0].characteristics[i], 16)))[0];
}
else
{
currentDeviceCharacteristic[i].GattCharacteristic = currentDevice.GattServices[index].GetCharacteristics(new Guid(CurrentJSGattProfileArgs[0].characteristics[i]))[0];
}
if (currentDeviceCharacteristic[i].GattCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Notify))
{
await currentDeviceCharacteristic[i].GattCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.None);
Thread.Sleep(waiting_time);
currentDeviceCharacteristic[i].GattCharacteristic.ValueChanged -= this.characteristics_ValueChanged;
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, "{\"status\":\"unsubscribed\",\"value\":\"\"}"));
break;
}
}
}
public async void read(string options)
{
string args = null;
try
{
args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(options)[0];
}
catch (FormatException)
{
}
JavaScriptArgs(args);
bool ShortUuidFlag = false;
string servuuid = null;
int index = 0;
if (CurrentJSGattProfileArgs[0].service.Length == 4)
{
servuuid = GattCharacteristic.ConvertShortIdToUuid(Convert.ToUInt16(CurrentJSGattProfileArgs[0].service, 16)).ToString();
ShortUuidFlag = true;
}
else
{
servuuid = CurrentJSGattProfileArgs[0].service;
}
for (int i = 0; i < currentDeviceServices.Length; i++)
{
if (currentDeviceServices[i].StrUuid == servuuid)
{
index = i;
}
}
currentDeviceCharacteristic = new CharacteristicWithValue[CurrentJSGattProfileArgs[0].characteristics.Length];
for (int i = 0; i < CurrentJSGattProfileArgs[0].characteristics.Length; i++)
{
if (ShortUuidFlag)
{
currentDeviceCharacteristic[i].GattCharacteristic = currentDevice.GattServices[index].
GetCharacteristics(GattCharacteristic.ConvertShortIdToUuid(Convert.ToUInt16(CurrentJSGattProfileArgs[0].characteristics[i], 16)))[0];
}
else
{
currentDeviceCharacteristic[i].GattCharacteristic = currentDevice.GattServices[index].GetCharacteristics(new Guid(CurrentJSGattProfileArgs[0].characteristics[i]))[0];
}
try
{
//Read
string base64String = null;
if (currentDeviceCharacteristic[i].GattCharacteristic.CharacteristicProperties.HasFlag(GattCharacteristicProperties.Read))
{
var result = await currentDeviceCharacteristic[i].GattCharacteristic.ReadValueAsync(BluetoothCacheMode.Uncached);
if (result.Status == GattCommunicationStatus.Success)
{
byte[] forceData = new byte[result.Value.Length];
DataReader.FromBuffer(result.Value).ReadBytes(forceData);
try
{
base64String = System.Convert.ToBase64String(forceData, 0, forceData.Length);
}
catch (System.ArgumentNullException)
{
}
}
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, "{\"status\":\"read\",\"value\":\"" + base64String + "\"}"));
break;
}
catch (Exception ex)
{
}
}
}
public async void readDescriptor(string options)
{
string[] args = null;
try
{
args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(options);
}
catch (FormatException)
{
}
JavaScriptArgs(args[0]);
bool ShortUuidFlag = false;
string base64String = null;
string servuuid = null;
int index = 0;
if (CurrentJSGattProfileArgs[0].service.Length == 4)
{
servuuid = GattCharacteristic.ConvertShortIdToUuid(Convert.ToUInt16(CurrentJSGattProfileArgs[0].service, 16)).ToString();
ShortUuidFlag = true;
}
else
{
servuuid = CurrentJSGattProfileArgs[0].service;
}
for (int i = 0; i < currentDeviceServices.Length; i++)
{
if (currentDeviceServices[i].StrUuid == servuuid)
{
index = i;
}
}
currentDeviceCharacteristic = new CharacteristicWithValue[CurrentJSGattProfileArgs[0].characteristics.Length];
for (int i = 0; i < CurrentJSGattProfileArgs[0].characteristics.Length; i++)
{
if (ShortUuidFlag)
{
currentDeviceCharacteristic[i].GattCharacteristic = currentDevice.GattServices[index].
GetCharacteristics(GattCharacteristic.ConvertShortIdToUuid(Convert.ToUInt16(CurrentJSGattProfileArgs[0].characteristics[i], 16)))[0];
}
else
{
currentDeviceCharacteristic[i].GattCharacteristic = currentDevice.GattServices[index].GetCharacteristics(new Guid(CurrentJSGattProfileArgs[0].characteristics[i]))[0];
}
var CCCD = await currentDeviceCharacteristic[i].GattCharacteristic.ReadClientCharacteristicConfigurationDescriptorAsync();
switch (CCCD.ClientCharacteristicConfigurationDescriptor.ToString())
{
case "None":
{
base64String = System.Convert.ToBase64String(new byte[2] { 0x00,0x00 }, 0, 2);
break;
}
case "Notify":
{
base64String = System.Convert.ToBase64String(new byte[2] {0x01,0x00}, 0, 2);
break;
}
case "Indicate":
{
base64String = System.Convert.ToBase64String(new byte[2] { 0x02,0x00 }, 0, 2);
break;
}
}
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, "{\"status\":\"readDescriptor\",\"value\":\"" + base64String + "\"}"));
break;
}
}
public void close(string options)
{
bleDevices = null;
currentDevice = null;
currentDeviceServices = null;
DispatchCommandResult(new PluginResult(PluginResult.Status.OK, "{\"status\":\"closed\"}"));
}
public void JavaScriptArgs (string args)
{
List<string> services = new List<string>();
List<string> characteristics = new List<string>();
List<string> CCCD = new List<string>();
string charavalue = null;
bool servicflag = false;
bool charcterflag = false;
bool CCCDflag= false;
bool valueflag = false;
char[] trimarray = { '\\', '[', ']', '"', ':' };
Regex r = new Regex(@"""([0-9a-zA-Z_\-\s]+)""");
Match m = r.Match(args);
bool scanning = true;
string value = m.Value.Trim(trimarray);
while (scanning)
{
switch (value)
{
case "serviceUuids":
{
servicflag = true;
charcterflag = false;
CCCDflag = false;
valueflag = false;
m = m.NextMatch();
value = m.Value.Trim(trimarray);
break;
}
case "serviceUuid":
{
servicflag = true;
charcterflag = false;
CCCDflag = false;
valueflag = false;
m = m.NextMatch();
value = m.Value.Trim(trimarray);
break;
}
case "characteristicUuids":
{
servicflag = false;
charcterflag = true;
CCCDflag = false;
valueflag = false;
m = m.NextMatch();
value = m.Value.Trim(trimarray);
break;
}
case "characteristicUuid":
{
servicflag = false;
charcterflag = true;
CCCDflag = false;
valueflag = false;
m = m.NextMatch();
value = m.Value.Trim(trimarray);
break;
}
case "descriptorUuid":
{
servicflag = false;
charcterflag = false;
CCCDflag = true;
valueflag = false;
m = m.NextMatch();
value = m.Value.Trim(trimarray);
break;
}
case "value":
{
servicflag = false;
charcterflag = false;
CCCDflag = false;
valueflag = true;
m = m.NextMatch();
value = m.Value.Trim(trimarray);
break;
}
default:
{
if (value == "")
{
scanning = false;
break;
}
else
{
if (servicflag)
services.Add(value);
else if (charcterflag)
characteristics.Add(value);
else if (CCCDflag)
CCCD.Add(value);
else if (valueflag)
charavalue = value;
m = m.NextMatch();
value = m.Value.Trim(trimarray);
break;
}
}
}
}
CurrentJSGattProfileArgs = new JavaScriptServiceArgs[services.Count];
for (int i = 0; i < services.Count; i++)
{
if (CCCD.Count == 0 && charavalue==null)
CurrentJSGattProfileArgs[i] = new JavaScriptServiceArgs(services[i],characteristics.Count);
else if(CCCD.Count!=0)
CurrentJSGattProfileArgs[i] = new JavaScriptServiceArgs(services[i],characteristics.Count,CCCD[0]);
else if (charavalue!=null)
CurrentJSGattProfileArgs[i] = new JavaScriptServiceArgs(services[i], characteristics.Count, System.Text.Encoding.UTF8.GetBytes(charavalue));
for (int j = 0; j < characteristics.Count; j++)
{
CurrentJSGattProfileArgs[i].characteristics[j] = characteristics[j];
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using Avalonia.Platform;
namespace Avalonia.Media
{
/// <summary>
/// Parses a path markup string.
/// </summary>
public class PathMarkupParser : IDisposable
{
private static readonly Dictionary<char, Command> s_commands =
new Dictionary<char, Command>
{
{ 'F', Command.FillRule },
{ 'M', Command.Move },
{ 'L', Command.Line },
{ 'H', Command.HorizontalLine },
{ 'V', Command.VerticalLine },
{ 'Q', Command.QuadraticBezierCurve },
{ 'T', Command.SmoothQuadraticBezierCurve },
{ 'C', Command.CubicBezierCurve },
{ 'S', Command.SmoothCubicBezierCurve },
{ 'A', Command.Arc },
{ 'Z', Command.Close },
};
private IGeometryContext _geometryContext;
private Point _currentPoint;
private Point? _beginFigurePoint;
private Point? _previousControlPoint;
private bool _isOpen;
private bool _isDisposed;
/// <summary>
/// Initializes a new instance of the <see cref="PathMarkupParser"/> class.
/// </summary>
/// <param name="geometryContext">The geometry context.</param>
/// <exception cref="ArgumentNullException">geometryContext</exception>
public PathMarkupParser(IGeometryContext geometryContext)
{
if (geometryContext == null)
{
throw new ArgumentNullException(nameof(geometryContext));
}
_geometryContext = geometryContext;
}
private enum Command
{
None,
FillRule,
Move,
Line,
HorizontalLine,
VerticalLine,
CubicBezierCurve,
QuadraticBezierCurve,
SmoothCubicBezierCurve,
SmoothQuadraticBezierCurve,
Arc,
Close
}
void IDisposable.Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (_isDisposed)
{
return;
}
if (disposing)
{
_geometryContext = null;
}
_isDisposed = true;
}
private static Point MirrorControlPoint(Point controlPoint, Point center)
{
var dir = controlPoint - center;
return center + -dir;
}
/// <summary>
/// Parses the specified path data and writes the result to the geometryContext of this instance.
/// </summary>
/// <param name="pathData">The path data.</param>
public void Parse(string pathData)
{
var span = pathData.AsSpan();
_currentPoint = new Point();
while(!span.IsEmpty)
{
if(!ReadCommand(ref span, out var command, out var relative))
{
break;
}
bool initialCommand = true;
do
{
if (!initialCommand)
{
span = ReadSeparator(span);
}
switch (command)
{
case Command.None:
break;
case Command.FillRule:
SetFillRule(ref span);
break;
case Command.Move:
AddMove(ref span, relative);
break;
case Command.Line:
AddLine(ref span, relative);
break;
case Command.HorizontalLine:
AddHorizontalLine(ref span, relative);
break;
case Command.VerticalLine:
AddVerticalLine(ref span, relative);
break;
case Command.CubicBezierCurve:
AddCubicBezierCurve(ref span, relative);
break;
case Command.QuadraticBezierCurve:
AddQuadraticBezierCurve(ref span, relative);
break;
case Command.SmoothCubicBezierCurve:
AddSmoothCubicBezierCurve(ref span, relative);
break;
case Command.SmoothQuadraticBezierCurve:
AddSmoothQuadraticBezierCurve(ref span, relative);
break;
case Command.Arc:
AddArc(ref span, relative);
break;
case Command.Close:
CloseFigure();
break;
default:
throw new NotSupportedException("Unsupported command");
}
initialCommand = false;
} while (PeekArgument(span));
}
if (_isOpen)
{
_geometryContext.EndFigure(false);
}
}
private void CreateFigure()
{
if (_isOpen)
{
_geometryContext.EndFigure(false);
}
_geometryContext.BeginFigure(_currentPoint);
_beginFigurePoint = _currentPoint;
_isOpen = true;
}
private void SetFillRule(ref ReadOnlySpan<char> span)
{
if (!ReadArgument(ref span, out var fillRule) || fillRule.Length != 1)
{
throw new InvalidDataException("Invalid fill rule.");
}
FillRule rule;
switch (fillRule[0])
{
case '0':
rule = FillRule.EvenOdd;
break;
case '1':
rule = FillRule.NonZero;
break;
default:
throw new InvalidDataException("Invalid fill rule");
}
_geometryContext.SetFillRule(rule);
}
private void CloseFigure()
{
if (_isOpen)
{
_geometryContext.EndFigure(true);
if (_beginFigurePoint != null)
{
_currentPoint = _beginFigurePoint.Value;
_beginFigurePoint = null;
}
}
_previousControlPoint = null;
_isOpen = false;
}
private void AddMove(ref ReadOnlySpan<char> span, bool relative)
{
var currentPoint = relative
? ReadRelativePoint(ref span, _currentPoint)
: ReadPoint(ref span);
_currentPoint = currentPoint;
CreateFigure();
while (PeekArgument(span))
{
span = ReadSeparator(span);
AddLine(ref span, relative);
}
}
private void AddLine(ref ReadOnlySpan<char> span, bool relative)
{
_currentPoint = relative
? ReadRelativePoint(ref span, _currentPoint)
: ReadPoint(ref span);
if (!_isOpen)
{
CreateFigure();
}
_geometryContext.LineTo(_currentPoint);
}
private void AddHorizontalLine(ref ReadOnlySpan<char> span, bool relative)
{
_currentPoint = relative
? new Point(_currentPoint.X + ReadDouble(ref span), _currentPoint.Y)
: _currentPoint.WithX(ReadDouble(ref span));
if (!_isOpen)
{
CreateFigure();
}
_geometryContext.LineTo(_currentPoint);
}
private void AddVerticalLine(ref ReadOnlySpan<char> span, bool relative)
{
_currentPoint = relative
? new Point(_currentPoint.X, _currentPoint.Y + ReadDouble(ref span))
: _currentPoint.WithY(ReadDouble(ref span));
if (!_isOpen)
{
CreateFigure();
}
_geometryContext.LineTo(_currentPoint);
}
private void AddCubicBezierCurve(ref ReadOnlySpan<char> span, bool relative)
{
var point1 = relative
? ReadRelativePoint(ref span, _currentPoint)
: ReadPoint(ref span);
span = ReadSeparator(span);
var point2 = relative
? ReadRelativePoint(ref span, _currentPoint)
: ReadPoint(ref span);
_previousControlPoint = point2;
span = ReadSeparator(span);
var point3 = relative
? ReadRelativePoint(ref span, _currentPoint)
: ReadPoint(ref span);
if (!_isOpen)
{
CreateFigure();
}
_geometryContext.CubicBezierTo(point1, point2, point3);
_currentPoint = point3;
}
private void AddQuadraticBezierCurve(ref ReadOnlySpan<char> span, bool relative)
{
var start = relative
? ReadRelativePoint(ref span, _currentPoint)
: ReadPoint(ref span);
_previousControlPoint = start;
span = ReadSeparator(span);
var end = relative
? ReadRelativePoint(ref span, _currentPoint)
: ReadPoint(ref span);
if (!_isOpen)
{
CreateFigure();
}
_geometryContext.QuadraticBezierTo(start, end);
_currentPoint = end;
}
private void AddSmoothCubicBezierCurve(ref ReadOnlySpan<char> span, bool relative)
{
var point2 = relative
? ReadRelativePoint(ref span, _currentPoint)
: ReadPoint(ref span);
span = ReadSeparator(span);
var end = relative
? ReadRelativePoint(ref span, _currentPoint)
: ReadPoint(ref span);
if (_previousControlPoint != null)
{
_previousControlPoint = MirrorControlPoint((Point)_previousControlPoint, _currentPoint);
}
if (!_isOpen)
{
CreateFigure();
}
_geometryContext.CubicBezierTo(_previousControlPoint ?? _currentPoint, point2, end);
_previousControlPoint = point2;
_currentPoint = end;
}
private void AddSmoothQuadraticBezierCurve(ref ReadOnlySpan<char> span, bool relative)
{
var end = relative
? ReadRelativePoint(ref span, _currentPoint)
: ReadPoint(ref span);
if (_previousControlPoint != null)
{
_previousControlPoint = MirrorControlPoint((Point)_previousControlPoint, _currentPoint);
}
if (!_isOpen)
{
CreateFigure();
}
_geometryContext.QuadraticBezierTo(_previousControlPoint ?? _currentPoint, end);
_currentPoint = end;
}
private void AddArc(ref ReadOnlySpan<char> span, bool relative)
{
var size = ReadSize(ref span);
span = ReadSeparator(span);
var rotationAngle = ReadDouble(ref span);
span = ReadSeparator(span);
var isLargeArc = ReadBool(ref span);
span = ReadSeparator(span);
var sweepDirection = ReadBool(ref span) ? SweepDirection.Clockwise : SweepDirection.CounterClockwise;
span = ReadSeparator(span);
var end = relative
? ReadRelativePoint(ref span, _currentPoint)
: ReadPoint(ref span);
if (!_isOpen)
{
CreateFigure();
}
_geometryContext.ArcTo(end, size, rotationAngle, isLargeArc, sweepDirection);
_currentPoint = end;
_previousControlPoint = null;
}
private static bool PeekArgument(ReadOnlySpan<char> span)
{
span = SkipWhitespace(span);
return !span.IsEmpty && (span[0] == ',' || span[0] == '-' || span[0] == '.' || char.IsDigit(span[0]));
}
private static bool ReadArgument(ref ReadOnlySpan<char> remaining, out ReadOnlySpan<char> argument)
{
remaining = SkipWhitespace(remaining);
if (remaining.IsEmpty)
{
argument = ReadOnlySpan<char>.Empty;
return false;
}
var valid = false;
int i = 0;
if (remaining[i] == '-')
{
i++;
}
for (; i < remaining.Length && char.IsNumber(remaining[i]); i++) valid = true;
if (i < remaining.Length && remaining[i] == '.')
{
valid = false;
i++;
}
for (; i < remaining.Length && char.IsNumber(remaining[i]); i++) valid = true;
if (i < remaining.Length)
{
// scientific notation
if (remaining[i] == 'E' || remaining[i] == 'e')
{
valid = false;
i++;
if (remaining[i] == '-' || remaining[i] == '+')
{
i++;
for (; i < remaining.Length && char.IsNumber(remaining[i]); i++) valid = true;
}
}
}
if (!valid)
{
argument = ReadOnlySpan<char>.Empty;
return false;
}
argument = remaining.Slice(0, i);
remaining = remaining.Slice(i);
return true;
}
private static ReadOnlySpan<char> ReadSeparator(ReadOnlySpan<char> span)
{
span = SkipWhitespace(span);
if (!span.IsEmpty && span[0] == ',')
{
span = span.Slice(1);
}
return span;
}
private static ReadOnlySpan<char> SkipWhitespace(ReadOnlySpan<char> span)
{
int i = 0;
for (; i < span.Length && char.IsWhiteSpace(span[i]); i++) ;
return span.Slice(i);
}
private bool ReadBool(ref ReadOnlySpan<char> span)
{
if (!ReadArgument(ref span, out var boolValue) || boolValue.Length != 1)
{
throw new InvalidDataException("Invalid bool rule.");
}
switch (boolValue[0])
{
case '0':
return false;
case '1':
return true;
default:
throw new InvalidDataException("Invalid bool rule");
}
}
private double ReadDouble(ref ReadOnlySpan<char> span)
{
if (!ReadArgument(ref span, out var doubleValue))
{
throw new InvalidDataException("Invalid double value");
}
return double.Parse(doubleValue.ToString(), CultureInfo.InvariantCulture);
}
private Size ReadSize(ref ReadOnlySpan<char> span)
{
var width = ReadDouble(ref span);
span = ReadSeparator(span);
var height = ReadDouble(ref span);
return new Size(width, height);
}
private Point ReadPoint(ref ReadOnlySpan<char> span)
{
var x = ReadDouble(ref span);
span = ReadSeparator(span);
var y = ReadDouble(ref span);
return new Point(x, y);
}
private Point ReadRelativePoint(ref ReadOnlySpan<char> span, Point origin)
{
var x = ReadDouble(ref span);
span = ReadSeparator(span);
var y = ReadDouble(ref span);
return new Point(origin.X + x, origin.Y + y);
}
private bool ReadCommand(ref ReadOnlySpan<char> span, out Command command, out bool relative)
{
span = SkipWhitespace(span);
if (span.IsEmpty)
{
command = default;
relative = false;
return false;
}
var c = span[0];
if (!s_commands.TryGetValue(char.ToUpperInvariant(c), out command))
{
throw new InvalidDataException("Unexpected path command '" + c + "'.");
}
relative = char.IsLower(c);
span = span.Slice(1);
return true;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel; // Win32Exception
using System.Diagnostics; // Eventlog class
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
using System.Management.Automation.Internal;
namespace Microsoft.PowerShell.Commands
{
#region GetEventLogCommand
/// <summary>
/// This class implements the Get-EventLog command.
/// </summary>
/// <remarks>
/// The CLR EventLogEntryCollection class has problems with managing
/// rapidly spinning logs (i.e. logs set to "Overwrite" which are
/// rapidly getting new events and discarding old events).
/// In particular, if you enumerate forward
/// EventLogEntryCollection entries = log.Entries;
/// foreach (EventLogEntry entry in entries)
/// it will occasionally skip an entry. Conversely, if you are
/// enumerating backward
/// EventLogEntryCollection entries = log.Entries;
/// int count = entries.Count;
/// for (int i = count-1; i >= 0; i--) {
/// EventLogEntry entry = entries[i];
/// it will occasionally repeat an entry. Accordingly, we enumerate
/// backward and try to leave off the repeated entries.
/// </remarks>
[Cmdlet(VerbsCommon.Get, "EventLog", DefaultParameterSetName = "LogName",
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=113314", RemotingCapability = RemotingCapability.SupportedByCommand)]
[OutputType(typeof(EventLog), typeof(EventLogEntry), typeof(string))]
public sealed class GetEventLogCommand : PSCmdlet
{
#region Parameters
/// <summary>
/// Read eventlog entries from this log.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ParameterSetName = "LogName")]
[Alias("LN")]
public string LogName { get; set; }
/// <summary>
/// Read eventlog entries from this computer.
/// </summary>
[Parameter()]
[ValidateNotNullOrEmpty()]
[Alias("Cn")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] ComputerName { get; set; } = new string[0];
/// <summary>
/// Read only this number of entries.
/// </summary>
[Parameter(ParameterSetName = "LogName")]
[ValidateRange(0, Int32.MaxValue)]
public int Newest { get; set; } = Int32.MaxValue;
/// <summary>
/// Return entries "after " this date.
/// </summary>
[Parameter(ParameterSetName = "LogName")]
[ValidateNotNullOrEmpty]
public DateTime After
{
get { return _after; }
set
{
_after = value;
_isDateSpecified = true;
_isFilterSpecified = true;
}
}
private DateTime _after;
/// <summary>
/// Return entries "Before" this date.
/// </summary>
[Parameter(ParameterSetName = "LogName")]
[ValidateNotNullOrEmpty]
public DateTime Before
{
get { return _before; }
set
{
_before = value;
_isDateSpecified = true;
_isFilterSpecified = true;
}
}
private DateTime _before;
/// <summary>
/// Return entries for this user.Wild characters is supported.
/// </summary>
[Parameter(ParameterSetName = "LogName")]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] UserName
{
get { return _username; }
set
{
_username = value;
_isFilterSpecified = true;
}
}
private string[] _username;
/// <summary>
/// Match eventlog entries by the InstanceIds
/// gets or sets an array of instanceIds.
/// </summary>
[Parameter(Position = 1, ParameterSetName = "LogName")]
[ValidateNotNullOrEmpty()]
[ValidateRangeAttribute((long)0, long.MaxValue)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public long[] InstanceId
{
get { return _instanceIds; }
set
{
_instanceIds = value;
_isFilterSpecified = true;
}
}
private long[] _instanceIds = null;
/// <summary>
/// Match eventlog entries by the Index
/// gets or sets an array of indexes.
/// </summary>
[Parameter(ParameterSetName = "LogName")]
[ValidateNotNullOrEmpty()]
[ValidateRangeAttribute((int)1, int.MaxValue)]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public int[] Index
{
get { return _indexes; }
set
{
_indexes = value;
_isFilterSpecified = true;
}
}
private int[] _indexes = null;
/// <summary>
/// Match eventlog entries by the EntryType
/// gets or sets an array of EntryTypes.
/// </summary>
[Parameter(ParameterSetName = "LogName")]
[ValidateNotNullOrEmpty()]
[ValidateSetAttribute(new string[] { "Error", "Information", "FailureAudit", "SuccessAudit", "Warning" })]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[Alias("ET")]
public string[] EntryType
{
get { return _entryTypes; }
set
{
_entryTypes = value;
_isFilterSpecified = true;
}
}
private string[] _entryTypes = null;
/// <summary>
/// Get or sets an array of Source.
/// </summary>
[Parameter(ParameterSetName = "LogName")]
[ValidateNotNullOrEmpty()]
[Alias("ABO")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Source
{
get
{ return _sources; }
set
{
_sources = value;
_isFilterSpecified = true;
}
}
private string[] _sources;
/// <summary>
/// Get or Set Message string to searched in EventLog.
/// </summary>
[Parameter(ParameterSetName = "LogName")]
[ValidateNotNullOrEmpty()]
[Alias("MSG")]
public string Message
{
get
{
return _message;
}
set
{
_message = value;
_isFilterSpecified = true;
}
}
private string _message;
/// <summary>
/// Returns Log Entry as base object.
/// </summary>
[Parameter(ParameterSetName = "LogName")]
public SwitchParameter AsBaseObject { get; set; }
/// <summary>
/// Return the Eventlog objects rather than the log contents.
/// </summary>
[Parameter(ParameterSetName = "List")]
public SwitchParameter List { get; set; }
/// <summary>
/// Return the log names rather than the EventLog objects.
/// </summary>
[Parameter(ParameterSetName = "List")]
public SwitchParameter AsString
{
get
{
return _asString;
}
set
{
_asString = value;
}
}
private bool _asString /* = false */;
#endregion Parameters
#region Overrides
/// <summary>
/// Sets true when Filter is Specified.
/// </summary>
private bool _isFilterSpecified = false;
private bool _isDateSpecified = false;
private bool _isThrowError = true;
/// <summary>
/// Process the specified logs.
/// </summary>
protected override void BeginProcessing()
{
if (ParameterSetName == "List")
{
if (ComputerName.Length > 0)
{
foreach (string computerName in ComputerName)
{
foreach (EventLog log in EventLog.GetEventLogs(computerName))
{
if (AsString)
WriteObject(log.Log);
else
WriteObject(log);
}
}
}
else
{
foreach (EventLog log in EventLog.GetEventLogs())
{
if (AsString)
WriteObject(log.Log);
else
WriteObject(log);
}
}
}
else
{
Diagnostics.Assert(ParameterSetName == "LogName", "Unexpected parameter set");
if (!WildcardPattern.ContainsWildcardCharacters(LogName))
{
OutputEvents(LogName);
}
else
{
//
// If we were given a wildcard that matches more than one log, output the matching logs. Otherwise output the events in the matching log.
//
List<EventLog> matchingLogs = GetMatchingLogs(LogName);
if (matchingLogs.Count == 1)
{
OutputEvents(matchingLogs[0].Log);
}
else
{
foreach (EventLog log in matchingLogs)
{
WriteObject(log);
}
}
}
}
}
#endregion Overrides
#region Private
private void OutputEvents(string logName)
{
// 2005/04/21-JonN This somewhat odd structure works
// around the FXCOP DisposeObjectsBeforeLosingScope rule.
bool processing = false;
try
{
if (ComputerName.Length == 0)
{
using (EventLog specificLog = new EventLog(logName))
{
processing = true;
Process(specificLog);
}
}
else
{
processing = true;
foreach (string computerName in ComputerName)
{
using (EventLog specificLog = new EventLog(logName, computerName))
{
Process(specificLog);
}
}
}
}
catch (InvalidOperationException e)
{
if (processing) throw;
ThrowTerminatingError(new ErrorRecord(
e, // default exception text is OK
"EventLogNotFound",
ErrorCategory.ObjectNotFound,
logName));
}
}
private void Process(EventLog log)
{
bool matchesfound = false;
if (Newest == 0)
{
return;
}
// enumerate backward, skipping repeat entries
EventLogEntryCollection entries = log.Entries;
int count = entries.Count;
int lastindex = Int32.MinValue;
int processed = 0;
for (int i = count - 1; (i >= 0) && (processed < Newest); i--)
{
EventLogEntry entry = null;
try
{
entry = entries[i];
}
catch (ArgumentException e)
{
ErrorRecord er = new ErrorRecord(
e,
"LogReadError",
ErrorCategory.ReadError,
null
);
er.ErrorDetails = new ErrorDetails(
this,
"EventlogResources",
"LogReadError",
log.Log,
e.Message
);
WriteError(er);
// NTRAID#Windows Out Of Band Releases-2005/09/27-JonN
// Break after the first one, rather than repeating this
// over and over
break;
}
catch (Exception e)
{
Diagnostics.Assert(false,
"EventLogEntryCollection error "
+ e.GetType().FullName
+ ": " + e.Message);
throw;
}
if ((entry != null) &&
((lastindex == Int32.MinValue
|| lastindex - entry.Index == 1)))
{
lastindex = entry.Index;
if (_isFilterSpecified)
{
if (!FiltersMatch(entry))
continue;
}
if (!AsBaseObject)
{
// wrapping in PSobject to insert into PStypesnames
PSObject logentry = new PSObject(entry);
// inserting at zero position in reverse order
logentry.TypeNames.Insert(0, logentry.ImmediateBaseObject + "#" + log.Log + "/" + entry.Source);
logentry.TypeNames.Insert(0, logentry.ImmediateBaseObject + "#" + log.Log + "/" + entry.Source + "/" + entry.InstanceId);
WriteObject(logentry);
matchesfound = true;
}
else
{
WriteObject(entry);
matchesfound = true;
}
processed++;
}
}
if (!matchesfound && _isThrowError)
{
Exception Ex = new ArgumentException(StringUtil.Format(EventlogResources.NoEntriesFound, log.Log, string.Empty));
WriteError(new ErrorRecord(Ex, "GetEventLogNoEntriesFound", ErrorCategory.ObjectNotFound, null));
}
}
private bool FiltersMatch(EventLogEntry entry)
{
if (_indexes != null)
{
if (!((IList)_indexes).Contains(entry.Index))
{
return false;
}
}
if (_instanceIds != null)
{
if (!((IList)_instanceIds).Contains(entry.InstanceId))
{
return false;
}
}
if (_entryTypes != null)
{
bool entrymatch = false;
foreach (string type in _entryTypes)
{
if (type.Equals(entry.EntryType.ToString(), StringComparison.OrdinalIgnoreCase))
{
entrymatch = true;
break;
}
}
if (!entrymatch) return entrymatch;
}
if (_sources != null)
{
bool sourcematch = false;
foreach (string source in _sources)
{
if (WildcardPattern.ContainsWildcardCharacters(source))
{
_isThrowError = false;
}
WildcardPattern wildcardpattern = WildcardPattern.Get(source, WildcardOptions.IgnoreCase);
if (wildcardpattern.IsMatch(entry.Source))
{
sourcematch = true;
break;
}
}
if (!sourcematch) return sourcematch;
}
if (_message != null)
{
if (WildcardPattern.ContainsWildcardCharacters(_message))
{
_isThrowError = false;
}
WildcardPattern wildcardpattern = WildcardPattern.Get(_message, WildcardOptions.IgnoreCase);
if (!wildcardpattern.IsMatch(entry.Message))
{
return false;
}
}
if (_username != null)
{
bool usernamematch = false;
foreach (string user in _username)
{
_isThrowError = false;
if (entry.UserName != null)
{
WildcardPattern wildcardpattern = WildcardPattern.Get(user, WildcardOptions.IgnoreCase);
if (wildcardpattern.IsMatch(entry.UserName))
{
usernamematch = true;
break;
}
}
}
if (!usernamematch) return usernamematch;
}
if (_isDateSpecified)
{
_isThrowError = false;
bool datematch = false;
if (!_after.Equals(_initial) && _before.Equals(_initial))
{
if (entry.TimeGenerated > _after)
{
datematch = true;
}
}
else if (!_before.Equals(_initial) && _after.Equals(_initial))
{
if (entry.TimeGenerated < _before)
{
datematch = true;
}
}
else if (!_after.Equals(_initial) && !_before.Equals(_initial))
{
if (_after > _before || _after == _before)
{
if ((entry.TimeGenerated > _after) || (entry.TimeGenerated < _before))
datematch = true;
}
else
{
if ((entry.TimeGenerated > _after) && (entry.TimeGenerated < _before))
{
datematch = true;
}
}
}
if (!datematch) return datematch;
}
return true;
}
private List<EventLog> GetMatchingLogs(string pattern)
{
WildcardPattern wildcardPattern = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);
List<EventLog> matchingLogs = new List<EventLog>();
if (ComputerName.Length == 0)
{
foreach (EventLog log in EventLog.GetEventLogs())
{
if (wildcardPattern.IsMatch(log.Log))
{
matchingLogs.Add(log);
}
}
}
else
{
foreach (string computerName in ComputerName)
{
foreach (EventLog log in EventLog.GetEventLogs(computerName))
{
if (wildcardPattern.IsMatch(log.Log))
{
matchingLogs.Add(log);
}
}
}
}
return matchingLogs;
}
// private string ErrorBase = "EventlogResources";
private DateTime _initial = new DateTime();
#endregion Private
}
#endregion GetEventLogCommand
#region ClearEventLogCommand
/// <summary>
/// This class implements the Clear-EventLog command.
/// </summary>
[Cmdlet(VerbsCommon.Clear, "EventLog", SupportsShouldProcess = true,
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135198", RemotingCapability = RemotingCapability.SupportedByCommand)]
public sealed class ClearEventLogCommand : PSCmdlet
{
#region Parameters
/// <summary>
/// Clear these logs.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true)]
[Alias("LN")]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] LogName { get; set; }
/// <summary>
/// Clear eventlog entries from these Computers.
/// </summary>
[Parameter(Position = 1, ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
[Alias("Cn")]
public string[] ComputerName { get; set; } = { "." };
#endregion Parameters
#region Overrides
/// <summary>
/// Does the processing.
/// </summary>
protected override void BeginProcessing()
{
string computer = string.Empty;
foreach (string compName in ComputerName)
{
if ((compName.Equals("localhost", StringComparison.OrdinalIgnoreCase)) || (compName.Equals(".", StringComparison.OrdinalIgnoreCase)))
{
computer = "localhost";
}
else
{
computer = compName;
}
foreach (string eventString in LogName)
{
try
{
if (!EventLog.Exists(eventString, compName))
{
ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.LogDoesNotExist, eventString, computer)), null, ErrorCategory.InvalidOperation, null);
WriteError(er);
continue;
}
if (!ShouldProcess(StringUtil.Format(EventlogResources.ClearEventLogWarning, eventString, computer)))
{
continue;
}
EventLog Log = new EventLog(eventString, compName);
Log.Clear();
}
catch (System.IO.IOException)
{
ErrorRecord er = new ErrorRecord(new System.IO.IOException(StringUtil.Format(EventlogResources.PathDoesNotExist, null, computer)), null, ErrorCategory.InvalidOperation, null);
WriteError(er);
continue;
}
catch (Win32Exception)
{
ErrorRecord er = new ErrorRecord(new Win32Exception(StringUtil.Format(EventlogResources.NoAccess, null, computer)), null, ErrorCategory.PermissionDenied, null);
WriteError(er);
continue;
}
catch (InvalidOperationException)
{
ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.OSWritingError)), null, ErrorCategory.ReadError, null);
WriteError(er);
continue;
}
}
}
}
// beginprocessing
#endregion Overrides
}
#endregion ClearEventLogCommand
#region WriteEventLogCommand
/// <summary>
/// This class implements the Write-EventLog command.
/// </summary>
[Cmdlet(VerbsCommunications.Write, "EventLog", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135281", RemotingCapability = RemotingCapability.SupportedByCommand)]
public sealed class WriteEventLogCommand : PSCmdlet
{
#region Parameters
/// <summary>
/// Write eventlog entries in this log.
/// </summary>
[Parameter(Position = 0, Mandatory = true)]
[Alias("LN")]
[ValidateNotNullOrEmpty]
public string LogName { get; set; }
/// <summary>
/// The source by which the application is registered on the specified computer.
/// </summary>
[Parameter(Position = 1, Mandatory = true)]
[Alias("SRC")]
[ValidateNotNullOrEmpty]
public string Source { get; set; }
/// <summary>
/// String which represents One of the EventLogEntryType values.
/// </summary>
[Parameter(Position = 3)]
[Alias("ET")]
[ValidateNotNullOrEmpty]
[ValidateSetAttribute(new string[] { "Error", "Information", "FailureAudit", "SuccessAudit", "Warning" })]
public EventLogEntryType EntryType { get; set; } = EventLogEntryType.Information;
/// <summary>
/// The application-specific subcategory associated with the message.
/// </summary>
[Parameter]
public Int16 Category { get; set; } = 1;
/// <summary>
/// The application-specific identifier for the event.
/// </summary>
[Parameter(Position = 2, Mandatory = true)]
[Alias("ID", "EID")]
[ValidateNotNullOrEmpty]
[ValidateRange(0, UInt16.MaxValue)]
public Int32 EventId { get; set; }
/// <summary>
/// The message goes here.
/// </summary>
[Parameter(Position = 4, Mandatory = true)]
[Alias("MSG")]
[ValidateNotNullOrEmpty]
[ValidateLength(0, 32766)]
public string Message { get; set; }
/// <summary>
/// Write eventlog entries of this log.
/// </summary>
[Parameter]
[Alias("RD")]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public byte[] RawData { get; set; }
/// <summary>
/// Write eventlog entries of this log.
/// </summary>
[Parameter]
[Alias("CN")]
[ValidateNotNullOrEmpty]
public string ComputerName { get; set; } = ".";
#endregion Parameters
#region private
private void WriteNonTerminatingError(Exception exception, string errorId, string errorMessage,
ErrorCategory category)
{
Exception ex = new Exception(errorMessage, exception);
WriteError(new ErrorRecord(ex, errorId, category, null));
}
#endregion private
#region Overrides
/// <summary>
/// Does the processing.
/// </summary>
protected override void BeginProcessing()
{
string _computerName = string.Empty;
if ((ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase)) || (ComputerName.Equals(".", StringComparison.OrdinalIgnoreCase)))
{
_computerName = "localhost";
}
else
{
_computerName = ComputerName;
}
try
{
if (!(EventLog.SourceExists(Source, ComputerName)))
{
ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.SourceDoesNotExist, null, _computerName, Source)), null, ErrorCategory.InvalidOperation, null);
WriteError(er);
}
else
{
if (!(EventLog.Exists(LogName, ComputerName)))
{
ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.LogDoesNotExist, LogName, _computerName)), null, ErrorCategory.InvalidOperation, null);
WriteError(er);
}
else
{
EventLog _myevent = new EventLog(LogName, ComputerName, Source);
_myevent.WriteEntry(Message, EntryType, EventId, Category, RawData);
}
}
}
catch (ArgumentException ex)
{
WriteNonTerminatingError(ex, ex.Message, ex.Message, ErrorCategory.InvalidOperation);
}
catch (InvalidOperationException ex)
{
WriteNonTerminatingError(ex, "AccessDenied", StringUtil.Format(EventlogResources.AccessDenied, LogName, null, Source), ErrorCategory.PermissionDenied);
}
catch (Win32Exception ex)
{
WriteNonTerminatingError(ex, "OSWritingError", StringUtil.Format(EventlogResources.OSWritingError, null, null, null), ErrorCategory.WriteError);
}
catch (System.IO.IOException ex)
{
WriteNonTerminatingError(ex, "PathDoesNotExist", StringUtil.Format(EventlogResources.PathDoesNotExist, null, ComputerName, null), ErrorCategory.InvalidOperation);
}
}
#endregion Overrides
}
#endregion WriteEventLogCommand
#region LimitEventLogCommand
/// <summary>
/// This class implements the Limit-EventLog command.
/// </summary>
[Cmdlet(VerbsData.Limit, "EventLog", SupportsShouldProcess = true,
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135227", RemotingCapability = RemotingCapability.SupportedByCommand)]
public sealed class LimitEventLogCommand : PSCmdlet
{
#region Parameters
/// <summary>
/// Limit the properties of this log.
/// </summary>
[Parameter(Position = 0, Mandatory = true)]
[Alias("LN")]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] LogName { get; set; }
/// <summary>
/// Limit eventlog entries of this computer.
/// </summary>
[Parameter]
[Alias("CN")]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] ComputerName { get; set; } = { "." };
/// <summary>
/// Minimum retention days for this log.
/// </summary>
[Parameter]
[Alias("MRD")]
[ValidateNotNullOrEmpty]
[ValidateRange(1, 365)]
public Int32 RetentionDays
{
get { return _retention; }
set
{
_retention = value;
_retentionSpecified = true;
}
}
private Int32 _retention;
private bool _retentionSpecified = false;
/// <summary>
/// Overflow action to be taken.
/// </summary>
[Parameter]
[Alias("OFA")]
[ValidateNotNullOrEmpty]
[ValidateSetAttribute(new string[] { "OverwriteOlder", "OverwriteAsNeeded", "DoNotOverwrite" })]
public System.Diagnostics.OverflowAction OverflowAction
{
get { return _overflowaction; }
set
{
_overflowaction = value;
_overflowSpecified = true;
}
}
private System.Diagnostics.OverflowAction _overflowaction;
private bool _overflowSpecified = false;
/// <summary>
/// Maximum size of this log.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public Int64 MaximumSize
{
get { return _maximumKilobytes; }
set
{
_maximumKilobytes = value;
_maxkbSpecified = true;
}
}
private Int64 _maximumKilobytes;
private bool _maxkbSpecified = false;
#endregion Parameters
#region private
private void WriteNonTerminatingError(Exception exception, string resourceId, string errorId,
ErrorCategory category, string _logName, string _compName)
{
Exception ex = new Exception(StringUtil.Format(resourceId, _logName, _compName), exception);
WriteError(new ErrorRecord(ex, errorId, category, null));
}
#endregion private
#region Overrides
/// <summary>
/// Does the processing.
/// </summary>
protected override
void
BeginProcessing()
{
string computer = string.Empty;
foreach (string compname in ComputerName)
{
if ((compname.Equals("localhost", StringComparison.OrdinalIgnoreCase)) || (compname.Equals(".", StringComparison.OrdinalIgnoreCase)))
{
computer = "localhost";
}
else
{
computer = compname;
}
foreach (string logname in LogName)
{
try
{
if (!EventLog.Exists(logname, compname))
{
ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.LogDoesNotExist, logname, computer)), null, ErrorCategory.InvalidOperation, null);
WriteError(er);
continue;
}
else
{
if (!ShouldProcess(StringUtil.Format(EventlogResources.LimitEventLogWarning, logname, computer)))
{
continue;
}
else
{
EventLog newLog = new EventLog(logname, compname);
int _minRetention = newLog.MinimumRetentionDays;
System.Diagnostics.OverflowAction _newFlowAction = newLog.OverflowAction;
if (_retentionSpecified && _overflowSpecified)
{
if (_overflowaction.CompareTo(System.Diagnostics.OverflowAction.OverwriteOlder) == 0)
{
newLog.ModifyOverflowPolicy(_overflowaction, _retention);
}
else
{
ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.InvalidOverflowAction)), null, ErrorCategory.InvalidOperation, null);
WriteError(er);
continue;
}
}
else if (_retentionSpecified && !_overflowSpecified)
{
if (_newFlowAction.CompareTo(System.Diagnostics.OverflowAction.OverwriteOlder) == 0)
{
newLog.ModifyOverflowPolicy(_newFlowAction, _retention);
}
else
{
ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.InvalidOverflowAction)), null, ErrorCategory.InvalidOperation, null);
WriteError(er);
continue;
}
}
else if (!_retentionSpecified && _overflowSpecified)
{
newLog.ModifyOverflowPolicy(_overflowaction, _minRetention);
}
if (_maxkbSpecified)
{
int kiloByte = 1024;
_maximumKilobytes = _maximumKilobytes / kiloByte;
newLog.MaximumKilobytes = _maximumKilobytes;
}
}
}
}
catch (InvalidOperationException ex)
{
WriteNonTerminatingError(ex, EventlogResources.PermissionDenied, "PermissionDenied", ErrorCategory.PermissionDenied, logname, computer);
continue;
}
catch (System.IO.IOException ex)
{
WriteNonTerminatingError(ex, EventlogResources.PathDoesNotExist, "PathDoesNotExist", ErrorCategory.InvalidOperation, null, computer);
continue;
}
catch (ArgumentOutOfRangeException ex)
{
if (!_retentionSpecified && !_maxkbSpecified)
{
WriteNonTerminatingError(ex, EventlogResources.InvalidArgument, "InvalidArgument", ErrorCategory.InvalidData, null, null);
}
else
{
WriteNonTerminatingError(ex, EventlogResources.ValueOutofRange, "ValueOutofRange", ErrorCategory.InvalidData, null, null);
}
continue;
}
}
}
}
#endregion override
}
#endregion LimitEventLogCommand
#region ShowEventLogCommand
/// <summary>
/// This class implements the Show-EventLog command.
/// </summary>
[Cmdlet(VerbsCommon.Show, "EventLog", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135257", RemotingCapability = RemotingCapability.SupportedByCommand)]
public sealed class ShowEventLogCommand : PSCmdlet
{
#region Parameters
/// <summary>
/// Show eventviewer of this computer.
/// </summary>
[Parameter(Position = 0)]
[Alias("CN")]
[ValidateNotNullOrEmpty]
public string ComputerName { get; set; } = ".";
#endregion Parameters
#region Overrides
/// <summary>
/// Does the processing.
/// </summary>
protected override
void
BeginProcessing()
{
try
{
string eventVwrExe = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System),
"eventvwr.exe");
Process.Start(eventVwrExe, ComputerName);
}
catch (Win32Exception e)
{
if (e.NativeErrorCode.Equals(0x00000002))
{
string message = StringUtil.Format(EventlogResources.NotSupported);
InvalidOperationException ex = new InvalidOperationException(message);
ErrorRecord er = new ErrorRecord(ex, "Win32Exception", ErrorCategory.InvalidOperation, null);
WriteError(er);
}
else
{
ErrorRecord er = new ErrorRecord(e, "Win32Exception", ErrorCategory.InvalidArgument, null);
WriteError(er);
}
}
catch (SystemException ex)
{
ErrorRecord er = new ErrorRecord(ex, "InvalidComputerName", ErrorCategory.InvalidArgument, ComputerName);
WriteError(er);
}
}
#endregion override
}
#endregion ShowEventLogCommand
#region NewEventLogCommand
/// <summary>
/// This cmdlet creates the new event log .This cmdlet can also be used to
/// configure a new source for writing entries to an event log on the local
/// computer or a remote computer.
/// You can create an event source for an existing event log or a new event log.
/// When you create a new source for a new event log, the system registers the
/// source for that log, but the log is not created until the first entry is
/// written to it.
/// The operating system stores event logs as files. The associated file is
/// stored in the %SystemRoot%\System32\Config directory on the specified
/// computer. The file name is set by appending the first 8 characters of the
/// Log property with the ".evt" file name extension.
/// You can register the event source with localized resource file(s) for your
/// event category and message strings. Your application can write event log
/// entries using resource identifiers, rather than specifying the actual
/// string. You can register a separate file for event categories, messages and
/// parameter insertion strings, or you can register the same resource file for
/// all three types of strings.
/// </summary>
[Cmdlet(VerbsCommon.New, "EventLog", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135235", RemotingCapability = RemotingCapability.SupportedByCommand)]
public class NewEventLogCommand : PSCmdlet
{
#region Parameter
/// <summary>
/// The following is the definition of the input parameter "CategoryResourceFile".
/// Specifies the path of the resource file that contains category strings for
/// the source
/// Resource File is expected to be present in Local/Remote Machines.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[Alias("CRF")]
public string CategoryResourceFile { get; set; }
/// <summary>
/// The following is the definition of the input parameter "ComputerName".
/// Specify the Computer Name. The default is local computer.
/// </summary>
[Parameter(Position = 2)]
[ValidateNotNullOrEmpty]
[Alias("CN")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] ComputerName { get; set; } = { "." };
/// <summary>
/// The following is the definition of the input parameter "LogName".
/// Specifies the name of the log.
/// </summary>
[Parameter(Mandatory = true,
Position = 0)]
[ValidateNotNullOrEmpty]
[Alias("LN")]
public string LogName { get; set; }
/// <summary>
/// The following is the definition of the input parameter "MessageResourceFile".
/// Specifies the path of the message resource file that contains message
/// formatting strings for the source
/// Resource File is expected to be present in Local/Remote Machines.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[Alias("MRF")]
public string MessageResourceFile { get; set; }
/// <summary>
/// The following is the definition of the input parameter "ParameterResourceFile".
/// Specifies the path of the resource file that contains message parameter
/// strings for the source
/// Resource File is expected to be present in Local/Remote Machines.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[Alias("PRF")]
public string ParameterResourceFile { get; set; }
/// <summary>
/// The following is the definition of the input parameter "Source".
/// Specifies the Source of the EventLog.
/// </summary>
[Parameter(Mandatory = true,
Position = 1)]
[ValidateNotNullOrEmpty]
[Alias("SRC")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Source { get; set; }
#endregion Parameter
#region private
private void WriteNonTerminatingError(Exception exception, string resourceId, string errorId,
ErrorCategory category, string _logName, string _compName, string _source, string _resourceFile)
{
Exception ex = new Exception(StringUtil.Format(resourceId, _logName, _compName, _source, _resourceFile), exception);
WriteError(new ErrorRecord(ex, errorId, category, null));
}
#endregion private
#region override
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
string computer = string.Empty;
foreach (string compname in ComputerName)
{
if ((compname.Equals("localhost", StringComparison.OrdinalIgnoreCase)) || (compname.Equals(".", StringComparison.OrdinalIgnoreCase)))
{
computer = "localhost";
}
else
{
computer = compname;
}
try
{
foreach (string _sourceName in Source)
{
if (!EventLog.SourceExists(_sourceName, compname))
{
EventSourceCreationData newEventSource = new EventSourceCreationData(_sourceName, LogName);
newEventSource.MachineName = compname;
if (!string.IsNullOrEmpty(MessageResourceFile))
newEventSource.MessageResourceFile = MessageResourceFile;
if (!string.IsNullOrEmpty(ParameterResourceFile))
newEventSource.ParameterResourceFile = ParameterResourceFile;
if (!string.IsNullOrEmpty(CategoryResourceFile))
newEventSource.CategoryResourceFile = CategoryResourceFile;
EventLog.CreateEventSource(newEventSource);
}
else
{
ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.SourceExistInComp, null, computer, _sourceName)), null, ErrorCategory.InvalidOperation, null);
WriteError(er);
continue;
}
}
}
catch (InvalidOperationException ex)
{
WriteNonTerminatingError(ex, EventlogResources.PermissionDenied, "PermissionDenied", ErrorCategory.PermissionDenied, LogName, computer, null, null);
continue;
}
catch (ArgumentException ex)
{
ErrorRecord er = new ErrorRecord(ex, "NewEventlogException", ErrorCategory.InvalidArgument, null);
WriteError(er);
continue;
}
catch (System.Security.SecurityException ex)
{
WriteNonTerminatingError(ex, EventlogResources.AccessIsDenied, "AccessIsDenied", ErrorCategory.InvalidOperation, null, null, null, null);
continue;
}
}
}
// End BeginProcessing()
#endregion override
}
#endregion NewEventLogCommand
#region RemoveEventLogCommand
/// <summary>
/// This cmdlet is used to delete the specified event log from the specified
/// computer. This can also be used to Clear the entries of the specified event
/// log and also to unregister the Source associated with the eventlog.
/// </summary>
[Cmdlet(VerbsCommon.Remove, "EventLog",
SupportsShouldProcess = true, DefaultParameterSetName = "Default",
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=135248", RemotingCapability = RemotingCapability.SupportedByCommand)]
public class RemoveEventLogCommand : PSCmdlet
{
/// <summary>
/// The following is the definition of the input parameter "ComputerName".
/// Specifies the Computer Name.
/// </summary>
[Parameter(Position = 1)]
[ValidateNotNull]
[ValidateNotNullOrEmpty]
[Alias("CN")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] ComputerName { get; set; } = { "." };
/// <summary>
/// The following is the definition of the input parameter "LogName".
/// Specifies the Event Log Name.
/// </summary>
[Parameter(Mandatory = true,
Position = 0, ParameterSetName = "Default")]
[ValidateNotNull]
[ValidateNotNullOrEmpty]
[Alias("LN")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] LogName { get; set; }
/// <summary>
/// The following is the definition of the input parameter "RemoveSource".
/// Specifies either to remove the event log and and associated source or
/// source. alone.
/// When this parameter is not specified, the cmdlet uses Delete Method which
/// clears the eventlog and also the source associated with it.
/// When this parameter value is true, then this cmdlet uses DeleteEventSource
/// Method to delete the Source alone.
/// </summary>
[Parameter(ParameterSetName = "Source")]
[ValidateNotNull]
[ValidateNotNullOrEmpty]
[Alias("SRC")]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Source { get; set; }
/// <summary>
/// BeginProcessing method.
/// </summary>
protected override void BeginProcessing()
{
try
{
string computer = string.Empty;
foreach (string compName in ComputerName)
{
if ((compName.Equals("localhost", StringComparison.OrdinalIgnoreCase)) || (compName.Equals(".", StringComparison.OrdinalIgnoreCase)))
{
computer = "localhost";
}
else
{
computer = compName;
}
if (ParameterSetName.Equals("Default"))
{
foreach (string log in LogName)
{
try
{
if (EventLog.Exists(log, compName))
{
if (!ShouldProcess(StringUtil.Format(EventlogResources.RemoveEventLogWarning, log, computer)))
{
continue;
}
EventLog.Delete(log, compName);
}
else
{
ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.LogDoesNotExist, log, computer)), null, ErrorCategory.InvalidOperation, null);
WriteError(er);
continue;
}
}
catch (System.IO.IOException)
{
ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.PathDoesNotExist, null, computer)), null, ErrorCategory.InvalidOperation, null);
WriteError(er);
continue;
}
}
}
else
{
foreach (string src in Source)
{
try
{
if (EventLog.SourceExists(src, compName))
{
if (!ShouldProcess(StringUtil.Format(EventlogResources.RemoveSourceWarning, src, computer)))
{
continue;
}
EventLog.DeleteEventSource(src, compName);
}
else
{
ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.SourceDoesNotExist, string.Empty, computer, src)), null, ErrorCategory.InvalidOperation, null);
WriteError(er);
continue;
}
}
catch (System.IO.IOException)
{
ErrorRecord er = new ErrorRecord(new InvalidOperationException(StringUtil.Format(EventlogResources.PathDoesNotExist, null, computer)), null, ErrorCategory.InvalidOperation, null);
WriteError(er);
continue;
}
}
}
}
}
catch (System.Security.SecurityException ex)
{
ErrorRecord er = new ErrorRecord(ex, "NewEventlogException", ErrorCategory.SecurityError, null);
WriteError(er);
}
}
}
#endregion RemoveEventLogCommand
}
| |
using UnityEngine;
using System.Collections;
public class CustomTeleporterB : MonoBehaviour
{
//teleport instantly upon entering trigger?
public bool instantTeleport;
//teleport to a random pad?
public bool randomTeleport;
//teleport when a button is pressed?
public bool buttonTeleport;
//the name of the button
public string buttonName;
//teleport delayed?
public bool delayedTeleport;
//time it takes to teleport, if not instant
public float teleportTime = 3;
//only allow specific tag object? if left empty, any object can teleport
public string objectTag = "if empty, any object will tp";
//one or more destination pads
public Transform[] destinationPad;
//height offset
public float teleportationHeightOffset = 1;
//a private float counting down the time
private float curTeleportTime;
//private bool checking if you entered the trigger
private bool inside;
//check to wait for arrived object to leave before enabling teleporation again
[HideInInspector]
public bool arrived;
//gameobjects inside the pad
private Transform subject;
//add a sound component if you want the teleport playing a sound when teleporting
public AudioSource teleportSound;
//add a sound component for the teleport pad, vibrating for example, or music if you want :D
//also to make it more apparent when the pad is off, stop this component playing with "teleportPadSound.Stop();"
//PS the distance is set to 10 units, so you only hear it standing close, not from the other side of the map
public AudioSource teleportPadSound;
//simple enable/disable function in case you want the teleport not working at some point
//without disabling the entire script, so receiving objects still works
public bool teleportPadOn = true;
void Start ()
{
//Set the countdown ready to the time you chose
curTeleportTime = teleportTime;
}
void Update ()
{
//check if theres something/someone inside
if(inside)
{
//if that object hasnt just arrived from another pad, teleport it
if(!arrived && teleportPadOn)
Teleport();
}
}
void Teleport()
{
//if you chose to teleport instantly
if(instantTeleport)
{
//if you chose instant + random teleport, teleport to a random pad from the array
if(randomTeleport)
{
//choose a random pad from the array
int chosenPad = Random.Range(0,destinationPad.Length);
//set arrived to true in that array, so it doesnt teleport the subject back
destinationPad[chosenPad].GetComponent<CustomTeleporter>().arrived = true;
//and teleport the subject
subject.transform.position = destinationPad[chosenPad].transform.position + new Vector3(0,teleportationHeightOffset,0);
//play teleport sound
teleportSound.Play();
}
else //if not random, teleport to the first one in the array list
{
//set arrived to true in that array, so it doesnt teleport the subject back
destinationPad[0].GetComponent<CustomTeleporter>().arrived = true;
//and teleport the subject
subject.transform.position = destinationPad[0].transform.position + new Vector3(0,teleportationHeightOffset,0);
//play teleport sound
teleportSound.Play();
}
}
else if(delayedTeleport) //if its a delayed teleport
{
//start the countdown
curTeleportTime-=1 * Time.deltaTime;
//if the countdown reaches zero
if(curTeleportTime <= 0)
{
//reset the countdown
curTeleportTime = teleportTime;
//if you chose delayed + random teleport, teleport to random pad from array, after the delay
if(randomTeleport)
{
Application.LoadLevel(3);
//choose a random pad from the array
int chosenPad = Random.Range(0,destinationPad.Length);
//set arrived to true in that array, so it doesnt teleport the subject back
destinationPad[chosenPad].GetComponent<CustomTeleporter>().arrived = true;
//teleport
subject.transform.position = destinationPad[chosenPad].transform.position + new Vector3(0,teleportationHeightOffset,0);
//play teleport sound
teleportSound.Play();
}
else //if not random, teleport to the first one in the array list
{
//set arrived to true in that array, so it doesnt teleport the subject back
destinationPad[0].GetComponent<CustomTeleporter>().arrived = true;
//teleport
subject.transform.position = destinationPad[0].transform.position + new Vector3(0,teleportationHeightOffset,0);
//play teleport sound
teleportSound.Play();
}
}
}
else if(buttonTeleport) //if you selected a teleport activated by a button
{
//checks if the button you set in the inspector is being pressed
if(Input.GetButtonDown(buttonName))
{
if(delayedTeleport) //if you set it to button + delayed
{
//start the countdown
curTeleportTime-=1 * Time.deltaTime;
//if the countdown reaches zero
if(curTeleportTime <= 0)
{
//reset the countdown
curTeleportTime = teleportTime;
//if you chose delayed + random teleport + button, teleport to random pad from array, after the delay
// and button press
if(randomTeleport)
{
//choose a random pad from the array
int chosenPad = Random.Range(0,destinationPad.Length);
//set arrived to true in that array, so it doesnt teleport the subject back
destinationPad[chosenPad].GetComponent<CustomTeleporter>().arrived = true;
//teleport
subject.transform.position = destinationPad[chosenPad].transform.position + new Vector3(0,teleportationHeightOffset,0);
//play teleport sound
teleportSound.Play();
}
else //if not random, teleport to the first one in the array list
{
//set arrived to true in that array, so it doesnt teleport the subject back
destinationPad[0].GetComponent<CustomTeleporter>().arrived = true;
//teleport
subject.transform.position = destinationPad[0].transform.position + new Vector3(0,teleportationHeightOffset,0);
//play teleport sound
teleportSound.Play();
}
}
}
//if you chose button + random teleport, teleport to random pad from array, on button down
else if(randomTeleport)
{
//choose a random pad from the array
int chosenPad = Random.Range(0,destinationPad.Length);
//set arrived to true in that array, so it doesnt teleport the subject back
destinationPad[chosenPad].GetComponent<CustomTeleporter>().arrived = true;
//teleport
subject.transform.position = destinationPad[chosenPad].transform.position + new Vector3(0,teleportationHeightOffset,0);
//play teleport sound
teleportSound.Play();
}
else
{
//set arrived to true in that array, so it doesnt teleport the subject back
destinationPad[0].GetComponent<CustomTeleporter>().arrived = true;
//teleport
subject.transform.position = destinationPad[0].transform.position + new Vector3(0,teleportationHeightOffset,0);
//play teleport sound
teleportSound.Play();
}
}
}
}
void OnTriggerEnter(Collider trig)
{
Application.LoadLevel(3);
//when an object enters the trigger
//if you set a tag in the inspector, check if an object has that tag
//otherwise the pad will take in and teleport any object
if (objectTag != "")
{
//if the objects tag is the same as the one allowed in the inspector
if(trig.gameObject.tag == objectTag)
{
//set the subject to be the entered object
subject = trig.transform;
//and check inside, ready for teleport
inside = true;
//if its a button teleport, the pad should be set to be ready to teleport again
//so the player/object doesn't have to leave the pad, and re enter again, we do that here
if(buttonTeleport)
{
arrived = false;
}
}
}
else
{
//set the subject to be the entered object
subject = trig.transform;
//and check inside, ready for teleport
inside = true;
//if its a button teleport, the pad should be set to be ready to teleport again
//so the player/object doesn't have to leave the pad, and re enter again, we do that here
if(buttonTeleport)
{
arrived = false;
}
}
}
void OnTriggerExit(Collider trig)
{
//////////////if you set a tag for the entering pad, you should also set it for the exiting pad////////
//when an object exists the trigger
//if you set a tag in the inspector, check if an object has that tag
//otherwise the pad will register any object as the one leaving
if(objectTag != "")
{
//if the objects tag is the same as the one allowed in the inspector
if(trig.gameObject.tag == objectTag)
{
//set that the object left
inside = false;
//reset countdown time
curTeleportTime = teleportTime;
//if the object that left the trigger is the same object as the subject
if(trig.transform == subject)
{
//set arrived to false, so that the pad can be used again
arrived = false;
}
//remove the subject from the pads memory
subject = null;
}
}
else //if tags arent important
{
//set that the object left
inside = false;
//reset countdown time
curTeleportTime = teleportTime;
//if the object that left the trigger is the same object as the subject
if(trig.transform == subject)
{
//set arrived to false, so that the pad can be used again
arrived = false;
}
//remove the subject from the pads memory
subject = null;
}
}
}
| |
// 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.Text;
using System.Linq;
using System.IO;
using System.Collections;
using System.Globalization;
using System.Runtime.CompilerServices;
using Xunit;
public class Directory_CreateDirectory
{
[Fact]
public static void CreateDirectory_NullAsPath_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() =>
{
Directory.CreateDirectory((string)null);
});
}
[Fact]
public static void CreateDirectory_EmptyAsPath_ThrowsArgumentException()
{
Assert.Throws<ArgumentException>(() => // BUG 995784: Not setting the parameter name
{
Directory.CreateDirectory(string.Empty);
});
}
[Fact]
public static void CreateDirectory_NonSignificantWhiteSpaceAsPath_ThrowsArgumentException()
{
var paths = IOInputs.GetNonSignificantTrailingWhiteSpace();
foreach (var path in paths)
{
Assert.Throws<ArgumentException>(() => // BUG 995784: Not setting the parameter name
{
Directory.CreateDirectory(path);
});
}
}
[Fact]
public static void CreateDirectory_PathWithInvalidCharactersAsPath_ThrowsArgumentException()
{
var paths = IOInputs.GetPathsWithInvalidCharacters();
foreach (var path in paths)
{
Assert.Throws<ArgumentException>(() => // BUG 995784: Not setting the parameter name
{
Directory.CreateDirectory(path);
});
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // alternate data streams
public static void CreateDirectory_PathWithAlternativeDataStreams_ThrowsNotSupportedException()
{
var paths = IOInputs.GetPathsWithAlternativeDataStreams();
foreach (var path in paths)
{
Assert.Throws<NotSupportedException>(() =>
{
Directory.CreateDirectory(path);
});
}
}
[Fact]
[OuterLoop]
[PlatformSpecific(PlatformID.Windows)] // device name prefixes
public static void CreateDirectory_PathWithReservedDeviceNameAsPath_ThrowsDirectoryNotFoundException()
{ // Throws DirectoryNotFoundException, when the behavior really should be an invalid path
var paths = IOInputs.GetPathsWithReservedDeviceNames();
foreach (var path in paths)
{
Assert.Throws<DirectoryNotFoundException>(() =>
{
Directory.CreateDirectory(path);
});
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // UNC shares
public static void CreateDirectory_UncPathWithoutShareNameAsPath_ThrowsArgumentException()
{
var paths = IOInputs.GetUncPathsWithoutShareName();
foreach (var path in paths)
{
Assert.Throws<ArgumentException>(() => // BUG 995784: Not setting the parameter name
{
Directory.CreateDirectory(path);
});
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // max component size not fixed on Unix
public static void CreateDirectory_DirectoryWithComponentLongerThanMaxComponentAsPath_ThrowsPathTooLongException()
{
// While paths themselves can be up to 260 characters including trailing null, file systems
// limit each components of the path to a total of 255 characters.
var paths = IOInputs.GetPathsWithComponentLongerThanMaxComponent();
foreach (string path in paths)
{
Assert.Throws<PathTooLongException>(() =>
{
Directory.CreateDirectory(path);
});
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // max directory size not fixed on Unix
public static void CreateDirectory_DirectoryLongerThanMaxDirectoryAsPath_ThrowsPathTooLongException()
{
var paths = IOInputs.GetPathsLongerThanMaxDirectory();
foreach (var path in paths)
{
Assert.Throws<PathTooLongException>(() =>
{
Directory.CreateDirectory(path);
});
}
}
[Fact]
public static void CreateDirectory_DirectoryLongerThanMaxPathAsPath_ThrowsPathTooLongException()
{
var paths = IOInputs.GetPathsLongerThanMaxPath();
foreach (var path in paths)
{
Assert.Throws<PathTooLongException>(() =>
{
Directory.CreateDirectory(path);
});
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // testing drive labels
public static void CreateDirectory_NotReadyDriveAsPath_ThrowsDirectoryNotFoundException()
{ // Behavior is suspect, should really have thrown IOException similar to the SubDirectory case
var drive = IOServices.GetNotReadyDrive();
if (drive == null)
{
Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted.");
return;
}
Assert.Throws<DirectoryNotFoundException>(() =>
{
Directory.CreateDirectory(drive);
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // testing drive labels
public static void CreateDirectory_SubdirectoryOnNotReadyDriveAsPath_ThrowsIOException()
{
var drive = IOServices.GetNotReadyDrive();
if (drive == null)
{
Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted.");
return;
}
// 'Device is not ready'
Assert.Throws<IOException>(() =>
{
Directory.CreateDirectory(Path.Combine(drive, "Subdirectory"));
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // testing drive labels
public static void CreateDirectory_NonExistentDriveAsPath_ThrowsDirectoryNotFoundException()
{
var drive = IOServices.GetNonExistentDrive();
if (drive == null)
{
Console.WriteLine("Skipping test. Unable to find a non-existent drive.");
return;
}
Assert.Throws<DirectoryNotFoundException>(() =>
{
Directory.CreateDirectory(drive);
});
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // testing drive labels
public static void CreateDirectory_SubdirectoryOnNonExistentDriveAsPath_ThrowsDirectoryNotFoundException()
{
var drive = IOServices.GetNonExistentDrive();
if (drive == null)
{
Console.WriteLine("Skipping test. Unable to find a non-existent drive.");
return;
}
Assert.Throws<DirectoryNotFoundException>(() =>
{
Directory.CreateDirectory(Path.Combine(drive, "Subdirectory"));
});
}
[Fact]
public static void CreateDirectory_FileWithoutTrailingSlashAsPath_ThrowsIOException()
{ // VSWhidbey #104049
using (TemporaryFile file = new TemporaryFile())
{
string path = IOServices.RemoveTrailingSlash(file.Path);
Assert.Throws<IOException>(() =>
{
Directory.CreateDirectory(path);
});
}
}
[Fact]
public static void CreateDirectory_FileWithTrailingSlashAsPath_ThrowsIOException()
{
using (TemporaryFile file = new TemporaryFile())
{
string path = IOServices.AddTrailingSlashIfNeeded(file.Path);
Assert.Throws<IOException>(() =>
{
Directory.CreateDirectory(path);
});
}
}
[Fact]
public static void CreateDirectory_ExistingDirectoryWithoutTrailingSlashAsPath_DoesNotThrow()
{
using (TemporaryDirectory directory = new TemporaryDirectory())
{
string path = IOServices.RemoveTrailingSlash(directory.Path);
DirectoryInfo result = Directory.CreateDirectory(path);
Assert.Equal(path, result.FullName);
Assert.True(Directory.Exists(result.FullName));
}
}
[Fact]
public static void CreateDirectory_ExistingDirectoryWithTrailingSlashAsPath_DoesNotThrow()
{
using (TemporaryDirectory directory = new TemporaryDirectory())
{
string path = IOServices.AddTrailingSlashIfNeeded(directory.Path);
DirectoryInfo result = Directory.CreateDirectory(path);
Assert.Equal(path, result.FullName);
Assert.True(Directory.Exists(result.FullName));
}
}
[Fact]
public static void CreateDirectory_DotWithoutTrailingSlashAsPath_DoesNotThrow()
{
DirectoryInfo result = Directory.CreateDirectory(Path.Combine(TestInfo.CurrentDirectory, ".")); // "Current" directory
Assert.True(Directory.Exists(result.FullName));
}
[Fact]
public static void CreateDirectory_DotWithTrailingSlashAsPath_DoesNotThrow()
{
DirectoryInfo result = Directory.CreateDirectory(Path.Combine(TestInfo.CurrentDirectory, ".") + Path.DirectorySeparatorChar); // "Current" directory
Assert.True(Directory.Exists(result.FullName));
}
[Fact]
public static void CreateDirectory_DotDotWithoutTrailingSlashAsPath_DoesNotThrow()
{
DirectoryInfo result = Directory.CreateDirectory(Path.Combine(TestInfo.CurrentDirectory, "..")); // "Parent" of current directory
Assert.True(Directory.Exists(result.FullName));
}
[Fact]
public static void CreateDirectory_DotDotWithTrailingSlashAsPath_DoesNotThrow()
{
DirectoryInfo result = Directory.CreateDirectory(Path.Combine(TestInfo.CurrentDirectory, "..") + Path.DirectorySeparatorChar); // "Parent" of current directory
Assert.True(Directory.Exists(result.FullName));
}
#if !TEST_WINRT // Cannot set current directory to root from appcontainer with it's default ACL
/*
[Fact]
[ActiveIssue(1220)] // SetCurrentDirectory
public static void CreateDirectory_DotDotAsPath_WhenCurrentDirectoryIsRoot_DoesNotThrow()
{
string root = Path.GetPathRoot(Directory.GetCurrentDirectory());
using (CurrentDirectoryContext context = new CurrentDirectoryContext(root))
{
DirectoryInfo result = Directory.CreateDirectory("..");
Assert.True(Directory.Exists(result.FullName));
Assert.Equal(root, result.FullName);
}
}
*/
#endif
[Fact]
public static void CreateDirectory_NonSignificantTrailingWhiteSpace_TreatsAsNonSignificant()
{
using (TemporaryDirectory directory = new TemporaryDirectory())
{
var components = IOInputs.GetNonSignificantTrailingWhiteSpace();
foreach (string component in components)
{
string path = directory.Path + component;
DirectoryInfo result = Directory.CreateDirectory(path);
Assert.True(Directory.Exists(result.FullName));
Assert.Equal(directory.Path, result.FullName);
}
}
}
[Fact]
public static void CreateDirectory_ReadOnlyFileAsPath_ThrowsIOException()
{
using (TemporaryFile file = new TemporaryFile())
{
file.IsReadOnly = true;
Assert.Throws<IOException>(() =>
{
Directory.CreateDirectory(file.Path);
});
}
}
#if !TEST_WINRT // TODO: Enable once we implement WinRT file attributes
[Fact]
public static void CreateDirectory_ReadOnlyExistingDirectoryAsPath_DoesNotThrow()
{ // DevDivBugs #33833
using (TemporaryDirectory directory = new TemporaryDirectory())
{
directory.IsReadOnly = true;
DirectoryInfo result = Directory.CreateDirectory(directory.Path);
Assert.Equal(directory.Path, result.FullName);
Assert.True(Directory.Exists(result.FullName));
}
}
[Fact]
public static void CreateDirectory_HiddenExistingDirectoryAsPath_DoesNotThrow()
{
using (TemporaryDirectory directory = new TemporaryDirectory())
{
directory.IsHidden = true;
DirectoryInfo result = Directory.CreateDirectory(directory.Path);
Assert.Equal(directory.Path, result.FullName);
Assert.True(Directory.Exists(result.FullName));
}
}
#endif
[Fact]
[PlatformSpecific(PlatformID.Windows)] // max directory length not fixed on Unix
public static void CreateDirectory_DirectoryEqualToMaxDirectory_CanBeCreated()
{ // Recursively creates directories right up to the maximum directory length ("247 chars not including null")
using (TemporaryDirectory directory = new TemporaryDirectory())
{
PathInfo path = IOServices.GetPath(directory.Path, IOInputs.MaxDirectory, IOInputs.MaxComponent);
// First create 'C:\AAA...AA', followed by 'C:\AAA...AAA\AAA...AAA', etc
foreach (string subpath in path.SubPaths)
{
DirectoryInfo result = Directory.CreateDirectory(subpath);
Assert.Equal(subpath, result.FullName);
Assert.True(Directory.Exists(result.FullName));
}
}
}
[Fact]
[PlatformSpecific(PlatformID.Windows)] // max directory length not fixed on Unix
public static void CreateDirectory_DirectoryEqualToMaxDirectory_CanBeCreatedAllAtOnce()
{ // Creates directories up to the maximum directory length all at once
using (TemporaryDirectory directory = new TemporaryDirectory())
{
PathInfo path = IOServices.GetPath(directory.Path, IOInputs.MaxDirectory, maxComponent: 10);
DirectoryInfo result = Directory.CreateDirectory(path.FullPath);
Assert.Equal(path.FullPath, result.FullName);
Assert.True(Directory.Exists(result.FullName));
}
}
[Fact]
public static void CreateDirectory_ValidPathWithTrailingSlash_CanBeCreated()
{
using (TemporaryDirectory directory = new TemporaryDirectory())
{
var components = IOInputs.GetValidPathComponentNames();
foreach (var component in components)
{
string path = IOServices.AddTrailingSlashIfNeeded(Path.Combine(directory.Path, component));
DirectoryInfo result = Directory.CreateDirectory(path);
Assert.Equal(path, result.FullName);
Assert.True(Directory.Exists(result.FullName));
}
}
}
[Fact]
public static void CreateDirectory_ValidPathWithoutTrailingSlashAsPath_CanBeCreated()
{
using (TemporaryDirectory directory = new TemporaryDirectory())
{
var components = IOInputs.GetValidPathComponentNames();
foreach (var component in components)
{
string path = directory.Path + Path.DirectorySeparatorChar + component;
DirectoryInfo result = Directory.CreateDirectory(path);
Assert.Equal(path, result.FullName);
Assert.True(Directory.Exists(result.FullName));
}
}
}
}
| |
// ---------------------------------------------------------------------------------------------------------------------
// <copyright file="Vs2008SolutionGenerator.cs" company="">
//
// </copyright>
// <summary>
// Defines the Vs2008SolutionGenerator type.
// </summary>
// ---------------------------------------------------------------------------------------------------------------------
namespace DbFriend.Core.Generator
{
using System;
using System.Collections.Generic;
using System.IO;
using Settings;
using Graph;
using Provider;
using Provider.MsSql;
using NVelocity;
/// <summary>
/// </summary>
public class Vs2008SolutionGenerator : IDbSolutionGenerator
{
/// <summary>
/// </summary>
private readonly IMsSqlConnectionSettings databaseSettings;
/// <summary>
/// </summary>
private readonly IVelocityFileGenerator fileGenerator;
/// <summary>
/// </summary>
private readonly IDbScriptFolderConfigurationSetting folderSettings;
/// <summary>
/// </summary>
private IDependencyGenerator dependencyGenerator;
/// <summary>
/// Initializes a new instance of the <see cref="Vs2008SolutionGenerator"/> class.
/// </summary>
/// <param name="databaseSettings">
/// The database settings.
/// </param>
/// <param name="folderSettings">
/// The folder settings.
/// </param>
/// <param name="fileGenerator">
/// The file generator.
/// </param>
/// <param name="dependencyGenerator">
/// The dependency generator.
/// </param>
public Vs2008SolutionGenerator(
IMsSqlConnectionSettings databaseSettings,
IDbScriptFolderConfigurationSetting folderSettings,
IVelocityFileGenerator fileGenerator,
IDependencyGenerator dependencyGenerator)
{
this.databaseSettings = databaseSettings;
this.fileGenerator = fileGenerator;
this.dependencyGenerator = dependencyGenerator;
this.folderSettings = folderSettings;
}
/// <summary>
/// Gets BaselinePath.
/// </summary>
/// <value>
/// The baseline path.
/// </value>
private string BaselinePath
{
get
{
string buildPath = Path.Combine(OutputPath, "build");
return Path.Combine(buildPath, "baseline");
}
}
/// <summary>
/// Gets BuildPath.
/// </summary>
/// <value>
/// The build path.
/// </value>
private string BuildPath
{
get { return Path.Combine(OutputPath, "build"); }
}
/// <summary>
/// Gets OutputPath.
/// </summary>
/// <value>
/// The output path.
/// </value>
private string OutputPath
{
get { return folderSettings.OutputFolder; }
}
/// <summary>
/// Gets SandboxDatabaseName.
/// </summary>
/// <value>
/// The sandbox database name.
/// </value>
private string SandboxDatabaseName
{
get { return databaseSettings.DatabaseName + "Sandbox"; }
}
/// <summary>
/// Gets SandboxPath.
/// </summary>
/// <value>
/// The sandbox path.
/// </value>
private string SandboxPath
{
get { return Path.Combine(BuildPath, "sandbox"); }
}
/// <summary>
/// </summary>
/// <param name="message">
/// The message.
/// </param>
public void Generate(Action<string> message)
{
MoveDbScriptsToFinalFolders();
CreateSolutionFile();
CreateDbProjectFile();
CreateBatchFiles();
CreateNantBuildFiles();
CreateSqlSandboxFiles();
CreateDeveloperProperties();
CopyFolderSkeleton();
}
/// <summary>
/// </summary>
private void CopyFolderSkeleton()
{
IDirectoryCopier copier = new DirectoryCopier();
string resources = Path.Combine(Directory.GetCurrentDirectory(), "Resources");
string skeleton = Path.Combine(resources, "skeleton");
copier.Copy(skeleton, OutputPath);
}
/// <summary>
/// </summary>
private void CreateBatchFiles()
{
var velocityContext = new VelocityContext();
velocityContext.Put("projectName", databaseSettings.DatabaseName);
GenerateFile(velocityContext, "build.bat.vm", Path.Combine(BuildPath, "build.bat"));
GenerateFile(velocityContext, "setupdb.bat.vm", Path.Combine(BuildPath, "setupdb.bat"));
GenerateFile(velocityContext, "sql.bat.vm", Path.Combine(BuildPath, "sql.bat"));
GenerateFile(velocityContext, "explore.bat.vm", Path.Combine(BuildPath, "explore.bat"));
GenerateFile(velocityContext, Path.Combine("VS2008", "open.bat.vm"), Path.Combine(BuildPath, "open.bat"));
}
/// <summary>
/// </summary>
private void CreateDbProjectFile()
{
Directory.CreateDirectory(OutputPath);
var velocityContext = new VelocityContext();
string dbrefString = string.Format("{0}.{1}.dbo", "localhost", SandboxDatabaseName);
velocityContext.Put("dbref", dbrefString);
velocityContext.Put("dbconnstring", string.Format(
"Data Source=localhost;Initial Catalog={0};Integrated Security=True;",
SandboxDatabaseName));
velocityContext.Put("spList", GetScriptedStoredProcedureList());
velocityContext.Put("tableList", GetScriptedTableList());
velocityContext.Put("functionList", GetScriptedFunctionList());
velocityContext.Put("viewList", GetScriptedViewList());
velocityContext.Put("projectName", databaseSettings.DatabaseName);
GenerateFile(
velocityContext,
Path.Combine("VS2008", "stub.dbp.vm"),
Path.Combine(OutputPath, databaseSettings.DatabaseName + "DB.dbp"));
}
/// <summary>
/// </summary>
private void CreateDeveloperProperties()
{
Directory.CreateDirectory(OutputPath);
var velocityContext = new VelocityContext();
velocityContext.Put("dbfriend-projectName", databaseSettings.DatabaseName);
GenerateFile(velocityContext, "developer.properties.xml.vm",
Path.Combine(BuildPath, "developer.properties.xml"));
}
/// <summary>
/// </summary>
private void CreateNantBuildFiles()
{
var velocityContext = new VelocityContext();
velocityContext.Put("projectName", databaseSettings.DatabaseName);
velocityContext.Put("dbfriend-nantGetCurrentDirectory", "${directory::get-current-directory()}");
velocityContext.Put("dbfriend-nantGetBaseDir",
"${directory::get-parent-directory(project::get-base-directory())}");
List<IDbObject> dependencyList = GetOrderedDependencyList();
velocityContext.Put("sqlobjectlist", dependencyList);
GenerateFile(velocityContext, "stub.build.vm",
Path.Combine(BuildPath, databaseSettings.DatabaseName + ".build"));
GenerateFile(velocityContext, "stub.core.build.vm",
Path.Combine(BuildPath, databaseSettings.DatabaseName + ".core.build"));
}
/// <summary>
/// </summary>
private void CreateSolutionFile()
{
Directory.CreateDirectory(OutputPath);
var velocityContext = new VelocityContext();
velocityContext.Put("dbGuid", Guid.NewGuid().ToString().ToUpper());
velocityContext.Put("projectName", databaseSettings.DatabaseName);
GenerateFile(
velocityContext,
Path.Combine("VS2008", "stub.sln.vm"),
Path.Combine(OutputPath, databaseSettings.DatabaseName + "DB.sln"));
}
/// <summary>
/// </summary>
private void CreateSqlSandboxFiles()
{
Directory.CreateDirectory(SandboxPath);
var velocityContext = new VelocityContext();
velocityContext.Put("projectName", databaseSettings.DatabaseName);
GenerateFile(velocityContext, "01_CreateSandbox.sql.vm", Path.Combine(SandboxPath, "01_CreateSandbox.sql"));
GenerateFile(
velocityContext, "02_SetupExternalDependencies.sql.vm",
Path.Combine(SandboxPath, "02_SetupExternalDependencies.sql"));
GenerateFile(velocityContext, "03_DefineSynonyms.sql.vm", Path.Combine(SandboxPath, "03_DefineSynonyms.sql"));
GenerateFile(velocityContext, "04_BuildShell.sql.vm", Path.Combine(SandboxPath, "04_BuildShell.sql"));
}
/// <summary>
/// </summary>
/// <param name="velocityContext">
/// The velocity context.
/// </param>
/// <param name="templatePath">
/// The template path.
/// </param>
/// <param name="outputFile">
/// The output file.
/// </param>
private void GenerateFile(VelocityContext velocityContext, string templatePath, string outputFile)
{
fileGenerator.Generate(templatePath, outputFile, velocityContext);
}
/// <summary>
/// </summary>
/// <param name="fileName">
/// The file name.
/// </param>
/// <returns>
/// </returns>
private string GetBaseFileName(string fileName)
{
var fileInfo = new FileInfo(fileName);
return fileInfo.Name;
}
/// <summary>
/// </summary>
/// <returns>
/// </returns>
private List<IDbObject> GetOrderedDependencyList()
{
IDependencyGraph graph = dependencyGenerator.GenerateGraph();
return new List<IDbObject>(graph.Dependencies);
}
/// <summary>
/// </summary>
/// <returns>
/// </returns>
private List<IScriptedFunction> GetScriptedFunctionList()
{
string baselinePath = BaselinePath;
var list = new List<IScriptedFunction>();
foreach (string fileName in Directory.GetFiles(Path.Combine(baselinePath, "UDFs")))
{
list.Add(new ScriptedFunction(GetBaseFileName(fileName)));
}
return list;
}
/// <summary>
/// </summary>
/// <returns>
/// </returns>
private List<IScriptedStoredProcedure> GetScriptedStoredProcedureList()
{
string baselinePath = BaselinePath;
var list = new List<IScriptedStoredProcedure>();
foreach (string fileName in Directory.GetFiles(Path.Combine(baselinePath, "SPs")))
{
list.Add(new ScriptedStoredProcedure(GetBaseFileName(fileName)));
}
return list;
}
/// <summary>
/// </summary>
/// <returns>
/// </returns>
private List<IScriptedTable> GetScriptedTableList()
{
string baselinePath = BaselinePath;
var list = new List<IScriptedTable>();
foreach (string fileName in Directory.GetFiles(Path.Combine(baselinePath, "Tables")))
{
list.Add(new ScriptedTable(GetBaseFileName(fileName)));
}
return list;
}
/// <summary>
/// </summary>
/// <returns>
/// </returns>
private List<IScriptedView> GetScriptedViewList()
{
string baselinePath = BaselinePath;
var list = new List<IScriptedView>();
foreach (string fileName in Directory.GetFiles(Path.Combine(baselinePath, "Views")))
{
list.Add(new ScriptedView(GetBaseFileName(fileName)));
}
return list;
}
/// <summary>
/// </summary>
/// <param name="targetPath">
/// The target path.
/// </param>
private void MakeSureTargetDirectoryIsMissing(string targetPath)
{
if (Directory.Exists(targetPath))
{
var directoryInfo = new DirectoryInfo(targetPath);
directoryInfo.Delete(true);
}
}
/// <summary>
/// </summary>
private void MoveDbScriptsToFinalFolders()
{
Directory.CreateDirectory(BuildPath);
MakeSureTargetDirectoryIsMissing(BaselinePath);
var directoryInfo = new DirectoryInfo(Path.Combine(OutputPath, "DbScripts"));
directoryInfo.MoveTo(BaselinePath);
}
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Text;
using NUnit.Framework;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Cms;
using Org.BouncyCastle.Asn1.Oiw;
using Org.BouncyCastle.Cms;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.IO;
using Org.BouncyCastle.Utilities.Test;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.X509.Store;
namespace Org.BouncyCastle.Cms.Tests
{
[TestFixture]
public class SignedDataStreamTest
{
private const string TestMessage = "Hello World!";
private const string SignDN = "O=Bouncy Castle, C=AU";
private static AsymmetricCipherKeyPair signKP;
private static X509Certificate signCert;
private const string OrigDN = "CN=Bob, OU=Sales, O=Bouncy Castle, C=AU";
private static AsymmetricCipherKeyPair origKP;
private static X509Certificate origCert;
private const string ReciDN = "CN=Doug, OU=Sales, O=Bouncy Castle, C=AU";
// private static AsymmetricCipherKeyPair reciKP;
// private static X509Certificate reciCert;
private static AsymmetricCipherKeyPair origDsaKP;
private static X509Certificate origDsaCert;
private static X509Crl signCrl;
private static X509Crl origCrl;
private static AsymmetricCipherKeyPair SignKP
{
get { return signKP == null ? (signKP = CmsTestUtil.MakeKeyPair()) : signKP; }
}
private static AsymmetricCipherKeyPair OrigKP
{
get { return origKP == null ? (origKP = CmsTestUtil.MakeKeyPair()) : origKP; }
}
// private static AsymmetricCipherKeyPair ReciKP
// {
// get { return reciKP == null ? (reciKP = CmsTestUtil.MakeKeyPair()) : reciKP; }
// }
private static AsymmetricCipherKeyPair OrigDsaKP
{
get { return origDsaKP == null ? (origDsaKP = CmsTestUtil.MakeDsaKeyPair()) : origDsaKP; }
}
private static X509Certificate SignCert
{
get { return signCert == null ? (signCert = CmsTestUtil.MakeCertificate(SignKP, SignDN, SignKP, SignDN)) : signCert; }
}
private static X509Certificate OrigCert
{
get { return origCert == null ? (origCert = CmsTestUtil.MakeCertificate(OrigKP, OrigDN, SignKP, SignDN)) : origCert; }
}
// private static X509Certificate ReciCert
// {
// get { return reciCert == null ? (reciCert = CmsTestUtil.MakeCertificate(ReciKP, ReciDN, SignKP, SignDN)) : reciCert; }
// }
private static X509Certificate OrigDsaCert
{
get { return origDsaCert == null ? (origDsaCert = CmsTestUtil.MakeCertificate(OrigDsaKP, OrigDN, SignKP, SignDN)) : origDsaCert; }
}
private static X509Crl SignCrl
{
get { return signCrl == null ? (signCrl = CmsTestUtil.MakeCrl(SignKP)) : signCrl; }
}
private static X509Crl OrigCrl
{
get { return origCrl == null ? (origCrl = CmsTestUtil.MakeCrl(OrigKP)) : origCrl; }
}
private void VerifySignatures(
CmsSignedDataParser sp,
byte[] contentDigest)
{
IX509Store certStore = sp.GetCertificates("Collection");
SignerInformationStore signers = sp.GetSignerInfos();
foreach (SignerInformation signer in signers.GetSigners())
{
ICollection certCollection = certStore.GetMatches(signer.SignerID);
IEnumerator certEnum = certCollection.GetEnumerator();
certEnum.MoveNext();
X509Certificate cert = (X509Certificate) certEnum.Current;
Assert.IsTrue(signer.Verify(cert));
if (contentDigest != null)
{
Assert.IsTrue(Arrays.AreEqual(contentDigest, signer.GetContentDigest()));
}
}
}
private void VerifySignatures(
CmsSignedDataParser sp)
{
VerifySignatures(sp, null);
}
private void VerifyEncodedData(
MemoryStream bOut)
{
CmsSignedDataParser sp = new CmsSignedDataParser(bOut.ToArray());
sp.GetSignedContent().Drain();
VerifySignatures(sp);
sp.Close();
}
private void CheckSigParseable(byte[] sig)
{
CmsSignedDataParser sp = new CmsSignedDataParser(sig);
sp.Version.ToString();
CmsTypedStream sc = sp.GetSignedContent();
if (sc != null)
{
sc.Drain();
}
sp.GetAttributeCertificates("Collection");
sp.GetCertificates("Collection");
sp.GetCrls("Collection");
sp.GetSignerInfos();
sp.Close();
}
[Test]
public void TestEarlyInvalidKeyException()
{
try
{
CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();
gen.AddSigner(OrigKP.Private, OrigCert,
"DSA", // DOESN'T MATCH KEY ALG
CmsSignedDataStreamGenerator.DigestSha1);
Assert.Fail("Expected InvalidKeyException in AddSigner");
}
catch (InvalidKeyException)
{
// Ignore
}
}
[Test]
public void TestEarlyNoSuchAlgorithmException()
{
try
{
CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();
gen.AddSigner(OrigKP.Private, OrigCert,
CmsSignedDataStreamGenerator.DigestSha1, // BAD OID!
CmsSignedDataStreamGenerator.DigestSha1);
Assert.Fail("Expected NoSuchAlgorithmException in AddSigner");
}
catch (SecurityUtilityException)
{
// Ignore
}
}
[Test]
public void TestSha1EncapsulatedSignature()
{
byte[] encapSigData = Base64.Decode(
"MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEH"
+ "AaCAJIAEDEhlbGxvIFdvcmxkIQAAAAAAAKCCBGIwggINMIIBdqADAgECAgEF"
+ "MA0GCSqGSIb3DQEBBAUAMCUxFjAUBgNVBAoTDUJvdW5jeSBDYXN0bGUxCzAJ"
+ "BgNVBAYTAkFVMB4XDTA1MDgwNzA2MjU1OVoXDTA1MTExNTA2MjU1OVowJTEW"
+ "MBQGA1UEChMNQm91bmN5IENhc3RsZTELMAkGA1UEBhMCQVUwgZ8wDQYJKoZI"
+ "hvcNAQEBBQADgY0AMIGJAoGBAI1fZGgH9wgC3QiK6yluH6DlLDkXkxYYL+Qf"
+ "nVRszJVYl0LIxZdpb7WEbVpO8fwtEgFtoDsOdxyqh3dTBv+L7NVD/v46kdPt"
+ "xVkSNHRbutJVY8Xn4/TC/CDngqtbpbniMO8n0GiB6vs94gBT20M34j96O2IF"
+ "73feNHP+x8PkJ+dNAgMBAAGjTTBLMB0GA1UdDgQWBBQ3XUfEE6+D+t+LIJgK"
+ "ESSUE58eyzAfBgNVHSMEGDAWgBQ3XUfEE6+D+t+LIJgKESSUE58eyzAJBgNV"
+ "HRMEAjAAMA0GCSqGSIb3DQEBBAUAA4GBAFK3r1stYOeXYJOlOyNGDTWEhZ+a"
+ "OYdFeFaS6c+InjotHuFLAy+QsS8PslE48zYNFEqYygGfLhZDLlSnJ/LAUTqF"
+ "01vlp+Bgn/JYiJazwi5WiiOTf7Th6eNjHFKXS3hfSGPNPIOjvicAp3ce3ehs"
+ "uK0MxgLAaxievzhFfJcGSUMDMIICTTCCAbagAwIBAgIBBzANBgkqhkiG9w0B"
+ "AQQFADAlMRYwFAYDVQQKEw1Cb3VuY3kgQ2FzdGxlMQswCQYDVQQGEwJBVTAe"
+ "Fw0wNTA4MDcwNjI1NTlaFw0wNTExMTUwNjI1NTlaMGUxGDAWBgNVBAMTD0Vy"
+ "aWMgSC4gRWNoaWRuYTEkMCIGCSqGSIb3DQEJARYVZXJpY0Bib3VuY3ljYXN0"
+ "bGUub3JnMRYwFAYDVQQKEw1Cb3VuY3kgQ2FzdGxlMQswCQYDVQQGEwJBVTCB"
+ "nzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAgHCJyfwV6/V3kqSu2SOU2E/K"
+ "I+N0XohCMUaxPLLNtNBZ3ijxwaV6JGFz7siTgZD/OGfzir/eZimkt+L1iXQn"
+ "OAB+ZChivKvHtX+dFFC7Vq+E4Uy0Ftqc/wrGxE6DHb5BR0hprKH8wlDS8wSP"
+ "zxovgk4nH0ffUZOoDSuUgjh3gG8CAwEAAaNNMEswHQYDVR0OBBYEFLfY/4EG"
+ "mYrvJa7Cky+K9BJ7YmERMB8GA1UdIwQYMBaAFDddR8QTr4P634sgmAoRJJQT"
+ "nx7LMAkGA1UdEwQCMAAwDQYJKoZIhvcNAQEEBQADgYEADIOmpMd6UHdMjkyc"
+ "mIE1yiwfClCsGhCK9FigTg6U1G2FmkBwJIMWBlkeH15uvepsAncsgK+Cn3Zr"
+ "dZMb022mwtTJDtcaOM+SNeuCnjdowZ4i71Hf68siPm6sMlZkhz49rA0Yidoo"
+ "WuzYOO+dggzwDsMldSsvsDo/ARyCGOulDOAxggEvMIIBKwIBATAqMCUxFjAU"
+ "BgNVBAoTDUJvdW5jeSBDYXN0bGUxCzAJBgNVBAYTAkFVAgEHMAkGBSsOAwIa"
+ "BQCgXTAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcBMBwGCSqGSIb3DQEJBTEP"
+ "Fw0wNTA4MDcwNjI1NTlaMCMGCSqGSIb3DQEJBDEWBBQu973mCM5UBOl9XwQv"
+ "lfifHCMocTANBgkqhkiG9w0BAQEFAASBgGxnBl2qozYKLgZ0ygqSFgWcRGl1"
+ "LgNuE587LtO+EKkgoc3aFqEdjXlAyP8K7naRsvWnFrsB6pUpnrgI9Z8ZSKv8"
+ "98IlpsSSJ0jBlEb4gzzavwcBpYbr2ryOtDcF+kYmKIpScglyyoLzm+KPXOoT"
+ "n7MsJMoKN3Kd2Vzh6s10PFgeAAAAAAAA");
CmsSignedDataParser sp = new CmsSignedDataParser(encapSigData);
sp.GetSignedContent().Drain();
VerifySignatures(sp);
}
// [Test]
// public void TestSha1WithRsaNoAttributes()
// {
// IList certList = new ArrayList();
// CmsProcessable msg = new CmsProcessableByteArray(Encoding.ASCII.GetBytes(TestMessage));
//
// certList.Add(OrigCert);
// certList.Add(SignCert);
//
// IX509Store x509Certs = X509StoreFactory.Create(
// "Certificate/Collection",
// new X509CollectionStoreParameters(certList));
//
// CmsSignedDataGenerator gen = new CmsSignedDataGenerator();
//
// gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestSha1);
//
// gen.AddCertificates(x509Certs);
//
// CmsSignedData s = gen.Generate(CmsSignedDataGenerator.Data, msg, false, false);
//
// CmsSignedDataParser sp = new CmsSignedDataParser(
// new CmsTypedStream(new MemoryStream(Encoding.ASCII.GetBytes(TestMessage), false)), s.GetEncoded());
//
// sp.GetSignedContent().Drain();
//
// //
// // compute expected content digest
// //
// IDigest md = DigestUtilities.GetDigest("SHA1");
//
// byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage);
// md.BlockUpdate(testBytes, 0, testBytes.Length);
// byte[] hash = DigestUtilities.DoFinal(md);
//
// VerifySignatures(sp, hash);
// }
// [Test]
// public void TestDsaNoAttributes()
// {
// IList certList = new ArrayList();
// CmsProcessable msg = new CmsProcessableByteArray(Encoding.ASCII.GetBytes(TestMessage));
//
// certList.Add(OrigDsaCert);
// certList.Add(SignCert);
//
// IX509Store x509Certs = X509StoreFactory.Create(
// "Certificate/Collection",
// new X509CollectionStoreParameters(certList));
//
// CmsSignedDataGenerator gen = new CmsSignedDataGenerator();
//
// gen.AddSigner(OrigDsaKP.Private, OrigDsaCert, CmsSignedDataGenerator.DigestSha1);
//
// gen.AddCertificates(x509Certs);
//
// CmsSignedData s = gen.Generate(CmsSignedDataGenerator.Data, msg, false, false);
//
// CmsSignedDataParser sp = new CmsSignedDataParser(
// new CmsTypedStream(
// new MemoryStream(Encoding.ASCII.GetBytes(TestMessage), false)),
// s.GetEncoded());
//
// sp.GetSignedContent().Drain();
//
// //
// // compute expected content digest
// //
// IDigest md = DigestUtilities.GetDigest("SHA1");
//
// byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage);
// md.BlockUpdate(testBytes, 0, testBytes.Length);
// byte[] hash = DigestUtilities.DoFinal(md);
//
// VerifySignatures(sp, hash);
// }
[Test]
public void TestSha1WithRsa()
{
IList certList = new ArrayList();
IList crlList = new ArrayList();
MemoryStream bOut = new MemoryStream();
certList.Add(OrigCert);
certList.Add(SignCert);
crlList.Add(SignCrl);
crlList.Add(OrigCrl);
IX509Store x509Certs = X509StoreFactory.Create(
"Certificate/Collection",
new X509CollectionStoreParameters(certList));
IX509Store x509Crls = X509StoreFactory.Create(
"CRL/Collection",
new X509CollectionStoreParameters(crlList));
CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();
gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1);
gen.AddCertificates(x509Certs);
gen.AddCrls(x509Crls);
Stream sigOut = gen.Open(bOut);
byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage);
sigOut.Write(testBytes, 0, testBytes.Length);
sigOut.Close();
CheckSigParseable(bOut.ToArray());
CmsSignedDataParser sp = new CmsSignedDataParser(
new CmsTypedStream(new MemoryStream(testBytes, false)), bOut.ToArray());
sp.GetSignedContent().Drain();
//
// compute expected content digest
//
IDigest md = DigestUtilities.GetDigest("SHA1");
md.BlockUpdate(testBytes, 0, testBytes.Length);
byte[] hash = DigestUtilities.DoFinal(md);
VerifySignatures(sp, hash);
//
// try using existing signer
//
gen = new CmsSignedDataStreamGenerator();
gen.AddSigners(sp.GetSignerInfos());
gen.AddCertificates(sp.GetCertificates("Collection"));
gen.AddCrls(sp.GetCrls("Collection"));
bOut.SetLength(0);
sigOut = gen.Open(bOut, true);
sigOut.Write(testBytes, 0, testBytes.Length);
sigOut.Close();
VerifyEncodedData(bOut);
//
// look for the CRLs
//
ArrayList col = new ArrayList(x509Crls.GetMatches(null));
Assert.AreEqual(2, col.Count);
Assert.IsTrue(col.Contains(SignCrl));
Assert.IsTrue(col.Contains(OrigCrl));
}
[Test]
public void TestSha1WithRsaNonData()
{
IList certList = new ArrayList();
IList crlList = new ArrayList();
MemoryStream bOut = new MemoryStream();
certList.Add(OrigCert);
certList.Add(SignCert);
crlList.Add(SignCrl);
crlList.Add(OrigCrl);
IX509Store x509Certs = X509StoreFactory.Create(
"Certificate/Collection",
new X509CollectionStoreParameters(certList));
IX509Store x509Crls = X509StoreFactory.Create(
"CRL/Collection",
new X509CollectionStoreParameters(crlList));
CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();
gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1);
gen.AddCertificates(x509Certs);
gen.AddCrls(x509Crls);
Stream sigOut = gen.Open(bOut, "1.2.3.4", true);
byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage);
sigOut.Write(testBytes, 0, testBytes.Length);
sigOut.Close();
CmsSignedDataParser sp = new CmsSignedDataParser(bOut.ToArray());
CmsTypedStream stream = sp.GetSignedContent();
Assert.AreEqual("1.2.3.4", stream.ContentType);
stream.Drain();
//
// compute expected content digest
//
IDigest md = DigestUtilities.GetDigest("SHA1");
md.BlockUpdate(testBytes, 0, testBytes.Length);
byte[] hash = DigestUtilities.DoFinal(md);
VerifySignatures(sp, hash);
}
[Test]
public void TestSha1AndMD5WithRsa()
{
IList certList = new ArrayList();
MemoryStream bOut = new MemoryStream();
certList.Add(OrigCert);
certList.Add(SignCert);
IX509Store x509Certs = X509StoreFactory.Create(
"Certificate/Collection",
new X509CollectionStoreParameters(certList));
CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();
gen.AddDigests(CmsSignedDataStreamGenerator.DigestSha1,
CmsSignedDataStreamGenerator.DigestMD5);
Stream sigOut = gen.Open(bOut);
byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage);
sigOut.Write(testBytes, 0, testBytes.Length);
gen.AddCertificates(x509Certs);
gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1);
gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestMD5);
sigOut.Close();
CheckSigParseable(bOut.ToArray());
CmsSignedDataParser sp = new CmsSignedDataParser(
new CmsTypedStream(new MemoryStream(testBytes, false)), bOut.ToArray());
sp.GetSignedContent().Drain();
VerifySignatures(sp);
}
[Test]
public void TestSha1WithRsaEncapsulatedBufferedStream()
{
IList certList = new ArrayList();
MemoryStream bOut = new MemoryStream();
certList.Add(OrigCert);
certList.Add(SignCert);
IX509Store x509Certs = X509StoreFactory.Create(
"Certificate/Collection",
new X509CollectionStoreParameters(certList));
//
// find unbuffered length
//
CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();
gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1);
gen.AddCertificates(x509Certs);
Stream sigOut = gen.Open(bOut, true);
for (int i = 0; i != 2000; i++)
{
sigOut.WriteByte((byte)(i & 0xff));
}
sigOut.Close();
CmsSignedDataParser sp = new CmsSignedDataParser(bOut.ToArray());
sp.GetSignedContent().Drain();
VerifySignatures(sp);
int unbufferedLength = bOut.ToArray().Length;
//
// find buffered length with buffered stream - should be equal
//
bOut.SetLength(0);
gen = new CmsSignedDataStreamGenerator();
gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1);
gen.AddCertificates(x509Certs);
sigOut = gen.Open(bOut, true);
byte[] data = new byte[2000];
for (int i = 0; i != 2000; i++)
{
data[i] = (byte)(i & 0xff);
}
Streams.PipeAll(new MemoryStream(data, false), sigOut);
sigOut.Close();
VerifyEncodedData(bOut);
Assert.AreEqual(unbufferedLength, bOut.ToArray().Length);
}
[Test]
public void TestSha1WithRsaEncapsulatedBuffered()
{
IList certList = new ArrayList();
MemoryStream bOut = new MemoryStream();
certList.Add(OrigCert);
certList.Add(SignCert);
IX509Store x509Certs = X509StoreFactory.Create(
"Certificate/Collection",
new X509CollectionStoreParameters(certList));
//
// find unbuffered length
//
CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();
gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1);
gen.AddCertificates(x509Certs);
Stream sigOut = gen.Open(bOut, true);
for (int i = 0; i != 2000; i++)
{
sigOut.WriteByte((byte)(i & 0xff));
}
sigOut.Close();
CmsSignedDataParser sp = new CmsSignedDataParser(bOut.ToArray());
sp.GetSignedContent().Drain();
VerifySignatures(sp);
int unbufferedLength = bOut.ToArray().Length;
//
// find buffered length - buffer size less than default
//
bOut.SetLength(0);
gen = new CmsSignedDataStreamGenerator();
gen.SetBufferSize(300);
gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1);
gen.AddCertificates(x509Certs);
sigOut = gen.Open(bOut, true);
for (int i = 0; i != 2000; i++)
{
sigOut.WriteByte((byte)(i & 0xff));
}
sigOut.Close();
VerifyEncodedData(bOut);
Assert.IsTrue(unbufferedLength < bOut.ToArray().Length);
}
[Test]
public void TestSha1WithRsaEncapsulated()
{
IList certList = new ArrayList();
MemoryStream bOut = new MemoryStream();
certList.Add(OrigCert);
certList.Add(SignCert);
IX509Store x509Certs = X509StoreFactory.Create(
"Certificate/Collection",
new X509CollectionStoreParameters(certList));
CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();
gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1);
gen.AddCertificates(x509Certs);
Stream sigOut = gen.Open(bOut, true);
byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage);
sigOut.Write(testBytes, 0, testBytes.Length);
sigOut.Close();
CmsSignedDataParser sp = new CmsSignedDataParser(bOut.ToArray());
sp.GetSignedContent().Drain();
VerifySignatures(sp);
byte[] contentDigest = (byte[])gen.GetGeneratedDigests()[CmsSignedGenerator.DigestSha1];
ArrayList signers = new ArrayList(sp.GetSignerInfos().GetSigners());
AttributeTable table = ((SignerInformation) signers[0]).SignedAttributes;
Asn1.Cms.Attribute hash = table[CmsAttributes.MessageDigest];
Assert.IsTrue(Arrays.AreEqual(contentDigest, ((Asn1OctetString)hash.AttrValues[0]).GetOctets()));
//
// try using existing signer
//
gen = new CmsSignedDataStreamGenerator();
gen.AddSigners(sp.GetSignerInfos());
gen.AddCertificates(sp.GetCertificates("Collection"));
gen.AddCrls(sp.GetCrls("Collection"));
bOut.SetLength(0);
sigOut = gen.Open(bOut, true);
sigOut.Write(testBytes, 0, testBytes.Length);
sigOut.Close();
CmsSignedData sd = new CmsSignedData(
new CmsProcessableByteArray(testBytes), bOut.ToArray());
Assert.AreEqual(1, sd.GetSignerInfos().GetSigners().Count);
VerifyEncodedData(bOut);
}
private static readonly DerObjectIdentifier dummyOid1 = new DerObjectIdentifier("1.2.3");
private static readonly DerObjectIdentifier dummyOid2 = new DerObjectIdentifier("1.2.3.4");
private class SignedGenAttributeTableGenerator
: DefaultSignedAttributeTableGenerator
{
public override AttributeTable GetAttributes(
IDictionary parameters)
{
IDictionary table = createStandardAttributeTable(parameters);
DerOctetString val = new DerOctetString((byte[])parameters[CmsAttributeTableParameter.Digest]);
Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(dummyOid1, new DerSet(val));
table[attr.AttrType] = attr;
return new AttributeTable(table);
}
};
private class UnsignedGenAttributeTableGenerator
: CmsAttributeTableGenerator
{
public AttributeTable GetAttributes(
IDictionary parameters)
{
DerOctetString val = new DerOctetString((byte[])parameters[CmsAttributeTableParameter.Signature]);
Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute(dummyOid2, new DerSet(val));
return new AttributeTable(new DerSet(attr));
}
};
[Test]
public void TestSha1WithRsaEncapsulatedSubjectKeyID()
{
IList certList = new ArrayList();
MemoryStream bOut = new MemoryStream();
certList.Add(OrigCert);
certList.Add(SignCert);
IX509Store x509Certs = X509StoreFactory.Create(
"Certificate/Collection",
new X509CollectionStoreParameters(certList));
CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();
gen.AddSigner(OrigKP.Private,
CmsTestUtil.CreateSubjectKeyId(OrigCert.GetPublicKey()).GetKeyIdentifier(),
CmsSignedDataStreamGenerator.DigestSha1);
gen.AddCertificates(x509Certs);
Stream sigOut = gen.Open(bOut, true);
byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage);
sigOut.Write(testBytes, 0, testBytes.Length);
sigOut.Close();
CmsSignedDataParser sp = new CmsSignedDataParser(bOut.ToArray());
sp.GetSignedContent().Drain();
VerifySignatures(sp);
byte[] contentDigest = (byte[])gen.GetGeneratedDigests()[CmsSignedGenerator.DigestSha1];
ArrayList signers = new ArrayList(sp.GetSignerInfos().GetSigners());
AttributeTable table = ((SignerInformation) signers[0]).SignedAttributes;
Asn1.Cms.Attribute hash = table[CmsAttributes.MessageDigest];
Assert.IsTrue(Arrays.AreEqual(contentDigest, ((Asn1OctetString)hash.AttrValues[0]).GetOctets()));
//
// try using existing signer
//
gen = new CmsSignedDataStreamGenerator();
gen.AddSigners(sp.GetSignerInfos());
// gen.AddCertificatesAndCRLs(sp.getCertificatesAndCRLs("Collection", "BC"));
gen.AddCertificates(sp.GetCertificates("Collection"));
bOut.SetLength(0);
sigOut = gen.Open(bOut, true);
sigOut.Write(testBytes, 0, testBytes.Length);
sigOut.Close();
CmsSignedData sd = new CmsSignedData(new CmsProcessableByteArray(testBytes), bOut.ToArray());
Assert.AreEqual(1, sd.GetSignerInfos().GetSigners().Count);
VerifyEncodedData(bOut);
}
[Test]
public void TestAttributeGenerators()
{
IList certList = new ArrayList();
MemoryStream bOut = new MemoryStream();
certList.Add(OrigCert);
certList.Add(SignCert);
IX509Store x509Certs = X509StoreFactory.Create(
"Certificate/Collection",
new X509CollectionStoreParameters(certList));
CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();
CmsAttributeTableGenerator signedGen = new SignedGenAttributeTableGenerator();
CmsAttributeTableGenerator unsignedGen = new UnsignedGenAttributeTableGenerator();
gen.AddSigner(OrigKP.Private, OrigCert,
CmsSignedDataStreamGenerator.DigestSha1, signedGen, unsignedGen);
gen.AddCertificates(x509Certs);
Stream sigOut = gen.Open(bOut, true);
byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage);
sigOut.Write(testBytes, 0, testBytes.Length);
sigOut.Close();
CmsSignedDataParser sp = new CmsSignedDataParser(bOut.ToArray());
sp.GetSignedContent().Drain();
VerifySignatures(sp);
//
// check attributes
//
SignerInformationStore signers = sp.GetSignerInfos();
foreach (SignerInformation signer in signers.GetSigners())
{
checkAttribute(signer.GetContentDigest(), signer.SignedAttributes[dummyOid1]);
checkAttribute(signer.GetSignature(), signer.UnsignedAttributes[dummyOid2]);
}
}
private void checkAttribute(
byte[] expected,
Asn1.Cms.Attribute attr)
{
DerOctetString value = (DerOctetString)attr.AttrValues[0];
Assert.AreEqual(new DerOctetString(expected), value);
}
[Test]
public void TestWithAttributeCertificate()
{
IList certList = new ArrayList();
certList.Add(SignCert);
IX509Store x509Certs = X509StoreFactory.Create(
"Certificate/Collection",
new X509CollectionStoreParameters(certList));
CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();
gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataGenerator.DigestSha1);
gen.AddCertificates(x509Certs);
IX509AttributeCertificate attrCert = CmsTestUtil.GetAttributeCertificate();
ArrayList attrCerts = new ArrayList();
attrCerts.Add(attrCert);
IX509Store store = X509StoreFactory.Create(
"AttributeCertificate/Collection",
new X509CollectionStoreParameters(attrCerts));
gen.AddAttributeCertificates(store);
MemoryStream bOut = new MemoryStream();
Stream sigOut = gen.Open(bOut, true);
byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage);
sigOut.Write(testBytes, 0, testBytes.Length);
sigOut.Close();
CmsSignedDataParser sp = new CmsSignedDataParser(bOut.ToArray());
sp.GetSignedContent().Drain();
Assert.AreEqual(4, sp.Version);
store = sp.GetAttributeCertificates("Collection");
ArrayList coll = new ArrayList(store.GetMatches(null));
Assert.AreEqual(1, coll.Count);
Assert.IsTrue(coll.Contains(attrCert));
}
[Test]
public void TestSignerStoreReplacement()
{
IList certList = new ArrayList();
MemoryStream bOut = new MemoryStream();
byte[] data = Encoding.ASCII.GetBytes(TestMessage);
certList.Add(OrigCert);
certList.Add(SignCert);
IX509Store x509Certs = X509StoreFactory.Create(
"Certificate/Collection",
new X509CollectionStoreParameters(certList));
CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();
gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1);
gen.AddCertificates(x509Certs);
Stream sigOut = gen.Open(bOut, false);
sigOut.Write(data, 0, data.Length);
sigOut.Close();
CheckSigParseable(bOut.ToArray());
//
// create new Signer
//
MemoryStream original = new MemoryStream(bOut.ToArray(), false);
bOut.SetLength(0);
gen = new CmsSignedDataStreamGenerator();
gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha224);
gen.AddCertificates(x509Certs);
sigOut = gen.Open(bOut);
sigOut.Write(data, 0, data.Length);
sigOut.Close();
CheckSigParseable(bOut.ToArray());
CmsSignedData sd = new CmsSignedData(bOut.ToArray());
//
// replace signer
//
MemoryStream newOut = new MemoryStream();
CmsSignedDataParser.ReplaceSigners(original, sd.GetSignerInfos(), newOut);
sd = new CmsSignedData(new CmsProcessableByteArray(data), newOut.ToArray());
IEnumerator signerEnum = sd.GetSignerInfos().GetSigners().GetEnumerator();
signerEnum.MoveNext();
SignerInformation signer = (SignerInformation) signerEnum.Current;
Assert.AreEqual(signer.DigestAlgOid, CmsSignedDataStreamGenerator.DigestSha224);
CmsSignedDataParser sp = new CmsSignedDataParser(new CmsTypedStream(
new MemoryStream(data, false)), newOut.ToArray());
sp.GetSignedContent().Drain();
VerifySignatures(sp);
}
[Test]
public void TestEncapsulatedSignerStoreReplacement()
{
IList certList = new ArrayList();
MemoryStream bOut = new MemoryStream();
certList.Add(OrigCert);
certList.Add(SignCert);
IX509Store x509Certs = X509StoreFactory.Create(
"Certificate/Collection",
new X509CollectionStoreParameters(certList));
CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();
gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1);
gen.AddCertificates(x509Certs);
Stream sigOut = gen.Open(bOut, true);
byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage);
sigOut.Write(testBytes, 0, testBytes.Length);
sigOut.Close();
//
// create new Signer
//
MemoryStream original = new MemoryStream(bOut.ToArray(), false);
bOut.SetLength(0);
gen = new CmsSignedDataStreamGenerator();
gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha224);
gen.AddCertificates(x509Certs);
sigOut = gen.Open(bOut, true);
sigOut.Write(testBytes, 0, testBytes.Length);
sigOut.Close();
CmsSignedData sd = new CmsSignedData(bOut.ToArray());
//
// replace signer
//
MemoryStream newOut = new MemoryStream();
CmsSignedDataParser.ReplaceSigners(original, sd.GetSignerInfos(), newOut);
sd = new CmsSignedData(newOut.ToArray());
IEnumerator signerEnum = sd.GetSignerInfos().GetSigners().GetEnumerator();
signerEnum.MoveNext();
SignerInformation signer = (SignerInformation) signerEnum.Current;
Assert.AreEqual(signer.DigestAlgOid, CmsSignedDataStreamGenerator.DigestSha224);
CmsSignedDataParser sp = new CmsSignedDataParser(newOut.ToArray());
sp.GetSignedContent().Drain();
VerifySignatures(sp);
}
[Test]
public void TestCertStoreReplacement()
{
IList certList = new ArrayList();
MemoryStream bOut = new MemoryStream();
byte[] data = Encoding.ASCII.GetBytes(TestMessage);
certList.Add(OrigDsaCert);
IX509Store x509Certs = X509StoreFactory.Create(
"Certificate/Collection",
new X509CollectionStoreParameters(certList));
CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();
gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1);
gen.AddCertificates(x509Certs);
Stream sigOut = gen.Open(bOut);
sigOut.Write(data, 0, data.Length);
sigOut.Close();
CheckSigParseable(bOut.ToArray());
//
// create new certstore with the right certificates
//
certList = new ArrayList();
certList.Add(OrigCert);
certList.Add(SignCert);
x509Certs = X509StoreFactory.Create(
"Certificate/Collection",
new X509CollectionStoreParameters(certList));
//
// replace certs
//
MemoryStream original = new MemoryStream(bOut.ToArray(), false);
MemoryStream newOut = new MemoryStream();
CmsSignedDataParser.ReplaceCertificatesAndCrls(original, x509Certs, null, null, newOut);
CmsSignedDataParser sp = new CmsSignedDataParser(new CmsTypedStream(new MemoryStream(data, false)), newOut.ToArray());
sp.GetSignedContent().Drain();
VerifySignatures(sp);
}
[Test]
public void TestEncapsulatedCertStoreReplacement()
{
IList certList = new ArrayList();
MemoryStream bOut = new MemoryStream();
certList.Add(OrigDsaCert);
IX509Store x509Certs = X509StoreFactory.Create(
"Certificate/Collection",
new X509CollectionStoreParameters(certList));
CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();
gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1);
gen.AddCertificates(x509Certs);
Stream sigOut = gen.Open(bOut, true);
byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage);
sigOut.Write(testBytes, 0, testBytes.Length);
sigOut.Close();
//
// create new certstore with the right certificates
//
certList = new ArrayList();
certList.Add(OrigCert);
certList.Add(SignCert);
x509Certs = X509StoreFactory.Create(
"Certificate/Collection",
new X509CollectionStoreParameters(certList));
//
// replace certs
//
MemoryStream original = new MemoryStream(bOut.ToArray(), false);
MemoryStream newOut = new MemoryStream();
CmsSignedDataParser.ReplaceCertificatesAndCrls(original, x509Certs, null, null, newOut);
CmsSignedDataParser sp = new CmsSignedDataParser(newOut.ToArray());
sp.GetSignedContent().Drain();
VerifySignatures(sp);
}
[Test]
public void TestCertOrdering1()
{
IList certList = new ArrayList();
MemoryStream bOut = new MemoryStream();
certList.Add(OrigCert);
certList.Add(SignCert);
IX509Store x509Certs = X509StoreFactory.Create(
"Certificate/Collection",
new X509CollectionStoreParameters(certList));
CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();
gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1);
gen.AddCertificates(x509Certs);
Stream sigOut = gen.Open(bOut, true);
byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage);
sigOut.Write(testBytes, 0, testBytes.Length);
sigOut.Close();
CmsSignedDataParser sp = new CmsSignedDataParser(bOut.ToArray());
sp.GetSignedContent().Drain();
x509Certs = sp.GetCertificates("Collection");
ArrayList a = new ArrayList(x509Certs.GetMatches(null));
Assert.AreEqual(2, a.Count);
Assert.AreEqual(OrigCert, a[0]);
Assert.AreEqual(SignCert, a[1]);
}
[Test]
public void TestCertOrdering2()
{
IList certList = new ArrayList();
MemoryStream bOut = new MemoryStream();
certList.Add(SignCert);
certList.Add(OrigCert);
IX509Store x509Certs = X509StoreFactory.Create(
"Certificate/Collection",
new X509CollectionStoreParameters(certList));
CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator();
gen.AddSigner(OrigKP.Private, OrigCert, CmsSignedDataStreamGenerator.DigestSha1);
gen.AddCertificates(x509Certs);
Stream sigOut = gen.Open(bOut, true);
byte[] testBytes = Encoding.ASCII.GetBytes(TestMessage);
sigOut.Write(testBytes, 0, testBytes.Length);
sigOut.Close();
CmsSignedDataParser sp = new CmsSignedDataParser(bOut.ToArray());
sp.GetSignedContent().Drain();
x509Certs = sp.GetCertificates("Collection");
ArrayList a = new ArrayList(x509Certs.GetMatches(null));
Assert.AreEqual(2, a.Count);
Assert.AreEqual(SignCert, a[0]);
Assert.AreEqual(OrigCert, a[1]);
}
}
}
| |
using UnityEngine;
public enum AnchorPresets
{
TopLeft,
TopCenter,
TopRight,
MiddleLeft,
MiddleCenter,
MiddleRight,
BottomLeft,
BottonCenter,
BottomRight,
BottomStretch,
VertStretchLeft,
VertStretchRight,
VertStretchCenter,
HorStretchTop,
HorStretchMiddle,
HorStretchBottom,
StretchAll
}
public enum PivotPresets
{
TopLeft,
TopCenter,
TopRight,
MiddleLeft,
MiddleCenter,
MiddleRight,
BottomLeft,
BottomCenter,
BottomRight,
}
public static class RectTransformExtensions
{
public static void SetAnchor(this RectTransform source, AnchorPresets allign, int offsetX=0, int offsetY=0)
{
source.anchoredPosition = new Vector3(offsetX, offsetY, 0);
switch (allign)
{
case(AnchorPresets.TopLeft):
{
source.anchorMin = new Vector2(0, 1);
source.anchorMax = new Vector2(0, 1);
break;
}
case (AnchorPresets.TopCenter):
{
source.anchorMin = new Vector2(0.5f, 1);
source.anchorMax = new Vector2(0.5f, 1);
break;
}
case (AnchorPresets.TopRight):
{
source.anchorMin = new Vector2(1, 1);
source.anchorMax = new Vector2(1, 1);
break;
}
case (AnchorPresets.MiddleLeft):
{
source.anchorMin = new Vector2(0, 0.5f);
source.anchorMax = new Vector2(0, 0.5f);
break;
}
case (AnchorPresets.MiddleCenter):
{
source.anchorMin = new Vector2(0.5f, 0.5f);
source.anchorMax = new Vector2(0.5f, 0.5f);
break;
}
case (AnchorPresets.MiddleRight):
{
source.anchorMin = new Vector2(1, 0.5f);
source.anchorMax = new Vector2(1, 0.5f);
break;
}
case (AnchorPresets.BottomLeft):
{
source.anchorMin = new Vector2(0, 0);
source.anchorMax = new Vector2(0, 0);
break;
}
case (AnchorPresets.BottonCenter):
{
source.anchorMin = new Vector2(0.5f, 0);
source.anchorMax = new Vector2(0.5f,0);
break;
}
case (AnchorPresets.BottomRight):
{
source.anchorMin = new Vector2(1, 0);
source.anchorMax = new Vector2(1, 0);
break;
}
case (AnchorPresets.HorStretchTop):
{
source.anchorMin = new Vector2(0, 1);
source.anchorMax = new Vector2(1, 1);
break;
}
case (AnchorPresets.HorStretchMiddle):
{
source.anchorMin = new Vector2(0, 0.5f);
source.anchorMax = new Vector2(1, 0.5f);
break;
}
case (AnchorPresets.HorStretchBottom):
{
source.anchorMin = new Vector2(0, 0);
source.anchorMax = new Vector2(1, 0);
break;
}
case (AnchorPresets.VertStretchLeft):
{
source.anchorMin = new Vector2(0, 0);
source.anchorMax = new Vector2(0, 1);
break;
}
case (AnchorPresets.VertStretchCenter):
{
source.anchorMin = new Vector2(0.5f, 0);
source.anchorMax = new Vector2(0.5f, 1);
break;
}
case (AnchorPresets.VertStretchRight):
{
source.anchorMin = new Vector2(1, 0);
source.anchorMax = new Vector2(1, 1);
break;
}
case (AnchorPresets.StretchAll):
{
source.anchorMin = new Vector2(0, 0);
source.anchorMax = new Vector2(1, 1);
break;
}
}
}
public static void SetPivot(this RectTransform source, PivotPresets preset)
{
switch (preset)
{
case (PivotPresets.TopLeft):
{
source.pivot = new Vector2(0, 1);
break;
}
case (PivotPresets.TopCenter):
{
source.pivot = new Vector2(0.5f, 1);
break;
}
case (PivotPresets.TopRight):
{
source.pivot = new Vector2(1, 1);
break;
}
case (PivotPresets.MiddleLeft):
{
source.pivot = new Vector2(0, 0.5f);
break;
}
case (PivotPresets.MiddleCenter):
{
source.pivot = new Vector2(0.5f, 0.5f);
break;
}
case (PivotPresets.MiddleRight):
{
source.pivot = new Vector2(1, 0.5f);
break;
}
case (PivotPresets.BottomLeft):
{
source.pivot = new Vector2(0, 0);
break;
}
case (PivotPresets.BottomCenter):
{
source.pivot = new Vector2(0.5f, 0);
break;
}
case (PivotPresets.BottomRight):
{
source.pivot = new Vector2(1, 0);
break;
}
}
}
}
| |
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
* copy, modify, and distribute this software in source code or binary form for use
* in connection with the web services and APIs provided by Facebook.
*
* As with any software that integrates with the Facebook platform, your use of
* this software is subject to the Facebook Developer Principles and Policies
* [http://developers.facebook.com/policy/]. This copyright notice shall be
* included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
namespace Facebook.Unity.Editor
{
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEditor.FacebookEditor;
using UnityEngine;
[CustomEditor(typeof(FacebookSettings))]
public class FacebookSettingsEditor : UnityEditor.Editor
{
private bool showFacebookInitSettings = false;
private bool showAndroidUtils = EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android;
private bool showIOSSettings = EditorUserBuildSettings.activeBuildTarget.ToString() == "iOS";
private bool showAppLinksSettings = false;
private bool showAboutSection = false;
private GUIContent appNameLabel = new GUIContent("App Name [?]:", "For your own use and organization.\n(ex. 'dev', 'qa', 'prod')");
private GUIContent appIdLabel = new GUIContent("App Id [?]:", "Facebook App Ids can be found at https://developers.facebook.com/apps");
private GUIContent urlSuffixLabel = new GUIContent("URL Scheme Suffix [?]", "Use this to share Facebook APP ID's across multiple iOS apps. https://developers.facebook.com/docs/ios/share-appid-across-multiple-apps-ios-sdk/");
private GUIContent cookieLabel = new GUIContent("Cookie [?]", "Sets a cookie which your server-side code can use to validate a user's Facebook session");
private GUIContent loggingLabel = new GUIContent("Logging [?]", "(Web Player only) If true, outputs a verbose log to the Javascript console to facilitate debugging.");
private GUIContent statusLabel = new GUIContent("Status [?]", "If 'true', attempts to initialize the Facebook object with valid session data.");
private GUIContent xfbmlLabel = new GUIContent("Xfbml [?]", "(Web Player only If true) Facebook will immediately parse any XFBML elements on the Facebook Canvas page hosting the app");
private GUIContent frictionlessLabel = new GUIContent("Frictionless Requests [?]", "Use frictionless app requests, as described in their own documentation.");
private GUIContent packageNameLabel = new GUIContent("Package Name [?]", "aka: the bundle identifier");
private GUIContent classNameLabel = new GUIContent("Class Name [?]", "aka: the activity name");
private GUIContent debugAndroidKeyLabel = new GUIContent("Debug Android Key Hash [?]", "Copy this key to the Facebook Settings in order to test a Facebook Android app");
private GUIContent sdkVersion = new GUIContent("SDK Version [?]", "This Unity Facebook SDK version. If you have problems or compliments please include this so we know exactly what version to look out for.");
public override void OnInspectorGUI()
{
EditorGUILayout.Separator();
this.AppIdGUI();
EditorGUILayout.Separator();
this.FBParamsInitGUI();
EditorGUILayout.Separator();
this.AndroidUtilGUI();
EditorGUILayout.Separator();
this.IOSUtilGUI();
EditorGUILayout.Separator();
this.AppLinksUtilGUI();
EditorGUILayout.Separator();
this.AboutGUI();
EditorGUILayout.Separator();
this.BuildGUI();
}
private void AppIdGUI()
{
EditorGUILayout.LabelField("Add the Facebook App Id(s) associated with this game");
if (FacebookSettings.AppIds.Count == 0 || FacebookSettings.AppId == "0")
{
EditorGUILayout.HelpBox("Invalid App Id", MessageType.Error);
}
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(this.appNameLabel);
EditorGUILayout.LabelField(this.appIdLabel);
EditorGUILayout.EndHorizontal();
for (int i = 0; i < FacebookSettings.AppIds.Count; ++i)
{
EditorGUILayout.BeginHorizontal();
FacebookSettings.AppLabels[i] = EditorGUILayout.TextField(FacebookSettings.AppLabels[i]);
GUI.changed = false;
FacebookSettings.AppIds[i] = EditorGUILayout.TextField(FacebookSettings.AppIds[i]);
if (GUI.changed)
{
FacebookSettings.SettingsChanged();
ManifestMod.GenerateManifest();
}
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Add Another App Id"))
{
FacebookSettings.AppLabels.Add("New App");
FacebookSettings.AppIds.Add("0");
FacebookSettings.AppLinkSchemes.Add(new FacebookSettings.UrlSchemes());
FacebookSettings.SettingsChanged();
}
if (FacebookSettings.AppLabels.Count > 1)
{
if (GUILayout.Button("Remove Last App Id"))
{
FacebookSettings.AppLabels.Pop();
FacebookSettings.AppIds.Pop();
FacebookSettings.AppLinkSchemes.Pop();
FacebookSettings.SettingsChanged();
}
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space();
if (FacebookSettings.AppIds.Count > 1)
{
EditorGUILayout.HelpBox("2) Select Facebook App Id to be compiled with this game", MessageType.None);
GUI.changed = false;
FacebookSettings.SelectedAppIndex = EditorGUILayout.Popup(
"Selected App Id",
FacebookSettings.SelectedAppIndex,
FacebookSettings.AppIds.ToArray());
if (GUI.changed)
{
ManifestMod.GenerateManifest();
}
EditorGUILayout.Space();
}
else
{
FacebookSettings.SelectedAppIndex = 0;
}
}
private void FBParamsInitGUI()
{
this.showFacebookInitSettings = EditorGUILayout.Foldout(this.showFacebookInitSettings, "FB.Init() Parameters");
if (this.showFacebookInitSettings)
{
FacebookSettings.Cookie = EditorGUILayout.Toggle(this.cookieLabel, FacebookSettings.Cookie);
FacebookSettings.Logging = EditorGUILayout.Toggle(this.loggingLabel, FacebookSettings.Logging);
FacebookSettings.Status = EditorGUILayout.Toggle(this.statusLabel, FacebookSettings.Status);
FacebookSettings.Xfbml = EditorGUILayout.Toggle(this.xfbmlLabel, FacebookSettings.Xfbml);
FacebookSettings.FrictionlessRequests = EditorGUILayout.Toggle(this.frictionlessLabel, FacebookSettings.FrictionlessRequests);
}
EditorGUILayout.Space();
}
private void IOSUtilGUI()
{
this.showIOSSettings = EditorGUILayout.Foldout(this.showIOSSettings, "iOS Build Settings");
if (this.showIOSSettings)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(this.urlSuffixLabel, GUILayout.Width(135), GUILayout.Height(16));
FacebookSettings.IosURLSuffix = EditorGUILayout.TextField(FacebookSettings.IosURLSuffix);
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.Space();
}
private void AndroidUtilGUI()
{
this.showAndroidUtils = EditorGUILayout.Foldout(this.showAndroidUtils, "Android Build Facebook Settings");
if (this.showAndroidUtils)
{
if (!FacebookAndroidUtil.SetupProperly)
{
var msg = "Your Android setup is not right. Check the documentation.";
switch (FacebookAndroidUtil.SetupError)
{
case FacebookAndroidUtil.ErrorNoSDK:
msg = "You don't have the Android SDK setup! Go to " + (Application.platform == RuntimePlatform.OSXEditor ? "Unity" : "Edit") + "->Preferences... and set your Android SDK Location under External Tools";
break;
case FacebookAndroidUtil.ErrorNoKeystore:
msg = "Your android debug keystore file is missing! You can create new one by creating and building empty Android project in Ecplise.";
break;
case FacebookAndroidUtil.ErrorNoKeytool:
msg = "Keytool not found. Make sure that Java is installed, and that Java tools are in your path.";
break;
case FacebookAndroidUtil.ErrorNoOpenSSL:
msg = "OpenSSL not found. Make sure that OpenSSL is installed, and that it is in your path.";
break;
case FacebookAndroidUtil.ErrorKeytoolError:
msg = "Unkown error while getting Debug Android Key Hash.";
break;
}
EditorGUILayout.HelpBox(msg, MessageType.Warning);
}
EditorGUILayout.LabelField(
"Copy and Paste these into your \"Native Android App\" Settings on developers.facebook.com/apps");
this.SelectableLabelField(this.packageNameLabel, PlayerSettings.bundleIdentifier);
this.SelectableLabelField(this.classNameLabel, ManifestMod.DeepLinkingActivityName);
this.SelectableLabelField(this.debugAndroidKeyLabel, FacebookAndroidUtil.DebugKeyHash);
if (GUILayout.Button("Regenerate Android Manifest"))
{
ManifestMod.GenerateManifest();
}
}
EditorGUILayout.Space();
}
private void AppLinksUtilGUI()
{
this.showAppLinksSettings = EditorGUILayout.Foldout(this.showAppLinksSettings, "App Links Settings");
if (this.showAppLinksSettings)
{
for (int i = 0; i < FacebookSettings.AppLinkSchemes.Count; ++i)
{
EditorGUILayout.LabelField(string.Format("App Link Schemes for '{0}'", FacebookSettings.AppLabels[i]));
List<string> currentAppLinkSchemes = FacebookSettings.AppLinkSchemes[i].Schemes;
for (int j = 0; j < currentAppLinkSchemes.Count; ++j)
{
GUI.changed = false;
string scheme = EditorGUILayout.TextField(currentAppLinkSchemes[j]);
if (scheme != currentAppLinkSchemes[j])
{
currentAppLinkSchemes[j] = scheme;
FacebookSettings.SettingsChanged();
}
if (GUI.changed)
{
ManifestMod.GenerateManifest();
}
}
EditorGUILayout.BeginHorizontal();
if (GUILayout.Button("Add a Scheme"))
{
FacebookSettings.AppLinkSchemes[i].Schemes.Add(string.Empty);
FacebookSettings.SettingsChanged();
}
if (currentAppLinkSchemes.Count > 0)
{
if (GUILayout.Button("Remove Last Scheme"))
{
FacebookSettings.AppLinkSchemes[i].Schemes.Pop();
}
}
EditorGUILayout.EndHorizontal();
}
}
}
private void AboutGUI()
{
this.showAboutSection = EditorGUILayout.Foldout(this.showAboutSection, "About the Facebook SDK");
if (this.showAboutSection)
{
this.SelectableLabelField(this.sdkVersion, FacebookSdkVersion.Build);
EditorGUILayout.Space();
}
}
private void SelectableLabelField(GUIContent label, string value)
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(label, GUILayout.Width(180), GUILayout.Height(16));
EditorGUILayout.SelectableLabel(value, GUILayout.Height(16));
EditorGUILayout.EndHorizontal();
}
private void BuildGUI()
{
if (GUILayout.Button("Build SDK Package"))
{
try
{
string outputPath = FacebookBuild.ExportPackage();
EditorUtility.DisplayDialog("Finished Exporting unityPackage", "Exported to: " + outputPath, "Okay");
}
catch (System.Exception e)
{
EditorUtility.DisplayDialog("Error Exporting unityPackage", e.Message, "Okay");
}
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: POGOProtos.Map.Fort.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace POGOProtos.Map.Fort {
/// <summary>Holder for reflection information generated from POGOProtos.Map.Fort.proto</summary>
public static partial class POGOProtosMapFortReflection {
#region Descriptor
/// <summary>File descriptor for POGOProtos.Map.Fort.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static POGOProtosMapFortReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChlQT0dPUHJvdG9zLk1hcC5Gb3J0LnByb3RvEhNQT0dPUHJvdG9zLk1hcC5G",
"b3J0GhZQT0dPUHJvdG9zLkVudW1zLnByb3RvGh9QT0dPUHJvdG9zLkludmVu",
"dG9yeS5JdGVtLnByb3RvIrsECghGb3J0RGF0YRIKCgJpZBgBIAEoCRIiChps",
"YXN0X21vZGlmaWVkX3RpbWVzdGFtcF9tcxgCIAEoAxIQCghsYXRpdHVkZRgD",
"IAEoARIRCglsb25naXR1ZGUYBCABKAESDwoHZW5hYmxlZBgIIAEoCBIrCgR0",
"eXBlGAkgASgOMh0uUE9HT1Byb3Rvcy5NYXAuRm9ydC5Gb3J0VHlwZRIyCg1v",
"d25lZF9ieV90ZWFtGAUgASgOMhsuUE9HT1Byb3Rvcy5FbnVtcy5UZWFtQ29s",
"b3ISNQoQZ3VhcmRfcG9rZW1vbl9pZBgGIAEoDjIbLlBPR09Qcm90b3MuRW51",
"bXMuUG9rZW1vbklkEhgKEGd1YXJkX3Bva2Vtb25fY3AYByABKAUSEgoKZ3lt",
"X3BvaW50cxgKIAEoAxIUCgxpc19pbl9iYXR0bGUYCyABKAgSJgoeY29vbGRv",
"d25fY29tcGxldGVfdGltZXN0YW1wX21zGA4gASgDEjEKB3Nwb25zb3IYDyAB",
"KA4yIC5QT0dPUHJvdG9zLk1hcC5Gb3J0LkZvcnRTcG9uc29yEj4KDnJlbmRl",
"cmluZ190eXBlGBAgASgOMiYuUE9HT1Byb3Rvcy5NYXAuRm9ydC5Gb3J0UmVu",
"ZGVyaW5nVHlwZRIcChRhY3RpdmVfZm9ydF9tb2RpZmllchgMIAEoDBI0Cgls",
"dXJlX2luZm8YDSABKAsyIS5QT0dPUHJvdG9zLk1hcC5Gb3J0LkZvcnRMdXJl",
"SW5mbyKQAQoMRm9ydEx1cmVJbmZvEg8KB2ZvcnRfaWQYASABKAkSFAoMZW5j",
"b3VudGVyX2lkGAIgASgGEjYKEWFjdGl2ZV9wb2tlbW9uX2lkGAMgASgOMhsu",
"UE9HT1Byb3Rvcy5FbnVtcy5Qb2tlbW9uSWQSIQoZbHVyZV9leHBpcmVzX3Rp",
"bWVzdGFtcF9tcxgEIAEoAyKFAQoMRm9ydE1vZGlmaWVyEjIKB2l0ZW1faWQY",
"ASABKA4yIS5QT0dPUHJvdG9zLkludmVudG9yeS5JdGVtLkl0ZW1JZBIfChdl",
"eHBpcmF0aW9uX3RpbWVzdGFtcF9tcxgCIAEoAxIgChhkZXBsb3llcl9wbGF5",
"ZXJfY29kZW5hbWUYAyABKAkibwoLRm9ydFN1bW1hcnkSFwoPZm9ydF9zdW1t",
"YXJ5X2lkGAEgASgJEiIKGmxhc3RfbW9kaWZpZWRfdGltZXN0YW1wX21zGAIg",
"ASgDEhAKCGxhdGl0dWRlGAMgASgBEhEKCWxvbmdpdHVkZRgEIAEoASozChFG",
"b3J0UmVuZGVyaW5nVHlwZRILCgdERUZBVUxUEAASEQoNSU5URVJOQUxfVEVT",
"VBABKkIKC0ZvcnRTcG9uc29yEhEKDVVOU0VUX1NQT05TT1IQABINCglNQ0RP",
"TkFMRFMQARIRCg1QT0tFTU9OX1NUT1JFEAIqIwoIRm9ydFR5cGUSBwoDR1lN",
"EAASDgoKQ0hFQ0tQT0lOVBABUABQAWIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::POGOProtos.Enums.POGOProtosEnumsReflection.Descriptor, global::POGOProtos.Inventory.Item.POGOProtosInventoryItemReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(new[] {typeof(global::POGOProtos.Map.Fort.FortRenderingType), typeof(global::POGOProtos.Map.Fort.FortSponsor), typeof(global::POGOProtos.Map.Fort.FortType), }, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Map.Fort.FortData), global::POGOProtos.Map.Fort.FortData.Parser, new[]{ "Id", "LastModifiedTimestampMs", "Latitude", "Longitude", "Enabled", "Type", "OwnedByTeam", "GuardPokemonId", "GuardPokemonCp", "GymPoints", "IsInBattle", "CooldownCompleteTimestampMs", "Sponsor", "RenderingType", "ActiveFortModifier", "LureInfo" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Map.Fort.FortLureInfo), global::POGOProtos.Map.Fort.FortLureInfo.Parser, new[]{ "FortId", "EncounterId", "ActivePokemonId", "LureExpiresTimestampMs" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Map.Fort.FortModifier), global::POGOProtos.Map.Fort.FortModifier.Parser, new[]{ "ItemId", "ExpirationTimestampMs", "DeployerPlayerCodename" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Map.Fort.FortSummary), global::POGOProtos.Map.Fort.FortSummary.Parser, new[]{ "FortSummaryId", "LastModifiedTimestampMs", "Latitude", "Longitude" }, null, null, null)
}));
}
#endregion
}
#region Enums
public enum FortRenderingType {
[pbr::OriginalName("DEFAULT")] Default = 0,
[pbr::OriginalName("INTERNAL_TEST")] InternalTest = 1,
}
public enum FortSponsor {
[pbr::OriginalName("UNSET_SPONSOR")] UnsetSponsor = 0,
[pbr::OriginalName("MCDONALDS")] Mcdonalds = 1,
[pbr::OriginalName("POKEMON_STORE")] PokemonStore = 2,
}
public enum FortType {
[pbr::OriginalName("GYM")] Gym = 0,
[pbr::OriginalName("CHECKPOINT")] Checkpoint = 1,
}
#endregion
#region Messages
public sealed partial class FortData : pb::IMessage<FortData> {
private static readonly pb::MessageParser<FortData> _parser = new pb::MessageParser<FortData>(() => new FortData());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<FortData> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Map.Fort.POGOProtosMapFortReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FortData() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FortData(FortData other) : this() {
id_ = other.id_;
lastModifiedTimestampMs_ = other.lastModifiedTimestampMs_;
latitude_ = other.latitude_;
longitude_ = other.longitude_;
enabled_ = other.enabled_;
type_ = other.type_;
ownedByTeam_ = other.ownedByTeam_;
guardPokemonId_ = other.guardPokemonId_;
guardPokemonCp_ = other.guardPokemonCp_;
gymPoints_ = other.gymPoints_;
isInBattle_ = other.isInBattle_;
cooldownCompleteTimestampMs_ = other.cooldownCompleteTimestampMs_;
sponsor_ = other.sponsor_;
renderingType_ = other.renderingType_;
activeFortModifier_ = other.activeFortModifier_;
LureInfo = other.lureInfo_ != null ? other.LureInfo.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FortData Clone() {
return new FortData(this);
}
/// <summary>Field number for the "id" field.</summary>
public const int IdFieldNumber = 1;
private string id_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Id {
get { return id_; }
set {
id_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "last_modified_timestamp_ms" field.</summary>
public const int LastModifiedTimestampMsFieldNumber = 2;
private long lastModifiedTimestampMs_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long LastModifiedTimestampMs {
get { return lastModifiedTimestampMs_; }
set {
lastModifiedTimestampMs_ = value;
}
}
/// <summary>Field number for the "latitude" field.</summary>
public const int LatitudeFieldNumber = 3;
private double latitude_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double Latitude {
get { return latitude_; }
set {
latitude_ = value;
}
}
/// <summary>Field number for the "longitude" field.</summary>
public const int LongitudeFieldNumber = 4;
private double longitude_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double Longitude {
get { return longitude_; }
set {
longitude_ = value;
}
}
/// <summary>Field number for the "enabled" field.</summary>
public const int EnabledFieldNumber = 8;
private bool enabled_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Enabled {
get { return enabled_; }
set {
enabled_ = value;
}
}
/// <summary>Field number for the "type" field.</summary>
public const int TypeFieldNumber = 9;
private global::POGOProtos.Map.Fort.FortType type_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Map.Fort.FortType Type {
get { return type_; }
set {
type_ = value;
}
}
/// <summary>Field number for the "owned_by_team" field.</summary>
public const int OwnedByTeamFieldNumber = 5;
private global::POGOProtos.Enums.TeamColor ownedByTeam_ = 0;
/// <summary>
/// Team that owns the gym
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Enums.TeamColor OwnedByTeam {
get { return ownedByTeam_; }
set {
ownedByTeam_ = value;
}
}
/// <summary>Field number for the "guard_pokemon_id" field.</summary>
public const int GuardPokemonIdFieldNumber = 6;
private global::POGOProtos.Enums.PokemonId guardPokemonId_ = 0;
/// <summary>
/// Highest CP Pokemon at the gym
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Enums.PokemonId GuardPokemonId {
get { return guardPokemonId_; }
set {
guardPokemonId_ = value;
}
}
/// <summary>Field number for the "guard_pokemon_cp" field.</summary>
public const int GuardPokemonCpFieldNumber = 7;
private int guardPokemonCp_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int GuardPokemonCp {
get { return guardPokemonCp_; }
set {
guardPokemonCp_ = value;
}
}
/// <summary>Field number for the "gym_points" field.</summary>
public const int GymPointsFieldNumber = 10;
private long gymPoints_;
/// <summary>
/// Prestigate / experience of the gym
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long GymPoints {
get { return gymPoints_; }
set {
gymPoints_ = value;
}
}
/// <summary>Field number for the "is_in_battle" field.</summary>
public const int IsInBattleFieldNumber = 11;
private bool isInBattle_;
/// <summary>
/// Whether someone is battling at the gym currently
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool IsInBattle {
get { return isInBattle_; }
set {
isInBattle_ = value;
}
}
/// <summary>Field number for the "cooldown_complete_timestamp_ms" field.</summary>
public const int CooldownCompleteTimestampMsFieldNumber = 14;
private long cooldownCompleteTimestampMs_;
/// <summary>
/// Timestamp when the pokestop can be activated again to get items / xp
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long CooldownCompleteTimestampMs {
get { return cooldownCompleteTimestampMs_; }
set {
cooldownCompleteTimestampMs_ = value;
}
}
/// <summary>Field number for the "sponsor" field.</summary>
public const int SponsorFieldNumber = 15;
private global::POGOProtos.Map.Fort.FortSponsor sponsor_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Map.Fort.FortSponsor Sponsor {
get { return sponsor_; }
set {
sponsor_ = value;
}
}
/// <summary>Field number for the "rendering_type" field.</summary>
public const int RenderingTypeFieldNumber = 16;
private global::POGOProtos.Map.Fort.FortRenderingType renderingType_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Map.Fort.FortRenderingType RenderingType {
get { return renderingType_; }
set {
renderingType_ = value;
}
}
/// <summary>Field number for the "active_fort_modifier" field.</summary>
public const int ActiveFortModifierFieldNumber = 12;
private pb::ByteString activeFortModifier_ = pb::ByteString.Empty;
/// <summary>
/// Might represent the type of item applied to the pokestop, right now only lures can be applied
/// </summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pb::ByteString ActiveFortModifier {
get { return activeFortModifier_; }
set {
activeFortModifier_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "lure_info" field.</summary>
public const int LureInfoFieldNumber = 13;
private global::POGOProtos.Map.Fort.FortLureInfo lureInfo_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Map.Fort.FortLureInfo LureInfo {
get { return lureInfo_; }
set {
lureInfo_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as FortData);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(FortData other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Id != other.Id) return false;
if (LastModifiedTimestampMs != other.LastModifiedTimestampMs) return false;
if (Latitude != other.Latitude) return false;
if (Longitude != other.Longitude) return false;
if (Enabled != other.Enabled) return false;
if (Type != other.Type) return false;
if (OwnedByTeam != other.OwnedByTeam) return false;
if (GuardPokemonId != other.GuardPokemonId) return false;
if (GuardPokemonCp != other.GuardPokemonCp) return false;
if (GymPoints != other.GymPoints) return false;
if (IsInBattle != other.IsInBattle) return false;
if (CooldownCompleteTimestampMs != other.CooldownCompleteTimestampMs) return false;
if (Sponsor != other.Sponsor) return false;
if (RenderingType != other.RenderingType) return false;
if (ActiveFortModifier != other.ActiveFortModifier) return false;
if (!object.Equals(LureInfo, other.LureInfo)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Id.Length != 0) hash ^= Id.GetHashCode();
if (LastModifiedTimestampMs != 0L) hash ^= LastModifiedTimestampMs.GetHashCode();
if (Latitude != 0D) hash ^= Latitude.GetHashCode();
if (Longitude != 0D) hash ^= Longitude.GetHashCode();
if (Enabled != false) hash ^= Enabled.GetHashCode();
if (Type != 0) hash ^= Type.GetHashCode();
if (OwnedByTeam != 0) hash ^= OwnedByTeam.GetHashCode();
if (GuardPokemonId != 0) hash ^= GuardPokemonId.GetHashCode();
if (GuardPokemonCp != 0) hash ^= GuardPokemonCp.GetHashCode();
if (GymPoints != 0L) hash ^= GymPoints.GetHashCode();
if (IsInBattle != false) hash ^= IsInBattle.GetHashCode();
if (CooldownCompleteTimestampMs != 0L) hash ^= CooldownCompleteTimestampMs.GetHashCode();
if (Sponsor != 0) hash ^= Sponsor.GetHashCode();
if (RenderingType != 0) hash ^= RenderingType.GetHashCode();
if (ActiveFortModifier.Length != 0) hash ^= ActiveFortModifier.GetHashCode();
if (lureInfo_ != null) hash ^= LureInfo.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Id.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Id);
}
if (LastModifiedTimestampMs != 0L) {
output.WriteRawTag(16);
output.WriteInt64(LastModifiedTimestampMs);
}
if (Latitude != 0D) {
output.WriteRawTag(25);
output.WriteDouble(Latitude);
}
if (Longitude != 0D) {
output.WriteRawTag(33);
output.WriteDouble(Longitude);
}
if (OwnedByTeam != 0) {
output.WriteRawTag(40);
output.WriteEnum((int) OwnedByTeam);
}
if (GuardPokemonId != 0) {
output.WriteRawTag(48);
output.WriteEnum((int) GuardPokemonId);
}
if (GuardPokemonCp != 0) {
output.WriteRawTag(56);
output.WriteInt32(GuardPokemonCp);
}
if (Enabled != false) {
output.WriteRawTag(64);
output.WriteBool(Enabled);
}
if (Type != 0) {
output.WriteRawTag(72);
output.WriteEnum((int) Type);
}
if (GymPoints != 0L) {
output.WriteRawTag(80);
output.WriteInt64(GymPoints);
}
if (IsInBattle != false) {
output.WriteRawTag(88);
output.WriteBool(IsInBattle);
}
if (ActiveFortModifier.Length != 0) {
output.WriteRawTag(98);
output.WriteBytes(ActiveFortModifier);
}
if (lureInfo_ != null) {
output.WriteRawTag(106);
output.WriteMessage(LureInfo);
}
if (CooldownCompleteTimestampMs != 0L) {
output.WriteRawTag(112);
output.WriteInt64(CooldownCompleteTimestampMs);
}
if (Sponsor != 0) {
output.WriteRawTag(120);
output.WriteEnum((int) Sponsor);
}
if (RenderingType != 0) {
output.WriteRawTag(128, 1);
output.WriteEnum((int) RenderingType);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Id.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Id);
}
if (LastModifiedTimestampMs != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(LastModifiedTimestampMs);
}
if (Latitude != 0D) {
size += 1 + 8;
}
if (Longitude != 0D) {
size += 1 + 8;
}
if (Enabled != false) {
size += 1 + 1;
}
if (Type != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Type);
}
if (OwnedByTeam != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) OwnedByTeam);
}
if (GuardPokemonId != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) GuardPokemonId);
}
if (GuardPokemonCp != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(GuardPokemonCp);
}
if (GymPoints != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(GymPoints);
}
if (IsInBattle != false) {
size += 1 + 1;
}
if (CooldownCompleteTimestampMs != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(CooldownCompleteTimestampMs);
}
if (Sponsor != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Sponsor);
}
if (RenderingType != 0) {
size += 2 + pb::CodedOutputStream.ComputeEnumSize((int) RenderingType);
}
if (ActiveFortModifier.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(ActiveFortModifier);
}
if (lureInfo_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(LureInfo);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(FortData other) {
if (other == null) {
return;
}
if (other.Id.Length != 0) {
Id = other.Id;
}
if (other.LastModifiedTimestampMs != 0L) {
LastModifiedTimestampMs = other.LastModifiedTimestampMs;
}
if (other.Latitude != 0D) {
Latitude = other.Latitude;
}
if (other.Longitude != 0D) {
Longitude = other.Longitude;
}
if (other.Enabled != false) {
Enabled = other.Enabled;
}
if (other.Type != 0) {
Type = other.Type;
}
if (other.OwnedByTeam != 0) {
OwnedByTeam = other.OwnedByTeam;
}
if (other.GuardPokemonId != 0) {
GuardPokemonId = other.GuardPokemonId;
}
if (other.GuardPokemonCp != 0) {
GuardPokemonCp = other.GuardPokemonCp;
}
if (other.GymPoints != 0L) {
GymPoints = other.GymPoints;
}
if (other.IsInBattle != false) {
IsInBattle = other.IsInBattle;
}
if (other.CooldownCompleteTimestampMs != 0L) {
CooldownCompleteTimestampMs = other.CooldownCompleteTimestampMs;
}
if (other.Sponsor != 0) {
Sponsor = other.Sponsor;
}
if (other.RenderingType != 0) {
RenderingType = other.RenderingType;
}
if (other.ActiveFortModifier.Length != 0) {
ActiveFortModifier = other.ActiveFortModifier;
}
if (other.lureInfo_ != null) {
if (lureInfo_ == null) {
lureInfo_ = new global::POGOProtos.Map.Fort.FortLureInfo();
}
LureInfo.MergeFrom(other.LureInfo);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Id = input.ReadString();
break;
}
case 16: {
LastModifiedTimestampMs = input.ReadInt64();
break;
}
case 25: {
Latitude = input.ReadDouble();
break;
}
case 33: {
Longitude = input.ReadDouble();
break;
}
case 40: {
ownedByTeam_ = (global::POGOProtos.Enums.TeamColor) input.ReadEnum();
break;
}
case 48: {
guardPokemonId_ = (global::POGOProtos.Enums.PokemonId) input.ReadEnum();
break;
}
case 56: {
GuardPokemonCp = input.ReadInt32();
break;
}
case 64: {
Enabled = input.ReadBool();
break;
}
case 72: {
type_ = (global::POGOProtos.Map.Fort.FortType) input.ReadEnum();
break;
}
case 80: {
GymPoints = input.ReadInt64();
break;
}
case 88: {
IsInBattle = input.ReadBool();
break;
}
case 98: {
ActiveFortModifier = input.ReadBytes();
break;
}
case 106: {
if (lureInfo_ == null) {
lureInfo_ = new global::POGOProtos.Map.Fort.FortLureInfo();
}
input.ReadMessage(lureInfo_);
break;
}
case 112: {
CooldownCompleteTimestampMs = input.ReadInt64();
break;
}
case 120: {
sponsor_ = (global::POGOProtos.Map.Fort.FortSponsor) input.ReadEnum();
break;
}
case 128: {
renderingType_ = (global::POGOProtos.Map.Fort.FortRenderingType) input.ReadEnum();
break;
}
}
}
}
}
public sealed partial class FortLureInfo : pb::IMessage<FortLureInfo> {
private static readonly pb::MessageParser<FortLureInfo> _parser = new pb::MessageParser<FortLureInfo>(() => new FortLureInfo());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<FortLureInfo> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Map.Fort.POGOProtosMapFortReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FortLureInfo() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FortLureInfo(FortLureInfo other) : this() {
fortId_ = other.fortId_;
encounterId_ = other.encounterId_;
activePokemonId_ = other.activePokemonId_;
lureExpiresTimestampMs_ = other.lureExpiresTimestampMs_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FortLureInfo Clone() {
return new FortLureInfo(this);
}
/// <summary>Field number for the "fort_id" field.</summary>
public const int FortIdFieldNumber = 1;
private string fortId_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string FortId {
get { return fortId_; }
set {
fortId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "encounter_id" field.</summary>
public const int EncounterIdFieldNumber = 2;
private ulong encounterId_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ulong EncounterId {
get { return encounterId_; }
set {
encounterId_ = value;
}
}
/// <summary>Field number for the "active_pokemon_id" field.</summary>
public const int ActivePokemonIdFieldNumber = 3;
private global::POGOProtos.Enums.PokemonId activePokemonId_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Enums.PokemonId ActivePokemonId {
get { return activePokemonId_; }
set {
activePokemonId_ = value;
}
}
/// <summary>Field number for the "lure_expires_timestamp_ms" field.</summary>
public const int LureExpiresTimestampMsFieldNumber = 4;
private long lureExpiresTimestampMs_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long LureExpiresTimestampMs {
get { return lureExpiresTimestampMs_; }
set {
lureExpiresTimestampMs_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as FortLureInfo);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(FortLureInfo other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (FortId != other.FortId) return false;
if (EncounterId != other.EncounterId) return false;
if (ActivePokemonId != other.ActivePokemonId) return false;
if (LureExpiresTimestampMs != other.LureExpiresTimestampMs) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (FortId.Length != 0) hash ^= FortId.GetHashCode();
if (EncounterId != 0UL) hash ^= EncounterId.GetHashCode();
if (ActivePokemonId != 0) hash ^= ActivePokemonId.GetHashCode();
if (LureExpiresTimestampMs != 0L) hash ^= LureExpiresTimestampMs.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (FortId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(FortId);
}
if (EncounterId != 0UL) {
output.WriteRawTag(17);
output.WriteFixed64(EncounterId);
}
if (ActivePokemonId != 0) {
output.WriteRawTag(24);
output.WriteEnum((int) ActivePokemonId);
}
if (LureExpiresTimestampMs != 0L) {
output.WriteRawTag(32);
output.WriteInt64(LureExpiresTimestampMs);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (FortId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(FortId);
}
if (EncounterId != 0UL) {
size += 1 + 8;
}
if (ActivePokemonId != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ActivePokemonId);
}
if (LureExpiresTimestampMs != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(LureExpiresTimestampMs);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(FortLureInfo other) {
if (other == null) {
return;
}
if (other.FortId.Length != 0) {
FortId = other.FortId;
}
if (other.EncounterId != 0UL) {
EncounterId = other.EncounterId;
}
if (other.ActivePokemonId != 0) {
ActivePokemonId = other.ActivePokemonId;
}
if (other.LureExpiresTimestampMs != 0L) {
LureExpiresTimestampMs = other.LureExpiresTimestampMs;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
FortId = input.ReadString();
break;
}
case 17: {
EncounterId = input.ReadFixed64();
break;
}
case 24: {
activePokemonId_ = (global::POGOProtos.Enums.PokemonId) input.ReadEnum();
break;
}
case 32: {
LureExpiresTimestampMs = input.ReadInt64();
break;
}
}
}
}
}
public sealed partial class FortModifier : pb::IMessage<FortModifier> {
private static readonly pb::MessageParser<FortModifier> _parser = new pb::MessageParser<FortModifier>(() => new FortModifier());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<FortModifier> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Map.Fort.POGOProtosMapFortReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FortModifier() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FortModifier(FortModifier other) : this() {
itemId_ = other.itemId_;
expirationTimestampMs_ = other.expirationTimestampMs_;
deployerPlayerCodename_ = other.deployerPlayerCodename_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FortModifier Clone() {
return new FortModifier(this);
}
/// <summary>Field number for the "item_id" field.</summary>
public const int ItemIdFieldNumber = 1;
private global::POGOProtos.Inventory.Item.ItemId itemId_ = 0;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::POGOProtos.Inventory.Item.ItemId ItemId {
get { return itemId_; }
set {
itemId_ = value;
}
}
/// <summary>Field number for the "expiration_timestamp_ms" field.</summary>
public const int ExpirationTimestampMsFieldNumber = 2;
private long expirationTimestampMs_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long ExpirationTimestampMs {
get { return expirationTimestampMs_; }
set {
expirationTimestampMs_ = value;
}
}
/// <summary>Field number for the "deployer_player_codename" field.</summary>
public const int DeployerPlayerCodenameFieldNumber = 3;
private string deployerPlayerCodename_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string DeployerPlayerCodename {
get { return deployerPlayerCodename_; }
set {
deployerPlayerCodename_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as FortModifier);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(FortModifier other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (ItemId != other.ItemId) return false;
if (ExpirationTimestampMs != other.ExpirationTimestampMs) return false;
if (DeployerPlayerCodename != other.DeployerPlayerCodename) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (ItemId != 0) hash ^= ItemId.GetHashCode();
if (ExpirationTimestampMs != 0L) hash ^= ExpirationTimestampMs.GetHashCode();
if (DeployerPlayerCodename.Length != 0) hash ^= DeployerPlayerCodename.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (ItemId != 0) {
output.WriteRawTag(8);
output.WriteEnum((int) ItemId);
}
if (ExpirationTimestampMs != 0L) {
output.WriteRawTag(16);
output.WriteInt64(ExpirationTimestampMs);
}
if (DeployerPlayerCodename.Length != 0) {
output.WriteRawTag(26);
output.WriteString(DeployerPlayerCodename);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (ItemId != 0) {
size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) ItemId);
}
if (ExpirationTimestampMs != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(ExpirationTimestampMs);
}
if (DeployerPlayerCodename.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(DeployerPlayerCodename);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(FortModifier other) {
if (other == null) {
return;
}
if (other.ItemId != 0) {
ItemId = other.ItemId;
}
if (other.ExpirationTimestampMs != 0L) {
ExpirationTimestampMs = other.ExpirationTimestampMs;
}
if (other.DeployerPlayerCodename.Length != 0) {
DeployerPlayerCodename = other.DeployerPlayerCodename;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 8: {
itemId_ = (global::POGOProtos.Inventory.Item.ItemId) input.ReadEnum();
break;
}
case 16: {
ExpirationTimestampMs = input.ReadInt64();
break;
}
case 26: {
DeployerPlayerCodename = input.ReadString();
break;
}
}
}
}
}
public sealed partial class FortSummary : pb::IMessage<FortSummary> {
private static readonly pb::MessageParser<FortSummary> _parser = new pb::MessageParser<FortSummary>(() => new FortSummary());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<FortSummary> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::POGOProtos.Map.Fort.POGOProtosMapFortReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FortSummary() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FortSummary(FortSummary other) : this() {
fortSummaryId_ = other.fortSummaryId_;
lastModifiedTimestampMs_ = other.lastModifiedTimestampMs_;
latitude_ = other.latitude_;
longitude_ = other.longitude_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public FortSummary Clone() {
return new FortSummary(this);
}
/// <summary>Field number for the "fort_summary_id" field.</summary>
public const int FortSummaryIdFieldNumber = 1;
private string fortSummaryId_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string FortSummaryId {
get { return fortSummaryId_; }
set {
fortSummaryId_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "last_modified_timestamp_ms" field.</summary>
public const int LastModifiedTimestampMsFieldNumber = 2;
private long lastModifiedTimestampMs_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long LastModifiedTimestampMs {
get { return lastModifiedTimestampMs_; }
set {
lastModifiedTimestampMs_ = value;
}
}
/// <summary>Field number for the "latitude" field.</summary>
public const int LatitudeFieldNumber = 3;
private double latitude_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double Latitude {
get { return latitude_; }
set {
latitude_ = value;
}
}
/// <summary>Field number for the "longitude" field.</summary>
public const int LongitudeFieldNumber = 4;
private double longitude_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public double Longitude {
get { return longitude_; }
set {
longitude_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as FortSummary);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(FortSummary other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (FortSummaryId != other.FortSummaryId) return false;
if (LastModifiedTimestampMs != other.LastModifiedTimestampMs) return false;
if (Latitude != other.Latitude) return false;
if (Longitude != other.Longitude) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (FortSummaryId.Length != 0) hash ^= FortSummaryId.GetHashCode();
if (LastModifiedTimestampMs != 0L) hash ^= LastModifiedTimestampMs.GetHashCode();
if (Latitude != 0D) hash ^= Latitude.GetHashCode();
if (Longitude != 0D) hash ^= Longitude.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (FortSummaryId.Length != 0) {
output.WriteRawTag(10);
output.WriteString(FortSummaryId);
}
if (LastModifiedTimestampMs != 0L) {
output.WriteRawTag(16);
output.WriteInt64(LastModifiedTimestampMs);
}
if (Latitude != 0D) {
output.WriteRawTag(25);
output.WriteDouble(Latitude);
}
if (Longitude != 0D) {
output.WriteRawTag(33);
output.WriteDouble(Longitude);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (FortSummaryId.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(FortSummaryId);
}
if (LastModifiedTimestampMs != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(LastModifiedTimestampMs);
}
if (Latitude != 0D) {
size += 1 + 8;
}
if (Longitude != 0D) {
size += 1 + 8;
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(FortSummary other) {
if (other == null) {
return;
}
if (other.FortSummaryId.Length != 0) {
FortSummaryId = other.FortSummaryId;
}
if (other.LastModifiedTimestampMs != 0L) {
LastModifiedTimestampMs = other.LastModifiedTimestampMs;
}
if (other.Latitude != 0D) {
Latitude = other.Latitude;
}
if (other.Longitude != 0D) {
Longitude = other.Longitude;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
FortSummaryId = input.ReadString();
break;
}
case 16: {
LastModifiedTimestampMs = input.ReadInt64();
break;
}
case 25: {
Latitude = input.ReadDouble();
break;
}
case 33: {
Longitude = input.ReadDouble();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Infoplus.Model
{
/// <summary>
///
/// </summary>
[DataContract]
public partial class ManageScheduledPlans : IEquatable<ManageScheduledPlans>
{
/// <summary>
/// Initializes a new instance of the <see cref="ManageScheduledPlans" /> class.
/// Initializes a new instance of the <see cref="ManageScheduledPlans" />class.
/// </summary>
/// <param name="Deleted">Deleted (default to false).</param>
/// <param name="WarehouseId">WarehouseId (required).</param>
/// <param name="CustomFields">CustomFields.</param>
public ManageScheduledPlans(bool? Deleted = null, int? WarehouseId = null, Dictionary<string, Object> CustomFields = null)
{
// to ensure "WarehouseId" is required (not null)
if (WarehouseId == null)
{
throw new InvalidDataException("WarehouseId is a required property for ManageScheduledPlans and cannot be null");
}
else
{
this.WarehouseId = WarehouseId;
}
// use default value if no "Deleted" provided
if (Deleted == null)
{
this.Deleted = false;
}
else
{
this.Deleted = Deleted;
}
this.CustomFields = CustomFields;
}
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public int? Id { get; private set; }
/// <summary>
/// Gets or Sets CreateDate
/// </summary>
[DataMember(Name="createDate", EmitDefaultValue=false)]
public DateTime? CreateDate { get; private set; }
/// <summary>
/// Gets or Sets ModifyDate
/// </summary>
[DataMember(Name="modifyDate", EmitDefaultValue=false)]
public DateTime? ModifyDate { get; private set; }
/// <summary>
/// Gets or Sets Description
/// </summary>
[DataMember(Name="description", EmitDefaultValue=false)]
public string Description { get; private set; }
/// <summary>
/// Gets or Sets Scheduledplantypeid
/// </summary>
[DataMember(Name="scheduledplantypeid", EmitDefaultValue=false)]
public int? Scheduledplantypeid { get; private set; }
/// <summary>
/// Gets or Sets Planid
/// </summary>
[DataMember(Name="planid", EmitDefaultValue=false)]
public int? Planid { get; private set; }
/// <summary>
/// Gets or Sets Active
/// </summary>
[DataMember(Name="active", EmitDefaultValue=false)]
public bool? Active { get; private set; }
/// <summary>
/// Gets or Sets User
/// </summary>
[DataMember(Name="user", EmitDefaultValue=false)]
public int? User { get; private set; }
/// <summary>
/// Gets or Sets Deleted
/// </summary>
[DataMember(Name="deleted", EmitDefaultValue=false)]
public bool? Deleted { get; set; }
/// <summary>
/// Gets or Sets WarehouseId
/// </summary>
[DataMember(Name="warehouseId", EmitDefaultValue=false)]
public int? WarehouseId { get; set; }
/// <summary>
/// Gets or Sets CustomFields
/// </summary>
[DataMember(Name="customFields", EmitDefaultValue=false)]
public Dictionary<string, Object> CustomFields { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class ManageScheduledPlans {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" CreateDate: ").Append(CreateDate).Append("\n");
sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n");
sb.Append(" Description: ").Append(Description).Append("\n");
sb.Append(" Scheduledplantypeid: ").Append(Scheduledplantypeid).Append("\n");
sb.Append(" Planid: ").Append(Planid).Append("\n");
sb.Append(" Active: ").Append(Active).Append("\n");
sb.Append(" User: ").Append(User).Append("\n");
sb.Append(" Deleted: ").Append(Deleted).Append("\n");
sb.Append(" WarehouseId: ").Append(WarehouseId).Append("\n");
sb.Append(" CustomFields: ").Append(CustomFields).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as ManageScheduledPlans);
}
/// <summary>
/// Returns true if ManageScheduledPlans instances are equal
/// </summary>
/// <param name="other">Instance of ManageScheduledPlans to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(ManageScheduledPlans other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.Id == other.Id ||
this.Id != null &&
this.Id.Equals(other.Id)
) &&
(
this.CreateDate == other.CreateDate ||
this.CreateDate != null &&
this.CreateDate.Equals(other.CreateDate)
) &&
(
this.ModifyDate == other.ModifyDate ||
this.ModifyDate != null &&
this.ModifyDate.Equals(other.ModifyDate)
) &&
(
this.Description == other.Description ||
this.Description != null &&
this.Description.Equals(other.Description)
) &&
(
this.Scheduledplantypeid == other.Scheduledplantypeid ||
this.Scheduledplantypeid != null &&
this.Scheduledplantypeid.Equals(other.Scheduledplantypeid)
) &&
(
this.Planid == other.Planid ||
this.Planid != null &&
this.Planid.Equals(other.Planid)
) &&
(
this.Active == other.Active ||
this.Active != null &&
this.Active.Equals(other.Active)
) &&
(
this.User == other.User ||
this.User != null &&
this.User.Equals(other.User)
) &&
(
this.Deleted == other.Deleted ||
this.Deleted != null &&
this.Deleted.Equals(other.Deleted)
) &&
(
this.WarehouseId == other.WarehouseId ||
this.WarehouseId != null &&
this.WarehouseId.Equals(other.WarehouseId)
) &&
(
this.CustomFields == other.CustomFields ||
this.CustomFields != null &&
this.CustomFields.SequenceEqual(other.CustomFields)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.Id != null)
hash = hash * 59 + this.Id.GetHashCode();
if (this.CreateDate != null)
hash = hash * 59 + this.CreateDate.GetHashCode();
if (this.ModifyDate != null)
hash = hash * 59 + this.ModifyDate.GetHashCode();
if (this.Description != null)
hash = hash * 59 + this.Description.GetHashCode();
if (this.Scheduledplantypeid != null)
hash = hash * 59 + this.Scheduledplantypeid.GetHashCode();
if (this.Planid != null)
hash = hash * 59 + this.Planid.GetHashCode();
if (this.Active != null)
hash = hash * 59 + this.Active.GetHashCode();
if (this.User != null)
hash = hash * 59 + this.User.GetHashCode();
if (this.Deleted != null)
hash = hash * 59 + this.Deleted.GetHashCode();
if (this.WarehouseId != null)
hash = hash * 59 + this.WarehouseId.GetHashCode();
if (this.CustomFields != null)
hash = hash * 59 + this.CustomFields.GetHashCode();
return hash;
}
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ASC.Api.Attributes;
using ASC.Api.Documents;
using ASC.Api.Impl;
using ASC.Api.Interfaces;
using ASC.Api.Projects.Calendars;
using ASC.Api.Utils;
using ASC.Projects.Core.Domain;
using ASC.Projects.Engine;
using ASC.Web.Core.Calendars;
using ASC.Web.Projects;
using ASC.Web.Projects.Core;
using Autofac;
namespace ASC.Api.Projects
{
///<summary>
///Projects access
///</summary>
public partial class ProjectApi : ProjectApiBase, IApiEntryPoint
{
private readonly DocumentsApi documentsApi;
///<summary>
///Api name entry
///</summary>
public string Name
{
get { return "project"; }
}
public TaskFilter CreateFilter(EntityType entityType)
{
var filter = new TaskFilter
{
SortOrder = !Context.SortDescending,
SearchText = Context.FilterValue,
Offset = Context.StartIndex,
Max = Context.Count
};
if (!string.IsNullOrEmpty(Context.SortBy))
{
var type = entityType.ToString();
var sortColumns = filter.SortColumns.ContainsKey(type) ? filter.SortColumns[type] : null;
if (sortColumns != null && sortColumns.Any())
filter.SortBy = sortColumns.ContainsKey(Context.SortBy) ? Context.SortBy : sortColumns.First().Key;
}
Context.SetDataFiltered().SetDataPaginated().SetDataSorted();
return filter;
}
///<summary>
///Constructor
///</summary>
///<param name="context"></param>
///<param name="documentsApi">Docs api</param>
public ProjectApi(ApiContext context, DocumentsApi documentsApi)
{
this.documentsApi = documentsApi;
Context = context;
}
private void SetTotalCount(int count)
{
Context.SetTotalCount(count);
}
private long StartIndex
{
get { return Context.StartIndex; }
}
private long Count
{
get { return Context.Count; }
}
private static HttpRequest Request
{
get { return HttpContext.Current.Request; }
}
internal static List<BaseCalendar> GetUserCalendars(Guid userId)
{
using (var scope = DIHelper.Resolve())
{
var engineFactory = scope.Resolve<EngineFactory>();
var cals = new List<BaseCalendar>();
var engine = engineFactory.ProjectEngine;
var projects = engine.GetByParticipant(userId);
if (projects != null)
{
var team = engine.GetTeam(projects.Select(r => r.ID).ToList());
foreach (var project in projects)
{
var p = project;
var sharingOptions = new SharingOptions();
foreach (var participant in team.Where(r => r.ProjectID == p.ID))
{
sharingOptions.PublicItems.Add(new SharingOptions.PublicItem
{
Id = participant.ID,
IsGroup = false
});
}
var index = project.ID % CalendarColors.BaseColors.Count;
cals.Add(new ProjectCalendar(
project,
CalendarColors.BaseColors[index].BackgroudColor,
CalendarColors.BaseColors[index].TextColor,
sharingOptions, false));
}
}
var folowingProjects = engine.GetFollowing(userId);
if (folowingProjects != null)
{
var team = engine.GetTeam(folowingProjects.Select(r => r.ID).ToList());
foreach (var project in folowingProjects)
{
var p = project;
if (projects != null && projects.Any(proj => proj.ID == p.ID)) continue;
var sharingOptions = new SharingOptions();
sharingOptions.PublicItems.Add(new SharingOptions.PublicItem { Id = userId, IsGroup = false });
foreach (var participant in team.Where(r => r.ProjectID == p.ID))
{
sharingOptions.PublicItems.Add(new SharingOptions.PublicItem
{
Id = participant.ID,
IsGroup = false
});
}
var index = p.ID % CalendarColors.BaseColors.Count;
cals.Add(new ProjectCalendar(
p,
CalendarColors.BaseColors[index].BackgroudColor,
CalendarColors.BaseColors[index].TextColor,
sharingOptions, true));
}
}
return cals;
}
}
[Update(@"settings")]
public ProjectsCommonSettings UpdateSettings(bool? everebodyCanCreate,
bool? hideEntitiesInPausedProjects,
StartModuleType? startModule,
object folderId)
{
if (everebodyCanCreate.HasValue || hideEntitiesInPausedProjects.HasValue)
{
if (!ProjectSecurity.CurrentUserAdministrator) ProjectSecurity.CreateSecurityException();
var settings = ProjectsCommonSettings.Load();
if (everebodyCanCreate.HasValue)
{
settings.EverebodyCanCreate = everebodyCanCreate.Value;
}
if (hideEntitiesInPausedProjects.HasValue)
{
settings.HideEntitiesInPausedProjects = hideEntitiesInPausedProjects.Value;
}
settings.Save();
return settings;
}
if (startModule.HasValue || folderId != null)
{
if (!ProjectSecurity.IsProjectsEnabled(CurrentUserId)) ProjectSecurity.CreateSecurityException();
var settings = ProjectsCommonSettings.LoadForCurrentUser();
if (startModule.HasValue)
{
settings.StartModuleType = startModule.Value;
}
if (folderId != null)
{
settings.FolderId = folderId;
}
settings.SaveForCurrentUser();
return settings;
}
return null;
}
[Read(@"settings")]
public ProjectsCommonSettings GetSettings()
{
var commonSettings = ProjectsCommonSettings.Load();
var userSettings = ProjectsCommonSettings.LoadForCurrentUser();
return new ProjectsCommonSettings
{
EverebodyCanCreate = commonSettings.EverebodyCanCreate,
HideEntitiesInPausedProjects = commonSettings.HideEntitiesInPausedProjects,
StartModuleType = userSettings.StartModuleType,
FolderId = userSettings.FolderId,
};
}
[Create(@"status")]
public CustomTaskStatus CreateStatus(CustomTaskStatus status)
{
return EngineFactory.StatusEngine.Create(status);
}
[Update(@"status")]
public CustomTaskStatus UpdateStatus(CustomTaskStatus newStatus)
{
if (newStatus.IsDefault && !EngineFactory.StatusEngine.Get().Any(r => r.IsDefault && r.StatusType == newStatus.StatusType))
{
return CreateStatus(newStatus);
}
var status = EngineFactory.StatusEngine.Get().FirstOrDefault(r => r.Id == newStatus.Id).NotFoundIfNull();
status.Title = Update.IfNotEmptyAndNotEquals(status.Title, newStatus.Title);
status.Description = Update.IfNotEmptyAndNotEquals(status.Description, newStatus.Description);
status.Color = Update.IfNotEmptyAndNotEquals(status.Color, newStatus.Color);
status.Image = Update.IfNotEmptyAndNotEquals(status.Image, newStatus.Image);
status.ImageType = Update.IfNotEmptyAndNotEquals(status.ImageType, newStatus.ImageType);
status.Order = Update.IfNotEmptyAndNotEquals(status.Order, newStatus.Order);
status.StatusType = Update.IfNotEmptyAndNotEquals(status.StatusType, newStatus.StatusType);
status.Available = Update.IfNotEmptyAndNotEquals(status.Available, newStatus.Available);
EngineFactory.StatusEngine.Update(status);
return status;
}
[Update(@"statuses")]
public List<CustomTaskStatus> UpdateStatuses(List<CustomTaskStatus> statuses)
{
foreach (var status in statuses)
{
UpdateStatus(status);
}
return statuses;
}
[Read(@"status")]
public List<CustomTaskStatus> GetStatuses()
{
return EngineFactory.StatusEngine.GetWithDefaults();
}
[Delete(@"status/{id}")]
public CustomTaskStatus DeleteStatus(int id)
{
var status = EngineFactory.StatusEngine.Get().FirstOrDefault(r => r.Id == id).NotFoundIfNull();
EngineFactory.StatusEngine.Delete(status.Id);
return status;
}
}
}
| |
//#define Trace
// ParallelDeflateOutputStream.cs
// ------------------------------------------------------------------
//
// A DeflateStream that does compression only, it uses a
// divide-and-conquer approach with multiple threads to exploit multiple
// CPUs for the DEFLATE computation.
//
// last saved: <2011-July-31 14:49:40>
//
// ------------------------------------------------------------------
//
// Copyright (c) 2009-2011 by Dino Chiesa
// All rights reserved!
//
// This code module is part of DotNetZip, a zipfile class library.
//
// ------------------------------------------------------------------
//
// This code is licensed under the Microsoft Public License.
// See the file License.txt for the license details.
// More info on: http://dotnetzip.codeplex.com
//
// ------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Threading;
using Ionic.Zlib;
using System.IO;
namespace Ionic.Zlib
{
internal class WorkItem
{
public byte[] buffer;
public byte[] compressed;
public int crc;
public int index;
public int ordinal;
public int inputBytesAvailable;
public int compressedBytesAvailable;
public ZlibCodec compressor;
public WorkItem(int size,
Ionic.Zlib.CompressionLevel compressLevel,
CompressionStrategy strategy,
int ix)
{
this.buffer= new byte[size];
// alloc 5 bytes overhead for every block (margin of safety= 2)
int n = size + ((size / 32768)+1) * 5 * 2;
this.compressed = new byte[n];
this.compressor = new ZlibCodec();
this.compressor.InitializeDeflate(compressLevel, false);
this.compressor.OutputBuffer = this.compressed;
this.compressor.InputBuffer = this.buffer;
this.index = ix;
}
}
/// <summary>
/// A class for compressing streams using the
/// Deflate algorithm with multiple threads.
/// </summary>
///
/// <remarks>
/// <para>
/// This class performs DEFLATE compression through writing. For
/// more information on the Deflate algorithm, see IETF RFC 1951,
/// "DEFLATE Compressed Data Format Specification version 1.3."
/// </para>
///
/// <para>
/// This class is similar to <see cref="Ionic.Zlib.DeflateStream"/>, except
/// that this class is for compression only, and this implementation uses an
/// approach that employs multiple worker threads to perform the DEFLATE. On
/// a multi-cpu or multi-core computer, the performance of this class can be
/// significantly higher than the single-threaded DeflateStream, particularly
/// for larger streams. How large? Anything over 10mb is a good candidate
/// for parallel compression.
/// </para>
///
/// <para>
/// The tradeoff is that this class uses more memory and more CPU than the
/// vanilla DeflateStream, and also is less efficient as a compressor. For
/// large files the size of the compressed data stream can be less than 1%
/// larger than the size of a compressed data stream from the vanialla
/// DeflateStream. For smaller files the difference can be larger. The
/// difference will also be larger if you set the BufferSize to be lower than
/// the default value. Your mileage may vary. Finally, for small files, the
/// ParallelDeflateOutputStream can be much slower than the vanilla
/// DeflateStream, because of the overhead associated to using the thread
/// pool.
/// </para>
///
/// </remarks>
/// <seealso cref="Ionic.Zlib.DeflateStream" />
public class ParallelDeflateOutputStream : System.IO.Stream
{
private static readonly int IO_BUFFER_SIZE_DEFAULT = 64 * 1024; // 128k
private static readonly int BufferPairsPerCore = 4;
private System.Collections.Generic.List<WorkItem> _pool;
private bool _leaveOpen;
private bool emitting;
private System.IO.Stream _outStream;
private int _maxBufferPairs;
private int _bufferSize = IO_BUFFER_SIZE_DEFAULT;
private AutoResetEvent _newlyCompressedBlob;
//private ManualResetEvent _writingDone;
//private ManualResetEvent _sessionReset;
private object _outputLock = new object();
private bool _isClosed;
private bool _firstWriteDone;
private int _currentlyFilling;
private int _lastFilled;
private int _lastWritten;
private int _latestCompressed;
private int _Crc32;
private Ionic.Crc.CRC32 _runningCrc;
private object _latestLock = new object();
private System.Collections.Generic.Queue<int> _toWrite;
private System.Collections.Generic.Queue<int> _toFill;
private Int64 _totalBytesProcessed;
private Ionic.Zlib.CompressionLevel _compressLevel;
private volatile Exception _pendingException;
private bool _handlingException;
private object _eLock = new Object(); // protects _pendingException
// This bitfield is used only when Trace is defined.
//private TraceBits _DesiredTrace = TraceBits.Write | TraceBits.WriteBegin |
//TraceBits.WriteDone | TraceBits.Lifecycle | TraceBits.Fill | TraceBits.Flush |
//TraceBits.Session;
//private TraceBits _DesiredTrace = TraceBits.WriteBegin | TraceBits.WriteDone | TraceBits.Synch | TraceBits.Lifecycle | TraceBits.Session ;
private TraceBits _DesiredTrace =
TraceBits.Session |
TraceBits.Compress |
TraceBits.WriteTake |
TraceBits.WriteEnter |
TraceBits.EmitEnter |
TraceBits.EmitDone |
TraceBits.EmitLock |
TraceBits.EmitSkip |
TraceBits.EmitBegin;
/// <summary>
/// Create a ParallelDeflateOutputStream.
/// </summary>
/// <remarks>
///
/// <para>
/// This stream compresses data written into it via the DEFLATE
/// algorithm (see RFC 1951), and writes out the compressed byte stream.
/// </para>
///
/// <para>
/// The instance will use the default compression level, the default
/// buffer sizes and the default number of threads and buffers per
/// thread.
/// </para>
///
/// <para>
/// This class is similar to <see cref="Ionic.Zlib.DeflateStream"/>,
/// except that this implementation uses an approach that employs
/// multiple worker threads to perform the DEFLATE. On a multi-cpu or
/// multi-core computer, the performance of this class can be
/// significantly higher than the single-threaded DeflateStream,
/// particularly for larger streams. How large? Anything over 10mb is
/// a good candidate for parallel compression.
/// </para>
///
/// </remarks>
///
/// <example>
///
/// This example shows how to use a ParallelDeflateOutputStream to compress
/// data. It reads a file, compresses it, and writes the compressed data to
/// a second, output file.
///
/// <code>
/// byte[] buffer = new byte[WORKING_BUFFER_SIZE];
/// int n= -1;
/// String outputFile = fileToCompress + ".compressed";
/// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress))
/// {
/// using (var raw = System.IO.File.Create(outputFile))
/// {
/// using (Stream compressor = new ParallelDeflateOutputStream(raw))
/// {
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// compressor.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
/// <code lang="VB">
/// Dim buffer As Byte() = New Byte(4096) {}
/// Dim n As Integer = -1
/// Dim outputFile As String = (fileToCompress & ".compressed")
/// Using input As Stream = File.OpenRead(fileToCompress)
/// Using raw As FileStream = File.Create(outputFile)
/// Using compressor As Stream = New ParallelDeflateOutputStream(raw)
/// Do While (n <> 0)
/// If (n > 0) Then
/// compressor.Write(buffer, 0, n)
/// End If
/// n = input.Read(buffer, 0, buffer.Length)
/// Loop
/// End Using
/// End Using
/// End Using
/// </code>
/// </example>
/// <param name="stream">The stream to which compressed data will be written.</param>
public ParallelDeflateOutputStream(System.IO.Stream stream)
: this(stream, CompressionLevel.Default, CompressionStrategy.Default, false)
{
}
/// <summary>
/// Create a ParallelDeflateOutputStream using the specified CompressionLevel.
/// </summary>
/// <remarks>
/// See the <see cref="ParallelDeflateOutputStream(System.IO.Stream)"/>
/// constructor for example code.
/// </remarks>
/// <param name="stream">The stream to which compressed data will be written.</param>
/// <param name="level">A tuning knob to trade speed for effectiveness.</param>
public ParallelDeflateOutputStream(System.IO.Stream stream, CompressionLevel level)
: this(stream, level, CompressionStrategy.Default, false)
{
}
/// <summary>
/// Create a ParallelDeflateOutputStream and specify whether to leave the captive stream open
/// when the ParallelDeflateOutputStream is closed.
/// </summary>
/// <remarks>
/// See the <see cref="ParallelDeflateOutputStream(System.IO.Stream)"/>
/// constructor for example code.
/// </remarks>
/// <param name="stream">The stream to which compressed data will be written.</param>
/// <param name="leaveOpen">
/// true if the application would like the stream to remain open after inflation/deflation.
/// </param>
public ParallelDeflateOutputStream(System.IO.Stream stream, bool leaveOpen)
: this(stream, CompressionLevel.Default, CompressionStrategy.Default, leaveOpen)
{
}
/// <summary>
/// Create a ParallelDeflateOutputStream and specify whether to leave the captive stream open
/// when the ParallelDeflateOutputStream is closed.
/// </summary>
/// <remarks>
/// See the <see cref="ParallelDeflateOutputStream(System.IO.Stream)"/>
/// constructor for example code.
/// </remarks>
/// <param name="stream">The stream to which compressed data will be written.</param>
/// <param name="level">A tuning knob to trade speed for effectiveness.</param>
/// <param name="leaveOpen">
/// true if the application would like the stream to remain open after inflation/deflation.
/// </param>
public ParallelDeflateOutputStream(System.IO.Stream stream, CompressionLevel level, bool leaveOpen)
: this(stream, CompressionLevel.Default, CompressionStrategy.Default, leaveOpen)
{
}
/// <summary>
/// Create a ParallelDeflateOutputStream using the specified
/// CompressionLevel and CompressionStrategy, and specifying whether to
/// leave the captive stream open when the ParallelDeflateOutputStream is
/// closed.
/// </summary>
/// <remarks>
/// See the <see cref="ParallelDeflateOutputStream(System.IO.Stream)"/>
/// constructor for example code.
/// </remarks>
/// <param name="stream">The stream to which compressed data will be written.</param>
/// <param name="level">A tuning knob to trade speed for effectiveness.</param>
/// <param name="strategy">
/// By tweaking this parameter, you may be able to optimize the compression for
/// data with particular characteristics.
/// </param>
/// <param name="leaveOpen">
/// true if the application would like the stream to remain open after inflation/deflation.
/// </param>
public ParallelDeflateOutputStream(System.IO.Stream stream,
CompressionLevel level,
CompressionStrategy strategy,
bool leaveOpen)
{
TraceOutput(TraceBits.Lifecycle | TraceBits.Session, "-------------------------------------------------------");
TraceOutput(TraceBits.Lifecycle | TraceBits.Session, "Create {0:X8}", this.GetHashCode());
_outStream = stream;
_compressLevel= level;
Strategy = strategy;
_leaveOpen = leaveOpen;
this.MaxBufferPairs = 16; // default
}
/// <summary>
/// The ZLIB strategy to be used during compression.
/// </summary>
///
public CompressionStrategy Strategy
{
get;
private set;
}
/// <summary>
/// The maximum number of buffer pairs to use.
/// </summary>
///
/// <remarks>
/// <para>
/// This property sets an upper limit on the number of memory buffer
/// pairs to create. The implementation of this stream allocates
/// multiple buffers to facilitate parallel compression. As each buffer
/// fills up, this stream uses <see
/// cref="System.Threading.ThreadPool.QueueUserWorkItem(WaitCallback)">
/// ThreadPool.QueueUserWorkItem()</see>
/// to compress those buffers in a background threadpool thread. After a
/// buffer is compressed, it is re-ordered and written to the output
/// stream.
/// </para>
///
/// <para>
/// A higher number of buffer pairs enables a higher degree of
/// parallelism, which tends to increase the speed of compression on
/// multi-cpu computers. On the other hand, a higher number of buffer
/// pairs also implies a larger memory consumption, more active worker
/// threads, and a higher cpu utilization for any compression. This
/// property enables the application to limit its memory consumption and
/// CPU utilization behavior depending on requirements.
/// </para>
///
/// <para>
/// For each compression "task" that occurs in parallel, there are 2
/// buffers allocated: one for input and one for output. This property
/// sets a limit for the number of pairs. The total amount of storage
/// space allocated for buffering will then be (N*S*2), where N is the
/// number of buffer pairs, S is the size of each buffer (<see
/// cref="BufferSize"/>). By default, DotNetZip allocates 4 buffer
/// pairs per CPU core, so if your machine has 4 cores, and you retain
/// the default buffer size of 128k, then the
/// ParallelDeflateOutputStream will use 4 * 4 * 2 * 128kb of buffer
/// memory in total, or 4mb, in blocks of 128kb. If you then set this
/// property to 8, then the number will be 8 * 2 * 128kb of buffer
/// memory, or 2mb.
/// </para>
///
/// <para>
/// CPU utilization will also go up with additional buffers, because a
/// larger number of buffer pairs allows a larger number of background
/// threads to compress in parallel. If you find that parallel
/// compression is consuming too much memory or CPU, you can adjust this
/// value downward.
/// </para>
///
/// <para>
/// The default value is 16. Different values may deliver better or
/// worse results, depending on your priorities and the dynamic
/// performance characteristics of your storage and compute resources.
/// </para>
///
/// <para>
/// This property is not the number of buffer pairs to use; it is an
/// upper limit. An illustration: Suppose you have an application that
/// uses the default value of this property (which is 16), and it runs
/// on a machine with 2 CPU cores. In that case, DotNetZip will allocate
/// 4 buffer pairs per CPU core, for a total of 8 pairs. The upper
/// limit specified by this property has no effect.
/// </para>
///
/// <para>
/// The application can set this value at any time, but it is effective
/// only before the first call to Write(), which is when the buffers are
/// allocated.
/// </para>
/// </remarks>
public int MaxBufferPairs
{
get
{
return _maxBufferPairs;
}
set
{
if (value < 4)
throw new ArgumentException("MaxBufferPairs",
"Value must be 4 or greater.");
_maxBufferPairs = value;
}
}
/// <summary>
/// The size of the buffers used by the compressor threads.
/// </summary>
/// <remarks>
///
/// <para>
/// The default buffer size is 128k. The application can set this value
/// at any time, but it is effective only before the first Write().
/// </para>
///
/// <para>
/// Larger buffer sizes implies larger memory consumption but allows
/// more efficient compression. Using smaller buffer sizes consumes less
/// memory but may result in less effective compression. For example,
/// using the default buffer size of 128k, the compression delivered is
/// within 1% of the compression delivered by the single-threaded <see
/// cref="Ionic.Zlib.DeflateStream"/>. On the other hand, using a
/// BufferSize of 8k can result in a compressed data stream that is 5%
/// larger than that delivered by the single-threaded
/// <c>DeflateStream</c>. Excessively small buffer sizes can also cause
/// the speed of the ParallelDeflateOutputStream to drop, because of
/// larger thread scheduling overhead dealing with many many small
/// buffers.
/// </para>
///
/// <para>
/// The total amount of storage space allocated for buffering will be
/// (N*S*2), where N is the number of buffer pairs, and S is the size of
/// each buffer (this property). There are 2 buffers used by the
/// compressor, one for input and one for output. By default, DotNetZip
/// allocates 4 buffer pairs per CPU core, so if your machine has 4
/// cores, then the number of buffer pairs used will be 16. If you
/// accept the default value of this property, 128k, then the
/// ParallelDeflateOutputStream will use 16 * 2 * 128kb of buffer memory
/// in total, or 4mb, in blocks of 128kb. If you set this property to
/// 64kb, then the number will be 16 * 2 * 64kb of buffer memory, or
/// 2mb.
/// </para>
///
/// </remarks>
public int BufferSize
{
get { return _bufferSize;}
set
{
if (value < 1024)
throw new ArgumentOutOfRangeException("BufferSize",
"BufferSize must be greater than 1024 bytes");
_bufferSize = value;
}
}
/// <summary>
/// The CRC32 for the data that was written out, prior to compression.
/// </summary>
/// <remarks>
/// This value is meaningful only after a call to Close().
/// </remarks>
public int Crc32 { get { return _Crc32; } }
/// <summary>
/// The total number of uncompressed bytes processed by the ParallelDeflateOutputStream.
/// </summary>
/// <remarks>
/// This value is meaningful only after a call to Close().
/// </remarks>
public Int64 BytesProcessed { get { return _totalBytesProcessed; } }
private void _InitializePoolOfWorkItems()
{
_toWrite = new Queue<int>();
_toFill = new Queue<int>();
_pool = new System.Collections.Generic.List<WorkItem>();
int nTasks = BufferPairsPerCore * Environment.ProcessorCount;
nTasks = Math.Min(nTasks, _maxBufferPairs);
for(int i=0; i < nTasks; i++)
{
_pool.Add(new WorkItem(_bufferSize, _compressLevel, Strategy, i));
_toFill.Enqueue(i);
}
_newlyCompressedBlob = new AutoResetEvent(false);
_runningCrc = new Ionic.Crc.CRC32();
_currentlyFilling = -1;
_lastFilled = -1;
_lastWritten = -1;
_latestCompressed = -1;
}
/// <summary>
/// Write data to the stream.
/// </summary>
///
/// <remarks>
///
/// <para>
/// To use the ParallelDeflateOutputStream to compress data, create a
/// ParallelDeflateOutputStream with CompressionMode.Compress, passing a
/// writable output stream. Then call Write() on that
/// ParallelDeflateOutputStream, providing uncompressed data as input. The
/// data sent to the output stream will be the compressed form of the data
/// written.
/// </para>
///
/// <para>
/// To decompress data, use the <see cref="Ionic.Zlib.DeflateStream"/> class.
/// </para>
///
/// </remarks>
/// <param name="buffer">The buffer holding data to write to the stream.</param>
/// <param name="offset">the offset within that data array to find the first byte to write.</param>
/// <param name="count">the number of bytes to write.</param>
public override void Write(byte[] buffer, int offset, int count)
{
bool mustWait = false;
// This method does this:
// 0. handles any pending exceptions
// 1. write any buffers that are ready to be written,
// 2. fills a work buffer; when full, flip state to 'Filled',
// 3. if more data to be written, goto step 1
if (_isClosed)
throw new InvalidOperationException();
// dispense any exceptions that occurred on the BG threads
if (_pendingException != null)
{
_handlingException = true;
var pe = _pendingException;
_pendingException = null;
throw pe;
}
if (count == 0) return;
if (!_firstWriteDone)
{
// Want to do this on first Write, first session, and not in the
// constructor. We want to allow MaxBufferPairs to
// change after construction, but before first Write.
_InitializePoolOfWorkItems();
_firstWriteDone = true;
}
do
{
// may need to make buffers available
EmitPendingBuffers(false, mustWait);
mustWait = false;
// use current buffer, or get a new buffer to fill
int ix = -1;
if (_currentlyFilling >= 0)
{
ix = _currentlyFilling;
TraceOutput(TraceBits.WriteTake,
"Write notake wi({0}) lf({1})",
ix,
_lastFilled);
}
else
{
TraceOutput(TraceBits.WriteTake, "Write take?");
if (_toFill.Count == 0)
{
// no available buffers, so... need to emit
// compressed buffers.
mustWait = true;
continue;
}
ix = _toFill.Dequeue();
TraceOutput(TraceBits.WriteTake,
"Write take wi({0}) lf({1})",
ix,
_lastFilled);
++_lastFilled;
}
WorkItem workitem = _pool[ix];
int limit = ((workitem.buffer.Length - workitem.inputBytesAvailable) > count)
? count
: (workitem.buffer.Length - workitem.inputBytesAvailable);
workitem.ordinal = _lastFilled;
TraceOutput(TraceBits.Write,
"Write lock wi({0}) ord({1}) iba({2})",
workitem.index,
workitem.ordinal,
workitem.inputBytesAvailable
);
// copy from the provided buffer to our workitem, starting at
// the tail end of whatever data we might have in there currently.
Buffer.BlockCopy(buffer,
offset,
workitem.buffer,
workitem.inputBytesAvailable,
limit);
count -= limit;
offset += limit;
workitem.inputBytesAvailable += limit;
if (workitem.inputBytesAvailable == workitem.buffer.Length)
{
// No need for interlocked.increment: the Write()
// method is documented as not multi-thread safe, so
// we can assume Write() calls come in from only one
// thread.
TraceOutput(TraceBits.Write,
"Write QUWI wi({0}) ord({1}) iba({2}) nf({3})",
workitem.index,
workitem.ordinal,
workitem.inputBytesAvailable );
if (!ThreadPool.QueueUserWorkItem( _DeflateOne, workitem ))
throw new Exception("Cannot enqueue workitem");
_currentlyFilling = -1; // will get a new buffer next time
}
else
_currentlyFilling = ix;
if (count > 0)
TraceOutput(TraceBits.WriteEnter, "Write more");
}
while (count > 0); // until no more to write
TraceOutput(TraceBits.WriteEnter, "Write exit");
return;
}
private void _FlushFinish()
{
// After writing a series of compressed buffers, each one closed
// with Flush.Sync, we now write the final one as Flush.Finish,
// and then stop.
byte[] buffer = new byte[128];
var compressor = new ZlibCodec();
int rc = compressor.InitializeDeflate(_compressLevel, false);
compressor.InputBuffer = null;
compressor.NextIn = 0;
compressor.AvailableBytesIn = 0;
compressor.OutputBuffer = buffer;
compressor.NextOut = 0;
compressor.AvailableBytesOut = buffer.Length;
rc = compressor.Deflate(FlushType.Finish);
if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK)
throw new Exception("deflating: " + compressor.Message);
if (buffer.Length - compressor.AvailableBytesOut > 0)
{
TraceOutput(TraceBits.EmitBegin,
"Emit begin flush bytes({0})",
buffer.Length - compressor.AvailableBytesOut);
_outStream.Write(buffer, 0, buffer.Length - compressor.AvailableBytesOut);
TraceOutput(TraceBits.EmitDone,
"Emit done flush");
}
compressor.EndDeflate();
_Crc32 = _runningCrc.Crc32Result;
}
private void _Flush(bool lastInput)
{
if (_isClosed)
throw new InvalidOperationException();
if (emitting) return;
// compress any partial buffer
if (_currentlyFilling >= 0)
{
WorkItem workitem = _pool[_currentlyFilling];
_DeflateOne(workitem);
_currentlyFilling = -1; // get a new buffer next Write()
}
if (lastInput)
{
EmitPendingBuffers(true, false);
_FlushFinish();
}
else
{
EmitPendingBuffers(false, false);
}
}
/// <summary>
/// Flush the stream.
/// </summary>
public override void Flush()
{
if (_pendingException != null)
{
_handlingException = true;
var pe = _pendingException;
_pendingException = null;
throw pe;
}
if (_handlingException)
return;
_Flush(false);
}
/// <summary>
/// Close the stream.
/// </summary>
/// <remarks>
/// You must call Close on the stream to guarantee that all of the data written in has
/// been compressed, and the compressed data has been written out.
/// </remarks>
public override void Close()
{
TraceOutput(TraceBits.Session, "Close {0:X8}", this.GetHashCode());
if (_pendingException != null)
{
_handlingException = true;
var pe = _pendingException;
_pendingException = null;
throw pe;
}
if (_handlingException)
return;
if (_isClosed) return;
_Flush(true);
if (!_leaveOpen)
_outStream.Close();
_isClosed= true;
}
// workitem 10030 - implement a new Dispose method
/// <summary>Dispose the object</summary>
/// <remarks>
/// <para>
/// Because ParallelDeflateOutputStream is IDisposable, the
/// application must call this method when finished using the instance.
/// </para>
/// <para>
/// This method is generally called implicitly upon exit from
/// a <c>using</c> scope in C# (<c>Using</c> in VB).
/// </para>
/// </remarks>
new public void Dispose()
{
TraceOutput(TraceBits.Lifecycle, "Dispose {0:X8}", this.GetHashCode());
Close();
_pool = null;
Dispose(true);
}
/// <summary>The Dispose method</summary>
/// <param name="disposing">
/// indicates whether the Dispose method was invoked by user code.
/// </param>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
/// <summary>
/// Resets the stream for use with another stream.
/// </summary>
/// <remarks>
/// Because the ParallelDeflateOutputStream is expensive to create, it
/// has been designed so that it can be recycled and re-used. You have
/// to call Close() on the stream first, then you can call Reset() on
/// it, to use it again on another stream.
/// </remarks>
///
/// <param name="stream">
/// The new output stream for this era.
/// </param>
///
/// <example>
/// <code>
/// ParallelDeflateOutputStream deflater = null;
/// foreach (var inputFile in listOfFiles)
/// {
/// string outputFile = inputFile + ".compressed";
/// using (System.IO.Stream input = System.IO.File.OpenRead(inputFile))
/// {
/// using (var outStream = System.IO.File.Create(outputFile))
/// {
/// if (deflater == null)
/// deflater = new ParallelDeflateOutputStream(outStream,
/// CompressionLevel.Best,
/// CompressionStrategy.Default,
/// true);
/// deflater.Reset(outStream);
///
/// while ((n= input.Read(buffer, 0, buffer.Length)) != 0)
/// {
/// deflater.Write(buffer, 0, n);
/// }
/// }
/// }
/// }
/// </code>
/// </example>
public void Reset(Stream stream)
{
TraceOutput(TraceBits.Session, "-------------------------------------------------------");
TraceOutput(TraceBits.Session, "Reset {0:X8} firstDone({1})", this.GetHashCode(), _firstWriteDone);
if (!_firstWriteDone) return;
// reset all status
_toWrite.Clear();
_toFill.Clear();
foreach (var workitem in _pool)
{
_toFill.Enqueue(workitem.index);
workitem.ordinal = -1;
}
_firstWriteDone = false;
_totalBytesProcessed = 0L;
_runningCrc = new Ionic.Crc.CRC32();
_isClosed= false;
_currentlyFilling = -1;
_lastFilled = -1;
_lastWritten = -1;
_latestCompressed = -1;
_outStream = stream;
}
private void EmitPendingBuffers(bool doAll, bool mustWait)
{
// When combining parallel deflation with a ZipSegmentedStream, it's
// possible for the ZSS to throw from within this method. In that
// case, Close/Dispose will be called on this stream, if this stream
// is employed within a using or try/finally pair as required. But
// this stream is unaware of the pending exception, so the Close()
// method invokes this method AGAIN. This can lead to a deadlock.
// Therefore, failfast if re-entering.
if (emitting) return;
emitting = true;
if (doAll || mustWait)
_newlyCompressedBlob.WaitOne();
do
{
int firstSkip = -1;
int millisecondsToWait = doAll ? 200 : (mustWait ? -1 : 0);
int nextToWrite = -1;
do
{
if (Monitor.TryEnter(_toWrite, millisecondsToWait))
{
nextToWrite = -1;
try
{
if (_toWrite.Count > 0)
nextToWrite = _toWrite.Dequeue();
}
finally
{
Monitor.Exit(_toWrite);
}
if (nextToWrite >= 0)
{
WorkItem workitem = _pool[nextToWrite];
if (workitem.ordinal != _lastWritten + 1)
{
// out of order. requeue and try again.
TraceOutput(TraceBits.EmitSkip,
"Emit skip wi({0}) ord({1}) lw({2}) fs({3})",
workitem.index,
workitem.ordinal,
_lastWritten,
firstSkip);
lock(_toWrite)
{
_toWrite.Enqueue(nextToWrite);
}
if (firstSkip == nextToWrite)
{
// We went around the list once.
// None of the items in the list is the one we want.
// Now wait for a compressor to signal again.
_newlyCompressedBlob.WaitOne();
firstSkip = -1;
}
else if (firstSkip == -1)
firstSkip = nextToWrite;
continue;
}
firstSkip = -1;
TraceOutput(TraceBits.EmitBegin,
"Emit begin wi({0}) ord({1}) cba({2})",
workitem.index,
workitem.ordinal,
workitem.compressedBytesAvailable);
_outStream.Write(workitem.compressed, 0, workitem.compressedBytesAvailable);
_runningCrc.Combine(workitem.crc, workitem.inputBytesAvailable);
_totalBytesProcessed += workitem.inputBytesAvailable;
workitem.inputBytesAvailable = 0;
TraceOutput(TraceBits.EmitDone,
"Emit done wi({0}) ord({1}) cba({2}) mtw({3})",
workitem.index,
workitem.ordinal,
workitem.compressedBytesAvailable,
millisecondsToWait);
_lastWritten = workitem.ordinal;
_toFill.Enqueue(workitem.index);
// don't wait next time through
if (millisecondsToWait == -1) millisecondsToWait = 0;
}
}
else
nextToWrite = -1;
} while (nextToWrite >= 0);
} while (doAll && (_lastWritten != _latestCompressed));
emitting = false;
}
#if OLD
private void _PerpetualWriterMethod(object state)
{
TraceOutput(TraceBits.WriterThread, "_PerpetualWriterMethod START");
try
{
do
{
// wait for the next session
TraceOutput(TraceBits.Synch | TraceBits.WriterThread, "Synch _sessionReset.WaitOne(begin) PWM");
_sessionReset.WaitOne();
TraceOutput(TraceBits.Synch | TraceBits.WriterThread, "Synch _sessionReset.WaitOne(done) PWM");
if (_isDisposed) break;
TraceOutput(TraceBits.Synch | TraceBits.WriterThread, "Synch _sessionReset.Reset() PWM");
_sessionReset.Reset();
// repeatedly write buffers as they become ready
WorkItem workitem = null;
Ionic.Zlib.CRC32 c= new Ionic.Zlib.CRC32();
do
{
workitem = _pool[_nextToWrite % _pc];
lock(workitem)
{
if (_noMoreInputForThisSegment)
TraceOutput(TraceBits.Write,
"Write drain wi({0}) stat({1}) canuse({2}) cba({3})",
workitem.index,
workitem.status,
(workitem.status == (int)WorkItem.Status.Compressed),
workitem.compressedBytesAvailable);
do
{
if (workitem.status == (int)WorkItem.Status.Compressed)
{
TraceOutput(TraceBits.WriteBegin,
"Write begin wi({0}) stat({1}) cba({2})",
workitem.index,
workitem.status,
workitem.compressedBytesAvailable);
workitem.status = (int)WorkItem.Status.Writing;
_outStream.Write(workitem.compressed, 0, workitem.compressedBytesAvailable);
c.Combine(workitem.crc, workitem.inputBytesAvailable);
_totalBytesProcessed += workitem.inputBytesAvailable;
_nextToWrite++;
workitem.inputBytesAvailable= 0;
workitem.status = (int)WorkItem.Status.Done;
TraceOutput(TraceBits.WriteDone,
"Write done wi({0}) stat({1}) cba({2})",
workitem.index,
workitem.status,
workitem.compressedBytesAvailable);
Monitor.Pulse(workitem);
break;
}
else
{
int wcycles = 0;
// I've locked a workitem I cannot use.
// Therefore, wake someone else up, and then release the lock.
while (workitem.status != (int)WorkItem.Status.Compressed)
{
TraceOutput(TraceBits.WriteWait,
"Write waiting wi({0}) stat({1}) nw({2}) nf({3}) nomore({4})",
workitem.index,
workitem.status,
_nextToWrite, _nextToFill,
_noMoreInputForThisSegment );
if (_noMoreInputForThisSegment && _nextToWrite == _nextToFill)
break;
wcycles++;
// wake up someone else
Monitor.Pulse(workitem);
// release and wait
Monitor.Wait(workitem);
if (workitem.status == (int)WorkItem.Status.Compressed)
TraceOutput(TraceBits.WriteWait,
"Write A-OK wi({0}) stat({1}) iba({2}) cba({3}) cyc({4})",
workitem.index,
workitem.status,
workitem.inputBytesAvailable,
workitem.compressedBytesAvailable,
wcycles);
}
if (_noMoreInputForThisSegment && _nextToWrite == _nextToFill)
break;
}
}
while (true);
}
if (_noMoreInputForThisSegment)
TraceOutput(TraceBits.Write,
"Write nomore nw({0}) nf({1}) break({2})",
_nextToWrite, _nextToFill, (_nextToWrite == _nextToFill));
if (_noMoreInputForThisSegment && _nextToWrite == _nextToFill)
break;
} while (true);
// Finish:
// After writing a series of buffers, closing each one with
// Flush.Sync, we now write the final one as Flush.Finish, and
// then stop.
byte[] buffer = new byte[128];
ZlibCodec compressor = new ZlibCodec();
int rc = compressor.InitializeDeflate(_compressLevel, false);
compressor.InputBuffer = null;
compressor.NextIn = 0;
compressor.AvailableBytesIn = 0;
compressor.OutputBuffer = buffer;
compressor.NextOut = 0;
compressor.AvailableBytesOut = buffer.Length;
rc = compressor.Deflate(FlushType.Finish);
if (rc != ZlibConstants.Z_STREAM_END && rc != ZlibConstants.Z_OK)
throw new Exception("deflating: " + compressor.Message);
if (buffer.Length - compressor.AvailableBytesOut > 0)
{
TraceOutput(TraceBits.WriteBegin,
"Write begin flush bytes({0})",
buffer.Length - compressor.AvailableBytesOut);
_outStream.Write(buffer, 0, buffer.Length - compressor.AvailableBytesOut);
TraceOutput(TraceBits.WriteBegin,
"Write done flush");
}
compressor.EndDeflate();
_Crc32 = c.Crc32Result;
// signal that writing is complete:
TraceOutput(TraceBits.Synch, "Synch _writingDone.Set() PWM");
_writingDone.Set();
}
while (true);
}
catch (System.Exception exc1)
{
lock(_eLock)
{
// expose the exception to the main thread
if (_pendingException!=null)
_pendingException = exc1;
}
}
TraceOutput(TraceBits.WriterThread, "_PerpetualWriterMethod FINIS");
}
#endif
private void _DeflateOne(Object wi)
{
// compress one buffer
WorkItem workitem = (WorkItem) wi;
try
{
Ionic.Crc.CRC32 crc = new Ionic.Crc.CRC32();
// calc CRC on the buffer
crc.SlurpBlock(workitem.buffer, 0, workitem.inputBytesAvailable);
// deflate it
DeflateOneSegment(workitem);
// update status
workitem.crc = crc.Crc32Result;
TraceOutput(TraceBits.Compress,
"Compress wi({0}) ord({1}) len({2})",
workitem.index,
workitem.ordinal,
workitem.compressedBytesAvailable
);
lock(_latestLock)
{
if (workitem.ordinal > _latestCompressed)
_latestCompressed = workitem.ordinal;
}
lock (_toWrite)
{
_toWrite.Enqueue(workitem.index);
}
_newlyCompressedBlob.Set();
}
catch (System.Exception exc1)
{
lock(_eLock)
{
// expose the exception to the main thread
if (_pendingException!=null)
_pendingException = exc1;
}
}
}
private bool DeflateOneSegment(WorkItem workitem)
{
ZlibCodec compressor = workitem.compressor;
int rc = 0;
compressor.ResetDeflate();
compressor.NextIn = 0;
compressor.AvailableBytesIn = workitem.inputBytesAvailable;
// step 1: deflate the buffer
compressor.NextOut = 0;
compressor.AvailableBytesOut = workitem.compressed.Length;
do
{
compressor.Deflate(FlushType.None);
}
while (compressor.AvailableBytesIn > 0 || compressor.AvailableBytesOut == 0);
// step 2: flush (sync)
rc = compressor.Deflate(FlushType.Sync);
// The rc is not processed here, this is only to eliminate the warning
if (rc != ZlibConstants.Z_OK | rc != ZlibConstants.Z_STREAM_END)
throw new ZlibException("Deflate: unknown return code");
workitem.compressedBytesAvailable= (int) compressor.TotalBytesOut;
return true;
}
[System.Diagnostics.ConditionalAttribute("Trace")]
private void TraceOutput(TraceBits bits, string format, params object[] varParams)
{
if ((bits & _DesiredTrace) != 0)
{
lock(_outputLock)
{
int tid = Thread.CurrentThread.GetHashCode();
#if !SILVERLIGHT
Console.ForegroundColor = (ConsoleColor) (tid % 8 + 8);
#endif
Console.Write("{0:000} PDOS ", tid);
Console.WriteLine(format, varParams);
#if !SILVERLIGHT
Console.ResetColor();
#endif
}
}
}
// used only when Trace is defined
[Flags]
enum TraceBits : uint
{
None = 0,
NotUsed1 = 1,
EmitLock = 2,
EmitEnter = 4, // enter _EmitPending
EmitBegin = 8, // begin to write out
EmitDone = 16, // done writing out
EmitSkip = 32, // writer skipping a workitem
EmitAll = 58, // All Emit flags
Flush = 64,
Lifecycle = 128, // constructor/disposer
Session = 256, // Close/Reset
Synch = 512, // thread synchronization
Instance = 1024, // instance settings
Compress = 2048, // compress task
Write = 4096, // filling buffers, when caller invokes Write()
WriteEnter = 8192, // upon entry to Write()
WriteTake = 16384, // on _toFill.Take()
All = 0xffffffff,
}
/// <summary>
/// Indicates whether the stream supports Seek operations.
/// </summary>
/// <remarks>
/// Always returns false.
/// </remarks>
public override bool CanSeek
{
get { return false; }
}
/// <summary>
/// Indicates whether the stream supports Read operations.
/// </summary>
/// <remarks>
/// Always returns false.
/// </remarks>
public override bool CanRead
{
get {return false;}
}
/// <summary>
/// Indicates whether the stream supports Write operations.
/// </summary>
/// <remarks>
/// Returns true if the provided stream is writable.
/// </remarks>
public override bool CanWrite
{
get { return _outStream.CanWrite; }
}
/// <summary>
/// Reading this property always throws a NotSupportedException.
/// </summary>
public override long Length
{
get { throw new NotSupportedException(); }
}
/// <summary>
/// Returns the current position of the output stream.
/// </summary>
/// <remarks>
/// <para>
/// Because the output gets written by a background thread,
/// the value may change asynchronously. Setting this
/// property always throws a NotSupportedException.
/// </para>
/// </remarks>
public override long Position
{
get { return _outStream.Position; }
set { throw new NotSupportedException(); }
}
/// <summary>
/// This method always throws a NotSupportedException.
/// </summary>
/// <param name="buffer">
/// The buffer into which data would be read, IF THIS METHOD
/// ACTUALLY DID ANYTHING.
/// </param>
/// <param name="offset">
/// The offset within that data array at which to insert the
/// data that is read, IF THIS METHOD ACTUALLY DID
/// ANYTHING.
/// </param>
/// <param name="count">
/// The number of bytes to write, IF THIS METHOD ACTUALLY DID
/// ANYTHING.
/// </param>
/// <returns>nothing.</returns>
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
/// <summary>
/// This method always throws a NotSupportedException.
/// </summary>
/// <param name="offset">
/// The offset to seek to....
/// IF THIS METHOD ACTUALLY DID ANYTHING.
/// </param>
/// <param name="origin">
/// The reference specifying how to apply the offset.... IF
/// THIS METHOD ACTUALLY DID ANYTHING.
/// </param>
/// <returns>nothing. It always throws.</returns>
public override long Seek(long offset, System.IO.SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <summary>
/// This method always throws a NotSupportedException.
/// </summary>
/// <param name="value">
/// The new value for the stream length.... IF
/// THIS METHOD ACTUALLY DID ANYTHING.
/// </param>
public override void SetLength(long value)
{
throw new NotSupportedException();
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_OXCMSG
{
using System;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Protocols.TestSuites.Common;
/// <summary>
/// Address book EntryIDs can represent several types of Address Book objects including individual users,
/// distribution lists, containers, and templates as specified in table 4.
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct AddressBookEntryID : ISerializable
{
/// <summary>
/// A 4 bytes indicates a long-term EntryID, this value must be 0x00000000.
/// </summary>
public uint Flags;
/// <summary>
/// The value of ProviderUID
/// </summary>
public byte[] ProviderUID;
/// <summary>
/// The version for address book entry id,MUST be set to %x01.00.00.00.
/// </summary>
public byte[] Version;
/// <summary>
/// A 32-bit integer representing the type of the object.
/// </summary>
public uint Type;
/// <summary>
/// The X500 DN of the Address Book object. X500DN is a null-terminated string of 8-bit characters.
/// </summary>
public string X500DN;
/// <summary>
/// Follows X500DN
/// </summary>
public string Domain;
/// <summary>
/// The size of ProviderUID field.
/// </summary>
private const int ProviderUIDSize = 0x0010;
/// <summary>
/// The size of VersionSize field.
/// </summary>
private const int VersionSize = 0x0004;
/// <summary>
/// The size of TypeSize field.
/// </summary>
private const int TypeSize = 0x0004;
/// <summary>
/// The serialized AddressBookEntryID structure.
/// </summary>
private byte[] result;
/// <summary>
/// Size of AddressBookEntryID structure.
/// </summary>
private int size;
/// <summary>
/// Deserialize the response buffer.
/// </summary>
/// <param name="ropBytes">Bytes in response.</param>
/// <param name="startIndex">The start index of this structure.</param>
/// <returns>The size of response buffer structure.</returns>
public int Deserialize(byte[] ropBytes, int startIndex)
{
int index = startIndex + 2;
this.Flags = BitConverter.ToUInt32(ropBytes, index);
index = index + TypeSize;
this.ProviderUID = new byte[ProviderUIDSize];
Array.Copy(ropBytes, index, this.ProviderUID, 0, ProviderUIDSize);
index = index + ProviderUIDSize;
this.Version = new byte[VersionSize];
Array.Copy(ropBytes, index, this.Version, 0, VersionSize);
index = index + VersionSize;
this.Type = BitConverter.ToUInt32(ropBytes, index);
index += TypeSize;
if (index >= ropBytes.Length)
{
throw new ParseException("The X500DN is not found from response buffer. The index was outside the bounds of the response buffer.");
}
this.X500DN = this.GetAddressValue(ropBytes, ref index);
return 0;
}
/// <summary>
/// Serialize the ROP request buffer.
/// </summary>
/// <returns>The serialized ROP request buffer.</returns>
public byte[] Serialize()
{
this.result = new byte[this.Size()];
int index = 0;
Array.Copy(new byte[] { 0x00, 0x00, 0x00, 0x00 }, 0, this.result, index, 4);
index += 4;
Array.Copy(this.ProviderUID, 0, this.result, index, 16);
index += 16;
Array.Copy(this.Version, 0, this.result, index, 4);
index += 4;
Array.Copy(BitConverter.GetBytes(this.Type), 0, this.result, index, sizeof(uint));
index += 4;
if (!string.IsNullOrEmpty(this.X500DN))
{
byte[] values = System.Text.Encoding.Default.GetBytes(this.X500DN);
Array.Copy(values, 0, this.result, index, values.Length);
}
return this.result;
}
/// <summary>
/// Size of address book EntryId structure.
/// </summary>
/// <returns>The size of this structure.</returns>
public int Size()
{
// For address book EntryId Flags
this.size = 0;
// For address book EntryId ProviderUID
this.size += ProviderUIDSize;
// For address book EntryId Version
this.size += VersionSize;
// For address book EntryId Type
this.size += TypeSize;
if (null != this.X500DN)
{
this.size += this.X500DN.Length;
}
return this.size;
}
/// <summary>
/// Indicates whether this instance and a specific object are equals
/// </summary>
/// <param name="obj">The object that compare with this instance.</param>
/// <returns>A Boolean value indicates whether this instance and a specific object are equals.</returns>
public override bool Equals(object obj)
{
if (obj.GetType() != typeof(AddressBookEntryID))
{
return false;
}
AddressBookEntryID addrObj = (AddressBookEntryID)obj;
if (addrObj.Type != this.Type)
{
return false;
}
if (addrObj.X500DN != this.X500DN)
{
return false;
}
return true;
}
/// <summary>
/// Return the hash code of this instance.
/// </summary>
/// <returns>The hash code of this instance </returns>
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
/// Get Address Value in the byte array values
/// </summary>
/// <param name="values">the byte array which contains the value</param>
/// <param name="index">The start index of values</param>
/// <returns>The value of Address</returns>
private string GetAddressValue(byte[] values, ref int index)
{
string res = string.Empty;
int i = Array.IndexOf<byte>(values, 0x00, index);
if (i == -1)
{
throw new ParseException("The X500DN is not found from response buffer. The index was outside the bounds of the response buffer.");
}
res = Encoding.ASCII.GetString(values, index, i + 1 - index);
index = i + 1;
return res;
}
}
}
| |
namespace Meziantou.Framework.CodeDom;
public class Visitor
{
public virtual void Visit(CodeObject? codeObject)
{
if (codeObject == null)
return;
switch (codeObject)
{
case AddEventHandlerStatement addEventHandlerStatement:
VisitAddEventHandlerStatement(addEventHandlerStatement);
break;
case ArgumentReferenceExpression argumentReferenceExpression:
VisitArgumentReferenceExpression(argumentReferenceExpression);
break;
case ArrayIndexerExpression arrayIndexerExpression:
VisitArrayIndexerExpression(arrayIndexerExpression);
break;
case AssignStatement assignStatement:
VisitAssignStatement(assignStatement);
break;
case AwaitExpression awaitExpression:
VisitAwaitExpression(awaitExpression);
break;
case BaseExpression baseExpression:
VisitBaseExpression(baseExpression);
break;
case BaseTypeParameterConstraint baseTypeParameterConstraint:
VisitBaseTypeParameterConstraint(baseTypeParameterConstraint);
break;
case BinaryExpression binaryExpression:
VisitBinaryExpression(binaryExpression);
break;
case CastExpression castExpression:
VisitCastExpression(castExpression);
break;
case CatchClause catchClause:
VisitCatchClause(catchClause);
break;
case CatchClauseCollection catchClauseCollection:
VisitCatchClauseCollection(catchClauseCollection);
break;
case ClassDeclaration classDeclaration:
VisitClassDeclaration(classDeclaration);
break;
case ClassTypeParameterConstraint classTypeParameterConstraint:
VisitClassTypeParameterConstraint(classTypeParameterConstraint);
break;
case CodeObjectCollection<Expression> expressions:
VisitExpressions(expressions);
break;
case Comment comment:
VisitComment(comment);
break;
case CommentCollection commentCollection:
VisitCommentCollection(commentCollection);
break;
case CommentStatement commentStatement:
VisitCommentStatement(commentStatement);
break;
case CompilationUnit compilationUnit:
VisitCompilationUnit(compilationUnit);
break;
case ConditionStatement conditionStatement:
VisitConditionStatement(conditionStatement);
break;
case ConstructorBaseInitializer constructorBaseInitializer:
VisitConstructorBaseInitializer(constructorBaseInitializer);
break;
case ConstructorDeclaration constructorDeclaration:
VisitConstructorDeclaration(constructorDeclaration);
break;
case ConstructorParameterConstraint constructorParameterConstraint:
VisitConstructorParameterConstraint(constructorParameterConstraint);
break;
case ConstructorThisInitializer constructorThisInitializer:
VisitConstructorThisInitializer(constructorThisInitializer);
break;
case ConvertExpression convertExpression:
VisitConvertExpression(convertExpression);
break;
case CustomAttribute customAttribute:
VisitCustomAttribute(customAttribute);
break;
case CustomAttributeArgument customAttributeArgument:
VisitCustomAttributeArgument(customAttributeArgument);
break;
case DefaultValueExpression defaultValueExpression:
VisitDefaultValueExpression(defaultValueExpression);
break;
case DelegateDeclaration delegateDeclaration:
VisitDelegateDeclaration(delegateDeclaration);
break;
case EnumerationDeclaration enumerationDeclaration:
VisitEnumerationDeclaration(enumerationDeclaration);
break;
case EnumerationMember enumerationMember:
VisitEnumerationMember(enumerationMember);
break;
case EventFieldDeclaration eventFieldDeclaration:
VisitEventFieldDeclaration(eventFieldDeclaration);
break;
case ExitLoopStatement exitLoopStatement:
VisitExitLoopStatement(exitLoopStatement);
break;
case ExpressionCollectionStatement expressionCollectionStatement:
VisitExpressionCollectionStatement(expressionCollectionStatement);
break;
case ExpressionStatement expressionStatement:
VisitExpressionStatement(expressionStatement);
break;
case FieldDeclaration fieldDeclaration:
VisitFieldDeclaration(fieldDeclaration);
break;
case GotoNextLoopIterationStatement gotoNextLoopIterationStatement:
VisitGotoNextLoopIterationStatement(gotoNextLoopIterationStatement);
break;
case InterfaceDeclaration interfaceDeclaration:
VisitInterfaceDeclaration(interfaceDeclaration);
break;
case IterationStatement iterationStatement:
VisitIterationStatement(iterationStatement);
break;
case LiteralExpression literalExpression:
VisitLiteralExpression(literalExpression);
break;
case MemberReferenceExpression memberReferenceExpression:
VisitMemberReferenceExpression(memberReferenceExpression);
break;
case MethodArgumentDeclaration methodArgumentDeclaration:
VisitMethodArgumentDeclaration(methodArgumentDeclaration);
break;
case MethodArgumentCollection methodArgumentCollection:
VisitMethodArgumentCollection(methodArgumentCollection);
break;
case MethodDeclaration methodDeclaration:
VisitMethodDeclaration(methodDeclaration);
break;
case MethodExitStatement methodExitStatement:
VisitMethodExitStatement(methodExitStatement);
break;
case MethodInvokeArgumentExpression methodInvokeArgumentExpression:
VisitMethodInvokeArgumentExpression(methodInvokeArgumentExpression);
break;
case MethodInvokeExpression methodInvokeExpression:
VisitMethodInvokeExpression(methodInvokeExpression);
break;
case NameofExpression nameofExpression:
VisitNameofExpression(nameofExpression);
break;
case NamespaceDeclaration namespaceDeclaration:
VisitNamespaceDeclaration(namespaceDeclaration);
break;
case NewObjectExpression newObjectExpression:
VisitNewObjectExpression(newObjectExpression);
break;
case OperatorDeclaration operatorDeclaration:
VisitOperatorDeclaration(operatorDeclaration);
break;
case PropertyAccessorDeclaration propertyAccessorDeclaration:
VisitPropertyAccessorDeclaration(propertyAccessorDeclaration);
break;
case PropertyDeclaration propertyDeclaration:
VisitPropertyDeclaration(propertyDeclaration);
break;
case RemoveEventHandlerStatement removeEventHandlerStatement:
VisitRemoveEventHandlerStatement(removeEventHandlerStatement);
break;
case ReturnStatement returnStatement:
VisitReturnStatement(returnStatement);
break;
case SnippetExpression snippetExpression:
VisitSnippetExpression(snippetExpression);
break;
case SnippetStatement snippetStatement:
VisitSnippetStatement(snippetStatement);
break;
case StatementCollection statementCollection:
VisitStatementCollection(statementCollection);
break;
case StructDeclaration structDeclaration:
VisitStructDeclaration(structDeclaration);
break;
case RecordDeclaration recordDeclaration:
VisitRecordDeclaration(recordDeclaration);
break;
case ThisExpression thisExpression:
VisitThisExpression(thisExpression);
break;
case ThrowStatement throwStatement:
VisitThrowStatement(throwStatement);
break;
case TryCatchFinallyStatement tryCatchFinallyStatement:
VisitTryCatchFinallyStatement(tryCatchFinallyStatement);
break;
case TypeOfExpression typeOfExpression:
VisitTypeOfExpression(typeOfExpression);
break;
case TypeParameter typeParameter:
VisitTypeParameter(typeParameter);
break;
case TypeParameterConstraintCollection typeParameterConstraintCollection:
VisitTypeParameterConstraintCollection(typeParameterConstraintCollection);
break;
case TypeReferenceExpression typeReference:
VisitTypeReferenceExpression(typeReference);
break;
case UnaryExpression unaryExpression:
VisitUnaryExpression(unaryExpression);
break;
case UnmanagedTypeParameterConstraint unmanagedTypeParameterConstraint:
VisitUnmanagedTypeParameterConstraint(unmanagedTypeParameterConstraint);
break;
case UsingDirective usingDirective:
VisitUsingDirective(usingDirective);
break;
case UsingStatement usingStatement:
VisitUsingStatement(usingStatement);
break;
case ValueArgumentExpression valueArgumentExpression:
VisitValueArgumentExpression(valueArgumentExpression);
break;
case ValueTypeTypeParameterConstraint valueTypeTypeParameterConstraint:
VisitValueTypeTypeParameterConstraint(valueTypeTypeParameterConstraint);
break;
case VariableDeclarationStatement variableDeclarationStatement:
VisitVariableDeclarationStatement(variableDeclarationStatement);
break;
case VariableReferenceExpression variableReference:
VisitVariableReference(variableReference);
break;
case WhileStatement whileStatement:
VisitWhileStatement(whileStatement);
break;
case XmlComment xmlComment:
VisitXmlComment(xmlComment);
break;
case XmlCommentCollection xmlCommentCollection:
VisitXmlCommentCollection(xmlCommentCollection);
break;
case YieldBreakStatement yieldBreakStatement:
VisitYieldBreakStatement(yieldBreakStatement);
break;
case YieldReturnStatement yieldReturnStatement:
VisitYieldReturnStatement(yieldReturnStatement);
break;
case NewArrayExpression newArrayExpression:
VisitNewArrayExpression(newArrayExpression);
break;
case IsInstanceOfTypeExpression isInstanceOfTypeExpression:
VisitIsInstanceOfTypeExpression(isInstanceOfTypeExpression);
break;
default:
throw new ArgumentOutOfRangeException(nameof(codeObject));
}
}
protected virtual void VisitIsInstanceOfTypeExpression(IsInstanceOfTypeExpression isInstanceOfTypeExpression)
{
VisitExpression(isInstanceOfTypeExpression);
VisitTypeReferenceIfNotNull(isInstanceOfTypeExpression.Type);
Visit(isInstanceOfTypeExpression.Expression);
}
protected virtual void VisitNewArrayExpression(NewArrayExpression newArrayExpression)
{
VisitExpression(newArrayExpression);
VisitTypeReferenceIfNotNull(newArrayExpression.Type);
VisitCollection(newArrayExpression.Arguments);
}
public virtual void VisitTypeParameterConstraintCollection(TypeParameterConstraintCollection typeParameterConstraintCollection)
{
VisitCollection(typeParameterConstraintCollection);
}
public virtual void VisitExpressionCollectionStatement(ExpressionCollectionStatement expressionCollectionStatement)
{
VisitStatement(expressionCollectionStatement);
foreach (var item in expressionCollectionStatement)
{
Visit(item);
}
}
public virtual void VisitXmlCommentCollection(XmlCommentCollection xmlCommentCollection)
{
VisitCollection(xmlCommentCollection);
}
public virtual void VisitCommentCollection(CommentCollection commentCollection)
{
VisitCollection(commentCollection);
}
public virtual void VisitYieldReturnStatement(YieldReturnStatement yieldReturnStatement)
{
VisitStatement(yieldReturnStatement);
Visit(yieldReturnStatement.Expression);
}
public virtual void VisitYieldBreakStatement(YieldBreakStatement yieldBreakStatement)
{
VisitStatement(yieldBreakStatement);
}
public virtual void VisitXmlComment(XmlComment xmlComment)
{
}
public virtual void VisitWhileStatement(WhileStatement whileStatement)
{
VisitStatement(whileStatement);
Visit(whileStatement.Condition);
Visit(whileStatement.Body);
}
public virtual void VisitVariableReference(VariableReferenceExpression variableReferenceExpression)
{
VisitExpression(variableReferenceExpression);
}
public virtual void VisitVariableDeclarationStatement(VariableDeclarationStatement variableDeclarationStatement)
{
VisitStatement(variableDeclarationStatement);
Visit(variableDeclarationStatement.InitExpression);
}
public virtual void VisitValueTypeTypeParameterConstraint(ValueTypeTypeParameterConstraint valueTypeTypeParameterConstraint)
{
}
public virtual void VisitValueArgumentExpression(ValueArgumentExpression valueArgumentExpression)
{
VisitExpression(valueArgumentExpression);
}
public virtual void VisitUsingStatement(UsingStatement usingStatement)
{
VisitStatement(usingStatement);
Visit(usingStatement.Statement);
Visit(usingStatement.Body);
}
public virtual void VisitUsingDirective(UsingDirective usingDirective)
{
VisitDirective(usingDirective);
}
public virtual void VisitUnmanagedTypeParameterConstraint(UnmanagedTypeParameterConstraint unmanagedTypeParameterConstraint)
{
}
public virtual void VisitUnaryExpression(UnaryExpression unaryExpression)
{
VisitExpression(unaryExpression);
Visit(unaryExpression.Expression);
}
private void VisitTypeReferenceIfNotNull(TypeReference? typeReference)
{
if (typeReference != null)
{
VisitTypeReference(typeReference);
}
}
public virtual void VisitTypeReference(TypeReference typeReference)
{
}
public virtual void VisitTypeReferenceExpression(TypeReferenceExpression typeReference)
{
VisitTypeReferenceIfNotNull(typeReference.Type);
}
public virtual void VisitTypeOfExpression(TypeOfExpression typeOfExpression)
{
VisitExpression(typeOfExpression);
VisitTypeReferenceIfNotNull(typeOfExpression.Type);
}
public virtual void VisitTryCatchFinallyStatement(TryCatchFinallyStatement tryCatchFinallyStatement)
{
VisitStatement(tryCatchFinallyStatement);
Visit(tryCatchFinallyStatement.Try);
Visit(tryCatchFinallyStatement.Catch);
Visit(tryCatchFinallyStatement.Finally);
}
public virtual void VisitCatchClauseCollection(CatchClauseCollection catchClauseCollection)
{
VisitCollection(catchClauseCollection);
}
public virtual void VisitThrowStatement(ThrowStatement throwStatement)
{
VisitStatement(throwStatement);
Visit(throwStatement.Expression);
}
public virtual void VisitThisExpression(ThisExpression thisExpression)
{
VisitExpression(thisExpression);
}
public virtual void VisitSnippetStatement(SnippetStatement snippetStatement)
{
VisitStatement(snippetStatement);
}
public virtual void VisitSnippetExpression(SnippetExpression snippetExpression)
{
VisitExpression(snippetExpression);
}
public virtual void VisitReturnStatement(ReturnStatement returnStatement)
{
VisitStatement(returnStatement);
Visit(returnStatement.Expression);
}
public virtual void VisitPropertyDeclaration(PropertyDeclaration propertyDeclaration)
{
VisitMemberDeclaration(propertyDeclaration);
VisitTypeReferenceIfNotNull(propertyDeclaration.PrivateImplementationType);
Visit(propertyDeclaration.Getter);
Visit(propertyDeclaration.Setter);
}
public virtual void VisitPropertyAccessorDeclaration(PropertyAccessorDeclaration propertyAccessorDeclaration)
{
Visit(propertyAccessorDeclaration.Statements);
}
public virtual void VisitOperatorDeclaration(OperatorDeclaration operatorDeclaration)
{
VisitMemberDeclaration(operatorDeclaration);
VisitTypeReferenceIfNotNull(operatorDeclaration.ReturnType);
VisitMethodArgumentCollection(operatorDeclaration.Arguments);
Visit(operatorDeclaration.Statements);
}
public virtual void VisitNewObjectExpression(NewObjectExpression newObjectExpression)
{
VisitExpression(newObjectExpression);
Visit(newObjectExpression.Arguments);
VisitTypeReferenceIfNotNull(newObjectExpression.Type);
}
public virtual void VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration)
{
VisitCommentable(namespaceDeclaration);
VisitCollection(namespaceDeclaration.Namespaces);
VisitCollection(namespaceDeclaration.Types);
VisitCollection(namespaceDeclaration.Usings);
}
public virtual void VisitNameofExpression(NameofExpression nameofExpression)
{
VisitExpression(nameofExpression);
Visit(nameofExpression.Expression);
}
public virtual void VisitMethodInvokeExpression(MethodInvokeExpression methodInvokeExpression)
{
VisitExpression(methodInvokeExpression);
VisitTypeReferenceCollection(methodInvokeExpression.Parameters);
Visit(methodInvokeExpression.Arguments);
Visit(methodInvokeExpression.Method);
}
public virtual void VisitMethodInvokeArgumentExpression(MethodInvokeArgumentExpression methodInvokeArgumentExpression)
{
VisitExpression(methodInvokeArgumentExpression);
Visit(methodInvokeArgumentExpression.Value);
}
public virtual void VisitMethodExitStatement(MethodExitStatement methodExitStatement)
{
VisitStatement(methodExitStatement);
}
public virtual void VisitMethodDeclaration(MethodDeclaration methodDeclaration)
{
VisitMemberDeclaration(methodDeclaration);
VisitTypeReferenceIfNotNull(methodDeclaration.ReturnType);
VisitTypeReferenceIfNotNull(methodDeclaration.PrivateImplementationType);
VisitCollection(methodDeclaration.Parameters);
VisitMethodArgumentCollection(methodDeclaration.Arguments);
Visit(methodDeclaration.Statements);
}
public virtual void VisitMethodArgumentDeclaration(MethodArgumentDeclaration methodArgumentDeclaration)
{
VisitCommentable(methodArgumentDeclaration);
VisitCustomAttributeContainer(methodArgumentDeclaration);
VisitTypeReferenceIfNotNull(methodArgumentDeclaration.Type);
Visit(methodArgumentDeclaration.DefaultValue);
}
public virtual void VisitMemberReferenceExpression(MemberReferenceExpression memberReferenceExpression)
{
VisitExpression(memberReferenceExpression);
}
public virtual void VisitLiteralExpression(LiteralExpression literalExpression)
{
VisitExpression(literalExpression);
}
public virtual void VisitIterationStatement(IterationStatement iterationStatement)
{
VisitStatement(iterationStatement);
Visit(iterationStatement.Initialization);
Visit(iterationStatement.Condition);
Visit(iterationStatement.IncrementStatement);
Visit(iterationStatement.Body);
}
public virtual void VisitGotoNextLoopIterationStatement(GotoNextLoopIterationStatement gotoNextLoopIterationStatement)
{
VisitStatement(gotoNextLoopIterationStatement);
}
public virtual void VisitFieldDeclaration(FieldDeclaration fieldDeclaration)
{
VisitMemberDeclaration(fieldDeclaration);
VisitTypeReferenceIfNotNull(fieldDeclaration.Type);
Visit(fieldDeclaration.InitExpression);
}
public virtual void VisitExpressionStatement(ExpressionStatement expressionStatement)
{
VisitStatement(expressionStatement);
Visit(expressionStatement.Expression);
}
public virtual void VisitExitLoopStatement(ExitLoopStatement exitLoopStatement)
{
VisitStatement(exitLoopStatement);
}
public virtual void VisitEventFieldDeclaration(EventFieldDeclaration eventFieldDeclaration)
{
VisitMemberDeclaration(eventFieldDeclaration);
VisitTypeReferenceIfNotNull(eventFieldDeclaration.Type);
Visit(eventFieldDeclaration.AddAccessor);
Visit(eventFieldDeclaration.RemoveAccessor);
VisitTypeReferenceIfNotNull(eventFieldDeclaration.PrivateImplementationType);
}
public virtual void VisitEnumerationMember(EnumerationMember enumerationMember)
{
VisitMemberDeclaration(enumerationMember);
VisitCollection(enumerationMember.Implements);
Visit(enumerationMember.Value);
}
public virtual void VisitEnumerationDeclaration(EnumerationDeclaration enumerationDeclaration)
{
VisitTypeDeclaration(enumerationDeclaration);
VisitTypeReferenceIfNotNull(enumerationDeclaration.BaseType);
VisitCollection(enumerationDeclaration.Members);
}
public virtual void VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration)
{
VisitTypeDeclaration(delegateDeclaration);
VisitTypeReferenceIfNotNull(delegateDeclaration.ReturnType);
VisitCollection(delegateDeclaration.Parameters);
VisitCollection(delegateDeclaration.Arguments);
}
public virtual void VisitDefaultValueExpression(DefaultValueExpression defaultValueExpression)
{
VisitExpression(defaultValueExpression);
}
public virtual void VisitCustomAttributeArgument(CustomAttributeArgument customAttributeArgument)
{
VisitCommentable(customAttributeArgument);
Visit(customAttributeArgument.Value);
}
public virtual void VisitCustomAttribute(CustomAttribute customAttribute)
{
VisitCommentable(customAttribute);
VisitCollection(customAttribute.Arguments);
VisitTypeReferenceIfNotNull(customAttribute.Type);
}
public virtual void VisitConvertExpression(ConvertExpression convertExpression)
{
VisitExpression(convertExpression);
Visit(convertExpression.Expression);
VisitTypeReferenceIfNotNull(convertExpression.Type);
}
public virtual void VisitConstructorThisInitializer(ConstructorThisInitializer constructorThisInitializer)
{
VisitConstructorInitializer(constructorThisInitializer);
}
public virtual void VisitConstructorParameterConstraint(ConstructorParameterConstraint constructorParameterConstraint)
{
}
public virtual void VisitConstructorDeclaration(ConstructorDeclaration constructorDeclaration)
{
VisitMemberDeclaration(constructorDeclaration);
VisitCollection(constructorDeclaration.Arguments);
Visit(constructorDeclaration.Statements);
Visit(constructorDeclaration.Initializer);
}
public virtual void VisitConstructorBaseInitializer(ConstructorBaseInitializer constructorBaseInitializer)
{
VisitConstructorInitializer(constructorBaseInitializer);
}
public virtual void VisitConditionStatement(ConditionStatement conditionStatement)
{
VisitStatement(conditionStatement);
Visit(conditionStatement.Condition);
Visit(conditionStatement.TrueStatements);
Visit(conditionStatement.FalseStatements);
}
public virtual void VisitCommentStatement(CommentStatement commentStatement)
{
VisitStatement(commentStatement);
}
public virtual void VisitComment(Comment comment)
{
}
public virtual void VisitClassTypeParameterConstraint(ClassTypeParameterConstraint classTypeParameterConstraint)
{
}
public virtual void VisitCatchClause(CatchClause catchClause)
{
VisitCommentable(catchClause);
VisitTypeReferenceIfNotNull(catchClause.ExceptionType);
Visit(catchClause.Body);
}
public virtual void VisitCastExpression(CastExpression castExpression)
{
VisitExpression(castExpression);
Visit(castExpression.Expression);
VisitTypeReferenceIfNotNull(castExpression.Type);
}
public virtual void VisitBinaryExpression(BinaryExpression binaryExpression)
{
VisitExpression(binaryExpression);
Visit(binaryExpression.LeftExpression);
Visit(binaryExpression.RightExpression);
}
public virtual void VisitBaseTypeParameterConstraint(BaseTypeParameterConstraint baseTypeParameterConstraint)
{
}
public virtual void VisitBaseExpression(BaseExpression baseExpression)
{
VisitExpression(baseExpression);
}
public virtual void VisitAwaitExpression(AwaitExpression awaitExpression)
{
VisitExpression(awaitExpression);
Visit(awaitExpression.Expression);
}
public virtual void VisitAssignStatement(AssignStatement assignStatement)
{
VisitStatement(assignStatement);
Visit(assignStatement.LeftExpression);
Visit(assignStatement.RightExpression);
}
public virtual void VisitArgumentReferenceExpression(ArgumentReferenceExpression argumentReferenceExpression)
{
VisitExpression(argumentReferenceExpression);
}
public virtual void VisitAddEventHandlerStatement(AddEventHandlerStatement addEventHandlerStatement)
{
VisitStatement(addEventHandlerStatement);
Visit(addEventHandlerStatement.LeftExpression);
Visit(addEventHandlerStatement.RightExpression);
}
public virtual void VisitRemoveEventHandlerStatement(RemoveEventHandlerStatement removeEventHandlerStatement)
{
VisitStatement(removeEventHandlerStatement);
Visit(removeEventHandlerStatement.LeftExpression);
Visit(removeEventHandlerStatement.RightExpression);
}
public virtual void VisitArrayIndexerExpression(ArrayIndexerExpression arrayIndexerExpression)
{
VisitExpression(arrayIndexerExpression);
Visit(arrayIndexerExpression.ArrayExpression);
Visit(arrayIndexerExpression.Indices);
}
public virtual void VisitInterfaceDeclaration(InterfaceDeclaration interfaceDeclaration)
{
VisitTypeDeclaration(interfaceDeclaration);
VisitMemberContainer(interfaceDeclaration);
VisitParametrableType(interfaceDeclaration);
VisitTypeDeclarationContainer(interfaceDeclaration);
VisitTypeReferenceCollection(interfaceDeclaration.Implements);
VisitTypeReferenceIfNotNull(interfaceDeclaration.BaseType);
}
public virtual void VisitTypeParameterConstraint(TypeParameterConstraint typeParameterConstraint)
{
}
public virtual void VisitTypeParameter(TypeParameter typeParameter)
{
VisitCollection(typeParameter.Constraints);
}
public virtual void VisitCompilationUnit(CompilationUnit compilationUnit)
{
VisitCollection(compilationUnit.Namespaces);
VisitCollection(compilationUnit.Types);
VisitCollection(compilationUnit.Usings);
}
public virtual void VisitNamespace(NamespaceDeclaration namespaceDeclaration)
{
VisitCollection(namespaceDeclaration.Namespaces);
VisitCollection(namespaceDeclaration.Types);
VisitCollection(namespaceDeclaration.Usings);
}
public virtual void VisitStructDeclaration(StructDeclaration structDeclaration)
{
VisitTypeDeclaration(structDeclaration);
VisitMemberContainer(structDeclaration);
VisitParametrableType(structDeclaration);
VisitTypeDeclarationContainer(structDeclaration);
VisitTypeReferenceCollection(structDeclaration.Implements);
}
public virtual void VisitClassDeclaration(ClassDeclaration classDeclaration)
{
VisitTypeDeclaration(classDeclaration);
VisitMemberContainer(classDeclaration);
VisitParametrableType(classDeclaration);
VisitTypeDeclarationContainer(classDeclaration);
VisitTypeReferenceCollection(classDeclaration.Implements);
VisitTypeReferenceIfNotNull(classDeclaration.BaseType);
}
public virtual void VisitRecordDeclaration(RecordDeclaration recordDeclaration)
{
VisitTypeDeclaration(recordDeclaration);
VisitMemberContainer(recordDeclaration);
VisitParametrableType(recordDeclaration);
VisitTypeDeclarationContainer(recordDeclaration);
VisitTypeReferenceCollection(recordDeclaration.Implements);
VisitTypeReferenceIfNotNull(recordDeclaration.BaseType);
}
public virtual void VisitExpressions(CodeObjectCollection<Expression> expressions)
{
VisitCollection(expressions);
}
public virtual void VisitStatementCollection(StatementCollection statements)
{
VisitCollection(statements);
}
public virtual void VisitMethodArgumentCollection(MethodArgumentCollection arguments)
{
VisitCollection(arguments);
}
private void VisitCollection<T>(IEnumerable<T> items) where T : CodeObject
{
if (items == null)
return;
foreach (var item in items)
{
Visit(item);
}
}
private void VisitTypeReferenceCollection(IEnumerable<TypeReference> items)
{
if (items == null)
return;
foreach (var item in items)
{
VisitTypeReferenceIfNotNull(item);
}
}
private void VisitCommentable(ICommentable commentable)
{
Visit(commentable.CommentsBefore);
Visit(commentable.CommentsAfter);
}
private void VisitXmlCommentable(IXmlCommentable commentable)
{
Visit(commentable.XmlComments);
}
private void VisitCustomAttributeContainer(ICustomAttributeContainer commentable)
{
VisitCollection(commentable.CustomAttributes);
}
private void VisitParametrableType(IParametrableType parametrableType)
{
VisitCollection(parametrableType.Parameters);
}
private void VisitTypeDeclarationContainer(ITypeDeclarationContainer typeDeclarationContainer)
{
VisitCollection(typeDeclarationContainer.Types);
}
private void VisitMemberContainer(IMemberContainer memberContainer)
{
VisitCollection(memberContainer.Members);
}
private void VisitTypeDeclaration(TypeDeclaration typeDeclaration)
{
VisitCustomAttributeContainer(typeDeclaration);
VisitCommentable(typeDeclaration);
VisitXmlCommentable(typeDeclaration);
}
private void VisitMemberDeclaration(MemberDeclaration memberDeclaration)
{
VisitCustomAttributeContainer(memberDeclaration);
VisitCommentable(memberDeclaration);
VisitXmlCommentable(memberDeclaration);
VisitCollection(memberDeclaration.Implements);
}
private void VisitExpression(Expression expression)
{
VisitCommentable(expression);
}
private void VisitStatement(Statement statement)
{
VisitCommentable(statement);
}
private void VisitDirective(Directive directive)
{
VisitCommentable(directive);
}
private void VisitConstructorInitializer(ConstructorInitializer constructor)
{
VisitCommentable(constructor);
Visit(constructor.Arguments);
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using ModestTree;
using Zenject.Internal;
using Zenject.ReflectionBaking.Mono.Cecil;
using Zenject.ReflectionBaking.Mono.Cecil.Cil;
using Zenject.ReflectionBaking.Mono.Collections.Generic;
using MethodAttributes = Zenject.ReflectionBaking.Mono.Cecil.MethodAttributes;
namespace Zenject.ReflectionBaking
{
public class ReflectionBakingModuleEditor
{
readonly Assembly _assembly;
readonly ModuleDefinition _module;
readonly List<Regex> _namespaceRegexes;
MethodReference _zenjectTypeInfoConstructor;
MethodReference _injectableInfoConstructor;
MethodReference _injectMethodInfoConstructor;
MethodReference _injectMemberInfoConstructor;
MethodReference _constructorInfoConstructor;
MethodReference _getTypeFromHandleMethod;
MethodReference _funcConstructor;
MethodReference _funcPostInject;
MethodReference _funcMemberSetter;
MethodReference _preserveConstructor;
TypeReference _injectMethodInfoType;
TypeReference _injectMemberInfoType;
TypeReference _injectableInfoType;
TypeReference _objectArrayType;
TypeReference _zenjectTypeInfoType;
ReflectionBakingModuleEditor(
ModuleDefinition module, Assembly assembly, List<string> namespacePatterns)
{
_module = module;
_assembly = assembly;
_namespaceRegexes = namespacePatterns.Select(CreateRegex).ToList();
_namespaceRegexes.Add(CreateRegex("^Zenject"));
}
public static int WeaveAssembly(
ModuleDefinition module, Assembly assembly)
{
return WeaveAssembly(module, assembly, new List<string>());
}
public static int WeaveAssembly(
ModuleDefinition module, Assembly assembly, List<string> namespacePatterns)
{
return new ReflectionBakingModuleEditor(module, assembly, namespacePatterns).Run();
}
int Run()
{
SaveImports();
int numTypesEditted = 0;
var allTypes = _module.LookupAllTypes();
foreach (var typeDef in allTypes)
{
if (_namespaceRegexes.Any() && !_namespaceRegexes.Any(x => x.IsMatch(typeDef.FullName)))
{
continue;
}
var actualType = typeDef.TryGetActualType(_assembly);
if (actualType == null)
{
Log.Warn("Could not find actual type for type '{0}', skipping", typeDef.FullName);
continue;
}
if (TryEditType(typeDef, actualType))
{
numTypesEditted++;
}
}
return numTypesEditted;
}
Regex CreateRegex(string regexStr)
{
return new Regex(regexStr, RegexOptions.Compiled);
}
void SaveImports()
{
_zenjectTypeInfoType = _module.ImportType<InjectTypeInfo>();
_zenjectTypeInfoConstructor = _module.ImportMethod<InjectTypeInfo>(".ctor");
_injectableInfoConstructor = _module.ImportMethod<InjectableInfo>(".ctor");
_getTypeFromHandleMethod = _module.ImportMethod<Type>("GetTypeFromHandle", 1);
_injectMethodInfoType = _module.ImportType<InjectTypeInfo.InjectMethodInfo>();
_injectMethodInfoConstructor = _module.ImportMethod<InjectTypeInfo.InjectMethodInfo>(".ctor");
_injectMemberInfoType = _module.ImportType<InjectTypeInfo.InjectMemberInfo>();
_injectMemberInfoConstructor = _module.ImportMethod<InjectTypeInfo.InjectMemberInfo>(".ctor");
_preserveConstructor = _module.ImportMethod<Zenject.Internal.PreserveAttribute>(".ctor");
_constructorInfoConstructor = _module.ImportMethod<InjectTypeInfo.InjectConstructorInfo>(".ctor");
_injectableInfoType = _module.ImportType<InjectableInfo>();
_objectArrayType = _module.Import(typeof(object[]));
_funcConstructor = _module.ImportMethod<ZenFactoryMethod>(".ctor", 2);
_funcPostInject = _module.ImportMethod<ZenInjectMethod>(".ctor", 2);
_funcMemberSetter = _module.ImportMethod<ZenMemberSetterMethod>(".ctor", 2);
}
public bool TryEditType(TypeDefinition typeDef, Type actualType)
{
if (actualType.IsEnum || actualType.IsValueType || actualType.IsInterface
|| actualType.HasAttribute<NoReflectionBakingAttribute>()
|| IsStaticClass(actualType) || actualType.DerivesFromOrEqual<Delegate>() || actualType.DerivesFromOrEqual<Attribute>())
{
return false;
}
// Allow running on the same dll multiple times without causing problems
if (IsTypeProcessed(typeDef))
{
return false;
}
try
{
var typeInfo = ReflectionTypeAnalyzer.GetReflectionInfo(actualType);
var factoryMethod = TryAddFactoryMethod(typeDef, typeInfo);
var genericTypeDef = CreateGenericInstanceWithParameters(typeDef);
var fieldSetMethods = AddFieldSetters(typeDef, genericTypeDef, typeInfo);
var propertySetMethods = AddPropertySetters(typeDef, genericTypeDef, typeInfo);
var postInjectMethods = AddPostInjectMethods(typeDef, genericTypeDef, typeInfo);
CreateGetInfoMethod(
typeDef, genericTypeDef, typeInfo,
factoryMethod, fieldSetMethods, propertySetMethods, postInjectMethods);
}
catch (Exception e)
{
Log.ErrorException("Error when modifying type '{0}'".Fmt(actualType), e);
throw;
}
return true;
}
static bool IsStaticClass(Type type)
{
// Apparently this is unique to static classes
return type.IsAbstract && type.IsSealed;
}
// We are already processed if our static constructor calls TypeAnalyzer
bool IsTypeProcessed(TypeDefinition typeDef)
{
return typeDef.GetMethod(TypeAnalyzer.ReflectionBakingGetInjectInfoMethodName) != null;
}
void EmitCastOperation(ILProcessor processor, Type type, Collection<GenericParameter> genericParams)
{
if (type.IsGenericParameter)
{
processor.Emit(OpCodes.Unbox_Any, genericParams[type.GenericParameterPosition]);
}
else if (type.IsEnum)
{
processor.Emit(OpCodes.Unbox_Any, _module.TypeSystem.Int32);
}
else if (type.IsValueType)
{
processor.Emit(OpCodes.Unbox_Any, _module.ImportType(type));
}
else
{
processor.Emit(OpCodes.Castclass, CreateGenericInstanceIfNecessary(type, genericParams));
}
}
TypeReference CreateGenericInstanceWithParameters(TypeDefinition typeDef)
{
if (typeDef.GenericParameters.Any())
{
var genericInstance = new GenericInstanceType(typeDef);
foreach (var parameter in typeDef.GenericParameters)
{
genericInstance.GenericArguments.Add(parameter);
}
return genericInstance;
}
return typeDef;
}
MethodDefinition TryAddFactoryMethod(
TypeDefinition typeDef, ReflectionTypeInfo typeInfo)
{
if (typeInfo.Type.GetParentTypes().Any(x => x.FullName == "UnityEngine.Component"))
{
Assert.That(typeInfo.InjectConstructor.Parameters.IsEmpty());
return null;
}
if (typeInfo.InjectConstructor.ConstructorInfo == null)
{
// static classes, abstract types
return null;
}
var factoryMethod = new MethodDefinition(
TypeAnalyzer.ReflectionBakingFactoryMethodName,
MethodAttributes.Private | MethodAttributes.HideBySig |
MethodAttributes.Static,
_module.TypeSystem.Object);
var p1 = new ParameterDefinition(_objectArrayType);
p1.Name = "P_0";
factoryMethod.Parameters.Add(p1);
var body = factoryMethod.Body;
body.InitLocals = true;
var processor = body.GetILProcessor();
var returnValueVar = new VariableDefinition(_module.TypeSystem.Object);
body.Variables.Add(returnValueVar);
processor.Emit(OpCodes.Nop);
Assert.IsNotNull(typeInfo.InjectConstructor);
var args = typeInfo.InjectConstructor.Parameters;
for (int i = 0; i < args.Count; i++)
{
var arg = args[i];
processor.Emit(OpCodes.Ldarg_0);
processor.Emit(OpCodes.Ldc_I4, i);
processor.Emit(OpCodes.Ldelem_Ref);
EmitCastOperation(
processor, arg.ParameterInfo.ParameterType, typeDef.GenericParameters);
}
processor.Emit(OpCodes.Newobj, _module.Import(typeInfo.InjectConstructor.ConstructorInfo));
processor.Emit(OpCodes.Stloc_0);
processor.Emit(OpCodes.Ldloc_S, returnValueVar);
processor.Emit(OpCodes.Ret);
typeDef.Methods.Add(factoryMethod);
return factoryMethod;
}
void AddPostInjectMethodBody(
ILProcessor processor, ReflectionTypeInfo.InjectMethodInfo postInjectInfo, TypeDefinition typeDef, TypeReference genericTypeDef)
{
processor.Emit(OpCodes.Nop);
TypeReference declaringTypeDef;
MethodReference actualMethodDef;
if (!TryFindLocalMethod(
genericTypeDef, postInjectInfo.MethodInfo.Name, out declaringTypeDef, out actualMethodDef))
{
throw Assert.CreateException();
}
processor.Emit(OpCodes.Ldarg_0);
processor.Emit(OpCodes.Castclass, declaringTypeDef);
for (int k = 0; k < postInjectInfo.Parameters.Count; k++)
{
var injectInfo = postInjectInfo.Parameters[k];
processor.Emit(OpCodes.Ldarg_1);
processor.Emit(OpCodes.Ldc_I4, k);
processor.Emit(OpCodes.Ldelem_Ref);
EmitCastOperation(processor, injectInfo.ParameterInfo.ParameterType, typeDef.GenericParameters);
}
processor.Emit(OpCodes.Callvirt, actualMethodDef);
processor.Emit(OpCodes.Ret);
}
MethodDefinition AddPostInjectMethod(
string name, ReflectionTypeInfo.InjectMethodInfo postInjectInfo, TypeDefinition typeDef, TypeReference genericTypeDef)
{
var methodDef = new MethodDefinition(
name,
MethodAttributes.Private | MethodAttributes.HideBySig |
MethodAttributes.Static,
_module.TypeSystem.Void);
var p1 = new ParameterDefinition(_module.TypeSystem.Object);
p1.Name = "P_0";
methodDef.Parameters.Add(p1);
var p2 = new ParameterDefinition(_objectArrayType);
p2.Name = "P_1";
methodDef.Parameters.Add(p2);
var body = methodDef.Body;
var processor = body.GetILProcessor();
AddPostInjectMethodBody(processor, postInjectInfo, typeDef, genericTypeDef);
typeDef.Methods.Add(methodDef);
return methodDef;
}
List<MethodDefinition> AddPostInjectMethods(
TypeDefinition typeDef, TypeReference genericTypeDef, ReflectionTypeInfo typeInfo)
{
var postInjectMethods = new List<MethodDefinition>();
for (int i = 0; i < typeInfo.InjectMethods.Count; i++)
{
postInjectMethods.Add(
AddPostInjectMethod(
TypeAnalyzer.ReflectionBakingInjectMethodPrefix + i, typeInfo.InjectMethods[i], typeDef, genericTypeDef));
}
return postInjectMethods;
}
void EmitSetterMethod(
ILProcessor processor, MemberInfo memberInfo, TypeDefinition typeDef, TypeReference genericTypeDef)
{
processor.Emit(OpCodes.Nop);
processor.Emit(OpCodes.Ldarg_0);
processor.Emit(OpCodes.Castclass, genericTypeDef);
processor.Emit(OpCodes.Ldarg_1);
if (memberInfo is FieldInfo)
{
var fieldInfo = (FieldInfo)memberInfo;
EmitCastOperation(processor, fieldInfo.FieldType, typeDef.GenericParameters);
processor.Emit(OpCodes.Stfld, FindLocalField(genericTypeDef, fieldInfo.Name));
}
else
{
var propertyInfo = (PropertyInfo)memberInfo;
EmitCastOperation(processor, propertyInfo.PropertyType, typeDef.GenericParameters);
processor.Emit(OpCodes.Callvirt, FindLocalPropertySetMethod(genericTypeDef, propertyInfo.Name));
}
processor.Emit(OpCodes.Ret);
}
MethodDefinition AddSetterMethod(
string name, MemberInfo memberInfo, TypeDefinition typeDef, TypeReference genericTypeDef)
{
var methodDef = new MethodDefinition(
name,
MethodAttributes.Private | MethodAttributes.HideBySig |
MethodAttributes.Static,
_module.TypeSystem.Void);
var p1 = new ParameterDefinition(_module.TypeSystem.Object);
p1.Name = "P_0";
methodDef.Parameters.Add(p1);
var p2 = new ParameterDefinition(_module.TypeSystem.Object);
p2.Name = "P_1";
methodDef.Parameters.Add(p2);
methodDef.Body.InitLocals = true;
EmitSetterMethod(
methodDef.Body.GetILProcessor(), memberInfo, typeDef, genericTypeDef);
typeDef.Methods.Add(methodDef);
return methodDef;
}
List<MethodDefinition> AddPropertySetters(
TypeDefinition typeDef, TypeReference genericTypeDef, ReflectionTypeInfo typeInfo)
{
var methodDefs = new List<MethodDefinition>();
for (int i = 0; i < typeInfo.InjectProperties.Count; i++)
{
methodDefs.Add(
AddSetterMethod(
TypeAnalyzer.ReflectionBakingPropertySetterPrefix + i,
typeInfo.InjectProperties[i].PropertyInfo, typeDef, genericTypeDef));
}
return methodDefs;
}
List<MethodDefinition> AddFieldSetters(
TypeDefinition typeDef, TypeReference genericTypeDef, ReflectionTypeInfo typeInfo)
{
var methodDefs = new List<MethodDefinition>();
for (int i = 0; i < typeInfo.InjectFields.Count; i++)
{
methodDefs.Add(
AddSetterMethod(
TypeAnalyzer.ReflectionBakingFieldSetterPrefix + i,
typeInfo.InjectFields[i].FieldInfo, typeDef, genericTypeDef));
}
return methodDefs;
}
void CreateGetInfoMethod(
TypeDefinition typeDef, TypeReference genericTypeDef, ReflectionTypeInfo typeInfo,
MethodDefinition factoryMethod, List<MethodDefinition> fieldSetMethods,
List<MethodDefinition> propertySetMethods, List<MethodDefinition> postInjectMethods)
{
var getInfoMethodDef = new MethodDefinition(
TypeAnalyzer.ReflectionBakingGetInjectInfoMethodName,
MethodAttributes.Private | MethodAttributes.HideBySig |
MethodAttributes.Static,
_zenjectTypeInfoType);
typeDef.Methods.Add(getInfoMethodDef);
getInfoMethodDef.CustomAttributes.Add(
new CustomAttribute(_preserveConstructor));
var returnValueVar = new VariableDefinition(_module.TypeSystem.Object);
var body = getInfoMethodDef.Body;
body.Variables.Add(returnValueVar);
body.InitLocals = true;
var instructions = new List<Instruction>();
instructions.Add(Instruction.Create(OpCodes.Ldtoken, genericTypeDef));
instructions.Add(Instruction.Create(OpCodes.Call, _getTypeFromHandleMethod));
if (factoryMethod == null)
{
instructions.Add(Instruction.Create(OpCodes.Ldnull));
}
else
{
instructions.Add(Instruction.Create(OpCodes.Ldnull));
instructions.Add(Instruction.Create(OpCodes.Ldftn, factoryMethod.ChangeDeclaringType(genericTypeDef)));
instructions.Add(Instruction.Create(OpCodes.Newobj, _funcConstructor));
}
instructions.Add(Instruction.Create(OpCodes.Ldc_I4, typeInfo.InjectConstructor.Parameters.Count));
instructions.Add(Instruction.Create(OpCodes.Newarr, _injectableInfoType));
for (int i = 0; i < typeInfo.InjectConstructor.Parameters.Count; i++)
{
var injectableInfo = typeInfo.InjectConstructor.Parameters[i].InjectableInfo;
instructions.Add(Instruction.Create(OpCodes.Dup));
instructions.Add(Instruction.Create(OpCodes.Ldc_I4, i));
EmitNewInjectableInfoInstructions(
instructions, injectableInfo, typeDef);
instructions.Add(Instruction.Create(OpCodes.Stelem_Ref));
}
instructions.Add(Instruction.Create(OpCodes.Newobj, _constructorInfoConstructor));
instructions.Add(Instruction.Create(OpCodes.Ldc_I4, typeInfo.InjectMethods.Count));
instructions.Add(Instruction.Create(OpCodes.Newarr, _injectMethodInfoType));
Assert.IsEqual(postInjectMethods.Count, typeInfo.InjectMethods.Count);
for (int i = 0; i < typeInfo.InjectMethods.Count; i++)
{
var injectMethodInfo = typeInfo.InjectMethods[i];
instructions.Add(Instruction.Create(OpCodes.Dup));
instructions.Add(Instruction.Create(OpCodes.Ldc_I4, i));
AddInjectableMethodInstructions(
instructions, injectMethodInfo, typeDef, genericTypeDef, postInjectMethods[i]);
instructions.Add(Instruction.Create(OpCodes.Stelem_Ref));
}
instructions.Add(Instruction.Create(OpCodes.Ldc_I4, fieldSetMethods.Count + propertySetMethods.Count));
instructions.Add(Instruction.Create(OpCodes.Newarr, _injectMemberInfoType));
for (int i = 0; i < fieldSetMethods.Count; i++)
{
var injectField = typeInfo.InjectFields[i];
instructions.Add(Instruction.Create(OpCodes.Dup));
instructions.Add(Instruction.Create(OpCodes.Ldc_I4, i));
AddInjectableMemberInstructions(
instructions,
injectField.InjectableInfo, injectField.FieldInfo.Name,
typeDef, genericTypeDef, fieldSetMethods[i]);
instructions.Add(Instruction.Create(OpCodes.Stelem_Ref));
}
for (int i = 0; i < propertySetMethods.Count; i++)
{
var injectProperty = typeInfo.InjectProperties[i];
instructions.Add(Instruction.Create(OpCodes.Dup));
instructions.Add(Instruction.Create(OpCodes.Ldc_I4, fieldSetMethods.Count + i));
AddInjectableMemberInstructions(
instructions,
injectProperty.InjectableInfo,
injectProperty.PropertyInfo.Name, typeDef, genericTypeDef,
propertySetMethods[i]);
instructions.Add(Instruction.Create(OpCodes.Stelem_Ref));
}
instructions.Add(Instruction.Create(OpCodes.Newobj, _zenjectTypeInfoConstructor));
instructions.Add(Instruction.Create(OpCodes.Stloc_0));
instructions.Add(Instruction.Create(OpCodes.Ldloc_S, returnValueVar));
instructions.Add(Instruction.Create(OpCodes.Ret));
var processor = body.GetILProcessor();
foreach (var instruction in instructions)
{
processor.Append(instruction);
}
}
MethodReference FindLocalPropertySetMethod(
TypeReference specificTypeRef, string memberName)
{
foreach (var typeRef in specificTypeRef.GetSpecificBaseTypesAndSelf())
{
var candidatePropertyDef = typeRef.Resolve().Properties
.Where(x => x.Name == memberName).SingleOrDefault();
if (candidatePropertyDef != null)
{
return candidatePropertyDef.SetMethod.ChangeDeclaringType(typeRef);
}
}
throw Assert.CreateException();
}
FieldReference FindLocalField(
TypeReference specificTypeRef, string fieldName)
{
foreach (var typeRef in specificTypeRef.GetSpecificBaseTypesAndSelf())
{
var candidateFieldDef = typeRef.Resolve().Fields
.Where(x => x.Name == fieldName).SingleOrDefault();
if (candidateFieldDef != null)
{
return candidateFieldDef.ChangeDeclaringType(typeRef);
}
}
throw Assert.CreateException();
}
bool TryFindLocalMethod(
TypeReference specificTypeRef, string methodName, out TypeReference declaringTypeRef, out MethodReference methodRef)
{
foreach (var typeRef in specificTypeRef.GetSpecificBaseTypesAndSelf())
{
var candidateMethodDef = typeRef.Resolve().Methods
.Where(x => x.Name == methodName).SingleOrDefault();
if (candidateMethodDef != null)
{
declaringTypeRef = typeRef;
methodRef = candidateMethodDef.ChangeDeclaringType(typeRef);
return true;
}
}
declaringTypeRef = null;
methodRef = null;
return false;
}
void AddObjectInstructions(
List<Instruction> instructions,
object identifier)
{
if (identifier == null)
{
instructions.Add(Instruction.Create(OpCodes.Ldnull));
}
else if (identifier is string)
{
instructions.Add(Instruction.Create(OpCodes.Ldstr, (string)identifier));
}
else if (identifier is int)
{
instructions.Add(Instruction.Create(OpCodes.Ldc_I4, (int)identifier));
instructions.Add(Instruction.Create(OpCodes.Box, _module.Import(typeof(int))));
}
else if (identifier.GetType().IsEnum)
{
instructions.Add(Instruction.Create(OpCodes.Ldc_I4, (int)identifier));
instructions.Add(Instruction.Create(OpCodes.Box, _module.Import(identifier.GetType())));
}
else
{
throw Assert.CreateException(
"Cannot process values with type '{0}' currently. Feel free to add support for this and submit a pull request to github.", identifier.GetType());
}
}
TypeReference CreateGenericInstanceIfNecessary(
Type memberType, Collection<GenericParameter> genericParams)
{
if (!memberType.ContainsGenericParameters)
{
return _module.Import(memberType);
}
if (memberType.IsGenericParameter)
{
return genericParams[memberType.GenericParameterPosition];
}
if (memberType.IsArray)
{
return new ArrayType(
CreateGenericInstanceIfNecessary(memberType.GetElementType(), genericParams), memberType.GetArrayRank());
}
var genericMemberType = memberType.GetGenericTypeDefinition();
var genericInstance = new GenericInstanceType(_module.Import(genericMemberType));
foreach (var arg in memberType.GenericArguments())
{
genericInstance.GenericArguments.Add(
CreateGenericInstanceIfNecessary(arg, genericParams));
}
return genericInstance;
}
void AddInjectableMemberInstructions(
List<Instruction> instructions,
InjectableInfo injectableInfo, string name,
TypeDefinition typeDef, TypeReference genericTypeDef,
MethodDefinition methodDef)
{
instructions.Add(Instruction.Create(OpCodes.Ldnull));
instructions.Add(Instruction.Create(OpCodes.Ldftn, methodDef.ChangeDeclaringType(genericTypeDef)));
instructions.Add(Instruction.Create(OpCodes.Newobj, _funcMemberSetter));
EmitNewInjectableInfoInstructions(
instructions, injectableInfo, typeDef);
instructions.Add(Instruction.Create(OpCodes.Newobj, _injectMemberInfoConstructor));
}
void AddInjectableMethodInstructions(
List<Instruction> instructions,
ReflectionTypeInfo.InjectMethodInfo injectMethod,
TypeDefinition typeDef, TypeReference genericTypeDef,
MethodDefinition methodDef)
{
instructions.Add(Instruction.Create(OpCodes.Ldnull));
instructions.Add(Instruction.Create(OpCodes.Ldftn, methodDef.ChangeDeclaringType(genericTypeDef)));
instructions.Add(Instruction.Create(OpCodes.Newobj, _funcPostInject));
instructions.Add(Instruction.Create(OpCodes.Ldc_I4, injectMethod.Parameters.Count));
instructions.Add(Instruction.Create(OpCodes.Newarr, _injectableInfoType));
for (int i = 0; i < injectMethod.Parameters.Count; i++)
{
var injectableInfo = injectMethod.Parameters[i].InjectableInfo;
instructions.Add(Instruction.Create(OpCodes.Dup));
instructions.Add(Instruction.Create(OpCodes.Ldc_I4, i));
EmitNewInjectableInfoInstructions(
instructions, injectableInfo, typeDef);
instructions.Add(Instruction.Create(OpCodes.Stelem_Ref));
}
instructions.Add(Instruction.Create(OpCodes.Ldstr, injectMethod.MethodInfo.Name));
instructions.Add(Instruction.Create(OpCodes.Newobj, _injectMethodInfoConstructor));
}
void EmitNewInjectableInfoInstructions(
List<Instruction> instructions,
InjectableInfo injectableInfo,
TypeDefinition typeDef)
{
if (injectableInfo.Optional)
{
instructions.Add(Instruction.Create(OpCodes.Ldc_I4_1));
}
else
{
instructions.Add(Instruction.Create(OpCodes.Ldc_I4_0));
}
AddObjectInstructions(instructions, injectableInfo.Identifier);
instructions.Add(Instruction.Create(OpCodes.Ldstr, injectableInfo.MemberName));
instructions.Add(Instruction.Create(OpCodes.Ldtoken, CreateGenericInstanceIfNecessary(injectableInfo.MemberType, typeDef.GenericParameters)));
instructions.Add(Instruction.Create(OpCodes.Call, _getTypeFromHandleMethod));
AddObjectInstructions(instructions, injectableInfo.DefaultValue);
instructions.Add(Instruction.Create(OpCodes.Ldc_I4, (int)injectableInfo.SourceType));
instructions.Add(Instruction.Create(OpCodes.Newobj, _injectableInfoConstructor));
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
using System.Security;
internal static partial class Interop
{
private const String HANDLEDLL = "api-ms-win-core-handle-l1-1-0.dll";
private const String MEMORYDLL = "api-ms-win-core-memory-l1-1-0.dll";
private const String SYSINFODLL = "api-ms-win-core-sysinfo-l1-1-0.dll";
private const String LOCALIZATIONDLL = "api-ms-win-core-localization-l1-2-0.dll";
//
// Win32 IO
//
// WinError.h codes:
internal const int ERROR_SUCCESS = 0x0;
internal const int ERROR_FILE_NOT_FOUND = 0x2;
internal const int ERROR_PATH_NOT_FOUND = 0x3;
internal const int ERROR_ACCESS_DENIED = 0x5;
internal const int ERROR_INVALID_HANDLE = 0x6;
// Can occurs when filled buffers are trying to flush to disk, but disk IOs are not fast enough.
// This happens when the disk is slow and event traffic is heavy.
// Eventually, there are no more free (empty) buffers and the event is dropped.
internal const int ERROR_NOT_ENOUGH_MEMORY = 0x8;
internal const int ERROR_INVALID_DRIVE = 0xF;
internal const int ERROR_NO_MORE_FILES = 0x12;
internal const int ERROR_NOT_READY = 0x15;
internal const int ERROR_BAD_LENGTH = 0x18;
internal const int ERROR_SHARING_VIOLATION = 0x20;
internal const int ERROR_LOCK_VIOLATION = 0x21; // 33
internal const int ERROR_HANDLE_EOF = 0x26; // 38
internal const int ERROR_FILE_EXISTS = 0x50;
internal const int ERROR_INVALID_PARAMETER = 0x57; // 87
internal const int ERROR_BROKEN_PIPE = 0x6D; // 109
internal const int ERROR_INSUFFICIENT_BUFFER = 0x7A; // 122
internal const int ERROR_INVALID_NAME = 0x7B;
internal const int ERROR_BAD_PATHNAME = 0xA1;
internal const int ERROR_ALREADY_EXISTS = 0xB7;
internal const int ERROR_ENVVAR_NOT_FOUND = 0xCB;
internal const int ERROR_FILENAME_EXCED_RANGE = 0xCE; // filename too long
internal const int ERROR_PIPE_BUSY = 0xE7; // 231
internal const int ERROR_NO_DATA = 0xE8; // 232
internal const int ERROR_PIPE_NOT_CONNECTED = 0xE9; // 233
internal const int ERROR_MORE_DATA = 0xEA;
internal const int ERROR_NO_MORE_ITEMS = 0x103; // 259
internal const int ERROR_PIPE_CONNECTED = 0x217; // 535
internal const int ERROR_PIPE_LISTENING = 0x218; // 536
internal const int ERROR_OPERATION_ABORTED = 0x3E3; // 995; For IO Cancellation
internal const int ERROR_IO_PENDING = 0x3E5; // 997
internal const int ERROR_NOT_FOUND = 0x490; // 1168
// The event size is larger than the allowed maximum (64k - header).
internal const int ERROR_ARITHMETIC_OVERFLOW = 0x216; // 534
internal const int ERROR_RESOURCE_LANG_NOT_FOUND = 0x717; // 1815
// Event log specific codes:
internal const int ERROR_EVT_MESSAGE_NOT_FOUND = 15027;
internal const int ERROR_EVT_MESSAGE_ID_NOT_FOUND = 15028;
internal const int ERROR_EVT_UNRESOLVED_VALUE_INSERT = 15029;
internal const int ERROR_EVT_UNRESOLVED_PARAMETER_INSERT = 15030;
internal const int ERROR_EVT_MAX_INSERTS_REACHED = 15031;
internal const int ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND = 15033;
internal const int ERROR_MUI_FILE_NOT_FOUND = 15100;
internal const int SECURITY_SQOS_PRESENT = 0x00100000;
internal const int SECURITY_ANONYMOUS = 0 << 16;
internal const int SECURITY_IDENTIFICATION = 1 << 16;
internal const int SECURITY_IMPERSONATION = 2 << 16;
internal const int SECURITY_DELEGATION = 3 << 16;
internal const int GENERIC_READ = unchecked((int)0x80000000);
internal const int GENERIC_WRITE = 0x40000000;
internal const int STD_INPUT_HANDLE = -10;
internal const int STD_OUTPUT_HANDLE = -11;
internal const int STD_ERROR_HANDLE = -12;
internal const int DUPLICATE_SAME_ACCESS = 0x00000002;
internal const int PIPE_ACCESS_INBOUND = 1;
internal const int PIPE_ACCESS_OUTBOUND = 2;
internal const int PIPE_ACCESS_DUPLEX = 3;
internal const int PIPE_TYPE_BYTE = 0;
internal const int PIPE_TYPE_MESSAGE = 4;
internal const int PIPE_READMODE_BYTE = 0;
internal const int PIPE_READMODE_MESSAGE = 2;
internal const int PIPE_UNLIMITED_INSTANCES = 255;
internal const int FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000;
internal const int FILE_SHARE_READ = 0x00000001;
internal const int FILE_SHARE_WRITE = 0x00000002;
internal const int FILE_ATTRIBUTE_NORMAL = 0x00000080;
internal const int FILE_FLAG_OVERLAPPED = 0x40000000;
internal const int OPEN_EXISTING = 3;
// From WinBase.h
internal const int FILE_TYPE_DISK = 0x0001;
internal const int FILE_TYPE_CHAR = 0x0002;
internal const int FILE_TYPE_PIPE = 0x0003;
// Memory mapped file constants
internal const int MEM_COMMIT = 0x1000;
internal const int MEM_RESERVE = 0x2000;
internal const int INVALID_FILE_SIZE = -1;
internal const int PAGE_READWRITE = 0x04;
internal const int PAGE_READONLY = 0x02;
internal const int PAGE_WRITECOPY = 0x08;
internal const int PAGE_EXECUTE_READ = 0x20;
internal const int PAGE_EXECUTE_READWRITE = 0x40;
internal const int FILE_MAP_COPY = 0x0001;
internal const int FILE_MAP_WRITE = 0x0002;
internal const int FILE_MAP_READ = 0x0004;
internal const int FILE_MAP_EXECUTE = 0x0020;
// From WinBase.h
internal const int SEM_FAILCRITICALERRORS = 1;
internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
[StructLayout(LayoutKind.Sequential)]
internal struct SYSTEM_INFO
{
internal int dwOemId;
internal int dwPageSize;
internal IntPtr lpMinimumApplicationAddress;
internal IntPtr lpMaximumApplicationAddress;
internal IntPtr dwActiveProcessorMask;
internal int dwNumberOfProcessors;
internal int dwProcessorType;
internal int dwAllocationGranularity;
internal short wProcessorLevel;
internal short wProcessorRevision;
}
[StructLayout(LayoutKind.Sequential)]
internal struct SECURITY_ATTRIBUTES
{
public uint nLength;
public IntPtr lpSecurityDescriptor;
public bool bInheritHandle;
}
[StructLayout(LayoutKind.Sequential)]
internal struct MEMORYSTATUSEX
{
internal uint dwLength;
internal uint dwMemoryLoad;
internal ulong ullTotalPhys;
internal ulong ullAvailPhys;
internal ulong ullTotalPageFile;
internal ulong ullAvailPageFile;
internal ulong ullTotalVirtual;
internal ulong ullAvailVirtual;
internal ulong ullAvailExtendedVirtual;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct MEMORY_BASIC_INFORMATION
{
internal void* BaseAddress;
internal void* AllocationBase;
internal uint AllocationProtect;
internal UIntPtr RegionSize;
internal uint State;
internal uint Protect;
internal uint Type;
}
internal static partial class mincore
{
[DllImport(LOCALIZATIONDLL, EntryPoint = "FormatMessageW", CharSet = CharSet.Unicode)]
internal extern static uint FormatMessage(
uint dwFlags,
IntPtr lpSource,
uint dwMessageId,
uint dwLanguageId,
char[] lpBuffer,
uint nSize,
IntPtr Arguments);
[DllImport(MEMORYDLL)]
internal extern static int FlushViewOfFile(IntPtr lpBaseAddress, UIntPtr dwNumberOfBytesToFlush);
[DllImport(MEMORYDLL)]
internal extern static int UnmapViewOfFile(IntPtr lpBaseAddress);
[DllImport(SYSINFODLL)]
internal extern static void GetSystemInfo(out SYSTEM_INFO lpSystemInfo);
[DllImport(SYSINFODLL)]
internal extern static int GlobalMemoryStatusEx(out MEMORYSTATUSEX lpBuffer);
[DllImport(MEMORYDLL, EntryPoint = "CreateFileMappingW", CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
internal static extern SafeMemoryMappedFileHandle CreateFileMapping(SafeFileHandle hFile,
ref SECURITY_ATTRIBUTES lpFileMappingAttributes, int flProtect,
int dwMaximumSizeHigh, int dwMaximumSizeLow, string lpName);
[DllImport(MEMORYDLL, EntryPoint = "CreateFileMappingW", CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
internal static extern SafeMemoryMappedFileHandle CreateFileMapping(IntPtr hFile,
ref SECURITY_ATTRIBUTES lpFileMappingAttributes, int flProtect,
int dwMaximumSizeHigh, int dwMaximumSizeLow, string lpName);
[DllImport(MEMORYDLL, EntryPoint = "OpenFileMappingW", CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
internal static extern SafeMemoryMappedFileHandle OpenFileMapping(
int dwDesiredAccess,
[MarshalAs(UnmanagedType.Bool)] bool bInheritHandle,
string lpName);
[DllImport(MEMORYDLL, EntryPoint = "MapViewOfFile", CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
internal static extern SafeMemoryMappedViewHandle MapViewOfFile(
SafeMemoryMappedFileHandle hFileMappingObject,
int dwDesiredAccess,
int dwFileOffsetHigh,
int dwFileOffsetLow,
UIntPtr dwNumberOfBytesToMap);
[DllImport(MEMORYDLL, EntryPoint = "VirtualQuery", CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
internal extern static UIntPtr VirtualQuery(
SafeMemoryMappedViewHandle lpAddress,
ref MEMORY_BASIC_INFORMATION lpBuffer,
UIntPtr dwLength);
[DllImport(MEMORYDLL, EntryPoint = "VirtualAlloc", CharSet = CharSet.Unicode, SetLastError = true)]
[SecurityCritical]
internal extern static IntPtr VirtualAlloc(
SafeHandle lpAddress,
UIntPtr dwSize,
int flAllocationType,
int flProtect);
[DllImport(HANDLEDLL, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
[SecurityCritical]
internal static extern bool CloseHandle(IntPtr handle);
}
}
| |
using NAME.Core.Exceptions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using NAME.Json;
using NAME.Core;
using NAME.ConnectionStrings;
using NAME.Dependencies;
using NAME.Registration;
using NAME.Core.Utils;
namespace NAME
{
/// <summary>
/// Provides mechanisms to read a NAME configuration file.
/// </summary>
public static class DependenciesReader
{
/// <summary>
/// The maximum dependency depth
/// </summary>
public const int MAX_DEPENDENCY_DEPTH = 10;
private static IDictionary<string, IVersionTranslator> dependencyVersionTranslators;
static DependenciesReader()
{
dependencyVersionTranslators = new Dictionary<string, IVersionTranslator>(StringComparer.OrdinalIgnoreCase)
{
[SupportedDependencies.SqlServer.ToString()] = new SqlServer.SqlServerVersionTranslator(),
["windows"] = new OperatingSystem.WindowsVersionTranslator()
};
}
/// <summary>
/// Reads the configuration.
/// </summary>
/// <param name="dependenciesFile">The configuration file.</param>
/// <param name="pathMapper">The path mapper.</param>
/// <param name="settings">The settings.</param>
/// <param name="context">The context.</param>
/// <returns>
/// Returns the dependencies read from the file.
/// </returns>
/// <exception cref="NAMEException">An unhandled exception happened.</exception>
/// <exception cref="System.IO.FileNotFoundException">The configuration file was not found.</exception>
public static ParsedDependencies ReadDependencies(
string dependenciesFile,
IFilePathMapper pathMapper,
NAMESettings settings,
NAMEContext context)
{
Guard.NotNull(settings, nameof(settings));
if (context == null)
context = new NAMEContext();
string jsonContents = ReadJsonContents(pathMapper.MapPath(dependenciesFile));
return ParseDependenciesFromString(jsonContents, pathMapper, settings, context);
}
/// <summary>
/// Reads the dependencies.
/// </summary>
/// <param name="configurationStream">The configuration stream.</param>
/// <param name="pathMapper">The path mapper.</param>
/// <param name="settings">The context information.</param>
/// <param name="context">The context.</param>
/// <returns>
/// Returns the dependencies read from the stream.
/// </returns>
/// <exception cref="NAMEException">Configuration file stream is not in readable state</exception>
public static ParsedDependencies ReadDependencies(
Stream configurationStream,
IFilePathMapper pathMapper,
NAMESettings settings,
NAMEContext context)
{
Guard.NotNull(settings, nameof(settings));
if (context == null)
context = new NAMEContext();
if (configurationStream.CanRead == false)
{
throw new NAMEException("Configuration file stream is not in readable state", NAMEStatusLevel.Warn);
}
using (StreamReader reader = new StreamReader(configurationStream))
{
var jsonContents = reader.ReadToEnd();
return ParseDependenciesFromString(jsonContents, pathMapper, settings, context);
}
}
private static string ReadJsonContents(string dependenciesFile)
{
if (!File.Exists(dependenciesFile))
{
string exceptionMessage = "The dependencies file was not found.";
throw new NAMEException(exceptionMessage, new FileNotFoundException(exceptionMessage, dependenciesFile), NAMEStatusLevel.Warn);
}
string[] jsonLines = File.ReadAllLines(dependenciesFile);
string jsonContents = string.Join(Environment.NewLine, jsonLines.Where(l => !l.TrimStart().StartsWith("//")));
return jsonContents;
}
private static ParsedDependencies ParseDependenciesFromString(
string jsonContents,
IFilePathMapper pathMapper,
NAMESettings settings,
NAMEContext context)
{
JsonNode rootNode = Json.Json.Parse(jsonContents);
return new ParsedDependencies(
HandleDependencyArray(rootNode?["infrastructure_dependencies"]?.AsArray, pathMapper, settings, context),
HandleDependencyArray(rootNode?["service_dependencies"]?.AsArray, pathMapper, settings, context));
}
private static IList<Dependency> HandleDependencyArray(
JsonArray dependencies,
IFilePathMapper pathMapper,
NAMESettings configuration,
NAMEContext context,
int depth = 0)
{
IList<Dependency> handledDependencies = new List<Dependency>();
if (dependencies == null)
return handledDependencies;
foreach (JsonNode dependency in dependencies)
{
if (dependency.AsObject != null)
handledDependencies.Add(HandleDependency(dependency.AsObject, pathMapper, configuration, context, depth));
}
return handledDependencies;
}
private static Dependency HandleDependency(
JsonClass dependency,
IFilePathMapper pathMapper,
NAMESettings configuration,
NAMEContext context,
int depth = 0)
{
if (depth == MAX_DEPENDENCY_DEPTH)
throw new NAMEException($"Reached the maximum dependency recursion of {MAX_DEPENDENCY_DEPTH}.", NAMEStatusLevel.Warn);
if (dependency == null)
return null;
var conditionObject = dependency["oneOf"];
if (conditionObject != null)
{
depth++;
return new OneOfDependency(HandleDependencyArray(conditionObject.AsArray, pathMapper, configuration, context, depth));
}
var minVersion = dependency["min_version"].Value;
var maxVersion = dependency["max_version"].Value;
var name = dependency["name"]?.Value;
var type = dependency["type"]?.Value;
var osName = dependency["os_name"]?.Value;
type = string.IsNullOrEmpty(type) ? SupportedDependencies.Service.ToString() : type;
if (!Enum.TryParse(type, out SupportedDependencies typedType))
throw new NAMEException($"The dependency type {type} is not supported.", NAMEStatusLevel.Warn);
VersionedDependency result;
if (typedType == SupportedDependencies.OperatingSystem)
{
result = new OperatingSystemDependency()
{
OperatingSystemName = osName,
MinimumVersion = ParseMinimumVersion(minVersion, osName),
MaximumVersion = ParseMaximumVersion(maxVersion, osName)
};
}
else
{
var connectionStringProvider = ParseConnectionStringProvider(dependency["connection_string"], pathMapper, configuration.ConnectionStringProviderOverride);
result = new ConnectedDependency(GetConnectedDependencyVersionResolver(typedType, connectionStringProvider, configuration, context))
{
ConnectionStringProvider = connectionStringProvider,
MinimumVersion = ParseMinimumVersion(minVersion, type),
MaximumVersion = ParseMaximumVersion(maxVersion, type),
ShowConnectionStringInJson = configuration.ConnectedDependencyShowConnectionString
};
}
result.Name = name;
result.Type = typedType;
return result;
}
private static DependencyVersion ParseMinimumVersion(string version, string dependencyType)
{
if (DependencyVersionParser.TryParse(version, false, out DependencyVersion parsedVersion))
return parsedVersion;
if (!dependencyVersionTranslators.ContainsKey(dependencyType))
throw new VersionParsingException($"Could not parse the version of the dependency type {dependencyType}.");
return dependencyVersionTranslators[dependencyType].Translate(version);
}
private static DependencyVersion ParseMaximumVersion(string version, string dependencyType)
{
if (DependencyVersionParser.TryParse(version, true, out DependencyVersion parsedVersion))
return parsedVersion;
if (!dependencyVersionTranslators.ContainsKey(dependencyType))
throw new VersionParsingException($"Could not parse the version of the dependency type {dependencyType}.");
return dependencyVersionTranslators[dependencyType].Translate(version);
}
private static IConnectionStringProvider ParseConnectionStringProvider(
JsonNode node,
IFilePathMapper pathMapper,
Func<IJsonNode, IConnectionStringProvider> connectionStringProviderOverride)
{
if (node.AsObject == null)
return new StaticConnectionStringProvider(node.Value);
IConnectionStringProvider provider = connectionStringProviderOverride?.Invoke(node);
if (provider != null)
return provider;
JsonClass objClass = node.AsObject;
if (!Enum.TryParse(objClass["locator"]?.Value, out SupportedConnectionStringLocators locator))
throw new NAMEException($"The locator {objClass["locator"]?.Value} is not supported.", NAMEStatusLevel.Warn);
string key;
switch (locator)
{
#if NET45
case SupportedConnectionStringLocators.ConnectionStrings:
key = objClass["key"]?.Value;
provider = new ConnectionStringsConnectionStringProvider(key);
break;
case SupportedConnectionStringLocators.AppSettings:
key = objClass["key"]?.Value;
provider = new AppSettingsConnectionStringProvider(key);
break;
case SupportedConnectionStringLocators.VSSettingsFile:
key = objClass["key"]?.Value;
string section = objClass["section"]?.Value;
if (string.IsNullOrEmpty(section))
throw new ArgumentNullException("section", "The section must be specified.");
provider = new VisualStudioSetingsFileConnectionStringProvider(section, key);
break;
#endif
case SupportedConnectionStringLocators.JSONPath:
{
key = objClass["expression"]?.Value;
string file = objClass["file"]?.Value;
if (string.IsNullOrEmpty(file))
throw new ArgumentNullException("file", "The file must be specified.");
provider = new JsonPathConnectionStringProvider(pathMapper.MapPath(file), key);
}
break;
case SupportedConnectionStringLocators.XPath:
{
key = objClass["expression"]?.Value;
string file = objClass["file"]?.Value;
if (string.IsNullOrEmpty(file))
throw new ArgumentNullException("file", "The file must be specified.");
provider = new XpathConnectionStringProvider(pathMapper.MapPath(file), key);
break;
}
case SupportedConnectionStringLocators.EnvironmentVariable:
{
key = objClass["key"]?.Value;
provider = new EnvironmentVariableConnectionStringProvider(key);
}
break;
default:
throw new NAMEException($"The locator {locator.ToString()} is not supported.", NAMEStatusLevel.Warn);
}
if (string.IsNullOrEmpty(key))
throw new ArgumentNullException($"The connection string key/expression must be specified.");
return provider;
}
private static IVersionResolver GetConnectedDependencyVersionResolver(SupportedDependencies dependencyType, IConnectionStringProvider connectionStringProvider, NAMESettings configuration, NAMEContext context)
{
switch (dependencyType)
{
case SupportedDependencies.MongoDb:
return new MongoDb.MongoDbVersionResolver(connectionStringProvider, configuration.DependencyConnectTimeout, configuration.DependencyReadWriteTimeout);
case SupportedDependencies.RabbitMq:
return new RabbitMq.RabbitMqVersionResolver(connectionStringProvider, configuration.DependencyConnectTimeout, configuration.DependencyReadWriteTimeout);
case SupportedDependencies.SqlServer:
return new SqlServer.SqlServerVersionResolver(connectionStringProvider, configuration.DependencyConnectTimeout, configuration.DependencyReadWriteTimeout);
case SupportedDependencies.Service:
return new Service.ServiceVersionResolver(connectionStringProvider, context.ServiceDependencyCurrentNumberOfHops, configuration.ServiceDependencyMaxHops, configuration.DependencyConnectTimeout, configuration.DependencyReadWriteTimeout);
case SupportedDependencies.Elasticsearch:
return new Elasticsearch.ElasticsearchVersionResolver(connectionStringProvider, configuration.DependencyConnectTimeout, configuration.DependencyReadWriteTimeout);
default:
throw new NAMEException($"The dependency of type {dependencyType} is not supported as a connected dependency.", NAMEStatusLevel.Warn);
}
}
/// <summary>
/// Reads the NAME settings overrides.
/// </summary>
/// <param name="settingsFile">The settings file.</param>
/// <param name="pathMapper">The path mapper.</param>
/// <returns>
/// Returns the <see cref="NAMESettings" />.
/// </returns>
public static NAMESettings ReadNAMESettingsOverrides(string settingsFile, IFilePathMapper pathMapper)
{
Guard.NotNull(settingsFile, nameof(settingsFile));
var jsonContents = ReadJsonContents(pathMapper.MapPath(settingsFile));
JsonNode rootNode = Json.Json.Parse(jsonContents);
var overrideNode = rootNode["Overrides"];
var settings = new NAMESettings();
if (overrideNode == null)
return settings;
var registryEndpoints = overrideNode[nameof(settings.RegistryEndpoints)]?.AsArray;
if (registryEndpoints != null)
{
settings.RegistryEndpoints = new string[registryEndpoints.Count];
for (int i = 0; i < registryEndpoints.Count; i++)
{
settings.RegistryEndpoints[i] = registryEndpoints[i].Value;
}
}
var selfhostPortRangeFirst = overrideNode[nameof(settings.SelfHostPortRangeFirst)]?.AsInt;
if (selfhostPortRangeFirst != null)
settings.SelfHostPortRangeFirst = selfhostPortRangeFirst.Value;
var selfhostPortRangeLast = overrideNode[nameof(settings.SelfHostPortRangeLast)]?.AsInt;
if (selfhostPortRangeLast != null)
settings.SelfHostPortRangeLast = selfhostPortRangeLast.Value;
var serviceDependencyMaxHops = overrideNode[nameof(settings.ServiceDependencyMaxHops)]?.AsInt;
if (serviceDependencyMaxHops != null)
settings.ServiceDependencyMaxHops = serviceDependencyMaxHops.Value;
var serviceDependencyShowConnectionString = overrideNode[nameof(settings.ConnectedDependencyShowConnectionString)]?.AsBool;
if (serviceDependencyShowConnectionString != null)
settings.ConnectedDependencyShowConnectionString = serviceDependencyShowConnectionString.Value;
var dependencyConnectTimeout = overrideNode[nameof(settings.DependencyConnectTimeout)]?.AsInt;
if (dependencyConnectTimeout != null)
settings.DependencyConnectTimeout = dependencyConnectTimeout.Value;
var dependencyReadWriteTimeout = overrideNode[nameof(settings.DependencyReadWriteTimeout)]?.AsInt;
if (dependencyReadWriteTimeout != null)
settings.DependencyReadWriteTimeout = dependencyReadWriteTimeout.Value;
var registryReAnnounceFrequency = overrideNode[nameof(settings.RegistryReAnnounceFrequency)];
if (registryReAnnounceFrequency != null && TimeSpan.TryParse(registryReAnnounceFrequency, out TimeSpan parsedAnnounceFreq))
settings.RegistryReAnnounceFrequency = parsedAnnounceFreq;
var registryPingFrequency = overrideNode[nameof(settings.RegistryPingFrequency)];
if (registryPingFrequency != null && TimeSpan.TryParse(registryPingFrequency, out TimeSpan parsedPingFreq))
settings.RegistryPingFrequency = parsedPingFreq;
var runningMode = overrideNode[nameof(settings.RunningMode)];
if (runningMode != null && Enum.TryParse<SupportedNAMEBehaviours>(runningMode.Value.ToString(), false, out var behaviour))
settings.RunningMode = behaviour;
var registryBootstrapRetryFrequency = overrideNode[nameof(settings.RegistryBootstrapRetryFrequency)];
if (registryBootstrapRetryFrequency != null && TimeSpan.TryParse(registryBootstrapRetryFrequency, out TimeSpan bootstrapRetryFreq))
settings.RegistryBootstrapRetryFrequency = bootstrapRetryFreq;
var registryBootstrapConnectTimeout = overrideNode[nameof(settings.RegistryBootstrapTimeout)];
if (registryBootstrapConnectTimeout != null && TimeSpan.TryParse(registryBootstrapConnectTimeout, out TimeSpan bootstrapConnectTimeout))
settings.RegistryBootstrapTimeout = bootstrapConnectTimeout;
return settings;
}
}
}
| |
using TribalWars.Controls.Finders;
using TribalWars.Controls.TimeConverter;
namespace TribalWars.Maps.AttackPlans.Controls
{
partial class AttackPlanControl
{
/// <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 Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AttackPlanControl));
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.panel1 = new System.Windows.Forms.Panel();
this.Coords = new TribalWars.Controls.Finders.VillagePlayerTribeSelector();
this.Close = new System.Windows.Forms.LinkLabel();
this._Player = new System.Windows.Forms.Label();
this._Village = new System.Windows.Forms.Label();
this._Tribe = new System.Windows.Forms.Label();
this.panel3 = new System.Windows.Forms.Panel();
this.CommentsToggle1 = new System.Windows.Forms.Panel();
this.AttackCountLabel = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.Date = new TribalWars.Controls.TimeConverter.TimeConverterControl();
this.Comments = new System.Windows.Forms.TextBox();
this.ToggleComments = new System.Windows.Forms.Button();
this.DistanceContainer = new System.Windows.Forms.FlowLayoutPanel();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.tableLayoutPanel1.SuspendLayout();
this.panel1.SuspendLayout();
this.panel3.SuspendLayout();
this.CommentsToggle1.SuspendLayout();
this.SuspendLayout();
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.panel1, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.panel3, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.DistanceContainer, 0, 2);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.toolTip1.SetToolTip(this.tableLayoutPanel1, resources.GetString("tableLayoutPanel1.ToolTip"));
//
// panel1
//
resources.ApplyResources(this.panel1, "panel1");
this.panel1.Controls.Add(this.Coords);
this.panel1.Controls.Add(this.Close);
this.panel1.Controls.Add(this._Player);
this.panel1.Controls.Add(this._Village);
this.panel1.Controls.Add(this._Tribe);
this.panel1.Name = "panel1";
this.toolTip1.SetToolTip(this.panel1, resources.GetString("panel1.ToolTip"));
//
// Coords
//
resources.ApplyResources(this.Coords, "Coords");
this.Coords.BackColor = System.Drawing.Color.White;
this.Coords.DisplayVillagePurposeImage = true;
this.Coords.GameLocation = null;
this.Coords.Name = "Coords";
this.Coords.PlaceHolderText = "";
this.Coords.ShowImage = false;
this.toolTip1.SetToolTip(this.Coords, resources.GetString("Coords.ToolTip"));
this.Coords.VillageSelected += new System.EventHandler<TribalWars.Worlds.Events.Impls.VillageEventArgs>(this.Coords_VillageSelected);
//
// Close
//
resources.ApplyResources(this.Close, "Close");
this.Close.ActiveLinkColor = System.Drawing.Color.Black;
this.Close.Cursor = System.Windows.Forms.Cursors.Hand;
this.Close.DisabledLinkColor = System.Drawing.Color.Black;
this.Close.LinkColor = System.Drawing.Color.Black;
this.Close.Name = "Close";
this.Close.TabStop = true;
this.toolTip1.SetToolTip(this.Close, resources.GetString("Close.ToolTip"));
this.Close.VisitedLinkColor = System.Drawing.Color.Black;
this.Close.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.Close_LinkClicked);
//
// _Player
//
resources.ApplyResources(this._Player, "_Player");
this._Player.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
this._Player.Name = "_Player";
this.toolTip1.SetToolTip(this._Player, resources.GetString("_Player.ToolTip"));
this._Player.DoubleClick += new System.EventHandler(this.Player_DoubleClick);
this._Player.MouseClick += new System.Windows.Forms.MouseEventHandler(this._Player_MouseClick);
//
// _Village
//
resources.ApplyResources(this._Village, "_Village");
this._Village.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
this._Village.Name = "_Village";
this.toolTip1.SetToolTip(this._Village, resources.GetString("_Village.ToolTip"));
this._Village.DoubleClick += new System.EventHandler(this._Village_DoubleClick);
this._Village.MouseClick += new System.Windows.Forms.MouseEventHandler(this._Village_MouseClick);
//
// _Tribe
//
resources.ApplyResources(this._Tribe, "_Tribe");
this._Tribe.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(64)))), ((int)(((byte)(0)))));
this._Tribe.Name = "_Tribe";
this.toolTip1.SetToolTip(this._Tribe, resources.GetString("_Tribe.ToolTip"));
this._Tribe.DoubleClick += new System.EventHandler(this.Tribe_DoubleClick);
this._Tribe.MouseClick += new System.Windows.Forms.MouseEventHandler(this._Tribe_MouseClick);
//
// panel3
//
resources.ApplyResources(this.panel3, "panel3");
this.panel3.Controls.Add(this.CommentsToggle1);
this.panel3.Controls.Add(this.Comments);
this.panel3.Controls.Add(this.ToggleComments);
this.panel3.Name = "panel3";
this.toolTip1.SetToolTip(this.panel3, resources.GetString("panel3.ToolTip"));
//
// CommentsToggle1
//
resources.ApplyResources(this.CommentsToggle1, "CommentsToggle1");
this.CommentsToggle1.Controls.Add(this.AttackCountLabel);
this.CommentsToggle1.Controls.Add(this.label1);
this.CommentsToggle1.Controls.Add(this.Date);
this.CommentsToggle1.Name = "CommentsToggle1";
this.toolTip1.SetToolTip(this.CommentsToggle1, resources.GetString("CommentsToggle1.ToolTip"));
//
// AttackCountLabel
//
resources.ApplyResources(this.AttackCountLabel, "AttackCountLabel");
this.AttackCountLabel.Name = "AttackCountLabel";
this.toolTip1.SetToolTip(this.AttackCountLabel, resources.GetString("AttackCountLabel.ToolTip"));
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
this.toolTip1.SetToolTip(this.label1, resources.GetString("label1.ToolTip"));
//
// Date
//
resources.ApplyResources(this.Date, "Date");
this.Date.BackColor = System.Drawing.Color.Transparent;
this.Date.CustomFormat = "MMM, dd yyyy HH:mm:ss";
this.Date.Name = "Date";
this.toolTip1.SetToolTip(this.Date, resources.GetString("Date.ToolTip"));
this.Date.Value = new System.DateTime(2008, 4, 10, 0, 26, 44, 906);
this.Date.DateSelected += new System.EventHandler<TribalWars.Controls.TimeConverter.DateEventArgs>(this.Date_DateSelected);
//
// Comments
//
this.Comments.AcceptsReturn = true;
this.Comments.AcceptsTab = true;
resources.ApplyResources(this.Comments, "Comments");
this.Comments.Name = "Comments";
this.toolTip1.SetToolTip(this.Comments, resources.GetString("Comments.ToolTip"));
this.Comments.TextChanged += new System.EventHandler(this.Comments_TextChanged);
//
// ToggleComments
//
resources.ApplyResources(this.ToggleComments, "ToggleComments");
this.ToggleComments.Image = global::TribalWars.Properties.Resources.pencil1;
this.ToggleComments.Name = "ToggleComments";
this.toolTip1.SetToolTip(this.ToggleComments, resources.GetString("ToggleComments.ToolTip"));
this.ToggleComments.UseVisualStyleBackColor = true;
this.ToggleComments.Click += new System.EventHandler(this.ToggleComments_Click);
//
// DistanceContainer
//
resources.ApplyResources(this.DistanceContainer, "DistanceContainer");
this.DistanceContainer.Name = "DistanceContainer";
this.toolTip1.SetToolTip(this.DistanceContainer, resources.GetString("DistanceContainer.ToolTip"));
//
// AttackPlanControl
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.tableLayoutPanel1);
this.Name = "AttackPlanControl";
this.toolTip1.SetToolTip(this, resources.GetString("$this.ToolTip"));
this.tableLayoutPanel1.ResumeLayout(false);
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.panel3.ResumeLayout(false);
this.panel3.PerformLayout();
this.CommentsToggle1.ResumeLayout(false);
this.CommentsToggle1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.Label _Village;
private System.Windows.Forms.Label _Player;
private System.Windows.Forms.Panel panel3;
private System.Windows.Forms.LinkLabel Close;
private TimeConverterControl Date;
private VillagePlayerTribeSelector Coords;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.FlowLayoutPanel DistanceContainer;
private System.Windows.Forms.Label AttackCountLabel;
private System.Windows.Forms.ToolTip toolTip1;
private System.Windows.Forms.Label _Tribe;
private System.Windows.Forms.Button ToggleComments;
private System.Windows.Forms.Panel CommentsToggle1;
private System.Windows.Forms.TextBox Comments;
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace DotSpatial.Data.Forms
{
/// <summary>
/// frmInputBox
/// </summary>
public class InputBox : Form
{
#region Fields
/// <summary>
/// Required designer variable.
/// </summary>
private readonly IContainer _components = null;
private Button _cmdCancel;
private Button _cmdOk;
private Label _lblMessageText;
private TextBox _txtInput;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="InputBox"/> class.
/// </summary>
public InputBox()
{
InitializeComponent();
}
/// <summary>
/// Initializes a new instance of the <see cref="InputBox"/> class.
/// </summary>
/// <param name="text">Sets the text of the message to show.</param>
public InputBox(string text)
: this()
{
_lblMessageText.Text = text;
Validation = ValidationType.None;
}
/// <summary>
/// Initializes a new instance of the <see cref="InputBox"/> class.
/// </summary>
/// <param name="text">The string message to show.</param>
/// <param name="caption">The string caption to allow.</param>
public InputBox(string text, string caption)
: this()
{
_lblMessageText.Text = text;
Validation = ValidationType.None;
Text = caption;
}
/// <summary>
/// Initializes a new instance of the <see cref="InputBox"/> class.
/// </summary>
/// <param name="text">The string message to show.</param>
/// <param name="caption">The string caption to allow.</param>
/// <param name="validation">A DotSpatial.Data.ValidationType enumeration specifying acceptable validation to return OK.</param>
public InputBox(string text, string caption, ValidationType validation)
: this()
{
_lblMessageText.Text = text;
Validation = validation;
Text = caption;
}
/// <summary>
/// Initializes a new instance of the <see cref="InputBox"/> class.
/// </summary>
/// <param name="text">The string message to show.</param>
/// <param name="caption">The string caption to allow.</param>
/// <param name="validation">A DotSpatial.Data.ValidationType enumeration specifying acceptable validation to return OK.</param>
/// <param name="icon">Specifies an icon to appear on this messagebox.</param>
public InputBox(string text, string caption, ValidationType validation, Icon icon)
: this()
{
_lblMessageText.Text = text;
Validation = validation;
Text = caption;
ShowIcon = true;
Icon = icon;
}
/// <summary>
/// Initializes a new instance of the <see cref="InputBox"/> class.
/// </summary>
/// <param name="owner">Specifies the Form to set as the owner of this dialog.</param>
/// <param name="text">Sets the text of the message to show.</param>
public InputBox(Form owner, string text)
: this()
{
Owner = owner;
_lblMessageText.Text = text;
}
/// <summary>
/// Initializes a new instance of the <see cref="InputBox"/> class.
/// </summary>
/// <param name="owner">Specifies the Form to set as the owner of this dialog.</param>
/// <param name="text">The string message to show.</param>
/// <param name="caption">The string caption to allow.</param>
public InputBox(Form owner, string text, string caption)
: this()
{
Owner = owner;
_lblMessageText.Text = text;
Text = caption;
}
/// <summary>
/// Initializes a new instance of the <see cref="InputBox"/> class.
/// </summary>
/// <param name="owner">Specifies the Form to set as the owner of this dialog.</param>
/// <param name="text">The string message to show.</param>
/// <param name="caption">The string caption to allow.</param>
/// <param name="validation">A DotSpatial.Data.ValidationType enumeration specifying acceptable validation to return OK.</param>
public InputBox(Form owner, string text, string caption, ValidationType validation)
: this()
{
Owner = owner;
_lblMessageText.Text = text;
Text = caption;
Validation = validation;
}
/// <summary>
/// Initializes a new instance of the <see cref="InputBox"/> class.
/// </summary>
/// <param name="owner">Specifies the Form to set as the owner of this dialog.</param>
/// <param name="text">The string message to show.</param>
/// <param name="caption">The string caption to allow.</param>
/// <param name="validation">A DotSpatial.Data.ValidationType enumeration specifying acceptable validation to return OK.</param>
/// <param name="icon">Specifies an icon to appear on this messagebox.</param>
public InputBox(Form owner, string text, string caption, ValidationType validation, Icon icon)
: this()
{
Owner = owner;
Validation = validation;
_lblMessageText.Text = text;
Text = caption;
ShowIcon = true;
Icon = icon;
}
#endregion
#region Properties
/// <summary>
/// Gets the string result that was entered for this text box.
/// </summary>
public string Result => _txtInput.Text;
/// <summary>
/// Gets or sets the type of validation to force on the value before the OK option is permitted.
/// </summary>
public ValidationType Validation { get; set; }
#endregion
#region Methods
/// <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?.Dispose();
}
base.Dispose(disposing);
}
private void CmdCancelClick(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
private void CmdOkClick(object sender, EventArgs e)
{
// Parse the value entered in the text box. If the value doesn't match the criteria, don't
// allow the user to exit the dialog by pressing ok.
switch (Validation)
{
case ValidationType.Byte:
if (Global.IsByte(_txtInput.Text) == false)
{
LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "byte"));
return;
}
break;
case ValidationType.Double:
if (Global.IsDouble(_txtInput.Text) == false)
{
LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "double"));
return;
}
break;
case ValidationType.Float:
if (Global.IsFloat(_txtInput.Text) == false)
{
LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "float"));
return;
}
break;
case ValidationType.Integer:
if (Global.IsInteger(_txtInput.Text) == false)
{
LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "integer"));
return;
}
break;
case ValidationType.PositiveDouble:
if (Global.IsDouble(_txtInput.Text) == false)
{
LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "double"));
return;
}
if (Global.GetDouble(_txtInput.Text) < 0)
{
LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "positive double"));
return;
}
break;
case ValidationType.PositiveFloat:
if (Global.IsFloat(_txtInput.Text) == false)
{
LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "float"));
return;
}
if (Global.GetFloat(_txtInput.Text) < 0)
{
LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "positive float"));
return;
}
break;
case ValidationType.PositiveInteger:
if (Global.IsInteger(_txtInput.Text) == false)
{
LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "integer"));
return;
}
if (Global.GetInteger(_txtInput.Text) < 0)
{
LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "positive integer"));
return;
}
break;
case ValidationType.PositiveShort:
if (Global.IsShort(_txtInput.Text) == false)
{
LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "short"));
return;
}
if (Global.GetShort(_txtInput.Text) < 0)
{
LogManager.DefaultLogManager.LogMessageBox(DataFormsMessageStrings.ParseFailed_S.Replace("%S", "positive short"));
return;
}
break;
}
DialogResult = DialogResult.OK;
Close();
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
ComponentResourceManager resources = new ComponentResourceManager(typeof(InputBox));
_lblMessageText = new Label();
_txtInput = new TextBox();
_cmdOk = new Button();
_cmdCancel = new Button();
SuspendLayout();
// lblMessageText
resources.ApplyResources(_lblMessageText, "_lblMessageText");
_lblMessageText.Name = "_lblMessageText";
// txtInput
resources.ApplyResources(_txtInput, "_txtInput");
_txtInput.Name = "_txtInput";
// cmdOk
resources.ApplyResources(_cmdOk, "_cmdOk");
_cmdOk.BackColor = Color.Transparent;
_cmdOk.DialogResult = DialogResult.OK;
_cmdOk.Name = "_cmdOk";
_cmdOk.UseVisualStyleBackColor = false;
_cmdOk.Click += CmdOkClick;
// cmdCancel
resources.ApplyResources(_cmdCancel, "_cmdCancel");
_cmdCancel.BackColor = Color.Transparent;
_cmdCancel.DialogResult = DialogResult.Cancel;
_cmdCancel.Name = "_cmdCancel";
_cmdCancel.UseVisualStyleBackColor = false;
_cmdCancel.Click += CmdCancelClick;
// InputBox
AcceptButton = _cmdOk;
CancelButton = _cmdCancel;
resources.ApplyResources(this, "$this");
Controls.Add(_cmdCancel);
Controls.Add(_cmdOk);
Controls.Add(_txtInput);
Controls.Add(_lblMessageText);
MaximizeBox = false;
MinimizeBox = false;
Name = "InputBox";
ShowIcon = false;
ResumeLayout(false);
PerformLayout();
}
#endregion
}
}
| |
#region License
/*
The MIT License
Copyright (c) 2008 Sky Morey
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
// https://github.com/enyim/EnyimMemcached/wiki/MemcachedClient-Usage
using Enyim.Caching.Configuration;
using Enyim.Caching.Memcached;
using System;
using System.Abstract;
using System.Collections.Generic;
namespace Enyim.Caching.Abstract
{
/// <summary>
/// IMemcachedServiceCache
/// </summary>
public interface IMemcachedServiceCache : IDistributedServiceCache
{
/// <summary>
/// Gets the cache.
/// </summary>
IMemcachedClient Cache { get; }
/// <summary>
/// Flushes all.
/// </summary>
void FlushAll();
/// <summary>
/// Gets the with cas.
/// </summary>
/// <param name="keys">The keys.</param>
/// <returns></returns>
IDictionary<string, CasResult<object>> GetWithCas(IEnumerable<string> keys);
/// <summary>
/// Gets the with cas.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
CasResult<object> GetWithCas(string key);
/// <summary>
/// Gets the with cas.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key">The key.</param>
/// <returns></returns>
CasResult<T> GetWithCas<T>(string key);
/// <summary>
/// Tries the get with cas.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
bool TryGetWithCas(string key, out CasResult<object> value);
}
/// <summary>
/// MemcachedServiceCache
/// </summary>
public partial class MemcachedServiceCache : IMemcachedServiceCache, IDisposable, ServiceCacheManager.ISetupRegistration
{
readonly ITagMapper _tagMapper;
#region Tags
/// <summary>
/// IncrementTag
/// </summary>
public struct IncrementTag
{
/// <summary>
/// DefaultValue
/// </summary>
public ulong DefaultValue;
/// <summary>
/// Delta
/// </summary>
public ulong Delta;
}
/// <summary>
/// DecrementTag
/// </summary>
public struct DecrementTag
{
/// <summary>
/// DefaultValue
/// </summary>
public ulong DefaultValue;
/// <summary>
/// Delta
/// </summary>
public ulong Delta;
}
#endregion
static MemcachedServiceCache() { ServiceCacheManager.EnsureRegistration(); }
/// <summary>
/// Initializes a new instance of the <see cref="MemcachedServiceCache" /> class.
/// </summary>
public MemcachedServiceCache()
: this(new MemcachedClient(), new TagMapper()) { }
/// <summary>
/// Initializes a new instance of the <see cref="MemcachedServiceCache" /> class.
/// </summary>
/// <param name="cache">The client.</param>
/// <param name="tagMapper">The tag mapper.</param>
/// <exception cref="System.ArgumentNullException">cache</exception>
/// <exception cref="System.ArgumentOutOfRangeException">cache;Must be of type IMemcachedClient or IMemcachedClientConfiguration.</exception>
public MemcachedServiceCache(object cache, ITagMapper tagMapper = null)
{
if (cache == null)
throw new ArgumentNullException("cache");
if (cache is IMemcachedClient)
Cache = (IMemcachedClient)cache;
else if (cache is IMemcachedClientConfiguration)
Cache = new MemcachedClient((IMemcachedClientConfiguration)cache);
else
throw new ArgumentOutOfRangeException("cache", "Must be of type IMemcachedClient or IMemcachedClientConfiguration.");
_tagMapper = tagMapper ?? new TagMapper();
Settings = new ServiceCacheSettings();
}
/// <summary>
/// Releases unmanaged resources and performs other cleanup operations before the
/// <see cref="MemcachedServiceCache" /> is reclaimed by garbage collection.
/// </summary>
~MemcachedServiceCache()
{
try { ((IDisposable)this).Dispose(); }
catch { }
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
if (Cache != null)
{
GC.SuppressFinalize(this);
try { Cache.Dispose(); }
finally { Cache = null; }
}
}
private static ArraySegment<T> OpValueToArraySegment<T>(object opvalue) { return (opvalue is ArraySegment<T> ? (ArraySegment<T>)opvalue : new ArraySegment<T>()); }
private static DecrementTag OpValueToDecrementTag(object opvalue)
{
if (opvalue is DecrementTag) return (DecrementTag)opvalue;
if (opvalue is ulong) return new DecrementTag { Delta = (ulong)opvalue, DefaultValue = 0 };
if (opvalue is long) return new DecrementTag { Delta = (ulong)opvalue, DefaultValue = 0 };
if (opvalue is int) return new DecrementTag { Delta = (ulong)opvalue, DefaultValue = 0 };
throw new ArgumentOutOfRangeException("opvalue");
}
private static IncrementTag OpValueToIncrementTag(object opvalue)
{
if (opvalue is IncrementTag) return (IncrementTag)opvalue;
if (opvalue is ulong) return new IncrementTag { Delta = (ulong)opvalue, DefaultValue = 0 };
if (opvalue is long) return new IncrementTag { Delta = (ulong)opvalue, DefaultValue = 0 };
if (opvalue is int) return new IncrementTag { Delta = (ulong)opvalue, DefaultValue = 0 };
throw new ArgumentOutOfRangeException("opvalue");
}
Action<IServiceLocator, string> ServiceCacheManager.ISetupRegistration.DefaultServiceRegistrar
{
get { return (locator, name) => ServiceCacheManager.RegisterInstance<IMemcachedServiceCache>(this, locator, name); }
}
/// <summary>
/// Gets the service object of the specified type.
/// </summary>
/// <param name="serviceType">An object that specifies the type of service object to get.</param>
/// <returns>
/// A service object of type <paramref name="serviceType"/>.
/// -or-
/// null if there is no service object of type <paramref name="serviceType"/>.
/// </returns>
public object GetService(Type serviceType) { throw new NotImplementedException(); }
/// <summary>
/// Gets or sets the <see cref="System.Object"/> with the specified name.
/// </summary>
public object this[string name]
{
get { return Get(null, name); }
set { Set(null, name, CacheItemPolicy.Default, value, ServiceCacheByDispatcher.Empty); }
}
/// <summary>
/// Adds the specified tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <param name="itemPolicy">The item policy.</param>
/// <param name="value">The value.</param>
/// <param name="dispatch">The dispatch.</param>
/// <returns></returns>
public object Add(object tag, string name, CacheItemPolicy itemPolicy, object value, ServiceCacheByDispatcher dispatch)
{
if (itemPolicy == null)
throw new ArgumentNullException("itemPolicy");
var updateCallback = itemPolicy.UpdateCallback;
if (updateCallback != null)
updateCallback(name, value);
//
var absoluteExpiration = itemPolicy.AbsoluteExpiration;
var slidingExpiration = itemPolicy.SlidingExpiration;
ulong cas;
object opvalue;
if (absoluteExpiration == DateTime.MaxValue && slidingExpiration == TimeSpan.Zero)
switch (_tagMapper.ToAddOpcode(tag, ref name, out cas, out opvalue))
{
case TagMapper.AddOpcode.Append: value = Cache.Append(name, OpValueToArraySegment<byte>(opvalue)); break;
case TagMapper.AddOpcode.AppendCas: value = Cache.Append(name, cas, OpValueToArraySegment<byte>(opvalue)); break;
case TagMapper.AddOpcode.Store: value = Cache.Store(StoreMode.Add, name, value); break;
case TagMapper.AddOpcode.Cas: value = Cache.Cas(StoreMode.Add, name, value, cas); break;
default: throw new InvalidOperationException();
}
else if (absoluteExpiration != DateTime.MinValue && slidingExpiration == TimeSpan.Zero)
switch (_tagMapper.ToAddOpcode(tag, ref name, out cas, out opvalue))
{
case TagMapper.AddOpcode.Append:
case TagMapper.AddOpcode.AppendCas: throw new NotSupportedException("Operation not supported with absoluteExpiration && slidingExpiration");
case TagMapper.AddOpcode.Store: value = Cache.Store(StoreMode.Add, name, value, absoluteExpiration); break;
case TagMapper.AddOpcode.Cas: value = Cache.Cas(StoreMode.Add, name, value, absoluteExpiration, cas); break;
default: throw new InvalidOperationException();
}
else if (absoluteExpiration == DateTime.MinValue && slidingExpiration != TimeSpan.Zero)
switch (_tagMapper.ToAddOpcode(tag, ref name, out cas, out opvalue))
{
case TagMapper.AddOpcode.Append:
case TagMapper.AddOpcode.AppendCas: throw new NotSupportedException("Operation not supported with absoluteExpiration && slidingExpiration");
case TagMapper.AddOpcode.Store: value = Cache.Store(StoreMode.Add, name, value, slidingExpiration); break;
case TagMapper.AddOpcode.Cas: value = Cache.Cas(StoreMode.Add, name, value, slidingExpiration, cas); break;
default: throw new InvalidOperationException();
}
else throw new InvalidOperationException("absoluteExpiration && slidingExpiration");
//
var registration = dispatch.Registration;
if (registration != null && registration.UseHeaders)
{
var header = dispatch.Header;
header.Item = name;
Add(tag, name + "#", CacheItemPolicy.Default, header, ServiceCacheByDispatcher.Empty);
}
return value;
}
/// <summary>
/// Gets the item from cache associated with the key provided.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <returns>
/// The cached item.
/// </returns>
public object Get(object tag, string name) { return Cache.Get(name); }
/// <summary>
/// Gets the specified tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <param name="registration">The registration.</param>
/// <param name="header">The header.</param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException"></exception>
public object Get(object tag, string name, IServiceCacheRegistration registration, out CacheItemHeader header)
{
if (registration == null)
throw new ArgumentNullException("registration");
header = (registration.UseHeaders ? (CacheItemHeader)Cache.Get(name + "#") : null);
return Cache.Get(name);
}
/// <summary>
/// Gets the specified tag.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="names">The names.</param>
/// <returns></returns>
public object Get(object tag, IEnumerable<string> names)
{
object opvalue;
switch (_tagMapper.ToGetOpcode(tag, out opvalue))
{
case TagMapper.GetOpcode.Get: return Cache.Get(names);
//case TagMapper.GetManyOpcode.PerformMultiGet:
// {
// var cache2 = (MemcachedClient)Cache;
// if (cache2 == null)
// throw new InvalidOperationException("Must be a MemcachedClient for PerformMultiGet");
// return cache2.PerformMultiGet<object>(names, (Func<IMultiGetOperation, KeyValuePair<string, CacheItem>, object>)opvalue);
// }
default: throw new InvalidOperationException();
}
}
/// <summary>
/// Gets the specified registration.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="registration">The registration.</param>
/// <returns></returns>
/// <exception cref="System.ArgumentNullException"></exception>
/// <exception cref="System.NotImplementedException"></exception>
public IEnumerable<CacheItemHeader> Get(object tag, IServiceCacheRegistration registration)
{
if (registration == null)
throw new ArgumentNullException("registration");
throw new NotImplementedException();
}
/// <summary>
/// Tries the get.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public bool TryGet(object tag, string name, out object value) { return Cache.TryGet(name, out value); }
/// <summary>
/// Removes from cache the item associated with the key provided.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <param name="registration">The registration.</param>
/// <returns>
/// The item removed from the Cache. If the value in the key parameter is not found, returns null.
/// </returns>
public object Remove(object tag, string name, IServiceCacheRegistration registration) { if (registration != null && registration.UseHeaders) Cache.Remove(name + "#"); return Cache.Remove(name); }
/// <summary>
/// Adds an object into cache based on the parameters provided.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="name">The name.</param>
/// <param name="itemPolicy">The itemPolicy object.</param>
/// <param name="value">The value to store in cache.</param>
/// <param name="dispatch">The dispatch.</param>
/// <returns></returns>
public object Set(object tag, string name, CacheItemPolicy itemPolicy, object value, ServiceCacheByDispatcher dispatch)
{
if (itemPolicy == null)
throw new ArgumentNullException("itemPolicy");
var updateCallback = itemPolicy.UpdateCallback;
if (updateCallback != null)
updateCallback(name, value);
//
var absoluteExpiration = itemPolicy.AbsoluteExpiration;
var slidingExpiration = itemPolicy.SlidingExpiration;
ulong cas;
object opvalue;
StoreMode storeMode;
IncrementTag increment;
DecrementTag decrement;
if (absoluteExpiration == DateTime.MaxValue && slidingExpiration == TimeSpan.Zero)
switch (_tagMapper.ToSetOpcode(tag, ref name, out cas, out opvalue, out storeMode))
{
case TagMapper.SetOpcode.Prepend: value = Cache.Prepend(name, OpValueToArraySegment<byte>(opvalue)); break;
case TagMapper.SetOpcode.PrependCas: value = Cache.Prepend(name, cas, OpValueToArraySegment<byte>(opvalue)); break;
//
case TagMapper.SetOpcode.Store: value = Cache.Store(storeMode, name, value); break;
case TagMapper.SetOpcode.Cas: value = Cache.Cas(storeMode, name, value, cas); break;
case TagMapper.SetOpcode.Decrement: decrement = OpValueToDecrementTag(opvalue); value = Cache.Decrement(name, decrement.DefaultValue, decrement.Delta); break;
case TagMapper.SetOpcode.DecrementCas: decrement = OpValueToDecrementTag(opvalue); value = Cache.Decrement(name, decrement.DefaultValue, decrement.Delta, cas); break;
case TagMapper.SetOpcode.Increment: increment = OpValueToIncrementTag(opvalue); value = Cache.Increment(name, increment.DefaultValue, increment.Delta); break;
case TagMapper.SetOpcode.IncrementCas: increment = OpValueToIncrementTag(opvalue); value = Cache.Increment(name, increment.DefaultValue, increment.Delta, cas); break;
default: throw new InvalidOperationException();
}
else if (absoluteExpiration != DateTime.MinValue && slidingExpiration == TimeSpan.Zero)
switch (_tagMapper.ToSetOpcode(tag, ref name, out cas, out opvalue, out storeMode))
{
case TagMapper.SetOpcode.Prepend:
case TagMapper.SetOpcode.PrependCas: throw new NotSupportedException("Operation not supported with absoluteExpiration && slidingExpiration");
case TagMapper.SetOpcode.Store: value = Cache.Store(storeMode, name, value, absoluteExpiration); break;
case TagMapper.SetOpcode.Cas: value = Cache.Cas(storeMode, name, value, absoluteExpiration, cas); break;
case TagMapper.SetOpcode.Decrement: decrement = OpValueToDecrementTag(opvalue); value = Cache.Decrement(name, decrement.DefaultValue, decrement.Delta, absoluteExpiration); break;
case TagMapper.SetOpcode.DecrementCas: decrement = OpValueToDecrementTag(opvalue); value = Cache.Decrement(name, decrement.DefaultValue, decrement.Delta, absoluteExpiration, cas); break;
case TagMapper.SetOpcode.Increment: increment = OpValueToIncrementTag(opvalue); value = Cache.Increment(name, increment.DefaultValue, increment.Delta, absoluteExpiration); break;
case TagMapper.SetOpcode.IncrementCas: increment = OpValueToIncrementTag(opvalue); value = Cache.Increment(name, increment.DefaultValue, increment.Delta, absoluteExpiration, cas); break;
default: throw new InvalidOperationException();
}
else if (absoluteExpiration == DateTime.MinValue && slidingExpiration != TimeSpan.Zero)
switch (_tagMapper.ToSetOpcode(tag, ref name, out cas, out opvalue, out storeMode))
{
case TagMapper.SetOpcode.Prepend:
case TagMapper.SetOpcode.PrependCas: throw new NotSupportedException("Operation not supported with absoluteExpiration && slidingExpiration");
case TagMapper.SetOpcode.Store: value = Cache.Store(storeMode, name, value, slidingExpiration); break;
case TagMapper.SetOpcode.Cas: value = Cache.Cas(storeMode, name, value, slidingExpiration, cas); break;
case TagMapper.SetOpcode.Decrement: decrement = OpValueToDecrementTag(opvalue); value = Cache.Decrement(name, decrement.DefaultValue, decrement.Delta, slidingExpiration); break;
case TagMapper.SetOpcode.DecrementCas: decrement = OpValueToDecrementTag(opvalue); value = Cache.Decrement(name, decrement.DefaultValue, decrement.Delta, slidingExpiration, cas); break;
case TagMapper.SetOpcode.Increment: increment = OpValueToIncrementTag(opvalue); value = Cache.Increment(name, increment.DefaultValue, increment.Delta, slidingExpiration); break;
case TagMapper.SetOpcode.IncrementCas: increment = OpValueToIncrementTag(opvalue); value = Cache.Increment(name, increment.DefaultValue, increment.Delta, slidingExpiration, cas); break;
default: throw new InvalidOperationException();
}
else throw new InvalidOperationException("absoluteExpiration && slidingExpiration");
//
var registration = dispatch.Registration;
if (registration != null && registration.UseHeaders)
{
var header = dispatch.Header;
header.Item = name;
Add(tag, name + "#", CacheItemPolicy.Default, header, ServiceCacheByDispatcher.Empty);
}
return value;
}
/// <summary>
/// Settings
/// </summary>
public ServiceCacheSettings Settings { get; private set; }
#region TouchableCacheItem
///// <summary>
///// DefaultTouchableCacheItem
///// </summary>
//public class DefaultTouchableCacheItem : ITouchableCacheItem
//{
// private MemcachedServiceCache _parent;
// private ITouchableCacheItem _base;
// public DefaultTouchableCacheItem(MemcachedServiceCache parent, ITouchableCacheItem @base) { _parent = parent; _base = @base; }
// public void Touch(object tag, string[] names)
// {
// if (names == null || names.Length == 0)
// return;
// throw new NotSupportedException();
// }
// public object MakeDependency(object tag, string[] names)
// {
// if (names == null || names.Length == 0)
// return null;
// throw new NotSupportedException();
// }
//}
#endregion
#region Domain-specific
/// <summary>
/// Gets the cache.
/// </summary>
public IMemcachedClient Cache { get; private set; }
/// <summary>
/// Flushes all.
/// </summary>
public void FlushAll() { Cache.FlushAll(); }
/// <summary>
/// Gets the with cas.
/// </summary>
/// <param name="keys">The keys.</param>
/// <returns></returns>
public IDictionary<string, CasResult<object>> GetWithCas(IEnumerable<string> keys) { return Cache.GetWithCas(keys); }
/// <summary>
/// Gets the with cas.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
public CasResult<object> GetWithCas(string key) { return Cache.GetWithCas(key); }
/// <summary>
/// Gets the with cas.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key">The key.</param>
/// <returns></returns>
public CasResult<T> GetWithCas<T>(string key) { return Cache.GetWithCas<T>(key); }
/// <summary>
/// Tries the get with cas.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public bool TryGetWithCas(string key, out CasResult<object> value) { return Cache.TryGetWithCas(key, out value); }
#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.Net;
using System.ComponentModel;
using System.Collections;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Diagnostics;
namespace System.DirectoryServices.ActiveDirectory
{
[Flags]
public enum SyncFromAllServersOptions
{
None = 0,
AbortIfServerUnavailable = 1,
SyncAdjacentServerOnly = 2,
CheckServerAlivenessOnly = 0x8,
SkipInitialCheck = 0x10,
PushChangeOutward = 0x20,
CrossSite = 0x40
}
public enum SyncFromAllServersEvent
{
Error = 0,
SyncStarted = 1,
SyncCompleted = 2,
Finished = 3
}
public enum SyncFromAllServersErrorCategory
{
ErrorContactingServer = 0,
ErrorReplicating = 1,
ServerUnreachable = 2
}
public delegate bool SyncUpdateCallback(SyncFromAllServersEvent eventType, string targetServer, string sourceServer, SyncFromAllServersOperationException exception);
internal delegate bool SyncReplicaFromAllServersCallback(IntPtr data, IntPtr update);
public class DomainController : DirectoryServer
{
private IntPtr _dsHandle = IntPtr.Zero;
private IntPtr _authIdentity = IntPtr.Zero;
private readonly string[] _becomeRoleOwnerAttrs = null;
private bool _disposed = false;
// internal variables for the public properties
private string _cachedComputerObjectName = null;
private string _cachedOSVersion = null;
private double _cachedNumericOSVersion = 0;
private Forest _currentForest = null;
private Domain _cachedDomain = null;
private ActiveDirectoryRoleCollection _cachedRoles = null;
private bool _dcInfoInitialized = false;
internal SyncUpdateCallback userDelegate = null;
internal readonly SyncReplicaFromAllServersCallback syncAllFunctionPointer = null;
// this is twice the maximum allowed RIDPool size which is 15k
internal const int UpdateRidPoolSeizureValue = 30000;
#region constructors
// Internal constructors
protected DomainController()
{
}
internal DomainController(DirectoryContext context, string domainControllerName)
: this(context, domainControllerName, new DirectoryEntryManager(context))
{
}
internal DomainController(DirectoryContext context, string domainControllerName, DirectoryEntryManager directoryEntryMgr)
{
this.context = context;
this.replicaName = domainControllerName;
this.directoryEntryMgr = directoryEntryMgr;
// initialize the transfer role owner attributes
_becomeRoleOwnerAttrs = new string[5];
_becomeRoleOwnerAttrs[0] = PropertyManager.BecomeSchemaMaster;
_becomeRoleOwnerAttrs[1] = PropertyManager.BecomeDomainMaster;
_becomeRoleOwnerAttrs[2] = PropertyManager.BecomePdc;
_becomeRoleOwnerAttrs[3] = PropertyManager.BecomeRidMaster;
_becomeRoleOwnerAttrs[4] = PropertyManager.BecomeInfrastructureMaster;
// initialize the callback function
syncAllFunctionPointer = new SyncReplicaFromAllServersCallback(SyncAllCallbackRoutine);
}
#endregion constructors
#region IDisposable
~DomainController() => Dispose(false);
// private Dispose method
protected override void Dispose(bool disposing)
{
if (!_disposed)
{
try
{
// if there are any managed or unmanaged
// resources to be freed, those should be done here
// if disposing = true, only unmanaged resources should
// be freed, else both managed and unmanaged.
FreeDSHandle();
_disposed = true;
}
finally
{
base.Dispose();
}
}
}
#endregion IDisposable
#region public methods
public static DomainController GetDomainController(DirectoryContext context)
{
string dcDnsName = null;
DirectoryEntryManager directoryEntryMgr = null;
// check that the context argument is not null
if (context == null)
throw new ArgumentNullException(nameof(context));
// target should be DC
if (context.ContextType != DirectoryContextType.DirectoryServer)
{
throw new ArgumentException(SR.TargetShouldBeDC, nameof(context));
}
// target should be a server
if (!(context.isServer()))
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFound, context.Name), typeof(DomainController), context.Name);
}
// work with copy of the context
context = new DirectoryContext(context);
try
{
// Get dns name of the dc
// by binding to root dse and getting the "dnsHostName" attribute
directoryEntryMgr = new DirectoryEntryManager(context);
DirectoryEntry rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
if (!Utils.CheckCapability(rootDSE, Capability.ActiveDirectory))
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFound, context.Name), typeof(DomainController), context.Name);
}
dcDnsName = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.DnsHostName);
}
catch (COMException e)
{
int errorCode = e.ErrorCode;
if (errorCode == unchecked((int)0x8007203a))
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFound, context.Name), typeof(DomainController), context.Name);
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
return new DomainController(context, dcDnsName, directoryEntryMgr);
}
public static DomainController FindOne(DirectoryContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.ContextType != DirectoryContextType.Domain)
{
throw new ArgumentException(SR.TargetShouldBeDomain, nameof(context));
}
return FindOneWithCredentialValidation(context, null, 0);
}
public static DomainController FindOne(DirectoryContext context, string siteName)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.ContextType != DirectoryContextType.Domain)
{
throw new ArgumentException(SR.TargetShouldBeDomain, nameof(context));
}
if (siteName == null)
{
throw new ArgumentNullException(nameof(siteName));
}
return FindOneWithCredentialValidation(context, siteName, 0);
}
public static DomainController FindOne(DirectoryContext context, LocatorOptions flag)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.ContextType != DirectoryContextType.Domain)
{
throw new ArgumentException(SR.TargetShouldBeDomain, nameof(context));
}
return FindOneWithCredentialValidation(context, null, flag);
}
public static DomainController FindOne(DirectoryContext context, string siteName, LocatorOptions flag)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.ContextType != DirectoryContextType.Domain)
{
throw new ArgumentException(SR.TargetShouldBeDomain, nameof(context));
}
if (siteName == null)
{
throw new ArgumentNullException(nameof(siteName));
}
return FindOneWithCredentialValidation(context, siteName, flag);
}
public static DomainControllerCollection FindAll(DirectoryContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.ContextType != DirectoryContextType.Domain)
{
throw new ArgumentException(SR.TargetShouldBeDomain, nameof(context));
}
// work with copy of the context
context = new DirectoryContext(context);
return FindAllInternal(context, context.Name, false /* isDnsDomainName */, null);
}
public static DomainControllerCollection FindAll(DirectoryContext context, string siteName)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.ContextType != DirectoryContextType.Domain)
{
throw new ArgumentException(SR.TargetShouldBeDomain, nameof(context));
}
if (siteName == null)
{
throw new ArgumentNullException(nameof(siteName));
}
// work with copy of the context
context = new DirectoryContext(context);
return FindAllInternal(context, context.Name, false /* isDnsDomainName */, siteName);
}
public virtual GlobalCatalog EnableGlobalCatalog()
{
CheckIfDisposed();
try
{
// bind to the server object
DirectoryEntry serverNtdsaEntry = directoryEntryMgr.GetCachedDirectoryEntry(NtdsaObjectName);
// set the NTDSDSA_OPT_IS_GC flag on the "options" property
int options = 0;
if (serverNtdsaEntry.Properties[PropertyManager.Options].Value != null)
{
options = (int)serverNtdsaEntry.Properties[PropertyManager.Options].Value;
}
serverNtdsaEntry.Properties[PropertyManager.Options].Value = options | 1;
serverNtdsaEntry.CommitChanges();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
// return a GlobalCatalog object
return new GlobalCatalog(context, Name);
}
public virtual bool IsGlobalCatalog()
{
CheckIfDisposed();
try
{
DirectoryEntry serverNtdsaEntry = directoryEntryMgr.GetCachedDirectoryEntry(NtdsaObjectName);
serverNtdsaEntry.RefreshCache();
// check if the NTDSDSA_OPT_IS_GC flag is set in the
// "options" attribute (lowest bit)
int options = 0;
if (serverNtdsaEntry.Properties[PropertyManager.Options].Value != null)
{
options = (int)serverNtdsaEntry.Properties[PropertyManager.Options].Value;
}
if ((options & (1)) == 1)
{
return true;
}
else
{
return false;
}
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
public void TransferRoleOwnership(ActiveDirectoryRole role)
{
CheckIfDisposed();
if (role < ActiveDirectoryRole.SchemaRole || role > ActiveDirectoryRole.InfrastructureRole)
{
throw new InvalidEnumArgumentException(nameof(role), (int)role, typeof(ActiveDirectoryRole));
}
try
{
// set the appropriate attribute on the rootDSE
DirectoryEntry rootDSE = directoryEntryMgr.GetCachedDirectoryEntry(WellKnownDN.RootDSE);
rootDSE.Properties[_becomeRoleOwnerAttrs[(int)role]].Value = 1;
rootDSE.CommitChanges();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e); ;
}
// invalidate the role collection so that it gets loaded again next time
_cachedRoles = null;
}
public void SeizeRoleOwnership(ActiveDirectoryRole role)
{
// set the "fsmoRoleOwner" attribute on the appropriate role object
// to the NTDSAObjectName of this DC
string roleObjectDN = null;
CheckIfDisposed();
switch (role)
{
case ActiveDirectoryRole.SchemaRole:
{
roleObjectDN = directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.SchemaNamingContext);
break;
}
case ActiveDirectoryRole.NamingRole:
{
roleObjectDN = directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.PartitionsContainer);
break;
}
case ActiveDirectoryRole.PdcRole:
{
roleObjectDN = directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.DefaultNamingContext);
break;
}
case ActiveDirectoryRole.RidRole:
{
roleObjectDN = directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.RidManager);
break;
}
case ActiveDirectoryRole.InfrastructureRole:
{
roleObjectDN = directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.Infrastructure);
break;
}
default:
throw new InvalidEnumArgumentException(nameof(role), (int)role, typeof(ActiveDirectoryRole));
}
DirectoryEntry roleObjectEntry = null;
try
{
roleObjectEntry = DirectoryEntryManager.GetDirectoryEntry(context, roleObjectDN);
// For RID FSMO role
// Increment the RIDAvailablePool by 30k.
if (role == ActiveDirectoryRole.RidRole)
{
System.DirectoryServices.Interop.UnsafeNativeMethods.IADsLargeInteger ridPool = (System.DirectoryServices.Interop.UnsafeNativeMethods.IADsLargeInteger)roleObjectEntry.Properties[PropertyManager.RIDAvailablePool].Value;
// check the overflow of the low part
if (ridPool.LowPart + UpdateRidPoolSeizureValue < ridPool.LowPart)
{
throw new InvalidOperationException(SR.UpdateAvailableRIDPoolOverflowFailure);
}
ridPool.LowPart += UpdateRidPoolSeizureValue;
roleObjectEntry.Properties[PropertyManager.RIDAvailablePool].Value = ridPool;
}
roleObjectEntry.Properties[PropertyManager.FsmoRoleOwner].Value = NtdsaObjectName;
roleObjectEntry.CommitChanges();
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
finally
{
if (roleObjectEntry != null)
{
roleObjectEntry.Dispose();
}
}
// invalidate the role collection so that it gets loaded again next time
_cachedRoles = null;
}
public virtual DirectorySearcher GetDirectorySearcher()
{
CheckIfDisposed();
return InternalGetDirectorySearcher();
}
public override void CheckReplicationConsistency()
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
// get the handle
GetDSHandle();
// call private helper function
CheckConsistencyHelper(_dsHandle, DirectoryContext.ADHandle);
}
public override ReplicationCursorCollection GetReplicationCursors(string partition)
{
IntPtr info = (IntPtr)0;
int context = 0;
bool advanced = true;
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (partition == null)
throw new ArgumentNullException(nameof(partition));
if (partition.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(partition));
// get the handle
GetDSHandle();
info = GetReplicationInfoHelper(_dsHandle, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_CURSORS_3_FOR_NC, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_CURSORS_FOR_NC, partition, ref advanced, context, DirectoryContext.ADHandle);
return ConstructReplicationCursors(_dsHandle, advanced, info, partition, this, DirectoryContext.ADHandle);
}
public override ReplicationOperationInformation GetReplicationOperationInformation()
{
IntPtr info = (IntPtr)0;
bool advanced = true;
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
// get the handle
GetDSHandle();
info = GetReplicationInfoHelper(_dsHandle, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_PENDING_OPS, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_PENDING_OPS, null, ref advanced, 0, DirectoryContext.ADHandle);
return ConstructPendingOperations(info, this, DirectoryContext.ADHandle);
}
public override ReplicationNeighborCollection GetReplicationNeighbors(string partition)
{
IntPtr info = (IntPtr)0;
bool advanced = true;
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (partition == null)
throw new ArgumentNullException(nameof(partition));
if (partition.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(partition));
// get the handle
GetDSHandle();
info = GetReplicationInfoHelper(_dsHandle, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_NEIGHBORS, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_NEIGHBORS, partition, ref advanced, 0, DirectoryContext.ADHandle);
return ConstructNeighbors(info, this, DirectoryContext.ADHandle);
}
public override ReplicationNeighborCollection GetAllReplicationNeighbors()
{
IntPtr info = (IntPtr)0;
bool advanced = true;
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
// get the handle
GetDSHandle();
info = GetReplicationInfoHelper(_dsHandle, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_NEIGHBORS, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_NEIGHBORS, null, ref advanced, 0, DirectoryContext.ADHandle);
return ConstructNeighbors(info, this, DirectoryContext.ADHandle);
}
public override ReplicationFailureCollection GetReplicationConnectionFailures()
{
return GetReplicationFailures(DS_REPL_INFO_TYPE.DS_REPL_INFO_KCC_DSA_CONNECT_FAILURES);
}
public override ActiveDirectoryReplicationMetadata GetReplicationMetadata(string objectPath)
{
IntPtr info = (IntPtr)0;
bool advanced = true;
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (objectPath == null)
throw new ArgumentNullException(nameof(objectPath));
if (objectPath.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(objectPath));
// get the handle
GetDSHandle();
info = GetReplicationInfoHelper(_dsHandle, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_METADATA_2_FOR_OBJ, (int)DS_REPL_INFO_TYPE.DS_REPL_INFO_METADATA_FOR_OBJ, objectPath, ref advanced, 0, DirectoryContext.ADHandle);
return ConstructMetaData(advanced, info, this, DirectoryContext.ADHandle);
}
public override void SyncReplicaFromServer(string partition, string sourceServer)
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (partition == null)
throw new ArgumentNullException(nameof(partition));
if (partition.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(partition));
if (sourceServer == null)
throw new ArgumentNullException(nameof(sourceServer));
if (sourceServer.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(sourceServer));
// get the dsHandle
GetDSHandle();
SyncReplicaHelper(_dsHandle, false, partition, sourceServer, 0, DirectoryContext.ADHandle);
}
public override void TriggerSyncReplicaFromNeighbors(string partition)
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (partition == null)
throw new ArgumentNullException(nameof(partition));
if (partition.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(partition));
// get the dsHandle
GetDSHandle();
SyncReplicaHelper(_dsHandle, false, partition, null, DS_REPSYNC_ASYNCHRONOUS_OPERATION | DS_REPSYNC_ALL_SOURCES, DirectoryContext.ADHandle);
}
public override void SyncReplicaFromAllServers(string partition, SyncFromAllServersOptions options)
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
if (partition == null)
throw new ArgumentNullException(nameof(partition));
if (partition.Length == 0)
throw new ArgumentException(SR.EmptyStringParameter, nameof(partition));
// get the dsHandle
GetDSHandle();
SyncReplicaAllHelper(_dsHandle, syncAllFunctionPointer, partition, options, SyncFromAllServersCallback, DirectoryContext.ADHandle);
}
#endregion public methods
#region public properties
public Forest Forest
{
get
{
CheckIfDisposed();
if (_currentForest == null)
{
DirectoryContext forestContext = Utils.GetNewDirectoryContext(Name, DirectoryContextType.DirectoryServer, context);
_currentForest = Forest.GetForest(forestContext);
}
return _currentForest;
}
}
public DateTime CurrentTime
{
get
{
CheckIfDisposed();
DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
string serverUTCTime = null;
try
{
serverUTCTime = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.CurrentTime);
}
finally
{
rootDSE.Dispose();
}
return ParseDateTime(serverUTCTime);
}
}
public long HighestCommittedUsn
{
get
{
CheckIfDisposed();
DirectoryEntry rootDSE = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE);
string serverHighestCommittedUsn = null;
try
{
serverHighestCommittedUsn = (string)PropertyManager.GetPropertyValue(context, rootDSE, PropertyManager.HighestCommittedUSN);
}
finally
{
rootDSE.Dispose();
}
return long.Parse(serverHighestCommittedUsn, NumberFormatInfo.InvariantInfo);
}
}
public string OSVersion
{
get
{
CheckIfDisposed();
if (_cachedOSVersion == null)
{
// get the operating system version attribute
DirectoryEntry computerEntry = directoryEntryMgr.GetCachedDirectoryEntry(ComputerObjectName);
// is in the form Windows Server 2003
_cachedOSVersion = (string)PropertyManager.GetPropertyValue(context, computerEntry, PropertyManager.OperatingSystem);
}
return _cachedOSVersion;
}
}
internal double NumericOSVersion
{
get
{
CheckIfDisposed();
if (_cachedNumericOSVersion == 0)
{
// get the operating system version attribute
DirectoryEntry computerEntry = directoryEntryMgr.GetCachedDirectoryEntry(ComputerObjectName);
// is in the form Windows Server 2003
string osVersion = (string)PropertyManager.GetPropertyValue(context, computerEntry, PropertyManager.OperatingSystemVersion);
// this could be in the form 5.2 (3790), so we need to take out the (3790)
int index = osVersion.IndexOf('(');
if (index != -1)
{
osVersion = osVersion.Substring(0, index);
}
_cachedNumericOSVersion = (double)double.Parse(osVersion, NumberFormatInfo.InvariantInfo);
}
return _cachedNumericOSVersion;
}
}
public ActiveDirectoryRoleCollection Roles
{
get
{
CheckIfDisposed();
if (_cachedRoles == null)
{
_cachedRoles = new ActiveDirectoryRoleCollection(GetRoles());
}
return _cachedRoles;
}
}
public Domain Domain
{
get
{
CheckIfDisposed();
if (_cachedDomain == null)
{
string domainName = null;
try
{
string defaultNCName = directoryEntryMgr.ExpandWellKnownDN(WellKnownDN.DefaultNamingContext);
domainName = Utils.GetDnsNameFromDN(defaultNCName);
}
catch (COMException e)
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
// For domain controllers this is always the
// domain naming context
// create a new domain context for the domain
DirectoryContext domainContext = Utils.GetNewDirectoryContext(Name, DirectoryContextType.DirectoryServer, context);
_cachedDomain = new Domain(domainContext, domainName);
}
return _cachedDomain;
}
}
public override string IPAddress
{
get
{
CheckIfDisposed();
IPHostEntry hostEntry = Dns.GetHostEntry(Name);
if (hostEntry.AddressList.GetLength(0) > 0)
{
return (hostEntry.AddressList[0]).ToString();
}
else
{
return null;
}
}
}
public override string SiteName
{
get
{
CheckIfDisposed();
if (!_dcInfoInitialized || siteInfoModified)
{
GetDomainControllerInfo();
}
if (cachedSiteName == null)
{
throw new ActiveDirectoryOperationException(SR.Format(SR.SiteNameNotFound, Name));
}
return cachedSiteName;
}
}
internal string SiteObjectName
{
get
{
CheckIfDisposed();
if (!_dcInfoInitialized || siteInfoModified)
{
GetDomainControllerInfo();
}
if (cachedSiteObjectName == null)
{
throw new ActiveDirectoryOperationException(SR.Format(SR.SiteObjectNameNotFound, Name));
}
return cachedSiteObjectName;
}
}
internal string ComputerObjectName
{
get
{
CheckIfDisposed();
if (!_dcInfoInitialized)
{
GetDomainControllerInfo();
}
if (_cachedComputerObjectName == null)
{
throw new ActiveDirectoryOperationException(SR.Format(SR.ComputerObjectNameNotFound, Name));
}
return _cachedComputerObjectName;
}
}
internal string ServerObjectName
{
get
{
CheckIfDisposed();
if (!_dcInfoInitialized || siteInfoModified)
{
GetDomainControllerInfo();
}
if (cachedServerObjectName == null)
{
throw new ActiveDirectoryOperationException(SR.Format(SR.ServerObjectNameNotFound, Name));
}
return cachedServerObjectName;
}
}
internal string NtdsaObjectName
{
get
{
CheckIfDisposed();
if (!_dcInfoInitialized || siteInfoModified)
{
GetDomainControllerInfo();
}
if (cachedNtdsaObjectName == null)
{
throw new ActiveDirectoryOperationException(SR.Format(SR.NtdsaObjectNameNotFound, Name));
}
return cachedNtdsaObjectName;
}
}
internal Guid NtdsaObjectGuid
{
get
{
CheckIfDisposed();
if (!_dcInfoInitialized || siteInfoModified)
{
GetDomainControllerInfo();
}
if (cachedNtdsaObjectGuid.Equals(Guid.Empty))
{
throw new ActiveDirectoryOperationException(SR.Format(SR.NtdsaObjectGuidNotFound, Name));
}
return cachedNtdsaObjectGuid;
}
}
public override SyncUpdateCallback SyncFromAllServersCallback
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
return userDelegate;
}
set
{
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
userDelegate = value;
}
}
public override ReplicationConnectionCollection InboundConnections => GetInboundConnectionsHelper();
public override ReplicationConnectionCollection OutboundConnections => GetOutboundConnectionsHelper();
internal IntPtr Handle
{
get
{
GetDSHandle();
return _dsHandle;
}
}
#endregion public properties
#region private methods
internal static void ValidateCredential(DomainController dc, DirectoryContext context)
{
DirectoryEntry de;
de = new DirectoryEntry("LDAP://" + dc.Name + "/RootDSE", context.UserName, context.Password, Utils.DefaultAuthType | AuthenticationTypes.ServerBind);
de.Bind(true);
}
internal static DomainController FindOneWithCredentialValidation(DirectoryContext context, string siteName, LocatorOptions flag)
{
DomainController dc;
bool retry = false;
bool credsValidated = false;
// work with copy of the context
context = new DirectoryContext(context);
// authenticate against this DC to validate the credentials
dc = FindOneInternal(context, context.Name, siteName, flag);
try
{
ValidateCredential(dc, context);
credsValidated = true;
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x8007203a))
{
// server is down , so try again with force rediscovery if the flags did not already contain force rediscovery
if ((flag & LocatorOptions.ForceRediscovery) == 0)
{
retry = true;
}
else
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFoundInDomain, context.Name), typeof(DomainController), null);
}
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
finally
{
if (!credsValidated)
{
dc.Dispose();
}
}
if (retry)
{
credsValidated = false;
dc = FindOneInternal(context, context.Name, siteName, flag | LocatorOptions.ForceRediscovery);
try
{
ValidateCredential(dc, context);
credsValidated = true;
}
catch (COMException e)
{
if (e.ErrorCode == unchecked((int)0x8007203a))
{
// server is down
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFoundInDomain, context.Name), typeof(DomainController), null);
}
else
{
throw ExceptionHelper.GetExceptionFromCOMException(context, e);
}
}
finally
{
if (!credsValidated)
{
dc.Dispose();
}
}
}
return dc;
}
internal static DomainController FindOneInternal(DirectoryContext context, string domainName, string siteName, LocatorOptions flag)
{
DomainControllerInfo domainControllerInfo;
int errorCode = 0;
if (siteName != null && siteName.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName));
}
// check that the flags passed have only the valid bits set
if (((long)flag & (~((long)LocatorOptions.AvoidSelf | (long)LocatorOptions.ForceRediscovery | (long)LocatorOptions.KdcRequired | (long)LocatorOptions.TimeServerRequired | (long)LocatorOptions.WriteableRequired))) != 0)
{
throw new ArgumentException(SR.InvalidFlags, nameof(flag));
}
if (domainName == null)
{
domainName = DirectoryContext.GetLoggedOnDomain();
}
// call DsGetDcName
errorCode = Locator.DsGetDcNameWrapper(null, domainName, siteName, (long)flag | (long)PrivateLocatorFlags.DirectoryServicesRequired, out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
throw new ActiveDirectoryObjectNotFoundException(SR.Format(SR.DCNotFoundInDomain, domainName), typeof(DomainController), null);
}
// this can only occur when flag is being explicitly passed (since the flags that we pass internally are valid)
if (errorCode == NativeMethods.ERROR_INVALID_FLAGS)
{
throw new ArgumentException(SR.InvalidFlags, nameof(flag));
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
// create a DomainController object
Debug.Assert(domainControllerInfo.DomainControllerName.Length > 2);
string domainControllerName = domainControllerInfo.DomainControllerName.Substring(2);
// create a new context object for the domain controller
DirectoryContext dcContext = Utils.GetNewDirectoryContext(domainControllerName, DirectoryContextType.DirectoryServer, context);
return new DomainController(dcContext, domainControllerName);
}
internal static DomainControllerCollection FindAllInternal(DirectoryContext context, string domainName, bool isDnsDomainName, string siteName)
{
ArrayList dcList = new ArrayList();
if (siteName != null && siteName.Length == 0)
{
throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName));
}
if (domainName == null || !isDnsDomainName)
{
// get the dns name of the domain
DomainControllerInfo domainControllerInfo;
int errorCode = Locator.DsGetDcNameWrapper(null, (domainName != null) ? domainName : DirectoryContext.GetLoggedOnDomain(), null, (long)PrivateLocatorFlags.DirectoryServicesRequired, out domainControllerInfo);
if (errorCode == NativeMethods.ERROR_NO_SUCH_DOMAIN)
{
// return an empty collection
return new DomainControllerCollection(dcList);
}
else if (errorCode != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(errorCode);
}
Debug.Assert(domainControllerInfo.DomainName != null);
domainName = domainControllerInfo.DomainName;
}
foreach (string dcName in Utils.GetReplicaList(context, Utils.GetDNFromDnsName(domainName), siteName, true /* isDefaultNC */, false /* isADAM */, false /* mustBeGC */))
{
DirectoryContext dcContext = Utils.GetNewDirectoryContext(dcName, DirectoryContextType.DirectoryServer, context);
dcList.Add(new DomainController(dcContext, dcName));
}
return new DomainControllerCollection(dcList);
}
private void GetDomainControllerInfo()
{
int result = 0;
int dcCount = 0;
IntPtr dcInfoPtr = IntPtr.Zero;
int dcInfoLevel = 0;
bool initialized = false;
// get the handle
GetDSHandle();
// call DsGetDomainControllerInfo
IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsGetDomainControllerInfoW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
}
NativeMethods.DsGetDomainControllerInfo dsGetDomainControllerInfo = (NativeMethods.DsGetDomainControllerInfo)Marshal.GetDelegateForFunctionPointer(functionPtr, typeof(NativeMethods.DsGetDomainControllerInfo));
// try DsDomainControllerInfoLevel3 first which supports Read only DC (RODC)
dcInfoLevel = NativeMethods.DsDomainControllerInfoLevel3;
result = dsGetDomainControllerInfo(_dsHandle, Domain.Name, dcInfoLevel, out dcCount, out dcInfoPtr);
if (result != 0)
{
// fallback to DsDomainControllerInfoLevel2
dcInfoLevel = NativeMethods.DsDomainControllerInfoLevel2;
result = dsGetDomainControllerInfo(_dsHandle, Domain.Name, dcInfoLevel, out dcCount, out dcInfoPtr);
}
if (result == 0)
{
try
{
IntPtr currentDc = dcInfoPtr;
for (int i = 0; i < dcCount; i++)
{
if (dcInfoLevel == NativeMethods.DsDomainControllerInfoLevel3)
{
DsDomainControllerInfo3 domainControllerInfo3 = new DsDomainControllerInfo3();
Marshal.PtrToStructure(currentDc, domainControllerInfo3);
// check if this is the same as "this" DC
if (domainControllerInfo3 != null)
{
if (Utils.Compare(domainControllerInfo3.dnsHostName, replicaName) == 0)
{
initialized = true;
// update all the fields
cachedSiteName = domainControllerInfo3.siteName;
cachedSiteObjectName = domainControllerInfo3.siteObjectName;
_cachedComputerObjectName = domainControllerInfo3.computerObjectName;
cachedServerObjectName = domainControllerInfo3.serverObjectName;
cachedNtdsaObjectName = domainControllerInfo3.ntdsaObjectName;
cachedNtdsaObjectGuid = domainControllerInfo3.ntdsDsaObjectGuid;
}
}
currentDc = IntPtr.Add(currentDc, Marshal.SizeOf(domainControllerInfo3));
}
else
{ //NativeMethods.DsDomainControllerInfoLevel2
DsDomainControllerInfo2 domainControllerInfo2 = new DsDomainControllerInfo2();
Marshal.PtrToStructure(currentDc, domainControllerInfo2);
// check if this is the same as "this" DC
if (domainControllerInfo2 != null)
{
if (Utils.Compare(domainControllerInfo2.dnsHostName, replicaName) == 0)
{
initialized = true;
// update all the fields
cachedSiteName = domainControllerInfo2.siteName;
cachedSiteObjectName = domainControllerInfo2.siteObjectName;
_cachedComputerObjectName = domainControllerInfo2.computerObjectName;
cachedServerObjectName = domainControllerInfo2.serverObjectName;
cachedNtdsaObjectName = domainControllerInfo2.ntdsaObjectName;
cachedNtdsaObjectGuid = domainControllerInfo2.ntdsDsaObjectGuid;
}
}
currentDc = IntPtr.Add(currentDc, Marshal.SizeOf(domainControllerInfo2));
}
}
}
finally
{
// free the domain controller info structure
if (dcInfoPtr != IntPtr.Zero)
{
// call DsFreeDomainControllerInfo
functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsFreeDomainControllerInfoW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
}
NativeMethods.DsFreeDomainControllerInfo dsFreeDomainControllerInfo = (NativeMethods.DsFreeDomainControllerInfo)Marshal.GetDelegateForFunctionPointer(functionPtr, typeof(NativeMethods.DsFreeDomainControllerInfo));
dsFreeDomainControllerInfo(dcInfoLevel, dcCount, dcInfoPtr);
}
}
// if we couldn't get this DC's info, throw an exception
if (!initialized)
{
throw new ActiveDirectoryOperationException(SR.DCInfoNotFound);
}
_dcInfoInitialized = true;
siteInfoModified = false;
}
else
{
throw ExceptionHelper.GetExceptionFromErrorCode(result, Name);
}
}
internal void GetDSHandle()
{
if (_disposed)
{
// cannot bind to the domain controller as the object has been
// disposed (finalizer has been suppressed)
throw new ObjectDisposedException(GetType().Name);
}
// this part of the code needs to be synchronized
lock (this)
{
if (_dsHandle == IntPtr.Zero)
{
// get the credentials object
if (_authIdentity == IntPtr.Zero)
{
_authIdentity = Utils.GetAuthIdentity(context, DirectoryContext.ADHandle);
}
// DsBind
_dsHandle = Utils.GetDSHandle(replicaName, null, _authIdentity, DirectoryContext.ADHandle);
}
}
}
internal void FreeDSHandle()
{
lock (this)
{
// DsUnbind
Utils.FreeDSHandle(_dsHandle, DirectoryContext.ADHandle);
// free the credentials object
Utils.FreeAuthIdentity(_authIdentity, DirectoryContext.ADHandle);
}
}
internal ReplicationFailureCollection GetReplicationFailures(DS_REPL_INFO_TYPE type)
{
IntPtr info = (IntPtr)0;
bool advanced = true;
if (_disposed)
throw new ObjectDisposedException(GetType().Name);
// get the handle
GetDSHandle();
info = GetReplicationInfoHelper(_dsHandle, (int)type, (int)type, null, ref advanced, 0, DirectoryContext.ADHandle);
return ConstructFailures(info, this, DirectoryContext.ADHandle);
}
private ArrayList GetRoles()
{
ArrayList roleList = new ArrayList();
int result = 0;
IntPtr rolesPtr = IntPtr.Zero;
GetDSHandle();
// Get the roles
// call DsListRoles
IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsListRolesW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
}
NativeMethods.DsListRoles dsListRoles = (NativeMethods.DsListRoles)Marshal.GetDelegateForFunctionPointer(functionPtr, typeof(NativeMethods.DsListRoles));
result = dsListRoles(_dsHandle, out rolesPtr);
if (result == 0)
{
try
{
DsNameResult dsNameResult = new DsNameResult();
Marshal.PtrToStructure(rolesPtr, dsNameResult);
IntPtr currentItem = dsNameResult.items;
for (int i = 0; i < dsNameResult.itemCount; i++)
{
DsNameResultItem dsNameResultItem = new DsNameResultItem();
Marshal.PtrToStructure(currentItem, dsNameResultItem);
// check if the role owner is this dc
if (dsNameResultItem.status == NativeMethods.DsNameNoError)
{
if (dsNameResultItem.name.Equals(NtdsaObjectName))
{
// add this role to the array
// the index of the item in the result signifies
// which role owner it is
roleList.Add((ActiveDirectoryRole)i);
}
}
currentItem = IntPtr.Add(currentItem, Marshal.SizeOf(dsNameResultItem));
}
}
finally
{
// free the DsNameResult structure
if (rolesPtr != IntPtr.Zero)
{
// call DsFreeNameResult
functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW");
if (functionPtr == (IntPtr)0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
}
UnsafeNativeMethods.DsFreeNameResultW dsFreeNameResult = (UnsafeNativeMethods.DsFreeNameResultW)Marshal.GetDelegateForFunctionPointer(functionPtr, typeof(UnsafeNativeMethods.DsFreeNameResultW));
dsFreeNameResult(rolesPtr);
}
}
}
else
{
throw ExceptionHelper.GetExceptionFromErrorCode(result, Name);
}
return roleList;
}
private DateTime ParseDateTime(string dateTime)
{
int year = (int)int.Parse(dateTime.Substring(0, 4), NumberFormatInfo.InvariantInfo);
int month = (int)int.Parse(dateTime.Substring(4, 2), NumberFormatInfo.InvariantInfo);
int day = (int)int.Parse(dateTime.Substring(6, 2), NumberFormatInfo.InvariantInfo);
int hour = (int)int.Parse(dateTime.Substring(8, 2), NumberFormatInfo.InvariantInfo);
int min = (int)int.Parse(dateTime.Substring(10, 2), NumberFormatInfo.InvariantInfo);
int sec = (int)int.Parse(dateTime.Substring(12, 2), NumberFormatInfo.InvariantInfo);
// this is the UniversalTime
return new DateTime(year, month, day, hour, min, sec, 0);
}
private DirectorySearcher InternalGetDirectorySearcher()
{
DirectoryEntry de = new DirectoryEntry("LDAP://" + Name);
de.AuthenticationType = Utils.DefaultAuthType | AuthenticationTypes.ServerBind;
de.Username = context.UserName;
de.Password = context.Password;
return new DirectorySearcher(de);
}
#endregion private methods
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace WindowsAuthorizationService.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.ServiceModel.Channels;
using System.ServiceModel;
using System.Transactions;
namespace Microsoft.Samples.SsbTransportChannel
{
public sealed class SsbConversationSender : CommunicationObject
{
bool ownsConnection = true;
SqlConnection con;
string connectionString;
string source;
string target;
ConversationInfo conversation;
bool endConversationOnClose;
string contract;
bool useEncryption;
/// <summary>
/// This property indicates whether the service broker conversatoin
/// will ended when this client is closed. If a client doesn't explicitly start
/// a conversation or open an existing conversation this property defaults to true.
///
/// Set this property to false if the client side of the conversation is going to receive
/// response messages or end conversation messages.
/// </summary>
public bool EndConversationOnClose
{
get { return endConversationOnClose; }
set { endConversationOnClose = value; }
}
SsbChannelFactory factory;
internal SsbConversationSender(string connectionString,Uri via, SsbChannelFactory factory, bool endConversationOnClose, string contract, bool useEncryption)
{
if (String.IsNullOrEmpty(connectionString))
{
throw new ArgumentNullException("connectionString");
}
if (via == null)
{
throw new ArgumentNullException("via");
}
if (factory == null)
{
throw new ArgumentNullException("factory");
}
SsbUri ssburi = new SsbUri(via);
this.source = ssburi.Client;
this.target = ssburi.Service;
this.connectionString = connectionString;
this.endConversationOnClose = endConversationOnClose;
this.factory = factory;
this.contract = contract;
this.useEncryption = useEncryption;
}
public Guid ConversationGroupID
{
get
{
ThrowIfDisposedOrNotOpen();
return conversation.ConversationGroupID;
}
}
public Guid ConversationHandle
{
get
{
ThrowIfDisposedOrNotOpen();
if (conversation == null)
{
throw new InvalidOperationException("There is no active conversation. Either send a message or call BeginConversation, or OpenConversation.");
}
return conversation.ConversationHandle;
}
}
public ServiceHost CreateResponseHost<TContract,TService>(Uri listenAddress)
{
ThrowIfDisposedOrNotOpen();
ServiceHost host = new ServiceHost(typeof(TService));
return CreateResponseHost2<TContract>(host,listenAddress);
}
public ServiceHost CreateResponseHost<TContract>(TContract serviceInstance, Uri listenAddress)
{
ThrowIfDisposedOrNotOpen();
ServiceHost host = new ServiceHost(serviceInstance);
return CreateResponseHost2<TContract>(host, listenAddress);
}
private ServiceHost CreateResponseHost2<TContract>(ServiceHost host, Uri listenAddress)
{
//if turn this off, since it makes no sense
//and if the conversation was started automatically, it will be on.
endConversationOnClose = false;
//Uri responseAddress = new SsbUri(listenAddress).Reverse();
BindingElementCollection bindingElements = factory.Binding.CreateBindingElements();
SsbBindingElement ssbBindingElement = bindingElements.Find<SsbBindingElement>();
ssbBindingElement.ConversationGroupId = ConversationGroupID;
Binding responseBinding = new CustomBinding(bindingElements);
responseBinding.ReceiveTimeout = factory.Binding.ReceiveTimeout;
responseBinding.OpenTimeout = factory.Binding.OpenTimeout;
responseBinding.CloseTimeout = factory.Binding.CloseTimeout;
host.AddServiceEndpoint(typeof(TContract), responseBinding, listenAddress);
return host;
}
public SqlConnection GetConnection()
{
return this.con;
}
internal void Send(byte[] buffer, TimeSpan timeout, string messageType)
{
ThrowIfDisposedOrNotOpen();
TimeoutHelper helper = new TimeoutHelper(timeout);
//if the client hasn't explicitly begun a conversation, start one here.
// CONSIDER (dbrowne) automatically ending the conversation in this case.
if (conversation == null)
{
BeginNewConversation();
this.endConversationOnClose = true;
}
try
{
string SQL = string.Format(@"SEND ON CONVERSATION @Conversation MESSAGE TYPE [{0}](@MessageBody)",SsbHelper.ValidateIdentifier(messageType));
SqlCommand cmd = new SqlCommand(SQL, con);
cmd.CommandTimeout = helper.RemainingTimeInMillisecondsOrZero();
SqlParameter pConversation = cmd.Parameters.Add("@Conversation", SqlDbType.UniqueIdentifier);
pConversation.Value = this.conversation.ConversationHandle;
SqlParameter pMessageBody = cmd.Parameters.Add("@MessageBody", SqlDbType.VarBinary);
pMessageBody.Value = buffer;
try
{
cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
if (ex.Number == 8429)
{
string errorMessage = SsbHelper.CheckConversationForErrorMessage(con,this.conversation.ConversationHandle);
if (errorMessage != null)
{
throw new Exception(errorMessage);
}
throw;
}
throw;
}
SsbInstrumentation.MessageSent(buffer.Length);
}
catch (Exception e)
{
if (!helper.IsTimeRemaining)
{
throw new TimeoutException("Timed out while sending a message. The timeout value passed in was " + timeout.TotalSeconds + " seconds");
}
else
{
throw new CommunicationException(String.Format("An exception occurred while sending on conversation {0}.", this.conversation.ConversationHandle), e);
}
}
}
protected override TimeSpan DefaultCloseTimeout
{
get { return SsbConstants.DefaultCloseTimeout; }
}
protected override TimeSpan DefaultOpenTimeout
{
get { return SsbConstants.DefaultOpenTimeout; }
}
#region AsyncWrappers
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
CloseDelegate d = new CloseDelegate(this.Close);
return d.BeginInvoke(timeout, callback, state);
}
protected override void OnEndClose(IAsyncResult result)
{
CloseDelegate d = new CloseDelegate(this.Close);
d.EndInvoke(result);
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
OpenDelegate d = new OpenDelegate(this.Open);
return d.BeginInvoke(timeout, callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
OpenDelegate d = new OpenDelegate(this.Open);
d.EndInvoke(result);
}
#endregion
protected override void OnAbort()
{
if (ownsConnection)
{
con.Dispose();
}
}
protected override void OnClose(TimeSpan timeout)
{
if (endConversationOnClose && this.conversation != null)
{
this.EndConversation();
}
if (ownsConnection)
{
con.Dispose();
}
}
public void SetConnection(SqlConnection con)
{
if (this.State == CommunicationState.Opened)
{
throw new InvalidOperationException("Cannot set the connection of an open SsbConversationSender");
}
this.connectionString = null;
this.con = con;
this.ownsConnection = false; //remember not to close this connection, as it's lifetime is controled elsewhere.
}
protected override void OnOpen(TimeSpan timeout)
{
TimeoutHelper helper = new TimeoutHelper(timeout);
if (this.con == null)
{
this.con = SsbHelper.GetConnection(this.connectionString);
con.Open();
this.ownsConnection = true;
}
}
public void OpenConversation(Guid conversationHandle)
{
this.OpenConversation(conversationHandle, this.DefaultOpenTimeout);
}
public void OpenConversation(Guid conversationHandle, TimeSpan timeout)
{
ThrowIfDisposedOrNotOpen();
this.conversation = SsbHelper.GetConversationInfo(conversationHandle, con);
}
public Guid BeginNewConversation()
{
return this.BeginNewConversation(Guid.Empty, this.DefaultOpenTimeout);
}
public Guid BeginNewConversation(TimeSpan timeout)
{
return this.BeginNewConversation(Guid.Empty, timeout);
}
public Guid BeginNewConversation(Guid conversationGroupId)
{
return this.BeginNewConversation(conversationGroupId, this.DefaultOpenTimeout);
}
public Guid BeginNewConversation(Guid conversationGroupId, TimeSpan timeout)
{
ThrowIfDisposedOrNotOpen();
endConversationOnClose = false; //if a conversation is explicitly started, don't automatically close it.
TimeoutHelper helper = new TimeoutHelper(timeout);
try
{
string SQL = string.Format(
@"BEGIN DIALOG CONVERSATION @ConversationHandle
FROM SERVICE @Source TO SERVICE @Target
ON CONTRACT [{0}] WITH ENCRYPTION = {1}",contract,useEncryption?"ON":"OFF");
if (conversationGroupId != Guid.Empty)
{
SQL += String.Format(", RELATED_CONVERSATION_GROUP = '{0}'", conversationGroupId);
}
SqlCommand cmd = new SqlCommand(SQL, con);
cmd.CommandTimeout = helper.RemainingTimeInMillisecondsOrZero();
SqlParameter pconversationHandle = cmd.Parameters.Add("@ConversationHandle", SqlDbType.UniqueIdentifier);
pconversationHandle.Direction = ParameterDirection.Output;
SqlParameter pTarget = cmd.Parameters.Add("@Target", SqlDbType.VarChar);
pTarget.Value = this.target;
SqlParameter pSource = cmd.Parameters.Add("@Source", SqlDbType.VarChar);
pSource.Value = this.source;
cmd.ExecuteNonQuery();
this.conversation = SsbHelper.GetConversationInfo((Guid)pconversationHandle.Value, con);
return this.conversation.ConversationHandle;
}
catch (SqlException ex)
{
if (!helper.IsTimeRemaining)
{
throw new TimeoutException(String.Format("Timed out while beginning new conversation to service {0}. Timeout value was {1} seconds", this.target, timeout.TotalSeconds), ex);
}
else
{
throw new CommunicationException(String.Format("An exception occurred while beginning new conversation to service {0}", this.target), ex);
}
}
finally
{
}
}
public void SetConversationTimer(Guid conversationHandle, TimeSpan timerTimeout)
{
SsbHelper.SetConversationTimer(conversationHandle, timerTimeout, this.con);
}
public void EndConversation()
{
this.EndConversation(this.DefaultCloseTimeout);
}
public void EndConversationWithError(TimeSpan timeout, int errorCode, string errorDescription)
{
TimeoutHelper helper = new TimeoutHelper(timeout);
try
{
string SQL = "END CONVERSATION @ConversationHandle WITH ERROR = @error DESCRIPTION = @description";
SqlCommand cmd = new SqlCommand(SQL, con);
cmd.CommandTimeout = helper.RemainingTimeInMillisecondsOrZero();
cmd.Parameters.Add("@ConversationHandle", SqlDbType.UniqueIdentifier).Value = conversation.ConversationHandle;
cmd.Parameters.Add("@error", SqlDbType.Int).Value = errorCode;
cmd.Parameters.Add("@description", SqlDbType.NVarChar, 3000).Value = errorDescription;
cmd.ExecuteNonQuery();
this.conversation = null;
}
catch (SqlException ex)
{
if (!helper.IsTimeRemaining)
{
throw new TimeoutException(String.Format("Timed out while ending conversation {0}. Timeout value was {1} seconds", this.conversation.ConversationHandle, timeout.TotalSeconds), ex);
}
else
{
throw new CommunicationException(String.Format("An exception occurred while ending conversation {0}.", this.conversation.ConversationHandle), ex);
}
}
}
public void EndConversation(TimeSpan timeout)
{
TimeoutHelper helper = new TimeoutHelper(timeout);
try
{
string SQL = "END CONVERSATION @ConversationHandle";
SqlCommand cmd = new SqlCommand(SQL, con);
cmd.CommandTimeout = helper.RemainingTimeInMillisecondsOrZero();
cmd.Parameters.Add("@ConversationHandle", SqlDbType.UniqueIdentifier).Value = conversation.ConversationHandle;
cmd.ExecuteNonQuery();
this.conversation = null;
}
catch (SqlException ex)
{
if (!helper.IsTimeRemaining)
{
throw new TimeoutException(String.Format("Timed out while ending conversation {0}. Timeout value was {1} seconds", this.conversation.ConversationHandle, timeout.TotalSeconds), ex);
}
else
{
throw new CommunicationException(String.Format("An exception occurred while ending conversation {0}.", this.conversation.ConversationHandle), ex);
}
}
}
}
}
| |
// 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 class is primarily used to test buffer boundary integrity of readers.
/// This class constructs a memory stream from the given buffer boundary length such that
/// the required tag completely lies exactly on the start and end of buffer boundary.
/// The class makes up the additional bytes by filling in whitespace if so.
/// The first buffer length consists of the XML Decl and the Root Start (done by PrepareStream() )
/// The next buffer length consists of the actual start and end text with the variable content stretched
/// out to end at the buffer boundary.
///
using System;
using System.Xml;
using System.Text;
using System.IO;
using System.Globalization;
using System.Diagnostics;
using OLEDB.Test.ModuleCore;
namespace XmlCoreTest.Common
{
/// This class adds the functionality to add a string and a char
/// to the memory stream class.
public class CustomMemoryStream : MemoryStream
{
public void WriteString(string s)
{
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
WriteByte((byte)(c & 0xFF));
WriteByte((byte)((c >> 8) & 0xFF));
}
}
public void WriteChar(char c)
{
WriteByte((byte)(c & 0xFF));
WriteByte((byte)((c >> 8) & 0xFF));
}
}
/// <summary>
/// This class contains helper methods for Readers.
/// ConvertToBinaryStream : Converts the given xml string to the binary equivalent of the string and returns it
/// using a memory stream.
/// Common usage pattern would be something like :
/// XmlReader.Create( new MemoryStream(ReaderHelper.ConvertToBinaryStream("<elem>abc</elem>", true, false)), "baseUri", readerSettings );
/// </summary>
public static partial class ReaderHelper
{
public class ReaderUtilException : XmlException
{
public ReaderUtilException(string msg) : base(msg)
{
}
}
}
// This class creates an XML tag which is exactly the length of the buffer
// boundary.
public class BufferBoundary
{
public static string START_TAG = "<?pi ";
public static string END_TAG = "?>";
private const int _4K = 4096;
// count values (useful for cases like tagContent = "attr%1='val%1' "
public int count = 0;
public int bufferBoundaryLength;
private static bool s_debug = false;
// flag for replacing tagContent % with count values
public bool replaceFlag = false;
public CustomMemoryStream memoryStream = new CustomMemoryStream();
public string xmlDecl = "<?xml version='1.0'?>";
public string rootStart = "<doc>";
public string rootEnd = "</doc>";
public string startText = null;
public string endText = null;
public string tagContent = null;
// for the iterative tagContent
public string iterContent = null;
public StringBuilder nodeValue = new StringBuilder();
//Overloaded Constructor.
public BufferBoundary(string sTag, string eTag, string cntt, int buffLen)
{
startText = sTag;
endText = eTag;
tagContent = cntt;
bufferBoundaryLength = buffLen;
}
private bool _prepared = false;
private bool _finished = false;
//This fills the first bufferboundary bytes with buffer length spaces.
public void PrepareStream()
{
if (_prepared)
return;
memoryStream.WriteString(xmlDecl);
memoryStream.WriteString(rootStart);
memoryStream.WriteString(
GetSpaces(bufferBoundaryLength - (xmlDecl.Length + rootStart.Length) * 2));
_prepared = true;
}
//This fills the first bufferboundary bytes with buffer length spaces and initial xml string user wants.
public void PrepareStream(string xml)
{
if (_prepared)
return;
memoryStream.WriteString(xmlDecl);
memoryStream.WriteString(rootStart);
memoryStream.WriteString(xml);
memoryStream.WriteString(GetSpaces(bufferBoundaryLength - (xmlDecl.Length + rootStart.Length + xml.Length) * 2));
_prepared = true;
}
//This writes out the end of root element
public void FinishStream()
{
if (_finished)
return;
memoryStream.WriteString(rootEnd);
_finished = true;
}
//This writes out the end of root element after writing some endXml
public void FinishStream(string endXml)
{
if (_finished)
return;
memoryStream.WriteString(endXml);
memoryStream.WriteString(rootEnd);
_finished = true;
}
//This places the required tags at the buffer boundary.
public MemoryStream StringAtBufferBoundary()
{
CError.WriteLine("MemoryStreamLength " + memoryStream.Length);
long lengthSoFar = memoryStream.Length;
//if parameters are to be replaced with count.
if (tagContent.IndexOf("{0}") > -1)
replaceFlag = true;
memoryStream.WriteString(startText);
if (s_debug)
CError.WriteLine("Stream Length after start tag = " + memoryStream.Length);
while (true)
{
if (replaceFlag)
{
iterContent = string.Format(tagContent, ++count);
}
else
{
iterContent = tagContent;
}
if (s_debug)
CError.Write((bufferBoundaryLength - nodeValue.Length * 2 - startText.Length * 2 - endText.Length * 2 - iterContent.Length * 2) + "|");
if (bufferBoundaryLength - nodeValue.Length * 2 - startText.Length * 2 - endText.Length * 2 - iterContent.Length * 2 < 0)
{
break;
}
nodeValue.Append(iterContent);
memoryStream.WriteString(iterContent);
}
if (s_debug) CError.WriteLine("\nCount = " + (count - 1));
if (s_debug) CError.WriteLine("Stream Length = " + nodeValue.Length);
if (s_debug) CError.WriteLine("Stream Length after tagContent tag = " + memoryStream.Length);
if (s_debug) CError.WriteLine("Node Value = " + nodeValue);
long spaces = bufferBoundaryLength - (nodeValue.Length + endText.Length + startText.Length) * 2;
if (s_debug) CError.WriteLine("Spaces Requested = " + spaces / 2);
nodeValue.Append(GetSpaces(spaces));
memoryStream.WriteString(GetSpaces(spaces));
memoryStream.WriteString(endText);
if (s_debug) CError.WriteLine("Stream Length before FinishStream = " + memoryStream.Length);
return memoryStream;
}
// This function builds a string made up of specified number of spaces.
public static string GetSpaces(long spaces)
{
StringBuilder sb = new StringBuilder();
long actualSpaces = spaces / 2;
while (actualSpaces-- > 0)
{
sb.Append(" ");
}
return sb.ToString();
}
// Just a test function.
public MemoryStream Test()
{
PrepareStream();
FinishStream();
return memoryStream;
}
}//End BufferBoundary
}
| |
// 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.IO;
using System.Xml;
using OLEDB.Test.ModuleCore;
namespace XmlReaderTest.Common
{
/////////////////////////////////////////////////////////////////////////
// TestCase ReadOuterXml
//
/////////////////////////////////////////////////////////////////////////
[InheritRequired()]
public abstract partial class TCReadOuterXml : TCXMLReaderBaseGeneral
{
// Element names to test ReadOuterXml on
private static string s_EMP1 = "EMPTY1";
private static string s_EMP2 = "EMPTY2";
private static string s_EMP3 = "EMPTY3";
private static string s_EMP4 = "EMPTY4";
private static string s_ENT1 = "ENTITY1";
private static string s_NEMP0 = "NONEMPTY0";
private static string s_NEMP1 = "NONEMPTY1";
private static string s_NEMP2 = "NONEMPTY2";
private static string s_ELEM1 = "CHARS2";
private static string s_ELEM2 = "SKIP3";
private static string s_ELEM3 = "CONTENT";
private static string s_ELEM4 = "COMPLEX";
// Element names after the ReadOuterXml call
private static string s_NEXT1 = "COMPLEX";
private static string s_NEXT2 = "ACT2";
private static string s_NEXT3 = "CHARS_ELEM1";
private static string s_NEXT4 = "AFTERSKIP3";
private static string s_NEXT5 = "TITLE";
private static string s_NEXT6 = "ENTITY2";
private static string s_NEXT7 = "DUMMY";
// Expected strings returned by ReadOuterXml
private static string s_EXP_EMP1 = "<EMPTY1 />";
private static string s_EXP_EMP2 = "<EMPTY2 val=\"abc\" />";
private static string s_EXP_EMP3 = "<EMPTY3></EMPTY3>";
private static string s_EXP_EMP4 = "<EMPTY4 val=\"abc\"></EMPTY4>";
private static string s_EXP_NEMP1 = "<NONEMPTY1>ABCDE</NONEMPTY1>";
private static string s_EXP_NEMP2 = "<NONEMPTY2 val=\"abc\">1234</NONEMPTY2>";
private static string s_EXP_ELEM1 = "<CHARS2>xxx<MARKUP />yyy</CHARS2>";
private static string s_EXP_ELEM2 = "<SKIP3><ELEM1 /><ELEM2>xxx yyy</ELEM2><ELEM3 /></SKIP3>";
private static string s_EXP_ELEM3 = "<CONTENT><e1 a1='a1value' a2='a2value'><e2 a1='a1value' a2='a2value'><e3 a1='a1value' a2='a2value'>leave</e3></e2></e1></CONTENT>";
private static string s_EXP_ELEM4 = "<COMPLEX>Text<!-- comment --><![CDATA[cdata]]></COMPLEX>";
private static string s_EXP_ELEM4_XSLT = "<COMPLEX>Text<!-- comment -->cdata</COMPLEX>";
private static string s_EXP_ENT1_EXPAND_ALL = "<ENTITY1 att1=\"xxx<xxxAxxxCxxxNO_REFERENCEe1;xxx\">xxx>xxxBxxxDxxxNO_REFERENCEe1;xxx</ENTITY1>";
private static string s_EXP_ENT1_EXPAND_CHAR = "<ENTITY1 att1=\"xxx<xxxAxxxCxxx&e1;xxx\">xxx>xxxBxxxDxxx&e1;xxx</ENTITY1>";
private int TestOuterOnElement(string strElem, string strOuterXml, string strNextElemName, bool bWhitespace)
{
ReloadSource();
DataReader.PositionOnElement(strElem);
CError.Compare(DataReader.ReadOuterXml(), strOuterXml, "outer");
if (bWhitespace)
{
if (!(IsXsltReader() || IsXPathNavigatorReader()))// xslt doesn't return whitespace
{
if (IsCoreReader())
{
CError.Compare(DataReader.VerifyNode(XmlNodeType.Whitespace, String.Empty, "\n"), true, "vn");
}
else
{
CError.Compare(DataReader.VerifyNode(XmlNodeType.Whitespace, String.Empty, "\r\n"), true, "vn");
}
DataReader.Read();
}
}
CError.Compare(DataReader.VerifyNode(XmlNodeType.Element, strNextElemName, String.Empty), true, "vn2");
return TEST_PASS;
}
private int TestOuterOnAttribute(string strElem, string strName, string strValue)
{
ReloadSource();
DataReader.PositionOnElement(strElem);
DataReader.MoveToAttribute(DataReader.AttributeCount / 2);
string strExpected = String.Format("{0}=\"{1}\"", strName, strValue);
CError.Compare(DataReader.ReadOuterXml(), strExpected, "outer");
CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, strName, strValue), true, "vn");
return TEST_PASS;
}
private int TestOuterOnNodeType(XmlNodeType nt)
{
ReloadSource();
PositionOnNodeType(nt);
DataReader.Read();
XmlNodeType expNt = DataReader.NodeType;
string expName = DataReader.Name;
string expValue = DataReader.Value;
ReloadSource();
PositionOnNodeType(nt);
CError.Compare(DataReader.ReadOuterXml(), String.Empty, "outer");
CError.Compare(DataReader.VerifyNode(expNt, expName, expValue), true, "vn");
return TEST_PASS;
}
////////////////////////////////////////////////////////////////
// Variations
////////////////////////////////////////////////////////////////
[Variation("ReadOuterXml on empty element w/o attributes", Pri = 0)]
public int ReadOuterXml1()
{
if (IsBinaryReader())
{
return TEST_SKIPPED;
}
return TestOuterOnElement(s_EMP1, s_EXP_EMP1, s_EMP2, true);
}
[Variation("ReadOuterXml on empty element w/ attributes", Pri = 0)]
public int ReadOuterXml2()
{
if (IsBinaryReader())
{
return TEST_SKIPPED;
}
return TestOuterOnElement(s_EMP2, s_EXP_EMP2, s_EMP3, true);
}
[Variation("ReadOuterXml on full empty element w/o attributes")]
public int ReadOuterXml3()
{
return TestOuterOnElement(s_EMP3, s_EXP_EMP3, s_NEMP0, true);
}
[Variation("ReadOuterXml on full empty element w/ attributes")]
public int ReadOuterXml4()
{
return TestOuterOnElement(s_EMP4, s_EXP_EMP4, s_NEXT1, true);
}
[Variation("ReadOuterXml on element with text content", Pri = 0)]
public int ReadOuterXml5()
{
return TestOuterOnElement(s_NEMP1, s_EXP_NEMP1, s_NEMP2, true);
}
[Variation("ReadOuterXml on element with attributes", Pri = 0)]
public int ReadOuterXml6()
{
return TestOuterOnElement(s_NEMP2, s_EXP_NEMP2, s_NEXT2, true);
}
[Variation("ReadOuterXml on element with text and markup content")]
public int ReadOuterXml7()
{
if (IsBinaryReader())
{
return TEST_SKIPPED;
}
return TestOuterOnElement(s_ELEM1, s_EXP_ELEM1, s_NEXT3, true);
}
[Variation("ReadOuterXml with multiple level of elements")]
public int ReadOuterXml8()
{
if (IsBinaryReader())
{
return TEST_SKIPPED;
}
return TestOuterOnElement(s_ELEM2, s_EXP_ELEM2, s_NEXT4, false);
}
[Variation("ReadOuterXml with multiple level of elements, text and attributes", Pri = 0)]
public int ReadOuterXml9()
{
string strExpected = s_EXP_ELEM3;
strExpected = strExpected.Replace('\'', '"');
return TestOuterOnElement(s_ELEM3, strExpected, s_NEXT5, true);
}
[Variation("ReadOuterXml on element with complex content (CDATA, PIs, Comments)", Pri = 0)]
public int ReadOuterXml10()
{
if (IsXsltReader() || IsXPathNavigatorReader())
return TestOuterOnElement(s_ELEM4, s_EXP_ELEM4_XSLT, s_NEXT7, true);
else
return TestOuterOnElement(s_ELEM4, s_EXP_ELEM4, s_NEXT7, true);
}
[Variation("ReadOuterXml on element with entities, EntityHandling = ExpandEntities")]
public int ReadOuterXml11()
{
string strExpected;
if (IsXsltReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc() || IsXmlValidatingReader() || IsCoreReader() || IsXPathNavigatorReader())
{
strExpected = s_EXP_ENT1_EXPAND_ALL;
}
else
{
strExpected = s_EXP_ENT1_EXPAND_CHAR;
}
return TestOuterOnElement(s_ENT1, strExpected, s_NEXT6, false);
}
[Variation("ReadOuterXml on attribute node of empty element")]
public int ReadOuterXml12()
{
return TestOuterOnAttribute(s_EMP2, "val", "abc");
}
[Variation("ReadOuterXml on attribute node of full empty element")]
public int ReadOuterXml13()
{
return TestOuterOnAttribute(s_EMP4, "val", "abc");
}
[Variation("ReadOuterXml on attribute node", Pri = 0)]
public int ReadOuterXml14()
{
return TestOuterOnAttribute(s_NEMP2, "val", "abc");
}
[Variation("ReadOuterXml on attribute with entities, EntityHandling = ExpandEntities", Pri = 0)]
public int ReadOuterXml15()
{
ReloadSource();
DataReader.PositionOnElement(s_ENT1);
DataReader.MoveToAttribute(DataReader.AttributeCount / 2);
string strExpected;
if (IsXsltReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc() || IsXmlValidatingReader() || IsCoreReader() || IsXPathNavigatorReader())
strExpected = "att1=\"xxx<xxxAxxxCxxxNO_REFERENCEe1;xxx\"";
else
{
strExpected = "att1=\"xxx<xxxAxxxCxxx&e1;xxx\"";
}
CError.Compare(DataReader.ReadOuterXml(), strExpected, "outer");
if (IsXmlTextReader())
CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "att1", ST_ENT1_ATT_EXPAND_CHAR_ENTITIES), true, "vn");
else
CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "att1", ST_ENT1_ATT_EXPAND_ENTITIES), true, "vn");
return TEST_PASS;
}
[Variation("ReadOuterXml on Comment")]
public int ReadOuterXml16()
{
return TestOuterOnNodeType(XmlNodeType.Comment);
}
[Variation("ReadOuterXml on ProcessingInstruction")]
public int ReadOuterXml17()
{
return TestOuterOnNodeType(XmlNodeType.ProcessingInstruction);
}
[Variation("ReadOuterXml on DocumentType")]
public int ReadOuterXml18()
{
if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader())
return TEST_SKIPPED;
return TestOuterOnNodeType(XmlNodeType.DocumentType);
}
[Variation("ReadOuterXml on XmlDeclaration")]
public int ReadOuterXml19()
{
if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader())
return TEST_SKIPPED;
return TestOuterOnNodeType(XmlNodeType.XmlDeclaration);
}
[Variation("ReadOuterXml on EndElement")]
public int ReadOuterXml20()
{
return TestOuterOnNodeType(XmlNodeType.EndElement);
}
[Variation("ReadOuterXml on Text")]
public int ReadOuterXml21()
{
return TestOuterOnNodeType(XmlNodeType.Text);
}
[Variation("ReadOuterXml on EntityReference")]
public int ReadOuterXml22()
{
if (IsXsltReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader())
return TEST_SKIPPED;
return TestOuterOnNodeType(XmlNodeType.EntityReference);
}
[Variation("ReadOuterXml on EndEntity")]
public int ReadOuterXml23()
{
if (IsXmlTextReader() || IsXsltReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader())
return TEST_SKIPPED;
return TestOuterOnNodeType(XmlNodeType.EndEntity);
}
[Variation("ReadOuterXml on CDATA")]
public int ReadOuterXml24()
{
if (IsXsltReader() || IsXPathNavigatorReader())
return TEST_SKIPPED;
return TestOuterOnNodeType(XmlNodeType.CDATA);
}
[Variation("ReadOuterXml on XmlDeclaration attributes")]
public int ReadOuterXml25()
{
if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader())
return TEST_SKIPPED;
ReloadSource();
DataReader.PositionOnNodeType(XmlNodeType.XmlDeclaration);
DataReader.MoveToAttribute(DataReader.AttributeCount / 2);
CError.Compare(DataReader.ReadOuterXml().ToLower(), "encoding=\"utf-8\"", "outer");
if (IsBinaryReader())
CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "encoding", "utf-8"), true, "vn");
else
CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "encoding", "UTF-8"), true, "vn");
return TEST_PASS;
}
[Variation("ReadOuterXml on DocumentType attributes")]
public int ReadOuterXml26()
{
if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader())
return TEST_SKIPPED;
ReloadSource();
DataReader.PositionOnNodeType(XmlNodeType.DocumentType);
DataReader.MoveToAttribute(DataReader.AttributeCount / 2);
CError.Compare(DataReader.ReadOuterXml(), "SYSTEM=\"AllNodeTypes.dtd\"", "outer");
CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "SYSTEM", "AllNodeTypes.dtd"), true, "vn");
return TEST_PASS;
}
[Variation("ReadOuterXml on element with entities, EntityHandling = ExpandCharEntities")]
public int TRReadOuterXml27()
{
string strExpected;
if (IsXsltReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader())
strExpected = s_EXP_ENT1_EXPAND_ALL;
else
{
if (IsXmlNodeReader())
{
strExpected = s_EXP_ENT1_EXPAND_CHAR;
}
else
{
strExpected = s_EXP_ENT1_EXPAND_CHAR;
}
}
ReloadSource();
DataReader.PositionOnElement(s_ENT1);
CError.Compare(DataReader.ReadOuterXml(), strExpected, "outer");
CError.Compare(DataReader.VerifyNode(XmlNodeType.Element, s_NEXT6, String.Empty), true, "vn");
return TEST_PASS;
}
[Variation("ReadOuterXml on attribute with entities, EntityHandling = ExpandCharEntites")]
public int TRReadOuterXml28()
{
string strExpected;
if (IsXsltReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader())
strExpected = "att1=\"xxx<xxxAxxxCxxxNO_REFERENCEe1;xxx\"";
else
{
if (IsXmlNodeReader())
{
strExpected = "att1=\"xxx<xxxAxxxCxxxNO_REFERENCEe1;xxx\"";
}
else
{
strExpected = "att1=\"xxx<xxxAxxxCxxxNO_REFERENCEe1;xxx\"";
}
}
ReloadSource();
DataReader.PositionOnElement(s_ENT1);
DataReader.MoveToAttribute(DataReader.AttributeCount / 2);
CError.Compare(DataReader.ReadOuterXml(), strExpected, "outer");
if (IsXmlTextReader())
CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "att1", ST_ENT1_ATT_EXPAND_CHAR_ENTITIES), true, "vn");
else
CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "att1", ST_ENT1_ATT_EXPAND_ENTITIES), true, "vn");
return TEST_PASS;
}
[Variation("One large element")]
public int TestTextReadOuterXml29()
{
String strp = "a ";
strp += strp;
strp += strp;
strp += strp;
strp += strp;
strp += strp;
strp += strp;
strp += strp;
string strxml = "<Name a=\"b\">" + strp + " </Name>";
ReloadSourceStr(strxml);
DataReader.Read();
CError.Compare(DataReader.ReadOuterXml(), strxml, "rox");
return TEST_PASS;
}
[Variation("Read OuterXml when Namespaces=false and has an attribute xmlns")]
public int ReadOuterXmlWhenNamespacesIgnoredWorksWithXmlns()
{
ReloadSourceStr("<?xml version='1.0' encoding='utf-8' ?> <foo xmlns='testing'><bar id='1'/></foo>");
if (IsXmlTextReader() || IsXmlValidatingReader())
DataReader.Namespaces = false;
DataReader.MoveToContent();
CError.WriteLine(DataReader.ReadOuterXml());
return TEST_PASS;
}
[Variation("XmlReader.ReadOuterXml outputs multiple namespace declarations if called within multiple XmlReader.ReadSubtree() calls")]
public int SubtreeXmlReaderOutputsSingleNamespaceDeclaration()
{
string xml = @"<root xmlns = ""http://www.test.com/""> <device> <thing>1</thing> </device></root>";
ReloadSourceStr(xml);
DataReader.ReadToFollowing("device");
Foo(DataReader.ReadSubtree());
return TEST_PASS;
}
private void Foo(XmlReader reader)
{
reader.Read();
Bar(reader.ReadSubtree());
}
private void Bar(XmlReader reader)
{
reader.Read();
string foo = reader.ReadOuterXml();
CError.Compare(foo, "<device xmlns=\"http://www.test.com/\"> <thing>1</thing> </device>",
"<device xmlns=\"http://www.test.com/\"><thing>1</thing></device>", "mismatch");
}
}
}
| |
// 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.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.Sockets
{
// This object is used to wrap a bunch of ConnectAsync operations
// on behalf of a single user call to ConnectAsync with a DnsEndPoint
internal abstract class MultipleConnectAsync
{
protected SocketAsyncEventArgs _userArgs;
protected SocketAsyncEventArgs _internalArgs;
protected DnsEndPoint _endPoint;
protected IPAddress[] _addressList;
protected int _nextAddress;
private enum State
{
NotStarted,
DnsQuery,
ConnectAttempt,
Completed,
Canceled,
}
private State _state;
private object _lockObject = new object();
// Called by Socket to kick off the ConnectAsync process. We'll complete the user's SAEA
// when it's done. Returns true if the operation will be asynchronous, false if it has failed synchronously
public bool StartConnectAsync(SocketAsyncEventArgs args, DnsEndPoint endPoint)
{
lock (_lockObject)
{
if (endPoint.AddressFamily != AddressFamily.Unspecified &&
endPoint.AddressFamily != AddressFamily.InterNetwork &&
endPoint.AddressFamily != AddressFamily.InterNetworkV6)
{
NetEventSource.Fail(this, $"Unexpected endpoint address family: {endPoint.AddressFamily}");
}
_userArgs = args;
_endPoint = endPoint;
// If Cancel() was called before we got the lock, it only set the state to Canceled: we need to
// fail synchronously from here. Once State.DnsQuery is set, the Cancel() call will handle calling AsyncFail.
if (_state == State.Canceled)
{
SyncFail(new SocketException((int)SocketError.OperationAborted));
return false;
}
if (_state != State.NotStarted)
{
NetEventSource.Fail(this, "MultipleConnectAsync.StartConnectAsync(): Unexpected object state");
}
_state = State.DnsQuery;
IAsyncResult result = Dns.BeginGetHostAddresses(endPoint.Host, new AsyncCallback(DnsCallback), null);
if (result.CompletedSynchronously)
{
return DoDnsCallback(result, true);
}
else
{
return true;
}
}
}
// Callback which fires when the Dns Resolve is complete
private void DnsCallback(IAsyncResult result)
{
if (!result.CompletedSynchronously)
{
DoDnsCallback(result, false);
}
}
// Called when the DNS query completes (either synchronously or asynchronously). Checks for failure and
// starts the first connection attempt if it succeeded. Returns true if the operation will be asynchronous,
// false if it has failed synchronously.
private bool DoDnsCallback(IAsyncResult result, bool sync)
{
Exception exception = null;
lock (_lockObject)
{
// If the connection attempt was canceled during the dns query, the user's callback has already been
// called asynchronously and we simply need to return.
if (_state == State.Canceled)
{
return true;
}
if (_state != State.DnsQuery)
{
NetEventSource.Fail(this, "MultipleConnectAsync.DoDnsCallback(): Unexpected object state");
}
try
{
_addressList = Dns.EndGetHostAddresses(result);
if (_addressList == null)
{
NetEventSource.Fail(this, "MultipleConnectAsync.DoDnsCallback(): EndGetHostAddresses returned null!");
}
}
catch (Exception e)
{
_state = State.Completed;
exception = e;
}
// If the dns query succeeded, try to connect to the first address
if (exception == null)
{
_state = State.ConnectAttempt;
_internalArgs = new SocketAsyncEventArgs();
_internalArgs.Completed += InternalConnectCallback;
_internalArgs.CopyBufferFrom(_userArgs);
exception = AttemptConnection();
if (exception != null)
{
// There was a synchronous error while connecting
_state = State.Completed;
}
}
}
// Call this outside of the lock because it might call the user's callback.
if (exception != null)
{
return Fail(sync, exception);
}
else
{
return true;
}
}
// Callback which fires when an internal connection attempt completes.
// If it failed and there are more addresses to try, do it.
private void InternalConnectCallback(object sender, SocketAsyncEventArgs args)
{
Exception exception = null;
lock (_lockObject)
{
if (_state == State.Canceled)
{
// If Cancel was called before we got the lock, the Socket will be closed soon. We need to report
// OperationAborted (even though the connection actually completed), or the user will try to use a
// closed Socket.
exception = new SocketException((int)SocketError.OperationAborted);
}
else
{
Debug.Assert(_state == State.ConnectAttempt);
if (args.SocketError == SocketError.Success)
{
// The connection attempt succeeded; go to the completed state.
// The callback will be called outside the lock.
_state = State.Completed;
}
else if (args.SocketError == SocketError.OperationAborted)
{
// The socket was closed while the connect was in progress. This can happen if the user
// closes the socket, and is equivalent to a call to CancelConnectAsync
exception = new SocketException((int)SocketError.OperationAborted);
_state = State.Canceled;
}
else
{
// Keep track of this because it will be overwritten by AttemptConnection
SocketError currentFailure = args.SocketError;
Exception connectException = AttemptConnection();
if (connectException == null)
{
// don't call the callback, another connection attempt is successfully started
return;
}
else
{
SocketException socketException = connectException as SocketException;
if (socketException != null && socketException.SocketErrorCode == SocketError.NoData)
{
// If the error is NoData, that means there are no more IPAddresses to attempt
// a connection to. Return the last error from an actual connection instead.
exception = new SocketException((int)currentFailure);
}
else
{
exception = connectException;
}
_state = State.Completed;
}
}
}
}
if (exception == null)
{
Succeed();
}
else
{
AsyncFail(exception);
}
}
// Called to initiate a connection attempt to the next address in the list. Returns an exception
// if the attempt failed synchronously, or null if it was successfully initiated.
private Exception AttemptConnection()
{
try
{
Socket attemptSocket;
IPAddress attemptAddress = GetNextAddress(out attemptSocket);
if (attemptAddress == null)
{
return new SocketException((int)SocketError.NoData);
}
_internalArgs.RemoteEndPoint = new IPEndPoint(attemptAddress, _endPoint.Port);
return AttemptConnection(attemptSocket, _internalArgs);
}
catch (Exception e)
{
if (e is ObjectDisposedException)
{
NetEventSource.Fail(this, "unexpected ObjectDisposedException");
}
return e;
}
}
private Exception AttemptConnection(Socket attemptSocket, SocketAsyncEventArgs args)
{
try
{
if (attemptSocket == null)
{
NetEventSource.Fail(null, "attemptSocket is null!");
}
bool pending = attemptSocket.ConnectAsync(args);
if (!pending)
{
InternalConnectCallback(null, args);
}
}
catch (ObjectDisposedException)
{
// This can happen if the user closes the socket, and is equivalent to a call
// to CancelConnectAsync
return new SocketException((int)SocketError.OperationAborted);
}
catch (Exception e)
{
return e;
}
return null;
}
protected abstract void OnSucceed();
private void Succeed()
{
OnSucceed();
_userArgs.FinishWrapperConnectSuccess(_internalArgs.ConnectSocket, _internalArgs.BytesTransferred, _internalArgs.SocketFlags);
_internalArgs.Dispose();
}
protected abstract void OnFail(bool abortive);
private bool Fail(bool sync, Exception e)
{
if (sync)
{
SyncFail(e);
return false;
}
else
{
AsyncFail(e);
return true;
}
}
private void SyncFail(Exception e)
{
OnFail(false);
if (_internalArgs != null)
{
_internalArgs.Dispose();
}
SocketException socketException = e as SocketException;
if (socketException != null)
{
_userArgs.FinishConnectByNameSyncFailure(socketException, 0, SocketFlags.None);
}
else
{
ExceptionDispatchInfo.Throw(e);
}
}
private void AsyncFail(Exception e)
{
OnFail(false);
if (_internalArgs != null)
{
_internalArgs.Dispose();
}
_userArgs.FinishOperationAsyncFailure(e, 0, SocketFlags.None);
}
public void Cancel()
{
bool callOnFail = false;
lock (_lockObject)
{
switch (_state)
{
case State.NotStarted:
// Cancel was called before the Dns query was started. The dns query won't be started
// and the connection attempt will fail synchronously after the state change to DnsQuery.
// All we need to do here is close all the sockets.
callOnFail = true;
break;
case State.DnsQuery:
// Cancel was called after the Dns query was started, but before it finished. We can't
// actually cancel the Dns query, but we'll fake it by failing the connect attempt asynchronously
// from here, and silently dropping the connection attempt when the Dns query finishes.
Task.Factory.StartNew(
s => CallAsyncFail(s),
null,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
callOnFail = true;
break;
case State.ConnectAttempt:
// Cancel was called after the Dns query completed, but before we had a connection result to give
// to the user. Closing the sockets will cause any in-progress ConnectAsync call to fail immediately
// with OperationAborted, and will cause ObjectDisposedException from any new calls to ConnectAsync
// (which will be translated to OperationAborted by AttemptConnection).
callOnFail = true;
break;
case State.Completed:
// Cancel was called after we locked in a result to give to the user. Ignore it and give the user
// the real completion.
break;
default:
NetEventSource.Fail(this, "Unexpected object state");
break;
}
_state = State.Canceled;
}
// Call this outside the lock because Socket.Close may block
if (callOnFail)
{
OnFail(true);
}
}
// Call AsyncFail on a threadpool thread so it's asynchronous with respect to Cancel().
private void CallAsyncFail(object ignored)
{
AsyncFail(new SocketException((int)SocketError.OperationAborted));
}
protected abstract IPAddress GetNextAddress(out Socket attemptSocket);
}
// Used when the instance ConnectAsync method is called, or when the DnsEndPoint specified
// an AddressFamily. There's only one Socket, and we only try addresses that match its
// AddressFamily
internal sealed class SingleSocketMultipleConnectAsync : MultipleConnectAsync
{
private Socket _socket;
private bool _userSocket;
public SingleSocketMultipleConnectAsync(Socket socket, bool userSocket)
{
_socket = socket;
_userSocket = userSocket;
}
protected override IPAddress GetNextAddress(out Socket attemptSocket)
{
_socket.ReplaceHandleIfNecessaryAfterFailedConnect();
IPAddress rval = null;
do
{
if (_nextAddress >= _addressList.Length)
{
attemptSocket = null;
return null;
}
rval = _addressList[_nextAddress];
++_nextAddress;
}
while (!_socket.CanTryAddressFamily(rval.AddressFamily));
attemptSocket = _socket;
return rval;
}
protected override void OnFail(bool abortive)
{
// Close the socket if this is an abortive failure (CancelConnectAsync)
// or if we created it internally
if (abortive || !_userSocket)
{
_socket.Dispose();
}
}
// nothing to do on success
protected override void OnSucceed() { }
}
// This is used when the static ConnectAsync method is called. We don't know the address family
// ahead of time, so we create both IPv4 and IPv6 sockets.
internal sealed class DualSocketMultipleConnectAsync : MultipleConnectAsync
{
private Socket _socket4;
private Socket _socket6;
public DualSocketMultipleConnectAsync(SocketType socketType, ProtocolType protocolType)
{
if (Socket.OSSupportsIPv4)
{
_socket4 = new Socket(AddressFamily.InterNetwork, socketType, protocolType);
}
if (Socket.OSSupportsIPv6)
{
_socket6 = new Socket(AddressFamily.InterNetworkV6, socketType, protocolType);
}
}
protected override IPAddress GetNextAddress(out Socket attemptSocket)
{
IPAddress rval = null;
attemptSocket = null;
while (attemptSocket == null)
{
if (_nextAddress >= _addressList.Length)
{
return null;
}
rval = _addressList[_nextAddress];
++_nextAddress;
if (rval.AddressFamily == AddressFamily.InterNetworkV6)
{
attemptSocket = _socket6;
}
else if (rval.AddressFamily == AddressFamily.InterNetwork)
{
attemptSocket = _socket4;
}
}
attemptSocket?.ReplaceHandleIfNecessaryAfterFailedConnect();
return rval;
}
// on success, close the socket that wasn't used
protected override void OnSucceed()
{
if (_socket4 != null && !_socket4.Connected)
{
_socket4.Dispose();
}
if (_socket6 != null && !_socket6.Connected)
{
_socket6.Dispose();
}
}
// close both sockets whether its abortive or not - we always create them internally
protected override void OnFail(bool abortive)
{
_socket4?.Dispose();
_socket6?.Dispose();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace RSG {
public static class RsgExtensions {
public static void Each<T>(this List<T> l, Action<T> callback) {
foreach (T item in l) callback(item);
}
public static void Each<T>(this T[] l, Action<T, int> callback) {
for (int i = 0; i < l.Length; i++) callback(l[i], i);
}
}
/// <summary>
/// Implements a C# promise.
/// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
/// </summary>
public interface IPromise<PromisedT> {
/// <summary>
/// Set the name of the promise, useful for debugging.
/// </summary>
IPromise<PromisedT> WithName(string name);
/// <summary>
/// Completes the promise.
/// onResolved is called on successful completion.
/// onRejected is called on error.
/// </summary>
void Done(Action<PromisedT> onResolved, Action<Exception> onRejected);
/// <summary>
/// Completes the promise.
/// onResolved is called on successful completion.
/// Adds a default error handler.
/// </summary>
void Done(Action<PromisedT> onResolved);
/// <summary>
/// Complete the promise. Adds a default error handler.
/// </summary>
void Done();
/// <summary>
/// Handle errors for the promise.
/// </summary>
IPromise<PromisedT> Catch(Action<Exception> onRejected);
/// <summary>
/// Add a resolved callback that chains a value promise (optionally converting to a different value type).
/// </summary>
IPromise<ConvertedT> Then<ConvertedT>(Func<PromisedT, IPromise<ConvertedT>> onResolved);
/// <summary>
/// Add a resolved callback that chains a non-value promise.
/// </summary>
IPromise Then(Func<PromisedT, IPromise> onResolved);
/// <summary>
/// Add a resolved callback.
/// </summary>
IPromise<PromisedT> Then(Action<PromisedT> onResolved);
/// <summary>
/// Add a resolved callback and a rejected callback.
/// The resolved callback chains a value promise (optionally converting to a different value type).
/// </summary>
IPromise<ConvertedT> Then<ConvertedT>(Func<PromisedT, IPromise<ConvertedT>> onResolved, Action<Exception> onRejected);
/// <summary>
/// Add a resolved callback and a rejected callback.
/// The resolved callback chains a non-value promise.
/// </summary>
IPromise Then(Func<PromisedT, IPromise> onResolved, Action<Exception> onRejected);
/// <summary>
/// Add a resolved callback and a rejected callback.
/// </summary>
IPromise<PromisedT> Then(Action<PromisedT> onResolved, Action<Exception> onRejected);
/// <summary>
/// Return a new promise with a different value.
/// May also change the type of the value.
/// </summary>
IPromise<ConvertedT> Transform<ConvertedT>(Func<PromisedT, ConvertedT> transform);
/// <summary>
/// Chain an enumerable of promises, all of which must resolve.
/// Returns a promise for a collection of the resolved results.
/// The resulting promise is resolved when all of the promises have resolved.
/// It is rejected as soon as any of the promises have been rejected.
/// </summary>
IPromise<IEnumerable<ConvertedT>> ThenAll<ConvertedT>(Func<PromisedT, IEnumerable<IPromise<ConvertedT>>> chain);
/// <summary>
/// Chain an enumerable of promises, all of which must resolve.
/// Converts to a non-value promise.
/// The resulting promise is resolved when all of the promises have resolved.
/// It is rejected as soon as any of the promises have been rejected.
/// </summary>
IPromise ThenAll(Func<PromisedT, IEnumerable<IPromise>> chain);
/// <summary>
/// Takes a function that yields an enumerable of promises.
/// Returns a promise that resolves when the first of the promises has resolved.
/// Yields the value from the first promise that has resolved.
/// </summary>
IPromise<ConvertedT> ThenRace<ConvertedT>(Func<PromisedT, IEnumerable<IPromise<ConvertedT>>> chain);
/// <summary>
/// Takes a function that yields an enumerable of promises.
/// Converts to a non-value promise.
/// Returns a promise that resolves when the first of the promises has resolved.
/// Yields the value from the first promise that has resolved.
/// </summary>
IPromise ThenRace(Func<PromisedT, IEnumerable<IPromise>> chain);
}
/// <summary>
/// Interface for a promise that can be rejected.
/// </summary>
public interface IRejectable {
/// <summary>
/// Reject the promise with an exception.
/// </summary>
void Reject(Exception ex);
}
/// <summary>
/// Interface for a promise that can be rejected or resolved.
/// </summary>
public interface IPendingPromise<PromisedT> : IRejectable {
/// <summary>
/// Resolve the promise with a particular value.
/// </summary>
void Resolve(PromisedT value);
}
/// <summary>
/// Specifies the state of a promise.
/// </summary>
public enum PromiseState {
Pending, // The promise is in-flight.
Rejected, // The promise has been rejected.
Resolved // The promise has been resolved.
};
/// <summary>
/// Implements a C# promise.
/// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
/// </summary>
public class Promise<PromisedT> : IPromise<PromisedT>, IPendingPromise<PromisedT>, IPromiseInfo {
/// <summary>
/// The exception when the promise is rejected.
/// </summary>
private Exception rejectionException;
/// <summary>
/// The value when the promises is resolved.
/// </summary>
private PromisedT resolveValue;
/// <summary>
/// Represents a handler invoked when the promise is resolved or rejected.
/// </summary>
public struct Handler<T> {
/// <summary>
/// Callback fn.
/// </summary>
public Action<T> callback;
/// <summary>
/// The promise that is rejected when there is an error while invoking the handler.
/// </summary>
public IRejectable rejectable;
}
/// <summary>
/// Error handler.
/// </summary>
private List<Handler<Exception>> rejectHandlers;
/// <summary>
/// Completed handlers that accept a value.
/// </summary>
private List<Handler<PromisedT>> resolveHandlers;
/// <summary>
/// ID of the promise, useful for debugging.
/// </summary>
public int Id { get; private set; }
/// <summary>
/// Name of the promise, when set, useful for debugging.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Tracks the current state of the promise.
/// </summary>
public PromiseState CurState { get; private set; }
public Promise() {
this.CurState = PromiseState.Pending;
this.Id = ++Promise.nextPromiseId;
if (Promise.EnablePromiseTracking) {
Promise.pendingPromises.Add(this);
}
}
public Promise(Action<Action<PromisedT>, Action<Exception>> resolver) {
this.CurState = PromiseState.Pending;
this.Id = ++Promise.nextPromiseId;
if (Promise.EnablePromiseTracking) {
Promise.pendingPromises.Add(this);
}
try {
resolver(
// Resolve
value => Resolve(value),
// Reject
ex => Reject(ex)
);
}
catch (Exception ex) {
Reject(ex);
}
}
/// <summary>
/// Add a rejection handler for this promise.
/// </summary>
private void AddRejectHandler(Action<Exception> onRejected, IRejectable rejectable) {
if (rejectHandlers == null) {
rejectHandlers = new List<Handler<Exception>>();
}
rejectHandlers.Add(new Handler<Exception>() { callback = onRejected, rejectable = rejectable }); ;
}
/// <summary>
/// Add a resolve handler for this promise.
/// </summary>
private void AddResolveHandler(Action<PromisedT> onResolved, IRejectable rejectable) {
if (resolveHandlers == null) {
resolveHandlers = new List<Handler<PromisedT>>();
}
resolveHandlers.Add(new Handler<PromisedT>() {
callback = onResolved,
rejectable = rejectable
});
}
/// <summary>
/// Invoke a single handler.
/// </summary>
private void InvokeHandler<T>(Action<T> callback, IRejectable rejectable, T value) {
try {
callback(value);
}
catch (Exception ex) {
rejectable.Reject(ex);
}
}
/// <summary>
/// Helper function clear out all handlers after resolution or rejection.
/// </summary>
private void ClearHandlers() {
rejectHandlers = null;
resolveHandlers = null;
}
/// <summary>
/// Invoke all reject handlers.
/// </summary>
private void InvokeRejectHandlers(Exception ex) {
if (rejectHandlers != null) {
rejectHandlers.Each(handler => InvokeHandler(handler.callback, handler.rejectable, ex));
}
ClearHandlers();
}
/// <summary>
/// Invoke all resolve handlers.
/// </summary>
private void InvokeResolveHandlers(PromisedT value) {
if (resolveHandlers != null) {
resolveHandlers.Each(handler => InvokeHandler(handler.callback, handler.rejectable, value));
}
ClearHandlers();
}
/// <summary>
/// Reject the promise with an exception.
/// </summary>
public void Reject(Exception ex) {
if (CurState != PromiseState.Pending) {
throw new ApplicationException("Attempt to reject a promise that is already in state: " + CurState + ", a promise can only be rejected when it is still in state: " + PromiseState.Pending);
}
rejectionException = ex;
CurState = PromiseState.Rejected;
if (Promise.EnablePromiseTracking) {
Promise.pendingPromises.Remove(this);
}
InvokeRejectHandlers(ex);
}
/// <summary>
/// Resolve the promise with a particular value.
/// </summary>
public void Resolve(PromisedT value) {
if (CurState != PromiseState.Pending) {
throw new ApplicationException("Attempt to resolve a promise that is already in state: " + CurState + ", a promise can only be resolved when it is still in state: " + PromiseState.Pending);
}
resolveValue = value;
CurState = PromiseState.Resolved;
if (Promise.EnablePromiseTracking) {
Promise.pendingPromises.Remove(this);
}
InvokeResolveHandlers(value);
}
/// <summary>
/// Completes the promise.
/// onResolved is called on successful completion.
/// onRejected is called on error.
/// </summary>
public void Done(Action<PromisedT> onResolved, Action<Exception> onRejected) {
var resultPromise = new Promise<PromisedT>();
resultPromise.WithName(Name);
ActionHandlers(resultPromise, onResolved, onRejected);
}
/// <summary>
/// Completes the promise.
/// onResolved is called on successful completion.
/// Adds a default error handler.
/// </summary>
public void Done(Action<PromisedT> onResolved) {
var resultPromise = new Promise<PromisedT>();
resultPromise.WithName(Name);
ActionHandlers(resultPromise,
onResolved,
ex => Promise.PropagateUnhandledException(this, ex)
);
}
/// <summary>
/// Complete the promise. Adds a default error handler.
/// </summary>
public void Done() {
var resultPromise = new Promise<PromisedT>();
resultPromise.WithName(Name);
ActionHandlers(resultPromise,
value => { },
ex => Promise.PropagateUnhandledException(this, ex)
);
}
/// <summary>
/// Set the name of the promise, useful for debugging.
/// </summary>
public IPromise<PromisedT> WithName(string name) {
this.Name = name;
return this;
}
/// <summary>
/// Handle errors for the promise.
/// </summary>
public IPromise<PromisedT> Catch(Action<Exception> onRejected) {
var resultPromise = new Promise<PromisedT>();
resultPromise.WithName(Name);
Action<PromisedT> resolveHandler = v => {
resultPromise.Resolve(v);
};
Action<Exception> rejectHandler = ex => {
onRejected(ex);
resultPromise.Reject(ex);
};
ActionHandlers(resultPromise, resolveHandler, rejectHandler);
return resultPromise;
}
/// <summary>
/// Add a resolved callback that chains a value promise (optionally converting to a different value type).
/// </summary>
public IPromise<ConvertedT> Then<ConvertedT>(Func<PromisedT, IPromise<ConvertedT>> onResolved) {
return Then(onResolved, null);
}
/// <summary>
/// Add a resolved callback that chains a non-value promise.
/// </summary>
public IPromise Then(Func<PromisedT, IPromise> onResolved) {
return Then(onResolved, null);
}
/// <summary>
/// Add a resolved callback.
/// </summary>
public IPromise<PromisedT> Then(Action<PromisedT> onResolved) {
return Then(onResolved, null);
}
/// <summary>
/// Add a resolved callback and a rejected callback.
/// The resolved callback chains a value promise (optionally converting to a different value type).
/// </summary>
public IPromise<ConvertedT> Then<ConvertedT>(Func<PromisedT, IPromise<ConvertedT>> onResolved, Action<Exception> onRejected) {
// This version of the function must supply an onResolved.
// Otherwise there is now way to get the converted value to pass to the resulting promise.
var resultPromise = new Promise<ConvertedT>();
resultPromise.WithName(Name);
Action<PromisedT> resolveHandler = v => {
onResolved(v)
.Then(
(ConvertedT chainedValue) => resultPromise.Resolve(chainedValue),
ex => resultPromise.Reject(ex)
)
.Done();
};
Action<Exception> rejectHandler = ex => {
if (onRejected != null) {
onRejected(ex);
}
resultPromise.Reject(ex);
};
ActionHandlers(resultPromise, resolveHandler, rejectHandler);
return resultPromise;
}
/// <summary>
/// Add a resolved callback and a rejected callback.
/// The resolved callback chains a non-value promise.
/// </summary>
public IPromise Then(Func<PromisedT, IPromise> onResolved, Action<Exception> onRejected) {
var resultPromise = new Promise();
resultPromise.WithName(Name);
Action<PromisedT> resolveHandler = v => {
if (onResolved != null) {
onResolved(v)
.Then(
() => resultPromise.Resolve(),
ex => resultPromise.Reject(ex)
)
.Done();
}
else {
resultPromise.Resolve();
}
};
Action<Exception> rejectHandler = ex => {
if (onRejected != null) {
onRejected(ex);
}
resultPromise.Reject(ex);
};
ActionHandlers(resultPromise, resolveHandler, rejectHandler);
return resultPromise;
}
/// <summary>
/// Add a resolved callback and a rejected callback.
/// </summary>
public IPromise<PromisedT> Then(Action<PromisedT> onResolved, Action<Exception> onRejected) {
var resultPromise = new Promise<PromisedT>();
resultPromise.WithName(Name);
Action<PromisedT> resolveHandler = v => {
if (onResolved != null) {
onResolved(v);
}
resultPromise.Resolve(v);
};
Action<Exception> rejectHandler = ex => {
if (onRejected != null) {
onRejected(ex);
}
resultPromise.Reject(ex);
};
ActionHandlers(resultPromise, resolveHandler, rejectHandler);
return resultPromise;
}
/// <summary>
/// Return a new promise with a different value.
/// May also change the type of the value.
/// </summary>
public IPromise<ConvertedT> Transform<ConvertedT>(Func<PromisedT, ConvertedT> transform) {
var resultPromise = new Promise<ConvertedT>();
resultPromise.WithName(Name);
Action<PromisedT> resolveHandler = v => {
resultPromise.Resolve(transform(v));
};
Action<Exception> rejectHandler = ex => {
resultPromise.Reject(ex);
};
ActionHandlers(resultPromise, resolveHandler, rejectHandler);
return resultPromise;
}
/// <summary>
/// Helper function to invoke or register resolve/reject handlers.
/// </summary>
private void ActionHandlers(IRejectable resultPromise, Action<PromisedT> resolveHandler, Action<Exception> rejectHandler) {
if (CurState == PromiseState.Resolved) {
InvokeHandler(resolveHandler, resultPromise, resolveValue);
}
else if (CurState == PromiseState.Rejected) {
InvokeHandler(rejectHandler, resultPromise, rejectionException);
}
else {
AddResolveHandler(resolveHandler, resultPromise);
AddRejectHandler(rejectHandler, resultPromise);
}
}
/// <summary>
/// Chain an enumerable of promises, all of which must resolve.
/// Returns a promise for a collection of the resolved results.
/// The resulting promise is resolved when all of the promises have resolved.
/// It is rejected as soon as any of the promises have been rejected.
/// </summary>
public IPromise<IEnumerable<ConvertedT>> ThenAll<ConvertedT>(Func<PromisedT, IEnumerable<IPromise<ConvertedT>>> chain) {
return Then(value => Promise<ConvertedT>.All(chain(value)));
}
/// <summary>
/// Chain an enumerable of promises, all of which must resolve.
/// Converts to a non-value promise.
/// The resulting promise is resolved when all of the promises have resolved.
/// It is rejected as soon as any of the promises have been rejected.
/// </summary>
public IPromise ThenAll(Func<PromisedT, IEnumerable<IPromise>> chain) {
return Then(value => Promise.All(chain(value)));
}
/// <summary>
/// Returns a promise that resolves when all of the promises in the enumerable argument have resolved.
/// Returns a promise of a collection of the resolved results.
/// </summary>
public static IPromise<IEnumerable<PromisedT>> All(params IPromise<PromisedT>[] promises) {
return All((IEnumerable<IPromise<PromisedT>>)promises); // Cast is required to force use of the other All function.
}
/// <summary>
/// Returns a promise that resolves when all of the promises in the enumerable argument have resolved.
/// Returns a promise of a collection of the resolved results.
/// </summary>
public static IPromise<IEnumerable<PromisedT>> All(IEnumerable<IPromise<PromisedT>> promises) {
var promisesArray = promises.ToArray();
if (promisesArray.Length == 0) {
return Promise<IEnumerable<PromisedT>>.Resolved(new List<PromisedT>());
}
var remainingCount = promisesArray.Length;
var results = new PromisedT[remainingCount];
var resultPromise = new Promise<IEnumerable<PromisedT>>();
resultPromise.WithName("All");
promisesArray.Each((promise, index) => {
promise
.Catch(ex => {
if (resultPromise.CurState == PromiseState.Pending) {
// If a promise errorred and the result promise is still pending, reject it.
resultPromise.Reject(ex);
}
})
.Then(result => {
results[index] = result;
--remainingCount;
if (remainingCount <= 0) {
// This will never happen if any of the promises errorred.
resultPromise.Resolve(results);
}
})
.Done();
});
return resultPromise;
}
/// <summary>
/// Takes a function that yields an enumerable of promises.
/// Returns a promise that resolves when the first of the promises has resolved.
/// Yields the value from the first promise that has resolved.
/// </summary>
public IPromise<ConvertedT> ThenRace<ConvertedT>(Func<PromisedT, IEnumerable<IPromise<ConvertedT>>> chain) {
return Then(value => Promise<ConvertedT>.Race(chain(value)));
}
/// <summary>
/// Takes a function that yields an enumerable of promises.
/// Converts to a non-value promise.
/// Returns a promise that resolves when the first of the promises has resolved.
/// Yields the value from the first promise that has resolved.
/// </summary>
public IPromise ThenRace(Func<PromisedT, IEnumerable<IPromise>> chain) {
return Then(value => Promise.Race(chain(value)));
}
/// <summary>
/// Returns a promise that resolves when the first of the promises in the enumerable argument have resolved.
/// Returns the value from the first promise that has resolved.
/// </summary>
public static IPromise<PromisedT> Race(params IPromise<PromisedT>[] promises) {
return Race((IEnumerable<IPromise<PromisedT>>)promises); // Cast is required to force use of the other function.
}
/// <summary>
/// Returns a promise that resolves when the first of the promises in the enumerable argument have resolved.
/// Returns the value from the first promise that has resolved.
/// </summary>
public static IPromise<PromisedT> Race(IEnumerable<IPromise<PromisedT>> promises) {
var promisesArray = promises.ToArray();
if (promisesArray.Length == 0) {
throw new ApplicationException("At least 1 input promise must be provided for Race");
}
var resultPromise = new Promise<PromisedT>();
resultPromise.WithName("Race");
promisesArray.Each((promise, index) => {
promise
.Catch(ex => {
if (resultPromise.CurState == PromiseState.Pending) {
// If a promise errorred and the result promise is still pending, reject it.
resultPromise.Reject(ex);
}
})
.Then(result => {
if (resultPromise.CurState == PromiseState.Pending) {
resultPromise.Resolve(result);
}
})
.Done();
});
return resultPromise;
}
public override string ToString() {
return base.ToString() + ", State: " + CurState.ToString() + ", Res: " + (resolveHandlers != null ? resolveHandlers.Count : 0) + ", Rej: " + (rejectHandlers != null ? rejectHandlers.Count : 0);
}
/// <summary>
/// Convert a simple value directly into a resolved promise.
/// </summary>
public static IPromise<PromisedT> Resolved(PromisedT promisedValue) {
var promise = new Promise<PromisedT>();
promise.Resolve(promisedValue);
return promise;
}
/// <summary>
/// Convert an exception directly into a rejected promise.
/// </summary>
public static IPromise<PromisedT> Rejected(Exception ex) {
var promise = new Promise<PromisedT>();
promise.Reject(ex);
return promise;
}
}
}
| |
/***************************************************************************
* StandardSaveStrategy.cs
* -------------------
* begin : May 1, 2002
* copyright : (C) The RunUO Software Team
* email : info@runuo.com
*
* $Id: StandardSaveStrategy.cs 828 2012-02-11 04:36:54Z asayre $
*
***************************************************************************/
/***************************************************************************
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
***************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
using System.Diagnostics;
using Server;
using Server.Guilds;
namespace Server
{
public class StandardSaveStrategy : SaveStrategy
{
public enum SaveOption
{
Normal,
Threaded
}
public static SaveOption SaveType = SaveOption.Normal;
public override string Name
{
get { return "Standard"; }
}
private Queue<Item> _decayQueue;
private bool _permitBackgroundWrite;
public StandardSaveStrategy()
{
_decayQueue = new Queue<Item>();
}
protected bool PermitBackgroundWrite { get { return _permitBackgroundWrite; } set { _permitBackgroundWrite = value; } }
protected bool UseSequentialWriters { get { return (StandardSaveStrategy.SaveType == SaveOption.Normal || !_permitBackgroundWrite); } }
public override void Save(SaveMetrics metrics, bool permitBackgroundWrite)
{
_permitBackgroundWrite = permitBackgroundWrite;
SaveMobiles(metrics);
SaveItems(metrics);
SaveGuilds(metrics);
if (permitBackgroundWrite && UseSequentialWriters) //If we're permitted to write in the background, but we don't anyways, then notify.
World.NotifyDiskWriteComplete();
}
protected void SaveMobiles(SaveMetrics metrics)
{
Dictionary<Serial, Mobile> mobiles = World.Mobiles;
GenericWriter idx;
GenericWriter tdb;
GenericWriter bin;
if (UseSequentialWriters)
{
idx = new BinaryFileWriter(World.MobileIndexPath, false);
tdb = new BinaryFileWriter(World.MobileTypesPath, false);
bin = new BinaryFileWriter(World.MobileDataPath, true);
}
else
{
idx = new AsyncWriter(World.MobileIndexPath, false);
tdb = new AsyncWriter(World.MobileTypesPath, false);
bin = new AsyncWriter(World.MobileDataPath, true);
}
idx.Write((int)mobiles.Count);
foreach (Mobile m in mobiles.Values)
{
long start = bin.Position;
idx.Write((int)m.m_TypeRef);
idx.Write((int)m.Serial);
idx.Write((long)start);
m.Serialize(bin);
if (metrics != null)
{
metrics.OnMobileSaved((int)(bin.Position - start));
}
idx.Write((int)(bin.Position - start));
m.FreeCache();
}
tdb.Write((int)World.m_MobileTypes.Count);
for (int i = 0; i < World.m_MobileTypes.Count; ++i)
tdb.Write(World.m_MobileTypes[i].FullName);
idx.Close();
tdb.Close();
bin.Close();
}
protected void SaveItems(SaveMetrics metrics)
{
Dictionary<Serial, Item> items = World.Items;
GenericWriter idx;
GenericWriter tdb;
GenericWriter bin;
if (UseSequentialWriters)
{
idx = new BinaryFileWriter(World.ItemIndexPath, false);
tdb = new BinaryFileWriter(World.ItemTypesPath, false);
bin = new BinaryFileWriter(World.ItemDataPath, true);
}
else
{
idx = new AsyncWriter(World.ItemIndexPath, false);
tdb = new AsyncWriter(World.ItemTypesPath, false);
bin = new AsyncWriter(World.ItemDataPath, true);
}
idx.Write((int)items.Count);
foreach (Item item in items.Values)
{
if (item.Decays && item.Parent == null && item.Map != Map.Internal && (item.LastMoved + item.DecayTime) <= DateTime.Now)
{
_decayQueue.Enqueue(item);
}
long start = bin.Position;
idx.Write((int)item.m_TypeRef);
idx.Write((int)item.Serial);
idx.Write((long)start);
item.Serialize(bin);
if (metrics != null)
{
metrics.OnItemSaved((int)(bin.Position - start));
}
idx.Write((int)(bin.Position - start));
item.FreeCache();
}
tdb.Write((int)World.m_ItemTypes.Count);
for (int i = 0; i < World.m_ItemTypes.Count; ++i)
tdb.Write(World.m_ItemTypes[i].FullName);
idx.Close();
tdb.Close();
bin.Close();
}
protected void SaveGuilds(SaveMetrics metrics)
{
GenericWriter idx;
GenericWriter bin;
if (UseSequentialWriters)
{
idx = new BinaryFileWriter(World.GuildIndexPath, false);
bin = new BinaryFileWriter(World.GuildDataPath, true);
}
else
{
idx = new AsyncWriter(World.GuildIndexPath, false);
bin = new AsyncWriter(World.GuildDataPath, true);
}
idx.Write((int)BaseGuild.List.Count);
foreach (BaseGuild guild in BaseGuild.List.Values)
{
long start = bin.Position;
idx.Write((int)0);//guilds have no typeid
idx.Write((int)guild.Id);
idx.Write((long)start);
guild.Serialize(bin);
if (metrics != null)
{
metrics.OnGuildSaved((int)(bin.Position - start));
}
idx.Write((int)(bin.Position - start));
}
idx.Close();
bin.Close();
}
public override void ProcessDecay()
{
while (_decayQueue.Count > 0)
{
Item item = _decayQueue.Dequeue();
if (item.OnDecay())
{
item.Delete();
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using SIL.IO;
using SIL.PlatformUtilities;
using SIL.Reflection;
namespace SIL.Reporting
{
public interface IErrorReporter
{
void ReportFatalException(Exception e);
ErrorResult NotifyUserOfProblem(IRepeatNoticePolicy policy,
string alternateButton1Label,
ErrorResult resultIfAlternateButtonPressed,
string message);
void ReportNonFatalException(Exception exception, IRepeatNoticePolicy policy);
void ReportNonFatalExceptionWithMessage(Exception error, string message, params object[] args);
void ReportNonFatalMessageWithStackTrace(string message, params object[] args);
void ReportFatalMessageWithStackTrace(string message, object[] args);
}
public enum ErrorResult
{
None,
OK,
Cancel,
Abort,
Retry,
Ignore,
Yes,
No
}
public class ErrorReport
{
#region Windows8PlusVersionReportingSupport
[DllImport("netapi32.dll", CharSet = CharSet.Auto)]
static extern int NetWkstaGetInfo(string server,
int level,
out IntPtr info);
[DllImport("netapi32.dll")]
static extern int NetApiBufferFree(IntPtr pBuf);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
struct MachineInfo
{
public int platform_id;
[MarshalAs(UnmanagedType.LPWStr)]
public string _computerName;
[MarshalAs(UnmanagedType.LPWStr)]
public string _languageGroup;
public int _majorVersion;
public int _minorVersion;
}
/// <summary>
/// An application can avoid the need of this method by adding/modifying the application manifest to declare support for a
/// particular windows version. This code is still necessary to report usefully about versions of windows released after
/// the application has shipped.
/// </summary>
public static string GetWindowsVersionInfoFromNetworkAPI()
{
IntPtr pBuffer;
// Get the version information from the network api, passing null to get network info from this machine
var retval = NetWkstaGetInfo(null, 100, out pBuffer);
if(retval != 0)
return "Windows Unknown(unidentifiable)";
var info = (MachineInfo)Marshal.PtrToStructure(pBuffer, typeof(MachineInfo));
string windowsVersion = null;
if(info._majorVersion == 6)
{
if(info._minorVersion == 2)
windowsVersion = "Windows 8";
else if(info._minorVersion == 3)
windowsVersion = "Windows 8.1";
}
else if(info._majorVersion == 10 && info._minorVersion == 0)
{
windowsVersion = "Windows 10";
}
else
{
windowsVersion = string.Format("Windows Unknown({0}.{1})", info._majorVersion, info._minorVersion);
}
NetApiBufferFree(pBuffer);
return windowsVersion;
}
#endregion
private static IErrorReporter _errorReporter;
//We removed all references to Winforms from Palaso.dll but our error reporting relied heavily on it.
//Not wanting to break existing applications we have now added this class initializer which will
//look for a reference to SIL.Windows.Forms in the consuming app and if it exists instantiate the
//WinformsErrorReporter from there through Reflection. otherwise we will simply use a console
//error reporter
static ErrorReport()
{
_errorReporter = ExceptionHandler.GetObjectFromSilWindowsForms<IErrorReporter>() ?? new ConsoleErrorReporter();
}
/// <summary>
/// Use this method if you want to override the default IErrorReporter.
/// This method should normally be called only once at application startup.
/// </summary>
public static void SetErrorReporter(IErrorReporter reporter)
{
_errorReporter = reporter ?? new ConsoleErrorReporter();
}
protected static string s_emailAddress = null;
protected static string s_emailSubject = "Exception Report";
/// <summary>
/// a list of name, string value pairs that will be included in the details of the error report.
/// </summary>
private static Dictionary<string, string> s_properties =
new Dictionary<string, string>();
private static bool s_isOkToInteractWithUser = true;
private static bool s_justRecordNonFatalMessagesForTesting=false;
private static string s_previousNonFatalMessage;
private static Exception s_previousNonFatalException;
public static void Init(string emailAddress)
{
s_emailAddress = emailAddress;
ErrorReport.AddStandardProperties();
}
private static void UpdateEmailSubject(Exception error)
{
var subject = new StringBuilder();
subject.AppendFormat("Exception: {0}", error.Message);
try
{
subject.AppendFormat(" in {0}", error.Source);
}
catch {}
s_emailSubject = subject.ToString();
}
/// ------------------------------------------------------------------------------------
/// <summary>
///
/// </summary>
/// <param name="error"></param>
/// <returns></returns>
/// ------------------------------------------------------------------------------------
public static string GetExceptionText(Exception error)
{
UpdateEmailSubject(error);
return ExceptionHelper.GetExceptionText(error);
}
public static string GetVersionForErrorReporting()
{
return ReflectionHelper.LongVersionNumberString;
}
public static object GetAssemblyAttribute(Type attributeType)
{
Assembly assembly = Assembly.GetEntryAssembly();
if (assembly != null)
{
object[] attributes =
assembly.GetCustomAttributes(attributeType, false);
if (attributes != null && attributes.Length > 0)
{
return attributes[0];
}
}
return null;
}
public static string VersionNumberString => ReflectionHelper.VersionNumberString;
public static string UserFriendlyVersionString
{
get
{
var asm = Assembly.GetEntryAssembly();
var ver = asm.GetName().Version;
var file = PathHelper.StripFilePrefix(asm.CodeBase);
var fi = new FileInfo(file);
return string.Format(
"Version {0}.{1}.{2} Built on {3}",
ver.Major,
ver.Minor,
ver.Build,
fi.CreationTime.ToString("dd-MMM-yyyy")
);
}
}
/// <summary>
/// use this in unit tests to cleanly check that a message would have been shown.
/// E.g. using (new Palaso.Reporting.ErrorReport.NonFatalErrorReportExpected()) {...}
/// </summary>
public class NonFatalErrorReportExpected :IDisposable
{
private readonly bool previousJustRecordNonFatalMessagesForTesting;
public NonFatalErrorReportExpected()
{
previousJustRecordNonFatalMessagesForTesting = s_justRecordNonFatalMessagesForTesting;
s_justRecordNonFatalMessagesForTesting = true;
s_previousNonFatalMessage = null;//this is a static, so a previous unit test could have filled it with something (yuck)
}
public void Dispose()
{
s_justRecordNonFatalMessagesForTesting= previousJustRecordNonFatalMessagesForTesting;
if (s_previousNonFatalException == null && s_previousNonFatalMessage == null)
throw new Exception("Non Fatal Error Report was expected but wasn't generated.");
s_previousNonFatalMessage = null;
}
/// <summary>
/// use this to check the actual contents of the message that was triggered
/// </summary>
public string Message
{
get { return s_previousNonFatalMessage; }
}
}
/// <summary>
/// use this in unit tests to cleanly check that a message would have been shown.
/// E.g. using (new Palaso.Reporting.ErrorReport.NonFatalErrorReportExpected()) {...}
/// </summary>
public class NoNonFatalErrorReportExpected : IDisposable
{
private readonly bool previousJustRecordNonFatalMessagesForTesting;
public NoNonFatalErrorReportExpected()
{
previousJustRecordNonFatalMessagesForTesting = s_justRecordNonFatalMessagesForTesting;
s_justRecordNonFatalMessagesForTesting = true;
s_previousNonFatalMessage = null;//this is a static, so a previous unit test could have filled it with something (yuck)
s_previousNonFatalException = null;
}
public void Dispose()
{
s_justRecordNonFatalMessagesForTesting = previousJustRecordNonFatalMessagesForTesting;
if (s_previousNonFatalException != null || s_previousNonFatalMessage != null)
throw new Exception("Non Fatal Error Report was not expected but was generated: "+Message);
s_previousNonFatalMessage = null;
}
/// <summary>
/// use this to check the actual contents of the message that was triggered
/// </summary>
public string Message
{
get { return s_previousNonFatalMessage; }
}
}
/// <summary>
/// set this property if you want the dialog to offer to create an e-mail message.
/// </summary>
public static string EmailAddress
{
set { s_emailAddress = value; }
get { return s_emailAddress; }
}
/// <summary>
/// set this property if you want something other than the default e-mail subject
/// </summary>
public static string EmailSubject
{
set { s_emailSubject = value; }
get { return s_emailSubject; }
}
/// <summary>
/// a list of name, string value pairs that will be included in the details of the error report.
/// </summary>
public static Dictionary<string, string> Properties
{
get
{
return s_properties;
}
set
{
s_properties = value;
}
}
public static bool IsOkToInteractWithUser
{
get
{
return s_isOkToInteractWithUser;
}
set
{
s_isOkToInteractWithUser = value;
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// add a property that he would like included in any bug reports created by this application.
/// </summary>
/// ------------------------------------------------------------------------------------
public static void AddProperty(string label, string contents)
{
//avoid an error if the user changes the value of something,
//which happens in FieldWorks, for example, when you change the language project.
if (s_properties.ContainsKey(label))
{
s_properties.Remove(label);
}
s_properties.Add(label, contents);
}
public static void AddStandardProperties()
{
AddProperty("Version", ErrorReport.GetVersionForErrorReporting());
AddProperty("CommandLine", Environment.CommandLine);
AddProperty("CurrentDirectory", Environment.CurrentDirectory);
AddProperty("MachineName", Environment.MachineName);
AddProperty("OSVersion", GetOperatingSystemLabel());
if (Platform.IsUnix)
AddProperty("DesktopEnvironment", Platform.DesktopEnvironmentInfoString);
AddProperty("DotNetVersion", Environment.Version.ToString());
AddProperty("WorkingSet", Environment.WorkingSet.ToString());
AddProperty("UserDomainName", Environment.UserDomainName);
AddProperty("UserName", Environment.UserName);
AddProperty("Culture", CultureInfo.CurrentCulture.ToString());
}
/// <summary>
/// Get the standard properties in a form suitable for other uses
/// (such as analytics).
/// </summary>
public static Dictionary<string, string> GetStandardProperties()
{
var props = new Dictionary<string,string>();
props.Add("Version", ErrorReport.GetVersionForErrorReporting());
props.Add("CommandLine", Environment.CommandLine);
props.Add("CurrentDirectory", Environment.CurrentDirectory);
props.Add("MachineName", Environment.MachineName);
props.Add("OSVersion", GetOperatingSystemLabel());
if (Platform.IsUnix)
props.Add("DesktopEnvironment", Platform.DesktopEnvironmentInfoString);
props.Add("DotNetVersion", Environment.Version.ToString());
props.Add("WorkingSet", Environment.WorkingSet.ToString());
props.Add("UserDomainName", Environment.UserDomainName);
props.Add("UserName", Environment.UserName);
props.Add("Culture", CultureInfo.CurrentCulture.ToString());
return props;
}
class Version
{
private readonly PlatformID _platform;
private readonly int _major;
private readonly int _minor;
public string Label { get; private set; }
public Version(PlatformID platform, int major, int minor, string label)
{
_platform = platform;
_major = major;
_minor = minor;
Label = label;
}
public bool Match(OperatingSystem os)
{
return os.Version.Minor == _minor &&
os.Version.Major == _major &&
os.Platform == _platform;
}
}
public static string GetOperatingSystemLabel()
{
if (Environment.OSVersion.Platform == PlatformID.Unix)
{
var startInfo = new ProcessStartInfo("lsb_release", "-si -sr -sc");
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
var proc = new Process { StartInfo = startInfo };
try
{
proc.Start();
proc.WaitForExit(500);
if(proc.ExitCode == 0)
{
var si = proc.StandardOutput.ReadLine();
var sr = proc.StandardOutput.ReadLine();
var sc = proc.StandardOutput.ReadLine();
return String.Format("{0} {1} {2}", si, sr, sc);
}
}
catch (Exception)
{
// lsb_release should work on all supported versions but fall back to the OSVersion.VersionString
}
}
else
{
// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724832%28v=vs.85%29.aspx
var list = new List<Version>();
list.Add(new Version(PlatformID.Win32NT, 5, 0, "Windows 2000"));
list.Add(new Version(PlatformID.Win32NT, 5, 1, "Windows XP"));
list.Add(new Version(PlatformID.Win32NT, 6, 0, "Vista"));
list.Add(new Version(PlatformID.Win32NT, 6, 1, "Windows 7"));
// After Windows 8 the Environment.OSVersion started misreporting information unless
// your app has a manifest which says it supports the OS it is running on. This is not
// helpful if someone starts using an app built before the OS is released. Anything that
// reports its self as Windows 8 is suspect, and must get the version info another way.
list.Add(new Version(PlatformID.Win32NT, 6, 3, "Windows 8.1"));
list.Add(new Version(PlatformID.Win32NT, 10, 0, "Windows 10"));
foreach (var version in list)
{
if (version.Match(Environment.OSVersion))
return version.Label + " " + Environment.OSVersion.ServicePack;
}
// Handle any as yet unrecognized (possibly unmanifested) versions, or anything that reported its self as Windows 8.
if(Environment.OSVersion.Platform == PlatformID.Win32NT)
{
return GetWindowsVersionInfoFromNetworkAPI() + " " + Environment.OSVersion.ServicePack;
}
}
return Environment.OSVersion.VersionString;
}
public static string GetHiearchicalExceptionInfo(Exception error, ref Exception innerMostException)
{
UpdateEmailSubject(error);
return ExceptionHelper.GetHiearchicalExceptionInfo(error, ref innerMostException);
}
public static void ReportFatalException(Exception error)
{
UsageReporter.ReportException(true, null, error, null);
_errorReporter.ReportFatalException(error);
}
/// <summary>
/// Put up a message box, unless OkToInteractWithUser is false, in which case throw an Appliciation Exception.
/// This will not report the problem to the developer. Use one of the "report" methods for that.
/// </summary>
public static void NotifyUserOfProblem(string message, params object[] args)
{
NotifyUserOfProblem(new ShowAlwaysPolicy(), message, args);
}
public static ErrorResult NotifyUserOfProblem(IRepeatNoticePolicy policy, string messageFmt, params object[] args)
{
return NotifyUserOfProblem(policy, null, default(ErrorResult), messageFmt, args);
}
public static void NotifyUserOfProblem(Exception error, string messageFmt, params object[] args)
{
NotifyUserOfProblem(new ShowAlwaysPolicy(), error, messageFmt, args);
}
public static void NotifyUserOfProblem(IRepeatNoticePolicy policy, Exception error, string messageFmt, params object[] args)
{
var result = NotifyUserOfProblem(policy, "Details", ErrorResult.Yes, messageFmt, args);
if (result == ErrorResult.Yes)
{
ErrorReport.ReportNonFatalExceptionWithMessage(error, string.Format(messageFmt, args));
}
UsageReporter.ReportException(false, null, error, String.Format(messageFmt, args));
}
public static ErrorResult NotifyUserOfProblem(IRepeatNoticePolicy policy,
string alternateButton1Label,
ErrorResult resultIfAlternateButtonPressed,
string messageFmt,
params object[] args)
{
var message = string.Format(messageFmt, args);
if (s_justRecordNonFatalMessagesForTesting)
{
s_previousNonFatalMessage = message;
return ErrorResult.OK;
}
return _errorReporter.NotifyUserOfProblem(policy, alternateButton1Label, resultIfAlternateButtonPressed, message);
}
/// <summary>
/// Bring up a "yellow box" that let's them send in a report, then return to the program.
/// </summary>
public static void ReportNonFatalExceptionWithMessage(Exception error, string message, params object[] args)
{
s_previousNonFatalMessage = message;
s_previousNonFatalException = error;
_errorReporter.ReportNonFatalExceptionWithMessage(error, message, args);
}
/// <summary>
/// Bring up a "yellow box" that let's them send in a report, then return to the program.
/// Use this one only when you don't have an exception (else you're not reporting the exception's message)
/// </summary>
public static void ReportNonFatalMessageWithStackTrace(string message, params object[] args)
{
s_previousNonFatalMessage = message;
_errorReporter.ReportNonFatalMessageWithStackTrace(message, args);
}
/// <summary>
/// Bring up a "green box" that let's them send in a report, then exit.
/// </summary>
public static void ReportFatalMessageWithStackTrace(string message, params object[] args)
{
_errorReporter.ReportFatalMessageWithStackTrace(message, args);
}
/// <summary>
/// Bring up a "yellow box" that lets them send in a report, then return to the program.
/// </summary>
public static void ReportNonFatalException(Exception exception)
{
ReportNonFatalException(exception, new ShowAlwaysPolicy());
}
/// <summary>
/// Allow user to report an exception even though the program doesn't need to exit
/// </summary>
public static void ReportNonFatalException(Exception exception, IRepeatNoticePolicy policy)
{
if (s_justRecordNonFatalMessagesForTesting)
{
ErrorReport.s_previousNonFatalException = exception;
return;
}
_errorReporter.ReportNonFatalException(exception, policy);
UsageReporter.ReportException(false, null, exception, null);
}
/// <summary>
/// this is for interacting with test code which doesn't want to allow an actual UI
/// </summary>
public class ProblemNotificationSentToUserException : ApplicationException
{
public ProblemNotificationSentToUserException(string message) : base(message) {}
}
/// <summary>
/// this is for interacting with test code which doesn't want to allow an actual UI
/// </summary>
public class NonFatalExceptionWouldHaveBeenMessageShownToUserException : ApplicationException
{
public NonFatalExceptionWouldHaveBeenMessageShownToUserException(Exception e) : base(e.Message, e) { }
}
}
public interface IRepeatNoticePolicy
{
bool ShouldShowErrorReportDialog(Exception exception);
bool ShouldShowMessage(string message);
string ReoccurenceMessage
{ get;
}
}
public class ShowAlwaysPolicy :IRepeatNoticePolicy
{
public bool ShouldShowErrorReportDialog(Exception exception)
{
return true;
}
public bool ShouldShowMessage(string message)
{
return true;
}
public string ReoccurenceMessage
{
get { return string.Empty; }
}
}
public class ShowOncePerSessionBasedOnExactMessagePolicy :IRepeatNoticePolicy
{
private static List<string> _alreadyReportedMessages = new List<string>();
public bool ShouldShowErrorReportDialog(Exception exception)
{
return ShouldShowMessage(exception.Message);
}
public bool ShouldShowMessage(string message)
{
if(_alreadyReportedMessages.Contains(message))
return false;
_alreadyReportedMessages.Add(message);
return true;
}
public string ReoccurenceMessage
{
get { return "This message will not be shown again this session."; }
}
public static void Reset()
{
_alreadyReportedMessages.Clear();
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V9.Resources;
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V9.Resources
{
/// <summary>Resource name for the <c>CustomizerAttribute</c> resource.</summary>
public sealed partial class CustomizerAttributeName : gax::IResourceName, sys::IEquatable<CustomizerAttributeName>
{
/// <summary>The possible contents of <see cref="CustomizerAttributeName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/customizerAttributes/{customizer_attribute_id}</c>
/// .
/// </summary>
CustomerCustomizerAttribute = 1,
}
private static gax::PathTemplate s_customerCustomizerAttribute = new gax::PathTemplate("customers/{customer_id}/customizerAttributes/{customizer_attribute_id}");
/// <summary>Creates a <see cref="CustomizerAttributeName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="CustomizerAttributeName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static CustomizerAttributeName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new CustomizerAttributeName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="CustomizerAttributeName"/> with the pattern
/// <c>customers/{customer_id}/customizerAttributes/{customizer_attribute_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="customizerAttributeId">
/// The <c>CustomizerAttribute</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// A new instance of <see cref="CustomizerAttributeName"/> constructed from the provided ids.
/// </returns>
public static CustomizerAttributeName FromCustomerCustomizerAttribute(string customerId, string customizerAttributeId) =>
new CustomizerAttributeName(ResourceNameType.CustomerCustomizerAttribute, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), customizerAttributeId: gax::GaxPreconditions.CheckNotNullOrEmpty(customizerAttributeId, nameof(customizerAttributeId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CustomizerAttributeName"/> with pattern
/// <c>customers/{customer_id}/customizerAttributes/{customizer_attribute_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="customizerAttributeId">
/// The <c>CustomizerAttribute</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="CustomizerAttributeName"/> with pattern
/// <c>customers/{customer_id}/customizerAttributes/{customizer_attribute_id}</c>.
/// </returns>
public static string Format(string customerId, string customizerAttributeId) =>
FormatCustomerCustomizerAttribute(customerId, customizerAttributeId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CustomizerAttributeName"/> with pattern
/// <c>customers/{customer_id}/customizerAttributes/{customizer_attribute_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="customizerAttributeId">
/// The <c>CustomizerAttribute</c> ID. Must not be <c>null</c> or empty.
/// </param>
/// <returns>
/// The string representation of this <see cref="CustomizerAttributeName"/> with pattern
/// <c>customers/{customer_id}/customizerAttributes/{customizer_attribute_id}</c>.
/// </returns>
public static string FormatCustomerCustomizerAttribute(string customerId, string customizerAttributeId) =>
s_customerCustomizerAttribute.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(customizerAttributeId, nameof(customizerAttributeId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="CustomizerAttributeName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/customizerAttributes/{customizer_attribute_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="customizerAttributeName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="CustomizerAttributeName"/> if successful.</returns>
public static CustomizerAttributeName Parse(string customizerAttributeName) => Parse(customizerAttributeName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="CustomizerAttributeName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/customizerAttributes/{customizer_attribute_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="customizerAttributeName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="CustomizerAttributeName"/> if successful.</returns>
public static CustomizerAttributeName Parse(string customizerAttributeName, bool allowUnparsed) =>
TryParse(customizerAttributeName, allowUnparsed, out CustomizerAttributeName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CustomizerAttributeName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/customizerAttributes/{customizer_attribute_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="customizerAttributeName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CustomizerAttributeName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string customizerAttributeName, out CustomizerAttributeName result) =>
TryParse(customizerAttributeName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CustomizerAttributeName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>customers/{customer_id}/customizerAttributes/{customizer_attribute_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="customizerAttributeName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CustomizerAttributeName"/>, or <c>null</c> if parsing
/// failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string customizerAttributeName, bool allowUnparsed, out CustomizerAttributeName result)
{
gax::GaxPreconditions.CheckNotNull(customizerAttributeName, nameof(customizerAttributeName));
gax::TemplatedResourceName resourceName;
if (s_customerCustomizerAttribute.TryParseName(customizerAttributeName, out resourceName))
{
result = FromCustomerCustomizerAttribute(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(customizerAttributeName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private CustomizerAttributeName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string customizerAttributeId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CustomerId = customerId;
CustomizerAttributeId = customizerAttributeId;
}
/// <summary>
/// Constructs a new instance of a <see cref="CustomizerAttributeName"/> class from the component parts of
/// pattern <c>customers/{customer_id}/customizerAttributes/{customizer_attribute_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="customizerAttributeId">
/// The <c>CustomizerAttribute</c> ID. Must not be <c>null</c> or empty.
/// </param>
public CustomizerAttributeName(string customerId, string customizerAttributeId) : this(ResourceNameType.CustomerCustomizerAttribute, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), customizerAttributeId: gax::GaxPreconditions.CheckNotNullOrEmpty(customizerAttributeId, nameof(customizerAttributeId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { get; }
/// <summary>
/// The <c>CustomizerAttribute</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed
/// resource name.
/// </summary>
public string CustomizerAttributeId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.CustomerCustomizerAttribute: return s_customerCustomizerAttribute.Expand(CustomerId, CustomizerAttributeId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as CustomizerAttributeName);
/// <inheritdoc/>
public bool Equals(CustomizerAttributeName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(CustomizerAttributeName a, CustomizerAttributeName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(CustomizerAttributeName a, CustomizerAttributeName b) => !(a == b);
}
public partial class CustomizerAttribute
{
/// <summary>
/// <see cref="gagvr::CustomizerAttributeName"/>-typed view over the <see cref="ResourceName"/> resource name
/// property.
/// </summary>
internal CustomizerAttributeName ResourceNameAsCustomizerAttributeName
{
get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::CustomizerAttributeName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagvr::CustomizerAttributeName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
internal CustomizerAttributeName CustomizerAttributeName
{
get => string.IsNullOrEmpty(Name) ? null : gagvr::CustomizerAttributeName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using System;
using Csla;
using ParentLoad.DataAccess;
using ParentLoad.DataAccess.ERCLevel;
namespace ParentLoad.Business.ERCLevel
{
/// <summary>
/// B05_SubContinent_ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="B05_SubContinent_ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="B04_SubContinent"/> collection.
/// </remarks>
[Serializable]
public partial class B05_SubContinent_ReChild : BusinessBase<B05_SubContinent_ReChild>
{
#region State Fields
[NotUndoable]
[NonSerialized]
internal int subContinent_ID2 = 0;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="SubContinent_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> SubContinent_Child_NameProperty = RegisterProperty<string>(p => p.SubContinent_Child_Name, "Sub Continent Child Name");
/// <summary>
/// Gets or sets the Sub Continent Child Name.
/// </summary>
/// <value>The Sub Continent Child Name.</value>
public string SubContinent_Child_Name
{
get { return GetProperty(SubContinent_Child_NameProperty); }
set { SetProperty(SubContinent_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="B05_SubContinent_ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="B05_SubContinent_ReChild"/> object.</returns>
internal static B05_SubContinent_ReChild NewB05_SubContinent_ReChild()
{
return DataPortal.CreateChild<B05_SubContinent_ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="B05_SubContinent_ReChild"/> object from the given B05_SubContinent_ReChildDto.
/// </summary>
/// <param name="data">The <see cref="B05_SubContinent_ReChildDto"/>.</param>
/// <returns>A reference to the fetched <see cref="B05_SubContinent_ReChild"/> object.</returns>
internal static B05_SubContinent_ReChild GetB05_SubContinent_ReChild(B05_SubContinent_ReChildDto data)
{
B05_SubContinent_ReChild obj = new B05_SubContinent_ReChild();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(data);
obj.MarkOld();
// check all object rules and property rules
obj.BusinessRules.CheckRules();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="B05_SubContinent_ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public B05_SubContinent_ReChild()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="B05_SubContinent_ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="B05_SubContinent_ReChild"/> object from the given <see cref="B05_SubContinent_ReChildDto"/>.
/// </summary>
/// <param name="data">The B05_SubContinent_ReChildDto to use.</param>
private void Fetch(B05_SubContinent_ReChildDto data)
{
// Value properties
LoadProperty(SubContinent_Child_NameProperty, data.SubContinent_Child_Name);
// parent properties
subContinent_ID2 = data.Parent_SubContinent_ID;
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="B05_SubContinent_ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(B04_SubContinent parent)
{
var dto = new B05_SubContinent_ReChildDto();
dto.Parent_SubContinent_ID = parent.SubContinent_ID;
dto.SubContinent_Child_Name = SubContinent_Child_Name;
using (var dalManager = DalFactoryParentLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IB05_SubContinent_ReChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="B05_SubContinent_ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(B04_SubContinent parent)
{
if (!IsDirty)
return;
var dto = new B05_SubContinent_ReChildDto();
dto.Parent_SubContinent_ID = parent.SubContinent_ID;
dto.SubContinent_Child_Name = SubContinent_Child_Name;
using (var dalManager = DalFactoryParentLoad.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IB05_SubContinent_ReChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="B05_SubContinent_ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(B04_SubContinent parent)
{
using (var dalManager = DalFactoryParentLoad.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IB05_SubContinent_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.SubContinent_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
//
// Options.cs
//
// Authors:
// Jonathan Pryor <jpryor@novell.com>
// Federico Di Gregorio <fog@initd.org>
// Rolf Bjarne Kvinge <rolf@xamarin.com>
//
// Copyright (C) 2008 Novell (http://www.novell.com)
// Copyright (C) 2009 Federico Di Gregorio.
// Copyright (C) 2012 Xamarin Inc (http://www.xamarin.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.
//
// Compile With:
// gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll
// gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll
//
// The LINQ version just changes the implementation of
// OptionSet.Parse(IEnumerable<string>), and confers no semantic changes.
//
// A Getopt::Long-inspired option parsing library for C#.
//
// NDesk.Options.OptionSet is built upon a key/value table, where the
// key is a option format string and the value is a delegate that is
// invoked when the format string is matched.
//
// Option format strings:
// Regex-like BNF Grammar:
// name: .+
// type: [=:]
// sep: ( [^{}]+ | '{' .+ '}' )?
// aliases: ( name type sep ) ( '|' name type sep )*
//
// Each '|'-delimited name is an alias for the associated action. If the
// format string ends in a '=', it has a required value. If the format
// string ends in a ':', it has an optional value. If neither '=' or ':'
// is present, no value is supported. `=' or `:' need only be defined on one
// alias, but if they are provided on more than one they must be consistent.
//
// Each alias portion may also end with a "key/value separator", which is used
// to split option values if the option accepts > 1 value. If not specified,
// it defaults to '=' and ':'. If specified, it can be any character except
// '{' and '}' OR the *string* between '{' and '}'. If no separator should be
// used (i.e. the separate values should be distinct arguments), then "{}"
// should be used as the separator.
//
// Options are extracted either from the current option by looking for
// the option name followed by an '=' or ':', or is taken from the
// following option IFF:
// - The current option does not contain a '=' or a ':'
// - The current option requires a value (i.e. not a Option type of ':')
//
// The `name' used in the option format string does NOT include any leading
// option indicator, such as '-', '--', or '/'. All three of these are
// permitted/required on any named option.
//
// Option bundling is permitted so long as:
// - '-' is used to start the option group
// - all of the bundled options are a single character
// - at most one of the bundled options accepts a value, and the value
// provided starts from the next character to the end of the string.
//
// This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value'
// as '-Dname=value'.
//
// Option processing is disabled by specifying "--". All options after "--"
// are returned by OptionSet.Parse() unchanged and unprocessed.
//
// Unprocessed options are returned from OptionSet.Parse().
//
// Examples:
// int verbose = 0;
// OptionSet p = new OptionSet ()
// .Add ("v", v => ++verbose)
// .Add ("name=|value=", v => Console.WriteLine (v));
// p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"});
//
// The above would parse the argument string array, and would invoke the
// lambda expression three times, setting `verbose' to 3 when complete.
// It would also print out "A" and "B" to standard output.
// The returned array would contain the string "extra".
//
// C# 3.0 collection initializers are supported and encouraged:
// var p = new OptionSet () {
// { "h|?|help", v => ShowHelp () },
// };
//
// System.ComponentModel.TypeConverter is also supported, allowing the use of
// custom data types in the callback type; TypeConverter.ConvertFromString()
// is used to convert the value option to an instance of the specified
// type:
//
// var p = new OptionSet () {
// { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) },
// };
//
// Random other tidbits:
// - Boolean options (those w/o '=' or ':' in the option format string)
// are explicitly enabled if they are followed with '+', and explicitly
// disabled if they are followed with '-':
// string a = null;
// var p = new OptionSet () {
// { "a", s => a = s },
// };
// p.Parse (new string[]{"-a"}); // sets v != null
// p.Parse (new string[]{"-a+"}); // sets v != null
// p.Parse (new string[]{"-a-"}); // sets v == null
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
#if LINQ
using System.Linq;
#endif
#if TEST
using NDesk.Options;
#endif
#if NDESK_OPTIONS
namespace NDesk.Options
#else
namespace Mono.Options
#endif
{
internal static class StringCoda
{
public static IEnumerable<string> WrappedLines(string self, params int[] widths)
{
IEnumerable<int> w = widths;
return WrappedLines(self, w);
}
public static IEnumerable<string> WrappedLines(string self, IEnumerable<int> widths)
{
if (widths == null)
throw new ArgumentNullException("widths");
return CreateWrappedLinesIterator(self, widths);
}
private static IEnumerable<string> CreateWrappedLinesIterator(string self, IEnumerable<int> widths)
{
if (string.IsNullOrEmpty(self))
{
yield return string.Empty;
yield break;
}
using (IEnumerator<int> ewidths = widths.GetEnumerator())
{
bool? hw = null;
int width = GetNextWidth(ewidths, int.MaxValue, ref hw);
int start = 0, end;
do
{
end = GetLineEnd(start, width, self);
char c = self[end - 1];
if (char.IsWhiteSpace(c))
--end;
bool needContinuation = end != self.Length && !IsEolChar(c);
string continuation = "";
if (needContinuation)
{
--end;
continuation = "-";
}
string line = self.Substring(start, end - start) + continuation;
yield return line;
start = end;
if (char.IsWhiteSpace(c))
++start;
width = GetNextWidth(ewidths, width, ref hw);
} while (start < self.Length);
}
}
private static int GetNextWidth(IEnumerator<int> ewidths, int curWidth, ref bool? eValid)
{
if (!eValid.HasValue || (eValid.HasValue && eValid.Value))
{
curWidth = (eValid = ewidths.MoveNext()).Value ? ewidths.Current : curWidth;
// '.' is any character, - is for a continuation
const string minWidth = ".-";
if (curWidth < minWidth.Length)
throw new ArgumentOutOfRangeException("widths",
string.Format("Element must be >= {0}, was {1}.", minWidth.Length, curWidth));
return curWidth;
}
// no more elements, use the last element.
return curWidth;
}
private static bool IsEolChar(char c)
{
return !char.IsLetterOrDigit(c);
}
private static int GetLineEnd(int start, int length, string description)
{
int end = System.Math.Min(start + length, description.Length);
int sep = -1;
for (int i = start; i < end; ++i)
{
if (description[i] == '\n')
return i + 1;
if (IsEolChar(description[i]))
sep = i + 1;
}
if (sep == -1 || end == description.Length)
return end;
return sep;
}
}
internal class OptionValueCollection : IList, IList<string>
{
List<string> values = new List<string>();
OptionContext c;
internal OptionValueCollection(OptionContext c)
{
this.c = c;
}
#region ICollection
void ICollection.CopyTo(Array array, int index) { (values as ICollection).CopyTo(array, index); }
bool ICollection.IsSynchronized { get { return (values as ICollection).IsSynchronized; } }
object ICollection.SyncRoot { get { return (values as ICollection).SyncRoot; } }
#endregion
#region ICollection<T>
public void Add(string item) { values.Add(item); }
public void Clear() { values.Clear(); }
public bool Contains(string item) { return values.Contains(item); }
public void CopyTo(string[] array, int arrayIndex) { values.CopyTo(array, arrayIndex); }
public bool Remove(string item) { return values.Remove(item); }
public int Count { get { return values.Count; } }
public bool IsReadOnly { get { return false; } }
#endregion
#region IEnumerable
IEnumerator IEnumerable.GetEnumerator() { return values.GetEnumerator(); }
#endregion
#region IEnumerable<T>
public IEnumerator<string> GetEnumerator() { return values.GetEnumerator(); }
#endregion
#region IList
int IList.Add(object value) { return (values as IList).Add(value); }
bool IList.Contains(object value) { return (values as IList).Contains(value); }
int IList.IndexOf(object value) { return (values as IList).IndexOf(value); }
void IList.Insert(int index, object value) { (values as IList).Insert(index, value); }
void IList.Remove(object value) { (values as IList).Remove(value); }
void IList.RemoveAt(int index) { (values as IList).RemoveAt(index); }
bool IList.IsFixedSize { get { return false; } }
object IList.this[int index] { get { return this[index]; } set { (values as IList)[index] = value; } }
#endregion
#region IList<T>
public int IndexOf(string item) { return values.IndexOf(item); }
public void Insert(int index, string item) { values.Insert(index, item); }
public void RemoveAt(int index) { values.RemoveAt(index); }
private void AssertValid(int index)
{
if (c.Option == null)
throw new InvalidOperationException("OptionContext.Option is null.");
if (index >= c.Option.MaxValueCount)
throw new ArgumentOutOfRangeException("index");
if (c.Option.OptionValueType == OptionValueType.Required &&
index >= values.Count)
throw new OptionException(string.Format(
c.OptionSet.MessageLocalizer("Missing required value for option '{0}'."), c.OptionName),
c.OptionName);
}
public string this[int index]
{
get
{
AssertValid(index);
return index >= values.Count ? null : values[index];
}
set
{
values[index] = value;
}
}
#endregion
public List<string> ToList()
{
return new List<string>(values);
}
public string[] ToArray()
{
return values.ToArray();
}
public override string ToString()
{
return string.Join(", ", values.ToArray());
}
}
internal class OptionContext
{
private Option option;
private string name;
private int index;
private OptionSet set;
private OptionValueCollection c;
public OptionContext(OptionSet set)
{
this.set = set;
this.c = new OptionValueCollection(this);
}
public Option Option
{
get { return option; }
set { option = value; }
}
public string OptionName
{
get { return name; }
set { name = value; }
}
public int OptionIndex
{
get { return index; }
set { index = value; }
}
public OptionSet OptionSet
{
get { return set; }
}
public OptionValueCollection OptionValues
{
get { return c; }
}
}
internal enum OptionValueType
{
None,
Optional,
Required,
}
internal abstract class Option
{
string prototype, description;
string[] names;
OptionValueType type;
int count;
string[] separators;
bool hidden;
protected Option(string prototype, string description)
: this(prototype, description, 1, false)
{
}
protected Option(string prototype, string description, int maxValueCount)
: this(prototype, description, maxValueCount, false)
{
}
protected Option(string prototype, string description, int maxValueCount, bool hidden)
{
if (prototype == null)
throw new ArgumentNullException("prototype");
if (prototype.Length == 0)
throw new ArgumentException("Cannot be the empty string.", "prototype");
if (maxValueCount < 0)
throw new ArgumentOutOfRangeException("maxValueCount");
this.prototype = prototype;
this.description = description;
this.count = maxValueCount;
this.names = (this is OptionSet.Category)
// append GetHashCode() so that "duplicate" categories have distinct
// names, e.g. adding multiple "" categories should be valid.
? new[] { prototype + this.GetHashCode() }
: prototype.Split('|');
if (this is OptionSet.Category)
return;
this.type = ParsePrototype();
this.hidden = hidden;
if (this.count == 0 && type != OptionValueType.None)
throw new ArgumentException(
"Cannot provide maxValueCount of 0 for OptionValueType.Required or " +
"OptionValueType.Optional.",
"maxValueCount");
if (this.type == OptionValueType.None && maxValueCount > 1)
throw new ArgumentException(
string.Format("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount),
"maxValueCount");
if (Array.IndexOf(names, "<>") >= 0 &&
((names.Length == 1 && this.type != OptionValueType.None) ||
(names.Length > 1 && this.MaxValueCount > 1)))
throw new ArgumentException(
"The default option handler '<>' cannot require values.",
"prototype");
}
public string Prototype { get { return prototype; } }
public string Description { get { return description; } }
public OptionValueType OptionValueType { get { return type; } }
public int MaxValueCount { get { return count; } }
public bool Hidden { get { return hidden; } }
public string[] GetNames()
{
return (string[])names.Clone();
}
public string[] GetValueSeparators()
{
if (separators == null)
return new string[0];
return (string[])separators.Clone();
}
protected static T Parse<T>(string value, OptionContext c)
{
Type tt = typeof(T);
bool nullable = tt.IsValueType && tt.IsGenericType &&
!tt.IsGenericTypeDefinition &&
tt.GetGenericTypeDefinition() == typeof(Nullable<>);
Type targetType = nullable ? tt.GetGenericArguments()[0] : typeof(T);
TypeConverter conv = TypeDescriptor.GetConverter(targetType);
T t = default(T);
try
{
if (value != null)
t = (T)conv.ConvertFromString(value);
}
catch (Exception e)
{
throw new OptionException(
string.Format(
c.OptionSet.MessageLocalizer("Could not convert string `{0}' to type {1} for option `{2}'."),
value, targetType.Name, c.OptionName),
c.OptionName, e);
}
return t;
}
internal string[] Names { get { return names; } }
internal string[] ValueSeparators { get { return separators; } }
static readonly char[] NameTerminator = new char[] { '=', ':' };
private OptionValueType ParsePrototype()
{
char type = '\0';
List<string> seps = new List<string>();
for (int i = 0; i < names.Length; ++i)
{
string name = names[i];
if (name.Length == 0)
throw new ArgumentException("Empty option names are not supported.", "prototype");
int end = name.IndexOfAny(NameTerminator);
if (end == -1)
continue;
names[i] = name.Substring(0, end);
if (type == '\0' || type == name[end])
type = name[end];
else
throw new ArgumentException(
string.Format("Conflicting option types: '{0}' vs. '{1}'.", type, name[end]),
"prototype");
AddSeparators(name, end, seps);
}
if (type == '\0')
return OptionValueType.None;
if (count <= 1 && seps.Count != 0)
throw new ArgumentException(
string.Format("Cannot provide key/value separators for Options taking {0} value(s).", count),
"prototype");
if (count > 1)
{
if (seps.Count == 0)
this.separators = new string[] { ":", "=" };
else if (seps.Count == 1 && seps[0].Length == 0)
this.separators = null;
else
this.separators = seps.ToArray();
}
return type == '=' ? OptionValueType.Required : OptionValueType.Optional;
}
private static void AddSeparators(string name, int end, ICollection<string> seps)
{
int start = -1;
for (int i = end + 1; i < name.Length; ++i)
{
switch (name[i])
{
case '{':
if (start != -1)
throw new ArgumentException(
string.Format("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
start = i + 1;
break;
case '}':
if (start == -1)
throw new ArgumentException(
string.Format("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
seps.Add(name.Substring(start, i - start));
start = -1;
break;
default:
if (start == -1)
seps.Add(name[i].ToString());
break;
}
}
if (start != -1)
throw new ArgumentException(
string.Format("Ill-formed name/value separator found in \"{0}\".", name),
"prototype");
}
public void Invoke(OptionContext c)
{
OnParseComplete(c);
c.OptionName = null;
c.Option = null;
c.OptionValues.Clear();
}
protected abstract void OnParseComplete(OptionContext c);
public override string ToString()
{
return Prototype;
}
}
internal abstract class ArgumentSource
{
protected ArgumentSource()
{
}
public abstract string[] GetNames();
public abstract string Description { get; }
public abstract bool GetArguments(string value, out IEnumerable<string> replacement);
public static IEnumerable<string> GetArgumentsFromFile(string file)
{
return GetArguments(File.OpenText(file), true);
}
public static IEnumerable<string> GetArguments(TextReader reader)
{
return GetArguments(reader, false);
}
// Cribbed from mcs/driver.cs:LoadArgs(string)
static IEnumerable<string> GetArguments(TextReader reader, bool close)
{
try
{
StringBuilder arg = new StringBuilder();
string line;
while ((line = reader.ReadLine()) != null)
{
int t = line.Length;
for (int i = 0; i < t; i++)
{
char c = line[i];
if (c == '"' || c == '\'')
{
char end = c;
for (i++; i < t; i++)
{
c = line[i];
if (c == end)
break;
arg.Append(c);
}
}
else if (c == ' ')
{
if (arg.Length > 0)
{
yield return arg.ToString();
arg.Length = 0;
}
}
else
arg.Append(c);
}
if (arg.Length > 0)
{
yield return arg.ToString();
arg.Length = 0;
}
}
}
finally
{
if (close)
reader.Close();
}
}
}
internal class ResponseFileSource : ArgumentSource
{
public override string[] GetNames()
{
return new string[] { "@file" };
}
public override string Description
{
get { return "Read response file for more options."; }
}
public override bool GetArguments(string value, out IEnumerable<string> replacement)
{
if (string.IsNullOrEmpty(value) || !value.StartsWith("@"))
{
replacement = null;
return false;
}
replacement = ArgumentSource.GetArgumentsFromFile(value.Substring(1));
return true;
}
}
[Serializable]
internal class OptionException : Exception
{
private string option;
public OptionException()
{
}
public OptionException(string message, string optionName)
: base(message)
{
this.option = optionName;
}
public OptionException(string message, string optionName, Exception innerException)
: base(message, innerException)
{
this.option = optionName;
}
protected OptionException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
this.option = info.GetString("OptionName");
}
public string OptionName
{
get { return this.option; }
}
[SecurityPermission(SecurityAction.LinkDemand, SerializationFormatter = true)]
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("OptionName", option);
}
}
internal delegate void OptionAction<TKey, TValue>(TKey key, TValue value);
internal class OptionSet : KeyedCollection<string, Option>
{
public OptionSet()
: this(delegate(string f) { return f; })
{
}
public OptionSet(Converter<string, string> localizer)
{
this.localizer = localizer;
this.roSources = new ReadOnlyCollection<ArgumentSource>(sources);
}
Converter<string, string> localizer;
public Converter<string, string> MessageLocalizer
{
get { return localizer; }
}
List<ArgumentSource> sources = new List<ArgumentSource>();
ReadOnlyCollection<ArgumentSource> roSources;
public ReadOnlyCollection<ArgumentSource> ArgumentSources
{
get { return roSources; }
}
protected override string GetKeyForItem(Option item)
{
if (item == null)
throw new ArgumentNullException("option");
if (item.Names != null && item.Names.Length > 0)
return item.Names[0];
// This should never happen, as it's invalid for Option to be
// constructed w/o any names.
throw new InvalidOperationException("Option has no names!");
}
[Obsolete("Use KeyedCollection.this[string]")]
protected Option GetOptionForName(string option)
{
if (option == null)
throw new ArgumentNullException("option");
try
{
return base[option];
}
catch (KeyNotFoundException)
{
return null;
}
}
protected override void InsertItem(int index, Option item)
{
base.InsertItem(index, item);
AddImpl(item);
}
protected override void RemoveItem(int index)
{
Option p = Items[index];
base.RemoveItem(index);
// KeyedCollection.RemoveItem() handles the 0th item
for (int i = 1; i < p.Names.Length; ++i)
{
Dictionary.Remove(p.Names[i]);
}
}
protected override void SetItem(int index, Option item)
{
base.SetItem(index, item);
AddImpl(item);
}
private void AddImpl(Option option)
{
if (option == null)
throw new ArgumentNullException("option");
List<string> added = new List<string>(option.Names.Length);
try
{
// KeyedCollection.InsertItem/SetItem handle the 0th name.
for (int i = 1; i < option.Names.Length; ++i)
{
Dictionary.Add(option.Names[i], option);
added.Add(option.Names[i]);
}
}
catch (Exception)
{
foreach (string name in added)
Dictionary.Remove(name);
throw;
}
}
public OptionSet Add(string header)
{
if (header == null)
throw new ArgumentNullException("header");
Add(new Category(header));
return this;
}
internal sealed class Category : Option
{
// Prototype starts with '=' because this is an invalid prototype
// (see Option.ParsePrototype(), and thus it'll prevent Category
// instances from being accidentally used as normal options.
public Category(string description)
: base("=:Category:= " + description, description)
{
}
protected override void OnParseComplete(OptionContext c)
{
throw new NotSupportedException("Category.OnParseComplete should not be invoked.");
}
}
public new OptionSet Add(Option option)
{
base.Add(option);
return this;
}
sealed class ActionOption : Option
{
Action<OptionValueCollection> action;
public ActionOption(string prototype, string description, int count, Action<OptionValueCollection> action)
: this(prototype, description, count, action, false)
{
}
public ActionOption(string prototype, string description, int count, Action<OptionValueCollection> action, bool hidden)
: base(prototype, description, count, hidden)
{
if (action == null)
throw new ArgumentNullException("action");
this.action = action;
}
protected override void OnParseComplete(OptionContext c)
{
action(c.OptionValues);
}
}
public OptionSet Add(string prototype, Action<string> action)
{
return Add(prototype, null, action);
}
public OptionSet Add(string prototype, string description, Action<string> action)
{
return Add(prototype, description, action, false);
}
public OptionSet Add(string prototype, string description, Action<string> action, bool hidden)
{
if (action == null)
throw new ArgumentNullException("action");
Option p = new ActionOption(prototype, description, 1,
delegate(OptionValueCollection v) { action(v[0]); }, hidden);
base.Add(p);
return this;
}
public OptionSet Add(string prototype, OptionAction<string, string> action)
{
return Add(prototype, null, action);
}
public OptionSet Add(string prototype, string description, OptionAction<string, string> action)
{
return Add(prototype, description, action, false);
}
public OptionSet Add(string prototype, string description, OptionAction<string, string> action, bool hidden)
{
if (action == null)
throw new ArgumentNullException("action");
Option p = new ActionOption(prototype, description, 2,
delegate(OptionValueCollection v) { action(v[0], v[1]); }, hidden);
base.Add(p);
return this;
}
sealed class ActionOption<T> : Option
{
Action<T> action;
public ActionOption(string prototype, string description, Action<T> action)
: base(prototype, description, 1)
{
if (action == null)
throw new ArgumentNullException("action");
this.action = action;
}
protected override void OnParseComplete(OptionContext c)
{
action(Parse<T>(c.OptionValues[0], c));
}
}
sealed class ActionOption<TKey, TValue> : Option
{
OptionAction<TKey, TValue> action;
public ActionOption(string prototype, string description, OptionAction<TKey, TValue> action)
: base(prototype, description, 2)
{
if (action == null)
throw new ArgumentNullException("action");
this.action = action;
}
protected override void OnParseComplete(OptionContext c)
{
action(
Parse<TKey>(c.OptionValues[0], c),
Parse<TValue>(c.OptionValues[1], c));
}
}
public OptionSet Add<T>(string prototype, Action<T> action)
{
return Add(prototype, null, action);
}
public OptionSet Add<T>(string prototype, string description, Action<T> action)
{
return Add(new ActionOption<T>(prototype, description, action));
}
public OptionSet Add<TKey, TValue>(string prototype, OptionAction<TKey, TValue> action)
{
return Add(prototype, null, action);
}
public OptionSet Add<TKey, TValue>(string prototype, string description, OptionAction<TKey, TValue> action)
{
return Add(new ActionOption<TKey, TValue>(prototype, description, action));
}
public OptionSet Add(ArgumentSource source)
{
if (source == null)
throw new ArgumentNullException("source");
sources.Add(source);
return this;
}
protected virtual OptionContext CreateOptionContext()
{
return new OptionContext(this);
}
public List<string> Parse(IEnumerable<string> arguments)
{
if (arguments == null)
throw new ArgumentNullException("arguments");
OptionContext c = CreateOptionContext();
c.OptionIndex = -1;
bool process = true;
List<string> unprocessed = new List<string>();
Option def = Contains("<>") ? this["<>"] : null;
ArgumentEnumerator ae = new ArgumentEnumerator(arguments);
foreach (string argument in ae)
{
++c.OptionIndex;
if (argument == "--")
{
process = false;
continue;
}
if (!process)
{
Unprocessed(unprocessed, def, c, argument);
continue;
}
if (AddSource(ae, argument))
continue;
if (!Parse(argument, c))
Unprocessed(unprocessed, def, c, argument);
}
if (c.Option != null)
c.Option.Invoke(c);
return unprocessed;
}
class ArgumentEnumerator : IEnumerable<string>
{
List<IEnumerator<string>> sources = new List<IEnumerator<string>>();
public ArgumentEnumerator(IEnumerable<string> arguments)
{
sources.Add(arguments.GetEnumerator());
}
public void Add(IEnumerable<string> arguments)
{
sources.Add(arguments.GetEnumerator());
}
public IEnumerator<string> GetEnumerator()
{
do
{
IEnumerator<string> c = sources[sources.Count - 1];
if (c.MoveNext())
yield return c.Current;
else
{
c.Dispose();
sources.RemoveAt(sources.Count - 1);
}
} while (sources.Count > 0);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
bool AddSource(ArgumentEnumerator ae, string argument)
{
foreach (ArgumentSource source in sources)
{
IEnumerable<string> replacement;
if (!source.GetArguments(argument, out replacement))
continue;
ae.Add(replacement);
return true;
}
return false;
}
private static bool Unprocessed(ICollection<string> extra, Option def, OptionContext c, string argument)
{
if (def == null)
{
extra.Add(argument);
return false;
}
c.OptionValues.Add(argument);
c.Option = def;
c.Option.Invoke(c);
return false;
}
private readonly Regex ValueOption = new Regex(
@"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$");
protected bool GetOptionParts(string argument, out string flag, out string name, out string sep, out string value)
{
if (argument == null)
throw new ArgumentNullException("argument");
flag = name = sep = value = null;
Match m = ValueOption.Match(argument);
if (!m.Success)
{
return false;
}
flag = m.Groups["flag"].Value;
name = m.Groups["name"].Value;
if (m.Groups["sep"].Success && m.Groups["value"].Success)
{
sep = m.Groups["sep"].Value;
value = m.Groups["value"].Value;
}
return true;
}
protected virtual bool Parse(string argument, OptionContext c)
{
if (c.Option != null)
{
ParseValue(argument, c);
return true;
}
string f, n, s, v;
if (!GetOptionParts(argument, out f, out n, out s, out v))
return false;
Option p;
if (Contains(n))
{
p = this[n];
c.OptionName = f + n;
c.Option = p;
switch (p.OptionValueType)
{
case OptionValueType.None:
c.OptionValues.Add(n);
c.Option.Invoke(c);
break;
case OptionValueType.Optional:
case OptionValueType.Required:
ParseValue(v, c);
break;
}
return true;
}
// no match; is it a bool option?
if (ParseBool(argument, n, c))
return true;
// is it a bundled option?
if (ParseBundledValue(f, string.Concat(n + s + v), c))
return true;
return false;
}
private void ParseValue(string option, OptionContext c)
{
if (option != null)
foreach (string o in c.Option.ValueSeparators != null
? option.Split(c.Option.ValueSeparators, c.Option.MaxValueCount - c.OptionValues.Count, StringSplitOptions.None)
: new string[] { option })
{
c.OptionValues.Add(o);
}
if (c.OptionValues.Count == c.Option.MaxValueCount ||
c.Option.OptionValueType == OptionValueType.Optional)
c.Option.Invoke(c);
else if (c.OptionValues.Count > c.Option.MaxValueCount)
{
throw new OptionException(localizer(string.Format(
"Error: Found {0} option values when expecting {1}.",
c.OptionValues.Count, c.Option.MaxValueCount)),
c.OptionName);
}
}
private bool ParseBool(string option, string n, OptionContext c)
{
Option p;
string rn;
if (n.Length >= 1 && (n[n.Length - 1] == '+' || n[n.Length - 1] == '-') &&
Contains((rn = n.Substring(0, n.Length - 1))))
{
p = this[rn];
string v = n[n.Length - 1] == '+' ? option : null;
c.OptionName = option;
c.Option = p;
c.OptionValues.Add(v);
p.Invoke(c);
return true;
}
return false;
}
private bool ParseBundledValue(string f, string n, OptionContext c)
{
if (f != "-")
return false;
for (int i = 0; i < n.Length; ++i)
{
Option p;
string opt = f + n[i].ToString();
string rn = n[i].ToString();
if (!Contains(rn))
{
if (i == 0)
return false;
throw new OptionException(string.Format(localizer(
"Cannot bundle unregistered option '{0}'."), opt), opt);
}
p = this[rn];
switch (p.OptionValueType)
{
case OptionValueType.None:
Invoke(c, opt, n, p);
break;
case OptionValueType.Optional:
case OptionValueType.Required:
{
string v = n.Substring(i + 1);
c.Option = p;
c.OptionName = opt;
ParseValue(v.Length != 0 ? v : null, c);
return true;
}
default:
throw new InvalidOperationException("Unknown OptionValueType: " + p.OptionValueType);
}
}
return true;
}
private static void Invoke(OptionContext c, string name, string value, Option option)
{
c.OptionName = name;
c.Option = option;
c.OptionValues.Add(value);
option.Invoke(c);
}
private const int OptionWidth = 29;
private const int Description_FirstWidth = 80 - OptionWidth;
private const int Description_RemWidth = 80 - OptionWidth - 2;
public void WriteOptionDescriptions(TextWriter o)
{
foreach (Option p in this)
{
int written = 0;
if (p.Hidden)
continue;
Category c = p as Category;
if (c != null)
{
WriteDescription(o, p.Description, "", 80, 80);
continue;
}
if (!WriteOptionPrototype(o, p, ref written))
continue;
if (written < OptionWidth)
o.Write(new string(' ', OptionWidth - written));
else
{
o.WriteLine();
o.Write(new string(' ', OptionWidth));
}
WriteDescription(o, p.Description, new string(' ', OptionWidth + 2),
Description_FirstWidth, Description_RemWidth);
}
foreach (ArgumentSource s in sources)
{
string[] names = s.GetNames();
if (names == null || names.Length == 0)
continue;
int written = 0;
Write(o, ref written, " ");
Write(o, ref written, names[0]);
for (int i = 1; i < names.Length; ++i)
{
Write(o, ref written, ", ");
Write(o, ref written, names[i]);
}
if (written < OptionWidth)
o.Write(new string(' ', OptionWidth - written));
else
{
o.WriteLine();
o.Write(new string(' ', OptionWidth));
}
WriteDescription(o, s.Description, new string(' ', OptionWidth + 2),
Description_FirstWidth, Description_RemWidth);
}
}
void WriteDescription(TextWriter o, string value, string prefix, int firstWidth, int remWidth)
{
bool indent = false;
foreach (string line in GetLines(localizer(GetDescription(value)), firstWidth, remWidth))
{
if (indent)
o.Write(prefix);
o.WriteLine(line);
indent = true;
}
}
bool WriteOptionPrototype(TextWriter o, Option p, ref int written)
{
string[] names = p.Names;
int i = GetNextOptionIndex(names, 0);
if (i == names.Length)
return false;
if (names[i].Length == 1)
{
Write(o, ref written, " -");
Write(o, ref written, names[0]);
}
else
{
Write(o, ref written, " --");
Write(o, ref written, names[0]);
}
for (i = GetNextOptionIndex(names, i + 1);
i < names.Length; i = GetNextOptionIndex(names, i + 1))
{
Write(o, ref written, ", ");
Write(o, ref written, names[i].Length == 1 ? "-" : "--");
Write(o, ref written, names[i]);
}
if (p.OptionValueType == OptionValueType.Optional ||
p.OptionValueType == OptionValueType.Required)
{
if (p.OptionValueType == OptionValueType.Optional)
{
Write(o, ref written, localizer("["));
}
Write(o, ref written, localizer("=" + GetArgumentName(0, p.MaxValueCount, p.Description)));
string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0
? p.ValueSeparators[0]
: " ";
for (int c = 1; c < p.MaxValueCount; ++c)
{
Write(o, ref written, localizer(sep + GetArgumentName(c, p.MaxValueCount, p.Description)));
}
if (p.OptionValueType == OptionValueType.Optional)
{
Write(o, ref written, localizer("]"));
}
}
return true;
}
static int GetNextOptionIndex(string[] names, int i)
{
while (i < names.Length && names[i] == "<>")
{
++i;
}
return i;
}
static void Write(TextWriter o, ref int n, string s)
{
n += s.Length;
o.Write(s);
}
private static string GetArgumentName(int index, int maxIndex, string description)
{
if (description == null)
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
string[] nameStart;
if (maxIndex == 1)
nameStart = new string[] { "{0:", "{" };
else
nameStart = new string[] { "{" + index + ":" };
for (int i = 0; i < nameStart.Length; ++i)
{
int start, j = 0;
do
{
start = description.IndexOf(nameStart[i], j);
} while (start >= 0 && j != 0 ? description[j++ - 1] == '{' : false);
if (start == -1)
continue;
int end = description.IndexOf("}", start);
if (end == -1)
continue;
return description.Substring(start + nameStart[i].Length, end - start - nameStart[i].Length);
}
return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1);
}
private static string GetDescription(string description)
{
if (description == null)
return string.Empty;
StringBuilder sb = new StringBuilder(description.Length);
int start = -1;
for (int i = 0; i < description.Length; ++i)
{
switch (description[i])
{
case '{':
if (i == start)
{
sb.Append('{');
start = -1;
}
else if (start < 0)
start = i + 1;
break;
case '}':
if (start < 0)
{
if ((i + 1) == description.Length || description[i + 1] != '}')
throw new InvalidOperationException("Invalid option description: " + description);
++i;
sb.Append("}");
}
else
{
sb.Append(description.Substring(start, i - start));
start = -1;
}
break;
case ':':
if (start < 0)
goto default;
start = i + 1;
break;
default:
if (start < 0)
sb.Append(description[i]);
break;
}
}
return sb.ToString();
}
private static IEnumerable<string> GetLines(string description, int firstWidth, int remWidth)
{
return StringCoda.WrappedLines(description, firstWidth, remWidth);
}
}
}
| |
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace OpenPop.Mime.Decode
{
/// <summary>
/// Used for decoding Quoted-Printable text.<br/>
/// This is a robust implementation of a Quoted-Printable decoder defined in <a href="http://tools.ietf.org/html/rfc2045">RFC 2045</a> and <a href="http://tools.ietf.org/html/rfc2047">RFC 2047</a>.<br/>
/// Every measurement has been taken to conform to the RFC.
/// </summary>
internal static class QuotedPrintable
{
/// <summary>
/// Decodes a Quoted-Printable string according to <a href="http://tools.ietf.org/html/rfc2047">RFC 2047</a>.<br/>
/// RFC 2047 is used for decoding Encoded-Word encoded strings.
/// </summary>
/// <param name="toDecode">Quoted-Printable encoded string</param>
/// <param name="encoding">Specifies which encoding the returned string will be in</param>
/// <returns>A decoded string in the correct encoding</returns>
/// <exception cref="ArgumentNullException">If <paramref name="toDecode"/> or <paramref name="encoding"/> is <see langword="null"/></exception>
public static string DecodeEncodedWord(string toDecode, Encoding encoding)
{
if (toDecode == null)
throw new ArgumentNullException("toDecode");
if (encoding == null)
throw new ArgumentNullException("encoding");
// Decode the QuotedPrintable string and return it
return encoding.GetString(Rfc2047QuotedPrintableDecode(toDecode, true));
}
/// <summary>
/// Decodes a Quoted-Printable string according to <a href="http://tools.ietf.org/html/rfc2045">RFC 2045</a>.<br/>
/// RFC 2045 specifies the decoding of a body encoded with Content-Transfer-Encoding of quoted-printable.
/// </summary>
/// <param name="toDecode">Quoted-Printable encoded string</param>
/// <returns>A decoded byte array that the Quoted-Printable encoded string described</returns>
/// <exception cref="ArgumentNullException">If <paramref name="toDecode"/> is <see langword="null"/></exception>
public static byte[] DecodeContentTransferEncoding(string toDecode)
{
if (toDecode == null)
throw new ArgumentNullException("toDecode");
// Decode the QuotedPrintable string and return it
return Rfc2047QuotedPrintableDecode(toDecode, false);
}
/// <summary>
/// This is the actual decoder.
/// </summary>
/// <param name="toDecode">The string to be decoded from Quoted-Printable</param>
/// <param name="encodedWordVariant">
/// If <see langword="true"/>, specifies that RFC 2047 quoted printable decoding is used.<br/>
/// This is for quoted-printable encoded words<br/>
/// <br/>
/// If <see langword="false"/>, specifies that RFC 2045 quoted printable decoding is used.<br/>
/// This is for quoted-printable Content-Transfer-Encoding
/// </param>
/// <returns>A decoded byte array that was described by <paramref name="toDecode"/></returns>
/// <exception cref="ArgumentNullException">If <paramref name="toDecode"/> is <see langword="null"/></exception>
/// <remarks>See <a href="http://tools.ietf.org/html/rfc2047#section-4.2">RFC 2047 section 4.2</a> for RFC details</remarks>
private static byte[] Rfc2047QuotedPrintableDecode(string toDecode, bool encodedWordVariant)
{
if (toDecode == null)
throw new ArgumentNullException("toDecode");
// Create a byte array builder which is roughly equivalent to a StringBuilder
using (MemoryStream byteArrayBuilder = new MemoryStream())
{
// Remove illegal control characters
toDecode = RemoveIllegalControlCharacters(toDecode);
// Run through the whole string that needs to be decoded
for (int i = 0; i < toDecode.Length; i++)
{
char currentChar = toDecode[i];
if (currentChar == '=')
{
// Check that there is at least two characters behind the equal sign
if (toDecode.Length - i < 3)
{
// We are at the end of the toDecode string, but something is missing. Handle it the way RFC 2045 states
WriteAllBytesToStream(byteArrayBuilder, DecodeEqualSignNotLongEnough(toDecode.Substring(i)));
// Since it was the last part, we should stop parsing anymore
break;
}
// Decode the Quoted-Printable part
string quotedPrintablePart = toDecode.Substring(i, 3);
WriteAllBytesToStream(byteArrayBuilder, DecodeEqualSign(quotedPrintablePart));
// We now consumed two extra characters. Go forward two extra characters
i += 2;
} else
{
// This character is not quoted printable hex encoded.
// Could it be the _ character, which represents space
// and are we using the encoded word variant of QuotedPrintable
if (currentChar == '_' && encodedWordVariant)
{
// The RFC specifies that the "_" always represents hexadecimal 20 even if the
// SPACE character occupies a different code position in the character set in use.
byteArrayBuilder.WriteByte(0x20);
}
else
{
// This is not encoded at all. This is a literal which should just be included into the output.
byteArrayBuilder.WriteByte((byte)currentChar);
}
}
}
return byteArrayBuilder.ToArray();
}
}
/// <summary>
/// Writes all bytes in a byte array to a stream
/// </summary>
/// <param name="stream">The stream to write to</param>
/// <param name="toWrite">The bytes to write to the <paramref name="stream"/></param>
private static void WriteAllBytesToStream(Stream stream, byte[] toWrite)
{
stream.Write(toWrite, 0, toWrite.Length);
}
/// <summary>
/// RFC 2045 states about robustness:<br/>
/// <code>
/// Control characters other than TAB, or CR and LF as parts of CRLF pairs,
/// must not appear. The same is true for octets with decimal values greater
/// than 126. If found in incoming quoted-printable data by a decoder, a
/// robust implementation might exclude them from the decoded data and warn
/// the user that illegal characters were discovered.
/// </code>
/// Control characters are defined in RFC 2396 as<br/>
/// <c>control = US-ASCII coded characters 00-1F and 7F hexadecimal</c>
/// </summary>
/// <param name="input">String to be stripped from illegal control characters</param>
/// <returns>A string with no illegal control characters</returns>
/// <exception cref="ArgumentNullException">If <paramref name="input"/> is <see langword="null"/></exception>
private static string RemoveIllegalControlCharacters(string input)
{
if(input == null)
throw new ArgumentNullException("input");
// First we remove any \r or \n which is not part of a \r\n pair
input = RemoveCarriageReturnAndNewLinewIfNotInPair(input);
// Here only legal \r\n is left over
// We now simply keep them, and the \t which is also allowed
// \x0A = \n
// \x0D = \r
// \x09 = \t)
return Regex.Replace(input, "[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]", "");
}
/// <summary>
/// This method will remove any \r and \n which is not paired as \r\n
/// </summary>
/// <param name="input">String to remove lonely \r and \n's from</param>
/// <returns>A string without lonely \r and \n's</returns>
/// <exception cref="ArgumentNullException">If <paramref name="input"/> is <see langword="null"/></exception>
private static string RemoveCarriageReturnAndNewLinewIfNotInPair(string input)
{
if (input == null)
throw new ArgumentNullException("input");
// Use this for building up the new string. This is used for performance instead
// of altering the input string each time a illegal token is found
StringBuilder newString = new StringBuilder(input.Length);
for (int i = 0; i < input.Length; i++)
{
// There is a character after it
// Check for lonely \r
// There is a lonely \r if it is the last character in the input or if there
// is no \n following it
if (input[i] == '\r' && (i + 1 >= input.Length || input[i + 1] != '\n'))
{
// Illegal token \r found. Do not add it to the new string
// Check for lonely \n
// There is a lonely \n if \n is the first character or if there
// is no \r in front of it
} else if (input[i] == '\n' && (i - 1 < 0 || input[i - 1] != '\r'))
{
// Illegal token \n found. Do not add it to the new string
} else
{
// No illegal tokens found. Simply insert the character we are at
// in our new string
newString.Append(input[i]);
}
}
return newString.ToString();
}
/// <summary>
/// RFC 2045 says that a robust implementation should handle:<br/>
/// <code>
/// An "=" cannot be the ultimate or penultimate character in an encoded
/// object. This could be handled as in case (2) above.
/// </code>
/// Case (2) is:<br/>
/// <code>
/// An "=" followed by a character that is neither a
/// hexadecimal digit (including "abcdef") nor the CR character of a CRLF pair
/// is illegal. This case can be the result of US-ASCII text having been
/// included in a quoted-printable part of a message without itself having
/// been subjected to quoted-printable encoding. A reasonable approach by a
/// robust implementation might be to include the "=" character and the
/// following character in the decoded data without any transformation and, if
/// possible, indicate to the user that proper decoding was not possible at
/// this point in the data.
/// </code>
/// </summary>
/// <param name="decode">
/// The string to decode which cannot have length above or equal to 3
/// and must start with an equal sign.
/// </param>
/// <returns>A decoded byte array</returns>
/// <exception cref="ArgumentNullException">If <paramref name="decode"/> is <see langword="null"/></exception>
/// <exception cref="ArgumentException">Thrown if a the <paramref name="decode"/> parameter has length above 2 or does not start with an equal sign.</exception>
private static byte[] DecodeEqualSignNotLongEnough(string decode)
{
if (decode == null)
throw new ArgumentNullException("decode");
// We can only decode wrong length equal signs
if (decode.Length >= 3)
throw new ArgumentException("decode must have length lower than 3", "decode");
// First char must be =
if (decode[0] != '=')
throw new ArgumentException("First part of decode must be an equal sign", "decode");
// We will now believe that the string sent to us, was actually not encoded
// Therefore it must be in US-ASCII and we will return the bytes it corrosponds to
return Encoding.ASCII.GetBytes(decode);
}
/// <summary>
/// This helper method will decode a string of the form "=XX" where X is any character.<br/>
/// This method will never fail, unless an argument of length not equal to three is passed.
/// </summary>
/// <param name="decode">The length 3 character that needs to be decoded</param>
/// <returns>A decoded byte array</returns>
/// <exception cref="ArgumentNullException">If <paramref name="decode"/> is <see langword="null"/></exception>
/// <exception cref="ArgumentException">Thrown if a the <paramref name="decode"/> parameter does not have length 3 or does not start with an equal sign.</exception>
private static byte[] DecodeEqualSign(string decode)
{
if (decode == null)
throw new ArgumentNullException("decode");
// We can only decode the string if it has length 3 - other calls to this function is invalid
if (decode.Length != 3)
throw new ArgumentException("decode must have length 3", "decode");
// First char must be =
if (decode[0] != '=')
throw new ArgumentException("decode must start with an equal sign", "decode");
// There are two cases where an equal sign might appear
// It might be a
// - hex-string like =3D, denoting the character with hex value 3D
// - it might be the last character on the line before a CRLF
// pair, denoting a soft linebreak, which simply
// splits the text up, because of the 76 chars per line restriction
if (decode.Contains("\r\n"))
{
// Soft break detected
// We want to return string.Empty which is equivalent to a zero-length byte array
return new byte[0];
}
// Hex string detected. Convertion needed.
// It might be that the string located after the equal sign is not hex characters
// An example: =JU
// In that case we would like to catch the FormatException and do something else
try
{
// The number part of the string is the last two digits. Here we simply remove the equal sign
string numberString = decode.Substring(1);
// Now we create a byte array with the converted number encoded in the string as a hex value (base 16)
// This will also handle illegal encodings like =3d where the hex digits are not uppercase,
// which is a robustness requirement from RFC 2045.
byte[] oneByte = new[] { Convert.ToByte(numberString, 16) };
// Simply return our one byte byte array
return oneByte;
} catch (FormatException)
{
// RFC 2045 says about robust implementation:
// An "=" followed by a character that is neither a
// hexadecimal digit (including "abcdef") nor the CR
// character of a CRLF pair is illegal. This case can be
// the result of US-ASCII text having been included in a
// quoted-printable part of a message without itself
// having been subjected to quoted-printable encoding. A
// reasonable approach by a robust implementation might be
// to include the "=" character and the following
// character in the decoded data without any
// transformation and, if possible, indicate to the user
// that proper decoding was not possible at this point in
// the data.
// So we choose to believe this is actually an un-encoded string
// Therefore it must be in US-ASCII and we will return the bytes it corrosponds to
return Encoding.ASCII.GetBytes(decode);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Web;
using System.Web.Hosting;
using Orchard.Specs.Util;
using Path = Bleroy.FluentPath.Path;
namespace Orchard.Specs.Hosting {
public class WebHost {
private readonly Path _orchardTemp;
private WebHostAgent _webHostAgent;
private Path _tempSite;
private Path _orchardWebPath;
private Path _codeGenDir;
private IEnumerable<string> _knownModules;
private IEnumerable<string> _knownThemes;
private IEnumerable<string> _knownBinAssemblies;
public WebHost(Path orchardTemp) {
_orchardTemp = orchardTemp;
}
public void Initialize(string templateName, string virtualDirectory, DynamicCompilationOption dynamicCompilationOption) {
var stopwatch = new Stopwatch();
stopwatch.Start();
var baseDir = Path.Get(AppDomain.CurrentDomain.BaseDirectory);
_tempSite = _orchardTemp.Combine(System.IO.Path.GetRandomFileName());
try { _tempSite.Delete(); }
catch { }
// Trying the two known relative paths to the Orchard.Web directory.
// The second one is for the target "spec" in orchard.proj.
_orchardWebPath = baseDir;
while (!_orchardWebPath.Combine("Orchard.proj").Exists && _orchardWebPath.Parent != null) {
_orchardWebPath = _orchardWebPath.Parent;
}
_orchardWebPath = _orchardWebPath.Combine("src").Combine("Orchard.Web");
Log("Initialization of ASP.NET host for template web site \"{0}\":", templateName);
Log(" Source location: \"{0}\"", _orchardWebPath);
Log(" Temporary location: \"{0}\"", _tempSite);
_knownModules = _orchardWebPath.Combine("Modules").Directories.Where(d => d.Combine("module.txt").Exists).Select(d => d.FileName).ToList();
//foreach (var filename in _knownModules)
// Log("Available Module: \"{0}\"", filename);
_knownThemes = _orchardWebPath.Combine("Themes").Directories.Where(d => d.Combine("theme.txt").Exists).Select(d => d.FileName).ToList();
//foreach (var filename in _knownThemes)
// Log("Available Theme: \"{0}\"", filename);
_knownBinAssemblies = _orchardWebPath.Combine("bin").GetFiles("*.dll").Select(f => f.FileNameWithoutExtension);
//foreach (var filename in _knownBinAssemblies)
// Log("Assembly in ~/bin: \"{0}\"", filename);
Log("Copy files from template \"{0}\"", templateName);
baseDir.Combine("Hosting").Combine(templateName)
.DeepCopy(_tempSite);
if (dynamicCompilationOption != DynamicCompilationOption.Enabled) {
var sourceConfig = baseDir.Combine("Hosting").Combine("TemplateConfigs");
var siteConfig = _tempSite.Combine("Config");
switch (dynamicCompilationOption) {
case DynamicCompilationOption.Disabled:
File.Copy(sourceConfig.Combine("DisableDynamicCompilation.HostComponents.config"), siteConfig.Combine("HostComponents.config"));
break;
case DynamicCompilationOption.Force:
File.Copy(sourceConfig.Combine("ForceDynamicCompilation.HostComponents.config"), siteConfig.Combine("HostComponents.config"));
break;
}
}
Log("Copy binaries of the \"Orchard.Web\" project");
_orchardWebPath.Combine("bin")
.ShallowCopy("*.dll", _tempSite.Combine("bin"))
.ShallowCopy("*.pdb", _tempSite.Combine("bin"));
Log("Copy SqlCe native binaries");
if (_orchardWebPath.Combine("bin").Combine("x86").IsDirectory) {
_orchardWebPath.Combine("bin").Combine("x86")
.DeepCopy("*.*", _tempSite.Combine("bin").Combine("x86"));
}
if (_orchardWebPath.Combine("bin").Combine("amd64").IsDirectory) {
_orchardWebPath.Combine("bin").Combine("amd64")
.DeepCopy("*.*", _tempSite.Combine("bin").Combine("amd64"));
}
// Copy binaries of this project, so that remote execution of lambda
// can be achieved through serialization to the ASP.NET appdomain
// (see Execute(Action) method)
Log("Copy Orchard.Specflow test project binaries");
baseDir.ShallowCopy(
path => IsSpecFlowTestAssembly(path) && !_tempSite.Combine("bin").Combine(path.FileName).Exists,
_tempSite.Combine("bin"));
Log("Copy Orchard recipes");
_orchardWebPath.Combine("Modules").Combine("Orchard.Setup").Combine("Recipes").DeepCopy("*.xml", _tempSite.Combine("Modules").Combine("Orchard.Setup").Combine("Recipes"));
StartAspNetHost(virtualDirectory);
Log("ASP.NET host initialization completed in {0} sec", stopwatch.Elapsed.TotalSeconds);
}
private void StartAspNetHost(string virtualDirectory) {
Log("Starting up ASP.NET host");
HostName = "localhost";
PhysicalDirectory = _tempSite;
VirtualDirectory = virtualDirectory;
_webHostAgent = (WebHostAgent)ApplicationHost.CreateApplicationHost(typeof(WebHostAgent), VirtualDirectory, PhysicalDirectory);
var shuttle = new Shuttle();
Execute(() => { shuttle.CodeGenDir = HttpRuntime.CodegenDir; });
// ASP.NET folder seems to be always nested into an empty directory
_codeGenDir = shuttle.CodeGenDir;
_codeGenDir = _codeGenDir.Parent;
Log("ASP.NET CodeGenDir: \"{0}\"", _codeGenDir);
}
[Serializable]
public class Shuttle {
public string CodeGenDir;
}
public void Dispose() {
if (_webHostAgent != null) {
_webHostAgent.Shutdown();
_webHostAgent = null;
}
Clean();
}
private void Log(string format, params object[] args) {
Trace.WriteLine(string.Format(format, args));
}
public void Clean() {
// Try to delete temporary files for up to ~1.2 seconds.
for (int i = 0; i < 4; i++) {
Log("Waiting 300msec before trying to delete temporary files");
Thread.Sleep(300);
if (TryDeleteTempFiles(i == 4)) {
Log("Successfully deleted all temporary files");
break;
}
}
}
private bool TryDeleteTempFiles(bool lastTry) {
var result = true;
if (_codeGenDir != null && _codeGenDir.Exists) {
Log("Trying to delete temporary files at \"{0}\"", _codeGenDir);
try {
_codeGenDir.Delete(true); // <- clean as much as possible
}
catch (Exception e) {
if (lastTry)
Log("Failure: \"{0}\"", e);
result = false;
}
}
if (_tempSite != null && _tempSite.Exists)
try {
Log("Trying to delete temporary files at \"{0}\"", _tempSite);
_tempSite.Delete(true); // <- progressively clean as much as possible
}
catch (Exception e) {
if (lastTry)
Log("failure: \"{0}\"", e);
result = false;
}
return result;
}
public void CopyExtension(string extensionFolder, string extensionName, ExtensionDeploymentOptions deploymentOptions) {
Log("Copy extension \"{0}\\{1}\" (options={2})", extensionFolder, extensionName, deploymentOptions);
var sourceModule = _orchardWebPath.Combine(extensionFolder).Combine(extensionName);
var targetModule = _tempSite.Combine(extensionFolder).Combine(extensionName);
sourceModule.ShallowCopy("*.txt", targetModule);
sourceModule.ShallowCopy("*.info", targetModule);
sourceModule.ShallowCopy("*.config", targetModule);
if ((deploymentOptions & ExtensionDeploymentOptions.SourceCode) == ExtensionDeploymentOptions.SourceCode) {
sourceModule.ShallowCopy("*.csproj", targetModule);
sourceModule.DeepCopy("*.cs", targetModule);
}
if (sourceModule.Combine("bin").IsDirectory) {
sourceModule.Combine("bin").ShallowCopy(path => IsExtensionBinaryFile(path, extensionName, deploymentOptions), targetModule.Combine("bin"));
}
if (sourceModule.Combine("Views").IsDirectory)
sourceModule.Combine("Views").DeepCopy(targetModule.Combine("Views"));
// don't copy content folders as they are useless in this headless scenario
}
public void CopyFile(string source, string destination) {
StackTrace st = new StackTrace(true);
Path origin = null;
foreach(var sf in st.GetFrames()) {
var sourceFile = sf.GetFileName();
if(String.IsNullOrEmpty(sourceFile)) {
continue;
}
var testOrigin = Path.Get(sourceFile).Parent.Combine(source);
if(testOrigin.Exists) {
origin = testOrigin;
break;
}
}
if(origin == null) {
throw new FileNotFoundException("File not found: " + source);
}
var target = _tempSite.Combine(destination);
Directory.CreateDirectory(target.DirectoryName);
File.Copy(origin, target);
}
private bool IsExtensionBinaryFile(Path path, string extensionName, ExtensionDeploymentOptions deploymentOptions) {
bool isValidExtension = IsAssemblyFile(path);
if (!isValidExtension)
return false;
bool isAssemblyInWebAppBin = _knownBinAssemblies.Contains(path.FileNameWithoutExtension, StringComparer.OrdinalIgnoreCase);
if (isAssemblyInWebAppBin)
return false;
bool isExtensionAssembly = IsOrchardExtensionFile(path);
bool copyExtensionAssembly = (deploymentOptions & ExtensionDeploymentOptions.CompiledAssembly) == ExtensionDeploymentOptions.CompiledAssembly;
if (isExtensionAssembly && !copyExtensionAssembly)
return false;
return true;
}
private bool IsSpecFlowTestAssembly(Path path) {
if (!IsAssemblyFile(path))
return false;
if (IsOrchardExtensionFile(path))
return false;
return true;
}
private bool IsAssemblyFile(Path path) {
return StringComparer.OrdinalIgnoreCase.Equals(path.Extension, ".exe") ||
StringComparer.OrdinalIgnoreCase.Equals(path.Extension, ".dll") ||
StringComparer.OrdinalIgnoreCase.Equals(path.Extension, ".pdb");
}
private bool IsOrchardExtensionFile(Path path) {
return _knownModules.Where(name => StringComparer.OrdinalIgnoreCase.Equals(name, path.FileNameWithoutExtension)).Any() ||
_knownThemes.Where(name => StringComparer.OrdinalIgnoreCase.Equals(name, path.FileNameWithoutExtension)).Any();
}
public string HostName { get; set; }
public string PhysicalDirectory { get; private set; }
public string VirtualDirectory { get; private set; }
public string Cookies { get; set; }
public void Execute(Action action) {
var shuttleSend = new SerializableDelegate<Action>(action);
var shuttleRecv = _webHostAgent.Execute(shuttleSend);
CopyFields(shuttleRecv.Delegate.Target, shuttleSend.Delegate.Target);
}
private static void CopyFields<T>(T from, T to) where T : class {
if (from == null || to == null)
return;
foreach (FieldInfo fieldInfo in from.GetType().GetFields()) {
var value = fieldInfo.GetValue(from);
fieldInfo.SetValue(to, value);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Management.Automation;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
namespace Erwine.Leonard.T.GDIPlus
{
/// <summary>
/// Model representing a color in terms of hue, saturation and brightness as floating-point values.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct HsbColorF : IEquatable<HsbColorF>, IEquatable<IHsbColorModel<byte>>, IEquatable<IRgbColorModel<byte>>, IHsbColorModel<float>
{
private readonly float _alpha, _hue, _saturation, _brightness;
#region Properties
/// <summary>
/// The opaqueness of the color.
/// </summary>
public float Alpha { get { return _alpha; } }
/// <summary>
/// The hue of the color.
/// </summary>
public float Hue { get { return _hue; } }
/// <summary>
/// The color saturation.
/// </summary>
public float Saturation { get { return _saturation; } }
/// <summary>
/// The brightness of the color.
/// </summary>
public float Brightness { get { return _brightness; } }
bool IColorModel.IsNormalized { get { return false; } }
ColorStringFormat IColorModel.DefaultStringFormat { get { return ColorStringFormat.HSLAPercent; } }
#endregion
#region Constructors
/// <summary>
///
/// </summary>
/// <param name="hue"></param>
/// <param name="saturation"></param>
/// <param name="brightness"></param>
/// <param name="alpha"></param>
public HsbColorF(float hue, float saturation, float brightness, float alpha)
{
if (hue < 0f || hue > ColorExtensions.HUE_MAXVALUE)
throw new ArgumentOutOfRangeException("hue");
if (saturation < 0f || saturation > 1f)
throw new ArgumentOutOfRangeException("saturation");
if (brightness < 0f || brightness > 1f)
throw new ArgumentOutOfRangeException("brightness");
if (alpha < 0f || alpha > 1f)
throw new ArgumentOutOfRangeException("alpha");
_hue = (hue == ColorExtensions.HUE_MAXVALUE) ? 0f : hue;
_saturation = saturation;
_brightness = brightness;
_alpha = alpha;
}
/// <summary>
///
/// </summary>
/// <param name="hue"></param>
/// <param name="saturation"></param>
/// <param name="brightness"></param>
public HsbColorF(float hue, float saturation, float brightness) : this(hue, saturation, brightness, 1f) { }
/// <summary>
///
/// </summary>
/// <param name="value"></param>
public HsbColorF(HsbColor32 value)
{
_hue = value.Hue.ToDegrees();
_saturation = value.Saturation.ToPercentage();
_brightness = value.Brightness.ToPercentage();
_alpha = value.Alpha.ToPercentage();
}
/// <summary>
///
/// </summary>
/// <param name="ahsb"></param>
public HsbColorF(int ahsb)
{
byte[] values = BitConverter.GetBytes(ahsb);
_brightness = values[0].ToPercentage();
_saturation = values[1].ToPercentage();
_hue = values[2].ToDegrees();
_alpha = values[3].ToPercentage();
}
#endregion
#region As* Methods
/// <summary>
///
/// </summary>
/// <returns></returns>
public HsbColor32 AsHsb32() { return new HsbColor32(this); }
IHsbColorModel<byte> IColorModel.AsHsb32() { return AsHsb32(); }
IHsbColorModel<float> IColorModel.AsHsbF() { return this; }
/// <summary>
///
/// </summary>
/// <returns></returns>
public RgbColor32 AsRgb32() { return new RgbColor32(this); }
IRgbColorModel<byte> IColorModel.AsRgb32() { return AsRgb32(); }
/// <summary>
///
/// </summary>
/// <returns></returns>
public RgbColorF AsRgbF() { return new RgbColorF(this); }
IRgbColorModel<float> IColorModel.AsRgbF() { return AsRgbF(); }
/// <summary>
///
/// </summary>
/// <returns></returns>
public HsbColorFNormalized AsNormalized() { return new HsbColorFNormalized(this); }
IHsbColorModel<float> IHsbColorModel<float>.AsNormalized() { return AsNormalized(); }
IColorModel<float> IColorModel<float>.AsNormalized() { return AsNormalized(); }
IColorModel IColorModel.AsNormalized() { return AsNormalized(); }
#endregion
#region Equals Methods
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <param name="exact"></param>
/// <returns></returns>
public bool Equals(IRgbColorModel<float> other, bool exact)
{
if (other == null || _alpha != other.Alpha)
return false;
float b;
if (exact)
{
ColorExtensions.RGBtoHSB(other.Red, other.Green, other.Blue, out float h, out float s, out b);
return _hue == h && _saturation == s && _brightness == b;
}
ColorExtensions.HSBtoRGB(_hue, _saturation, _brightness, out float r, out float g, out b);
return other.Red == r && other.Green == g && other.Blue == b;
}
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <param name="exact"></param>
/// <returns></returns>
public bool Equals(IRgbColorModel<byte> other, bool exact)
{
if (other == null)
return false;
float b;
if (exact)
{
if (other.Alpha.ToPercentage() != _alpha)
return false;
ColorExtensions.RGBtoHSB(other.Red.ToPercentage(), other.Green.ToPercentage(), other.Blue.ToPercentage(), out float h, out float s, out b);
return _hue == h && _saturation == s && _brightness == b;
}
return AsNormalized().Equals(other, false);
}
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <param name="exact"></param>
/// <returns></returns>
public bool Equals(IHsbColorModel<byte> other, bool exact)
{
if (other == null)
return false;
if (exact)
return _alpha == other.Alpha.ToPercentage() && _hue == other.Hue.ToDegrees() && _saturation == other.Saturation.ToPercentage() && _brightness == other.Brightness.ToPercentage();
if (!other.IsNormalized)
other = other.AsNormalized();
return _alpha.FromPercentage() == other.Alpha && _hue.FromDegrees() == other.Hue && _saturation.FromPercentage() == other.Saturation && _brightness.FromPercentage() == other.Brightness;
}
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <param name="exact"></param>
/// <returns></returns>
public bool Equals(IColorModel other, bool exact)
{
if (other == null)
return false;
if (other is HsbColorF)
return Equals((HsbColorF)other);
if (other is IHsbColorModel<float>)
return Equals((IHsbColorModel<float>)other);
if (other is IHsbColorModel<byte>)
return Equals((IHsbColorModel<byte>)other, exact);
if (other is IRgbColorModel<float>)
return Equals((IRgbColorModel<float>)other, exact);
return other is IRgbColorModel<byte> && Equals((IRgbColorModel<byte>)other, exact);
}
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(HsbColorF other) { return other._alpha == _alpha && other._hue == _hue && other._saturation == _saturation && other._brightness == _brightness; }
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(IHsbColorModel<byte> other) { return Equals(other, false); }
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(IRgbColorModel<byte> other) { return Equals(other, false); }
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(IHsbColorModel<float> other) { return other.Alpha == _alpha && other.Hue == _hue && other.Saturation == _saturation && other.Brightness == _brightness; }
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(IRgbColorModel<float> other) { return Equals(other, false); }
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(IColorModel other) { return Equals(other, false); }
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(System.Drawing.Color other)
{
if (other.A != _alpha.FromPercentage())
return false;
ColorExtensions.HSBtoRGB(_hue, _saturation, _brightness, out float r, out float g, out float b);
return r.FromPercentage() == other.R && g.FromPercentage() == other.G && b.FromPercentage() == other.B;
}
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public bool Equals(System.Windows.Media.Color other)
{
if (other.A != _alpha.FromPercentage())
return false;
ColorExtensions.HSBtoRGB(_hue, _saturation, _brightness, out float r, out float g, out float b);
return r.FromPercentage() == other.R && g.FromPercentage() == other.G && b.FromPercentage() == other.B;
}
/// <summary>
///
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
if (obj == null)
return false;
object value = (obj is PSObject) ? ((PSObject)obj).BaseObject : obj;
if (value is HsbColorF)
return Equals((HsbColorF)value);
if (value is IHsbColorModel<byte>)
return Equals((IHsbColorModel<byte>)value);
if (value is IHsbColorModel<float>)
return Equals((IHsbColorModel<float>)value, false);
if (value is IRgbColorModel<byte>)
return Equals((IRgbColorModel<byte>)value, false);
if (value is IRgbColorModel<float>)
return Equals((IRgbColorModel<float>)value, false);
if (value is int)
return Equals((int)value);
value = ColorExtensions.AsSimplestType(value);
if (value is string)
return (string)value == ToString();
if (value is int)
return ToAHSB() == (int)value;
if (value is float)
return ToAHSB() == (float)value;
if (obj is PSObject && ColorExtensions.TryGetColor((PSObject)obj, out IColorModel color))
return Equals(color.AsHsbF());
return false;
}
#endregion
/// <summary>
/// Returns the hash code for this value.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode() { return ToAHSB(); }
#region MergeAverage Method
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public IHsbColorModel<float> MergeAverage(IEnumerable<IHsbColorModel<float>> other)
{
if (other == null)
return this;
ColorExtensions.HSBtoRGB(_hue, _saturation, _brightness, out float rF, out float gF, out float bF);
double r = rF, g = gF, b = bF, a = _alpha;
double brightness = _brightness;
int count = 0;
foreach (IHsbColorModel<float> item in other)
{
if (item != null)
{
count++;
ColorExtensions.HSBtoRGB(item.Hue, item.Saturation, item.Brightness, out rF, out gF, out bF);
r += (double)rF;
g += (double)gF;
b += (double)bF;
a += (double)item.Alpha;
brightness += (double)item.Brightness;
}
}
if (count == 0)
return this;
ColorExtensions.RGBtoHSB((float)(r / (double)count), (float)(r / (double)count), (float)(r / (double)count), out float h, out float s, out bF);
return new HsbColorFNormalized(h, s, bF, (float)(a / (double)count));
}
/// <summary>
///
/// </summary>
/// <param name="other"></param>
/// <returns></returns>
public IHsbColorModel<float> MergeAverage(IEnumerable<IColorModel> other)
{
throw new NotImplementedException();
}
IColorModel IColorModel.MergeAverage(IEnumerable<IColorModel> other) { return MergeAverage(other); }
#endregion
#region ShiftHue Method
/// <summary>
/// Returns a <see cref="HsbColorF" /> value with the color hue adjusted.
/// </summary>
/// <param name="degrees">The number of degrees to shift the hue value, ranging from -360.0 to 360.0. A positive value shifts the hue in the red-to-cyan direction, and a negative value shifts the hue in the cyan-to-red direction.</param>
/// <returns>A <see cref="HsbColorF" /> value with the color hue adjusted.</returns>
/// <remarks>The values 0.0, -360.0 and 360.0 have no effect since they would result in no hue change.</remarks>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="degrees" /> is less than -360.0 or <paramref name="degrees" /> is greater than 360.0.</exception>
public HsbColorF ShiftHue(float degrees)
{
if (degrees < -360f || degrees > 360f)
throw new ArgumentOutOfRangeException("degrees");
if (degrees == 0f || degrees == 360f || degrees == -360f)
return this;
float hue = _hue + degrees;
if (hue < 0f)
hue += 360f;
else if (hue >= 360f)
hue -= 360f;
return new HsbColorF(hue, _saturation, _brightness, _alpha);
}
IHsbColorModel<float> IHsbColorModel<float>.ShiftHue(float degrees) { return ShiftHue(degrees); }
IColorModel<float> IColorModel<float>.ShiftHue(float degrees) { return ShiftHue(degrees); }
IColorModel IColorModel.ShiftHue(float degrees) { return ShiftHue(degrees); }
#endregion
#region ShiftSaturation Method
/// <summary>
/// Returns a <see cref="HsbColorF" /> value with the color saturation adjusted.
/// </summary>
/// <param name="percentage">The percentage to saturate the color, ranging from -1.0 to 1.0. A positive value increases saturation, a negative value decreases saturation and a zero vale has no effect.</param>
/// <returns>A <see cref="HsbColorF" /> value with the color saturation adjusted.</returns>
/// <remarks>For positive values, the target saturation value is determined using the following formula: <c>saturation + (1.0 - saturation) * percentage</c>
/// <para>For negative values, the target saturation value is determined using the following formula: <c>saturation + saturation * percentage</c></para></remarks>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="percentage" /> is less than -1.0 or <paramref name="percentage" /> is greater than 1.0.</exception>
public HsbColorF ShiftSaturation(float percentage)
{
if (percentage < -1f || percentage > 1f)
throw new ArgumentOutOfRangeException("percentage");
if (percentage == 0f || (percentage == 1f) ? _saturation == 1f : percentage == -1f && _saturation == 0f)
return this;
return new HsbColorF(_hue, _saturation + ((percentage > 0f) ? (1f - _saturation) : _saturation) * percentage, _brightness, _alpha);
}
IHsbColorModel<float> IHsbColorModel<float>.ShiftSaturation(float percentage) { return ShiftSaturation(percentage); }
IColorModel<float> IColorModel<float>.ShiftSaturation(float percentage) { return ShiftSaturation(percentage); }
IColorModel IColorModel.ShiftSaturation(float percentage) { return ShiftSaturation(percentage); }
#endregion
#region ShiftBrightness Method
/// <summary>
/// Returns a <see cref="HsbColorF" /> value with the color brightness adjusted.
/// </summary>
/// <param name="percentage">The percentage to saturate the color, ranging from -1.0 to 1.0. A positive value increases brightness, a negative value decreases brightness and a zero vale has no effect.</param>
/// <returns>A <see cref="HsbColorF" /> value with the color brightness adjusted.</returns>
/// <remarks>For positive values, the target brightness value is determined using the following formula: <c>brightness + (1.0 - brightness) * percentage</c>
/// <para>For negative values, the target brightness value is determined using the following formula: <c>brightness + brightness * percentage</c></para></remarks>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="percentage" /> is less than -1.0 or <paramref name="percentage" /> is greater than 1.0.</exception>
public HsbColorF ShiftBrightness(float percentage)
{
if (percentage < -1f || percentage > 1f)
throw new ArgumentOutOfRangeException("percentage");
if (percentage == 0f || (percentage == 1f) ? _brightness == 1f : percentage == -1f && _brightness == 0f)
return this;
return new HsbColorF(_hue, _saturation, _brightness + ((percentage > 0f) ? (1f - _brightness) : _brightness) * percentage, _alpha);
}
IHsbColorModel<float> IHsbColorModel<float>.ShiftBrightness(float percentage) { return ShiftBrightness(percentage); }
IColorModel<float> IColorModel<float>.ShiftBrightness(float percentage) { return ShiftBrightness(percentage); }
IColorModel IColorModel.ShiftBrightness(float percentage) { return ShiftBrightness(percentage); }
#endregion
/// <summary>
/// Gets the AHSB integer value for the current <see cref="HsbColorF" /> value.
/// </summary>
/// <returns>The AHSB integer value for the current <see cref="HsbColorF" /> value.</returns>
public int ToAHSB() { return BitConverter.ToInt32(new byte[] { _brightness.FromPercentage(), _saturation.FromPercentage(), _hue.FromPercentage(), _alpha.FromPercentage() }, 0); }
#region ToString Methods
/// <summary>
/// Gets formatted string representing the current color value.
/// </summary>
/// <param name="format">The color string format to use.</param>
/// <returns>The formatted string representing the current color value.</returns>
public string ToString(ColorStringFormat format)
{
float r, g, b;
switch (format)
{
case ColorStringFormat.HSLAHex:
return HsbColor32.ToHexidecimalString(_hue.FromDegrees(), _saturation.FromPercentage(), _brightness.FromPercentage(), _alpha.FromPercentage(), false);
case ColorStringFormat.HSLAHexOpt:
return HsbColor32.ToHexidecimalString(_hue.FromDegrees(), _saturation.FromPercentage(), _brightness.FromPercentage(), _alpha.FromPercentage(), true);
case ColorStringFormat.HSLAValues:
return HsbColor32.ToValueParameterString(_hue.FromDegrees(), _saturation.FromPercentage(), _brightness.FromPercentage(), _alpha);
case ColorStringFormat.HSLHex:
return HsbColor32.ToHexidecimalString(_hue.FromDegrees(), _saturation.FromPercentage(), _brightness.FromPercentage(), false);
case ColorStringFormat.HSLHexOpt:
return HsbColor32.ToHexidecimalString(_hue.FromDegrees(), _saturation.FromPercentage(), _brightness.FromPercentage(), true);
case ColorStringFormat.HSLPercent:
return HsbColorF.ToPercentParameterString(_hue, _saturation, _brightness);
case ColorStringFormat.HSLValues:
return HsbColor32.ToValueParameterString(_hue.FromDegrees(), _saturation.FromPercentage(), _brightness.FromPercentage());
case ColorStringFormat.RGBAHex:
ColorExtensions.HSBtoRGB(_hue, _saturation, _brightness, out r, out g, out b);
return RgbColor32.ToHexidecimalString(r.FromPercentage(), g.FromPercentage(), b.FromPercentage(), _alpha.FromPercentage(), false);
case ColorStringFormat.RGBAHexOpt:
ColorExtensions.HSBtoRGB(_hue, _saturation, _brightness, out r, out g, out b);
return RgbColor32.ToHexidecimalString(r.FromPercentage(), g.FromPercentage(), b.FromPercentage(), _alpha.FromPercentage(), true);
case ColorStringFormat.RGBAPercent:
ColorExtensions.HSBtoRGB(_hue, _saturation, _brightness, out r, out g, out b);
return RgbColorF.ToPercentParameterString(r, g, b, _alpha);
case ColorStringFormat.RGBAValues:
ColorExtensions.HSBtoRGB(_hue, _saturation, _brightness, out r, out g, out b);
return RgbColor32.ToValueParameterString(r.FromPercentage(), g.FromPercentage(), b.FromPercentage(), _alpha.FromPercentage());
case ColorStringFormat.RGBHex:
ColorExtensions.HSBtoRGB(_hue, _saturation, _brightness, out r, out g, out b);
return RgbColor32.ToHexidecimalString(r.FromPercentage(), g.FromPercentage(), b.FromPercentage(), false);
case ColorStringFormat.RGBHexOpt:
ColorExtensions.HSBtoRGB(_hue, _saturation, _brightness, out r, out g, out b);
return RgbColor32.ToHexidecimalString(r.FromPercentage(), g.FromPercentage(), b.FromPercentage(), true);
case ColorStringFormat.RGBPercent:
ColorExtensions.HSBtoRGB(_hue, _saturation, _brightness, out r, out g, out b);
return RgbColorF.ToPercentParameterString(r, g, b);
case ColorStringFormat.RGBValues:
ColorExtensions.HSBtoRGB(_hue, _saturation, _brightness, out r, out g, out b);
return RgbColor32.ToValueParameterString(r.FromPercentage(), g.FromPercentage(), b.FromPercentage());
}
return HsbColorF.ToPercentParameterString(_hue, _saturation, _brightness, _alpha);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public override string ToString(){ return HsbColorF.ToPercentParameterString(_hue, _saturation, _brightness, _alpha); }
/// <summary>
///
/// </summary>
/// <param name="h"></param>
/// <param name="s"></param>
/// <param name="b"></param>
/// <param name="a"></param>
/// <returns></returns>
public static string ToPercentParameterString(float h, float s, float b, float a)
{
return "hsla(" + Math.Round(h, 0).ToString() + ", " + Math.Round(Convert.ToDouble(s * 100f), 0).ToString() + "%, " +
Math.Round(Convert.ToDouble(b * 100f), 0).ToString() + "%, " + Math.Round(Convert.ToDouble(a * 100f), 0).ToString() + "%)";
}
/// <summary>
///
/// </summary>
/// <param name="h"></param>
/// <param name="s"></param>
/// <param name="b"></param>
/// <returns></returns>
public static string ToPercentParameterString(float h, float s, float b)
{
return "hsl(" + Math.Round(h, 0).ToString() + ", " + Math.Round(Convert.ToDouble(s * 100f), 0).ToString() + "%, " +
Math.Round(Convert.ToDouble(b * 100f), 0).ToString() + "%)";
}
#endregion
/// <summary>
///
/// </summary>
/// <param name="text"></param>
/// <param name="result"></param>
/// <returns></returns>
public static bool TryParse(string text, out HsbColorF result) { return TryParse(text, false, out result); }
internal static bool TryParse(string text, bool strict, out HsbColorF result)
{
if (text != null && (text = text.Trim()).Length > 0)
{
Match match = HsbColor32.ParseRegex.Match(text);
if (match.Success)
{
try
{
if (match.Groups["h"].Success)
{
switch (text.Length)
{
case 3:
result = new HsbColorF(int.Parse(new string(new char[] { text[0], text[0], text[1], text[1], text[2], text[2]}), NumberStyles.HexNumber) << 8);
break;
case 4:
result = new HsbColorF(int.Parse(new string(new char[] { text[0], text[0], text[1], text[1], text[2], text[2]}), NumberStyles.HexNumber) << 8 | int.Parse(new string(new char[] { text[3], text[3] })));
break;
case 8:
result = new HsbColorF(int.Parse(text.Substring(0, 6), NumberStyles.HexNumber) << 8 | int.Parse(text.Substring(6), NumberStyles.HexNumber));
break;
default:
result = new HsbColorF(int.Parse(text, NumberStyles.HexNumber) << 8);
break;
}
return true;
}
float alpha = 100f;
if (!match.Groups["a"].Success || (((match.Groups["a"].Value.EndsWith("%")) ? (float.TryParse(match.Groups["a"].Value.Substring(0, match.Groups["a"].Length - 1), out alpha) && (alpha = alpha / 100f) <= 1f) : (float.TryParse(match.Groups["a"].Value, out alpha) && alpha <= 1f)) && alpha >= 0f))
{
if (match.Groups["b"].Success)
{
int h, s, l;
if (int.TryParse(match.Groups["h"].Value, out h) && h > -1 && h < 256 && int.TryParse(match.Groups["s"].Value, out s) && s > -1 && s < 256 &&
int.TryParse(match.Groups["l"].Value, out l) && l > -1 && l < 256)
{
result = new HsbColorF(((byte)h).ToDegrees(), ((byte)s).ToPercentage(), ((byte)l).ToPercentage(), alpha);
return true;
}
}
else if (float.TryParse(match.Groups["h"].Value, out float hF) && hF >= 0f && hF <= 360f && float.TryParse(match.Groups["s"].Value, out float sF) && sF >= 0f && sF <= 100f && float.TryParse(match.Groups["l"].Value, out float lF) && lF >= 0f && lF <= 100f)
{
result = new HsbColorF(hF, sF / 100f, lF / 100f, alpha);
return true;
}
}
}
catch { }
}
else if (!strict && RgbColorF.TryParse(text, true, out RgbColorF rgb))
{
ColorExtensions.RGBtoHSB(rgb.Red, rgb.Blue, rgb.Green, out float h, out float s, out float b);
result = new HsbColorF(h, s, b, rgb.Alpha);
return true;
}
}
result = default(HsbColorF);
return false;
}
}
}
| |
//
// SCSharp.Mpq.Dat
//
// Authors:
// Chris Toshok (toshok@gmail.com)
//
// Copyright 2006-2010 Chris Toshok
//
//
// 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.IO;
using System.Text;
using System.Collections.Generic;
namespace SCSharp
{
public abstract class Dat : MpqResource
{
protected byte[] buf;
List<DatVariable> variables;
Dictionary<int,DatCollection> collections;
protected Dat ()
{
variables = new List<DatVariable> ();
collections = new Dictionary<int,DatCollection> ();
}
public void ReadFromStream (Stream stream)
{
buf = new byte[(int)stream.Length];
stream.Read (buf, 0, buf.Length);
//Console.WriteLine ("buf size = {0}, offset = {0}", buf.Length, offset);
}
int offset = 0;
protected int AddVariableBlock (int num_entries, DatVariableType var)
{
DatVariable new_variable = new DatVariable (var, offset, num_entries);
int rv = variables.Count;
variables.Add (new_variable);
offset += new_variable.BlockSize ();
return rv;
}
protected void AddUnknownBlock (int size)
{
offset += size;
}
protected int AddPlacedVariableBlock (int place, int num_entries, DatVariableType var)
{
offset = place;
DatVariable new_variable = new DatVariable (var, offset, num_entries);
int rv = variables.Count;
variables.Add (new_variable);
offset += new_variable.BlockSize ();
return rv;
}
public int GetVariableOffset (int variableId)
{
return variables[variableId].Offset;
}
protected DatCollection GetCollection (int variableId)
{
if (collections.ContainsKey (variableId))
return collections[variableId];
DatCollection rv = variables[variableId].CreateCollection (buf);
collections[variableId] = rv;
return rv;
}
}
public enum DatVariableType {
Byte,
Word,
DWord
}
public class DatCollection {
}
public class DatCollection<T> : DatCollection {
byte[] buf;
DatVariable var;
public DatCollection (byte[] buf, DatVariable var)
: base ()
{
this.buf = buf;
this.var = var;
}
public int Count {
get { return var.NumEntries; }
}
public T this [int index] {
get { return (T)var[buf, index]; }
}
}
public class DatVariable {
DatVariableType type;
int offset;
int num_entries;
public DatVariable (DatVariableType type, int offset, int num_entries)
{
this.type = type;
this.offset = offset;
this.num_entries = num_entries;
}
public int Offset {
get { return offset; }
}
public int NumEntries {
get { return num_entries; }
}
public int BlockSize ()
{
switch (type) {
case DatVariableType.Byte:
return num_entries;
case DatVariableType.Word:
return num_entries * 2;
case DatVariableType.DWord:
return num_entries * 4;
default:
return 0;
}
}
public object this [byte[] buf, int index] {
get {
switch (type) {
case DatVariableType.Byte:
return buf[offset + index];
case DatVariableType.Word:
return Util.ReadWord (buf, offset + index * 2);
case DatVariableType.DWord:
return Util.ReadDWord (buf, offset + index * 4);
default:
return null;
}
}
}
public DatCollection CreateCollection (byte[] buf)
{
switch (type) {
case DatVariableType.Byte:
return new DatCollection<byte>(buf, this);
case DatVariableType.Word:
return new DatCollection<ushort>(buf, this);
case DatVariableType.DWord:
return new DatCollection<uint>(buf, this);
default:
return null;
}
}
}
}
| |
// 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 NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Osu.Objects;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Tests.Visual.Editing
{
[TestFixture]
public class TestSceneEditorSeekSnapping : EditorClockTestScene
{
public TestSceneEditorSeekSnapping()
{
BeatDivisor.Value = 4;
}
[BackgroundDependencyLoader]
private void load()
{
var testBeatmap = new Beatmap
{
ControlPointInfo = new ControlPointInfo(),
HitObjects =
{
new HitCircle { StartTime = 0 },
new HitCircle { StartTime = 5000 }
}
};
testBeatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = 200 });
testBeatmap.ControlPointInfo.Add(100, new TimingControlPoint { BeatLength = 400 });
testBeatmap.ControlPointInfo.Add(175, new TimingControlPoint { BeatLength = 800 });
testBeatmap.ControlPointInfo.Add(350, new TimingControlPoint { BeatLength = 200 });
testBeatmap.ControlPointInfo.Add(450, new TimingControlPoint { BeatLength = 100 });
testBeatmap.ControlPointInfo.Add(500, new TimingControlPoint { BeatLength = 307.69230769230802 });
Beatmap.Value = CreateWorkingBeatmap(testBeatmap);
Child = new TimingPointVisualiser(testBeatmap, 5000) { Clock = Clock };
}
/// <summary>
/// Tests whether time is correctly seeked without snapping.
/// </summary>
[Test]
public void TestSeekNoSnapping()
{
reset();
// Forwards
AddStep("Seek(0)", () => Clock.Seek(0));
AddAssert("Time = 0", () => Clock.CurrentTime == 0);
AddStep("Seek(33)", () => Clock.Seek(33));
AddAssert("Time = 33", () => Clock.CurrentTime == 33);
AddStep("Seek(89)", () => Clock.Seek(89));
AddAssert("Time = 89", () => Clock.CurrentTime == 89);
// Backwards
AddStep("Seek(25)", () => Clock.Seek(25));
AddAssert("Time = 25", () => Clock.CurrentTime == 25);
AddStep("Seek(0)", () => Clock.Seek(0));
AddAssert("Time = 0", () => Clock.CurrentTime == 0);
}
/// <summary>
/// Tests whether seeking to exact beat times puts us on the beat time.
/// These are the white/yellow ticks on the graph.
/// </summary>
[Test]
public void TestSeekSnappingOnBeat()
{
reset();
AddStep("Seek(0), Snap", () => Clock.SeekSnapped(0));
AddAssert("Time = 0", () => Clock.CurrentTime == 0);
AddStep("Seek(50), Snap", () => Clock.SeekSnapped(50));
AddAssert("Time = 50", () => Clock.CurrentTime == 50);
AddStep("Seek(100), Snap", () => Clock.SeekSnapped(100));
AddAssert("Time = 100", () => Clock.CurrentTime == 100);
AddStep("Seek(175), Snap", () => Clock.SeekSnapped(175));
AddAssert("Time = 175", () => Clock.CurrentTime == 175);
AddStep("Seek(350), Snap", () => Clock.SeekSnapped(350));
AddAssert("Time = 350", () => Clock.CurrentTime == 350);
AddStep("Seek(400), Snap", () => Clock.SeekSnapped(400));
AddAssert("Time = 400", () => Clock.CurrentTime == 400);
AddStep("Seek(450), Snap", () => Clock.SeekSnapped(450));
AddAssert("Time = 450", () => Clock.CurrentTime == 450);
}
/// <summary>
/// Tests whether seeking to somewhere in the middle between beats puts us on the expected beats.
/// For example, snapping between a white/yellow beat should put us on either the yellow or white, depending on which one we're closer too.
/// </summary>
[Test]
public void TestSeekSnappingInBetweenBeat()
{
reset();
AddStep("Seek(24), Snap", () => Clock.SeekSnapped(24));
AddAssert("Time = 0", () => Clock.CurrentTime == 0);
AddStep("Seek(26), Snap", () => Clock.SeekSnapped(26));
AddAssert("Time = 50", () => Clock.CurrentTime == 50);
AddStep("Seek(150), Snap", () => Clock.SeekSnapped(150));
AddAssert("Time = 100", () => Clock.CurrentTime == 100);
AddStep("Seek(170), Snap", () => Clock.SeekSnapped(170));
AddAssert("Time = 175", () => Clock.CurrentTime == 175);
AddStep("Seek(274), Snap", () => Clock.SeekSnapped(274));
AddAssert("Time = 175", () => Clock.CurrentTime == 175);
AddStep("Seek(276), Snap", () => Clock.SeekSnapped(276));
AddAssert("Time = 350", () => Clock.CurrentTime == 350);
}
/// <summary>
/// Tests that when seeking forward with no beat snapping, beats are never explicitly snapped to, nor the next timing point (if we've skipped it).
/// </summary>
[Test]
public void TestSeekForwardNoSnapping()
{
reset();
AddStep("SeekForward", () => Clock.SeekForward());
AddAssert("Time = 50", () => Clock.CurrentTime == 50);
AddStep("SeekForward", () => Clock.SeekForward());
AddAssert("Time = 100", () => Clock.CurrentTime == 100);
AddStep("SeekForward", () => Clock.SeekForward());
AddAssert("Time = 200", () => Clock.CurrentTime == 200);
AddStep("SeekForward", () => Clock.SeekForward());
AddAssert("Time = 400", () => Clock.CurrentTime == 400);
AddStep("SeekForward", () => Clock.SeekForward());
AddAssert("Time = 450", () => Clock.CurrentTime == 450);
}
/// <summary>
/// Tests that when seeking forward with beat snapping, all beats are snapped to and timing points are never skipped.
/// </summary>
[Test]
public void TestSeekForwardSnappingOnBeat()
{
reset();
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 50", () => Clock.CurrentTime == 50);
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 100", () => Clock.CurrentTime == 100);
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 175", () => Clock.CurrentTime == 175);
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 350", () => Clock.CurrentTime == 350);
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 400", () => Clock.CurrentTime == 400);
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 450", () => Clock.CurrentTime == 450);
}
/// <summary>
/// Tests that when seeking forward from in-between two beats, the next beat or timing point is snapped to, and no beats are skipped.
/// This will also test being extremely close to the next beat/timing point, to ensure rounding is not an issue.
/// </summary>
[Test]
public void TestSeekForwardSnappingFromInBetweenBeat()
{
reset();
AddStep("Seek(49)", () => Clock.Seek(49));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 50", () => Clock.CurrentTime == 50);
AddStep("Seek(49.999)", () => Clock.Seek(49.999));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 100", () => Clock.CurrentTime == 100);
AddStep("Seek(99)", () => Clock.Seek(99));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 100", () => Clock.CurrentTime == 100);
AddStep("Seek(99.999)", () => Clock.Seek(99.999));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 100", () => Clock.CurrentTime == 150);
AddStep("Seek(174)", () => Clock.Seek(174));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 175", () => Clock.CurrentTime == 175);
AddStep("Seek(349)", () => Clock.Seek(349));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 350", () => Clock.CurrentTime == 350);
AddStep("Seek(399)", () => Clock.Seek(399));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 400", () => Clock.CurrentTime == 400);
AddStep("Seek(449)", () => Clock.Seek(449));
AddStep("SeekForward, Snap", () => Clock.SeekForward(true));
AddAssert("Time = 450", () => Clock.CurrentTime == 450);
}
/// <summary>
/// Tests that when seeking backward with no beat snapping, beats are never explicitly snapped to, nor the next timing point (if we've skipped it).
/// </summary>
[Test]
public void TestSeekBackwardNoSnapping()
{
reset();
AddStep("Seek(450)", () => Clock.Seek(450));
AddStep("SeekBackward", () => Clock.SeekBackward());
AddAssert("Time = 400", () => Clock.CurrentTime == 400);
AddStep("SeekBackward", () => Clock.SeekBackward());
AddAssert("Time = 350", () => Clock.CurrentTime == 350);
AddStep("SeekBackward", () => Clock.SeekBackward());
AddAssert("Time = 150", () => Clock.CurrentTime == 150);
AddStep("SeekBackward", () => Clock.SeekBackward());
AddAssert("Time = 50", () => Clock.CurrentTime == 50);
AddStep("SeekBackward", () => Clock.SeekBackward());
AddAssert("Time = 0", () => Clock.CurrentTime == 0);
}
/// <summary>
/// Tests that when seeking backward with beat snapping, all beats are snapped to and timing points are never skipped.
/// </summary>
[Test]
public void TestSeekBackwardSnappingOnBeat()
{
reset();
AddStep("Seek(450)", () => Clock.Seek(450));
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 400", () => Clock.CurrentTime == 400);
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 350", () => Clock.CurrentTime == 350);
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 175", () => Clock.CurrentTime == 175);
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 100", () => Clock.CurrentTime == 100);
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 50", () => Clock.CurrentTime == 50);
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 0", () => Clock.CurrentTime == 0);
}
/// <summary>
/// Tests that when seeking backward from in-between two beats, the previous beat or timing point is snapped to, and no beats are skipped.
/// This will also test being extremely close to the previous beat/timing point, to ensure rounding is not an issue.
/// </summary>
[Test]
public void TestSeekBackwardSnappingFromInBetweenBeat()
{
reset();
AddStep("Seek(451)", () => Clock.Seek(451));
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 450", () => Clock.CurrentTime == 450);
AddStep("Seek(450.999)", () => Clock.Seek(450.999));
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 450", () => Clock.CurrentTime == 450);
AddStep("Seek(401)", () => Clock.Seek(401));
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 400", () => Clock.CurrentTime == 400);
AddStep("Seek(401.999)", () => Clock.Seek(401.999));
AddStep("SeekBackward, Snap", () => Clock.SeekBackward(true));
AddAssert("Time = 400", () => Clock.CurrentTime == 400);
}
/// <summary>
/// Tests that there are no rounding issues when snapping to beats within a timing point with a floating-point beatlength.
/// </summary>
[Test]
public void TestSeekingWithFloatingPointBeatLength()
{
reset();
double lastTime = 0;
AddStep("Seek(0)", () => Clock.Seek(0));
for (int i = 0; i < 9; i++)
{
AddStep("SeekForward, Snap", () =>
{
lastTime = Clock.CurrentTime;
Clock.SeekForward(true);
});
AddAssert("Time > lastTime", () => Clock.CurrentTime > lastTime);
}
for (int i = 0; i < 9; i++)
{
AddStep("SeekBackward, Snap", () =>
{
lastTime = Clock.CurrentTime;
Clock.SeekBackward(true);
});
AddAssert("Time < lastTime", () => Clock.CurrentTime < lastTime);
}
AddAssert("Time = 0", () => Clock.CurrentTime == 0);
}
private void reset()
{
AddStep("Reset", () => Clock.Seek(0));
}
private class TimingPointVisualiser : CompositeDrawable
{
private readonly double length;
private readonly Drawable tracker;
public TimingPointVisualiser(IBeatmap beatmap, double length)
{
this.length = length;
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Width = 0.75f;
FillFlowContainer timelineContainer;
InternalChildren = new Drawable[]
{
new Box
{
Name = "Background",
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black.Opacity(85f)
},
new Container
{
Name = "Tracks",
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Padding = new MarginPadding(15),
Children = new[]
{
tracker = new Box
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Y,
RelativePositionAxes = Axes.X,
Width = 2,
Colour = Color4.Red,
},
timelineContainer = new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Spacing = new Vector2(0, 5)
},
}
}
};
var timingPoints = beatmap.ControlPointInfo.TimingPoints;
for (int i = 0; i < timingPoints.Count; i++)
{
TimingControlPoint next = i == timingPoints.Count - 1 ? null : timingPoints[i + 1];
timelineContainer.Add(new TimingPointTimeline(timingPoints[i], next?.Time ?? length, length));
}
}
protected override void Update()
{
base.Update();
tracker.X = (float)(Time.Current / length);
}
private class TimingPointTimeline : CompositeDrawable
{
public TimingPointTimeline(TimingControlPoint timingPoint, double endTime, double fullDuration)
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Box createMainTick(double time) => new Box
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomCentre,
RelativePositionAxes = Axes.X,
X = (float)(time / fullDuration),
Height = 10,
Width = 2
};
Box createBeatTick(double time) => new Box
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomCentre,
RelativePositionAxes = Axes.X,
X = (float)(time / fullDuration),
Height = 5,
Width = 2,
Colour = time > endTime ? Color4.Gray : Color4.Yellow
};
AddInternal(createMainTick(timingPoint.Time));
AddInternal(createMainTick(endTime));
for (double t = timingPoint.Time + timingPoint.BeatLength / 4; t < fullDuration; t += timingPoint.BeatLength / 4)
AddInternal(createBeatTick(t));
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.Reflection.Tests
{
public class EventInfoTests
{
public static IEnumerable<object[]> Events_TestData()
{
yield return new object[] { typeof(BaseClass), nameof(BaseClass.PublicEvent) };
yield return new object[] { typeof(BaseClass), "PrivateEvent" };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.PublicStaticEvent) };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.PublicVirtualEvent) };
yield return new object[] { typeof(SubClass), nameof(BaseClass.PublicEvent) };
yield return new object[] { typeof(SubClass), nameof(SubClass.EventPublicNew) };
}
[Theory]
[MemberData(nameof(Events_TestData))]
public void IsMulticast_ReturnsTrue(Type type, string name)
{
EventInfo eventInfo = GetEventInfo(type, name);
Assert.True(eventInfo.IsMulticast);
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.PublicEvent), true)]
[InlineData(typeof(BaseClass), "PrivateEvent", false)]
public void GetAddMethod(Type type, string name, bool isVisible)
{
EventInfo eventInfo = GetEventInfo(type, name);
Assert.Equal(isVisible, eventInfo.GetAddMethod() != null);
Assert.Equal(isVisible, eventInfo.GetAddMethod(false) != null);
Assert.NotNull(eventInfo.GetAddMethod(true));
MethodInfo addMethod = eventInfo.AddMethod;
Assert.Equal(addMethod, eventInfo.GetAddMethod(true));
if (addMethod != null)
{
Assert.Equal("add_" + name, addMethod.Name);
Assert.Equal(1, addMethod.GetParameters().Length);
Assert.Equal(typeof(void), addMethod.ReturnParameter.ParameterType);
}
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.PublicEvent), true)]
[InlineData(typeof(BaseClass), "PrivateEvent", false)]
public void GetRemoveMethod(Type type, string name, bool isVisible)
{
EventInfo eventInfo = GetEventInfo(type, name);
Assert.Equal(isVisible, eventInfo.GetRemoveMethod() != null);
Assert.Equal(isVisible, eventInfo.GetRemoveMethod(false) != null);
Assert.NotNull(eventInfo.GetRemoveMethod(true));
MethodInfo removeMethod = eventInfo.RemoveMethod;
Assert.Equal(removeMethod, eventInfo.GetRemoveMethod(true));
if (removeMethod != null)
{
Assert.Equal("remove_" + name, removeMethod.Name);
Assert.Equal(1, removeMethod.GetParameters().Length);
Assert.Equal(typeof(void), removeMethod.ReturnParameter.ParameterType);
}
}
[Theory]
[MemberData(nameof(Events_TestData))]
public void GetRaiseMethod(Type type, string name)
{
EventInfo eventInfo = GetEventInfo(type, name);
Assert.Null(eventInfo.GetRaiseMethod(false));
Assert.Null(eventInfo.GetRaiseMethod(true));
Assert.Equal(eventInfo.GetRaiseMethod(true), eventInfo.RaiseMethod);
}
public static IEnumerable<object[]> AddRemove_TestData()
{
yield return new object[] { typeof(BaseClass), nameof(BaseClass.PublicEvent), new BaseClass() };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.PublicStaticEvent), null };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.PublicVirtualEvent), new BaseClass() };
yield return new object[] { typeof(SubClass), nameof(SubClass.EventPublicNew), new SubClass() };
yield return new object[] { typeof(SubClass), nameof(SubClass.PublicEvent), new SubClass() };
}
[Theory]
[MemberData(nameof(AddRemove_TestData))]
public void AddRemove(Type type, string name, object target)
{
EventInfo eventInfo = GetEventInfo(type, name);
EventHandler handler = new EventHandler(ObjectEventArgsHandler);
eventInfo.AddEventHandler(target, handler);
eventInfo.RemoveEventHandler(target, handler);
}
public static IEnumerable<object[]> AddEventHandler_Invalid_TestData()
{
// Target is null
yield return new object[] { typeof(BaseClass), nameof(BaseClass.PublicEvent), null, new EventHandler(ObjectEventArgsHandler), typeof(TargetException) };
// Handler is incorrect
yield return new object[] { typeof(BaseClass), nameof(BaseClass.PublicEvent), "hello", new EventHandler(ObjectEventArgsHandler), typeof(TargetException) };
yield return new object[] { typeof(BaseClass), nameof(BaseClass.PublicEvent), new BaseClass(), new ObjectDelegate(ObjectHandler), typeof(ArgumentException) };
}
[Theory]
[MemberData(nameof(AddEventHandler_Invalid_TestData))]
public void AddEventHandler_Invalid(Type type, string name, object target, Delegate handler, Type exceptionType)
{
EventInfo eventInfo = GetEventInfo(type, name);
Assert.Throws(exceptionType, () => eventInfo.AddEventHandler(target, handler));
}
public static IEnumerable<object[]> RemoveEventHandler_Invalid_TestData()
{
// Target is null
yield return new object[] { typeof(BaseClass), nameof(BaseClass.PublicEvent), new BaseClass(), new EventHandler(ObjectEventArgsHandler), null, new EventHandler(ObjectEventArgsHandler), typeof(TargetException) };
// Target is incorrect
yield return new object[] { typeof(BaseClass), nameof(BaseClass.PublicEvent), new BaseClass(), new EventHandler(ObjectEventArgsHandler), "hello", new EventHandler(ObjectEventArgsHandler), typeof(TargetException) };
// Handler is incorrect
yield return new object[] { typeof(BaseClass), nameof(BaseClass.PublicEvent), new BaseClass(), new EventHandler(ObjectEventArgsHandler), new BaseClass(), new ObjectDelegate(ObjectHandler), typeof(ArgumentException) };
}
[Theory]
[MemberData(nameof(RemoveEventHandler_Invalid_TestData))]
public void RemovEventHandler_Invalid(Type type, string name, object addTarget, Delegate addHandler, object removeTarget, Delegate removeHandler, Type exceptionType)
{
EventInfo eventInfo = GetEventInfo(type, name);
eventInfo.AddEventHandler(addTarget, addHandler);
Assert.Throws(exceptionType, () => eventInfo.RemoveEventHandler(removeTarget, removeHandler));
}
[Theory]
[InlineData(typeof(BaseClass), nameof(BaseClass.PublicEvent), typeof(BaseClass), nameof(BaseClass.PublicEvent), true)]
[InlineData(typeof(BaseClass), nameof(BaseClass.PublicEvent), typeof(SubClass), nameof(SubClass.PublicEvent), false)]
[InlineData(typeof(BaseClass), nameof(BaseClass.PublicEvent), typeof(BaseClass), nameof(BaseClass.PublicStaticEvent), false)]
public void Equals(Type type1, string name1, Type type2, string name2, bool expected)
{
EventInfo eventInfo1 = GetEventInfo(type1, name1);
EventInfo eventInfo2 = GetEventInfo(type2, name2);
Assert.Equal(expected, eventInfo1.Equals(eventInfo2));
if (expected)
{
Assert.Equal(eventInfo1.GetHashCode(), eventInfo2.GetHashCode());
}
}
[Theory]
[MemberData(nameof(Events_TestData))]
public void EventHandlerType(Type type, string name)
{
EventInfo eventInfo = GetEventInfo(type, name);
Assert.Equal(typeof(EventHandler), eventInfo.EventHandlerType);
}
[Theory]
[MemberData(nameof(Events_TestData))]
public void Attributes(Type type, string name)
{
EventInfo eventInfo = GetEventInfo(type, name);
Assert.Equal(EventAttributes.None, eventInfo.Attributes);
}
[Theory]
[MemberData(nameof(Events_TestData))]
public void IsSpecialName_NormalEvent_ReturnsFalse(Type type, string name)
{
EventInfo eventInfo = GetEventInfo(type, name);
Assert.False(eventInfo.IsSpecialName);
}
private static void ObjectEventArgsHandler(object o, EventArgs e) { }
private static void ObjectHandler(object o) { }
public delegate void ObjectDelegate(object o);
private static EventInfo GetEventInfo(Type declaringType, string eventName)
{
TypeInfo type = declaringType.GetTypeInfo();
return type.DeclaredEvents.First(declaredEvent => declaredEvent.Name == eventName);
}
#pragma warning disable 0067
protected class BaseClass
{
private event EventHandler PrivateEvent;
public event EventHandler PublicEvent;
public static event EventHandler PublicStaticEvent;
public virtual event EventHandler PublicVirtualEvent;
}
protected class SubClass : BaseClass
{
public new event EventHandler PublicEvent;
public event EventHandler EventPublicNew;
}
#pragma warning restore 0067
}
}
| |
using System.Collections.ObjectModel;
using System.Collections.Immutable;
namespace Signum.Engine.Linq;
internal class QueryRebinder : DbExpressionVisitor
{
ImmutableStack<Dictionary<ColumnExpression, ColumnExpression?>> scopes = ImmutableStack<Dictionary<ColumnExpression, ColumnExpression?>>.Empty;
public Dictionary<ColumnExpression, ColumnExpression?> CurrentScope { get { return scopes.Peek(); } }
private QueryRebinder() { }
internal class ColumnCollector : DbExpressionVisitor
{
internal Alias[] knownAliases = null!;
internal Dictionary<ColumnExpression, ColumnExpression?> currentScope = null!;
protected internal override Expression VisitColumn(ColumnExpression column)
{
if (knownAliases.Contains(column.Alias))
currentScope[column] = null;
return base.VisitColumn(column);
}
}
ColumnCollector cachedCollector = new ColumnCollector();
public ColumnCollector GetColumnCollector(Alias[] knownAliases)
{
cachedCollector.currentScope = CurrentScope;
cachedCollector.knownAliases = knownAliases;
return cachedCollector;
}
internal static Expression Rebind(Expression binded)
{
QueryRebinder qr = new QueryRebinder();
using (qr.NewScope())
{
return qr.Visit(binded);
}
}
protected internal override Expression VisitProjection(ProjectionExpression proj)
{
using (HeavyProfiler.LogNoStackTrace(nameof(VisitProjection), () => proj.Type.TypeName()))
{
GetColumnCollector(proj.Select.KnownAliases).Visit(proj.Projector);
SelectExpression source = (SelectExpression)this.Visit(proj.Select);
Expression projector = this.Visit(proj.Projector);
CurrentScope.RemoveAll(kvp =>
{
if (source.KnownAliases.Contains(kvp.Key.Alias))
{
if (kvp.Value == null)
throw new InvalidOperationException();
return true;
}
return false;
});
if (source != proj.Select || projector != proj.Projector)
{
return new ProjectionExpression(source, projector, proj.UniqueFunction, proj.Type);
}
return proj;
}
}
protected internal override Expression VisitTable(TableExpression table)
{
var columns = CurrentScope.Keys.Where(ce => ce.Alias == table.Alias).ToList();
CurrentScope.SetRange(columns, columns);
return table;
}
protected internal override Expression VisitSqlTableValuedFunction(SqlTableValuedFunctionExpression sqlFunction)
{
var columns = CurrentScope.Keys.Where(ce => ce.Alias == sqlFunction.Alias).ToList();
CurrentScope.SetRange(columns, columns);
ReadOnlyCollection<Expression> args = Visit(sqlFunction.Arguments);
if (args != sqlFunction.Arguments)
return new SqlTableValuedFunctionExpression(sqlFunction.SqlFunction, sqlFunction.ViewTable, sqlFunction.SingleColumnType, sqlFunction.Alias, args);
return sqlFunction;
}
protected internal override Expression VisitJoin(JoinExpression join)
{
if (join.Condition != null)
GetColumnCollector(join.KnownAliases).Visit(join.Condition);
else if (join.JoinType == JoinType.CrossApply || join.JoinType == JoinType.OuterApply)
GetColumnCollector(join.Left.KnownAliases).Visit(join.Right);
SourceExpression left = this.VisitSource(join.Left);
SourceExpression right = this.VisitSource(join.Right);
Expression? condition = this.Visit(join.Condition);
if (left != join.Left || right != join.Right || condition != join.Condition)
{
return new JoinExpression(join.JoinType, left, right, condition);
}
return join;
}
protected internal override Expression VisitSetOperator(SetOperatorExpression set)
{
List<ColumnExpression> askedColumns = CurrentScope.Keys.Where(k => k.Alias == set.Alias).ToList();
SourceWithAliasExpression left = VisitSetOperatorPart(set.Left, askedColumns);
SourceWithAliasExpression right = VisitSetOperatorPart(set.Right, askedColumns);
CurrentScope.SetRange(askedColumns, askedColumns);
if (left != set.Left || right != set.Right)
return new SetOperatorExpression(set.Operator, left, right, set.Alias);
return set;
}
private SourceWithAliasExpression VisitSetOperatorPart(SourceWithAliasExpression part, List<ColumnExpression> askedColumns)
{
using (NewScope())
{
CurrentScope.AddRange(askedColumns.ToDictionary(c => new ColumnExpression(c.Type, part.Alias, c.Name), c => (ColumnExpression?)null));
return (SourceWithAliasExpression)Visit(part);
}
}
protected internal override Expression VisitDelete(DeleteExpression delete)
{
GetColumnCollector(delete.Source.KnownAliases).Visit(delete.Where);
var source = Visit(delete.Source);
var where = Visit(delete.Where);
if (source != delete.Source || where != delete.Where)
return new DeleteExpression(delete.Table, delete.UseHistoryTable, (SourceWithAliasExpression)source, where, delete.ReturnRowCount);
return delete;
}
protected internal override Expression VisitUpdate(UpdateExpression update)
{
var coll = GetColumnCollector(update.Source.KnownAliases);
coll.Visit(update.Where);
foreach (var ca in update.Assigments)
coll.Visit(ca.Expression);
var source = Visit(update.Source);
var where = Visit(update.Where);
var assigments = Visit(update.Assigments, VisitColumnAssigment);
if (source != update.Source || where != update.Where || assigments != update.Assigments)
return new UpdateExpression(update.Table, update.UseHistoryTable, (SourceWithAliasExpression)source, where, assigments, update.ReturnRowCount);
return update;
}
protected internal override Expression VisitInsertSelect(InsertSelectExpression insertSelect)
{
var coll = GetColumnCollector(insertSelect.Source.KnownAliases);
foreach (var ca in insertSelect.Assigments)
coll.Visit(ca.Expression);
var source = Visit(insertSelect.Source);
var assigments = Visit(insertSelect.Assigments, VisitColumnAssigment);
if (source != insertSelect.Source || assigments != insertSelect.Assigments)
return new InsertSelectExpression(insertSelect.Table, insertSelect.UseHistoryTable, (SourceWithAliasExpression)source, assigments, insertSelect.ReturnRowCount);
return insertSelect;
}
protected internal override Expression VisitSelect(SelectExpression select)
{
Dictionary<ColumnExpression, ColumnExpression?> askedColumns = CurrentScope.Keys.Where(k => select.KnownAliases.Contains(k.Alias)).ToDictionary(k => k, k => (ColumnExpression?)null);
Dictionary<ColumnExpression, ColumnExpression?> externalAnswers = CurrentScope.Where(kvp => !select.KnownAliases.Contains(kvp.Key.Alias) && kvp.Value != null).ToDictionary();
var disposable = NewScope();//SCOPE START
var scope = CurrentScope;
scope.AddRange(askedColumns.Where(kvp => kvp.Key.Alias != select.Alias).ToDictionary());
scope.AddRange(externalAnswers);
var col = GetColumnCollector(select.KnownAliases);
col.Visit(select.Top);
col.Visit(select.Where);
foreach (var cd in select.Columns)
col.Visit(cd.Expression);
foreach (var oe in select.OrderBy)
col.Visit(oe.Expression);
foreach (var e in select.GroupBy)
col.Visit(e);
SourceExpression from = this.VisitSource(select.From!);
Expression? top = this.Visit(select.Top);
Expression? where = this.Visit(select.Where);
ReadOnlyCollection<OrderExpression> orderBy = Visit(select.OrderBy, VisitOrderBy);
if (orderBy.HasItems())
orderBy = RemoveDuplicates(orderBy);
ReadOnlyCollection<Expression> groupBy = Visit(select.GroupBy, Visit);
ReadOnlyCollection<ColumnDeclaration> columns = Visit(select.Columns, VisitColumnDeclaration); ;
columns = AnswerAndExpand(columns, select.Alias, askedColumns);
var externals = CurrentScope.Where(kvp => !select.KnownAliases.Contains(kvp.Key.Alias) && kvp.Value == null).ToDictionary();
disposable.Dispose(); ////SCOPE END
CurrentScope.SetRange(externals);
CurrentScope.SetRange(askedColumns);
if (top != select.Top || from != select.From || where != select.Where || columns != select.Columns || orderBy != select.OrderBy || groupBy != select.GroupBy)
return new SelectExpression(select.Alias, select.IsDistinct, top, columns, from, where, orderBy, groupBy, select.SelectOptions);
return select;
}
protected internal override Expression VisitRowNumber(RowNumberExpression rowNumber)
{
var orderBys = RemoveDuplicates(Visit(rowNumber.OrderBy, VisitOrderBy));
if (orderBys != rowNumber.OrderBy)
return new RowNumberExpression(orderBys);
return rowNumber;
}
private static ReadOnlyCollection<OrderExpression> RemoveDuplicates(ReadOnlyCollection<OrderExpression> orderBy)
{
List<OrderExpression> result = new List<OrderExpression>();
HashSet<Expression> used = new HashSet<Expression>();
foreach (var ord in orderBy)
{
if (used.Add(ord.Expression))
result.Add(ord);
}
return result.AsReadOnly();
}
private ReadOnlyCollection<ColumnDeclaration> AnswerAndExpand(ReadOnlyCollection<ColumnDeclaration> columns, Alias currentAlias, Dictionary<ColumnExpression, ColumnExpression?> askedColumns)
{
ColumnGenerator cg = new ColumnGenerator(columns);
foreach (var col in askedColumns.Keys.ToArray())
{
if (col.Alias == currentAlias)
{
//Expression expr = columns.SingleEx(cd => (cd.Name ?? "-") == col.Name).Expression;
//askedColumns[col] = expr is SqlConstantExpression ? expr : col;
askedColumns[col] = col;
}
else
{
ColumnExpression? colExp = CurrentScope[col];
//if (expr is ColumnExpression colExp)
//{
ColumnDeclaration? cd = cg.Columns.FirstOrDefault(c => c!.Expression.Equals(colExp));
if (cd == null)
cd = cg.MapColumn(colExp!);
askedColumns[col] = new ColumnExpression(col.Type, currentAlias, cd.Name);
//}
//else
//{
// askedColumns[col] = expr;
//}
}
}
if (columns.Count != cg.Columns.Count())
return cg.Columns.NotNull().ToReadOnly();
return columns;
}
public IDisposable NewScope()
{
scopes = scopes.Push(new Dictionary<ColumnExpression, ColumnExpression?>());
return new Disposable(() => scopes = scopes.Pop());
}
protected internal override Expression VisitColumn(ColumnExpression column)
{
if (CurrentScope.TryGetValue(column, out ColumnExpression? result))
return result ?? column;
else
{
CurrentScope[column] = null;
return column;
}
}
protected internal override Expression VisitScalar(ScalarExpression scalar)
{
var column = scalar.Select!.Columns.SingleEx();
VisitColumn(new ColumnExpression(scalar.Type, scalar.Select.Alias, column.Name ?? "-"));
var select = (SelectExpression)this.Visit(scalar.Select);
if (select != scalar.Select)
return new ScalarExpression(scalar.Type, select);
return scalar;
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
// <auto-generated />
namespace NorthwindRepository
{
/// <summary>
/// Strongly-typed collection for the ProductCategoryMap class.
/// </summary>
[Serializable]
public partial class ProductCategoryMapCollection : RepositoryList<ProductCategoryMap, ProductCategoryMapCollection>
{
public ProductCategoryMapCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>ProductCategoryMapCollection</returns>
public ProductCategoryMapCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
ProductCategoryMap o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the Product_Category_Map table.
/// </summary>
[Serializable]
public partial class ProductCategoryMap : RepositoryRecord<ProductCategoryMap>, IRecordBase
{
#region .ctors and Default Settings
public ProductCategoryMap()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public ProductCategoryMap(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("Product_Category_Map", TableType.Table, DataService.GetInstance("NorthwindRepository"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarCategoryID = new TableSchema.TableColumn(schema);
colvarCategoryID.ColumnName = "CategoryID";
colvarCategoryID.DataType = DbType.Int32;
colvarCategoryID.MaxLength = 0;
colvarCategoryID.AutoIncrement = false;
colvarCategoryID.IsNullable = false;
colvarCategoryID.IsPrimaryKey = true;
colvarCategoryID.IsForeignKey = true;
colvarCategoryID.IsReadOnly = false;
colvarCategoryID.DefaultSetting = @"";
colvarCategoryID.ForeignKeyTableName = "Categories";
schema.Columns.Add(colvarCategoryID);
TableSchema.TableColumn colvarProductID = new TableSchema.TableColumn(schema);
colvarProductID.ColumnName = "ProductID";
colvarProductID.DataType = DbType.Int32;
colvarProductID.MaxLength = 0;
colvarProductID.AutoIncrement = false;
colvarProductID.IsNullable = false;
colvarProductID.IsPrimaryKey = true;
colvarProductID.IsForeignKey = true;
colvarProductID.IsReadOnly = false;
colvarProductID.DefaultSetting = @"";
colvarProductID.ForeignKeyTableName = "Products";
schema.Columns.Add(colvarProductID);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["NorthwindRepository"].AddSchema("Product_Category_Map",schema);
}
}
#endregion
#region Props
[XmlAttribute("CategoryID")]
[Bindable(true)]
public int CategoryID
{
get { return GetColumnValue<int>(Columns.CategoryID); }
set { SetColumnValue(Columns.CategoryID, value); }
}
[XmlAttribute("ProductID")]
[Bindable(true)]
public int ProductID
{
get { return GetColumnValue<int>(Columns.ProductID); }
set { SetColumnValue(Columns.ProductID, value); }
}
#endregion
//no foreign key tables defined (2)
//no ManyToMany tables defined (0)
#region Typed Columns
public static TableSchema.TableColumn CategoryIDColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn ProductIDColumn
{
get { return Schema.Columns[1]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string CategoryID = @"CategoryID";
public static string ProductID = @"ProductID";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using Gallio.Common.Collections;
using Gallio.Common.Reflection;
namespace Gallio.Runtime.Extensibility
{
internal sealed class ComponentDescriptor : IComponentDescriptor
{
private readonly Registry registry;
private readonly PluginDescriptor pluginDescriptor;
private readonly ServiceDescriptor serviceDescriptor;
private readonly string componentId;
private readonly TypeName componentTypeName;
private readonly PropertySet componentProperties;
private readonly PropertySet traitsProperties;
private readonly IHandlerFactory componentHandlerFactory;
private Type componentType;
private IHandler componentHandler;
private IHandler traitsHandler;
public ComponentDescriptor(Registry registry, ComponentRegistration componentRegistration)
{
this.registry = registry;
pluginDescriptor = (PluginDescriptor) componentRegistration.Plugin;
serviceDescriptor = (ServiceDescriptor) componentRegistration.Service;
componentId = componentRegistration.ComponentId;
componentTypeName = componentRegistration.ComponentTypeName ?? serviceDescriptor.DefaultComponentTypeName;
componentProperties = componentRegistration.ComponentProperties.Copy().AsReadOnly();
traitsProperties = componentRegistration.TraitsProperties.Copy().AsReadOnly();
componentHandlerFactory = componentRegistration.ComponentHandlerFactory;
}
public IPluginDescriptor Plugin
{
get { return pluginDescriptor; }
}
public IServiceDescriptor Service
{
get { return serviceDescriptor; }
}
public string ComponentId
{
get { return componentId; }
}
public TypeName ComponentTypeName
{
get { return componentTypeName; }
}
public IHandlerFactory ComponentHandlerFactory
{
get { return componentHandlerFactory; }
}
public PropertySet ComponentProperties
{
get { return componentProperties; }
}
public PropertySet TraitsProperties
{
get { return traitsProperties; }
}
public bool IsDisabled
{
get { return pluginDescriptor.IsDisabled || serviceDescriptor.IsDisabled; }
}
public string DisabledReason
{
get
{
if (pluginDescriptor.IsDisabled)
return string.Format("The plugin that provides this component was disabled. Reason: {0}", pluginDescriptor.DisabledReason);
if (serviceDescriptor.IsDisabled)
return string.Format("The service implemented by this component was disabled. Reason: {0}", serviceDescriptor.DisabledReason);
throw new InvalidOperationException("The component has not been disabled.");
}
}
public Type ResolveComponentType()
{
if (componentType == null)
{
try
{
componentType = componentTypeName.Resolve();
}
catch (Exception ex)
{
throw new RuntimeException(string.Format("Could not resolve the component type of component '{0}'.", componentId), ex);
}
}
return componentType;
}
public IHandler ResolveComponentHandler()
{
if (componentHandler == null)
{
try
{
Type contractType = serviceDescriptor.ResolveServiceType();
Type objectType = ResolveComponentType();
registry.DataBox.Write(data =>
{
if (componentHandler == null)
componentHandler = componentHandlerFactory.CreateHandler(
new ComponentDependencyResolver(this),
contractType, objectType, componentProperties);
});
}
catch (Exception ex)
{
throw new RuntimeException(string.Format("Could not resolve the component handler of component '{0}'.", componentId), ex);
}
}
return componentHandler;
}
public object ResolveComponent()
{
try
{
return ResolveComponentHandler().Activate();
}
catch (Exception ex)
{
throw new RuntimeException(string.Format("Could not resolve instance of component '{0}'.", componentId), ex);
}
}
public IHandler ResolveTraitsHandler()
{
if (traitsHandler == null)
{
try
{
Type contractType = typeof(Traits);
Type objectType = serviceDescriptor.ResolveTraitsType();
registry.DataBox.Write(data =>
{
if (traitsHandler == null)
traitsHandler = serviceDescriptor.TraitsHandlerFactory.CreateHandler(
new DefaultObjectDependencyResolver(registry.ServiceLocator, registry.ResourceLocator),
contractType, objectType, traitsProperties);
});
}
catch (Exception ex)
{
throw new RuntimeException(string.Format("Could not resolve the traits handler of component '{0}'.", componentId), ex);
}
}
return traitsHandler;
}
public Traits ResolveTraits()
{
try
{
return (Traits) ResolveTraitsHandler().Activate();
}
catch (Exception ex)
{
throw new RuntimeException(string.Format("Could not resolve traits of component '{0}'.", componentId), ex);
}
}
private sealed class ComponentDependencyResolver : DefaultObjectDependencyResolver
{
private readonly ComponentDescriptor descriptor;
public ComponentDependencyResolver(ComponentDescriptor descriptor)
: base(descriptor.registry.ServiceLocator, descriptor.registry.ResourceLocator)
{
this.descriptor = descriptor;
}
public override DependencyResolution ResolveDependency(string parameterName, Type parameterType, string configurationArgument)
{
if (configurationArgument == null)
{
if (typeof (Traits).IsAssignableFrom(parameterType) // check we want traits (fast, do this first)
&& parameterType.IsAssignableFrom(descriptor.serviceDescriptor.ResolveTraitsType())) // confirm we can handle the traits (slow)
return DependencyResolution.Satisfied(descriptor.ResolveTraits());
if (parameterType == typeof (IComponentDescriptor))
return DependencyResolution.Satisfied(descriptor);
}
return base.ResolveDependency(parameterName, parameterType, configurationArgument);
}
}
}
}
| |
// 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 BlendUInt322()
{
var test = new ImmBinaryOpTest__BlendUInt322();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.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 (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ImmBinaryOpTest__BlendUInt322
{
private struct TestStruct
{
public Vector256<UInt32> _fld1;
public Vector256<UInt32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(ImmBinaryOpTest__BlendUInt322 testClass)
{
var result = Avx2.Blend(_fld1, _fld2, 2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static UInt32[] _data1 = new UInt32[Op1ElementCount];
private static UInt32[] _data2 = new UInt32[Op2ElementCount];
private static Vector256<UInt32> _clsVar1;
private static Vector256<UInt32> _clsVar2;
private Vector256<UInt32> _fld1;
private Vector256<UInt32> _fld2;
private SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32> _dataTable;
static ImmBinaryOpTest__BlendUInt322()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
}
public ImmBinaryOpTest__BlendUInt322()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32>(_data1, _data2, new UInt32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.Blend(
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr),
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.Blend(
Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)),
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.Blend(
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)),
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr),
(byte)2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr)),
(byte)2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.Blend), new Type[] { typeof(Vector256<UInt32>), typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr)),
(byte)2
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.Blend(
_clsVar1,
_clsVar2,
2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray2Ptr);
var result = Avx2.Blend(left, right, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((UInt32*)(_dataTable.inArray2Ptr));
var result = Avx2.Blend(left, right, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray2Ptr));
var result = Avx2.Blend(left, right, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ImmBinaryOpTest__BlendUInt322();
var result = Avx2.Blend(test._fld1, test._fld2, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.Blend(_fld1, _fld2, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.Blend(test._fld1, test._fld2, 2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<UInt32> left, Vector256<UInt32> right, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray1 = new UInt32[Op1ElementCount];
UInt32[] inArray2 = new UInt32[Op2ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (((2 & (1 << 0)) == 0) ? left[0] : right[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (((2 & (1 << i)) == 0) ? left[i] : right[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Blend)}<UInt32>(Vector256<UInt32>.2, Vector256<UInt32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Ploeh.Albedo;
using Ploeh.Albedo.Refraction;
using Ploeh.AutoFixture.Kernel;
namespace Ploeh.AutoFixture.Idioms
{
/// <summary>
/// Encapsulates a unit test that verifies that a member (property or field) is correctly intialized
/// by the constructor.
/// </summary>
public class ConstructorInitializedMemberAssertion : IdiomaticAssertion
{
private readonly ISpecimenBuilder builder;
private readonly IEqualityComparer comparer;
private readonly IEqualityComparer<IReflectionElement> parameterMemberMatcher;
/// <summary>
/// Initializes a new instance of the <see cref="ConstructorInitializedMemberAssertion"/> class.
/// </summary>
/// <param name="builder">
/// A composer which can create instances required to implement the idiomatic unit test,
/// such as the owner of the property, as well as the value to be assigned and read from
/// the member.
/// </param>
/// <param name="comparer"> An <see cref="IEqualityComparer"/> instance, which is used
/// to determine if each member has the same value which was passed to the matching
/// constructor parameter.
/// </param>
/// <param name="parameterMemberMatcher">Provides a way to customize the way parameters
/// are matched to members. The boolean value returned from
/// <see cref="IEqualityComparer{T}.Equals(T,T)"/> indicates if the parameter and member
/// are matched.
/// </param>
/// <remarks>
/// <para>
/// <paramref name="builder" /> will typically be a <see cref="Fixture" /> instance.
/// </para>
/// </remarks>
public ConstructorInitializedMemberAssertion(
ISpecimenBuilder builder,
IEqualityComparer comparer,
IEqualityComparer<IReflectionElement> parameterMemberMatcher)
{
if (builder == null)
{
throw new ArgumentNullException("builder");
}
if (comparer == null)
{
throw new ArgumentNullException("comparer");
}
if (parameterMemberMatcher == null)
{
throw new ArgumentNullException("parameterMemberMatcher");
}
this.builder = builder;
this.comparer = comparer;
this.parameterMemberMatcher = parameterMemberMatcher;
}
/// <summary>
/// Initializes a new instance of the <see cref="ConstructorInitializedMemberAssertion"/> class.
/// </summary>
/// <param name="builder">
/// A composer which can create instances required to implement the idiomatic unit test,
/// such as the owner of the property, as well as the value to be assigned and read from
/// the member.
/// </param>
/// <remarks>
/// <para>
/// <paramref name="builder" /> will typically be a <see cref="Fixture" /> instance.
/// </para>
/// </remarks>
public ConstructorInitializedMemberAssertion(ISpecimenBuilder builder)
: this(
builder,
EqualityComparer<object>.Default,
new DefaultParameterMemberMatcher())
{
}
/// <summary>
/// Gets the builder supplied by the constructor.
/// </summary>
public ISpecimenBuilder Builder
{
get { return this.builder; }
}
/// <summary>
/// Gets the comparer supplied to the constructor.
/// </summary>
/// <remarks>
/// This comparer instance is used to determine if all of the value retreived from
/// the members are equal to their corresponding 'matched' constructor parameter.
/// </remarks>
public IEqualityComparer Comparer
{
get { return comparer; }
}
/// <summary>
/// Gets the <see cref="IEqualityComparer{IReflectionElement}"/> instance which is
/// used to determine if a constructor parameter matches a given member (property
/// or field).
/// </summary>
/// <remarks>
/// If the parameter and member are matched, the member is expected to be initialized
/// from the value passed into the matching constructor parameter.
/// </remarks>
public IEqualityComparer<IReflectionElement> ParameterMemberMatcher
{
get { return parameterMemberMatcher; }
}
/// <summary>
/// Verifies that all constructor arguments are properly exposed as either fields
/// or properties.
/// </summary>
/// <param name="constructorInfo">The constructor.</param>
public override void Verify(ConstructorInfo constructorInfo)
{
if (constructorInfo == null)
throw new ArgumentNullException("constructorInfo");
var parameters = constructorInfo.GetParameters();
if (parameters.Length == 0)
return;
var publicPropertiesAndFields = GetPublicPropertiesAndFields(constructorInfo.DeclaringType).ToArray();
// Handle backwards-compatibility by replacing the default
// matcher with one that behaves the similar to the previous
// behaviour
IEqualityComparer<IReflectionElement> matcher =
this.parameterMemberMatcher is DefaultParameterMemberMatcher
? new DefaultParameterMemberMatcher(
new DefaultParameterMemberMatcher.NameIgnoreCaseAndTypeAssignableComparer())
: this.parameterMemberMatcher;
var firstParameterNotExposed = parameters.FirstOrDefault(
p => !publicPropertiesAndFields.Any(m =>
matcher.Equals(p.ToReflectionElement(), m.ToReflectionElement())));
if (firstParameterNotExposed != null)
{
throw new ConstructorInitializedMemberException(constructorInfo, firstParameterNotExposed);
}
}
/// <summary>
/// Verifies that a property is correctly initialized by the constructor.
/// </summary>
/// <param name="propertyInfo">The property.</param>
/// <remarks>
/// <para>
/// This method verifies that the <paramref name="propertyInfo" /> is correctly initialized with
/// the value given to the same-named constructor paramter. It uses the <see cref="Builder" /> to
/// supply values to the constructor(s) of the Type on which the field is implemented, and then
/// reads from the field. The assertion passes if the value read from the property is the same as
/// the value passed to the constructor. If more than one constructor has an argument with the
/// same name and type, all constructors are checked. If any constructor (with a matching argument)
/// does not initialise the property with the correct value, a
/// <see cref="ConstructorInitializedMemberException" /> is thrown.
/// </para>
/// </remarks>
/// <exception cref="WritablePropertyException">The verification fails.</exception>
public override void Verify(PropertyInfo propertyInfo)
{
if (propertyInfo == null)
throw new ArgumentNullException("propertyInfo");
var matchingConstructors = GetConstructorsWithInitializerForMember(propertyInfo).ToArray();
if (!matchingConstructors.Any())
{
if (IsMemberThatRequiresConstructorInitialization(propertyInfo))
{
throw new ConstructorInitializedMemberException(propertyInfo, string.Format(CultureInfo.CurrentCulture,
"No constructors with an argument that matches the read-only property '{0}' were found", propertyInfo.Name));
}
// For writable properties or fields, having no constructor parameter that initializes
// the member is perfectly fine.
return;
}
var expectedAndActuals = matchingConstructors
.Select(ctor => BuildSpecimenFromConstructor(ctor, propertyInfo));
// Compare the value passed into the constructor with the value returned from the property
if (expectedAndActuals.Any(s => !this.comparer.Equals(s.Expected, s.Actual)))
{
throw new ConstructorInitializedMemberException(propertyInfo);
}
}
/// <summary>
/// Verifies that a field is correctly initialized by the constructor.
/// </summary>
/// <param name="fieldInfo">The field.</param>
/// <remarks>
/// <para>
/// This method verifies that <paramref name="fieldInfo" /> is correctly initialized with the
/// value given to the same-named constructor paramter. It uses the <see cref="Builder" /> to
/// supply values to the constructor(s) of the Type on which the field is implemented, and then
/// reads from the field. The assertion passes if the value read from the field is the same as
/// the value passed to the constructor. If more than one constructor has an argument with the
/// same name and type, all constructors are checked. If any constructor does not initialise
/// the field with the correct value, a <see cref="ConstructorInitializedMemberException" />
/// is thrown.
/// </para>
/// </remarks>
/// <exception cref="ConstructorInitializedMemberException">The verification fails.</exception>
public override void Verify(FieldInfo fieldInfo)
{
if (fieldInfo == null)
throw new ArgumentNullException("fieldInfo");
var matchingConstructors = GetConstructorsWithInitializerForMember(fieldInfo).ToArray();
if (!matchingConstructors.Any())
{
if (IsMemberThatRequiresConstructorInitialization(fieldInfo))
{
throw new ConstructorInitializedMemberException(fieldInfo, string.Format(CultureInfo.CurrentCulture,
"No constructors with an argument that matches the read-only field '{0}' were found", fieldInfo.Name));
}
// For writable properties or fields, having no constructor parameter that initializes
// the member is perfectly fine.
return;
}
var expectedAndActuals = matchingConstructors
.Select(ctor => BuildSpecimenFromConstructor(ctor, fieldInfo));
// Compare the value passed into the constructor with the value returned from the property
if (expectedAndActuals.Any(s => !this.comparer.Equals(s.Expected, s.Actual)))
{
throw new ConstructorInitializedMemberException(fieldInfo);
}
}
private ExpectedAndActual BuildSpecimenFromConstructor(
ConstructorInfo ci, MemberInfo propertyOrField)
{
var parametersAndValues = ci.GetParameters()
.Select(pi => new {Parameter = pi, Value = this.builder.CreateAnonymous(pi)})
.ToArray();
// Get the value expected to be assigned to the matching member
var expectedValueForMember = parametersAndValues
.Single(p => IsMatchingParameterAndMember(p.Parameter, propertyOrField))
.Value;
// Construct an instance of the specimen class
var specimen = ci.Invoke(parametersAndValues.Select(pv => pv.Value).ToArray());
// Get the value from the specimen field/property
object actual;
if (propertyOrField is FieldInfo)
{
actual = (propertyOrField as FieldInfo).GetValue(specimen);
}
else if (propertyOrField is PropertyInfo)
{
var propertyInfo = propertyOrField as PropertyInfo;
actual = propertyInfo.CanRead
? propertyInfo.GetValue(specimen, null)
: expectedValueForMember;
}
else
{
throw new ArgumentException("Must be a property or field", "propertyOrField");
}
return new ExpectedAndActual(expectedValueForMember, actual);
}
private class ExpectedAndActual
{
public ExpectedAndActual(object expected, object actual)
{
this.Expected = expected;
this.Actual = actual;
}
public object Expected { get; private set; }
public object Actual { get; private set; }
}
private IEnumerable<ConstructorInfo> GetConstructorsWithInitializerForMember(MemberInfo member)
{
return member.ReflectedType
.GetConstructors()
.Where(ci => IsConstructorWithMatchingArgument(ci, member));
}
private bool IsMatchingParameterAndMember(ParameterInfo parameter, MemberInfo fieldOrProperty)
{
return this.parameterMemberMatcher.Equals(
fieldOrProperty.ToReflectionElement(), parameter.ToReflectionElement());
}
private bool IsConstructorWithMatchingArgument(ConstructorInfo ci, MemberInfo memberInfo)
{
return ci.GetParameters().Any(parameterElement =>
IsMatchingParameterAndMember(parameterElement, memberInfo));
}
private static IEnumerable<MemberInfo> GetPublicPropertiesAndFields(Type t)
{
return t.GetMembers(BindingFlags.Instance | BindingFlags.Public)
.Where(m => m.MemberType.HasFlag(MemberTypes.Field) || m.MemberType.HasFlag(MemberTypes.Property));
}
private static bool IsMemberThatRequiresConstructorInitialization(MemberInfo member)
{
var memberAsPropertyInfo = member as PropertyInfo;
if (memberAsPropertyInfo != null)
{
MethodInfo setterMethod = memberAsPropertyInfo.GetSetMethod();
bool isReadOnly = memberAsPropertyInfo.CanRead &&
(setterMethod == null || setterMethod.IsPrivate || setterMethod.IsFamilyOrAssembly || setterMethod.IsFamilyAndAssembly);
return isReadOnly;
}
var memberAsFieldInfo = member as FieldInfo;
if (memberAsFieldInfo != null)
{
bool isReadOnly = memberAsFieldInfo.Attributes.HasFlag(FieldAttributes.InitOnly);
return isReadOnly;
}
return false;
}
private class DefaultParameterMemberMatcher : ReflectionVisitorElementComparer<NameAndType>
{
public class NameIgnoreCaseAndTypeAssignableComparer : IEqualityComparer<NameAndType>
{
public bool Equals(NameAndType x, NameAndType y)
{
if (x == null) throw new ArgumentNullException("x");
if (y == null) throw new ArgumentNullException("y");
return x.Name.Equals(y.Name, StringComparison.CurrentCultureIgnoreCase)
&& (x.Type.IsAssignableFrom(y.Type) || y.Type.IsAssignableFrom(x.Type));
}
public int GetHashCode(NameAndType obj)
{
// Forces methods like Distinct() to use the Equals method, because
// the hashcodes will all be equal.
return 0;
}
}
public DefaultParameterMemberMatcher(
IEqualityComparer<NameAndType> comparer)
: base(new NameAndTypeCollectingVisitor(), comparer)
{
}
public DefaultParameterMemberMatcher()
: this(null)
{
}
}
}
}
| |
using System;
using System.IO;
using Raksha.Crypto.Generators;
using Raksha.Crypto.IO;
using Raksha.Asn1;
using Raksha.Asn1.Cms;
using Raksha.Asn1.X509;
using Raksha.Crypto;
using Raksha.Crypto.Parameters;
using Raksha.Security;
using Raksha.Utilities.IO;
namespace Raksha.Cms
{
/**
* General class for generating a CMS authenticated-data message stream.
* <p>
* A simple example of usage.
* <pre>
* CMSAuthenticatedDataStreamGenerator edGen = new CMSAuthenticatedDataStreamGenerator();
*
* edGen.addKeyTransRecipient(cert);
*
* ByteArrayOutputStream bOut = new ByteArrayOutputStream();
*
* OutputStream out = edGen.open(
* bOut, CMSAuthenticatedDataGenerator.AES128_CBC, "BC");*
* out.write(data);
*
* out.close();
* </pre>
* </p>
*/
public class CmsAuthenticatedDataStreamGenerator
: CmsAuthenticatedGenerator
{
// TODO Add support
// private object _originatorInfo = null;
// private object _unprotectedAttributes = null;
private int _bufferSize;
private bool _berEncodeRecipientSet;
/**
* base constructor
*/
public CmsAuthenticatedDataStreamGenerator()
{
}
/**
* constructor allowing specific source of randomness
* @param rand instance of SecureRandom to use
*/
public CmsAuthenticatedDataStreamGenerator(
SecureRandom rand)
: base(rand)
{
}
/**
* Set the underlying string size for encapsulated data
*
* @param bufferSize length of octet strings to buffer the data.
*/
public void SetBufferSize(
int bufferSize)
{
_bufferSize = bufferSize;
}
/**
* Use a BER Set to store the recipient information
*/
public void SetBerEncodeRecipients(
bool berEncodeRecipientSet)
{
_berEncodeRecipientSet = berEncodeRecipientSet;
}
/**
* generate an enveloped object that contains an CMS Enveloped Data
* object using the given provider and the passed in key generator.
* @throws java.io.IOException
*/
private Stream Open(
Stream outStr,
string macOid,
CipherKeyGenerator keyGen)
{
// FIXME Will this work for macs?
byte[] encKeyBytes = keyGen.GenerateKey();
KeyParameter encKey = ParameterUtilities.CreateKeyParameter(macOid, encKeyBytes);
Asn1Encodable asn1Params = GenerateAsn1Parameters(macOid, encKeyBytes);
ICipherParameters cipherParameters;
AlgorithmIdentifier macAlgId = GetAlgorithmIdentifier(
macOid, encKey, asn1Params, out cipherParameters);
Asn1EncodableVector recipientInfos = new Asn1EncodableVector();
foreach (RecipientInfoGenerator rig in recipientInfoGenerators)
{
try
{
recipientInfos.Add(rig.Generate(encKey, rand));
}
catch (InvalidKeyException e)
{
throw new CmsException("key inappropriate for algorithm.", e);
}
catch (GeneralSecurityException e)
{
throw new CmsException("error making encrypted content.", e);
}
}
// FIXME Only passing key at the moment
// return Open(outStr, macAlgId, cipherParameters, recipientInfos);
return Open(outStr, macAlgId, encKey, recipientInfos);
}
protected Stream Open(
Stream outStr,
AlgorithmIdentifier macAlgId,
ICipherParameters cipherParameters,
Asn1EncodableVector recipientInfos)
{
try
{
//
// ContentInfo
//
BerSequenceGenerator cGen = new BerSequenceGenerator(outStr);
cGen.AddObject(CmsObjectIdentifiers.AuthenticatedData);
//
// Authenticated Data
//
BerSequenceGenerator authGen = new BerSequenceGenerator(
cGen.GetRawOutputStream(), 0, true);
authGen.AddObject(new DerInteger(AuthenticatedData.CalculateVersion(null)));
Stream authRaw = authGen.GetRawOutputStream();
Asn1Generator recipGen = _berEncodeRecipientSet
? (Asn1Generator) new BerSetGenerator(authRaw)
: new DerSetGenerator(authRaw);
foreach (Asn1Encodable ae in recipientInfos)
{
recipGen.AddObject(ae);
}
recipGen.Close();
authGen.AddObject(macAlgId);
BerSequenceGenerator eiGen = new BerSequenceGenerator(authRaw);
eiGen.AddObject(CmsObjectIdentifiers.Data);
Stream octetOutputStream = CmsUtilities.CreateBerOctetOutputStream(
eiGen.GetRawOutputStream(), 0, false, _bufferSize);
IMac mac = MacUtilities.GetMac(macAlgId.ObjectID);
// TODO Confirm no ParametersWithRandom needed
mac.Init(cipherParameters);
Stream mOut = new TeeOutputStream(octetOutputStream, new MacOutputStream(mac));
return new CmsAuthenticatedDataOutputStream(mOut, mac, cGen, authGen, eiGen);
}
catch (SecurityUtilityException e)
{
throw new CmsException("couldn't create cipher.", e);
}
catch (InvalidKeyException e)
{
throw new CmsException("key invalid in message.", e);
}
catch (IOException e)
{
throw new CmsException("exception decoding algorithm parameters.", e);
}
}
/**
* generate an enveloped object that contains an CMS Enveloped Data object
*/
public Stream Open(
Stream outStr,
string encryptionOid)
{
CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid);
keyGen.Init(new KeyGenerationParameters(rand, keyGen.DefaultStrength));
return Open(outStr, encryptionOid, keyGen);
}
/**
* generate an enveloped object that contains an CMS Enveloped Data object
*/
public Stream Open(
Stream outStr,
string encryptionOid,
int keySize)
{
CipherKeyGenerator keyGen = GeneratorUtilities.GetKeyGenerator(encryptionOid);
keyGen.Init(new KeyGenerationParameters(rand, keySize));
return Open(outStr, encryptionOid, keyGen);
}
private class CmsAuthenticatedDataOutputStream
: BaseOutputStream
{
private readonly Stream macStream;
private readonly IMac mac;
private readonly BerSequenceGenerator cGen;
private readonly BerSequenceGenerator authGen;
private readonly BerSequenceGenerator eiGen;
public CmsAuthenticatedDataOutputStream(
Stream macStream,
IMac mac,
BerSequenceGenerator cGen,
BerSequenceGenerator authGen,
BerSequenceGenerator eiGen)
{
this.macStream = macStream;
this.mac = mac;
this.cGen = cGen;
this.authGen = authGen;
this.eiGen = eiGen;
}
public override void WriteByte(
byte b)
{
macStream.WriteByte(b);
}
public override void Write(
byte[] bytes,
int off,
int len)
{
macStream.Write(bytes, off, len);
}
protected override void Dispose(bool disposing)
{
try
{
if (!disposing)
{
return;
}
macStream.Dispose();
// TODO Parent context(s) should really be be closed explicitly
eiGen.Close();
// [TODO] auth attributes go here
byte[] macOctets = MacUtilities.DoFinal(mac);
authGen.AddObject(new DerOctetString(macOctets));
// [TODO] unauth attributes go here
authGen.Close();
cGen.Close();
}
finally
{
base.Dispose(disposing);
}
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.AspNet.Identity;
using Microsoft.Data.Entity;
using Microsoft.Framework.Configuration;
using PartsUnlimited.Areas.Admin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace PartsUnlimited.Models
{
public static class SampleData
{
public static async Task InitializePartsUnlimitedDatabaseAsync(Func<PartsUnlimitedContext> contextFactory, UserManager<ApplicationUser> userManager, IConfiguration adminRole)
{
using (var db = contextFactory())
{
bool dbNewlyCreated = await db.Database.EnsureCreatedAsync();
//Seeding a database using migrations is not yet supported. (https://github.com/aspnet/EntityFramework/issues/629.)
//Add seed data, only if the tables are empty.
bool tablesEmpty = !db.Products.Any() && !db.Orders.Any() && !db.Categories.Any() && !db.Stores.Any();
if (dbNewlyCreated || tablesEmpty)
{
await InsertTestData(contextFactory, adminRole);
await CreateAdminUser(userManager, adminRole);
}
}
}
public static async Task InsertTestData(Func<PartsUnlimitedContext> contextFactory, IConfiguration adminRole)
{
var categories = GetCategories().ToList();
await AddOrUpdateAsync(contextFactory, g => g.Name, categories);
var products = GetProducts(categories).ToList();
await AddOrUpdateAsync(contextFactory, a => a.Title, products);
var stores = GetStores().ToList();
await AddOrUpdateAsync(contextFactory, a => a.Name, stores);
var rainchecks = GetRainchecks(stores, products).ToList();
await AddOrUpdateAsync(contextFactory, a => a.RaincheckId, rainchecks);
PopulateOrderHistory(contextFactory, products, adminRole);
}
// TODO [EF] This may be replaced by a first class mechanism in EF
private static async Task AddOrUpdateAsync<TEntity>(
Func<PartsUnlimitedContext> contextFactory,
Func<TEntity, object> propertyToMatch, IEnumerable<TEntity> entities)
where TEntity : class
{
// Query in a separate context so that we can attach existing entities as modified
List<TEntity> existingData;
using (var db = contextFactory())
{
existingData = db.Set<TEntity>().ToList();
}
using (var db = contextFactory())
{
foreach (var item in entities)
{
var newState = existingData.Any(g => propertyToMatch(g).Equals(propertyToMatch(item)))
? EntityState.Modified
: EntityState.Added;
db.Entry(item).State = newState;
}
await db.SaveChangesAsync();
}
}
/// <summary>
/// Creates a store manager user who can manage the inventory.
/// </summary>
/// <param name="serviceProvider"></param>
/// <returns></returns>
public static async Task CreateAdminUser(UserManager<ApplicationUser> userManager, IConfiguration adminRole)
{
// TODO: Identity SQL does not support roles yet
//var roleManager = serviceProvider.GetService<ApplicationRoleManager>();
//if (!await roleManager.RoleExistsAsync(adminRole))
//{
// await roleManager.CreateAsync(new IdentityRole(adminRole));
//}
var username = adminRole.Get("UserName");
var password = adminRole.Get("Password");
var user = await userManager.FindByNameAsync(username);
if (user == null)
{
user = new ApplicationUser { UserName = username };
await userManager.CreateAsync(user, password);
//await userManager.AddToRoleAsync(user, adminRole);
await userManager.AddClaimAsync(user, new Claim(AdminConstants.ManageStore.Name, AdminConstants.ManageStore.Allowed));
}
}
/// <summary>
/// Generate an enumeration of rainchecks. The random number generator uses a seed to ensure
/// that the sequence is consistent, but provides somewhat random looking data.
/// </summary>
public static IEnumerable<Raincheck> GetRainchecks(IEnumerable<Store> stores, IList<Product> products)
{
var random = new Random(1234);
foreach (var store in stores)
{
for (var i = 0; i < random.Next(1, 5); i++)
{
yield return new Raincheck
{
StoreId = store.StoreId,
Name = $"John Smith{random.Next()}",
Quantity = random.Next(1, 10),
ProductId = products[random.Next(0, products.Count)].ProductId,
SalePrice = Math.Round(100 * random.NextDouble(), 2)
};
}
}
}
public static IEnumerable<Store> GetStores()
{
return Enumerable.Range(1, 20).Select(id => new Store { Name = $"Store{id}" });
}
public static IEnumerable<Category> GetCategories()
{
yield return new Category { Name = "Brakes", Description = "Brakes description", ImageUrl = "product_brakes_disc.jpg" };
yield return new Category { Name = "Lighting", Description = "Lighting description", ImageUrl = "product_lighting_headlight.jpg" };
yield return new Category { Name = "Wheels & Tires", Description = "Wheels & Tires description", ImageUrl = "product_wheel_rim.jpg" };
yield return new Category { Name = "Batteries", Description = "Batteries description", ImageUrl = "product_batteries_basic-battery.jpg" };
yield return new Category { Name = "Oil", Description = "Oil description", ImageUrl = "product_oil_premium-oil.jpg" };
}
public static void PopulateOrderHistory(Func<PartsUnlimitedContext> contextFactory, IEnumerable<Product> products, IConfiguration adminRole)
{
var random = new Random(1234);
var recomendationCombinations = new[] {
new{ Transactions = new []{1, 3, 8}, Multiplier = 60 },
new{ Transactions = new []{2, 6}, Multiplier = 10 },
new{ Transactions = new []{4, 11}, Multiplier = 20 },
new{ Transactions = new []{5, 14}, Multiplier = 10 },
new{ Transactions = new []{6, 16, 18}, Multiplier = 20 },
new{ Transactions = new []{7, 17}, Multiplier = 25 },
new{ Transactions = new []{8, 1}, Multiplier = 5 },
new{ Transactions = new []{10, 17,9}, Multiplier = 15 },
new{ Transactions = new []{11, 5}, Multiplier = 15 },
new{ Transactions = new []{12, 8}, Multiplier = 5 },
new{ Transactions = new []{13, 15}, Multiplier = 50 },
new{ Transactions = new []{14, 15}, Multiplier = 30 },
new{ Transactions = new []{16, 18}, Multiplier = 80 }
};
using (var db = contextFactory())
{
var orders = new List<Order>();
foreach (var combination in recomendationCombinations)
{
for (int i = 0; i < combination.Multiplier; i++)
{
var order = new Order
{
Username = adminRole.Get("UserName"),
OrderDate = DateTime.Now,
Name = $"John Smith{random.Next()}",
Address = "15010 NE 36th St",
City = "Redmond",
State = "WA",
PostalCode = "98052",
Country = "United States",
Phone = "425-703-6214",
Email = adminRole.Get("UserName")
};
db.Orders.Add(order);
decimal total = 0;
foreach (var id in combination.Transactions)
{
var product = products.Single(x => x.RecommendationId == id);
var orderDetail = GetOrderDetail(product, order);
db.OrderDetails.Add(orderDetail);
total += orderDetail.UnitPrice;
}
order.Total = total;
}
}
db.SaveChanges();
}
}
public static OrderDetail GetOrderDetail(Product product, Order order)
{
var random = new Random();
int quantity;
switch (product.Category.Name)
{
case "Brakes":
case "Wheels & Tires":
{
quantity = random.Next(1, 5);
break;
}
default:
{
quantity = random.Next(1, 3);
break;
}
}
return new OrderDetail
{
ProductId = product.ProductId,
UnitPrice = product.Price,
OrderId = order.OrderId,
Quantity = quantity,
};
}
public static IEnumerable<Product> GetProducts(IEnumerable<Category> categories)
{
var categoriesMap = categories.ToDictionary(c => c.Name, c => c.CategoryId);
yield return new Product
{
SkuNumber = "LIG-0001",
Title = "Halogen Headlights (2 Pack)",
CategoryId = categoriesMap["Lighting"],
Price = 38.99M,
SalePrice = 38.99M,
ProductArtUrl = "product_lighting_headlight.jpg",
ProductDetails = "{ \"Light Source\" : \"Halogen\", \"Assembly Required\": \"Yes\", \"Color\" : \"Clear\", \"Interior\" : \"Chrome\", \"Beam\": \"low and high\", \"Wiring harness included\" : \"Yes\", \"Bulbs Included\" : \"No\", \"Includes Parking Signal\" : \"Yes\"}",
Description = "Our Halogen Headlights are made to fit majority of vehicles with our universal fitting mold. Product requires some assembly.",
Inventory = 10,
LeadTime = 0,
RecommendationId = 1
};
yield return new Product
{
SkuNumber = "LIG-0002",
Title = "Bugeye Headlights (2 Pack)",
CategoryId = categoriesMap["Lighting"],
Price = 48.99M,
SalePrice = 48.99M,
ProductArtUrl = "product_lighting_bugeye-headlight.jpg",
ProductDetails = "{ \"Light Source\" : \"Halogen\", \"Assembly Required\": \"Yes\", \"Color\" : \"Clear\", \"Interior\" : \"Chrome\", \"Beam\": \"low and high\", \"Wiring harness included\" : \"No\", \"Bulbs Included\" : \"Yes\", \"Includes Parking Signal\" : \"Yes\"}",
Description = "Our Bugeye Headlights use Halogen light bulbs are made to fit into a standard bugeye slot. Product requires some assembly and includes light bulbs.",
Inventory = 7,
LeadTime = 0,
RecommendationId = 2
};
yield return new Product
{
SkuNumber = "LIG-0003",
Title = "Turn Signal Light Bulb",
CategoryId = categoriesMap["Lighting"],
Price = 6.49M,
SalePrice = 6.49M,
ProductArtUrl = "product_lighting_lightbulb.jpg",
ProductDetails = "{ \"Color\" : \"Clear\", \"Fit\" : \"Universal\", \"Wattage\" : \"30 Watts\", \"Includes Socket\" : \"Yes\"}",
Description = " Clear bulb that with a universal fitting for all headlights/taillights. Simple Installation, low wattage and a clear light for optimal visibility and efficiency.",
Inventory = 18,
LeadTime = 0,
RecommendationId = 3
};
yield return new Product
{
SkuNumber = "WHE-0001",
Title = "Matte Finish Rim",
CategoryId = categoriesMap["Wheels & Tires"],
Price = 75.99M,
SalePrice = 75.99M,
ProductArtUrl = "product_wheel_rim.jpg",
ProductDetails = "{ \"Material\" : \"Aluminum alloy\", \"Design\" : \"Spoke\", \"Spokes\" : \"9\", \"Number of Lugs\" : \"4\", \"Wheel Diameter\" : \"17 in.\", \"Color\" : \"Black\", \"Finish\" : \"Matte\" } ",
Description = "A Parts Unlimited favorite, the Matte Finish Rim is affordable low profile style. Fits all low profile tires.",
Inventory = 4,
LeadTime = 0,
RecommendationId = 4
};
yield return new Product
{
SkuNumber = "WHE-0002",
Title = "Blue Performance Alloy Rim",
CategoryId = categoriesMap["Wheels & Tires"],
Price = 88.99M,
SalePrice = 88.99M,
ProductArtUrl = "product_wheel_rim-blue.jpg",
ProductDetails = "{ \"Material\" : \"Aluminum alloy\", \"Design\" : \"Spoke\", \"Spokes\" : \"5\", \"Number of Lugs\" : \"4\", \"Wheel Diameter\" : \"18 in.\", \"Color\" : \"Blue\", \"Finish\" : \"Glossy\" } ",
Description = "Stand out from the crowd with a set of aftermarket blue rims to make you vehicle turn heads and at a price that will do the same.",
Inventory = 8,
LeadTime = 0,
RecommendationId = 5
};
yield return new Product
{
SkuNumber = "WHE-0003",
Title = "High Performance Rim",
CategoryId = categoriesMap["Wheels & Tires"],
Price = 99.99M,
SalePrice = 99.49M,
ProductArtUrl = "product_wheel_rim-red.jpg",
ProductDetails = "{ \"Material\" : \"Aluminum alloy\", \"Design\" : \"Spoke\", \"Spokes\" : \"12\", \"Number of Lugs\" : \"5\", \"Wheel Diameter\" : \"18 in.\", \"Color\" : \"Red\", \"Finish\" : \"Matte\" } ",
Description = "Light Weight Rims with a twin cross spoke design for stability and reliable performance.",
Inventory = 3,
LeadTime = 0,
RecommendationId = 6
};
yield return new Product
{
SkuNumber = "WHE-0004",
Title = "Wheel Tire Combo",
CategoryId = categoriesMap["Wheels & Tires"],
Price = 72.49M,
SalePrice = 72.49M,
ProductArtUrl = "product_wheel_tyre-wheel-combo.jpg",
ProductDetails = "{ \"Material\" : \"Steel\", \"Design\" : \"Spoke\", \"Spokes\" : \"8\", \"Number of Lugs\" : \"4\", \"Wheel Diameter\" : \"19 in.\", \"Color\" : \"Gray\", \"Finish\" : \"Standard\", \"Pre-Assembled\" : \"Yes\" } ",
Description = "For the endurance driver, take advantage of our best wearing tire yet. Composite rubber and a heavy duty steel rim.",
Inventory = 0,
LeadTime = 4,
RecommendationId = 7
};
yield return new Product
{
SkuNumber = "WHE-0005",
Title = "Chrome Rim Tire Combo",
CategoryId = categoriesMap["Wheels & Tires"],
Price = 129.99M,
SalePrice = 129.99M,
ProductArtUrl = "product_wheel_tyre-rim-chrome-combo.jpg",
ProductDetails = "{ \"Material\" : \"Aluminum alloy\", \"Design\" : \"Spoke\", \"Spokes\" : \"10\", \"Number of Lugs\" : \"5\", \"Wheel Diameter\" : \"17 in.\", \"Color\" : \"Silver\", \"Finish\" : \"Chrome\", \"Pre-Assembled\" : \"Yes\" } ",
Description = "Save time and money with our ever popular wheel and tire combo. Pre-assembled and ready to go.",
Inventory = 1,
LeadTime = 0,
RecommendationId = 8
};
yield return new Product
{
SkuNumber = "WHE-0006",
Title = "Wheel Tire Combo (4 Pack)",
CategoryId = categoriesMap["Wheels & Tires"],
Price = 219.99M,
SalePrice = 219.99M,
ProductArtUrl = "product_wheel_tyre-wheel-combo-pack.jpg",
ProductDetails = "{ \"Material\" : \"Steel\", \"Design\" : \"Spoke\", \"Spokes\" : \"8\", \"Number of Lugs\" : \"5\", \"Wheel Diameter\" : \"19 in.\", \"Color\" : \"Gray\", \"Finish\" : \"Standard\", \"Pre-Assembled\" : \"Yes\" } ",
Description = "Having trouble in the wet? Then try our special patent tire on a heavy duty steel rim. These wheels perform excellent in all conditions but were designed specifically for wet weather.",
Inventory = 3,
LeadTime = 0,
RecommendationId = 9
};
yield return new Product
{
SkuNumber = "BRA-0001",
Title = "Disk and Pad Combo",
CategoryId = categoriesMap["Brakes"],
Price = 25.99M,
SalePrice = 25.99M,
ProductArtUrl = "product_brakes_disk-pad-combo.jpg",
ProductDetails = "{ \"Disk Design\" : \"Cross Drill Slotted\", \" Pad Material\" : \"Ceramic\", \"Construction\" : \"Vented Rotor\", \"Diameter\" : \"10.3 in.\", \"Finish\" : \"Silver Zinc Plated\", \"Hat Finish\" : \"Silver Zinc Plated\", \"Material\" : \"Cast Iron\" }",
Description = "Our brake disks and pads perform the best togeather. Better stopping distances without locking up, reduced rust and dusk.",
Inventory = 0,
LeadTime = 6,
RecommendationId = 10
};
yield return new Product
{
SkuNumber = "BRA-0002",
Title = "Brake Rotor",
CategoryId = categoriesMap["Brakes"],
Price = 18.99M,
SalePrice = 18.99M,
ProductArtUrl = "product_brakes_disc.jpg",
ProductDetails = "{ \"Disk Design\" : \"Cross Drill Slotted\", \"Construction\" : \"Vented Rotor\", \"Diameter\" : \"10.3 in.\", \"Finish\" : \"Silver Zinc Plated\", \"Hat Finish\" : \"Black E-coating\", \"Material\" : \"Cast Iron\" }",
Description = "Our Brake Rotor Performs well in wet coditions with a smooth responsive feel. Machined to a high tolerance to ensure all of our Brake Rotors are safe and reliable.",
Inventory = 4,
LeadTime = 0,
RecommendationId = 11
};
yield return new Product
{
SkuNumber = "BRA-0003",
Title = "Brake Disk and Calipers",
CategoryId = categoriesMap["Brakes"],
Price = 43.99M,
SalePrice = 43.99M,
ProductArtUrl = "product_brakes_disc-calipers-red.jpg",
ProductDetails = "{\"Disk Design\" : \"Cross Drill Slotted\", \" Pad Material\" : \"Carbon Ceramic\", \"Construction\" : \"Vented Rotor\", \"Diameter\" : \"11.3 in.\", \"Bolt Pattern\": \"6 x 5.31 in.\", \"Finish\" : \"Silver Zinc Plated\", \"Material\" : \"Carbon Alloy\", \"Includes Brake Pads\" : \"Yes\" }",
Description = "Upgrading your brakes can increase stopping power, reduce dust and noise. Our Disk Calipers exceed factory specification for the best performance.",
Inventory = 2,
LeadTime = 0,
RecommendationId = 12
};
yield return new Product
{
SkuNumber = "BAT-0001",
Title = "12-Volt Calcium Battery",
CategoryId = categoriesMap["Batteries"],
Price = 129.99M,
SalePrice = 129.99M,
ProductArtUrl = "product_batteries_basic-battery.jpg",
ProductDetails = "{ \"Type\": \"Calcium\", \"Volts\" : \"12\", \"Weight\" : \"22.9 lbs\", \"Size\" : \"7.7x5x8.6\", \"Cold Cranking Amps\" : \"510\" }",
Description = "Calcium is the most common battery type. It is durable and has a long shelf and service life. They also provide high cold cranking amps.",
Inventory = 9,
LeadTime = 0,
RecommendationId = 13
};
yield return new Product
{
SkuNumber = "BAT-0002",
Title = "Spiral Coil Battery",
CategoryId = categoriesMap["Batteries"],
Price = 154.99M,
SalePrice = 154.99M,
ProductArtUrl = "product_batteries_premium-battery.jpg",
ProductDetails = "{ \"Type\": \"Spiral Coil\", \"Volts\" : \"12\", \"Weight\" : \"20.3 lbs\", \"Size\" : \"7.4x5.1x8.5\", \"Cold Cranking Amps\" : \"460\" }",
Description = "Spiral Coil batteries are the preferred option for high performance Vehicles where extra toque is need for starting. They are more resistant to heat and higher charge rates than conventional batteries.",
Inventory = 3,
LeadTime = 0,
RecommendationId = 14
};
yield return new Product
{
SkuNumber = "BAT-0003",
Title = "Jumper Leads",
CategoryId = categoriesMap["Batteries"],
Price = 16.99M,
SalePrice = 16.99M,
ProductArtUrl = "product_batteries_jumper-leads.jpg",
ProductDetails = "{ \"length\" : \"6ft.\", \"Connection Type\" : \"Alligator Clips\", \"Fit\" : \"Universal\", \"Max Amp's\" : \"750\" }",
Description = "Battery Jumper Leads have a built in surge protector and a includes a plastic carry case to keep them safe from corrosion.",
Inventory = 6,
LeadTime = 0,
RecommendationId = 15
};
yield return new Product
{
SkuNumber = "OIL-0001",
Title = "Filter Set",
CategoryId = categoriesMap["Oil"],
Price = 28.99M,
SalePrice = 28.99M,
ProductArtUrl = "product_oil_filters.jpg",
ProductDetails = "{ \"Filter Type\" : \"Canister and Cartridge\", \"Thread Size\" : \"0.75-16 in.\", \"Anti-Drainback Valve\" : \"Yes\"}",
Description = "Ensure that your vehicle's engine has a longer life with our new filter set. Trapping more dirt to ensure old freely circulates through your engine.",
Inventory = 3,
LeadTime = 0,
RecommendationId = 16
};
yield return new Product
{
SkuNumber = "OIL-0002",
Title = "Oil and Filter Combo",
CategoryId = categoriesMap["Oil"],
Price = 34.49M,
SalePrice = 34.49M,
ProductArtUrl = "product_oil_oil-filter-combo.jpg",
ProductDetails = "{ \"Filter Type\" : \"Canister\", \"Thread Size\" : \"0.75-16 in.\", \"Anti-Drainback Valve\" : \"Yes\", \"Size\" : \"1.1 gal.\", \"Synthetic\" : \"No\" }",
Description = "This Oil and Oil Filter combo is suitable for all types of passenger and light commercial vehicles. Providing affordable performance through excellent lubrication and breakdown resistance.",
Inventory = 5,
LeadTime = 0,
RecommendationId = 17
};
yield return new Product
{
SkuNumber = "OIL-0003",
Title = "Synthetic Engine Oil",
CategoryId = categoriesMap["Oil"],
Price = 36.49M,
SalePrice = 36.49M,
ProductArtUrl = "product_oil_premium-oil.jpg",
ProductDetails = "{ \"Size\" : \"1.1 Gal.\" , \"Synthetic \" : \"Yes\"}",
Description = "This Oil is designed to reduce sludge deposits and metal friction throughout your cars engine. Provides performance no matter the condition or temperature.",
Inventory = 11,
LeadTime = 0,
RecommendationId = 18
};
}
}
}
| |
#region Using directives
#define USE_TRACING
using System;
using System.IO;
using System.Xml;
#endregion
//////////////////////////////////////////////////////////////////////
// <summary>contains Service, the base interface that
// allows to query a service for different feeds
// </summary>
//////////////////////////////////////////////////////////////////////
namespace Google.GData.Client
{
//////////////////////////////////////////////////////////////////////
/// <summary>base Service interface definition
/// </summary>
//////////////////////////////////////////////////////////////////////
public interface IService
{
/// <summary>get/set for credentials to the service calls. Gets passed through to GDatarequest</summary>
GDataCredentials Credentials { get; set; }
/// <summary>get/set for the GDataRequestFactory object to use</summary>
IGDataRequestFactory RequestFactory { get; set; }
/// <summary>
/// returns the name of the service identifier, like wise for spreadsheets services
/// </summary>
string ServiceIdentifier { get; }
/// <summary>the minimal Get OpenSearchRssDescription function</summary>
Stream QueryOpenSearchRssDescription(Uri serviceUri);
/// <summary>the minimal query implementation</summary>
AtomFeed Query(FeedQuery feedQuery);
/// <summary>the minimal query implementation with conditional GET</summary>
AtomFeed Query(FeedQuery feedQuery, DateTime ifModifiedSince);
/// <summary>simple update for atom resources</summary>
AtomEntry Update(AtomEntry entry);
/// <summary>simple insert for atom entries, based on a feed</summary>
AtomEntry Insert(AtomFeed feed, AtomEntry entry);
/// <summary>delete an entry</summary>
void Delete(AtomEntry entry);
/// <summary>delete an entry</summary>
void Delete(Uri uriTarget);
/// <summary>batch operation, posting of a set of entries</summary>
AtomFeed Batch(AtomFeed feed, Uri batchUri);
/// <summary>simple update for media resources</summary>
AtomEntry Update(Uri uriTarget, Stream input, string contentType, string slugHeader);
/// <summary>simple insert for media resources</summary>
AtomEntry Insert(Uri uriTarget, Stream input, string contentType, string slugHeader);
}
//////////////////////////////////////////////////////////////////////
/// <summary>the one that creates GDatarequests on the service
/// </summary>
//////////////////////////////////////////////////////////////////////
public interface IGDataRequestFactory
{
/// <summary>set wether or not to use gzip for new requests</summary>
bool UseGZip { get; set; }
/// <summary>
/// indicates that the service should use SSL exclusively
/// </summary>
bool UseSSL { get; set; }
/// <summary>creation method for GDatarequests</summary>
IGDataRequest CreateRequest(GDataRequestType type, Uri uriTarget);
}
//////////////////////////////////////////////////////////////////////
/// <summary>enum to describe the different operations on the GDataRequest
/// </summary>
//////////////////////////////////////////////////////////////////////
public enum GDataRequestType
{
/// <summary>
/// The request is used for query
/// </summary>
Query,
/// <summary>
/// The request is used for an insert
/// </summary>
Insert,
/// <summary>
/// The request is used for an update
/// </summary>
Update,
/// <summary>
/// The request is used for a delete
/// </summary>
Delete,
/// <summary>
/// This request is used for a batch operation
/// </summary>
Batch
}
/// <summary>
/// Thin layer to abstract the request/response
/// </summary>
public interface IGDataRequest
{
/// <summary>get/set for credentials to the service calls. Gets passed through to GDatarequest</summary>
GDataCredentials Credentials { get; set; }
/// <summary>set wether or not to use gzip for this request</summary>
bool UseGZip { get; set; }
/// <summary>set a timestamp for conditional GET</summary>
DateTime IfModifiedSince { get; set; }
/// <summary>persist the content so if reset</summary>
AtomBase ContentStore { get; set; }
/// <summary>denotes if it's a batch request</summary>
bool IsBatch { get; set; }
/// <summary>gets the request stream to write into</summary>
Stream GetRequestStream();
/// <summary>Executes the request</summary>
void Execute();
/// <summary>gets the response stream to read from</summary>
Stream GetResponseStream();
}
/// <summary>
/// interface to indicate that an element supports an Etag. Currently implemented on AbstractEntry,
/// AbstractFeed and GDataRequest
/// </summary>
public interface ISupportsEtag
{
/// <summary>set the etag for updates</summary>
string Etag { get; set; }
}
//////////////////////////////////////////////////////////////////////
/// <summary>Thin layer to create an action on an item/response
/// </summary>
//////////////////////////////////////////////////////////////////////
public interface IBaseWalkerAction
{
/// <summary>the only relevant method here</summary>
bool Go(AtomBase atom);
}
/// <summary>
/// Wrapper interface used to replace the ExtensionList.
/// </summary>
public interface IExtensionElementFactory
{
/// <summary>
/// returns the XML local name that is used
/// </summary>
string XmlName { get; }
/// <summary>
/// returns the XML namespace that is processed
/// </summary>
string XmlNameSpace { get; }
/// <summary>
/// returns the xml prefix used
/// </summary>
string XmlPrefix { get; }
/// <summary>
/// instantiates the correct extension element
/// </summary>
/// <param name="node">the xmlnode to parse</param>
/// <param name="parser">the atomfeedparser to use if deep parsing of subelements is required</param>
/// <returns></returns>
IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser);
/// <summary>the only relevant method here</summary>
void Save(XmlWriter writer);
}
//////////////////////////////////////////////////////////////////////
/// <summary>interface for commone extension container functionallity
/// used for AtomBase and SimpleContainer
/// </summary>
//////////////////////////////////////////////////////////////////////
public interface IExtensionContainer
{
/// <summary>the list of extensions for this container
/// the elements in that list MUST implement IExtensionElementFactory
/// and IExtensionElement</summary>
/// <returns> </returns>
ExtensionList ExtensionElements { get; }
/// <summary>the list of extensions for this container
/// the elements in that list MUST implement IExtensionElementFactory
/// and IExtensionElement</summary>
/// <returns> </returns>
ExtensionList ExtensionFactories { get; }
/// <summary>
/// Finds a specific ExtensionElement based on its local name
/// and its namespace. If namespace is NULL, the first one where
/// the localname matches is found. If there are extensionelements that do
/// not implment ExtensionElementFactory, they will not be taken into account
/// </summary>
/// <param name="localName">the xml local name of the element to find</param>
/// <param name="ns">the namespace of the elementToPersist</param>
/// <returns>Object</returns>
IExtensionElementFactory FindExtension(string localName, string ns);
/// <summary>
/// all extension elements that match a namespace/localname
/// given will be removed and the new one will be inserted
/// </summary>
/// <param name="localName">the local name to find</param>
/// <param name="ns">the namespace to match, if null, ns is ignored</param>
/// <param name="obj">the new element to put in</param>
void ReplaceExtension(string localName, string ns, IExtensionElementFactory obj);
/// <summary>
/// Finds all ExtensionElement based on its local name
/// and its namespace. If namespace is NULL, allwhere
/// the localname matches is found. If there are extensionelements that do
/// not implment ExtensionElementFactory, they will not be taken into account
/// Primary use of this is to find XML nodes
/// </summary>
/// <param name="localName">the xml local name of the element to find</param>
/// <param name="ns">the namespace of the elementToPersist</param>
/// <returns>none</returns>
ExtensionList FindExtensions(string localName, string ns);
/// <summary>
/// Deletes all Extensions from the Extension list that match
/// a localName and a Namespace.
/// </summary>
/// <param name="localName">the local name to find</param>
/// <param name="ns">the namespace to match, if null, ns is ignored</param>
/// <returns>int - the number of deleted extensions</returns>
int DeleteExtensions(string localName, string ns);
}
}
| |
using XPT.Games.Generic.Constants;
using XPT.Games.Generic.Maps;
using XPT.Games.Twinion.Entities;
namespace XPT.Games.Twinion.Maps {
class TwMap09 : TwMap {
public override int MapIndex => 9;
public override int MapID => 0x0402;
protected override int RandomEncounterChance => 15;
protected override int RandomEncounterExtraCount => 0;
private const int BRICK_ZAP = 1;
protected override void FnEvent01(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, DWARFWIZARD);
ShowText(player, type, doMsgs, "You come across an aging magician. 'Be sure to open all doors in the dungeon. I have learned many a spell by being curious.'");
}
protected override void FnEvent02(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, FOUNTAIN);
ShowText(player, type, doMsgs, "Windward Fountain restores your mana.");
ModifyMana(player, type, doMsgs, 10000);
}
protected override void FnEvent03(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, GREMLINWIZARD);
ShowText(player, type, doMsgs, "A wizard rushes by you laughing and shouting, 'Now they will all be clueless.'");
}
protected override void FnEvent04(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "A sign on the wall reminds you, 'Some rooms should be accessed only by certain guilds, races or alignments. Oft times you could lose something of value by not heeding a warning.'");
}
protected override void FnEvent05(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetRace(player, type, doMsgs) == HUMAN) {
ShowText(player, type, doMsgs, "The message on the plaque says 'Use the Pearl third.'");
}
else {
ShowText(player, type, doMsgs, "Runes in the Human tongue are etched here.");
}
}
protected override void FnEvent06(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetRace(player, type, doMsgs) == HALFLING) {
ShowText(player, type, doMsgs, "The message on the plaque says 'If given a choice, use the Pearl second.'");
}
else {
ShowText(player, type, doMsgs, "You see a royal insignia of the Halflings.");
}
}
protected override void FnEvent07(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, HUMANBARBARIAN);
ShowText(player, type, doMsgs, "You see a badly wounded barbarian. 'Heed my words... grave robbing can be hazardous to your health.'");
}
protected override void FnEvent08(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetRace(player, type, doMsgs) == GREMLIN) {
ShowText(player, type, doMsgs, "The message on the plaque says 'If given a choice, use the Pearl first.'");
}
else {
ShowText(player, type, doMsgs, "The etchings on the plaque seem familiar.");
}
}
protected override void FnEvent09(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetRace(player, type, doMsgs) == ELF) {
ShowText(player, type, doMsgs, "The message on the plaque says 'Use Dabelais' payment first.'");
}
else {
ShowText(player, type, doMsgs, "Elven runes abound here.");
}
}
protected override void FnEvent0A(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetRace(player, type, doMsgs) == TROLL) {
ShowText(player, type, doMsgs, "The message on the plaque says 'Use Dabelais' payment second.'");
}
else {
ShowText(player, type, doMsgs, "You don't understand the language on the plaque.");
}
}
protected override void FnEvent0B(TwPlayerServer player, MapEventType type, bool doMsgs) {
TeleportParty(player, type, doMsgs, 4, 2, 162, Direction.South);
}
protected override void FnEvent0C(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasUsedSkill(player, type, ref doMsgs, DETECT_SKILL) >= 6 || HasUsedSpell(player, type, ref doMsgs, TRUE_SEEING_SPELL) >= 1 || UsedItem(player, type, ref doMsgs, HELMOFWISDOM, HELMOFWISDOM) || UsedItem(player, type, ref doMsgs, VALKYRIESHELM, VALKYRIESHELM) || UsedItem(player, type, ref doMsgs, RINGOFTHIEVES, RINGOFTHIEVES) || UsedItem(player, type, ref doMsgs, CRYSTALBALL, CRYSTALBALL)) {
ShowText(player, type, doMsgs, "A door suddenly appears.");
DoorHere(player, type, doMsgs);
WallClear(player, type, doMsgs);
}
else {
WallBlock(player, type, doMsgs);
}
}
protected override void FnEvent0D(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "As the winds swirl around, you hear a ghostly voice whispering something about benevolent spirits endowing you with certain attributes.");
}
protected override void FnEvent0E(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetRace(player, type, doMsgs) == ORC) {
ShowText(player, type, doMsgs, "The message on the plaque says 'Use the Coral before the Topaz.'");
}
else {
ShowText(player, type, doMsgs, "Some guttural language pervades here.");
}
}
protected override void FnEvent0F(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetRace(player, type, doMsgs) == GNOME) {
ShowText(player, type, doMsgs, "The message on the plaque says 'If given a choice, use the Opal third.'");
}
else {
ShowText(player, type, doMsgs, "Only Gnomes can read this.");
}
}
protected override void FnEvent10(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (UsedItem(player, type, ref doMsgs, MAZEKEY, MAZEKEY)) {
WallClear(player, type, doMsgs);
DoorHere(player, type, doMsgs);
ShowText(player, type, doMsgs, "The Maze Key opens the door.");
}
else {
WallBlock(player, type, doMsgs);
ShowText(player, type, doMsgs, "The door is locked. Engraved on the lock are the words -");
ShowText(player, type, doMsgs, "'Manufactured by");
ShowText(player, type, doMsgs, "Aeowyn's Slateworks.");
ShowText(player, type, doMsgs, "Zembolinee Bromerique,");
ShowText(player, type, doMsgs, "Esquire.'");
}
}
protected override void FnEvent11(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetRace(player, type, doMsgs) == DWARF) {
ShowText(player, type, doMsgs, "The message on the plaque says 'Use Tyndil's payment first.'");
}
else {
ShowText(player, type, doMsgs, "Ah, you recognize but don't understand the Dwarven runes.");
}
}
protected override void FnEvent12(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, DWARFTHIEF);
ShowText(player, type, doMsgs, "Flashing his black and white shield at you the thief states, 'It's aMAZEing how this shield guards against the dangers of this maze.'");
}
protected override void FnEvent13(TwPlayerServer player, MapEventType type, bool doMsgs) {
TeleportParty(player, type, doMsgs, 4, 2, 185, Direction.West);
}
protected override void FnEvent14(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasItem(player, type, doMsgs, HARMONYSGUARDIAN) || HasItem(player, type, doMsgs, CHAOSGUARDIAN)) {
ShowText(player, type, doMsgs, "Your guardian protects you from the mist.");
}
else {
ShowText(player, type, doMsgs, "A mist surrounds you absorbing some of your mana.");
ModifyMana(player, type, doMsgs, - 100);
}
}
protected override void FnEvent15(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You stop and contemplate your luck in having found items which assist you in locating secret passages. These items have become handy.");
}
protected override void FnEvent16(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SLATE_MAP) == 1) {
if (HasItem(player, type, doMsgs, SLATEMAP)) {
EmptyRoom(player, type, doMsgs);
ItemTake(player, type, doMsgs);
}
else {
GiveItem(player, type, doMsgs, SLATEMAP);
MapPieceTxt(player, type, doMsgs);
ItemTake(player, type, doMsgs);
}
}
else {
if (HasItem(player, type, doMsgs, MAZEKEY)) {
GiveItem(player, type, doMsgs, SLATEMAP);
ModifyExperience(player, type, doMsgs, 200000);
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.SLATE_MAP, 1);
MapPieceTxt(player, type, doMsgs);
ItemTake(player, type, doMsgs);
}
else {
EmptyRoom(player, type, doMsgs);
}
}
}
protected override void FnEvent17(TwPlayerServer player, MapEventType type, bool doMsgs) {
TeleportParty(player, type, doMsgs, 4, 2, 208, Direction.North);
}
protected override void FnEvent18(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You wander past a group of adventurers all lugging ropes and you wonder about their destination.");
}
protected override void FnEvent19(TwPlayerServer player, MapEventType type, bool doMsgs) {
TeleportParty(player, type, doMsgs, 4, 2, 255, Direction.West);
}
protected override void FnEvent1A(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, HALFLINGKNIGHT);
ShowText(player, type, doMsgs, "You pass a knight who, as he hurries by, calls out - ");
ShowText(player, type, doMsgs, "'I have traversed the Night Elves' Domain and have found the locations of Snicker's three brothers. Now off to find the item they desire!'");
}
protected override void FnEvent1B(TwPlayerServer player, MapEventType type, bool doMsgs) {
TeleportParty(player, type, doMsgs, 4, 1, 170, Direction.North);
}
protected override void FnEvent1D(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasItem(player, type, doMsgs, STONEOFAWARENESS)) {
WallClear(player, type, doMsgs);
DoorHere(player, type, doMsgs);
ShowText(player, type, doMsgs, "The Stone of Awareness makes a door visible.");
}
else {
WallBlock(player, type, doMsgs);
}
}
protected override void FnEvent1E(TwPlayerServer player, MapEventType type, bool doMsgs) {
TeleportParty(player, type, doMsgs, 4, 2, 33, Direction.East);
}
protected override void FnEvent1F(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, FOUNTAIN);
ModifyHealth(player, type, doMsgs, GetHealthMax(player, type, doMsgs));
ShowText(player, type, doMsgs, "The waters of Leeward Fountain heal your wounds.");
}
protected override void FnEvent21(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, DWARFKNIGHT);
ShowText(player, type, doMsgs, "You pass a lost knight who toys with a stone.");
ShowText(player, type, doMsgs, "The knight suddenly snarls at you, 'This is not it!");
ShowText(player, type, doMsgs, "The stone I seek will let me find what is otherwise undetectable in this area of the dungeon!'");
}
protected override void FnEvent22(TwPlayerServer player, MapEventType type, bool doMsgs) {
TeleportParty(player, type, doMsgs, 4, 2, 233, Direction.East);
}
protected override void FnEvent23(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, TROLLCLERIC);
ShowText(player, type, doMsgs, "You stumble upon a cleric who says gravely, 'Not all fountains are good for your health.'");
}
protected override void FnEvent25(TwPlayerServer player, MapEventType type, bool doMsgs) {
TeleportParty(player, type, doMsgs, 4, 2, 227, Direction.East);
}
protected override void FnEvent26(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You come across a worn journal telling an adventurer's story about becoming more skilled after scaling cliffs.");
}
protected override void FnEvent27(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasItem(player, type, doMsgs, STONEOFAWARENESS)) {
SetTreasure(player, type, doMsgs, SCROLLOFTHESUN, ELIXIROFHEALTH, 0, 0, 0, 1500);
ShowText(player, type, doMsgs, "Golems attack you for your stone.");
}
else {
SetTreasure(player, type, doMsgs, STONEOFAWARENESS, 0, 0, 0, 0, 3500);
ShowText(player, type, doMsgs, "You see golems looking at a stone.");
}
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 13);
AddEncounter(player, type, doMsgs, 02, 12);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 11);
AddEncounter(player, type, doMsgs, 02, 12);
AddEncounter(player, type, doMsgs, 06, 14);
}
else {
AddEncounter(player, type, doMsgs, 01, 11);
AddEncounter(player, type, doMsgs, 02, 11);
AddEncounter(player, type, doMsgs, 03, 13);
AddEncounter(player, type, doMsgs, 05, 29);
AddEncounter(player, type, doMsgs, 06, 30);
}
}
protected override void FnEvent28(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.CHAOS_MAZE) == 1) {
EmptyRoom(player, type, doMsgs);
}
else {
if (GetAlignment(player, type, doMsgs) == CHAOS) {
ModifyGold(player, type, doMsgs, 25000);
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.CHAOS_MAZE, 1);
ShowText(player, type, doMsgs, "You find a bag with 25,000 gold pieces.");
GiveItem(player, type, doMsgs, LANCEOFDARKNESS);
GiveItem(player, type, doMsgs, GLASSBOW);
}
else {
ModifyGold(player, type, doMsgs, - 2000);
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.CHAOS_MAZE, 1);
ShowText(player, type, doMsgs, "You are jumped by chaotic adventurers who steal 2,000 gold pieces.");
}
}
}
protected override void FnEvent29(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasItem(player, type, doMsgs, CHAOSGUARDIAN) || HasItem(player, type, doMsgs, HARMONYSGUARDIAN)) {
WallClear(player, type, doMsgs);
DoorHere(player, type, doMsgs);
ShowText(player, type, doMsgs, "The fog lifts and you see the door to the Tool Shed.");
}
else {
WallBlock(player, type, doMsgs);
}
}
protected override void FnEvent2A(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasItem(player, type, doMsgs, TNEPRESKEY)) {
SetTreasure(player, type, doMsgs, REFRESHSCROLL, BLESSPOTION, 0, 0, 0, 1500);
ShowText(player, type, doMsgs, "Nasty looking monsters attack you for your key.");
}
else {
SetTreasure(player, type, doMsgs, TNEPRESKEY, MANAELIXIR, BLESSPOTION, 0, 0, 3000);
ShowText(player, type, doMsgs, "Vicious monsters stand guard over an S-shaped key.");
}
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 1);
AddEncounter(player, type, doMsgs, 02, 4);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 2);
AddEncounter(player, type, doMsgs, 02, 27);
AddEncounter(player, type, doMsgs, 06, 5);
}
else {
AddEncounter(player, type, doMsgs, 01, 2);
AddEncounter(player, type, doMsgs, 02, 2);
AddEncounter(player, type, doMsgs, 04, 3);
AddEncounter(player, type, doMsgs, 05, 26);
AddEncounter(player, type, doMsgs, 06, 27);
}
}
protected override void FnEvent2C(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasItem(player, type, doMsgs, CHAOSGUARDIAN) || HasItem(player, type, doMsgs, HARMONYSGUARDIAN)) {
WallClear(player, type, doMsgs);
DoorHere(player, type, doMsgs);
ShowText(player, type, doMsgs, "The fog lifts and you see the door to the Gardener's Shed.");
}
else {
WallBlock(player, type, doMsgs);
}
}
protected override void FnEvent2D(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.HARMONY_MAZE) == 1) {
EmptyRoom(player, type, doMsgs);
}
else {
if (GetAlignment(player, type, doMsgs) == HARMONY) {
ModifyGold(player, type, doMsgs, 25000);
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.HARMONY_MAZE, 1);
ShowText(player, type, doMsgs, "You find a bag with 25,000 gold pieces.");
GiveItem(player, type, doMsgs, PEACEMAKER);
GiveItem(player, type, doMsgs, HEAVENSWRATH);
}
else {
ModifyGold(player, type, doMsgs, - 2000);
SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.HARMONY_MAZE, 1);
ShowText(player, type, doMsgs, "You are jumped by harmonic adventurers who steal 2,000 gold pieces.");
}
}
}
protected override void FnEvent2E(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasItem(player, type, doMsgs, HARMONYSGUARDIAN) || HasItem(player, type, doMsgs, CHAOSGUARDIAN)) {
ShowText(player, type, doMsgs, "Your guardian protects you from injury.");
}
else {
if (GetFlag(player, type, doMsgs, FlagTypeTile, BRICK_ZAP) == 0) {
DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs) / 5);
ShowText(player, type, doMsgs, "A loose brick falls from the maze wall and injures you.");
SetFlag(player, type, doMsgs, FlagTypeTile, BRICK_ZAP, 1);
}
}
}
protected override void FnEvent2F(TwPlayerServer player, MapEventType type, bool doMsgs) {
ModifyHealth(player, type, doMsgs, GetHealthMax(player, type, doMsgs));
ModifyMana(player, type, doMsgs, 10000);
ShowText(player, type, doMsgs, "The swirling waters of the Whirlwind Pool increase your health and mana.");
}
protected override void FnEvent30(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "Inside a quest bag you find a scribbled note to another adventurer...");
ShowText(player, type, doMsgs, "'Rumor has it that treasure might still be hidden in a safe.'");
}
protected override void FnEvent31(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasItem(player, type, doMsgs, HARMONYSGUARDIAN)) {
SetTreasure(player, type, doMsgs, CURATIVEELIXIR, MANAELIXIR, 0, 0, 0, 1000);
}
else {
if (GetAlignment(player, type, doMsgs) == HARMONY) {
SetTreasure(player, type, doMsgs, HARMONYSGUARDIAN, CUREALLPOTION, MANAELIXIR, 0, 0, 3000);
ShowText(player, type, doMsgs, "You see a shield on the floor, but the way is blocked.");
}
else {
ModifyExperience(player, type, doMsgs, - 5000);
SetTreasure(player, type, doMsgs, MANAPOTION, 0, 0, 0, 0, 1);
ShowText(player, type, doMsgs, "You lose experience for not heeding warnings.");
}
}
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 6);
AddEncounter(player, type, doMsgs, 02, 8);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 7);
AddEncounter(player, type, doMsgs, 02, 7);
AddEncounter(player, type, doMsgs, 06, 9);
}
else {
AddEncounter(player, type, doMsgs, 01, 7);
AddEncounter(player, type, doMsgs, 02, 7);
AddEncounter(player, type, doMsgs, 04, 8);
AddEncounter(player, type, doMsgs, 05, 8);
AddEncounter(player, type, doMsgs, 06, 28);
}
}
protected override void FnEvent32(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowPortrait(player, type, doMsgs, HALFLINGRANGER);
ShowText(player, type, doMsgs, "'Excuse me? I'm trying to find the Ballroom. I must be completely lost.");
ShowText(player, type, doMsgs, "Oh, if you ever find yourself in the Ballroom, make sure you have your musical key ready.'");
}
protected override void FnEvent33(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (HasItem(player, type, doMsgs, CHAOSGUARDIAN)) {
SetTreasure(player, type, doMsgs, CURATIVEELIXIR, MANAELIXIR, 0, 0, 0, 1000);
}
else {
if (GetAlignment(player, type, doMsgs) == CHAOS) {
SetTreasure(player, type, doMsgs, CHAOSGUARDIAN, CUREALLPOTION, MANAELIXIR, 0, 0, 3000);
ShowText(player, type, doMsgs, "You see a shield on the floor, but the way to it is blocked.");
}
else {
ModifyExperience(player, type, doMsgs, - 5000);
SetTreasure(player, type, doMsgs, MANAPOTION, 0, 0, 0, 0, 1);
ShowText(player, type, doMsgs, "You lose experience for not heeding warnings.");
}
}
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 6);
AddEncounter(player, type, doMsgs, 02, 8);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 7);
AddEncounter(player, type, doMsgs, 02, 7);
AddEncounter(player, type, doMsgs, 06, 9);
}
else {
AddEncounter(player, type, doMsgs, 01, 7);
AddEncounter(player, type, doMsgs, 02, 7);
AddEncounter(player, type, doMsgs, 04, 8);
AddEncounter(player, type, doMsgs, 05, 8);
AddEncounter(player, type, doMsgs, 06, 28);
}
}
protected override void FnEvent34(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "The door to the north bears a sign - 'Harmony Only.' The door to the west bears a sign - 'Chaos Only.'");
}
protected override void FnEvent35(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetAlignment(player, type, doMsgs) == HARMONY) {
ShowText(player, type, doMsgs, "A secret message for Harmonics only is posted on the door. 'Do not enter the Tool Shed.'");
}
}
protected override void FnEvent36(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetAlignment(player, type, doMsgs) == CHAOS) {
ShowText(player, type, doMsgs, "A secret message for Chaotics only is posted on the door. 'Do not enter the Gardener's Shed.'");
}
}
protected override void FnEvent37(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 34);
AddEncounter(player, type, doMsgs, 02, 39);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 17);
AddEncounter(player, type, doMsgs, 02, 34);
AddEncounter(player, type, doMsgs, 06, 36);
}
else {
AddEncounter(player, type, doMsgs, 01, 17);
AddEncounter(player, type, doMsgs, 02, 33);
AddEncounter(player, type, doMsgs, 03, 37);
AddEncounter(player, type, doMsgs, 04, 38);
AddEncounter(player, type, doMsgs, 05, 37);
}
}
protected override void FnEvent38(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 1);
AddEncounter(player, type, doMsgs, 02, 8);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 8);
AddEncounter(player, type, doMsgs, 02, 9);
AddEncounter(player, type, doMsgs, 06, 26);
}
else {
AddEncounter(player, type, doMsgs, 01, 26);
AddEncounter(player, type, doMsgs, 02, 26);
AddEncounter(player, type, doMsgs, 03, 27);
AddEncounter(player, type, doMsgs, 05, 8);
AddEncounter(player, type, doMsgs, 06, 28);
}
}
protected override void FnEvent39(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 10);
AddEncounter(player, type, doMsgs, 02, 13);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 11);
AddEncounter(player, type, doMsgs, 02, 13);
AddEncounter(player, type, doMsgs, 05, 40);
}
else {
AddEncounter(player, type, doMsgs, 01, 11);
AddEncounter(player, type, doMsgs, 02, 13);
AddEncounter(player, type, doMsgs, 04, 14);
AddEncounter(player, type, doMsgs, 05, 31);
AddEncounter(player, type, doMsgs, 06, 40);
}
}
protected override void FnEvent3A(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 39);
AddEncounter(player, type, doMsgs, 02, 17);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 17);
AddEncounter(player, type, doMsgs, 02, 17);
AddEncounter(player, type, doMsgs, 03, 19);
}
else {
AddEncounter(player, type, doMsgs, 01, 17);
AddEncounter(player, type, doMsgs, 02, 17);
AddEncounter(player, type, doMsgs, 03, 19);
AddEncounter(player, type, doMsgs, 04, 34);
AddEncounter(player, type, doMsgs, 06, 35);
}
}
protected override void FnEvent3B(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 8);
AddEncounter(player, type, doMsgs, 02, 12);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 8);
AddEncounter(player, type, doMsgs, 02, 9);
AddEncounter(player, type, doMsgs, 03, 13);
AddEncounter(player, type, doMsgs, 04, 30);
}
else {
AddEncounter(player, type, doMsgs, 01, 9);
AddEncounter(player, type, doMsgs, 02, 29);
AddEncounter(player, type, doMsgs, 03, 13);
AddEncounter(player, type, doMsgs, 05, 28);
AddEncounter(player, type, doMsgs, 06, 16);
}
}
protected override void FnEvent3C(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 1);
AddEncounter(player, type, doMsgs, 02, 2);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 1);
AddEncounter(player, type, doMsgs, 02, 1);
AddEncounter(player, type, doMsgs, 05, 2);
AddEncounter(player, type, doMsgs, 06, 3);
}
else {
AddEncounter(player, type, doMsgs, 01, 2);
AddEncounter(player, type, doMsgs, 02, 2);
AddEncounter(player, type, doMsgs, 04, 27);
AddEncounter(player, type, doMsgs, 05, 4);
AddEncounter(player, type, doMsgs, 06, 25);
}
}
protected override void FnEvent3D(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 39);
AddEncounter(player, type, doMsgs, 02, 39);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 16);
AddEncounter(player, type, doMsgs, 02, 16);
AddEncounter(player, type, doMsgs, 03, 17);
AddEncounter(player, type, doMsgs, 04, 18);
}
else {
AddEncounter(player, type, doMsgs, 01, 36);
AddEncounter(player, type, doMsgs, 02, 21);
AddEncounter(player, type, doMsgs, 03, 20);
AddEncounter(player, type, doMsgs, 05, 28);
AddEncounter(player, type, doMsgs, 06, 8);
}
}
protected override void FnEvent3E(TwPlayerServer player, MapEventType type, bool doMsgs) {
if (GetPartyCount(player, type, doMsgs) == 1) {
AddEncounter(player, type, doMsgs, 01, 23);
AddEncounter(player, type, doMsgs, 02, 13);
}
else if (GetPartyCount(player, type, doMsgs) == 2) {
AddEncounter(player, type, doMsgs, 01, 29);
AddEncounter(player, type, doMsgs, 02, 29);
AddEncounter(player, type, doMsgs, 05, 23);
}
else {
AddEncounter(player, type, doMsgs, 01, 29);
AddEncounter(player, type, doMsgs, 02, 29);
AddEncounter(player, type, doMsgs, 03, 30);
AddEncounter(player, type, doMsgs, 05, 24);
AddEncounter(player, type, doMsgs, 06, 38);
}
}
private void MapPieceTxt(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "You find a Map etched on a piece of slate. It must be one of the four maps Queen Aeowyn sent you to find.");
ShowText(player, type, doMsgs, "Your Maze Key and Stone of Awareness dissipate as you grab it.");
}
private void WallClear(TwPlayerServer player, MapEventType type, bool doMsgs) {
ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
private void WallBlock(TwPlayerServer player, MapEventType type, bool doMsgs) {
SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
private void DoorHere(TwPlayerServer player, MapEventType type, bool doMsgs) {
SetWallItem(player, type, doMsgs, DOOR, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs));
}
private void ItemTake(TwPlayerServer player, MapEventType type, bool doMsgs) {
RemoveItem(player, type, doMsgs, MAZEKEY);
RemoveItem(player, type, doMsgs, STONEOFAWARENESS);
}
private void DamXit(TwPlayerServer player, MapEventType type, bool doMsgs) {
DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs));
}
private void EmptyRoom(TwPlayerServer player, MapEventType type, bool doMsgs) {
ShowText(player, type, doMsgs, "The room is empty.");
}
}
}
| |
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace Palaso.UI.WindowsForms.SuperToolTip
{
[ToolboxItem(false)]
public partial class SuperToolTipWindowData : UserControl
{
#region Private Members
int bodyPicWidth = 100;
private SuperToolTipInfo _superToolTipInfo;
#endregion
#region Public Properties
public SuperToolTipInfo SuperInfo
{
get { return _superToolTipInfo; }
set
{
//palaso additions
_superToolTipInfo.OffsetForWhereToDisplay = value.OffsetForWhereToDisplay;
bool redrawBackground = false;
// if (!_superToolTipInfo.Equals(value))
{
if (_superToolTipInfo.BackgroundGradientBegin != value.BackgroundGradientBegin)
{
_superToolTipInfo.BackgroundGradientBegin = value.BackgroundGradientBegin;
redrawBackground = true;
}
if (_superToolTipInfo.BackgroundGradientMiddle != value.BackgroundGradientMiddle)
{
_superToolTipInfo.BackgroundGradientMiddle = value.BackgroundGradientMiddle;
redrawBackground = true;
}
if (_superToolTipInfo.BackgroundGradientEnd != value.BackgroundGradientEnd)
{
_superToolTipInfo.BackgroundGradientEnd = value.BackgroundGradientEnd;
redrawBackground = true;
}
if (_superToolTipInfo.BodyImage != value.BodyImage || _superToolTipInfo.BodyForeColor != value.BodyForeColor ||
_superToolTipInfo.BodyFont != value.BodyFont || _superToolTipInfo.BodyText != value.BodyText)
{
_superToolTipInfo.BodyImage = value.BodyImage;
_superToolTipInfo.BodyForeColor = value.BodyForeColor;
_superToolTipInfo.BodyText = value.BodyText;
_superToolTipInfo.BodyFont = value.BodyFont;
picBody.Visible = _superToolTipInfo.BodyImage == null ? false : true;
picBody.Image = _superToolTipInfo.BodyImage;
SetBodyData();
}
if (value.ShowHeader)
{
_superToolTipInfo.ShowHeader = value.ShowHeader;
if (_superToolTipInfo.HeaderFont != value.HeaderFont || _superToolTipInfo.HeaderText != value.HeaderText
|| _superToolTipInfo.HeaderForeColor != value.HeaderForeColor || _superToolTipInfo.ShowHeaderSeparator != value.ShowHeaderSeparator)
{
_superToolTipInfo.HeaderText = value.HeaderText;
_superToolTipInfo.HeaderForeColor = value.HeaderForeColor;
_superToolTipInfo.HeaderFont = value.HeaderFont;
_superToolTipInfo.ShowHeaderSeparator = value.ShowHeaderSeparator;
SetHeaderData();
}
}
lblHeader.Visible = value.ShowHeader;
if (value.ShowFooter)
{
_superToolTipInfo.ShowFooter = value.ShowFooter;
if (_superToolTipInfo.FooterFont != value.FooterFont || _superToolTipInfo.FooterText != value.FooterText
|| _superToolTipInfo.FooterForeColor != value.FooterForeColor || _superToolTipInfo.FooterImage != value.FooterImage || _superToolTipInfo.ShowFooterSeparator != value.ShowFooterSeparator)
{
_superToolTipInfo.FooterText = value.FooterText;
_superToolTipInfo.FooterForeColor = value.FooterForeColor;
_superToolTipInfo.FooterFont = value.FooterFont;
_superToolTipInfo.FooterImage = value.FooterImage;
_superToolTipInfo.ShowFooterSeparator = value.ShowFooterSeparator;
picFooter.Visible = _superToolTipInfo.FooterImage == null ? false : true;
SetFooterData();
}
}
flwPnlFooter.Visible = value.ShowFooter;
if (redrawBackground) RedrawBackground();
}
}
}
#endregion
#region Constructors
public SuperToolTipWindowData()
{
InitializeComponent();
_superToolTipInfo = new SuperToolTipInfo();
}
#endregion
#region Painting
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
Rectangle rect1 = new Rectangle(0, Height / 2, Width, Height / 2);
Rectangle rect2 = new Rectangle(0, 0, Width, Height / 2);
using (LinearGradientBrush b2 = new LinearGradientBrush(new Rectangle(0, Height / 2 - 1, Width, Height / 2), _superToolTipInfo.BackgroundGradientMiddle, _superToolTipInfo.BackgroundGradientEnd, LinearGradientMode.Vertical))
using (LinearGradientBrush b1 = new LinearGradientBrush(new Rectangle(0, 0, Width, Height / 2), _superToolTipInfo.BackgroundGradientBegin, _superToolTipInfo.BackgroundGradientMiddle, LinearGradientMode.Vertical))
{
e.Graphics.FillRectangle(b2, rect1);
e.Graphics.FillRectangle(b1, rect2);
}
}
#endregion
#region Helpers
private void RedrawBackground()
{
}
private void SetHeaderData()
{
lblHeader.Text = _superToolTipInfo.HeaderText;
lblHeader.ForeColor = _superToolTipInfo.HeaderForeColor;
lblHeader.Font = _superToolTipInfo.HeaderFont;
lblHeader.Visible = _superToolTipInfo.ShowHeader;
pnlHeaderSeparator.Invalidate();
pnlHeaderSeparator.Visible = _superToolTipInfo.ShowHeader;
}
private void SetFooterData()
{
lblFooter.Text = _superToolTipInfo.FooterText;
lblFooter.Font = _superToolTipInfo.FooterFont;
lblFooter.ForeColor = _superToolTipInfo.FooterForeColor;
if (_superToolTipInfo.FooterImage != null)
{
picFooter.Image = _superToolTipInfo.FooterImage;
}
pnlFooterSeparator.Invalidate();
flwPnlFooter.Visible = _superToolTipInfo.ShowFooter;
pnlFooterSeparator.Visible = _superToolTipInfo.ShowFooter;
}
private void SetBodyData()
{
lblBody.Text = _superToolTipInfo.BodyText;
lblBody.Font = _superToolTipInfo.BodyFont;
lblBody.ForeColor = _superToolTipInfo.BodyForeColor;
if (_superToolTipInfo.BodyImage != null)
{
picBody.Image = _superToolTipInfo.BodyImage;
int height = _superToolTipInfo.BodyImage.Height * bodyPicWidth / _superToolTipInfo.BodyImage.Width;
picBody.Size = new Size(picBody.Size.Width, height);
}
//jh
lblBody.MaximumSize = new Size(200, 1000);
}
#endregion
private void pnlHeaderSeparator_Paint(object sender, PaintEventArgs e)
{
if (_superToolTipInfo.ShowHeader && _superToolTipInfo.ShowHeaderSeparator)
{
DrawSeparator(e.Graphics, pnlHeaderSeparator);
}
}
private void pnlFooterSeparator_Paint(object sender, PaintEventArgs e)
{
if (_superToolTipInfo.ShowFooter && _superToolTipInfo.ShowFooterSeparator)
{
DrawSeparator(e.Graphics, pnlFooterSeparator);
}
}
private void DrawSeparator(Graphics graphics, Panel p)
{
graphics.DrawLine(Pens.White, new Point(0, p.Height / 2), new Point(p.Width, p.Height / 2));
graphics.DrawLine(Pens.Black, new Point(0, p.Height / 2 + 1), new Point(p.Width, p.Height / 2 + 1));
}
protected override void OnSizeChanged(EventArgs e)
{
pnlHeaderSeparator.Width = this.Width * 95 / 100;
pnlFooterSeparator.Width = this.Width * 95 / 100;
base.OnSizeChanged(e);
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Microsoft.TeamFoundation.TestClient.PublishTestResults;
using Microsoft.VisualStudio.Services.Agent.Worker;
using Microsoft.VisualStudio.Services.Agent.Worker.TestResults;
using Moq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using Xunit;
namespace Microsoft.VisualStudio.Services.Agent.Tests.Worker.TestResults
{
public class ParserTests
{
private Mock<IExecutionContext> _ec;
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "PublishTestResults")]
public void PublishTrxResults()
{
SetupMocks();
String trxContents = "<?xml version = \"1.0\" encoding = \"UTF-8\"?>" +
"<TestRun id = \"ee3d8b3b-1ac9-4a7e-abfa-3d3ed2008613\" name = \"somerandomusername@SOMERANDOMCOMPUTERNAME 2015-03-20 16:53:32\" runUser = \"FAREAST\\somerandomusername\" xmlns =\"http://microsoft.com/schemas/VisualStudio/TeamTest/2010\"><Times creation = \"2015-03-20T16:53:32.3309380+05:30\" queuing = \"2015-03-20T16:53:32.3319381+05:30\" start = \"2015-03-20T16:53:32.3349628+05:30\" finish = \"2015-03-20T16:53:32.9232329+05:30\" />" +
"<TestDefinitions>" +
"<UnitTest name = \"TestMethod2\" storage = \"c:/users/somerandomusername/source/repos/projectx/unittestproject4/unittestproject4/bin/debug/unittestproject4.dll\" priority = \"1\" id = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\"><Owners><Owner name = \"asdf2\" /></Owners><Execution id = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" /><TestMethod codeBase = \"c:/users/somerandomusername/source/repos/projectx/unittestproject4/unittestproject4/bin/debug/unittestproject4.dll\" adapterTypeName = \"Microsoft.VisualStudio.TestTools.TestTypes.Unit.UnitTestAdapter\" className = \"UnitTestProject4.UnitTest1\" name = \"TestMethod2\" /></UnitTest>" +
"<WebTest name=\"PSD_Startseite\" storage=\"c:\\vsoagent\\a284d2cc\\vseqa1\\psd_startseite.webtest\" id=\"01da1a13-b160-4ee6-9d84-7a6dfe37b1d2\" persistedWebTest=\"7\"><TestCategory><TestCategoryItem TestCategory=\"PSD\" /></TestCategory><Execution id=\"eb421c16-4546-435a-9c24-0d2878ea76d4\" /></WebTest>" +
"<OrderedTest name=\"OrderedTest1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\orderedtest1.orderedtest\" id=\"4eb63268-af79-48f1-b625-05ef09b0301a\"><Execution id=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestLinks><TestLink id=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\" name=\"CodedUITestMethod1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" /><TestLink id=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\" name=\"CodedUITestMethod2\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" /></TestLinks></OrderedTest>" +
"<UnitTest name=\"CodedUITestMethod1\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" id=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\"><Execution id=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" parentId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestMethod codeBase=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" adapterTypeName=\"executor://orderedtestadapter/v1\" className=\"CodedUITestProject1.CodedUITest1\" name=\"CodedUITestMethod1\" /></UnitTest>" +
"<UnitTest name=\"CodedUITestMethod2\" storage=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" priority=\"1\" id=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\"><Execution id=\"5918f7d4-4619-4869-b777-71628227c62a\" parentId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" /><TestMethod codeBase=\"c:\\users\\random\\source\\repos\\codeduitestproject1\\codeduitestproject1\\bin\\debug\\codeduitestproject1.dll\" adapterTypeName=\"executor://orderedtestadapter/v1\" className=\"CodedUITestProject1.CodedUITest1\" name=\"CodedUITestMethod2\" /></UnitTest>" +
"</TestDefinitions>" +
"<Results>" +
"<UnitTestResult executionId = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" testId = \"f0d6b58f-dc08-9c0b-aab7-0a1411d4a346\" testName = \"TestMethod2\" computerName = \"SOMERANDOMCOMPUTERNAME\" duration = \"00:00:00.0834563\" startTime = \"2015-03-20T16:53:32.3099353+05:30\" endTime = \"2015-03-20T16:53:32.3939623+05:30\" testType = \"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome = \"Pending\" testListId = \"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory = \"48ec1e47-b9df-43b9-aef2-a2cc8742353d\" ><Output><StdOut>Show console log output.</StdOut><ErrorInfo><Message>Assert.Fail failed.</Message><StackTrace>at UnitTestProject4.UnitTest1.TestMethod2() in C:\\Users\\somerandomusername\\Source\\Repos\\Projectx\\UnitTestProject4\\UnitTestProject4\\UnitTest1.cs:line 21</StackTrace></ErrorInfo></Output>" +
"<ResultFiles><ResultFile path=\"DIGANR-DEV4\\x.txt\" /></ResultFiles>" +
"</UnitTestResult>" +
"<WebTestResult executionId=\"eb421c16-4546-435a-9c24-0d2878ea76d4\" testId=\"01da1a13-b160-4ee6-9d84-7a6dfe37b1d2\" testName=\"PSD_Startseite\" computerName=\"LAB-BUILDVNEXT\" duration=\"00:00:01.6887389\" startTime=\"2015-05-20T18:53:51.1063165+00:00\" endTime=\"2015-05-20T18:54:03.9160742+00:00\" testType=\"4e7599fa-5ecb-43e9-a887-cd63cf72d207\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"eb421c16-4546-435a-9c24-0d2878ea76d4\"><Output><StdOut>Do not show console log output.</StdOut></Output>" +
"<ResultFiles>" +
"<ResultFile path=\"PSD_Startseite.webtestResult\" />" +
"</ResultFiles>" +
"<WebTestResultFilePath>LOCAL SERVICE_LAB-BUILDVNEXT 2015-05-20 18_53_41\\In\\eb421c16-4546-435a-9c24-0d2878ea76d4\\PSD_Startseite.webtestResult</WebTestResultFilePath>" +
"</WebTestResult>" +
"<TestResultAggregation executionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"4eb63268-af79-48f1-b625-05ef09b0301a\" testName=\"OrderedTest1\" computerName=\"random-DT\" duration=\"00:00:01.4031295\" startTime=\"2017-12-14T16:27:24.2216619+05:30\" endTime=\"2017-12-14T16:27:25.6423256+05:30\" testType=\"ec4800e8-40e5-4ab3-8510-b8bf29b1904d\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\">" +
"<InnerResults>" +
"<UnitTestResult executionId=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" parentExecutionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"fd846020-c6f8-3c49-3ed0-fbe1e1fd340b\" testName=\"01- CodedUITestMethod1 (OrderedTest1)\" computerName=\"random-DT\" duration=\"00:00:00.3658086\" startTime=\"2017-12-14T10:57:24.2386920+05:30\" endTime=\"2017-12-14T10:57:25.3440342+05:30\" testType=\"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"4f82d822-cd28-4bcc-b091-b08a66cf92e7\" />" +
"<UnitTestResult executionId=\"5918f7d4-4619-4869-b777-71628227c62a\" parentExecutionId=\"20927d24-2eb4-473f-b5b2-f52667b88f6f\" testId=\"1c7ece84-d949-bed1-0a4c-dfad4f9c953e\" testName=\"02- CodedUITestMethod2 (OrderedTest1)\" computerName=\"random-DT\" duration=\"00:00:00.0448870\" startTime=\"2017-12-14T10:57:25.3480349+05:30\" endTime=\"2017-12-14T10:57:25.3950371+05:30\" testType=\"13cdc9d9-ddb5-4fa4-a97d-d965ccfc6d4b\" outcome=\"Passed\" testListId=\"8c84fa94-04c1-424b-9868-57a2d4851a1d\" relativeResultsDirectory=\"5918f7d4-4619-4869-b777-71628227c62a\" />" +
"</InnerResults>" +
"</TestResultAggregation>" +
"</Results>" +
"<ResultSummary outcome=\"Failed\"><Counters total = \"3\" executed = \"3\" passed=\"2\" failed=\"1\" error=\"0\" timeout=\"0\" aborted=\"0\" inconclusive=\"0\" passedButRunAborted=\"0\" notRunnable=\"0\" notExecuted=\"0\" disconnected=\"0\" warning=\"0\" completed=\"0\" inProgress=\"0\" pending=\"0\" />" +
"</ResultSummary>" +
"</TestRun>";
string resultFile = TestUtil.WriteAllTextToTempFile(trxContents, "trx");
TrxParser reader = new TrxParser();
TestRunContext runContext = new TestRunContext();
TestDataProvider runDataProvider = reader.ParseTestResultFiles(_ec.Object, runContext, new List<string> { resultFile });
List<TestRunData> runData = runDataProvider.GetTestRunData();
Assert.Equal(runData[0].TestResults.Count, 3);
Assert.Equal(runData[0].TestResults[0].Outcome, "NotExecuted");
Assert.Equal(runData[0].TestResults[0].TestCaseTitle, "TestMethod2");
Assert.Equal(runData[0].TestResults[1].Outcome, "Passed");
Assert.Equal(runData[0].TestResults[1].TestCaseTitle, "PSD_Startseite");
Assert.Equal(runData[0].TestResults[2].Outcome, "Passed");
Assert.Equal(runData[0].TestResults[2].TestCaseTitle, "OrderedTest1");
CleanupTempFile(resultFile);
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "PublishTestResults")]
public void PublishNUnitResultFile()
{
SetupMocks();
string nUnitBasicResultsXml =
"<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>" +
"<!--This file represents the results of running a test suite-->" +
"<test-results name=\"C:\\testws\\mghost\\projvc\\TBScoutTest1\\bin\\Debug\\TBScoutTest1.dll\" total=\"3\" errors=\"0\" failures=\"1\" not-run=\"0\" inconclusive=\"0\" ignored=\"0\" skipped=\"0\" invalid=\"0\" date=\"2015-04-15\" time=\"12:25:14\">" +
" <environment nunit-version=\"2.6.4.14350\" clr-version=\"2.0.50727.8009\" os-version=\"Microsoft Windows NT 6.2.9200.0\" platform=\"Win32NT\" cwd=\"D:\\Software\\NUnit-2.6.4\\bin\" machine-name=\"MGHOST\" user=\"madhurig\" user-domain=\"REDMOND\" />" +
" <culture-info current-culture=\"en-US\" current-uiculture=\"en-US\" />" +
" <test-suite type=\"Assembly\" name=\"C:\\testws\\mghost\\projvc\\TBScoutTest1\\bin\\Debug\\TBScoutTest1.dll\" executed=\"True\" result=\"Failure\" success=\"False\" time=\"0.059\" asserts=\"0\">" +
" <results>" +
" <test-suite type=\"Namespace\" name=\"TBScoutTest1\" executed=\"True\" result=\"Failure\" success=\"False\" time=\"0.051\" asserts=\"0\">" +
" <results>" +
" <test-suite type=\"TestFixture\" name=\"ProgramTest1\" executed=\"True\" result=\"Failure\" success=\"False\" time=\"0.050\" asserts=\"0\">" +
" <results>" +
" <test-case name=\"TBScoutTest1.ProgramTest1.MultiplyTest\" executed=\"True\" result=\"Success\" success=\"True\" time=\"-0.027\" asserts=\"1\" />" +
" <test-case name=\"TBScoutTest1.ProgramTest1.SumTest\" executed=\"True\" result=\"Success\" success=\"True\" time=\"0.000\" asserts=\"1\" />" +
" <test-case name=\"TBScoutTest1.ProgramTest1.TestSumWithZeros\" executed=\"True\" result=\"Failure\" success=\"False\" time=\"0.009\" asserts=\"1\">" +
" <failure>" +
" <message><![CDATA[ TBScout.Program.Sum did not return the expected value." +
" Expected: 0" +
" But was: 25" +
"]]></message>" +
" <stack-trace><![CDATA[at TBScoutTest1.ProgramTest1.TestSumWithZeros() in C:\\testws\\mghost\\projvc\\TBScoutTest1\\ProgramTest1.cs:line 63" +
"]]></stack-trace>" +
" </failure>" +
" </test-case>" +
" </results>" +
" </test-suite>" +
" </results>" +
" </test-suite>" +
" </results>" +
" </test-suite>" +
"</test-results>";
string resultFile = TestUtil.WriteAllTextToTempFile(nUnitBasicResultsXml, "xml");
NUnitParser reader = new NUnitParser();
TestRunContext runContext = new TestRunContext();
TestDataProvider runDataProvider = reader.ParseTestResultFiles(_ec.Object, runContext, new List<string> { resultFile });
List<TestRunData> runData = runDataProvider.GetTestRunData();
Assert.NotNull(runData[0].TestResults);
Assert.Equal("C:\\testws\\mghost\\projvc\\TBScoutTest1\\bin\\Debug\\TBScoutTest1.dll", runData[0].RunCreateModel.Name);
Assert.Equal(3, runData[0].TestResults.Count);
Assert.Equal(2, runData[0].TestResults.Count(r => r.Outcome.Equals("Passed")));
Assert.Equal(1, runData[0].TestResults.Count(r => r.Outcome.Equals("Failed")));
Assert.Equal(1, runData[0].AttachmentsFilePathList.Count);
Assert.Equal(null, runData[0].TestResults[0].AutomatedTestId);
Assert.Equal(null, runData[0].TestResults[0].AutomatedTestTypeId);
CleanupTempFile(resultFile);
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "PublishTestResults")]
public void PublishBasicNestedJUnitResults()
{
SetupMocks();
string junitResultsToBeRead = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<testsuites>"
+ "<testsuite name=\"com.contoso.billingservice.ConsoleMessageRendererTest\" errors=\"0\" failures=\"1\" skipped=\"0\" tests=\"2\" time=\"0.006\" timestamp=\"2015-04-06T21:56:24\">"
+ "<testsuite errors=\"0\" failures=\"1\" hostname=\"mghost\" name=\"com.contoso.billingservice.ConsoleMessageRendererTest\" skipped=\"0\" tests=\"2\" time=\"0.006\" timestamp=\"2015-04-06T21:56:24\">"
+ "<testcase classname=\"com.contoso.billingservice.ConsoleMessageRendererTest\" name=\"testRenderNullMessage\" testType=\"asdasdas\" time=\"0.001\" />"
+ "<testcase classname=\"com.contoso.billingservice.ConsoleMessageRendererTest\" name=\"testRenderMessage\" time=\"0.003\">"
+ "<failure type=\"junit.framework.AssertionFailedError\">junit.framework.AssertionFailedError at com.contoso.billingservice.ConsoleMessageRendererTest.testRenderMessage(ConsoleMessageRendererTest.java:11)"
+ "</failure>"
+ "</testcase >"
+ "<system-out><![CDATA[Hello World!]]>"
+ "</system-out>"
+ "<system-err><![CDATA[]]></system-err>"
+ "</testsuite>"
+ "</testsuite>"
+ "</testsuites>";
string resultFile = TestUtil.WriteAllTextToTempFile(junitResultsToBeRead, "xml");
JUnitParser reader = new JUnitParser();
TestRunContext runContext = new TestRunContext();
TestDataProvider runDataProvider = reader.ParseTestResultFiles(_ec.Object, runContext, new List<string> { resultFile });
List<TestRunData> runData = runDataProvider.GetTestRunData();
Assert.NotNull(runData[0].TestResults);
Assert.Equal(2, runData[0].TestResults.Count);
Assert.Equal(1, runData[0].TestResults.Count(r => r.Outcome.Equals("Passed")));
Assert.Equal(null, runData[0].TestResults[0].AutomatedTestId);
Assert.Equal(null, runData[0].TestResults[0].AutomatedTestTypeId);
Assert.Equal(1, runData[0].TestResults.Count(r => r.Outcome.Equals("Failed")));
Assert.Equal("com.contoso.billingservice.ConsoleMessageRendererTest", runData[0].RunCreateModel.Name);
CleanupTempFile(resultFile);
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "PublishTestResults")]
public void PublishBasicXUnitResults()
{
SetupMocks();
string xunitResultsToBeRead = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<assemblies>" +
"<assembly name = \"C:\\Users\\somerandomusername\\Source\\Workspaces\\p1\\ClassLibrary2\\ClassLibrary2\\bin\\Debug\\ClassLibrary2.DLL\">" +
"<class name=\"MyFirstUnitTests.Class1\">" +
"<test name=\"MyFirstUnitTests.Class1.FailingTest\">" +
"</test>" +
"</class>" +
"</assembly>" +
"</assemblies>";
string resultFile = TestUtil.WriteAllTextToTempFile(xunitResultsToBeRead, "xml");
JUnitParser reader = new JUnitParser();
TestRunContext runContext = new TestRunContext();
TestDataProvider runDataProvider = reader.ParseTestResultFiles(_ec.Object, runContext, new List<string> { resultFile });
List<TestRunData> runData = runDataProvider.GetTestRunData();
Assert.Equal(1, runData[0].AttachmentsFilePathList.Count);
CleanupTempFile(resultFile);
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "PublishTestResults")]
public void PublishBasicCTestResults()
{
SetupMocks();
string cTestResultsToBeRead = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<Site BuildName=\"(empty)\" BuildStamp=\"20180515-1731-Experimental\" Name=\"(empty)\" Generator=\"ctest-3.11.0\" "
+ "CompilerName=\"\" CompilerVersion=\"\" OSName=\"Linux\" Hostname=\"3tnavBuild\" OSRelease=\"4.4.0-116-generic\" "
+ "OSVersion=\"#140-Ubuntu SMP Mon Feb 12 21:23:04 UTC 2018\" OSPlatform=\"x86_64\" Is64Bits=\"1\">"
+ "<Testing>"
+ "<StartDateTime>May 15 10:31 PDT</StartDateTime>"
+ "<StartTestTime>1526405497</StartTestTime>"
+ "<TestList>"
+ "<Test>./libs/MgmtVisualization/tests/LoggingSinkRandomTests.loggingSinkRandomTest_CallLoggingManagerCallback</Test>"
+ "<Test>./tools/simulator/test/simulator.SimulatorTest.readEventFile_mediaDetectedEvent_oneSignalEmitted</Test>"
+ "</TestList>"
+ "<Test Status =\"passed\">"
+ "<Name>LoggingSinkRandomTests.loggingSinkRandomTest_CallLoggingManagerCallback</Name>"
+ "<Path>./libs/MgmtVisualization/tests</Path>"
+ "<FullName>./libs/MgmtVisualization/tests/LoggingSinkRandomTests.loggingSinkRandomTest_CallLoggingManagerCallback</FullName>"
+ "<FullCommandLine>D:/a/r1/a/libs/MgmtVisualization/tests/MgmtVisualizationResultsAPI \"--gtest_filter=LoggingSinkRandomTests.loggingSinkRandomTest_CallLoggingManagerCallback\"</FullCommandLine>"
+ "<Results>"
+ "<NamedMeasurement type =\"numeric/double\" name=\"Execution Time\">"
+ "<Value>0.074303</Value>"
+ "</NamedMeasurement>"
+ "<NamedMeasurement type =\"numeric/double\" name=\"Processors\">"
+ "<Value>1</Value>"
+ "</NamedMeasurement>"
+ "<NamedMeasurement type =\"text/string\" name=\"Completion Status\">"
+ "<Value>Completed</Value>"
+ "</NamedMeasurement>"
+ "<NamedMeasurement type =\"text/string\" name=\"Command Line\">"
+ "<Value>/home/ctc/jenkins/workspace/build_TNAV-dev_Pull-Request/build/libs/MgmtVisualization/tests/MgmtVisualizationTestPublicAPI \"--gtest_filter=loggingSinkRandomTests.loggingSinkRandomTest_CallLoggingCallback\"</Value>"
+ "</NamedMeasurement>"
+ "<Measurement>"
+ "<Value>output : [----------] Global test environment set-up.</Value>"
+ "</Measurement>"
+ "</Results>"
+ "</Test>"
+ "<Test Status =\"notrun\">"
+ "<Name>simulator.SimulatorTest.readEventFile_mediaDetectedEvent_oneSignalEmitted</Name>"
+ "<Path>./tools/simulator/test</Path>"
+ "<FullName>./tools/simulator/test/simulator.SimulatorTest.readEventFile_mediaDetectedEvent_oneSignalEmitted</FullName>"
+ "<FullCommandLine></FullCommandLine>"
+ "<Results>"
+ "<NamedMeasurement type =\"numeric/double\" name=\"Processors\">"
+ "<Value>1</Value>"
+ "</NamedMeasurement>"
+ "<NamedMeasurement type =\"text/string\" name=\"Completion Status\">"
+ "<Value>Disabled</Value>"
+ "</NamedMeasurement>"
+ "<NamedMeasurement type =\"text/string\" name=\"Command Line\">"
+ "<Value></Value>"
+ "</NamedMeasurement>"
+ "<Measurement>"
+ "<Value>Disabled</Value>"
+ "</Measurement>"
+ "</Results>"
+ "</Test>"
+ "<Test Status=\"passed\">"
+ "<Name>test_cgreen_run_named_test</Name>"
+ "<Path>./tests</Path>"
+ "<FullName>./tests/test_cgreen_run_named_test</FullName>"
+ "<FullCommandLine>/var/lib/jenkins/workspace/Cgreen-thoni56/build/build-c/tests/test_cgreen_c "integer_one_should_assert_true"</FullCommandLine>"
+ "<Results>"
+ "<NamedMeasurement type=\"numeric/double\" name=\"Execution Time\"><Value>0.00615707</Value></NamedMeasurement>"
+ "<NamedMeasurement type=\"text/string\" name=\"Completion Status\"><Value>Completed</Value></NamedMeasurement>"
+ "<NamedMeasurement type=\"text/string\" name=\"Command Line\"><Value>/var/lib/jenkins/workspace/Cgreen-thoni56/build/build-c/tests/test_cgreen_c "integer_one_should_assert_true"</Value></NamedMeasurement>"
+ "<Measurement>"
+ "<Value>Running "all_c_tests" (136 tests)..."
+ "Completed "assertion_tests": 1 pass, 0 failures, 0 exceptions in 0ms."
+ "Completed "all_c_tests": 1 pass, 0 failures, 0 exceptions in 0ms."
+ "</Value>"
+ "</Measurement>"
+ "</Results>"
+ "</Test>"
+ "<Test Status=\"passed\">"
+ "<Name>runner_test_cgreen_c</Name>"
+ "<Path>./tests</Path>"
+ "<FullName>./tests/runner_test_cgreen_c</FullName>"
+ "<FullCommandLine>D:/a/r1/a/Cgreen-thoni56/build/build-c/tools/cgreen-runner "-x" "TEST" "libcgreen_c_tests.so"</FullCommandLine>"
+ "<Results>"
+ "<NamedMeasurement type=\"numeric/double\" name=\"Execution Time\"><Value>0.499399</Value></NamedMeasurement>"
+ "<NamedMeasurement type=\"text/string\" name=\"Completion Status\"><Value>Completed</Value></NamedMeasurement>"
+ "<NamedMeasurement type=\"text/string\" name=\"Command Line\"><Value>/var/lib/jenkins/workspace/Cgreen-thoni56/build/build-c/tools/cgreen-runner "-x" "TEST" "libcgreen_c_tests.so"</Value></NamedMeasurement>"
+ "<Measurement>"
+ "<Value> CGREEN EXCEPTION: Too many assertions within a single test."
+ "</Value>"
+ "</Measurement>"
+ "</Results>"
+ "</Test>"
+ "<Test Status=\"failed\">"
+ "<Name>WGET-testU-MD5-fail</Name>"
+ "<Path>E_/foo/sources</Path>"
+ "<FullName>E_/foo/sources/WGET-testU-MD5-fail</FullName>"
+ "<FullCommandLine>E:\\Tools\\cmake\\cmake-2.8.11-rc4-win32-x86\\bin\\cmake.exe "-DTEST_OUTPUT_DIR:PATH=E:/foo/build-vs2008-visual/_cmake/modules/testU_WGET""
+ ""-P" "E:/foo/sources/modules/testU/WGET-testU-MD5-fail.cmake"</FullCommandLine>"
+ "<Results>"
+ "<NamedMeasurement type=\"text/string\" name=\"Exit Code\">"
+ "<Value>Failed</Value>"
+ "</NamedMeasurement>"
+ "<NamedMeasurement type=\"text/string\" name=\"Exit Value\">"
+ "<Value>0</Value>"
+ "</NamedMeasurement>"
+ "<NamedMeasurement type=\"numeric/double\" name=\"Execution Time\">"
+ "<Value>0.0760078</Value>"
+ "</NamedMeasurement>"
+ "<NamedMeasurement type=\"text/string\" name=\"Completion Status\">"
+ "<Value>Completed</Value>"
+ "</NamedMeasurement>"
+ "<NamedMeasurement type=\"text/string\" name=\"Command Line\">"
+ "<Value>E:\\Tools\\cmake\\cmake-2.8.11-rc4-win32-x86\\bin\\cmake.exe "-DTEST_OUTPUT_DIR:PATH=E:/foo/build-vs2008-visual/_cmake/modules/testU_WGET""
+ ""-P" "E:/foo/sources/modules/testU/WGET-testU-MD5-fail.cmake"</Value>"
+ "</NamedMeasurement>"
+ "<Measurement>"
+ "<Value>-- Download of file://\\abc-mang.md5.txt"
+ "failed with message: [37]"couldn't read a file:// file""
+ "</Value>"
+ "</Measurement>"
+ "</Results>"
+ "</Test>"
+ "<Test Status=\"failed\">"
+ "<Name>WGET-testU-noMD5</Name>"
+ "<Path>E_/foo/sources</Path>"
+ "<FullName>E_/foo/sources/WGET-testU-noMD5</FullName>"
+ "<FullCommandLine>E:\\Tools\\cmake\\cmake-2.8.11-rc4-win32-x86\\bin\\cmake.exe "-DTEST_OUTPUT_DIR:PATH=E:/foo/build-vs2008-visual/_cmake/modules/testU_WGET""
+ ""-P" "E:/foo/sources/modules/testU/WGET-testU-noMD5.cmake"</FullCommandLine>"
+ "<Results>"
+ "<NamedMeasurement type=\"text/string\" name=\"Exit Code\">"
+ "<Value>Failed</Value>"
+ "</NamedMeasurement>"
+ "<NamedMeasurement type=\"text/string\" name=\"Exit Value\">"
+ "<Value>1</Value>"
+ "</NamedMeasurement>"
+ "<NamedMeasurement type=\"numeric/double\" name=\"Execution Time\">"
+ "<Value>0.0820084</Value>"
+ "</NamedMeasurement>"
+ "<NamedMeasurement type=\"text/string\" name=\"Completion Status\">"
+ "<Value>Completed</Value>"
+ "</NamedMeasurement>"
+ "<NamedMeasurement type=\"text/string\" name=\"Command Line\">"
+ "<Value>E:\\Tools\\cmake\\cmake-2.8.11-rc4-win32-x86\\bin\\cmake.exe "-DTEST_OUTPUT_DIR:PATH=E:/foo/build-vs2008-visual/_cmake/modules/testU_WGET""
+ ""-P" "E:/foo/sources/modules/testU/WGET-testU-noMD5.cmake"</Value>"
+ "</NamedMeasurement>"
+ "<Measurement>"
+ "<Value>-- Download of file://\\abc-mang.md5.txt"
+ "failed with message: [37]"couldn't read a file:// file""
+ "CMake Error at modules/Logging.cmake:121 (message):"
+ ""
+ ""
+ "test BAR_wget_file succeed: result is "OFF" instead of "ON""
+ ""
+ "Call Stack (most recent call first):"
+ "modules/Test.cmake:74 (BAR_msg_fatal)"
+ "modules/testU/WGET-testU-noMD5.cmake:14 (BAR_check_equal)"
+ ""
+ ""
+ "</Value>"
+ "</Measurement>"
+ "</Results>"
+ "</Test>"
+ "<EndDateTime>May 15 10:37 PDT</EndDateTime>"
+ "<EndTestTime>1526405879</EndTestTime>"
+ "<ElapsedMinutes>6</ElapsedMinutes>"
+ "</Testing>"
+ "</Site>";
string resultFile = TestUtil.WriteAllTextToTempFile(cTestResultsToBeRead, "xml");
CTestParser reader = new CTestParser();
TestRunContext runContext = new TestRunContext();
TestDataProvider runDataProvider = reader.ParseTestResultFiles(_ec.Object, runContext, new List<string> { resultFile });
List<TestRunData> runData = runDataProvider.GetTestRunData();
Assert.NotNull(runData[0].TestResults);
Assert.Equal(6, runData[0].TestResults.Count);
Assert.Equal(3, runData[0].TestResults.Count(r => r.Outcome.Equals("Passed")));
Assert.Equal(2, runData[0].TestResults.Count(r => r.Outcome.Equals("Failed")));
Assert.Equal(1, runData[0].TestResults.Count(r => r.Outcome.Equals("NotExecuted")));
Assert.Equal("CTest Test Run ", runData[0].RunCreateModel.Name);
Assert.Equal("Completed", runData[0].TestResults[0].State);
Assert.Equal("./libs/MgmtVisualization/tests/LoggingSinkRandomTests.loggingSinkRandomTest_CallLoggingManagerCallback", runData[0].TestResults[0].AutomatedTestName);
Assert.Equal("./libs/MgmtVisualization/tests", runData[0].TestResults[0].AutomatedTestStorage);
Assert.Equal("LoggingSinkRandomTests.loggingSinkRandomTest_CallLoggingManagerCallback", runData[0].TestResults[0].TestCaseTitle);
Assert.Equal(null, runData[0].TestResults[0].AutomatedTestId);
Assert.Equal(null, runData[0].TestResults[0].AutomatedTestTypeId);
CleanupTempFile(resultFile);
}
private void CleanupTempFile(string resultFile)
{
try
{
File.Delete(resultFile);
}
catch
{
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA2000:Dispose objects before losing scope", MessageId = "TestHostContext")]
private void SetupMocks([CallerMemberName] string name = "")
{
TestHostContext hc = new TestHostContext(this, name);
_ec = new Mock<IExecutionContext>();
List<string> warnings;
var variables = new Variables(hc, new Dictionary<string, VariableValue>(), out warnings);
_ec.Setup(x => x.Variables).Returns(variables);
_ec.Setup(x => x.Write(It.IsAny<string>(), It.IsAny<string>()))
.Callback<string, string>
((tag, message) =>
{
Console.Error.WriteLine(tag + ": " + message);
});
}
}
}
| |
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 BarUTomaREST.Areas.HelpPage.ModelDescriptions;
using BarUTomaREST.Areas.HelpPage.Models;
namespace BarUTomaREST.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);
}
}
}
}
| |
using System;
using System.Runtime.InteropServices;
public class Helper
{
#region methods for InnerSequential struct
// Return new InnerSequential instance
public static InnerSequential NewInnerSequential(int f1, float f2, string f3)
{
InnerSequential inner_seq = new InnerSequential();
inner_seq.f1 = f1;
inner_seq.f2 = f2;
inner_seq.f3 = f3;
return inner_seq;
}
// Prints InnerSequential
public static void PrintInnerSequential(InnerSequential inner_seq, string name)
{
Console.WriteLine("\t{0}.f1 = {1}", name, inner_seq.f1);
Console.WriteLine("\t{0}.f2 = {1}", name, inner_seq.f2);
Console.WriteLine("\t{0}.f3 = {1}", name, inner_seq.f3);
}
public static bool ValidateInnerSequential(InnerSequential s1, InnerSequential s2, string methodName)
{
if (s1.f1 != s2.f1 || s1.f2 != s2.f2 || s1.f3 != s2.f3)
{
Console.WriteLine("\tFAILED! " + methodName + "did not receive result as expected.");
Console.WriteLine("\tThe Actual is...");
PrintInnerSequential(s1, s1.ToString());
Console.WriteLine("\tThe Expected is...");
PrintInnerSequential(s2, s2.ToString());
return false;
}
else
{
Console.WriteLine("\tPASSED!");
return true;
}
}
#endregion
#region methods for INNER2 struct
// Return new INNER2 instance
public static INNER2 NewINNER2(int f1, float f2, string f3)
{
INNER2 inner = new INNER2();
inner.f1 = f1;
inner.f2 = f2;
inner.f3 = f3;
return inner;
}
// Prints INNER2
public static void PrintINNER2(INNER2 inner, string name)
{
Console.WriteLine("\t{0}.f1 = {1}", name, inner.f1);
Console.WriteLine("\t{0}.f2 = {1}", name, inner.f2);
Console.WriteLine("\t{0}.f3 = {1}", name, inner.f3);
}
public static bool ValidateINNER2(INNER2 inner1, INNER2 inner2, string methodName)
{
if (inner1.f1 != inner2.f1 || inner1.f2 != inner2.f2 || inner1.f3 != inner2.f3)
{
Console.WriteLine("\tFAILED! " + methodName + "did not receive result as expected.");
Console.WriteLine("\tThe Actual is...");
PrintINNER2(inner1, inner1.ToString());
Console.WriteLine("\tThe Expected is...");
PrintINNER2(inner2, inner2.ToString());
return false;
}
else
{
Console.WriteLine("\tPASSED!");
return true;
}
}
#endregion
#region methods for InnerExplicit struct
// Return new InnerExplicit instance
public static InnerExplicit NewInnerExplicit(int f1, float f2, string f3)
{
InnerExplicit inner = new InnerExplicit();
inner.f1 = f1;
inner.f2 = f2;
inner.f3 = f3;
return inner;
}
// Prints InnerExplicit
public static void PrintInnerExplicit(InnerExplicit inner, string name)
{
Console.WriteLine("\t{0}.f1 = {1}", name, inner.f1);
Console.WriteLine("\t{0}.f2 = {1}", name, inner.f2);
Console.WriteLine("\t{0}.f3 = {1}", name, inner.f3);
}
public static bool ValidateInnerExplicit(InnerExplicit inner1, InnerExplicit inner2, string methodName)
{
if (inner1.f1 != inner2.f1 || inner1.f2 != inner2.f2 || inner1.f3 != inner2.f3)
{
Console.WriteLine("\tFAILED! " + methodName + "did not receive result as expected.");
Console.WriteLine("\tThe Actual is...");
PrintInnerExplicit(inner1, inner1.ToString());
Console.WriteLine("\tThe Expected is...");
PrintInnerExplicit(inner2, inner2.ToString());
return false;
}
else
{
Console.WriteLine("\tPASSED!");
return true;
}
}
#endregion
#region methods for InnerArraySequential struct
// Returns new OUTER instance; the params are the fields of INNER;
// all the INNER elements have the same field values
public static InnerArraySequential NewInnerArraySequential(int f1, float f2, string f3)
{
InnerArraySequential outer = new InnerArraySequential();
outer.arr = new InnerSequential[Common.NumArrElements];
for (int i = 0; i < Common.NumArrElements; i++)
{
outer.arr[i].f1 = f1;
outer.arr[i].f2 = f2;
outer.arr[i].f3 = f3;
}
return outer;
}
// Prints InnerArraySequential
public static void PrintInnerArraySequential(InnerArraySequential outer, string name)
{
for (int i = 0; i < Common.NumArrElements; i++)
{
Console.WriteLine("\t{0}.arr[{1}].f1 = {2}", name, i, outer.arr[i].f1);
Console.WriteLine("\t{0}.arr[{1}].f2 = {2}", name, i, outer.arr[i].f2);
Console.WriteLine("\t{0}.arr[{1}].f3 = {2}", name, i, outer.arr[i].f3);
}
}
// Returns true if the two params have the same fields
public static bool ValidateInnerArraySequential(InnerArraySequential outer1, InnerArraySequential outer2, string methodName)
{
for (int i = 0; i < Common.NumArrElements; i++)
{
if (outer1.arr[i].f1 != outer2.arr[i].f1 ||
outer1.arr[i].f2 != outer2.arr[i].f2 ||
outer1.arr[i].f3 != outer2.arr[i].f3)
{
Console.WriteLine("\tFAILED! " + methodName + "did not receive result as expected.");
Console.WriteLine("\tThe Actual is...");
Console.WriteLine("\t{0}.arr[{1}].f1 = {2}", outer1.ToString(), i, outer1.arr[i].f1);
Console.WriteLine("\t{0}.arr[{1}].f2 = {2}", outer1.ToString(), i, outer1.arr[i].f2);
Console.WriteLine("\t{0}.arr[{1}].f3 = {2}", outer1.ToString(), i, outer1.arr[i].f3);
Console.WriteLine("\tThe Expected is...");
Console.WriteLine("\t{0}.arr[{1}].f1 = {2}", outer2.ToString(), i, outer2.arr[i].f1);
Console.WriteLine("\t{0}.arr[{1}].f2 = {2}", outer2.ToString(), i, outer2.arr[i].f2);
Console.WriteLine("\t{0}.arr[{1}].f3 = {2}", outer2.ToString(), i, outer2.arr[i].f3);
return false;
}
}
Console.WriteLine("\tPASSED!");
return true;
}
#endregion
#region methods for InnerArrayExplicit struct
// Returns new InnerArrayExplicit instance; the params are the fields of INNER;
// all the INNER elements have the same field values
public static InnerArrayExplicit NewInnerArrayExplicit(int f1, float f2, string f3, string f4)
{
InnerArrayExplicit outer = new InnerArrayExplicit();
outer.arr = new InnerSequential[Common.NumArrElements];
for (int i = 0; i < Common.NumArrElements; i++)
{
outer.arr[i].f1 = f1;
outer.arr[i].f2 = f2;
outer.arr[i].f3 = f3;
}
outer.f4 = f4;
return outer;
}
// Prints InnerArrayExplicit
public static void PrintInnerArrayExplicit(InnerArrayExplicit outer, string name)
{
for (int i = 0; i < Common.NumArrElements; i++)
{
Console.WriteLine("\t{0}.arr[{1}].f1 = {2}", name, i, outer.arr[i].f1);
Console.WriteLine("\t{0}.arr[{1}].f2 = {2}", name, i, outer.arr[i].f2);
Console.WriteLine("\t{0}.arr[{1}].f3 = {2}", name, i, outer.arr[i].f3);
}
Console.WriteLine("\t{0}.f4 = {1}", name, outer.f4);
}
// Returns true if the two params have the same fields
public static bool ValidateInnerArrayExplicit(InnerArrayExplicit outer1, InnerArrayExplicit InnerArrayExplicit, string methodName)
{
for (int i = 0; i < Common.NumArrElements; i++)
{
if (outer1.arr[i].f1 != InnerArrayExplicit.arr[i].f1)
{
Console.WriteLine("\tFAILED! " + methodName + "did not receive result as expected.");
Console.WriteLine("\tThe Actual f1 field is...");
Console.WriteLine("\t{0}.arr[{1}].f1 = {2}", outer1.ToString(), i, outer1.arr[i].f1);
Console.WriteLine("\tThe Expected f1 field is...");
Console.WriteLine("\t{0}.arr[{1}].f1 = {2}", InnerArrayExplicit.ToString(), i, InnerArrayExplicit.arr[i].f1);
return false;
}
}
if (outer1.f4 != InnerArrayExplicit.f4)
{
Console.WriteLine("\tFAILED! " + methodName + "did not receive result as expected.");
Console.WriteLine("\tThe Actual f4 field is...");
Console.WriteLine("\t{0}.f4 = {1}", outer1.ToString(), outer1.f4);
Console.WriteLine("\tThe Expected f4 field is...");
Console.WriteLine("\t{0}.f4 = {1}", InnerArrayExplicit.ToString(), InnerArrayExplicit.f4);
return false;
}
Console.WriteLine("\tPASSED!");
return true;
}
#endregion
#region methods for OUTER3 struct
// Returns new OUTER3 instance; the params are the fields of INNER;
// all the INNER elements have the same field values
public static OUTER3 NewOUTER3(int f1, float f2, string f3, string f4)
{
OUTER3 outer = new OUTER3();
outer.arr = new InnerSequential[Common.NumArrElements];
for (int i = 0; i < Common.NumArrElements; i++)
{
outer.arr[i].f1 = f1;
outer.arr[i].f2 = f2;
outer.arr[i].f3 = f3;
}
outer.f4 = f4;
return outer;
}
// Prints OUTER3
public static void PrintOUTER3(OUTER3 outer, string name)
{
for (int i = 0; i < Common.NumArrElements; i++)
{
Console.WriteLine("\t{0}.arr[{1}].f1 = {2}", name, i, outer.arr[i].f1);
Console.WriteLine("\t{0}.arr[{1}].f2 = {2}", name, i, outer.arr[i].f2);
Console.WriteLine("\t{0}.arr[{1}].f3 = {2}", name, i, outer.arr[i].f3);
}
Console.WriteLine("\t{0}.f4 = {1}", name, outer.f4);
}
// Returns true if the two params have the same fields
public static bool ValidateOUTER3(OUTER3 outer1, OUTER3 InnerArrayExplicit, string methodName)
{
for (int i = 0; i < Common.NumArrElements; i++)
{
if (outer1.arr[i].f1 != InnerArrayExplicit.arr[i].f1 ||
outer1.arr[i].f2 != InnerArrayExplicit.arr[i].f2 ||
outer1.arr[i].f3 != InnerArrayExplicit.arr[i].f3)
{
Console.WriteLine("\tFAILED! " + methodName + "did not receive result as expected.");
Console.WriteLine("\tThe Actual is...");
Console.WriteLine("\t{0}.arr[{1}].f1 = {2}", outer1.ToString(), i, outer1.arr[i].f1);
Console.WriteLine("\t{0}.arr[{1}].f2 = {2}", outer1.ToString(), i, outer1.arr[i].f2);
Console.WriteLine("\t{0}.arr[{1}].f3 = {2}", outer1.ToString(), i, outer1.arr[i].f3);
Console.WriteLine("\tThe Expected is...");
Console.WriteLine("\t{0}.arr[{1}].f1 = {2}", InnerArrayExplicit.ToString(), i, InnerArrayExplicit.arr[i].f1);
Console.WriteLine("\t{0}.arr[{1}].f2 = {2}", InnerArrayExplicit.ToString(), i, InnerArrayExplicit.arr[i].f2);
Console.WriteLine("\t{0}.arr[{1}].f3 = {2}", InnerArrayExplicit.ToString(), i, InnerArrayExplicit.arr[i].f3);
return false;
}
}
if (outer1.f4 != InnerArrayExplicit.f4)
{
Console.WriteLine("\tFAILED! " + methodName + "did not receive result as expected.");
Console.WriteLine("\tThe Actual f4 field is...");
Console.WriteLine("\t{0}.f4 = {1}", outer1.ToString(), outer1.f4);
Console.WriteLine("\tThe Expected f4 field is...");
Console.WriteLine("\t{0}.f4 = {1}", InnerArrayExplicit.ToString(), InnerArrayExplicit.f4);
return false;
}
Console.WriteLine("\tPASSED!");
return true;
}
#endregion
#region methods for CharSetAnsiSequential struct
//return CharSetAnsiSequential struct instance
public static CharSetAnsiSequential NewCharSetAnsiSequential(string f1, char f2)
{
CharSetAnsiSequential str1 = new CharSetAnsiSequential();
str1.f1 = f1;
str1.f2 = f2;
return str1;
}
//print the struct CharSetAnsiSequential element
public static void PrintCharSetAnsiSequential(CharSetAnsiSequential str1, string name)
{
Console.WriteLine("\t{0}.f1 = {1}", name, str1.f1);
Console.WriteLine("\t{0}.f2 = {1}", name, str1.f2);
}
// Returns true if the two params have the same fields
public static bool ValidateCharSetAnsiSequential(CharSetAnsiSequential str1, CharSetAnsiSequential str2, string methodName)
{
if (str1.f1 != str2.f1 || str1.f2 != str2.f2)
{
Console.WriteLine("\tFAILED! " + methodName + "did not receive result as expected.");
Console.WriteLine("\tThe Actual is...");
PrintCharSetAnsiSequential(str1, str1.ToString());
Console.WriteLine("\tThe Expected is...");
PrintCharSetAnsiSequential(str2, str2.ToString());
return false;
}
else
{
Console.WriteLine("\tPASSED!");
return true;
}
}
#endregion
#region methods for CharSetUnicodeSequential struct
//return the struct CharSetUnicodeSequential instance
public static CharSetUnicodeSequential NewCharSetUnicodeSequential(string f1, char f2)
{
CharSetUnicodeSequential str1 = new CharSetUnicodeSequential();
str1.f1 = f1;
str1.f2 = f2;
return str1;
}
//print the struct CharSetUnicodeSequential element
public static void PrintCharSetUnicodeSequential(CharSetUnicodeSequential str1, string name)
{
Console.WriteLine("\t{0}.f1 = {1}", name, str1.f1);
Console.WriteLine("\t{0}.f2 = {1}", name, str1.f2);
}
// Returns true if the two params have the same fields
public static bool ValidateCharSetUnicodeSequential(CharSetUnicodeSequential str1, CharSetUnicodeSequential str2, string methodName)
{
if (str1.f1 != str2.f1 || str1.f2 != str2.f2)
{
Console.WriteLine("\tFAILED! " + methodName + "did not receive result as expected.");
Console.WriteLine("\tThe Actual is...");
PrintCharSetUnicodeSequential(str1, str1.ToString());
Console.WriteLine("\tThe Expected is...");
PrintCharSetUnicodeSequential(str2, str2.ToString());
return false;
}
else
{
Console.WriteLine("\tPASSED!");
return true;
}
}
#endregion
#region methods for NumberSequential struct
public static NumberSequential NewNumberSequential(int i32, uint ui32, short s1, ushort us1, Byte b, SByte sb,
Int16 i16, UInt16 ui16, Int64 i64, UInt64 ui64, Single sgl, Double d)
{
NumberSequential str1 = new NumberSequential();
str1.i32 = i32;
str1.ui32 = ui32;
str1.s1 = s1;
str1.us1 = us1;
str1.b = b;
str1.sb = sb;
str1.i16 = i16;
str1.ui16 = ui16;
str1.i64 = i64;
str1.ui64 = ui64;
str1.sgl = sgl;
str1.d = d;
return str1;
}
public static void PrintNumberSequential(NumberSequential str1, string name)
{
Console.WriteLine("\t{0}.i32 = {1}", name, str1.i32);
Console.WriteLine("\t{0}.ui32 = {1}", name, str1.ui32);
Console.WriteLine("\t{0}.s1 = {1}", name, str1.s1);
Console.WriteLine("\t{0}.us1 = {1}", name, str1.us1);
Console.WriteLine("\t{0}.b = {1}", name, str1.b);
Console.WriteLine("\t{0}.sb = {1}", name, str1.sb);
Console.WriteLine("\t{0}.i16 = {1}", name, str1.i16);
Console.WriteLine("\t{0}.ui16 = {1}", name, str1.ui16);
Console.WriteLine("\t{0}.i64 = {1}", name, str1.i64);
Console.WriteLine("\t{0}.ui64 = {1}", name, str1.ui64);
Console.WriteLine("\t{0}.sgl = {1}", name, str1.sgl);
Console.WriteLine("\t{0}.d = {1}", name, str1.d);
}
public static bool ValidateNumberSequential(NumberSequential str1, NumberSequential str2, string methodName)
{
if (str1.i32 != str2.i32 || str1.ui32 != str2.ui32 || str1.s1 != str2.s1 ||
str1.us1 != str2.us1 || str1.b != str2.b || str1.sb != str2.sb || str1.i16 != str2.i16 ||
str1.ui16 != str2.ui16 || str1.i64 != str2.i64 || str1.ui64 != str2.ui64 ||
str1.sgl != str2.sgl || str1.d != str2.d)
{
Console.WriteLine("\tFAILED! " + methodName + "did not receive result as expected.");
Console.WriteLine("\tThe Actual is...");
PrintNumberSequential(str1, str1.ToString());
Console.WriteLine("\tThe Expected is...");
PrintNumberSequential(str2, str2.ToString());
return false;
}
else
{
Console.WriteLine("\tPASSED!");
return true;
}
}
#endregion
#region methods for S3 struct
public static void InitialArray(int[] iarr, int[] icarr)
{
for (int i = 0; i < iarr.Length; i++)
{
iarr[i] = i;
}
for (int i = 1; i < icarr.Length + 1; i++)
{
icarr[i - 1] = i;
}
}
public static S3 NewS3(bool flag, string str, int[] vals)
{
S3 str1 = new S3();
str1.flag = flag;
str1.str = str;
str1.vals = vals;
return str1;
}
public static void PrintS3(S3 str1, string name)
{
Console.WriteLine("\t{0}.flag = {1}", name, str1.flag);
Console.WriteLine("\t{0}.flag = {1}", name, str1.str);
for (int i = 0; i < str1.vals.Length; i++)
{
Console.WriteLine("\t{0}.vals[{1}] = {2}", name, i, str1.vals[i]);
}
}
public static bool ValidateS3(S3 str1, S3 str2, string methodName)
{
int iflag = 0;
if (str1.flag != str2.flag || str1.str != str2.str)
{
Console.WriteLine("\tFAILED! " + methodName + "did not receive result as expected.");
Console.WriteLine("\tThe Actual flag field is...");
Console.WriteLine("\t{0}.flag = {1}", str1.ToString(), str1.flag);
Console.WriteLine("\t{0}.str = {1}", str1.ToString(), str1.str);
Console.WriteLine("\tThe Expected is...");
Console.WriteLine("\t{0}.flag = {1}", str2.ToString(), str2.flag);
Console.WriteLine("\t{0}.str = {1}", str2.ToString(), str2.str);
return false;
}
for (int i = 0; i < 256; i++)
{
if (str1.vals[i] != str2.vals[i])
{
Console.WriteLine("\tFAILED! " + methodName + "did not receive result as expected.");
Console.WriteLine("\tThe Actual vals field is...");
Console.WriteLine("\t{0}.vals[{1}] = {2}", str1.ToString(), i, str1.vals[i]);
Console.WriteLine("\tThe Expected vals field is...");
Console.WriteLine("\t{0}.vals[{1}] = {2}", str2.ToString(), i, str2.vals[i]);
iflag++;
}
}
if (iflag != 0)
{
return false;
}
Console.WriteLine("\tPASSED!");
return true;
}
#endregion
#region methods for S5 struct
public static S5 NewS5(int age, string name,Enum1 ef)
{
S4 s4 = new S4();
s4.age = age;
s4.name = name;
S5 s5 = new S5();
s5.s4 = s4;
s5.ef = ef;
return s5;
}
public static void PrintS5(S5 str1, string name)
{
Console.WriteLine("\t{0}.s4.age = {1}", str1.s4.age);
Console.WriteLine("\t{0}.s4.name = {1}", str1.s4.name);
Console.WriteLine("\t{0}.ef = {1}", str1.ef.ToString());
}
public static bool ValidateS5(S5 str1, S5 str2, string methodName)
{
if (str1.s4.age != str2.s4.age || str1.s4.name != str2.s4.name)
{
Console.WriteLine("\tFAILED! " + methodName + "did not receive result as expected.");
Console.WriteLine("\tThe Actual s4 field is...");
Console.WriteLine("\t{0}.s4.age = {1}", str1.ToString(), str1.s4.age);
Console.WriteLine("\t{0}.s4.name = {1}", str1.ToString(), str1.s4.name);
Console.WriteLine("\tThe Expected s4 field is...");
Console.WriteLine("\t{0}.s4.age = {1}", str2.ToString(), str2.s4.age);
Console.WriteLine("\t{0}.s4.name = {1}", str2.ToString(), str2.s4.name);
return false;
}
if (str1.ef != str2.ef)
{
Console.WriteLine("\tFAILED! " + methodName + "did not receive result as expected.");
Console.WriteLine("\tThe Actual ef field is...");
Console.WriteLine("\t{0}.ef = {1}", str1.ToString(), str1.ef);
Console.WriteLine("\tThe Expected s4 field is...");
Console.WriteLine("\t{0}.ef = {1}", str2.ToString(), str2.ef);
return false;
}
Console.WriteLine("\tPASSED!");
return true;
}
#endregion
#region methods for StringStructSequentialAnsi struct
public static StringStructSequentialAnsi NewStringStructSequentialAnsi(string first, string last)
{
StringStructSequentialAnsi s6 = new StringStructSequentialAnsi();
s6.first = first;
s6.last = last;
return s6;
}
public static void PrintStringStructSequentialAnsi(StringStructSequentialAnsi str1, string name)
{
Console.WriteLine("\t{0}.first = {1}", name, str1.first);
Console.WriteLine("\t{0}.last = {1}", name, str1.last);
}
public static bool ValidateStringStructSequentialAnsi(StringStructSequentialAnsi str1, StringStructSequentialAnsi str2, string methodName)
{
if (str1.first != str2.first || str1.last != str2.last)
{
Console.WriteLine("\tFAILED! " + methodName + "did not receive result as expected.");
Console.WriteLine("\tThe Actual is...");
PrintStringStructSequentialAnsi(str1, str1.ToString());
Console.WriteLine("\tThe Expected is...");
PrintStringStructSequentialAnsi(str2, str2.ToString());
return false;
}
else
{
Console.WriteLine("\tPASSED!");
return true;
}
}
#endregion
#region methods for StringStructSequentialUnicode struct
public static StringStructSequentialUnicode NewStringStructSequentialUnicode(string first, string last)
{
StringStructSequentialUnicode s7 = new StringStructSequentialUnicode();
s7.first = first;
s7.last = last;
return s7;
}
public static void PrintStringStructSequentialUnicode(StringStructSequentialUnicode str1, string name)
{
Console.WriteLine("\t{0}.first = {1}", name, str1.first);
Console.WriteLine("\t{0}.last = {1}", name, str1.last);
}
public static bool ValidateStringStructSequentialUnicode(StringStructSequentialUnicode str1, StringStructSequentialUnicode str2, string methodName)
{
if (str1.first != str2.first || str1.last != str2.last)
{
Console.WriteLine("\tFAILED! " + methodName + "did not receive result as expected.");
Console.WriteLine("\tThe Actual is...");
PrintStringStructSequentialUnicode(str1, str1.ToString());
Console.WriteLine("\tThe Expected is...");
PrintStringStructSequentialUnicode(str2, str2.ToString());
return false;
}
else
{
Console.WriteLine("\tPASSED!");
return true;
}
}
#endregion
#region methods for S8 struct
public static S8 NewS8(string name, bool gender, UInt16 jobNum, int i32, uint ui32, sbyte mySByte)
{
S8 s8 = new S8();
s8.name = name;
s8.gender = gender;
s8.i32 = i32;
s8.ui32 = ui32;
s8.jobNum = jobNum;
s8.mySByte = mySByte;
return s8;
}
public static void PrintS8(S8 str1, string name)
{
Console.WriteLine("\t{0}.name = {1}", name, str1.name);
Console.WriteLine("\t{0}.gender = {1}", name, str1.gender);
Console.WriteLine("\t{0}.jobNum = {1}", name, str1.jobNum);
Console.WriteLine("\t{0}.i32 = {1}", name, str1.i32);
Console.WriteLine("\t{0}.ui32 = {1}", name, str1.ui32);
Console.WriteLine("\t{0}.mySByte = {1}", name, str1.mySByte);
}
public static bool ValidateS8(S8 str1, S8 str2, string methodName)
{
if (str1.name != str2.name || str1.gender != str2.gender ||
str1.jobNum != str2.jobNum ||
str1.i32 != str2.i32 || str1.ui32 != str2.ui32 || str1.mySByte != str2.mySByte)
{
Console.WriteLine("\tFAILED! " + methodName + "did not receive result as expected.");
Console.WriteLine("\tThe Actual is...");
PrintS8(str1, str1.ToString());
Console.WriteLine("\tThe Expected is...");
PrintS8(str2, str2.ToString());
return false;
}
Console.WriteLine("\tPASSED!");
return true;
}
#endregion
#region methods for S9 struct
public static S9 NewS9(int i32, TestDelegate1 testDel1)
{
S9 s9 = new S9();
s9.i32 = i32;
s9.myDelegate1 = testDel1;
return s9;
}
public static bool ValidateS9(S9 str1, S9 str2, string methodName)
{
if (str1.i32 != str2.i32 || str1.myDelegate1 != str2.myDelegate1)
{
Console.WriteLine("\tFAILED! " + methodName + "did not receive result as expected.");
Console.WriteLine("\tThe Actual is...");
Console.WriteLine("\t{0}.i32 = {1}", str1.ToString(), str1.i32);
Console.WriteLine("\t{0}.myDelegate1 = {1}", str1.ToString(), str1.myDelegate1);
Console.WriteLine("\tThe Expected is...");
Console.WriteLine("\t{0}.i32 = {1}", str2.ToString(), str2.i32);
Console.WriteLine("\t{0}.myDelegate1 = {1}", str2.ToString(), str2.myDelegate1);
return false;
}
Console.WriteLine("\tPASSED!");
return true;
}
#endregion
#region methods for IncludeOuterIntegerStructSequential struct
public static IncludeOuterIntegerStructSequential NewIncludeOuterIntegerStructSequential(int i321, int i322)
{
IncludeOuterIntegerStructSequential s10 = new IncludeOuterIntegerStructSequential();
s10.s.s_int.i = i321;
s10.s.i = i322;
return s10;
}
public static void PrintIncludeOuterIntegerStructSequential(IncludeOuterIntegerStructSequential str1, string name)
{
Console.WriteLine("\t{0}.s.s_int.i = {1}", name, str1.s.s_int.i);
Console.WriteLine("\t{0}.s.i = {1}", name, str1.s.i);
}
public static bool ValidateIncludeOuterIntegerStructSequential(IncludeOuterIntegerStructSequential str1, IncludeOuterIntegerStructSequential str2, string methodName)
{
if (str1.s.s_int.i != str2.s.s_int.i || str1.s.i != str2.s.i)
{
Console.WriteLine("\tFAILED! " + methodName + "did not receive result as expected.");
Console.WriteLine("\tThe Actual is...");
PrintIncludeOuterIntegerStructSequential(str1, str1.ToString());
Console.WriteLine("\tThe Expected is...");
PrintIncludeOuterIntegerStructSequential(str2, str2.ToString());
return false;
}
else
{
Console.WriteLine("\tPASSED!");
return true;
}
}
#endregion
#region methods for S11 struct
unsafe public static void PrintS11(S11 str1, string name)
{
Console.WriteLine("\t{0}.i32 = {1}", name, (int)(str1.i32));
Console.WriteLine("\t{0}.i = {1}", name, str1.i);
}
unsafe public static S11 NewS11(int* i32, int i)
{
S11 s11 = new S11();
s11.i32 = i32;
s11.i = i;
return s11;
}
unsafe public static bool ValidateS11(S11 str1, S11 str2, string methodName)
{
if (str1.i32 != str2.i32 || str1.i != str2.i)
{
Console.WriteLine("\tFAILED! " + methodName + "did not receive result as expected.");
Console.WriteLine("\tThe Actual is...");
PrintS11(str1, str1.ToString());
Console.WriteLine("\tThe Expected is...");
PrintS11(str2, str2.ToString());
return false;
}
Console.WriteLine("\tPASSED!");
return true;
}
#endregion
#region methods for U struct
public static U NewU(int i32, uint ui32, IntPtr iPtr, UIntPtr uiPtr, short s, ushort us, byte b, sbyte sb, long l, ulong ul, float f, double d)
{
U u = new U();
u.i32 = i32;
u.ui32 = ui32;
u.iPtr = iPtr;
u.uiPtr = uiPtr;
u.s = s;
u.us = us;
u.b = b;
u.sb = sb;
u.l = l;
u.ul = ul;
u.f = f;
u.d = d;
return u;
}
public static void PrintU(U str1, string name)
{
Console.WriteLine("\t{0}.i32 = {1}", name, str1.i32);
Console.WriteLine("\t{0}.ui32 = {1}", name, str1.ui32);
Console.WriteLine("\t{0}.iPtr = {1}", name, str1.iPtr);
Console.WriteLine("\t{0}.uiPtr = {1}", name, str1.uiPtr);
Console.WriteLine("\t{0}.s = {1}", name, str1.s);
Console.WriteLine("\t{0}.us = {1}", name, str1.us);
Console.WriteLine("\t{0}.b = {1}", name, str1.b);
Console.WriteLine("\t{0}.sb = {1}", name, str1.sb);
Console.WriteLine("\t{0}.l = {1}", name, str1.l);
Console.WriteLine("\t{0}.ul = {1}", name, str1.ul);
Console.WriteLine("\t{0}.f = {1}", name, str1.f);
Console.WriteLine("\t{0}.d = {1}", name, str1.d);
}
public static bool ValidateU(U str1, U str2, string methodName)
{
if (str1.i32 != str2.i32 || str1.ui32 != str2.ui32 || str1.iPtr != str2.iPtr ||
str1.uiPtr != str2.uiPtr || str1.s != str2.s || str1.us != str2.us ||
str1.b != str2.b || str1.sb != str2.sb || str1.l != str2.l || str1.ul != str2.ul ||
str1.f != str2.f || str1.d != str2.d)
{
Console.WriteLine("\tFAILED! " + methodName + "did not receive result as expected.");
Console.WriteLine("\tThe Actual is...");
PrintU(str1, str1.ToString());
Console.WriteLine("\tThe Expected is...");
PrintU(str2, str2.ToString());
return false;
}
Console.WriteLine("\tPASSED!");
return true;
}
#endregion
#region methods for ByteStructPack2Explicit struct
public static ByteStructPack2Explicit NewByteStructPack2Explicit(byte b1, byte b2)
{
ByteStructPack2Explicit u1 = new ByteStructPack2Explicit();
u1.b1 = b1;
u1.b2 = b2;
return u1;
}
public static void PrintByteStructPack2Explicit(ByteStructPack2Explicit str1, string name)
{
Console.WriteLine("\t{0}.b1 = {1}", name, str1.b1);
Console.WriteLine("\t{0}.b2 = {1}", name, str1.b2);
}
public static bool ValidateByteStructPack2Explicit(ByteStructPack2Explicit str1, ByteStructPack2Explicit str2, string methodName)
{
if (str1.b1 != str2.b1 || str1.b2 != str2.b2)
{
Console.WriteLine("\tFAILED! " + methodName + "did not receive result as expected.");
Console.WriteLine("\tThe Actual is...");
PrintByteStructPack2Explicit(str1, str1.ToString());
Console.WriteLine("\tThe Expected is...");
PrintByteStructPack2Explicit(str2, str2.ToString());
return false;
}
else
{
Console.WriteLine("\tPASSED!");
return true;
}
}
#endregion
#region methods for ShortStructPack4Explicit struct
public static ShortStructPack4Explicit NewShortStructPack4Explicit(short s1, short s2)
{
ShortStructPack4Explicit u2 = new ShortStructPack4Explicit();
u2.s1 = s1;
u2.s2 = s2;
return u2;
}
public static void PrintShortStructPack4Explicit(ShortStructPack4Explicit str1, string name)
{
Console.WriteLine("\t{0}.s1 = {1}", name, str1.s1);
Console.WriteLine("\t{0}.s2 = {1}", name, str1.s2);
}
public static bool ValidateShortStructPack4Explicit(ShortStructPack4Explicit str1, ShortStructPack4Explicit str2, string methodName)
{
if (str1.s1 != str2.s1 || str1.s2 != str2.s2)
{
Console.WriteLine("\tFAILED! " + methodName + "did not receive result as expected.");
Console.WriteLine("\tThe Actual is...");
PrintShortStructPack4Explicit(str1, str1.ToString());
Console.WriteLine("\tThe Expected is...");
PrintShortStructPack4Explicit(str2, str2.ToString());
return false;
}
else
{
Console.WriteLine("\tPASSED!");
return true;
}
}
#endregion
#region methods for IntStructPack8Explicit struct
public static IntStructPack8Explicit NewIntStructPack8Explicit(int i1, int i2)
{
IntStructPack8Explicit u3 = new IntStructPack8Explicit();
u3.i1 = i1;
u3.i2 = i2;
return u3;
}
public static void PrintIntStructPack8Explicit(IntStructPack8Explicit str1, string name)
{
Console.WriteLine("\t{0}.i1 = {1}", name, str1.i1);
Console.WriteLine("\t{0}.i2 = {1}", name, str1.i2);
}
public static bool ValidateIntStructPack8Explicit(IntStructPack8Explicit str1, IntStructPack8Explicit str2, string methodName)
{
if (str1.i1 != str2.i1 || str1.i2 != str2.i2)
{
Console.WriteLine("\tFAILED! " + methodName + "did not receive result as expected.");
Console.WriteLine("\tThe Actual is...");
PrintIntStructPack8Explicit(str1, str1.ToString());
Console.WriteLine("\tThe Expected is...");
PrintIntStructPack8Explicit(str2, str2.ToString());
return false;
}
else
{
Console.WriteLine("\tPASSED!");
return true;
}
}
#endregion
#region methods for LongStructPack16Explicit struct
public static LongStructPack16Explicit NewLongStructPack16Explicit(long l1, long l2)
{
LongStructPack16Explicit u4 = new LongStructPack16Explicit();
u4.l1 = l1;
u4.l2 = l2;
return u4;
}
public static void PrintLongStructPack16Explicit(LongStructPack16Explicit str1, string name)
{
Console.WriteLine("\t{0}.l1 = {1}", name, str1.l1);
Console.WriteLine("\t{0}.l2 = {1}", name, str1.l2);
}
public static bool ValidateLongStructPack16Explicit(LongStructPack16Explicit str1, LongStructPack16Explicit str2, string methodName)
{
if (str1.l1 != str2.l1 || str1.l2 != str2.l2)
{
Console.WriteLine("\tFAILED! " + methodName + "did not receive result as expected.");
Console.WriteLine("\tThe Actual is...");
PrintLongStructPack16Explicit(str1, str1.ToString());
Console.WriteLine("\tThe Expected is...");
PrintLongStructPack16Explicit(str2, str2.ToString());
return false;
}
else
{
Console.WriteLine("\tPASSED!");
return true;
}
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
using KSP.Localization;
namespace KERBALISM
{
public static class Storm
{
// TODO multi sun support?
public static float sun_observation_quality = 1.0f;
internal static void CreateStorm(StormData bd, CelestialBody body, double distanceToSun)
{
// do nothing if storms are disabled
if (!Features.SpaceWeather) return;
var now = Planetarium.GetUniversalTime();
if (bd.storm_generation < now)
{
var sun = Lib.GetParentSun(body);
var avgDuration = PreferencesRadiation.Instance.AvgStormDuration;
// retry after 5 * average storm duration + jitter (to avoid recalc spikes)
bd.storm_generation = now + avgDuration * 5 + avgDuration * Lib.RandomDouble();
var rb = Radiation.Info(sun);
var activity = rb.solar_cycle > 0 ? rb.SolarActivity() : 1.0;
if (Lib.RandomDouble() < activity * PreferencesRadiation.Instance.stormFrequency)
{
// storm duration depends on current solar activity
bd.storm_duration = avgDuration / 2.0 + avgDuration * activity * 2;
// if further out, the storm lasts longer (but is weaker)
bd.storm_duration /= Storm_frequency(distanceToSun);
// set a start time to give enough time for warning
bd.storm_time = now + Time_to_impact(distanceToSun);
// delay next storm generation by duration of this one
bd.storm_generation += bd.storm_duration;
// add a random error to the estimated storm duration if we don't observe the sun too well
var error = bd.storm_duration * 3 * Lib.RandomDouble() * (1 - sun_observation_quality);
bd.displayed_duration = bd.storm_duration + error;
// show warning message only if you're lucky...
bd.display_warning = Lib.RandomFloat() < sun_observation_quality;
#if DEBUG_RADIATION
Lib.Log("Storm on " + body + " will start in " + Lib.HumanReadableDuration(bd.storm_time - now) + " and last for " + Lib.HumanReadableDuration(bd.storm_duration));
}
else
{
Lib.Log("No storm on " + body + ", will retry in " + Lib.HumanReadableDuration(bd.storm_generation - now));
#endif
}
}
if (bd.storm_time + bd.storm_duration < now)
{
// storm is over
bd.Reset();
}
else if (bd.storm_time < now && bd.storm_time + bd.storm_duration > now)
{
// storm in progress
bd.storm_state = 2;
}
else if (bd.storm_time > now)
{
// storm incoming
bd.storm_state = 1;
}
}
public static void Update(CelestialBody body, double elapsed_s)
{
// do nothing if storms are disabled
if (!Features.SpaceWeather) return;
StormData bd = DB.Storm(body.name);
CreateStorm(bd, body, body.orbit.semiMajorAxis);
// send messages
if (Body_is_relevant(body))
{
switch (bd.storm_state)
{
case 2:
if (bd.msg_storm < 2)
{
Message.Post(Severity.danger, Local.Storm_msg1.Format("<b>" + body.name + "</b>"),//"The coronal mass ejection hit <<1>> system //Lib.BuildString( )
Lib.BuildString(Local.Storm_msg1text, " ", Lib.HumanReadableDuration(bd.displayed_duration)));//"Storm duration:"
}
break;
case 1:
if (bd.msg_storm < 1 && bd.display_warning)
{
var tti = bd.storm_time - Planetarium.GetUniversalTime();
Message.Post(Severity.warning, Local.Storm_msg2.Format("<b>" + body.name + "</b>"),//Lib.BuildString("Our observatories report a coronal mass ejection directed toward <<1>> system")
Lib.BuildString(Local.Storm_msg2text," ", Lib.HumanReadableDuration(tti)));//"Time to impact:"
}
break;
case 0:
if (bd.msg_storm == 2)
{
Message.Post(Severity.relax, Local.Storm_msg3.Format("<b>" + body.name + "</b>"));//Lib.BuildString("The solar storm at <<1>> system is over")
}
break;
}
}
bd.msg_storm = bd.storm_state;
}
public static void Update(Vessel v, VesselData vd, double elapsed_s)
{
// do nothing if storms are disabled
if (!Features.SpaceWeather) return;
// only consider vessels in interplanetary space
if (!Lib.IsSun(v.mainBody)) return;
// disregard EVAs
if (v.isEVA) return;
var bd = vd.stormData;
CreateStorm(bd, v.mainBody, vd.EnvMainSun.Distance);
if (vd.cfg_storm)
{
switch (bd.storm_state)
{
case 0: // no storm
if (bd.msg_storm == 2)
{
// send message
Message.Post(Severity.relax, Local.Storm_msg4.Format("<b>" + v.vesselName + "</b>"));//Lib.BuildString("The solar storm around <<1>> is over")
vd.msg_signal = false; // used to avoid sending 'signal is back' messages en-masse after the storm is over
}
break;
case 2: // storm in progress
if (bd.msg_storm < 2)
{
Message.Post(Severity.danger, Local.Storm_msg5.Format("<b>" + v.vesselName + "</b>"),//Lib.BuildString("The coronal mass ejection hit <<1>>)
Lib.BuildString(Local.Storm_msg1text, " ", Lib.HumanReadableDuration(bd.displayed_duration)));//"Storm duration:"
}
break;
case 1: // storm incoming
if (bd.msg_storm < 1 && bd.display_warning)
{
var tti = bd.storm_time - Planetarium.GetUniversalTime();
Message.Post(Severity.warning, Local.Storm_msg6.Format("<b>" + v.vesselName + "</b>"),//Lib.BuildString("Our observatories report a coronal mass ejection directed toward <<1>>)
Lib.BuildString(Local.Storm_msg2text, " ", Lib.HumanReadableDuration(tti)));//"Time to impact:
}
break;
}
}
bd.msg_storm = bd.storm_state;
}
// return storm frequency factor by distance from sun
static double Storm_frequency(double dist)
{
return Sim.AU / dist;
}
// return time to impact from CME event, in seconds
static double Time_to_impact(double dist)
{
return dist / PreferencesRadiation.Instance.StormEjectionSpeed;
}
// return true if body is relevant to the player
// - body: reference body of the planetary system
static bool Body_is_relevant(CelestialBody body)
{
// [disabled]
// special case: home system is always relevant
// note: we deal with the case of a planet mod setting homebody as a moon
//if (body == Lib.PlanetarySystem(FlightGlobals.GetHomeBody())) return true;
// for each vessel
foreach (Vessel v in FlightGlobals.Vessels)
{
// if inside the system
if (Lib.GetParentPlanet(v.mainBody) == body)
{
// get info from the cache
VesselData vd = v.KerbalismData();
// skip invalid vessels
if (!vd.IsSimulated) continue;
// obey message config
if (!v.KerbalismData().cfg_storm) continue;
// body is relevant
return true;
}
}
return false;
}
// used by the engine to update one body per-step
public static bool Skip_body(CelestialBody body)
{
// skip all bodies if storms are disabled
if (!Features.SpaceWeather) return true;
// skip the sun
if (Lib.IsSun(body)) return true;
// skip moons
// note: referenceBody is never null here
if (!Lib.IsSun(body.referenceBody)) return true;
// do not skip the body
return false;
}
/// <summary>return true if a storm is incoming</summary>
public static bool Incoming(Vessel v)
{
var bd = Lib.IsSun(v.mainBody) ? v.KerbalismData().stormData : DB.Storm(Lib.GetParentPlanet(v.mainBody).name);
return bd.storm_state == 1 && bd.display_warning;
}
/// <summary>return true if a storm is in progress</summary>
public static bool InProgress(Vessel v)
{
var bd = Lib.IsSun(v.mainBody) ? v.KerbalismData().stormData : DB.Storm(Lib.GetParentPlanet(v.mainBody).name);
return bd.storm_state == 2;
}
}
} // KERBALISM
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
#if FEATURE_SECURITY_PRINCIPAL_WINDOWS
using System.Security.AccessControl;
using System.Security.Principal;
#endif
using System.Text;
using System.Threading;
using System.Xml;
using Microsoft.Build.Construction;
using Microsoft.Build.Engine.UnitTests;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Shared;
using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;
using ProjectCollection = Microsoft.Build.Evaluation.ProjectCollection;
using Xunit;
namespace Microsoft.Build.UnitTests.OM.Construction
{
/// <summary>
/// Test the ProjectRootElement class
/// </summary>
public class ProjectRootElement_Tests
{
private const string SimpleProject =
@"<Project xmlns=`msbuildnamespace`>
<PropertyGroup>
<P>property value</P>
</PropertyGroup>
<PropertyGroup>
<ProjectFile>$(MSBuildProjectFullPath)</ProjectFile>
<ThisFile>$(MSBuildThisFileFullPath)</ThisFile>
</PropertyGroup>
<ItemGroup>
<i Include=`a`>
<m>metadata value</m>
</i>
</ItemGroup>
</Project>";
private const string ComplexProject =
@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<PropertyGroup Condition=""false"">
<p>p1</p>
<q>q1</q>
</PropertyGroup>
<PropertyGroup/>
<PropertyGroup>
<r>r1</r>
</PropertyGroup>
<PropertyGroup>
<ProjectFile>$(MSBuildProjectFullPath)</ProjectFile>
<ThisFile>$(MSBuildThisFileFullPath)</ThisFile>
</PropertyGroup>
<Choose>
<When Condition=""true"">
<Choose>
<When Condition=""true"">
<PropertyGroup>
<s>s1</s>
</PropertyGroup>
</When>
</Choose>
</When>
<When Condition=""false"">
<PropertyGroup>
<s>s2</s> <!-- both esses -->
</PropertyGroup>
</When>
<Otherwise>
<Choose>
<When Condition=""false""/>
<Otherwise>
<PropertyGroup>
<t>t1</t>
</PropertyGroup>
</Otherwise>
</Choose>
</Otherwise>
</Choose>
<Import Project='$(MSBuildToolsPath)\Microsoft.CSharp.targets'/>
</Project>";
/// <summary>
/// Empty project content
/// </summary>
[Fact]
public void EmptyProject()
{
ProjectRootElement project = ProjectRootElement.Create();
Assert.Equal(0, Helpers.Count(project.Children));
Assert.Equal(string.Empty, project.DefaultTargets);
Assert.Equal(string.Empty, project.InitialTargets);
Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, project.ToolsVersion);
Assert.True(project.HasUnsavedChanges); // it is indeed unsaved
}
/// <summary>
/// Set default targets
/// </summary>
[Fact]
public void SetDefaultTargets()
{
ProjectRootElement project = ProjectRootElement.Create();
project.DefaultTargets = "dt";
Assert.Equal("dt", project.DefaultTargets);
Assert.True(project.HasUnsavedChanges);
}
/// <summary>
/// Set initialtargets
/// </summary>
[Fact]
public void SetInitialTargets()
{
ProjectRootElement project = ProjectRootElement.Create();
project.InitialTargets = "it";
Assert.Equal("it", project.InitialTargets);
Assert.True(project.HasUnsavedChanges);
}
/// <summary>
/// Set toolsversion
/// </summary>
[Fact]
public void SetToolsVersion()
{
ProjectRootElement project = ProjectRootElement.Create();
project.ToolsVersion = "tv";
Assert.Equal("tv", project.ToolsVersion);
Assert.True(project.HasUnsavedChanges);
}
/// <summary>
/// Setting full path should accept and update relative path
/// </summary>
[Fact]
public void SetFullPath()
{
ProjectRootElement project = ProjectRootElement.Create();
project.FullPath = "X";
Assert.Equal(project.FullPath, Path.Combine(Directory.GetCurrentDirectory(), "X"));
}
/// <summary>
/// Attempting to load a second ProjectRootElement over the same file path simply
/// returns the first one.
/// A ProjectRootElement is notionally a "memory mapped" view of a file, and we assume there is only
/// one per file path, so we must reject attempts to make another.
/// </summary>
[Fact]
public void ConstructOverSameFileReturnsSame()
{
ProjectRootElement projectXml1 = ProjectRootElement.Create();
projectXml1.Save(FileUtilities.GetTemporaryFile());
ProjectRootElement projectXml2 = ProjectRootElement.Open(projectXml1.FullPath);
Assert.True(object.ReferenceEquals(projectXml1, projectXml2));
}
/// <summary>
/// Attempting to load a second ProjectRootElement over the same file path simply
/// returns the first one. This should work even if one of the paths is not a full path.
/// </summary>
[Fact]
public void ConstructOverSameFileReturnsSameEvenWithOneBeingRelativePath()
{
ProjectRootElement projectXml1 = ProjectRootElement.Create();
projectXml1.FullPath = Path.Combine(Directory.GetCurrentDirectory(), @"xyz\abc");
ProjectRootElement projectXml2 = ProjectRootElement.Open(@"xyz\abc");
Assert.True(object.ReferenceEquals(projectXml1, projectXml2));
}
/// <summary>
/// Attempting to load a second ProjectRootElement over the same file path simply
/// returns the first one. This should work even if one of the paths is not a full path.
/// </summary>
[Fact]
public void ConstructOverSameFileReturnsSameEvenWithOneBeingRelativePath2()
{
ProjectRootElement projectXml1 = ProjectRootElement.Create();
projectXml1.FullPath = @"xyz\abc";
ProjectRootElement projectXml2 = ProjectRootElement.Open(Path.Combine(Directory.GetCurrentDirectory(), @"xyz\abc"));
Assert.True(object.ReferenceEquals(projectXml1, projectXml2));
}
/// <summary>
/// Using TextReader
/// </summary>
[Fact]
public void ConstructOverSameFileReturnsSameEvenWithOneBeingRelativePath3()
{
string content = "<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n</Project>";
ProjectRootElement projectXml1 = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
projectXml1.FullPath = @"xyz\abc";
ProjectRootElement projectXml2 = ProjectRootElement.Open(Path.Combine(Directory.GetCurrentDirectory(), @"xyz\abc"));
Assert.True(object.ReferenceEquals(projectXml1, projectXml2));
}
/// <summary>
/// Using TextReader
/// </summary>
[Fact]
public void ConstructOverSameFileReturnsSameEvenWithOneBeingRelativePath4()
{
string content = "<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">\r\n</Project>";
ProjectRootElement projectXml1 = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
projectXml1.FullPath = Path.Combine(Directory.GetCurrentDirectory(), @"xyz\abc");
ProjectRootElement projectXml2 = ProjectRootElement.Open(@"xyz\abc");
Assert.True(object.ReferenceEquals(projectXml1, projectXml2));
}
/// <summary>
/// Two ProjectRootElement's over the same file path does not throw (although you shouldn't do it)
/// </summary>
[Fact]
public void SetFullPathProjectXmlAlreadyLoaded()
{
ProjectRootElement projectXml1 = ProjectRootElement.Create();
projectXml1.FullPath = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
ProjectRootElement projectXml2 = ProjectRootElement.Create();
projectXml2.FullPath = projectXml1.FullPath;
}
/// <summary>
/// Invalid XML
/// </summary>
[Fact]
public void InvalidXml()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
ProjectRootElement.Create(XmlReader.Create(new StringReader("XXX")));
}
);
}
/// <summary>
/// Valid Xml, invalid namespace on the root
/// </summary>
[Fact]
public void InvalidNamespace()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
var content = @"<Project xmlns='XXX'/>";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
});
}
/// <summary>
/// Invalid root tag
/// </summary>
[Fact]
public void InvalidRootTag()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content = @"
<XXX xmlns='http://schemas.microsoft.com/developer/msbuild/2003'/>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
);
}
/// <summary>
/// Valid Xml, invalid syntax below the root
/// </summary>
[Fact]
public void InvalidChildBelowRoot()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<XXX/>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
);
}
/// <summary>
/// Root indicates upgrade needed
/// </summary>
[Fact]
public void NeedsUpgrade()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content = @"
<VisualStudioProject/>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
);
}
/// <summary>
/// Valid Xml, invalid namespace below the root
/// </summary>
[Fact]
public void InvalidNamespaceBelowRoot()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<PropertyGroup xmlns='XXX'/>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
);
}
/// <summary>
/// Tests that the namespace error reports are correct
/// </summary>
[Fact]
public void InvalidNamespaceErrorReport()
{
string content = @"
<msb:Project xmlns:msb=`http://schemas.microsoft.com/developer/msbuild/2003`>
<msb:Target Name=`t`>
<msb:Message Text=`[t]`/>
</msb:Target>
</msb:Project>
";
content = content.Replace("`", "\"");
bool exceptionThrown = false;
try
{
Project project = new Project(XmlReader.Create(new StringReader(content)));
}
catch (InvalidProjectFileException ex)
{
exceptionThrown = true;
// MSB4068: The element <msb:Project> is unrecognized, or not supported in this context.
Assert.NotEqual("MSB4068", ex.ErrorCode);
// MSB4041: The default XML namespace of the project must be the MSBuild XML namespace.
Assert.Equal("MSB4041", ex.ErrorCode);
}
Assert.True(exceptionThrown); // "ERROR: An invalid project file exception should have been thrown."
}
/// <summary>
/// Valid Xml, invalid syntax thrown by child element parsing
/// </summary>
[Fact]
public void ValidXmlInvalidSyntaxInChildElement()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<ItemGroup>
<XXX YYY='ZZZ'/>
</ItemGroup>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
);
}
/// <summary>
/// Valid Xml, invalid syntax, should not get added to the Xml cache and
/// thus returned on the second request!
/// </summary>
[Fact]
public void ValidXmlInvalidSyntaxOpenFromDiskTwice()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<ItemGroup>
<XXX YYY='ZZZ'/>
</ItemGroup>
</Project>
";
string path = null;
try
{
try
{
path = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
File.WriteAllText(path, content);
ProjectRootElement.Open(path);
}
catch (InvalidProjectFileException)
{
}
// Should throw again, not get from cache
ProjectRootElement.Open(path);
}
finally
{
File.Delete(path);
}
}
);
}
/// <summary>
/// Verify that opening project using XmlTextReader does not add it to the Xml cache
/// </summary>
[Fact]
[Trait("Category", "netcore-osx-failing")]
[Trait("Category", "netcore-linux-failing")]
public void ValidXmlXmlTextReaderNotCache()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
</Project>
";
string path = null;
try
{
path = FileUtilities.GetTemporaryFile();
File.WriteAllText(path, content);
var reader1 = XmlReader.Create(path);
ProjectRootElement root1 = ProjectRootElement.Create(reader1);
root1.AddItem("type", "include");
// If it's in the cache, then the 2nd document won't see the add.
var reader2 = XmlReader.Create(path);
ProjectRootElement root2 = ProjectRootElement.Create(reader2);
Assert.Single(root1.Items);
Assert.Empty(root2.Items);
reader1.Dispose();
reader2.Dispose();
}
finally
{
File.Delete(path);
}
}
/// <summary>
/// Verify that opening project using the same path adds it to the Xml cache
/// </summary>
[Fact]
public void ValidXmlXmlReaderCache()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
</Project>
";
string content2 = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' DefaultTargets='t'>
</Project>
";
string path = null;
try
{
path = FileUtilities.GetTemporaryFile();
File.WriteAllText(path, content);
ProjectRootElement root1 = ProjectRootElement.Create(path);
File.WriteAllText(path, content2);
// If it went in the cache, and this path also reads from the cache,
// then we'll see the first version of the file.
ProjectRootElement root2 = ProjectRootElement.Create(path);
Assert.Equal(string.Empty, root1.DefaultTargets);
Assert.Equal(string.Empty, root2.DefaultTargets);
}
finally
{
File.Delete(path);
}
}
/// <summary>
/// A simple "system" test: load microsoft.*.targets and verify we don't throw
/// </summary>
[Fact]
public void LoadCommonTargets()
{
ProjectCollection projectCollection = new ProjectCollection();
string toolsPath = projectCollection.Toolsets.Where(toolset => (string.Compare(toolset.ToolsVersion, ObjectModelHelpers.MSBuildDefaultToolsVersion, StringComparison.OrdinalIgnoreCase) == 0)).First().ToolsPath;
string[] targets =
{
"Microsoft.Common.targets",
"Microsoft.CSharp.targets",
"Microsoft.VisualBasic.targets"
};
foreach (string target in targets)
{
string path = Path.Combine(toolsPath, target);
ProjectRootElement project = ProjectRootElement.Open(path);
Console.WriteLine(@"Loaded target: {0}", target);
Console.WriteLine(@"Children: {0}", Helpers.Count(project.Children));
Console.WriteLine(@"Targets: {0}", Helpers.MakeList(project.Targets).Count);
Console.WriteLine(@"Root ItemGroups: {0}", Helpers.MakeList(project.ItemGroups).Count);
Console.WriteLine(@"Root PropertyGroups: {0}", Helpers.MakeList(project.PropertyGroups).Count);
Console.WriteLine(@"UsingTasks: {0}", Helpers.MakeList(project.UsingTasks).Count);
Console.WriteLine(@"ItemDefinitionGroups: {0}", Helpers.MakeList(project.ItemDefinitionGroups).Count);
}
}
/// <summary>
/// Save project loaded from TextReader, without setting FullPath.
/// </summary>
[Fact]
public void InvalidSaveWithoutFullPath()
{
Assert.Throws<InvalidOperationException>(() =>
{
XmlReader reader = XmlReader.Create(new StringReader("<Project xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\"/>"));
ProjectRootElement project = ProjectRootElement.Create(reader);
project.Save();
}
);
}
/// <summary>
/// Save content with transforms.
/// The ">" should not turn into "<"
/// </summary>
[Fact]
public void SaveWithTransforms()
{
ProjectRootElement project = ProjectRootElement.Create();
project.AddItem("i", "@(h->'%(x)')");
StringBuilder builder = new StringBuilder();
StringWriter writer = new StringWriter(builder);
project.Save(writer);
// UTF-16 because writer.Encoding is UTF-16
string expected = ObjectModelHelpers.CleanupFileContents(
@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemGroup>
<i Include=""@(h->'%(x)')"" />
</ItemGroup>
</Project>");
Helpers.VerifyAssertLineByLine(expected, builder.ToString());
}
/// <summary>
/// Save content with transforms to a file.
/// The ">" should not turn into "<"
/// </summary>
[Fact]
public void SaveWithTransformsToFile()
{
ProjectRootElement project = ProjectRootElement.Create();
project.AddItem("i", "@(h->'%(x)')");
string file = null;
try
{
file = FileUtilities.GetTemporaryFile();
project.Save(file);
string expected = ObjectModelHelpers.CleanupFileContents(
@"<?xml version=""1.0"" encoding=""utf-8""?>
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemGroup>
<i Include=""@(h->'%(x)')"" />
</ItemGroup>
</Project>");
string actual = File.ReadAllText(file);
Helpers.VerifyAssertLineByLine(expected, actual);
}
finally
{
File.Delete(file);
}
}
/// <summary>
/// Save should create a directory if it is missing
/// </summary>
[Fact]
public void SaveToNonexistentDirectory()
{
ProjectRootElement project = ProjectRootElement.Create();
string directory = null;
try
{
directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
string file = "foo.proj";
string path = Path.Combine(directory, file);
project.Save(path);
Assert.True(File.Exists(path));
Assert.Equal(path, project.FullPath);
Assert.Equal(directory, project.DirectoryPath);
}
finally
{
FileUtilities.DeleteWithoutTrailingBackslash(directory, true);
}
}
/// <summary>
/// Save should create a directory if it is missing
/// </summary>
[Fact]
public void SaveToNonexistentDirectoryRelativePath()
{
ProjectRootElement project = ProjectRootElement.Create();
string directory = null;
string savedCurrentDirectory = Directory.GetCurrentDirectory();
try
{
Directory.SetCurrentDirectory(Path.GetTempPath()); // should be used for project.DirectoryPath; it must exist
// Use the *real* current directory for constructing the path
var curDir = Directory.GetCurrentDirectory();
string file = "bar" + Path.DirectorySeparatorChar + "foo.proj";
string path = Path.Combine(curDir, file);
directory = Path.Combine(curDir, "bar");
project.Save(file); // relative path: file and a single directory only; should create the "bar" part
Assert.True(File.Exists(file));
Assert.Equal(path, project.FullPath);
Assert.Equal(directory, project.DirectoryPath);
}
finally
{
FileUtilities.DeleteWithoutTrailingBackslash(directory, true);
Directory.SetCurrentDirectory(savedCurrentDirectory);
}
}
/// <summary>
/// Saving an unnamed project without a path specified should give a nice exception
/// </summary>
[Fact]
public void SaveUnnamedProject()
{
Assert.Throws<InvalidOperationException>(() =>
{
ProjectRootElement project = ProjectRootElement.Create();
project.Save();
}
);
}
/// <summary>
/// Verifies that the ProjectRootElement.Encoding property getter returns values
/// that are based on the XML declaration in the file.
/// </summary>
[Fact]
public void EncodingGetterBasedOnXmlDeclaration()
{
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project DefaultTargets=""Build"" ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
</Project>"))));
Assert.Equal(Encoding.Unicode, project.Encoding);
project = ProjectRootElement.Create(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"<?xml version=""1.0"" encoding=""utf-8""?>
<Project DefaultTargets=""Build"" ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
</Project>"))));
Assert.Equal(Encoding.UTF8, project.Encoding);
project = ProjectRootElement.Create(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"<?xml version=""1.0"" encoding=""us-ascii""?>
<Project DefaultTargets=""Build"" ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
</Project>"))));
Assert.Equal(Encoding.ASCII, project.Encoding);
}
/// <summary>
/// Verifies that ProjectRootElement.Encoding returns the correct value
/// after reading a file off disk, even if no xml declaration is present.
/// </summary>
[Fact]
public void EncodingGetterBasedOnActualEncodingWhenXmlDeclarationIsAbsent()
{
string projectFullPath = FileUtilities.GetTemporaryFile();
try
{
VerifyLoadedProjectHasEncoding(projectFullPath, Encoding.UTF8);
VerifyLoadedProjectHasEncoding(projectFullPath, Encoding.Unicode);
// We don't test ASCII, since there is no byte order mark for it,
// and the XmlReader will legitimately decide to interpret it as UTF8,
// which would fail the test although it's a reasonable assumption
// when no xml declaration is present.
////VerifyLoadedProjectHasEncoding(projectFullPath, Encoding.ASCII);
}
finally
{
File.Delete(projectFullPath);
}
}
/// <summary>
/// Verifies that the Save method saves an otherwise unmodified project
/// with a specified file encoding.
/// </summary>
[Fact]
public void SaveUnmodifiedWithNewEncoding()
{
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(@"
<Project DefaultTargets=""Build"" ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
</Project>"))));
project.FullPath = FileUtilities.GetTemporaryFile();
string projectFullPath = project.FullPath;
try
{
project.Save();
project = null;
// We haven't made any changes to the project, but we want to save it using various encodings.
SaveProjectWithEncoding(projectFullPath, Encoding.Unicode);
SaveProjectWithEncoding(projectFullPath, Encoding.ASCII);
SaveProjectWithEncoding(projectFullPath, Encoding.UTF8);
}
finally
{
File.Delete(projectFullPath);
}
}
/// <summary>
/// Enumerate over all properties from the project directly.
/// It should traverse into Choose's.
/// </summary>
[Fact]
public void PropertiesEnumerator()
{
string content = ObjectModelHelpers.CleanupFileContents(
@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<PropertyGroup Condition=""false"">
<p>p1</p>
<q>q1</q>
</PropertyGroup>
<PropertyGroup/>
<PropertyGroup>
<r>r1</r>
</PropertyGroup>
<Choose>
<When Condition=""true"">
<Choose>
<When Condition=""true"">
<PropertyGroup>
<s>s1</s>
</PropertyGroup>
</When>
</Choose>
</When>
<When Condition=""false"">
<PropertyGroup>
<s>s2</s> <!-- both esses -->
</PropertyGroup>
</When>
<Otherwise>
<Choose>
<When Condition=""false""/>
<Otherwise>
<PropertyGroup>
<t>t1</t>
</PropertyGroup>
</Otherwise>
</Choose>
</Otherwise>
</Choose>
</Project>");
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
List<ProjectPropertyElement> properties = Helpers.MakeList(project.Properties);
Assert.Equal(6, properties.Count);
Assert.Equal("q", properties[1].Name);
Assert.Equal("r1", properties[2].Value);
Assert.Equal("t1", properties[5].Value);
}
/// <summary>
/// Enumerate over all items from the project directly.
/// It should traverse into Choose's.
/// </summary>
[Fact]
public void ItemsEnumerator()
{
string content = ObjectModelHelpers.CleanupFileContents(
@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemGroup Condition=""false"">
<i Include=""i1""/>
<j Include=""j1""/>
</ItemGroup>
<ItemGroup/>
<ItemGroup>
<k Include=""k1""/>
</ItemGroup>
<Choose>
<When Condition=""true"">
<Choose>
<When Condition=""true"">
<ItemGroup>
<k Include=""k2""/>
</ItemGroup>
</When>
</Choose>
</When>
<When Condition=""false"">
<ItemGroup>
<k Include=""k3""/>
</ItemGroup>
</When>
<Otherwise>
<Choose>
<When Condition=""false""/>
<Otherwise>
<ItemGroup>
<k Include=""k4""/>
</ItemGroup>
</Otherwise>
</Choose>
</Otherwise>
</Choose>
</Project>");
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
List<ProjectItemElement> items = Helpers.MakeList(project.Items);
Assert.Equal(6, items.Count);
Assert.Equal("j", items[1].ItemType);
Assert.Equal("k1", items[2].Include);
Assert.Equal("k4", items[5].Include);
}
#if FEATURE_SECURITY_PRINCIPAL_WINDOWS
/// <summary>
/// Build a solution file that can't be accessed
/// </summary>
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Security classes are not supported on Unix
public void SolutionCanNotBeOpened()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string solutionFile = null;
string tempFileSentinel = null;
IdentityReference identity = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
FileSystemAccessRule rule = new FileSystemAccessRule(identity, FileSystemRights.Read, AccessControlType.Deny);
FileSecurity security = null;
try
{
tempFileSentinel = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
solutionFile = Path.ChangeExtension(tempFileSentinel, ".sln");
File.Copy(tempFileSentinel, solutionFile);
security = new FileSecurity(solutionFile, System.Security.AccessControl.AccessControlSections.All);
security.AddAccessRule(rule);
File.SetAccessControl(solutionFile, security);
ProjectRootElement.Open(solutionFile);
}
catch (PrivilegeNotHeldException)
{
throw new InvalidProjectFileException("Running unelevated so skipping this scenario.");
}
finally
{
if (security != null)
{
security.RemoveAccessRule(rule);
}
File.Delete(solutionFile);
File.Delete(tempFileSentinel);
Assert.False(File.Exists(solutionFile));
}
}
);
}
/// <summary>
/// Build a project file that can't be accessed
/// </summary>
[Fact]
[PlatformSpecific (TestPlatforms.Windows)]
// FileSecurity class is not supported on Unix
public void ProjectCanNotBeOpened()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string projectFile = null;
IdentityReference identity = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
FileSystemAccessRule rule = new FileSystemAccessRule(identity, FileSystemRights.Read, AccessControlType.Deny);
FileSecurity security = null;
try
{
// Does not have .sln or .vcproj extension so loads as project
projectFile = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
security = new FileSecurity(projectFile, System.Security.AccessControl.AccessControlSections.All);
security.AddAccessRule(rule);
File.SetAccessControl(projectFile, security);
ProjectRootElement.Open(projectFile);
}
catch (PrivilegeNotHeldException)
{
throw new InvalidProjectFileException("Running unelevated so skipping the scenario.");
}
finally
{
if (security != null)
{
security.RemoveAccessRule(rule);
}
File.Delete(projectFile);
Assert.False(File.Exists(projectFile));
}
}
);
}
#endif
/// <summary>
/// Build a corrupt solution
/// </summary>
[Fact]
public void SolutionCorrupt()
{
Assert.Throws<InvalidProjectFileException>(() =>
{
string solutionFile = null;
try
{
solutionFile = Microsoft.Build.Shared.FileUtilities.GetTemporaryFile();
// Arbitrary corrupt content
string content = @"Microsoft Visual Studio Solution File, Format Version 10.00
# Visual Studio Codename Orcas
Project(""{";
File.WriteAllText(solutionFile, content);
ProjectRootElement.Open(solutionFile);
}
finally
{
File.Delete(solutionFile);
}
}
);
}
/// <summary>
/// Open lots of projects concurrently to try to trigger problems
/// </summary>
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] //This test is platform specific for Windows
public void ConcurrentProjectOpenAndCloseThroughProject()
{
int iterations = 500;
string[] paths = ObjectModelHelpers.GetTempFiles(iterations);
try
{
Project[] projects = new Project[iterations];
for (int i = 0; i < iterations; i++)
{
CreatePREWithSubstantialContent().Save(paths[i]);
}
var collection = new ProjectCollection();
int counter = 0;
int remaining = iterations;
var done = new ManualResetEvent(false);
for (int i = 0; i < iterations; i++)
{
ThreadPool.QueueUserWorkItem(delegate
{
var current = Interlocked.Increment(ref counter) - 1;
projects[current] = collection.LoadProject(paths[current]);
if (Interlocked.Decrement(ref remaining) == 0)
{
done.Set();
}
});
}
done.WaitOne();
Assert.Equal(iterations, collection.LoadedProjects.Count);
counter = 0;
remaining = iterations;
done.Reset();
for (int i = 0; i < iterations; i++)
{
ThreadPool.QueueUserWorkItem(delegate
{
var current = Interlocked.Increment(ref counter) - 1;
var pre = projects[current].Xml;
collection.UnloadProject(projects[current]);
collection.UnloadProject(pre);
if (Interlocked.Decrement(ref remaining) == 0)
{
done.Set();
}
});
}
done.WaitOne();
Assert.Empty(collection.LoadedProjects);
}
finally
{
for (int i = 0; i < iterations; i++)
{
File.Delete(paths[i]);
}
}
}
/// <summary>
/// Open lots of projects concurrently to try to trigger problems
/// </summary>
[Fact]
public void ConcurrentProjectOpenAndCloseThroughProjectRootElement()
{
int iterations = 500;
string[] paths = ObjectModelHelpers.GetTempFiles(iterations);
try
{
var projects = new ProjectRootElement[iterations];
var collection = new ProjectCollection();
int counter = 0;
int remaining = iterations;
var done = new ManualResetEvent(false);
for (int i = 0; i < iterations; i++)
{
ThreadPool.QueueUserWorkItem(delegate
{
var current = Interlocked.Increment(ref counter) - 1;
CreatePREWithSubstantialContent().Save(paths[current]);
projects[current] = ProjectRootElement.Open(paths[current], collection);
if (Interlocked.Decrement(ref remaining) == 0)
{
done.Set();
}
});
}
done.WaitOne();
counter = 0;
remaining = iterations;
done.Reset();
for (int i = 0; i < iterations; i++)
{
ThreadPool.QueueUserWorkItem(delegate
{
var current = Interlocked.Increment(ref counter) - 1;
collection.UnloadProject(projects[current]);
if (Interlocked.Decrement(ref remaining) == 0)
{
done.Set();
}
});
}
done.WaitOne();
}
finally
{
for (int i = 0; i < iterations; i++)
{
File.Delete(paths[i]);
}
}
}
/// <summary>
/// Tests DeepClone and CopyFrom for ProjectRootElements.
/// </summary>
[Fact]
public void DeepClone()
{
var pre = ProjectRootElement.Create();
var pg = pre.AddPropertyGroup();
pg.AddProperty("a", "$(b)");
pg.AddProperty("c", string.Empty);
var ig = pre.AddItemGroup();
var item = ig.AddItem("Foo", "boo$(hoo)");
item.AddMetadata("Some", "Value");
var target = pre.AddTarget("SomeTarget");
target.Condition = "Some Condition";
var task = target.AddTask("SomeTask");
task.AddOutputItem("p1", "it");
task.AddOutputProperty("prop", "it2");
target.AppendChild(pre.CreateOnErrorElement("someTarget"));
var idg = pre.AddItemDefinitionGroup();
var id = idg.AddItemDefinition("SomeType");
id.AddMetadata("sm", "sv");
pre.AddUsingTask("name", "assembly", null);
var inlineUt = pre.AddUsingTask("anotherName", "somefile", null);
inlineUt.TaskFactory = "SomeFactory";
inlineUt.AddUsingTaskBody("someEvaluate", "someTaskBody");
var choose = pre.CreateChooseElement();
pre.AppendChild(choose);
var when1 = pre.CreateWhenElement("some condition");
choose.AppendChild(when1);
when1.AppendChild(pre.CreatePropertyGroupElement());
var otherwise = pre.CreateOtherwiseElement();
choose.AppendChild(otherwise);
otherwise.AppendChild(pre.CreateItemGroupElement());
var importGroup = pre.AddImportGroup();
importGroup.AddImport("Some imported project");
pre.AddImport("direct import");
ValidateDeepCloneAndCopyFrom(pre);
}
/// <summary>
/// Tests DeepClone and CopyFrom for ProjectRootElement that contain ProjectExtensions with text inside.
/// </summary>
[Fact]
public void DeepCloneWithProjectExtensionsElementOfText()
{
var pre = ProjectRootElement.Create();
var extensions = pre.CreateProjectExtensionsElement();
extensions.Content = "Some foo content";
pre.AppendChild(extensions);
ValidateDeepCloneAndCopyFrom(pre);
}
/// <summary>
/// Tests DeepClone and CopyFrom for ProjectRootElement that contain ProjectExtensions with xml inside.
/// </summary>
[Fact]
public void DeepCloneWithProjectExtensionsElementOfXml()
{
var pre = ProjectRootElement.Create();
var extensions = pre.CreateProjectExtensionsElement();
extensions.Content = "<a><b/></a>";
pre.AppendChild(extensions);
ValidateDeepCloneAndCopyFrom(pre);
}
/// <summary>
/// Tests DeepClone and CopyFrom when there is metadata expressed as attributes
/// </summary>
[Fact]
public void DeepCloneWithMetadataAsAttributes()
{
var project =
@"<?xml version=`1.0` encoding=`utf-8`?>
<Project xmlns = 'msbuildnamespace'>
<ItemDefinitionGroup>
<Compile A=`a`/>
<B M1=`dv1`>
<M2>dv2</M2>
</B>
<C/>
</ItemDefinitionGroup>
<ItemGroup>
<Compile Include=`Class1.cs` A=`a` />
<Compile Include=`Class2.cs` />
</ItemGroup>
<PropertyGroup>
<P>val</P>
</PropertyGroup>
<Target Name=`Build`>
<ItemGroup>
<A Include=`a` />
<B Include=`b` M1=`v1`>
<M2>v2</M2>
</B>
<C Include=`c`/>
</ItemGroup>
</Target>
</Project>";
var pre = ProjectRootElement.Create(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(project))));
ValidateDeepCloneAndCopyFrom(pre);
}
/// <summary>
/// Tests TryOpen when preserveFormatting is the same and different than the cached project.
/// </summary>
[Fact]
public void TryOpenWithPreserveFormatting()
{
string project =
@"<?xml version=`1.0` encoding=`utf-8`?>
<Project xmlns = 'msbuildnamespace'>
</Project>";
using (var env = TestEnvironment.Create())
using (var projectCollection = new ProjectCollection())
{
var projectFiles = env.CreateTestProjectWithFiles("", new[] { "build.proj" });
var projectFile = projectFiles.CreatedFiles.First();
var projectXml = ProjectRootElement.Create(
XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(project))),
projectCollection,
preserveFormatting: true);
projectXml.Save(projectFile);
var xml0 = ProjectRootElement.TryOpen(projectXml.FullPath, projectCollection, preserveFormatting: true);
Assert.True(xml0.PreserveFormatting);
var xml1 = ProjectRootElement.TryOpen(projectXml.FullPath, projectCollection, preserveFormatting: false);
Assert.False(xml1.PreserveFormatting);
var xml2 = ProjectRootElement.TryOpen(projectXml.FullPath, projectCollection, preserveFormatting: null);
// reuses existing setting
Assert.False(xml2.PreserveFormatting);
Assert.NotNull(xml0);
Assert.Same(xml0, xml1);
Assert.Same(xml0, xml2);
}
}
[Theory]
[InlineData(true, false, false)]
[InlineData(true, true, true)]
[InlineData(false, false, false)]
[InlineData(false, true, true)]
[InlineData(true, null, true)]
[InlineData(false, null, false)]
public void ReloadCanSpecifyPreserveFormatting(bool initialPreserveFormatting, bool? reloadShouldPreserveFormatting, bool expectedFormattingAfterReload)
{
using (var env = TestEnvironment.Create())
{
var testFiles = env.CreateTestProjectWithFiles("", new[] { "build.proj" });
var projectFile = testFiles.CreatedFiles.First();
var projectElement = ObjectModelHelpers.CreateInMemoryProjectRootElement(SimpleProject, null, initialPreserveFormatting);
projectElement.Save(projectFile);
Assert.Equal(initialPreserveFormatting, projectElement.PreserveFormatting);
projectElement.Reload(false, reloadShouldPreserveFormatting);
Assert.Equal(expectedFormattingAfterReload, projectElement.PreserveFormatting);
// reset project to original preserve formatting
projectElement.Reload(false, initialPreserveFormatting);
Assert.Equal(initialPreserveFormatting, projectElement.PreserveFormatting);
projectElement.ReloadFrom(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(SimpleProject))), false, reloadShouldPreserveFormatting);
Assert.Equal(expectedFormattingAfterReload, projectElement.PreserveFormatting);
// reset project to original preserve formatting
projectElement.Reload(false, initialPreserveFormatting);
Assert.Equal(initialPreserveFormatting, projectElement.PreserveFormatting);
projectElement.ReloadFrom(projectFile, false, reloadShouldPreserveFormatting);
Assert.Equal(expectedFormattingAfterReload, projectElement.PreserveFormatting);
}
}
[Theory]
// same content should still dirty the project
[InlineData(
SimpleProject,
SimpleProject,
true, false, false)]
// new comment
[InlineData(
@"<Project xmlns=`msbuildnamespace`>
<PropertyGroup>
<P>property value</P>
</PropertyGroup>
<ItemGroup>
<i Include=`a`>
<m>metadata value</m>
</i>
</ItemGroup>
</Project>",
@"
<!-- new comment -->
<Project xmlns=`msbuildnamespace`>
<PropertyGroup>
<P><!-- new comment -->property value<!-- new comment --></P>
</PropertyGroup>
<!-- new comment -->
<ItemGroup>
<i Include=`a`>
<!-- new comment -->
<m>metadata value</m>
</i>
</ItemGroup>
</Project>",
true, false, true)]
// changed comment
[InlineData(
@"
<!-- new comment -->
<Project xmlns=`msbuildnamespace`>
<PropertyGroup>
<P><!-- new comment -->property value<!-- new comment --></P>
</PropertyGroup>
<!-- new comment -->
<ItemGroup>
<i Include=`a`>
<!-- new comment -->
<m>metadata value</m>
</i>
</ItemGroup>
</Project>",
@"
<!-- changed comment -->
<Project xmlns=`msbuildnamespace`>
<PropertyGroup>
<P><!-- changed comment -->property value<!-- changed comment --></P>
</PropertyGroup>
<!-- changed comment -->
<ItemGroup>
<i Include=`a`>
<!-- changed comment -->
<m>metadata value</m>
</i>
</ItemGroup>
</Project>",
true, false, true)]
// deleted comment
[InlineData(
@"
<!-- new comment -->
<Project xmlns=`msbuildnamespace`>
<PropertyGroup>
<P><!-- new comment -->property value<!-- new comment --></P>
</PropertyGroup>
<!-- new comment -->
<ItemGroup>
<i Include=`a`>
<!-- new comment -->
<m>metadata value</m>
</i>
</ItemGroup>
</Project>",
@"
<Project xmlns=`msbuildnamespace`>
<PropertyGroup>
<P>property value</P>
</PropertyGroup>
<ItemGroup>
<i Include=`a`>
<m>metadata value</m>
</i>
</ItemGroup>
</Project>",
true, false, true)]
// new comments and changed code
[InlineData(
@"<Project xmlns=`msbuildnamespace`>
<PropertyGroup>
<P>property value</P>
</PropertyGroup>
<ItemGroup>
<i Include=`a`>
<m>metadata value</m>
</i>
</ItemGroup>
</Project>",
@"
<!-- new comment -->
<Project xmlns=`msbuildnamespace`>
<PropertyGroup>
<P>property value</P>
<P2><!-- new comment -->property value<!-- new comment --></P2>
</PropertyGroup>
</Project>",
true, true, true)]
// commented out code
[InlineData(
@"<Project xmlns=`msbuildnamespace`>
<PropertyGroup>
<P>property value</P>
</PropertyGroup>
<ItemGroup>
<i Include=`a`>
<m>metadata value</m>
</i>
</ItemGroup>
</Project>",
@"<Project xmlns=`msbuildnamespace`>
<PropertyGroup>
<P>property value</P>
</PropertyGroup>
<!--
<ItemGroup>
<i Include=`a`>
<m>metadata value</m>
</i>
</ItemGroup>
-->
</Project>",
true, true, true)]
public void ReloadRespectsNewContents(string initialProjectContents, string changedProjectContents, bool versionChanged, bool msbuildChildrenChanged, bool xmlChanged)
{
Action<ProjectRootElement, string> act = (p, c) =>
{
p.ReloadFrom(
XmlReader.Create(new StringReader(c)),
throwIfUnsavedChanges: false);
};
AssertReload(initialProjectContents, changedProjectContents, versionChanged, msbuildChildrenChanged, xmlChanged, act);
}
[Fact]
public void ReloadedStateIsResilientToChangesAndDiskRoundtrip()
{
var initialProjectContents = ObjectModelHelpers.CleanupFileContents(
@"
<!-- new comment -->
<Project xmlns=`msbuildnamespace`>
<!-- new comment -->
<ItemGroup>
<i Include=`a`>
<!-- new comment -->
<m>metadata value</m>
</i>
</ItemGroup>
</Project>");
var changedProjectContents1 = ObjectModelHelpers.CleanupFileContents(
@"
<!-- changed comment -->
<Project xmlns=`msbuildnamespace`>
<!-- changed comment -->
<ItemGroup>
<i Include=`a`>
<!-- changed comment -->
<m>metadata value</m>
</i>
</ItemGroup>
</Project>");
var changedProjectContents2 = ObjectModelHelpers.CleanupFileContents(
// spurious comment placement issue: https://github.com/Microsoft/msbuild/issues/1503
@"
<!-- changed comment -->
<Project xmlns=`msbuildnamespace`>
<!-- changed comment -->
<PropertyGroup>
<P>v</P>
</PropertyGroup>
<ItemGroup>
<i Include=`a`>
<!-- changed comment -->
<m>metadata value</m>
</i>
</ItemGroup>
</Project>");
using (var env = TestEnvironment.Create())
{
var projectCollection1 = env.CreateProjectCollection().Collection;
var projectCollection2 = env.CreateProjectCollection().Collection;
var testFiles = env.CreateTestProjectWithFiles("", new[] { "build.proj" });
var projectPath = testFiles.CreatedFiles.First();
var projectElement = ObjectModelHelpers.CreateInMemoryProjectRootElement(initialProjectContents, projectCollection1, preserveFormatting: true);
projectElement.Save(projectPath);
projectElement.ReloadFrom(XmlReader.Create(new StringReader(changedProjectContents1)));
VerifyAssertLineByLine(changedProjectContents1, projectElement.RawXml);
projectElement.AddProperty("P", "v");
VerifyAssertLineByLine(changedProjectContents2, projectElement.RawXml);
projectElement.Save();
var projectElement2 = ProjectRootElement.Open(projectPath, projectCollection2, preserveFormatting: true);
VerifyAssertLineByLine(changedProjectContents2, projectElement2.RawXml);
}
}
[Fact]
public void ReloadThrowsOnInvalidXmlSyntax()
{
var missingClosingTag =
@"<Project xmlns=`msbuildnamespace`>
<PropertyGroup>
<P>property value</P>
</PropertyGroup>
<ItemGroup>
<i Include=`a`>
<m>metadata value<m>
</i>
</ItemGroup>
</Project>";
Action<ProjectRootElement, string> act = (p, c) =>
{
var exception =
Assert.Throws<InvalidProjectFileException>(
() =>
p.ReloadFrom(
XmlReader.Create(
new StringReader(c)),
throwIfUnsavedChanges: false));
Assert.Contains(@"The project file could not be loaded. The 'm' start tag on line", exception.Message);
};
// reload does not mutate the project element
AssertReload(SimpleProject, missingClosingTag, false, false, false, act);
}
[Fact]
public void ReloadThrowsForInMemoryProjectsWithoutAPath()
{
Action<ProjectRootElement, string> act = (p, c) =>
{
var exception =
Assert.Throws<InvalidOperationException>(
() =>
p.Reload(throwIfUnsavedChanges: false));
Assert.Contains(@"Value not set:", exception.Message);
};
// reload does not mutate the project element
AssertReload(SimpleProject, ComplexProject, false, false, false, act);
}
[Fact]
public void ReloadFromAPathThrowsOnMissingPath()
{
Action<ProjectRootElement, string> act = (p, c) =>
{
var fullPath = Path.GetFullPath("foo");
var exception =
Assert.Throws<InvalidOperationException>(
() =>
p.ReloadFrom(fullPath, throwIfUnsavedChanges: false));
Assert.Contains(@"File to reload from does not exist:", exception.Message);
};
// reload does not mutate the project element
AssertReload(SimpleProject, ComplexProject, false, false, false, act);
}
[Fact]
public void ReloadFromMemoryWhenProjectIsInMemoryKeepsProjectFileEmpty()
{
AssertProjectFileAfterReload(
true,
true,
(initial, reload, actualFile) => { Assert.Equal(String.Empty, actualFile); });
}
[Fact]
public void ReloadFromMemoryWhenProjectIsInFileKeepsProjectFile()
{
AssertProjectFileAfterReload(
false,
true,
(initial, reload, actualFile) => { Assert.Equal(initial, actualFile); });
}
[Fact]
public void ReloadFromFileWhenProjectIsInMemorySetsProjectFile()
{
AssertProjectFileAfterReload(
true,
false,
(initial, reload, actualFile) => { Assert.Equal(reload, actualFile);});
}
[Fact]
public void ReloadFromFileWhenProjectIsInFileUpdatesProjectFile()
{
AssertProjectFileAfterReload(
false,
false,
(initial, reload, actualFile) => { Assert.Equal(reload, actualFile); });
}
private void AssertProjectFileAfterReload(
bool initialProjectFromMemory,
bool reloadProjectFromMemory,
Action<string, string, string> projectFileAssert)
{
using (var env = TestEnvironment.Create())
{
var projectCollection = env.CreateProjectCollection().Collection;
string initialLocation = null;
ProjectRootElement rootElement = null;
if (initialProjectFromMemory)
{
rootElement = ObjectModelHelpers.CreateInMemoryProjectRootElement(SimpleProject, projectCollection);
}
else
{
initialLocation = env.CreateFile().Path;
File.WriteAllText(initialLocation, ObjectModelHelpers.CleanupFileContents(SimpleProject));
rootElement = ProjectRootElement.Open(initialLocation, projectCollection);
}
var project = new Project(rootElement, null, null, projectCollection);
string reloadLocation = null;
if (reloadProjectFromMemory)
{
rootElement.ReloadFrom(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(ComplexProject))), false);
}
else
{
reloadLocation = env.CreateFile().Path;
File.WriteAllText(reloadLocation, ObjectModelHelpers.CleanupFileContents(ComplexProject));
rootElement.ReloadFrom(reloadLocation, false);
}
project.ReevaluateIfNecessary();
projectFileAssert.Invoke(initialLocation, reloadLocation, EmptyIfNull(rootElement.FullPath));
projectFileAssert.Invoke(initialLocation, reloadLocation, rootElement.ProjectFileLocation.File);
projectFileAssert.Invoke(initialLocation, reloadLocation, rootElement.AllChildren.Last().Location.File);
projectFileAssert.Invoke(initialLocation, reloadLocation, project.GetPropertyValue("ProjectFile"));
projectFileAssert.Invoke(initialLocation, reloadLocation, project.GetPropertyValue("ThisFile"));
if (initialProjectFromMemory && reloadProjectFromMemory)
{
Assert.Equal(NativeMethodsShared.GetCurrentDirectory(), rootElement.DirectoryPath);
}
else
{
projectFileAssert.Invoke(Path.GetDirectoryName(initialLocation), Path.GetDirectoryName(reloadLocation), rootElement.DirectoryPath);
}
}
}
private static string EmptyIfNull(string aString) => aString ?? string.Empty;
[Fact]
public void ReloadThrowsOnInvalidMsBuildSyntax()
{
var unknownAttribute =
@"<Project xmlns=`msbuildnamespace`>
<PropertyGroup Foo=`bar`>
<P>property value</P>
</PropertyGroup>
<ItemGroup>
<i Include=`a`>
<m>metadata value</m>
</i>
</ItemGroup>
</Project>";
Action<ProjectRootElement, string> act = (p, c) =>
{
var exception =
Assert.Throws<InvalidProjectFileException>(
() =>
p.ReloadFrom(
XmlReader.Create(
new StringReader(c)),
throwIfUnsavedChanges: false));
Assert.Contains(@"The attribute ""Foo"" in element <PropertyGroup> is unrecognized", exception.Message);
};
// reload does not mutate the project element
AssertReload(SimpleProject, unknownAttribute, false, false, false, act);
}
[Fact]
public void ReloadThrowsByDefaultIfThereAreUnsavedChanges()
{
Action<ProjectRootElement, string> act = (p, c) =>
{
var exception =
Assert.Throws<InvalidOperationException>(
() =>
p.ReloadFrom(
XmlReader.Create(
new StringReader(c))));
Assert.Contains(@"ProjectRootElement can't reload if it contains unsaved changes.", exception.Message);
};
// reload does not mutate the project element
AssertReload(SimpleProject, ComplexProject, false, false, false, act);
}
[Fact]
public void ReloadCanOverwriteUnsavedChanges()
{
Action<ProjectRootElement, string> act = (p, c) =>
{
p.ReloadFrom(
XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(c))),
throwIfUnsavedChanges: false);
};
AssertReload(SimpleProject, ComplexProject, true, true, true, act);
}
private void AssertReload(
string initialContents,
string changedContents,
bool versionChanged,
bool msbuildChildrenChanged,
bool xmlChanged,
Action<ProjectRootElement, string> act)
{
var projectElement = ObjectModelHelpers.CreateInMemoryProjectRootElement(initialContents);
var version = projectElement.Version;
var childrenCount = projectElement.AllChildren.Count();
var xml = projectElement.RawXml;
Assert.True(projectElement.HasUnsavedChanges);
act(projectElement, ObjectModelHelpers.CleanupFileContents(changedContents));
if (versionChanged)
{
Assert.NotEqual(version, projectElement.Version);
}
else
{
Assert.Equal(version, projectElement.Version);
}
if (msbuildChildrenChanged)
{
Assert.NotEqual(childrenCount, projectElement.AllChildren.Count());
}
else
{
Assert.Equal(childrenCount, projectElement.AllChildren.Count());
}
if (xmlChanged)
{
Assert.NotEqual(xml, projectElement.RawXml);
}
else
{
Assert.Equal(xml, projectElement.RawXml);
}
}
/// <summary>
/// Test helper for validating that DeepClone and CopyFrom work as advertised.
/// </summary>
private static void ValidateDeepCloneAndCopyFrom(ProjectRootElement pre)
{
var pre2 = pre.DeepClone();
Assert.NotSame(pre2, pre);
Assert.Equal(pre.RawXml, pre2.RawXml);
var pre3 = ProjectRootElement.Create();
pre3.AddPropertyGroup(); // this should get wiped out in the DeepCopyFrom
pre3.DeepCopyFrom(pre);
Assert.Equal(pre.RawXml, pre3.RawXml);
}
/// <summary>
/// Re-saves a project with a new encoding and thoroughly verifies that the right things happen.
/// </summary>
private void SaveProjectWithEncoding(string projectFullPath, Encoding encoding)
{
// Always use a new project collection to guarantee we're reading off disk.
ProjectRootElement project = ProjectRootElement.Open(projectFullPath, new ProjectCollection());
project.Save(encoding);
Assert.Equal(encoding, project.Encoding); // "Changing an unmodified project's encoding failed to update ProjectRootElement.Encoding."
// Try to verify that the xml declaration was emitted, and that the correct byte order marks
// are also present.
using (var reader = FileUtilities.OpenRead(projectFullPath, encoding, true))
{
Assert.Equal(encoding, reader.CurrentEncoding);
string actual = reader.ReadLine();
string expected = string.Format(@"<?xml version=""1.0"" encoding=""{0}""?>", encoding.WebName);
Assert.Equal(expected, actual); // "The encoding was not emitted as an XML declaration."
}
project = ProjectRootElement.Open(projectFullPath, new ProjectCollection());
// It's ok for the read Encoding to differ in fields like DecoderFallback,
// so a pure equality check here is too much.
Assert.Equal(encoding.CodePage, project.Encoding.CodePage);
Assert.Equal(encoding.EncodingName, project.Encoding.EncodingName);
}
/// <summary>
/// Creates a project at a given path with a given encoding but without the Xml declaration,
/// and then verifies that when loaded by MSBuild, the encoding is correctly reported.
/// </summary>
private void VerifyLoadedProjectHasEncoding(string projectFullPath, Encoding encoding)
{
CreateProjectWithEncodingWithoutDeclaration(projectFullPath, encoding);
// Let's just be certain the project has been read off disk...
ProjectRootElement project = ProjectRootElement.Open(projectFullPath, new ProjectCollection());
Assert.Equal(encoding.WebName, project.Encoding.WebName);
}
/// <summary>
/// Creates a project file with a specific encoding, but without an XML declaration.
/// </summary>
private void CreateProjectWithEncodingWithoutDeclaration(string projectFullPath, Encoding encoding)
{
const string EmptyProject = @"<Project DefaultTargets=""Build"" ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
</Project>";
using (StreamWriter writer = FileUtilities.OpenWrite(projectFullPath, false, encoding))
{
writer.Write(ObjectModelHelpers.CleanupFileContents(EmptyProject));
}
}
/// <summary>
/// Create a nice big PRE
/// </summary>
private ProjectRootElement CreatePREWithSubstantialContent()
{
string content = ObjectModelHelpers.CleanupFileContents(ComplexProject);
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
return project;
}
private void VerifyAssertLineByLine(string expected, string actual)
{
Helpers.VerifyAssertLineByLine(expected, actual, false);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace NPoco
{
public class SqlBuilder
{
Dictionary<string, Clauses> data = new Dictionary<string, Clauses>();
int seq;
class Clause
{
public string Sql { get; set; }
public string ResolvedSql { get; set; }
public List<object> Parameters { get; set; }
}
class Clauses : List<Clause>
{
string joiner;
string prefix;
string postfix;
public Clauses(string joiner, string prefix, string postfix)
{
this.joiner = joiner;
this.prefix = prefix;
this.postfix = postfix;
}
public string ResolveClauses(List<object> finalParams)
{
foreach (var item in this)
{
item.ResolvedSql = ParameterHelper.ProcessParams(item.Sql, item.Parameters.ToArray(), finalParams);
}
return prefix + string.Join(joiner, this.Select(c => c.ResolvedSql).ToArray()) + postfix;
}
}
public class Template
{
public bool TokenReplacementRequired { get; set; }
readonly string sql;
readonly SqlBuilder builder;
private List<object> finalParams = new List<object>();
int dataSeq;
public Template(SqlBuilder builder, string sql, params object[] parameters)
{
this.sql = ParameterHelper.ProcessParams(sql, parameters, finalParams);
this.builder = builder;
}
static Regex regex = new Regex(@"\/\*\*.+\*\*\/", RegexOptions.Compiled | RegexOptions.Multiline);
void ResolveSql()
{
if (dataSeq != builder.seq)
{
rawSql = sql;
foreach (var pair in builder.data)
{
rawSql = rawSql.Replace("/**" + pair.Key + "**/", pair.Value.ResolveClauses(finalParams));
}
ReplaceDefaults();
dataSeq = builder.seq;
}
if (builder.seq == 0)
{
rawSql = sql;
ReplaceDefaults();
}
}
private void ReplaceDefaults()
{
foreach (var pair in builder.defaultsIfEmpty)
{
var fullToken = "/**" + pair.Key + "**/";
if (TokenReplacementRequired)
{
if (rawSql.Contains(fullToken))
{
throw new Exception(string.Format("Token '{0}' not used. All tokens must be replaced if TokenReplacementRequired switched on.", fullToken));
}
}
rawSql = rawSql.Replace(fullToken, " " + pair.Value + " ");
}
// replace all that is left with empty
rawSql = regex.Replace(rawSql, "");
}
string rawSql;
public string RawSql { get { ResolveSql(); return rawSql; } }
public object[] Parameters { get { ResolveSql(); return finalParams.ToArray(); } }
}
public SqlBuilder()
{
}
public Template AddTemplate(string sql, params object[] parameters)
{
return new Template(this, sql, parameters);
}
void AddClause(string name, string sql, object[] parameters, string joiner, string prefix, string postfix)
{
Clauses clauses;
if (!data.TryGetValue(name, out clauses))
{
clauses = new Clauses(joiner, prefix, postfix);
data[name] = clauses;
}
clauses.Add(new Clause { Sql = sql, Parameters = new List<object>(parameters) });
seq++;
}
readonly Dictionary<string, string> defaultsIfEmpty = new Dictionary<string, string>
{
{ "where", "1=1" },
{ "select", "1" }
};
/// <summary>
/// Replaces the Select columns. Uses /**select**/
/// </summary>
public SqlBuilder Select(params string[] columns)
{
AddClause("select", string.Join(", ", columns), new object[] { }, ", ", "", "");
return this;
}
/// <summary>
/// Adds an Inner Join. Uses /**join**/
/// </summary>
public SqlBuilder Join(string sql, params object[] parameters)
{
AddClause("join", sql, parameters, "\nINNER JOIN ", "\nINNER JOIN ", "\n");
return this;
}
/// <summary>
/// Adds a Left Join. Uses /**leftjoin**/
/// </summary>
public SqlBuilder LeftJoin(string sql, params object[] parameters)
{
AddClause("leftjoin", sql, parameters, "\nLEFT JOIN ", "\nLEFT JOIN ", "\n");
return this;
}
/// <summary>
/// Adds a filter. The Where keyword still needs to be specified. Uses /**where**/
/// </summary>
public SqlBuilder Where(string sql, params object[] parameters)
{
AddClause("where", sql, parameters, " AND ", " ( ", " )\n");
return this;
}
/// <summary>
/// Adds an Order By clause. Uses /**orderby**/
/// </summary>
public SqlBuilder OrderBy(string sql, params object[] parameters)
{
AddClause("orderby", sql, parameters, ", ", "ORDER BY ", "\n");
return this;
}
/// <summary>
/// Adds columns in the Order By clause. Uses /**orderbycols**/
/// </summary>
public SqlBuilder OrderByCols(params string[] columns)
{
AddClause("orderbycols", string.Join(", ", columns), new object[] { }, ", ", ", ", "");
return this;
}
/// <summary>
/// Adds a Group By clause. Uses /**groupby**/
/// </summary>
public SqlBuilder GroupBy(string sql, params object[] parameters)
{
AddClause("groupby", sql, parameters, " , ", "\nGROUP BY ", "\n");
return this;
}
/// <summary>
/// Adds a Having clause. Uses /**having**/
/// </summary>
public SqlBuilder Having(string sql, params object[] parameters)
{
AddClause("having", sql, parameters, "\nAND ", "HAVING ", "\n");
return this;
}
}
}
| |
namespace RepositoryLayer.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class InitalRepositoryTables : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.AccessDetails",
c => new
{
Id = c.Int(nullable: false, identity: true),
AccessToken = c.String(),
AccessTokenSecret = c.String(),
UpdateDateTime = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"),
Expires_in = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"),
Refresh_token = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.AccSettings",
c => new
{
Id = c.Int(nullable: false, identity: true),
Language = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.SuperTargetUsers",
c => new
{
Id = c.Int(nullable: false, identity: true),
AccSettingId = c.Int(nullable: false),
UserName = c.String(),
SMId = c.String(),
Followers = c.Int(nullable: false),
IsBlocked = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AccSettings", t => t.AccSettingId, cascadeDelete: true)
.Index(t => t.AccSettingId);
CreateTable(
"dbo.Tags",
c => new
{
Id = c.Int(nullable: false, identity: true),
AccSettingId = c.Int(nullable: false),
TagName = c.String(),
Location = c.String(),
IsBlocked = c.Boolean(nullable: false),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AccSettings", t => t.AccSettingId, cascadeDelete: true)
.Index(t => t.AccSettingId);
CreateTable(
"dbo.UserManagements",
c => new
{
Id = c.Int(nullable: false, identity: true),
AccSettingId = c.Int(nullable: false),
userId = c.String(),
Email = c.String(),
Role = c.String(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AccSettings", t => t.AccSettingId, cascadeDelete: true)
.Index(t => t.AccSettingId);
CreateTable(
"dbo.Activities",
c => new
{
Id = c.Int(nullable: false, identity: true),
Tag = c.String(),
socialId = c.Int(nullable: false),
SMId = c.String(),
PostId = c.String(),
OriginalPostId = c.String(),
Username = c.String(),
Activity = c.String(),
UserType = c.String(),
ActivityDate = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.BusinessCategories",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Conversions",
c => new
{
Id = c.Int(nullable: false, identity: true),
SMId = c.String(),
Username = c.String(),
socialId = c.Int(nullable: false),
Tag = c.String(),
ConvertDate = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.FollowersGraphs",
c => new
{
Id = c.Int(nullable: false, identity: true),
SocialId = c.Int(nullable: false),
Date = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"),
Followers = c.Int(nullable: false),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.InstagramLocations",
c => new
{
Id = c.Int(nullable: false, identity: true),
SocialId = c.Int(nullable: false),
Location = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Languages",
c => new
{
Id = c.Int(nullable: false, identity: true),
Language = c.String(),
LangCode = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.OrderDetails",
c => new
{
Id = c.Int(nullable: false, identity: true),
UserId = c.String(),
Date = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"),
SubscriptionPlanId = c.String(),
Amount = c.String(),
TransactionId = c.String(),
PaymentMethod = c.String(),
InvoiceId = c.String(),
Currency = c.String(),
Status = c.String(),
SocialId = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.SocialMedias",
c => new
{
Id = c.Int(nullable: false, identity: true),
UserId = c.String(),
Provider = c.String(),
Status = c.Boolean(nullable: false),
Followers = c.Int(nullable: false),
SMId = c.String(),
UserName = c.String(),
ProfilepicUrl = c.String(),
IsDeleted = c.Boolean(nullable: false),
IsInvalid = c.Boolean(nullable: false),
AccessDetails_Id = c.Int(),
AccSettings_Id = c.Int(),
})
.PrimaryKey(t => t.Id)
.ForeignKey("dbo.AccessDetails", t => t.AccessDetails_Id)
.ForeignKey("dbo.AccSettings", t => t.AccSettings_Id)
.Index(t => t.AccessDetails_Id)
.Index(t => t.AccSettings_Id);
CreateTable(
"dbo.SubscriptionsPlans",
c => new
{
Id = c.Int(nullable: false, identity: true),
Title = c.String(),
Price = c.Double(nullable: false),
BillingFrequency = c.String(),
NoOfAccounts = c.String(),
LimitedTagService = c.Boolean(nullable: false),
LowSpeedOfInteraction = c.Boolean(nullable: false),
AllowSuperTargeting = c.Boolean(nullable: false),
AllowNegativeTags = c.Boolean(nullable: false),
TagLimit = c.String(),
IsDeleted = c.Boolean(nullable: false),
IsTrail = c.Boolean(nullable: false),
TrailDays = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.UserAccountSubscriptions",
c => new
{
Id = c.Int(nullable: false, identity: true),
userId = c.String(),
socialIds = c.String(),
ExpiresOn = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"),
PlanId = c.Int(nullable: false),
IsTrail = c.Boolean(nullable: false),
IsExpire = c.Boolean(nullable: false),
OrderId = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.UserBillingAddresses",
c => new
{
Id = c.Int(nullable: false, identity: true),
UserId = c.String(),
Name = c.String(),
Company = c.String(),
Address = c.String(),
PostalCode = c.String(),
Country = c.String(),
TaxId = c.String(),
})
.PrimaryKey(t => t.Id);
}
public override void Down()
{
DropForeignKey("dbo.SocialMedias", "AccSettings_Id", "dbo.AccSettings");
DropForeignKey("dbo.SocialMedias", "AccessDetails_Id", "dbo.AccessDetails");
DropForeignKey("dbo.UserManagements", "AccSettingId", "dbo.AccSettings");
DropForeignKey("dbo.Tags", "AccSettingId", "dbo.AccSettings");
DropForeignKey("dbo.SuperTargetUsers", "AccSettingId", "dbo.AccSettings");
DropIndex("dbo.SocialMedias", new[] { "AccSettings_Id" });
DropIndex("dbo.SocialMedias", new[] { "AccessDetails_Id" });
DropIndex("dbo.UserManagements", new[] { "AccSettingId" });
DropIndex("dbo.Tags", new[] { "AccSettingId" });
DropIndex("dbo.SuperTargetUsers", new[] { "AccSettingId" });
DropTable("dbo.UserBillingAddresses");
DropTable("dbo.UserAccountSubscriptions");
DropTable("dbo.SubscriptionsPlans");
DropTable("dbo.SocialMedias");
DropTable("dbo.OrderDetails");
DropTable("dbo.Languages");
DropTable("dbo.InstagramLocations");
DropTable("dbo.FollowersGraphs");
DropTable("dbo.Conversions");
DropTable("dbo.BusinessCategories");
DropTable("dbo.Activities");
DropTable("dbo.UserManagements");
DropTable("dbo.Tags");
DropTable("dbo.SuperTargetUsers");
DropTable("dbo.AccSettings");
DropTable("dbo.AccessDetails");
}
}
}
| |
// Kruskal's Minimum Spanning Tree Algorithm
// Union-find implemented using disjoint set trees
using System;
using System.IO;
// convert vertex into char for pretty printing
class Edge {
// missing code
public int u;
public int v;
public int wgt;
public void show()
{
Console.Write("Edge {0}-{1}-{2}\n",toChar(u), wgt, toChar(v)) ;
}
// convert vertex into char for pretty printing
private char toChar(int u)
{
return (char)(u + 64);
}
}
class Heap
{
private int[] h;
int N, Nmax;
Edge[] edge;
// Bottom up heap constructor
public Heap(int _N, Edge[] _edge)
{
int i;
Nmax = N = _N;
h = new int[N+1];
edge = _edge;
// initially just fill heap array with
// indices of edge[] array.
for (i=0; i <= N; ++i)
h[i] = i;
// Then convert h[] into a heap
// from the bottom up.
for(i = N/2; i >= 1; i--)
siftDown(i);
}
private void siftDown( int k)
{
int v, j;
v = h[k];
while(2 * k <= N)
{
j = 2*k;
if((j < N) && (edge[h[j+1]].wgt < edge[h[j]].wgt))
++j;
if(edge[v].wgt <= edge[h[j]].wgt)
break;
h[k] = h[j];
k = j;
}
h[k] = v;
}
public int remove()
{
h[0] = h[1];
h[1] = h[N--];
siftDown(1);
return h[0];
}
/*Method to display the content of heap
public void display()
{
Console.WriteLine("{0}", h[1]);
for(int i = 1; i <= N/2; i = i * 2) {
for(int j = 2*i; j < 4*i && j <= N; ++j)
Console.Write("{0} ", h[j]);
Console.Write("\n");
}
}*/
}
/****************************************************
*
* UnionFind partition to support union-find operations
* Implemented simply using Discrete Set Trees
*
*****************************************************/
class UnionFindSets
{
private int[] treeParent;
private int N;
public UnionFindSets( int V) //constructor;
{
N = V;
treeParent = new int[N+1];
for(int i = 1; i <= N; i++)
{
treeParent[i] = i;
}
}
public int findSet( int vertex)
{
while(vertex != treeParent[vertex])
{
vertex = treeParent[vertex];
}
return vertex;
}
public void union( int set1, int set2)
{
treeParent[set2] = set1;
}
public void showTrees()
{
int i;
for(i=1; i<=N; ++i)
Console.Write("{0}->{1} ", toChar(i), toChar(treeParent[i]));
Console.Write("\n");
}
public void showSets()
{
for(int i=1; i<=N; ++i)
{
int j = findSet(i);
Console.WriteLine("Element {0} in set {1} ", toChar(i), toChar(treeParent[j]));
}
Console.Write("\n");
}
private void showSet(int root)
{
Console.WriteLine("The set with root {0} contains the following elements: ", toChar(root));
for(int i=1; i<=N; ++i)
{
if(treeParent[i] == root)
Console.Write("{0} ",toChar(i));
}
Console.WriteLine();
}
private char toChar(int u)
{
return (char)(u + 64);
}
}
class Graph
{
private int V, E;
private Edge[] edge;
private Edge[] mst;
public Graph(string graphFile)
{
int u, v;
int w, e;
StreamReader reader = new StreamReader(graphFile);
char[] splits = new char[] { ' ', ',', '\t'};
string line = reader.ReadLine();
string[] parts = line.Split(splits, StringSplitOptions.RemoveEmptyEntries);
// find out number of vertices and edges
V = int.Parse(parts[0]);
E = int.Parse(parts[1]);
// create edge array
edge = new Edge[E+1];
// read the edges
Console.WriteLine("Reading edges from text file");
for(e = 1; e <= E; ++e)
{
line = reader.ReadLine();
parts = line.Split(splits, StringSplitOptions.RemoveEmptyEntries);
u = int.Parse(parts[0]);
v = int.Parse(parts[1]);
w = int.Parse(parts[2]);
Edge ed = new Edge();
ed.u = u;
ed.v = v;
ed.wgt = w;
edge[e] = ed;
Console.WriteLine("Edge {0}--({1})--{2}", toChar(u), w, toChar(v));
}
for(e = 1; e <= E; ++e)
{
Console.Write("\n edge[{0}] = {1}, {2}, {3} ", e, edge[e].u, edge[e].v, edge[e].wgt);
}
Console.Write("\n\n");
}
/**********************************************************
*
* Kruskal's minimum spanning tree algorithm
*
**********************************************************/
public Edge[] MST_Kruskal()
{
int ei, i = 0;
Edge e;
int uSet, vSet;
UnionFindSets partition;
int wgt_sum = 0;
// create edge array to store MST
// Initially it has no edges.
mst = new Edge[V-1];
// priority queue for indices of array of edges
Heap h = new Heap(E, edge);
// create partition of singleton sets for the vertices
partition = new UnionFindSets(V);
partition.showSets();
//Comment this code out if you want to see what is inside the heap at each step
//Console.WriteLine("Heap content is:");
//h.display();
while(i < V-1)
{
ei = h.remove();
//I used the commented code to see how are elements removed from the heap each time
//Console.WriteLine("\nRemoving element {0} from heap", ei);
//h.display();
e = edge[ei];
uSet = partition.findSet(e.u);
vSet = partition.findSet(e.v);
if(uSet != vSet)
{
partition.union(uSet, vSet);
mst[i++] = e;
wgt_sum += e.wgt;
}
}
Console.WriteLine("Weight of MST is: {0}", wgt_sum);
return mst;
}
// convert vertex into char for pretty printing
private char toChar(int u)
{
return (char)(u + 64);
}
public void showMST()
{
Console.Write("\nMinimum spanning tree build from following edges:\n");
for(int e = 0; e < V-1; ++e)
{
mst[e].show();
}
Console.WriteLine();
}
// test code
public static int Main()
{
string fname = "wGraph3.txt";
//Console.Write("\nInput name of file with graph definition: ");
//fname = Console.ReadLine();
Graph g = new Graph(fname);
g.MST_Kruskal();
g.showMST();
return 0;
}
} // end of Graph class
| |
using Caliburn.Micro;
using csImb;
using csShared;
using csShared.Geo;
using csShared.Utils;
using ESRI.ArcGIS.Client;
using ESRI.ArcGIS.Client.Geometry;
using ESRI.ArcGIS.Client.Projection;
using ESRI.ArcGIS.Client.Symbols;
using IMB3;
using System;
using System.Collections.ObjectModel;
using System.Timers;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using System.Windows.Threading;
using PointCollection = ESRI.ArcGIS.Client.Geometry.PointCollection;
namespace csGeoLayers.MapTools.CameraTool
{
public class Camera : PropertyChangedBase
{
private const double Rad2Deg = 180.0 / Math.PI;
private readonly Timer _updateTimer = new Timer();
private readonly WebMercator webMercator = new WebMercator();
public GroupLayer Layer;
public Graphic Line;
public GraphicsLayer MLayer;
private TEventEntry _3d;
private Graphic _attachedFinish;
private Graphic _attachedStart;
private double _distance;
public Graphic _finish;
private string _firstMoveState;
private bool _firstMovement = true;
private string _lastMes;
private double _rotateFixAngle;
//private double _rotateFixDistance;
private string _rotateFixState;
private bool _rotating;
private string _rotatingState;
public Graphic _start;
private bool autoHeight = true;
private DispatcherTimer dtr;
public csPoint finishPoint;
public csPoint startPoint;
public AppStateSettings AppState
{
get { return AppStateSettings.Instance; }
}
public double Distance
{
get { return _distance; }
set
{
_distance = value;
NotifyOfPropertyChange(() => Distance);
}
}
public bool AutoHeight
{
get { return autoHeight; }
set
{
autoHeight = value;
NotifyOfPropertyChange(() => AutoHeight);
}
}
public bool RotateFix { get; set; }
public double GetDistance()
{
var p1 = webMercator.ToGeographic(startPoint.Mp) as MapPoint;
var p2 = webMercator.ToGeographic(finishPoint.Mp) as MapPoint;
if (p1 != null && p2 != null)
{
var pLon1 = p1.X;
var pLat1 = p1.Y;
var pLon2 = p2.X;
var pLat2 = p2.Y;
var dist = CoordinateUtils.Distance(pLat1, pLon1, pLat2, pLon2, 'K');
return dist; //Math.Sqrt((deltaX*deltaX) + (deltaY*deltaY));
}
return 0;
}
public void Init(GroupLayer gl, MapPoint start, MapPoint finish, ResourceDictionary rd)
{
startPoint = new csPoint
{
Mp = start
};
finishPoint = new csPoint
{
Mp = finish
};
MLayer = new GraphicsLayer
{
ID = Guid.NewGuid().ToString()
};
_start = new Graphic();
_finish = new Graphic();
Line = new Graphic();
var ls = new LineSymbol
{
Color = Brushes.Black,
Width = 4
};
Line.Symbol = ls;
UpdateLine();
MLayer.Graphics.Add(Line);
_start.Geometry = start;
_start.Symbol = rd["Start"] as Symbol;
_start.Attributes["position"] = start;
_start.Attributes["finish"] = _finish;
_start.Attributes["start"] = _start;
_start.Attributes["line"] = Line;
_start.Attributes["state"] = "start";
_start.Attributes["measure"] = this;
_start.Attributes["menuenabled"] = true;
MLayer.Graphics.Add(_start);
_finish.Geometry = finish;
_finish.Attributes["position"] = finish;
_finish.Symbol = rd["Finish"] as Symbol;
_finish.Attributes["finish"] = _finish;
_finish.Attributes["start"] = _start;
_finish.Attributes["line"] = Line;
_finish.Attributes["measure"] = this;
_finish.Attributes["state"] = "finish";
_finish.Attributes["menuenabled"] = true;
MLayer.Graphics.Add(_finish);
Layer.ChildLayers.Add(MLayer);
MLayer.Initialize();
AppStateSettings.Instance.ViewDef.MapManipulationDelta += ViewDef_MapManipulationDelta;
if (AppState.Imb != null && AppState.Imb.Imb != null)
{
_3d = AppState.Imb.Imb.Publish(AppState.Imb.Imb.ClientHandle + ".3d");
//AppState.Imb.Imb.Publish(_channel);
}
_updateTimer.Interval = 50;
_updateTimer.Elapsed += UpdateTimerElapsed;
_updateTimer.Start();
}
private void UpdateTimerElapsed(object sender, ElapsedEventArgs e)
{
if (AppState.Imb != null && AppState.Imb.IsConnected)
{
if (!string.IsNullOrEmpty(_lastMes)) _3d.SignalString(_lastMes);
}
_lastMes = "";
}
private void ViewDef_MapManipulationDelta(object sender, EventArgs e)
{
UpdateLine();
}
internal void UpdateLine()
{
var pl = new Polyline
{
Paths = new ObservableCollection<PointCollection>()
};
var pc = new PointCollection {
startPoint.Mp,
finishPoint.Mp
};
pl.Paths.Add(pc);
Line.Geometry = pl;
}
internal void Remove()
{
Layer.ChildLayers.Remove(MLayer);
StopRotation();
}
public void Attach(string state, Graphic g)
{
if (g == null) return;
_firstMovement = true;
_firstMoveState = state;
switch (state)
{
case "start":
_attachedStart = g;
UpdatePoint("start", _attachedStart.Geometry as MapPoint);
g.PropertyChanged += (e, s) =>
{
if (s.PropertyName == "Geometry" && _attachedStart != null)
{
UpdatePoint("start", _attachedStart.Geometry as MapPoint);
}
};
break;
case "finish":
_attachedFinish = g;
UpdatePoint("finish", _attachedFinish.Geometry as MapPoint);
g.PropertyChanged += (e, s) =>
{
if (s.PropertyName == "Geometry" && _attachedFinish != null)
{
UpdatePoint("finish", _attachedFinish.Geometry as MapPoint);
}
};
break;
}
}
public void FixRotation(string state)
{
_rotateFixState = state;
var sp = webMercator.ToGeographic(startPoint.Mp) as MapPoint;
var fp = webMercator.ToGeographic(finishPoint.Mp) as MapPoint;
RotateFix = true;
var c1 = AppStateSettings.Instance.ViewDef.MapPoint(new KmlPoint(sp.X, sp.Y));
var c2 = AppStateSettings.Instance.ViewDef.MapPoint(new KmlPoint(fp.X, fp.Y));
var angle = 360 - Angle(c1.X, c1.Y, c2.X, c2.Y);
_rotateFixAngle = angle % 360;
switch (state)
{
case "start":
var o = Convert.ToDouble(_attachedStart.Attributes.ContainsKey("Orientation"));
_attachedStart.AttributeValueChanged += (e, s) =>
{
if (_attachedStart.Attributes.ContainsKey("Orientation"))
{
var no = Convert.ToDouble(_attachedStart.Attributes["Orientation"]);
var na = (no - o) + _rotateFixAngle;
var d1 = Math.Abs(finishPoint.Mp.X - startPoint.Mp.X);
d1 = d1 * d1;
var d2 = Math.Abs(finishPoint.Mp.Y - startPoint.Mp.Y);
d2 = d2 * d2;
var d = Math.Sqrt(d1 + d2);
finishPoint.Mp.Y = startPoint.Mp.Y + (int)Math.Round(d * Math.Cos((na / 180) * Math.PI));
finishPoint.Mp.X = startPoint.Mp.X + (int)Math.Round(d * Math.Sin((na / 180) * Math.PI));
Console.WriteLine(d);
}
};
break;
}
}
internal void UpdatePoint(string state, MapPoint geometry)
{
if (_firstMovement)
{
if (string.IsNullOrEmpty(_firstMoveState))
{
_firstMoveState = state;
}
else if (_firstMoveState != state)
{
_firstMovement = false;
}
else
{
_firstMoveState = state;
}
}
switch (state)
{
case "start":
if (startPoint == null || _start == null) break;
if (_firstMovement)
{
finishPoint.Mp.X += geometry.X - startPoint.Mp.X;
finishPoint.Mp.Y += geometry.Y - startPoint.Mp.Y;
}
startPoint.Mp = geometry;
_start.Geometry = geometry;
break;
case "finish":
if (finishPoint == null || _finish == null) break;
if (_firstMovement)
{
startPoint.Mp.X += geometry.X - finishPoint.Mp.X;
startPoint.Mp.Y += geometry.Y - finishPoint.Mp.Y;
}
//_firstMovement = false;
finishPoint.Mp = geometry;
_finish.Geometry = geometry;
break;
}
UpdateLine();
Distance = GetDistance();
Send3DMessage();
}
public void Send3DMessage()
{
var wm = new WebMercator();
var p = new Pos3D();
var mpC = (MapPoint)wm.ToGeographic(finishPoint.Mp);
var mpD = (MapPoint)wm.ToGeographic(startPoint.Mp);
if (AutoHeight)
{
var d = SphericalMercator.Distance(mpC.Y, mpC.X, mpD.Y, mpD.X, 'K') * 100; // distance in km times 10.
finishPoint.Altitude = 2 + d * d * 0.15;
//finishPoint.Altitude = Math.Max(res*res*100, 0);
startPoint.Altitude = 0;
}
p.Camera = new Point3D(mpC.X, mpC.Y, finishPoint.Altitude);
p.Destination = new Point3D(mpD.X, mpD.Y, startPoint.Altitude);
_lastMes = p.ToString();
}
public double Angle(double px1, double py1, double px2, double py2)
{
// Negate X and Y values
var pxRes = px2 - px1;
var pyRes = py2 - py1;
double angle;
// Calculate the angle
if (pxRes == 0.0)
{
if (pxRes == 0.0)
angle = 0.0;
else if (pyRes > 0.0) angle = Math.PI / 2.0;
else
angle = Math.PI * 3.0 / 2.0;
}
else if (pyRes == 0.0)
{
angle = pxRes > 0.0
? 0.0
: Math.PI;
}
else
{
if (pxRes < 0.0)
angle = Math.Atan(pyRes / pxRes) + Math.PI;
else if (pyRes < 0.0) angle = Math.Atan(pyRes / pxRes) + (2 * Math.PI);
else
angle = Math.Atan(pyRes / pxRes);
}
// Convert to degrees
angle = angle * 180 / Math.PI;
return angle;
}
private void dtr_Tick(object sender, EventArgs e)
{
if (_rotating)
{
_firstMovement = false;
switch (_rotatingState)
{
case "start":
var angles = Angle(startPoint.Mp.X, startPoint.Mp.Y, finishPoint.Mp.X, finishPoint.Mp.Y);
var deltaXs = startPoint.Mp.X - finishPoint.Mp.X;
var deltaYs = startPoint.Mp.Y - finishPoint.Mp.Y;
var distances = Math.Sqrt((deltaXs * deltaXs) + (deltaYs * deltaYs));
angles += 1;
angles = ((angles - 180) / 360) * 2 * Math.PI;
var ys = (int)Math.Round(finishPoint.Mp.Y + distances * Math.Sin(angles));
;
var xs = (int)Math.Round(finishPoint.Mp.X + distances * Math.Cos(angles));
UpdatePoint("start", new MapPoint(xs, ys));
break;
case "finish":
var angle = Angle(finishPoint.Mp.X, finishPoint.Mp.Y, startPoint.Mp.X, startPoint.Mp.Y);
var deltaX = startPoint.Mp.X - finishPoint.Mp.X;
var deltaY = startPoint.Mp.Y - finishPoint.Mp.Y;
var distance = Math.Sqrt((deltaX * deltaX) + (deltaY * deltaY));
angle += 1;
angle = ((angle - 180) / 360) * 2 * Math.PI;
var y = (int)Math.Round(startPoint.Mp.Y + distance * Math.Sin(angle));
;
var x = (int)Math.Round(startPoint.Mp.X + distance * Math.Cos(angle));
UpdatePoint("finish", new MapPoint(x, y));
break;
}
//MapPoint mp = new MapPoint(this.Position.X + 10, this.Position.Y + 10);
//UpdatePoint(_state, mp);
}
else
{
dtr.Stop();
}
}
internal void StopRotation()
{
_rotating = false;
}
internal void StartRotation(string state)
{
if (dtr != null && dtr.IsEnabled) dtr.Stop();
_rotatingState = state;
_rotating = true;
dtr = new DispatcherTimer();
dtr.Interval = new TimeSpan(0, 0, 0, 0, 100);
dtr.Tick += dtr_Tick;
dtr.Start();
}
internal void Detach(string _state)
{
_firstMoveState = null;
switch (_state)
{
case "start":
_attachedStart = null;
break;
case "finish":
_attachedFinish = null;
break;
}
}
}
}
| |
// 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;
using static System.Runtime.Intrinsics.X86.Sse;
using static System.Runtime.Intrinsics.X86.Sse2;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void InsertSingle1()
{
var test = new InsertVector128Test__InsertSingle1();
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();
// 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();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class InsertVector128Test__InsertSingle1
{
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(InsertVector128Test__InsertSingle1 testClass)
{
var result = Sse41.Insert(_fld1, _fld2, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private SimpleBinaryOpTest__DataTable<Single, Single, Single> _dataTable;
static InsertVector128Test__InsertSingle1()
{
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 InsertVector128Test__InsertSingle1()
{
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 SimpleBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse41.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse41.Insert(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse41.Insert(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
LoadVector128((Single*)(_dataTable.inArray2Ptr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse41.Insert(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
LoadVector128((Single*)(_dataTable.inArray2Ptr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse41).GetMethod(nameof(Sse41.Insert), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>), typeof(byte) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse41.Insert(
_clsVar1,
_clsVar2,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse41.Insert(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var right = LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse41.Insert(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var right = LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse41.Insert(left, right, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new InsertVector128Test__InsertSingle1();
var result = Sse41.Insert(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse41.Insert(_fld1, _fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse41.Insert(test._fld1, test._fld2, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), left);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.SingleToInt32Bits(result[0]) != BitConverter.SingleToInt32Bits(0.0f))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.SingleToInt32Bits(result[i]) != BitConverter.SingleToInt32Bits(left[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse41)}.{nameof(Sse41.Insert)}<Single>(Vector128<Single>, Vector128<Single>.1): {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 NullGuard;
public class SimpleClass
{
public SimpleClass()
{
}
// Why would anyone place an out parameter on a ctor?! I don't know, but I'll support your idiocy.
public SimpleClass(out string nonNullOutArg)
{
nonNullOutArg = null;
}
public SimpleClass(string nonNullArg, [AllowNull] string nullArg)
{
Console.WriteLine(nonNullArg + " " + nullArg);
}
public void SomeMethod(string nonNullArg, [AllowNull] string nullArg)
{
Console.WriteLine(nonNullArg);
}
public string NonNullProperty { get; set; }
[AllowNull]
public string NullProperty { get; set; }
public string PropertyAllowsNullGetButDoesNotAllowNullSet { [return: AllowNull] get; set; }
public string PropertyAllowsNullSetButDoesNotAllowNullGet { get; [param: AllowNull] set; }
public int? NonNullNullableProperty { get; set; }
public string MethodWithReturnValue(bool returnNull)
{
return returnNull ? null : "";
}
public void MethodWithRef(ref object returnNull)
{
}
public void MethodWithGeneric<T>(T returnNull)
{
}
public void MethodWithGenericRef<T>(ref T returnNull)
{
}
[return: AllowNull]
public string MethodAllowsNullReturnValue()
{
return null;
}
[CanBeNull]
public string MethodWithCanBeNullResult()
{
return null;
}
public void MethodWithOutValue(out string nonNullOutArg)
{
nonNullOutArg = null;
}
public void MethodWithAllowedNullOutValue([AllowNull]out string nonNullOutArg)
{
nonNullOutArg = null;
}
public void PublicWrapperOfPrivateMethod()
{
SomePrivateMethod(null);
}
void SomePrivateMethod(string x)
{
Console.WriteLine(x);
}
public void MethodWithTwoRefs(ref string first, ref string second)
{
}
public void MethodWithTwoOuts(out string first, out string second)
{
first = null;
second = null;
}
public void MethodWithOptionalParameter(string optional = null)
{
}
public void MethodWithOptionalParameterWithNonNullDefaultValue(string optional = "default")
{
}
public void MethodWithOptionalParameterWithNonNullDefaultValueButAllowNullAttribute([AllowNull] string optional = "default")
{
}
public void MethodWithGenericOut<T>(out T item)
{
item = default(T);
}
public T MethodWithGenericReturn<T>(bool returnNull)
{
return returnNull ? default(T) : Activator.CreateInstance<T>();
}
public object MethodWithOutAndReturn(out string prefix)
{
prefix = null;
return null;
}
public void MethodWithExistingArgumentGuard(string x)
{
if (string.IsNullOrEmpty(x))
throw new ArgumentException("x is null or empty.", "x");
Console.WriteLine(x);
}
public void MethodWithExistingArgumentNullGuard(string x)
{
if (string.IsNullOrEmpty(x))
throw new ArgumentNullException("x");
Console.WriteLine(x);
}
public void MethodWithExistingArgumentNullGuardWithMessage(string x)
{
if (string.IsNullOrEmpty(x))
throw new ArgumentNullException("x", "x is null or empty.");
Console.WriteLine(x);
}
public string ReturnValueChecksWithBranchToRetInstruction()
{
// This is a regression test scenario for the "Branch to RET" issue described in https://github.com/Fody/NullGuard/issues/57.
// It is important that the return value is assinged *before* the branch, otherwise the C# compiler emits
// instructions before the RET instructions, which wouldn't trigger the original issue.
string returnValue = null;
// The following, not-reachable, branch will jump directly to the RET statement (at least with Roslyn 1.0 with
// enabled optimizations flag) which triggers the issue (the return value checks will be skipped).
if ("".Length == 42)
throw new Exception("Not reachable");
return returnValue;
}
public void OutValueChecksWithBranchToRetInstruction(out string outParam)
{
// This is the same scenario as above, but for out parameters.
outParam = null;
if ("".Length == 42)
throw new Exception("Not reachable");
}
public string GetterReturnValueChecksWithBranchToRetInstruction
{
get
{
// This is the same scenario as above, but for property getters.
string returnValue = null;
if ("".Length == 42)
throw new Exception("Not reachable");
return returnValue;
}
}
public void OutValueChecksWithRetInstructionAsSwitchCase(int i, out string outParam)
{
// This is the same scenario as above, but with a SWITCH instruction with branch targets to RET
// instructions (they are handled specially).
// Note that its important to have more than sections to prove that all sections with only a RET instruction are handled.
outParam = null;
switch (i)
{
case 0:
return;
case 1:
Console.WriteLine("1");
break;
case 2:
return;
case 3:
Console.WriteLine("3");
break;
}
}
}
| |
/*
FluorineFx open source library
Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using log4net;
using FluorineFx.Context;
using FluorineFx.Configuration;
using FluorineFx.Util;
using FluorineFx.Messaging.Rtmp.Event;
using FluorineFx.Messaging.Api.Service;
using FluorineFx.Messaging.Api;
using FluorineFx.Messaging.Api.Stream;
using FluorineFx.Messaging.Api.Event;
using FluorineFx.Messaging.Api.SO;
using FluorineFx.Exceptions;
using FluorineFx.Messaging.Rtmp.SO;
using FluorineFx.Messaging.Messages;
using FluorineFx.Messaging.Services;
using FluorineFx.Messaging.Endpoints;
using FluorineFx.IO;
using FluorineFx.Threading;
namespace FluorineFx.Messaging.Rtmp
{
/// <summary>
/// This type supports the Fluorine infrastructure and is not intended to be used directly from your code.
/// </summary>
sealed class RtmpServer : DisposableBase
{
private static readonly ILog log = LogManager.GetLogger(typeof(RtmpServer));
event ErrorHandler _onErrorEvent;
Hashtable _connections;
ArrayList _socketListeners;
//Timer _idleTimer;
//int _idleCheckInterval = 1000 * 60;
//int _idleTimeOutValue = 1000 * 60;
//ThreadPoolEx _threadPoolEx;
BufferPool _bufferPool;
RtmpHandler _rtmpHandler;
IEndpoint _endpoint;
X509Certificate _serverCertificate;
public RtmpServer(RtmpEndpoint endpoint)
{
_connections = new Hashtable();
_socketListeners = new ArrayList();
_endpoint = endpoint;
_rtmpHandler = new RtmpHandler(endpoint);
try
{
if (endpoint.ChannelDefinition.Properties.KeystoreFile != null)
{
FileSystemResource fsr = new FileSystemResource(endpoint.ChannelDefinition.Properties.KeystoreFile);
if (fsr.Exists)
{
if (endpoint.ChannelDefinition.Properties.KeystorePassword != null)
_serverCertificate = new X509Certificate2(fsr.File.FullName, endpoint.ChannelDefinition.Properties.KeystorePassword);
else
_serverCertificate = X509Certificate.CreateFromCertFile(fsr.File.FullName);
log.Info(string.Format("Certificate issued to {0} and is valid from {1} until {2}.", _serverCertificate.Subject, _serverCertificate.GetEffectiveDateString(), _serverCertificate.GetExpirationDateString()));
}
else
log.Error("Certificate file not found");
}
else
{
if (endpoint.ChannelDefinition.Properties.ServerCertificate != null)
{
StoreName storeName = (StoreName)Enum.Parse(typeof(StoreName), endpoint.ChannelDefinition.Properties.ServerCertificate.StoreName, false);
StoreLocation storeLocation = (StoreLocation)Enum.Parse(typeof(StoreLocation), endpoint.ChannelDefinition.Properties.ServerCertificate.StoreLocation, false);
X509FindType x509FindType = (X509FindType)Enum.Parse(typeof(X509FindType), endpoint.ChannelDefinition.Properties.ServerCertificate.X509FindType, false);
X509Store store = new X509Store(storeName, storeLocation);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certificateCollection = store.Certificates.Find(x509FindType, endpoint.ChannelDefinition.Properties.ServerCertificate.FindValue, false);
X509Certificate2Enumerator enumerator = certificateCollection.GetEnumerator();
if (enumerator.MoveNext())
{
_serverCertificate = enumerator.Current;
log.Info(string.Format("Certificate issued to {0} and is valid from {1} until {2}.", _serverCertificate.Subject, _serverCertificate.GetEffectiveDateString(), _serverCertificate.GetExpirationDateString()));
}
else
log.Error("Certificate not found");
}
}
}
catch (Exception ex)
{
log.Error("Error loading certificate.", ex);
}
}
/*
internal ThreadPoolEx ThreadPoolEx
{
get{ return _threadPoolEx; }
}
*/
internal BufferPool BufferPool
{
get { return _bufferPool; }
}
internal IRtmpHandler RtmpHandler
{
get { return _rtmpHandler; }
}
internal IEndpoint Endpoint
{
get { return _endpoint; }
}
public event ErrorHandler OnError
{
add { _onErrorEvent += value; }
remove { _onErrorEvent -= value; }
}
protected override void Free()
{
Stop();
if (_bufferPool != null)
_bufferPool.Dispose();
}
#region Server Management
public void Start()
{
try
{
if( log.IsInfoEnabled )
log.Info(__Res.GetString(__Res.SocketServer_Start));
//_threadPoolEx = new ThreadPoolEx();
_bufferPool = new BufferPool(FluorineConfiguration.Instance.FluorineSettings.RtmpServer.RtmpTransportSettings.ReceiveBufferSize);
if(!this.IsDisposed)
{
foreach (RtmpSocketListener socketListener in _socketListeners)
{
socketListener.Start();
}
}
//_idleTimer = new Timer(new TimerCallback(IdleCheck), null, _idleCheckInterval, _idleCheckInterval);
if( log.IsInfoEnabled )
log.Info(__Res.GetString(__Res.SocketServer_Started));
}
catch(Exception ex)
{
if( log.IsFatalEnabled )
log.Fatal("SocketServer failed", ex);
}
}
private void StopListeners()
{
if(!this.IsDisposed)
{
RtmpSocketListener[] socketListeners = GetSocketListeners();
if( socketListeners != null )
{
foreach (RtmpSocketListener socketListener in socketListeners)
{
try
{
socketListener.Stop();
RemoveListener(socketListener);
}
catch { }
}
}
}
}
private void StopConnections()
{
if( !this.IsDisposed )
{
RtmpServerConnection[] connections = GetConnections();
if (connections != null)
{
foreach (RtmpServerConnection connection in connections)
{
try
{
connection.Close();
}
catch { }
}
}
}
}
public void Stop()
{
if( !this.IsDisposed )
{
try
{
if( log.IsInfoEnabled )
log.Info(__Res.GetString(__Res.SocketServer_Stopping));
StopListeners();
StopConnections();
//if (_threadPoolEx != null)
// _threadPoolEx.Shutdown();
if (log.IsInfoEnabled)
log.Info(__Res.GetString(__Res.SocketServer_Stopped));
}
catch(Exception ex)
{
if( log.IsFatalEnabled )
log.Fatal(__Res.GetString(__Res.SocketServer_Failed), ex);
}
}
}
/*
private void IdleCheck(object state)
{
if (!IsDisposed)
{
//Disable timer event
_idleTimer.Change(Timeout.Infinite, Timeout.Infinite);
try
{
int loopSleep = 0;
RtmpServerConnection[] connections = GetConnections();
if (connections != null)
{
foreach (RtmpServerConnection connection in connections)
{
if (IsDisposed)
break;
try
{
if (connection != null && connection.IsActive)
{
//Check the idle timeout
if (DateTime.Now > (connection.LastAction.AddMilliseconds(_idleTimeOutValue)))
{
//connection.Close();
}
}
}
finally
{
ThreadPoolEx.LoopSleep(ref loopSleep);
}
}
}
}
finally
{
//Restart the timer event
if (!IsDisposed)
_idleTimer.Change(_idleCheckInterval, _idleCheckInterval);
}
}
}
*/
internal RtmpSocketListener[] GetSocketListeners()
{
RtmpSocketListener[] socketListeners = null;
if(!this.IsDisposed)
{
lock(_socketListeners)
{
socketListeners = new RtmpSocketListener[_socketListeners.Count];
_socketListeners.CopyTo(socketListeners, 0);
}
}
return socketListeners;
}
internal RtmpServerConnection[] GetConnections()
{
RtmpServerConnection[] connections = null;
if(!this.IsDisposed)
{
lock(_connections)
{
connections = new RtmpServerConnection[_connections.Count];
_connections.Keys.CopyTo(connections, 0);
}
}
return connections;
}
internal void AddConnection(RtmpServerConnection connection)
{
if(!this.IsDisposed)
{
lock(_connections)
{
_connections[connection] = connection;
}
}
}
internal void RemoveConnection(RtmpServerConnection connection)
{
if(!this.IsDisposed)
{
lock(_connections)
{
_connections.Remove(connection);
}
}
}
public void AddListener(IPEndPoint localEndPoint)
{
AddListener(localEndPoint, 1);
}
public void AddListener(IPEndPoint localEndPoint, int acceptCount)
{
if(!this.IsDisposed)
{
lock(_socketListeners)
{
RtmpSocketListener socketListener = new RtmpSocketListener(this, localEndPoint, acceptCount);
_socketListeners.Add(socketListener);
}
}
}
public void RemoveListener(RtmpSocketListener socketListener)
{
if(!this.IsDisposed)
{
lock(_socketListeners)
{
_socketListeners.Remove(socketListener);
}
}
}
#endregion Server Management
internal void InitializeConnection(Socket socket)
{
if(!IsDisposed)
{
RtmpServerConnection connection = null;
if (_serverCertificate == null)
{
connection = new RtmpServerConnection(this, new RtmpNetworkStream(socket));
if (log.IsDebugEnabled)
log.Debug(__Res.GetString(__Res.Rtmp_SocketListenerAccept, connection.ConnectionId));
}
else
{
SslStream sslStream = new SslStream(new NetworkStream(socket, false), false);
//sslStream.AuthenticateAsServer(_serverCertificate, false, SslProtocols.Tls, true);
sslStream.AuthenticateAsServer(_serverCertificate, false, SslProtocols.Default, false);
connection = new RtmpServerConnection(this, new RtmpNetworkStream(socket, sslStream));
if (log.IsDebugEnabled)
{
log.Debug(__Res.GetString(__Res.Rtmp_SocketListenerAccept, connection.ConnectionId));
string msg = string.Format("Cipher: {0} strength {1} Hash: {2} strength {3} Key exchange: {4} strength {5} Protocol: {6} Signed: {7} Encrypted: {8}",
sslStream.CipherAlgorithm, sslStream.CipherStrength,
sslStream.HashAlgorithm, sslStream.HashStrength,
sslStream.KeyExchangeAlgorithm, sslStream.KeyExchangeStrength,
sslStream.SslProtocol, sslStream.IsSigned, sslStream.IsEncrypted);
log.Debug(msg);
}
}
//We are still in an IOCP thread
this.AddConnection(connection);
//FluorineRtmpContext.Initialize(connection);
_rtmpHandler.ConnectionOpened(connection);
connection.BeginReceive(true);
}
}
/// <summary>
/// Begin disconnect the connection
/// </summary>
internal void OnConnectionClose(RtmpServerConnection connection)
{
if(!IsDisposed)
{
RemoveConnection(connection);
//connection.Dispose();
}
}
internal void RaiseOnError(Exception exception)
{
if(_onErrorEvent != null)
{
_onErrorEvent(this, new ServerErrorEventArgs(exception));
}
}
}
delegate void ErrorHandler(object sender, ServerErrorEventArgs e);
/// <summary>
/// Base event arguments for connection events.
/// </summary>
class ServerErrorEventArgs : EventArgs
{
Exception _exception;
public ServerErrorEventArgs(Exception exception)
{
_exception = exception;
}
#region Properties
public Exception Exception
{
get { return _exception; }
}
#endregion
}
}
| |
// <copyright file="BiCgStabTest.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2014 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Complex;
using MathNet.Numerics.LinearAlgebra.Complex.Solvers;
using MathNet.Numerics.LinearAlgebra.Solvers;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex.Solvers.Iterative
{
#if NOSYSNUMERICS
using Complex = Numerics.Complex;
#else
using Complex = System.Numerics.Complex;
#endif
/// <summary>
/// Tests of Bi-Conjugate Gradient stabilized iterative matrix solver.
/// </summary>
[TestFixture, Category("LASolver")]
public class BiCgStabTest
{
/// <summary>
/// Convergence boundary.
/// </summary>
const double ConvergenceBoundary = 1e-10;
/// <summary>
/// Maximum iterations.
/// </summary>
const int MaximumIterations = 1000;
/// <summary>
/// Solve wide matrix throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void SolveWideMatrixThrowsArgumentException()
{
var matrix = new SparseMatrix(2, 3);
var input = new DenseVector(2);
var solver = new BiCgStab();
Assert.That(() => matrix.SolveIterative(input, solver), Throws.ArgumentException);
}
/// <summary>
/// Solve long matrix throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void SolveLongMatrixThrowsArgumentException()
{
var matrix = new SparseMatrix(3, 2);
var input = new DenseVector(3);
var solver = new BiCgStab();
Assert.That(() => matrix.SolveIterative(input, solver), Throws.ArgumentException);
}
/// <summary>
/// Solve unit matrix and back multiply.
/// </summary>
[Test]
public void SolveUnitMatrixAndBackMultiply()
{
// Create the identity matrix
var matrix = SparseMatrix.CreateIdentity(100);
// Create the y vector
var y = DenseVector.Create(matrix.RowCount, Complex.One);
// Create an iteration monitor which will keep track of iterative convergence
var monitor = new Iterator<Complex>(
new IterationCountStopCriterion<Complex>(MaximumIterations),
new ResidualStopCriterion<Complex>(ConvergenceBoundary),
new DivergenceStopCriterion<Complex>(),
new FailureStopCriterion<Complex>());
var solver = new BiCgStab();
// Solve equation Ax = y
var x = matrix.SolveIterative(y, solver, monitor);
// Now compare the results
Assert.IsNotNull(x, "#02");
Assert.AreEqual(y.Count, x.Count, "#03");
// Back multiply the vector
var z = matrix.Multiply(x);
// Check that the solution converged
Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");
// Now compare the vectors
for (var i = 0; i < y.Count; i++)
{
Assert.GreaterOrEqual(ConvergenceBoundary, (y[i] - z[i]).Magnitude, "#05-" + i);
}
}
/// <summary>
/// Solve scaled unit matrix and back multiply.
/// </summary>
[Test]
public void SolveScaledUnitMatrixAndBackMultiply()
{
// Create the identity matrix
var matrix = SparseMatrix.CreateIdentity(100);
// Scale it with a funny number
matrix.Multiply(new Complex(Math.PI, Math.PI), matrix);
// Create the y vector
var y = DenseVector.Create(matrix.RowCount, Complex.One);
// Create an iteration monitor which will keep track of iterative convergence
var monitor = new Iterator<Complex>(new IterationCountStopCriterion<Complex>(MaximumIterations),
new ResidualStopCriterion<Complex>(ConvergenceBoundary),
new DivergenceStopCriterion<Complex>(),
new FailureStopCriterion<Complex>());
var solver = new BiCgStab();
// Solve equation Ax = y
var x = matrix.SolveIterative(y, solver, monitor);
// Now compare the results
Assert.IsNotNull(x, "#02");
Assert.AreEqual(y.Count, x.Count, "#03");
// Back multiply the vector
var z = matrix.Multiply(x);
// Check that the solution converged
Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");
// Now compare the vectors
for (var i = 0; i < y.Count; i++)
{
Assert.GreaterOrEqual(ConvergenceBoundary, (y[i] - z[i]).Magnitude, "#05-" + i);
}
}
/// <summary>
/// Solve poisson matrix and back multiply.
/// </summary>
[Test]
public void SolvePoissonMatrixAndBackMultiply()
{
// Create the matrix
var matrix = new SparseMatrix(100);
// Assemble the matrix. We assume we're solving the Poisson equation
// on a rectangular 10 x 10 grid
const int GridSize = 10;
// The pattern is:
// 0 .... 0 -1 0 0 0 0 0 0 0 0 -1 4 -1 0 0 0 0 0 0 0 0 -1 0 0 ... 0
for (var i = 0; i < matrix.RowCount; i++)
{
// Insert the first set of -1's
if (i > (GridSize - 1))
{
matrix[i, i - GridSize] = -1;
}
// Insert the second set of -1's
if (i > 0)
{
matrix[i, i - 1] = -1;
}
// Insert the centerline values
matrix[i, i] = 4;
// Insert the first trailing set of -1's
if (i < matrix.RowCount - 1)
{
matrix[i, i + 1] = -1;
}
// Insert the second trailing set of -1's
if (i < matrix.RowCount - GridSize)
{
matrix[i, i + GridSize] = -1;
}
}
// Create the y vector
var y = DenseVector.Create(matrix.RowCount, Complex.One);
// Create an iteration monitor which will keep track of iterative convergence
var monitor = new Iterator<Complex>(new IterationCountStopCriterion<Complex>(MaximumIterations),
new ResidualStopCriterion<Complex>(ConvergenceBoundary),
new DivergenceStopCriterion<Complex>(),
new FailureStopCriterion<Complex>());
var solver = new BiCgStab();
// Solve equation Ax = y
var x = matrix.SolveIterative(y, solver, monitor);
// Now compare the results
Assert.IsNotNull(x, "#02");
Assert.AreEqual(y.Count, x.Count, "#03");
// Back multiply the vector
var z = matrix.Multiply(x);
// Check that the solution converged
Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04");
// Now compare the vectors
for (var i = 0; i < y.Count; i++)
{
Assert.GreaterOrEqual(ConvergenceBoundary, (y[i] - z[i]).Magnitude, "#05-" + i);
}
}
/// <summary>
/// Can solve for a random vector.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(4)]
[TestCase(8)]
[TestCase(10)]
public void CanSolveForRandomVector(int order)
{
var matrixA = Matrix<Complex>.Build.Random(order, order, 1);
var vectorb = Vector<Complex>.Build.Random(order, 1);
var monitor = new Iterator<Complex>(
new IterationCountStopCriterion<Complex>(1000),
new ResidualStopCriterion<Complex>(1e-10));
var solver = new BiCgStab();
var resultx = matrixA.SolveIterative(vectorb, solver, monitor);
Assert.AreEqual(matrixA.ColumnCount, resultx.Count);
var matrixBReconstruct = matrixA*resultx;
// Check the reconstruction.
for (var i = 0; i < order; i++)
{
Assert.AreEqual(vectorb[i].Real, matrixBReconstruct[i].Real, 1e-5);
Assert.AreEqual(vectorb[i].Imaginary, matrixBReconstruct[i].Imaginary, 1e-5);
}
}
/// <summary>
/// Can solve for random matrix.
/// </summary>
/// <param name="order">Matrix order.</param>
[TestCase(4)]
[TestCase(8)]
[TestCase(10)]
public void CanSolveForRandomMatrix(int order)
{
var matrixA = Matrix<Complex>.Build.Random(order, order, 1);
var matrixB = Matrix<Complex>.Build.Random(order, order, 1);
var monitor = new Iterator<Complex>(
new IterationCountStopCriterion<Complex>(1000),
new ResidualStopCriterion<Complex>(1e-10));
var solver = new BiCgStab();
var matrixX = matrixA.SolveIterative(matrixB, solver, monitor);
// The solution X row dimension is equal to the column dimension of A
Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount);
// The solution X has the same number of columns as B
Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount);
var matrixBReconstruct = matrixA*matrixX;
// Check the reconstruction.
for (var i = 0; i < matrixB.RowCount; i++)
{
for (var j = 0; j < matrixB.ColumnCount; j++)
{
Assert.AreEqual(matrixB[i, j].Real, matrixBReconstruct[i, j].Real, 1.0e-5);
Assert.AreEqual(matrixB[i, j].Imaginary, matrixBReconstruct[i, j].Imaginary, 1.0e-5);
}
}
}
}
}
| |
//
// Copyright (c) 2004-2020 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.
//
namespace NLog.Conditions
{
using System;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
/// <summary>
/// A bunch of utility methods (mostly predicates) which can be used in
/// condition expressions. Partially inspired by XPath 1.0.
/// </summary>
[ConditionMethods]
public static class ConditionMethods
{
/// <summary>
/// Compares two values for equality.
/// </summary>
/// <param name="firstValue">The first value.</param>
/// <param name="secondValue">The second value.</param>
/// <returns><b>true</b> when two objects are equal, <b>false</b> otherwise.</returns>
[ConditionMethod("equals")]
public static bool Equals2(object firstValue, object secondValue)
{
return firstValue.Equals(secondValue);
}
/// <summary>
/// Compares two strings for equality.
/// </summary>
/// <param name="firstValue">The first string.</param>
/// <param name="secondValue">The second string.</param>
/// <param name="ignoreCase">Optional. If <c>true</c>, case is ignored; if <c>false</c> (default), case is significant.</param>
/// <returns><b>true</b> when two strings are equal, <b>false</b> otherwise.</returns>
[ConditionMethod("strequals")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Justification = "Not called directly, only ever Invoked.")]
#if SILVERLIGHT
public static bool Equals2(string firstValue, string secondValue, [Optional] object ignoreCase)
#else
public static bool Equals2( string firstValue, string secondValue, [Optional, DefaultParameterValue(false)] bool ignoreCase)
#endif
{
#if SILVERLIGHT
bool ic = false;
if (ignoreCase is bool b)
ic = b;
#else
bool ic = ignoreCase;
#endif
return firstValue.Equals(secondValue, ic ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
/// <summary>
/// Gets or sets a value indicating whether the second string is a substring of the first one.
/// </summary>
/// <param name="haystack">The first string.</param>
/// <param name="needle">The second string.</param>
/// <param name="ignoreCase">Optional. If <c>true</c> (default), case is ignored; if <c>false</c>, case is significant.</param>
/// <returns><b>true</b> when the second string is a substring of the first string, <b>false</b> otherwise.</returns>
[ConditionMethod("contains")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Justification = "Not called directly, only ever Invoked.")]
#if SILVERLIGHT
public static bool Contains( string haystack, string needle, [Optional] object ignoreCase)
#else
public static bool Contains(string haystack, string needle, [Optional, DefaultParameterValue(true)] bool ignoreCase)
#endif
{
#if SILVERLIGHT
bool ic = true;
if ( ignoreCase != null && ignoreCase is bool )
ic = ( bool ) ignoreCase;
#else
bool ic = ignoreCase;
#endif
return haystack.IndexOf(needle, ic ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) >= 0;
}
/// <summary>
/// Gets or sets a value indicating whether the second string is a prefix of the first one.
/// </summary>
/// <param name="haystack">The first string.</param>
/// <param name="needle">The second string.</param>
/// <param name="ignoreCase">Optional. If <c>true</c> (default), case is ignored; if <c>false</c>, case is significant.</param>
/// <returns><b>true</b> when the second string is a prefix of the first string, <b>false</b> otherwise.</returns>
[ConditionMethod("starts-with")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Justification = "Not called directly, only ever Invoked.")]
#if SILVERLIGHT
public static bool StartsWith( string haystack, string needle, [Optional] object ignoreCase)
#else
public static bool StartsWith(string haystack, string needle, [Optional, DefaultParameterValue(true)] bool ignoreCase)
#endif
{
#if SILVERLIGHT
bool ic = true;
if ( ignoreCase != null && ignoreCase is bool )
ic = ( bool ) ignoreCase;
#else
bool ic = ignoreCase;
#endif
return haystack.StartsWith(needle, ic ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
/// <summary>
/// Gets or sets a value indicating whether the second string is a suffix of the first one.
/// </summary>
/// <param name="haystack">The first string.</param>
/// <param name="needle">The second string.</param>
/// <param name="ignoreCase">Optional. If <c>true</c> (default), case is ignored; if <c>false</c>, case is significant.</param>
/// <returns><b>true</b> when the second string is a prefix of the first string, <b>false</b> otherwise.</returns>
[ConditionMethod("ends-with")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Justification = "Not called directly, only ever Invoked.")]
#if SILVERLIGHT
public static bool EndsWith( string haystack, string needle, [Optional] object ignoreCase)
#else
public static bool EndsWith(string haystack, string needle, [Optional, DefaultParameterValue(true)] bool ignoreCase)
#endif
{
#if SILVERLIGHT
bool ic = true;
if ( ignoreCase != null && ignoreCase is bool )
ic = ( bool ) ignoreCase;
#else
bool ic = ignoreCase;
#endif
return haystack.EndsWith(needle, ic ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
/// <summary>
/// Returns the length of a string.
/// </summary>
/// <param name="text">A string whose lengths is to be evaluated.</param>
/// <returns>The length of the string.</returns>
[ConditionMethod("length")]
public static int Length(string text)
{
return text.Length;
}
/// <summary>
/// Indicates whether the specified regular expression finds a match in the specified input string.
/// </summary>
/// <param name="input">The string to search for a match.</param>
/// <param name="pattern">The regular expression pattern to match.</param>
/// <param name="options">A string consisting of the desired options for the test. The possible values are those of the <see cref="RegexOptions"/> separated by commas.</param>
/// <returns>true if the regular expression finds a match; otherwise, false.</returns>
[ConditionMethod("regex-matches")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Justification = "Not called directly, only ever Invoked.")]
#if SILVERLIGHT
public static bool RegexMatches(string input, string pattern, [Optional] string options)
#else
public static bool RegexMatches(string input, string pattern, [Optional, DefaultParameterValue("")] string options)
#endif
{
RegexOptions regexOpts = ParseRegexOptions(options);
return Regex.IsMatch(input, pattern, regexOpts);
}
/// <summary>
///
/// </summary>
/// <param name="options"></param>
/// <returns></returns>
private static RegexOptions ParseRegexOptions(string options)
{
if (string.IsNullOrEmpty(options))
{
return RegexOptions.None;
}
return (RegexOptions)Enum.Parse(typeof(RegexOptions), options, true);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.Drawing.Internal;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using Gdip = System.Drawing.SafeNativeMethods.Gdip;
namespace System.Drawing
{
public abstract partial class Image
{
#if FINALIZATION_WATCH
private string allocationSite = Graphics.GetAllocationStack();
#endif
public static Image FromFile(string filename, bool useEmbeddedColorManagement)
{
if (!File.Exists(filename))
{
// Throw a more specific exception for invalid paths that are null or empty,
// contain invalid characters or are too long.
filename = Path.GetFullPath(filename);
throw new FileNotFoundException(filename);
}
// GDI+ will read this file multiple times. Get the fully qualified path
// so if our app changes default directory we won't get an error
filename = Path.GetFullPath(filename);
IntPtr image = IntPtr.Zero;
if (useEmbeddedColorManagement)
{
Gdip.CheckStatus(Gdip.GdipLoadImageFromFileICM(filename, out image));
}
else
{
Gdip.CheckStatus(Gdip.GdipLoadImageFromFile(filename, out image));
}
ValidateImage(image);
Image img = CreateImageObject(image);
EnsureSave(img, filename, null);
return img;
}
public static Image FromStream(Stream stream, bool useEmbeddedColorManagement, bool validateImageData)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
IntPtr image = IntPtr.Zero;
if (useEmbeddedColorManagement)
{
Gdip.CheckStatus(Gdip.GdipLoadImageFromStreamICM(new GPStream(stream), out image));
}
else
{
Gdip.CheckStatus(Gdip.GdipLoadImageFromStream(new GPStream(stream), out image));
}
if (validateImageData)
ValidateImage(image);
Image img = CreateImageObject(image);
EnsureSave(img, null, stream);
return img;
}
// Used for serialization
private IntPtr InitializeFromStream(Stream stream)
{
IntPtr image = IntPtr.Zero;
Gdip.CheckStatus(Gdip.GdipLoadImageFromStream(new GPStream(stream), out image));
ValidateImage(image);
nativeImage = image;
int type = -1;
Gdip.CheckStatus(Gdip.GdipGetImageType(new HandleRef(this, nativeImage), out type));
EnsureSave(this, null, stream);
return image;
}
internal Image(IntPtr nativeImage) => SetNativeImage(nativeImage);
/// <summary>
/// Creates an exact copy of this <see cref='Image'/>.
/// </summary>
public object Clone()
{
IntPtr cloneImage = IntPtr.Zero;
Gdip.CheckStatus(Gdip.GdipCloneImage(new HandleRef(this, nativeImage), out cloneImage));
ValidateImage(cloneImage);
return CreateImageObject(cloneImage);
}
protected virtual void Dispose(bool disposing)
{
#if FINALIZATION_WATCH
if (!disposing && nativeImage != IntPtr.Zero)
Debug.WriteLine("**********************\nDisposed through finalization:\n" + allocationSite);
#endif
if (nativeImage == IntPtr.Zero)
return;
try
{
#if DEBUG
int status = !Gdip.Initialized ? Gdip.Ok :
#endif
Gdip.GdipDisposeImage(new HandleRef(this, nativeImage));
#if DEBUG
Debug.Assert(status == Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture));
#endif
}
catch (Exception ex)
{
if (ClientUtils.IsSecurityOrCriticalException(ex))
{
throw;
}
Debug.Fail("Exception thrown during Dispose: " + ex.ToString());
}
finally
{
nativeImage = IntPtr.Zero;
}
}
internal static Image CreateImageObject(IntPtr nativeImage)
{
Image image;
Gdip.CheckStatus(Gdip.GdipGetImageType(new HandleRef(null, nativeImage), out int type));
switch ((ImageType)type)
{
case ImageType.Bitmap:
image = new Bitmap(nativeImage);
break;
case ImageType.Metafile:
image = Metafile.FromGDIplus(nativeImage);
break;
default:
throw new ArgumentException(SR.InvalidImage);
}
return image;
}
/// <summary>
/// Returns information about the codecs used for this <see cref='Image'/>.
/// </summary>
public EncoderParameters GetEncoderParameterList(Guid encoder)
{
EncoderParameters p;
Gdip.CheckStatus(Gdip.GdipGetEncoderParameterListSize(
new HandleRef(this, nativeImage),
ref encoder,
out int size));
if (size <= 0)
return null;
IntPtr buffer = Marshal.AllocHGlobal(size);
try
{
Gdip.CheckStatus(Gdip.GdipGetEncoderParameterList(
new HandleRef(this, nativeImage),
ref encoder,
size,
buffer));
p = EncoderParameters.ConvertFromMemory(buffer);
}
finally
{
Marshal.FreeHGlobal(buffer);
}
return p;
}
/// <summary>
/// Saves this <see cref='Image'/> to the specified file in the specified format.
/// </summary>
public void Save(string filename, ImageFormat format)
{
if (format == null)
throw new ArgumentNullException(nameof(format));
ImageCodecInfo codec = format.FindEncoder();
if (codec == null)
codec = ImageFormat.Png.FindEncoder();
Save(filename, codec, null);
}
/// <summary>
/// Saves this <see cref='Image'/> to the specified file in the specified format and with the specified encoder parameters.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void Save(string filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
{
if (filename == null)
throw new ArgumentNullException(nameof(filename));
if (encoder == null)
throw new ArgumentNullException(nameof(encoder));
IntPtr encoderParamsMemory = IntPtr.Zero;
if (encoderParams != null)
{
_rawData = null;
encoderParamsMemory = encoderParams.ConvertToMemory();
}
try
{
Guid g = encoder.Clsid;
bool saved = false;
if (_rawData != null)
{
ImageCodecInfo rawEncoder = RawFormat.FindEncoder();
if (rawEncoder != null && rawEncoder.Clsid == g)
{
using (FileStream fs = File.OpenWrite(filename))
{
fs.Write(_rawData, 0, _rawData.Length);
saved = true;
}
}
}
if (!saved)
{
Gdip.CheckStatus(Gdip.GdipSaveImageToFile(
new HandleRef(this, nativeImage),
filename,
ref g,
new HandleRef(encoderParams, encoderParamsMemory)));
}
}
finally
{
if (encoderParamsMemory != IntPtr.Zero)
{
Marshal.FreeHGlobal(encoderParamsMemory);
}
}
}
private void Save(MemoryStream stream)
{
// Jpeg loses data, so we don't want to use it to serialize...
ImageFormat dest = RawFormat;
if (dest.Guid == ImageFormat.Jpeg.Guid)
dest = ImageFormat.Png;
// If we don't find an Encoder (for things like Icon), we just switch back to PNG...
ImageCodecInfo codec = dest.FindEncoder() ?? ImageFormat.Png.FindEncoder();
Save(stream, codec, null);
}
/// <summary>
/// Saves this <see cref='Image'/> to the specified stream in the specified format.
/// </summary>
public void Save(Stream stream, ImageFormat format)
{
if (format == null)
throw new ArgumentNullException(nameof(format));
ImageCodecInfo codec = format.FindEncoder();
Save(stream, codec, null);
}
/// <summary>
/// Saves this <see cref='Image'/> to the specified stream in the specified format.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (encoder == null)
throw new ArgumentNullException(nameof(encoder));
IntPtr encoderParamsMemory = IntPtr.Zero;
if (encoderParams != null)
{
_rawData = null;
encoderParamsMemory = encoderParams.ConvertToMemory();
}
try
{
Guid g = encoder.Clsid;
bool saved = false;
if (_rawData != null)
{
ImageCodecInfo rawEncoder = RawFormat.FindEncoder();
if (rawEncoder != null && rawEncoder.Clsid == g)
{
stream.Write(_rawData, 0, _rawData.Length);
saved = true;
}
}
if (!saved)
{
Gdip.CheckStatus(Gdip.GdipSaveImageToStream(
new HandleRef(this, nativeImage),
new GPStream(stream, makeSeekable: false),
ref g,
new HandleRef(encoderParams, encoderParamsMemory)));
}
}
finally
{
if (encoderParamsMemory != IntPtr.Zero)
{
Marshal.FreeHGlobal(encoderParamsMemory);
}
}
}
/// <summary>
/// Adds an <see cref='EncoderParameters'/> to this <see cref='Image'/>.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void SaveAdd(EncoderParameters encoderParams)
{
IntPtr encoder = IntPtr.Zero;
if (encoderParams != null)
encoder = encoderParams.ConvertToMemory();
_rawData = null;
try
{
Gdip.CheckStatus(Gdip.GdipSaveAdd(new HandleRef(this, nativeImage), new HandleRef(encoderParams, encoder)));
}
finally
{
if (encoder != IntPtr.Zero)
{
Marshal.FreeHGlobal(encoder);
}
}
}
/// <summary>
/// Adds an <see cref='EncoderParameters'/> to the specified <see cref='Image'/>.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void SaveAdd(Image image, EncoderParameters encoderParams)
{
IntPtr encoder = IntPtr.Zero;
if (image == null)
throw new ArgumentNullException(nameof(image));
if (encoderParams != null)
encoder = encoderParams.ConvertToMemory();
_rawData = null;
try
{
Gdip.CheckStatus(Gdip.GdipSaveAddImage(
new HandleRef(this, nativeImage),
new HandleRef(image, image.nativeImage),
new HandleRef(encoderParams, encoder)));
}
finally
{
if (encoder != IntPtr.Zero)
{
Marshal.FreeHGlobal(encoder);
}
}
}
/// <summary>
/// Gets a bounding rectangle in the specified units for this <see cref='Image'/>.
/// </summary>
public RectangleF GetBounds(ref GraphicsUnit pageUnit)
{
Gdip.CheckStatus(Gdip.GdipGetImageBounds(new HandleRef(this, nativeImage), out RectangleF bounds, out pageUnit));
return bounds;
}
/// <summary>
/// Gets or sets the color palette used for this <see cref='Image'/>.
/// </summary>
[Browsable(false)]
public ColorPalette Palette
{
get
{
Gdip.CheckStatus(Gdip.GdipGetImagePaletteSize(new HandleRef(this, nativeImage), out int size));
// "size" is total byte size:
// sizeof(ColorPalette) + (pal->Count-1)*sizeof(ARGB)
ColorPalette palette = new ColorPalette(size);
// Memory layout is:
// UINT Flags
// UINT Count
// ARGB Entries[size]
IntPtr memory = Marshal.AllocHGlobal(size);
try
{
Gdip.CheckStatus(Gdip.GdipGetImagePalette(new HandleRef(this, nativeImage), memory, size));
palette.ConvertFromMemory(memory);
}
finally
{
Marshal.FreeHGlobal(memory);
}
return palette;
}
set
{
IntPtr memory = value.ConvertToMemory();
try
{
Gdip.CheckStatus(Gdip.GdipSetImagePalette(new HandleRef(this, nativeImage), memory));
}
finally
{
if (memory != IntPtr.Zero)
{
Marshal.FreeHGlobal(memory);
}
}
}
}
// Thumbnail support
/// <summary>
/// Returns the thumbnail for this <see cref='Image'/>.
/// </summary>
public Image GetThumbnailImage(int thumbWidth, int thumbHeight, GetThumbnailImageAbort callback, IntPtr callbackData)
{
IntPtr thumbImage = IntPtr.Zero;
Gdip.CheckStatus(Gdip.GdipGetImageThumbnail(
new HandleRef(this, nativeImage),
thumbWidth,
thumbHeight,
out thumbImage,
callback,
callbackData));
return CreateImageObject(thumbImage);
}
/// <summary>
/// Gets an array of the property IDs stored in this <see cref='Image'/>.
/// </summary>
[Browsable(false)]
public int[] PropertyIdList
{
get
{
Gdip.CheckStatus(Gdip.GdipGetPropertyCount(new HandleRef(this, nativeImage), out int count));
int[] propid = new int[count];
//if we have a 0 count, just return our empty array
if (count == 0)
return propid;
Gdip.CheckStatus(Gdip.GdipGetPropertyIdList(new HandleRef(this, nativeImage), count, propid));
return propid;
}
}
/// <summary>
/// Gets the specified property item from this <see cref='Image'/>.
/// </summary>
public PropertyItem GetPropertyItem(int propid)
{
Gdip.CheckStatus(Gdip.GdipGetPropertyItemSize(new HandleRef(this, nativeImage), propid, out int size));
if (size == 0)
return null;
IntPtr propdata = Marshal.AllocHGlobal(size);
if (propdata == IntPtr.Zero)
throw Gdip.StatusException(Gdip.OutOfMemory);
try
{
Gdip.CheckStatus(Gdip.GdipGetPropertyItem(new HandleRef(this, nativeImage), propid, size, propdata));
return PropertyItemInternal.ConvertFromMemory(propdata, 1)[0];
}
finally
{
Marshal.FreeHGlobal(propdata);
}
}
/// <summary>
/// Sets the specified property item to the specified value.
/// </summary>
public void SetPropertyItem(PropertyItem propitem)
{
PropertyItemInternal propItemInternal = PropertyItemInternal.ConvertFromPropertyItem(propitem);
using (propItemInternal)
{
Gdip.CheckStatus(Gdip.GdipSetPropertyItem(new HandleRef(this, nativeImage), propItemInternal));
}
}
/// <summary>
/// Gets an array of <see cref='PropertyItem'/> objects that describe this <see cref='Image'/>.
/// </summary>
[Browsable(false)]
public PropertyItem[] PropertyItems
{
get
{
Gdip.CheckStatus(Gdip.GdipGetPropertyCount(new HandleRef(this, nativeImage), out int count));
Gdip.CheckStatus(Gdip.GdipGetPropertySize(new HandleRef(this, nativeImage), out int size, ref count));
if (size == 0 || count == 0)
return Array.Empty<PropertyItem>();
IntPtr propdata = Marshal.AllocHGlobal(size);
try
{
Gdip.CheckStatus(Gdip.GdipGetAllPropertyItems(new HandleRef(this, nativeImage), size, count, propdata));
return PropertyItemInternal.ConvertFromMemory(propdata, count);
}
finally
{
Marshal.FreeHGlobal(propdata);
}
}
}
/// <summary>
/// Returns the size of the specified pixel format.
/// </summary>
public static int GetPixelFormatSize(PixelFormat pixfmt)
{
return (unchecked((int)pixfmt) >> 8) & 0xFF;
}
/// <summary>
/// Returns a value indicating whether the pixel format contains alpha information.
/// </summary>
public static bool IsAlphaPixelFormat(PixelFormat pixfmt)
{
return (pixfmt & PixelFormat.Alpha) != 0;
}
internal static void ValidateImage(IntPtr image)
{
try
{
Gdip.CheckStatus(Gdip.GdipImageForceValidation(new HandleRef(null, image)));
}
catch
{
Gdip.GdipDisposeImage(new HandleRef(null, image));
throw;
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
{
/// <summary>
/// Utility methods for inventory archiving
/// </summary>
public static class InventoryArchiveUtils
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
// Character used for escaping the path delimter ("\/") and itself ("\\") in human escaped strings
public static readonly char ESCAPE_CHARACTER = '\\';
// The character used to separate inventory path components (different folders and items)
public static readonly char PATH_DELIMITER = '/';
/// <summary>
/// Find a folder given a PATH_DELIMITER delimited path starting from a user's root folder
/// </summary>
///
/// This method does not handle paths that contain multiple delimitors
///
/// FIXME: We do not yet handle situations where folders have the same name. We could handle this by some
/// XPath like expression
///
/// FIXME: Delimitors which occur in names themselves are not currently escapable.
///
/// <param name="inventoryService">
/// Inventory service to query
/// </param>
/// <param name="userId">
/// User id to search
/// </param>
/// <param name="path">
/// The path to the required folder.
/// It this is empty or consists only of the PATH_DELIMTER then this folder itself is returned.
/// </param>
/// <returns>null if the folder is not found</returns>
public static InventoryFolderBase FindFolderByPath(
IInventoryService inventoryService, UUID userId, string path)
{
InventoryFolderBase rootFolder = inventoryService.GetRootFolder(userId);
if (null == rootFolder)
return null;
return FindFolderByPath(inventoryService, rootFolder, path);
}
/// <summary>
/// Find a folder given a PATH_DELIMITER delimited path starting from this folder
/// </summary>
///
/// This method does not handle paths that contain multiple delimitors
///
/// FIXME: We do not yet handle situations where folders have the same name. We could handle this by some
/// XPath like expression
///
/// FIXME: Delimitors which occur in names themselves are not currently escapable.
///
/// <param name="inventoryService">
/// Inventory service to query
/// </param>
/// <param name="startFolder">
/// The folder from which the path starts
/// </param>
/// <param name="path">
/// The path to the required folder.
/// It this is empty or consists only of the PATH_DELIMTER then this folder itself is returned.
/// </param>
/// <returns>null if the folder is not found</returns>
public static InventoryFolderBase FindFolderByPath(
IInventoryService inventoryService, InventoryFolderBase startFolder, string path)
{
if (path == string.Empty)
return startFolder;
path = path.Trim();
if (path == PATH_DELIMITER.ToString())
return startFolder;
string[] components = SplitEscapedPath(path);
components[0] = UnescapePath(components[0]);
//string[] components = path.Split(new string[] { PATH_DELIMITER.ToString() }, 2, StringSplitOptions.None);
InventoryCollection contents = inventoryService.GetFolderContent(startFolder.Owner, startFolder.ID);
foreach (InventoryFolderBase folder in contents.Folders)
{
if (folder.Name == components[0])
{
if (components.Length > 1)
return FindFolderByPath(inventoryService, folder, components[1]);
else
return folder;
}
}
// We didn't find a folder with the right name
return null;
}
/// <summary>
/// Find an item given a PATH_DELIMITOR delimited path starting from the user's root folder.
///
/// This method does not handle paths that contain multiple delimitors
///
/// FIXME: We do not yet handle situations where folders or items have the same name. We could handle this by some
/// XPath like expression
///
/// FIXME: Delimitors which occur in names themselves are not currently escapable.
/// </summary>
///
/// <param name="inventoryService">
/// Inventory service to query
/// </param>
/// <param name="userId">
/// The user to search
/// </param>
/// <param name="path">
/// The path to the required item.
/// </param>
/// <returns>null if the item is not found</returns>
public static InventoryItemBase FindItemByPath(
IInventoryService inventoryService, UUID userId, string path)
{
InventoryFolderBase rootFolder = inventoryService.GetRootFolder(userId);
if (null == rootFolder)
return null;
return FindItemByPath(inventoryService, rootFolder, path);
}
/// <summary>
/// Find an item given a PATH_DELIMITOR delimited path starting from this folder.
///
/// This method does not handle paths that contain multiple delimitors
///
/// FIXME: We do not yet handle situations where folders or items have the same name. We could handle this by some
/// XPath like expression
///
/// FIXME: Delimitors which occur in names themselves are not currently escapable.
/// </summary>
///
/// <param name="inventoryService">
/// Inventory service to query
/// </param>
/// <param name="startFolder">
/// The folder from which the path starts
/// </param>
/// <param name="path">
/// <param name="path">
/// The path to the required item.
/// </param>
/// <returns>null if the item is not found</returns>
public static InventoryItemBase FindItemByPath(
IInventoryService inventoryService, InventoryFolderBase startFolder, string path)
{
string[] components = SplitEscapedPath(path);
components[0] = UnescapePath(components[0]);
//string[] components = path.Split(new string[] { PATH_DELIMITER }, 2, StringSplitOptions.None);
if (components.Length == 1)
{
// m_log.DebugFormat("FOUND SINGLE COMPONENT [{0}]", components[0]);
List<InventoryItemBase> items = inventoryService.GetFolderItems(startFolder.Owner, startFolder.ID);
foreach (InventoryItemBase item in items)
{
if (item.Name == components[0])
return item;
}
}
else
{
// m_log.DebugFormat("FOUND COMPONENTS [{0}] and [{1}]", components[0], components[1]);
InventoryCollection contents = inventoryService.GetFolderContent(startFolder.Owner, startFolder.ID);
foreach (InventoryFolderBase folder in contents.Folders)
{
if (folder.Name == components[0])
return FindItemByPath(inventoryService, folder, components[1]);
}
}
// We didn't find an item or intermediate folder with the given name
return null;
}
/// <summary>
/// Split a human escaped path into two components if it contains an unescaped path delimiter, or one component
/// if no delimiter is present
/// </summary>
/// <param name="path"></param>
/// <returns>
/// The split path. We leave the components in their originally unescaped state (though we remove the delimiter
/// which originally split them if applicable).
/// </returns>
public static string[] SplitEscapedPath(string path)
{
// m_log.DebugFormat("SPLITTING PATH {0}", path);
bool singleEscapeChar = false;
for (int i = 0; i < path.Length; i++)
{
if (path[i] == ESCAPE_CHARACTER && !singleEscapeChar)
{
singleEscapeChar = true;
}
else
{
if (PATH_DELIMITER == path[i] && !singleEscapeChar)
return new string[2] { path.Remove(i), path.Substring(i + 1) };
else
singleEscapeChar = false;
}
}
// We didn't find a delimiter
return new string[1] { path };
}
/// <summary>
/// Unescapes a human escaped path. This means that "\\" goes to "\", and "\/" goes to "/"
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string UnescapePath(string path)
{
// m_log.DebugFormat("ESCAPING PATH {0}", path);
StringBuilder sb = new StringBuilder();
bool singleEscapeChar = false;
for (int i = 0; i < path.Length; i++)
{
if (path[i] == ESCAPE_CHARACTER && !singleEscapeChar)
singleEscapeChar = true;
else
singleEscapeChar = false;
if (singleEscapeChar)
{
if (PATH_DELIMITER == path[i])
sb.Append(PATH_DELIMITER);
}
else
{
sb.Append(path[i]);
}
}
// m_log.DebugFormat("ESCAPED PATH TO {0}", sb);
return sb.ToString();
}
/// <summary>
/// Escape an archive path.
/// </summary>
/// This has to be done differently from human paths because we can't leave in any "/" characters (due to
/// problems if the archive is built from or extracted to a filesystem
/// <param name="path"></param>
/// <returns></returns>
public static string EscapeArchivePath(string path)
{
// Only encode ampersands (for escaping anything) and / (since this is used as general dir separator).
return path.Replace("&", "&").Replace("/", "/");
}
/// <summary>
/// Unescape an archive path.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string UnescapeArchivePath(string path)
{
return path.Replace("/", "/").Replace("&", "&");
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.Linq;
[System.Serializable]
class tk2dScratchpadLayer {
public int width, height;
public int[] tiles;
public tk2dScratchpadLayer() {
width = 0;
height = 0;
tiles = new int[0];
}
public void SetDimensions(int _width, int _height) {
int[] newTiles = new int[_width * _height];
for (int y = 0; y < _height; ++y) {
for (int x = 0; x < _width; ++x) {
newTiles[y * _width + x] = (x < width && y < height) ? tiles[y * width + x] : -1;
}
}
tiles = newTiles;
width = _width;
height = _height;
}
public void SplatTile(int x, int y, int rawTile) {
if (x >= 0 && x < width && y >= 0 && y < height) {
tiles[y * width + x] = rawTile;
}
}
public void EraseTiles(int x1, int y1, int x2, int y2) {
for (int y = y1; y <= y2; ++y) {
for (int x = x1; x <= x2; ++x) {
if (x >= 0 && x < width && y >= 0 && y < height) {
tiles[y * width + x] = -1;
}
}
}
}
public int GetTile(int x, int y) {
if (x >= 0 && x < width && y >= 0 && y < height) {
return tiles[y * width + x];
}
return -1;
}
}
[System.Serializable]
public class tk2dTileMapScratchpad
{
[SerializeField] int width;
[SerializeField] int height;
[SerializeField] tk2dScratchpadLayer[] layers;
tk2dTileMapEditorBrush canvas;
public string name = "New Scratchpad";
bool tileSortLeftToRight = true;
bool tileSortBottomToTop = true;
public tk2dTileMapScratchpad() {
width = 0;
height = 0;
layers = new tk2dScratchpadLayer[0];
canvas = new tk2dTileMapEditorBrush();
}
public void SetDimensions(int _width, int _height) {
width = _width;
height = _height;
foreach (tk2dScratchpadLayer layer in layers) {
layer.SetDimensions(width, height);
}
}
public void SetNumLayers(int n) {
tk2dScratchpadLayer[] newLayers = new tk2dScratchpadLayer[n];
for (int i = 0; i < n; ++i) {
newLayers[i] = (i < layers.Length) ? layers[i] : new tk2dScratchpadLayer();
}
layers = newLayers;
SetDimensions(width, height);
}
public void UpdateCanvas() {
List<tk2dSparseTile> newTiles = new List<tk2dSparseTile>();
for (int iLayer = 0; iLayer < layers.Length; ++iLayer) {
tk2dScratchpadLayer layer = layers[iLayer];
for (int y = 0; y < layer.height; ++y) {
for (int x = 0; x < layer.width; ++x) {
int k = y * layer.width + x;
if (layer.tiles[k] != -1) {
newTiles.Add(new tk2dSparseTile(x, y, iLayer, layer.tiles[k]));
}
}
}
}
canvas.tiles = newTiles.ToArray();
canvas.SortTiles(tileSortLeftToRight, tileSortBottomToTop);
canvas.UpdateBrushHash();
}
public void SplatTile(int x, int y, int layer, int rawTile) {
if (layer >= 0 && layer < layers.Length) {
layers[layer].SplatTile(x, y, rawTile);
}
}
public void EraseTiles(int x1, int y1, int x2, int y2, int layer) {
if (layer >= 0 && layer < layers.Length) {
layers[layer].EraseTiles(x1, y1, x2, y2);
}
}
public int GetTile(int x, int y, int layer) {
if (layer >= 0 && layer < layers.Length) {
return layers[layer].GetTile(x, y);
}
return -1;
}
public void GetDimensions(out int _width, out int _height) {
_width = width;
_height = height;
}
public int GetNumLayers() {
return layers.Length;
}
public void SetTileSort(bool leftToRight, bool bottomToTop) {
tileSortLeftToRight = leftToRight;
tileSortBottomToTop = bottomToTop;
}
public tk2dTileMapEditorBrush CanvasBrush {
get {return canvas;}
}
}
public class tk2dScratchpadGUI {
tk2dTileMapSceneGUI parent = null;
List<tk2dTileMapScratchpad> activeScratchpads = null;
List<tk2dTileMapScratchpad> filteredScratchpads = null;
tk2dTileMapScratchpad currentScratchpad = null;
int currentLayer = 0;
tk2dEditor.BrushRenderer brushRenderer = null;
tk2dTileMapEditorBrush workingBrush = null;
public bool workingHere = false;
public bool doMouseDown = false;
public bool doMouseDrag = false;
public bool doMouseUp = false;
public bool doMouseMove = false;
public Vector2 paintMousePosition = Vector2.zero;
public Rect padAreaRect = new Rect(0, 0, 0, 0);
public bool requestSelectAllTiles = false;
public bool requestClose = false;
public string tooltip = "";
public float scratchZoom = 1.0f;
Vector3 tileSize = Vector3.zero;
Vector2 texelSize = Vector2.one;
public tk2dScratchpadGUI(tk2dTileMapSceneGUI _parent, tk2dEditor.BrushRenderer _brushRenderer, tk2dTileMapEditorBrush _workingBrush) {
parent = _parent;
brushRenderer = _brushRenderer;
workingBrush = _workingBrush;
}
public void SetActiveScratchpads(List<tk2dTileMapScratchpad> scratchpads) {
activeScratchpads = scratchpads;
currentScratchpad = null;
UpdateFilteredScratchpads();
}
public void SetTileSizes(Vector3 _tileSize, Vector2 _texelSize) {
tileSize = _tileSize;
texelSize = _texelSize;
}
public void SetTileSort(bool leftToRight, bool bottomToTop) {
if (currentScratchpad != null)
currentScratchpad.SetTileSort(leftToRight, bottomToTop);
}
Vector2 padsScrollPos = Vector2.zero;
Vector2 canvasScrollPos = Vector2.zero;
int padWidthField = 15;
int padHeightField = 15;
string searchFilter = "";
bool focusName = false;
bool focusSearchFilter = false;
bool focusSearchFilterOnKeyUp = false;
System.Action<int> pendingAction = null;
void SelectScratchpad(tk2dTileMapScratchpad pad) {
currentScratchpad = pad;
if (currentScratchpad != null)
currentScratchpad.GetDimensions(out padWidthField, out padHeightField);
}
public void DrawGUI() {
GUILayout.BeginHorizontal();
GUIStyle centeredLabel = new GUIStyle(EditorStyles.label);
centeredLabel.alignment = TextAnchor.MiddleCenter;
GUIStyle centeredTextField = new GUIStyle(EditorStyles.textField);
centeredTextField.alignment = TextAnchor.MiddleCenter;
GUILayout.BeginVertical(GUILayout.Width(150.0f));
GUILayout.BeginHorizontal();
if (GUILayout.Button("New Scratchpad")) {
if (activeScratchpads != null) {
pendingAction = delegate(int i) {
tk2dTileMapScratchpad newPad = new tk2dTileMapScratchpad();
newPad.SetNumLayers(1);
newPad.SetDimensions(15, 15);
activeScratchpads.Add(newPad);
SelectScratchpad(newPad);
UpdateFilteredScratchpads();
focusName = true;
};
}
}
GUILayout.EndHorizontal();
bool pressedUp = (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.UpArrow);
bool pressedDown = (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.DownArrow);
bool pressedReturn = (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Return);
bool pressedEscape = (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Escape);
if (pressedUp || pressedDown) {
Event.current.Use();
if (filteredScratchpads != null) {
int curIdx = 0;
for (int i = 0; i < filteredScratchpads.Count(); ++i) {
if (filteredScratchpads[i] == currentScratchpad)
curIdx = i;
}
curIdx += pressedDown ? 1 : -1;
curIdx = Mathf.Clamp(curIdx, 0, filteredScratchpads.Count() - 1);
for (int i = 0; i < filteredScratchpads.Count(); ++i) {
if (i == curIdx)
SelectScratchpad(filteredScratchpads[i]);
}
}
}
GUILayout.BeginHorizontal();
GUI.SetNextControlName("SearchFilter");
string newSearchFilter = GUILayout.TextField(searchFilter, tk2dEditorSkin.ToolbarSearch);
if (newSearchFilter != searchFilter) {
searchFilter = newSearchFilter;
UpdateFilteredScratchpads();
if (searchFilter.Length > 0 && filteredScratchpads != null && filteredScratchpads.Count() > 0) {
SelectScratchpad(filteredScratchpads[0]);
}
}
GUILayout.Label("", tk2dEditorSkin.ToolbarSearchRightCap);
GUI.SetNextControlName("dummy");
GUILayout.Box("", GUIStyle.none, GUILayout.Width(0), GUILayout.Height(0));
if (focusSearchFilter || (focusSearchFilterOnKeyUp && Event.current.type == EventType.KeyUp)) {
GUI.FocusControl("dummy");
GUI.FocusControl("SearchFilter");
focusSearchFilter = false;
focusSearchFilterOnKeyUp = false;
}
GUILayout.EndHorizontal();
bool searchHasFocus = (GUI.GetNameOfFocusedControl() == "SearchFilter");
if (pressedEscape) {
if (searchHasFocus && searchFilter.Length > 0) {
searchFilter = "";
UpdateFilteredScratchpads();
}
else {
requestClose = true;
}
}
// Select All
if (pressedReturn && GUI.GetNameOfFocusedControl() != "ScratchpadName") {
requestSelectAllTiles = true;
requestClose = true;
}
padsScrollPos = GUILayout.BeginScrollView(padsScrollPos);
List<tk2dTileMapScratchpad> curList = null;
if (filteredScratchpads != null)
curList = filteredScratchpads;
else if (activeScratchpads != null)
curList = activeScratchpads;
if (curList != null) {
GUILayout.BeginVertical();
foreach (var pad in curList) {
bool selected = currentScratchpad == pad;
if (selected) {
GUILayout.BeginHorizontal();
}
if (GUILayout.Toggle(selected, pad.name, tk2dEditorSkin.SC_ListBoxItem)) {
if (currentScratchpad != pad) {
SelectScratchpad(pad);
}
}
if (selected) {
if (GUILayout.Button("", tk2dEditorSkin.GetStyle("TilemapDeleteItem"))) {
pendingAction = delegate(int i) {
if (EditorUtility.DisplayDialog("Delete Scratchpad \"" + currentScratchpad.name + "\" ?", " ", "Yes", "No"))
{
activeScratchpads.Remove(currentScratchpad);
SelectScratchpad(null);
UpdateFilteredScratchpads();
}
};
}
GUILayout.EndHorizontal();
}
}
GUILayout.EndVertical();
}
GUILayout.EndScrollView();
if (currentScratchpad != null) {
GUILayout.Space(20.0f);
GUILayout.BeginVertical(tk2dEditorSkin.SC_ListBoxBG);
// Select All
if (GUILayout.Button(new GUIContent("Select All", "(Enter)"))) {
requestSelectAllTiles = true;
requestClose = true;
}
// Name
GUI.SetNextControlName("ScratchpadName");
currentScratchpad.name = EditorGUILayout.TextField(currentScratchpad.name, centeredTextField);
if (focusName) {
GUI.FocusControl("ScratchpadName");
focusName = false;
}
// Size
int padWidth, padHeight;
currentScratchpad.GetDimensions(out padWidth, out padHeight);
GUILayout.BeginHorizontal();
padWidthField = EditorGUILayout.IntField(padWidthField);
padHeightField = EditorGUILayout.IntField(padHeightField);
GUILayout.EndHorizontal();
if (padWidthField != padWidth || padHeightField != padHeight) {
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("Apply size change")) {
currentScratchpad.SetDimensions(padWidthField, padHeightField);
}
GUILayout.EndHorizontal();
}
GUILayout.EndVertical();
}
tooltip = GUI.tooltip;
GUILayout.EndVertical();
GUILayout.BeginVertical();
// Painting area
doMouseDown = false;
doMouseDrag = false;
doMouseUp = false;
doMouseMove = false;
if (currentScratchpad != null) {
//temp
currentScratchpad.UpdateCanvas();
int scratchW, scratchH;
currentScratchpad.GetDimensions(out scratchW, out scratchH);
canvasScrollPos = EditorGUILayout.BeginScrollView(canvasScrollPos, GUILayout.Width(Mathf.Min(scratchW * tileSize.x * scratchZoom + 24.0f, Screen.width - 190.0f)));
Rect padRect = GUILayoutUtility.GetRect(scratchW * tileSize.x * scratchZoom, scratchH * tileSize.y * scratchZoom, GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(false));
tk2dGrid.Draw(padRect);
padAreaRect = padRect;
Matrix4x4 canvasMatrix = Matrix4x4.identity;
SceneView sceneview = SceneView.lastActiveSceneView;
if (sceneview != null) {
Camera sceneCam = sceneview.camera;
if (sceneCam != null) {
canvasMatrix = sceneCam.cameraToWorldMatrix;
}
}
canvasMatrix *= Matrix4x4.TRS( new Vector3(padRect.x, padRect.y + padRect.height, 0.0f),
Quaternion.identity,
new Vector3(scratchZoom / texelSize.x, -scratchZoom / texelSize.y, 1.0f));
if (Event.current.type == EventType.Repaint) {
if (brushRenderer != null) {
brushRenderer.DrawBrushInScratchpad(currentScratchpad.CanvasBrush, canvasMatrix, false);
if (workingBrush != null && workingHere) {
brushRenderer.DrawBrushInScratchpad(workingBrush, canvasMatrix, true);
}
}
if (workingHere && parent != null) {
parent.DrawTileCursor();
}
}
Event ev = Event.current;
if (ev.type == EventType.MouseMove || ev.type == EventType.MouseDrag) {
paintMousePosition.x = ev.mousePosition.x - padRect.x;
paintMousePosition.y = padRect.height - (ev.mousePosition.y - padRect.y);
HandleUtility.Repaint();
}
if (ev.button == 0 || ev.button == 1) {
doMouseDown = (ev.type == EventType.MouseDown);
doMouseDrag = (ev.type == EventType.MouseDrag);
doMouseUp = (ev.rawType == EventType.MouseUp);
}
doMouseMove = (ev.type == EventType.MouseMove);
EditorGUILayout.EndScrollView();
GUILayout.BeginHorizontal();
if (GUILayout.Button("+", GUILayout.Width(20)))
scratchZoom *= 1.5f;
if (GUILayout.Button("-", GUILayout.Width(20)))
scratchZoom /= 1.5f;
GUILayout.EndHorizontal();
}
GUILayout.EndVertical();
GUILayout.EndHorizontal();
if (pendingAction != null && Event.current.type == EventType.Repaint) {
pendingAction(0);
pendingAction = null;
HandleUtility.Repaint();
}
}
public void SplatTile(int x, int y, int rawTile) {
if (currentScratchpad != null) {
currentScratchpad.SplatTile(x, y, currentLayer, rawTile);
}
}
public void EraseTiles(int x1, int y1, int x2, int y2) {
if (currentScratchpad != null) {
currentScratchpad.EraseTiles(x1, y1, x2, y2, currentLayer);
}
}
public int GetTile(int x, int y, int layer) {
if (currentScratchpad != null) {
return currentScratchpad.GetTile(x, y, layer);
}
return -1;
}
public void GetScratchpadSize(out int x, out int y) {
if (currentScratchpad != null) {
currentScratchpad.GetDimensions(out x, out y);
} else {
x = 0;
y = 0;
}
}
public void FocusOnSearchFilter(bool onKeyUp) {
if (onKeyUp) focusSearchFilterOnKeyUp = true;
else focusSearchFilter = true;
}
public bool Contains(string s, string text) { return s.ToLower().IndexOf(text.ToLower()) != -1; }
void UpdateFilteredScratchpads() {
if (activeScratchpads != null) {
if (searchFilter.Length == 0) {
filteredScratchpads = activeScratchpads;
}
else {
filteredScratchpads = (from pad in activeScratchpads where Contains(pad.name, searchFilter) select pad)
.OrderBy( a => a.name, new tk2dEditor.Shared.NaturalComparer() )
.ToList();
}
}
else {
filteredScratchpads = null;
}
}
public void GetTilesCropRect(out int x1, out int y1, out int x2, out int y2) {
x1 = 0;
y1 = 0;
x2 = 0;
y2 = 0;
if (currentScratchpad != null) {
int w, h;
currentScratchpad.GetDimensions(out w, out h);
x1 = w - 1;
y1 = h - 1;
x2 = 0;
y2 = 0;
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
if (currentScratchpad.GetTile(x, y, 0) != -1) {
x1 = Mathf.Min(x1, x);
y1 = Mathf.Min(y1, y);
x2 = Mathf.Max(x2, x);
y2 = Mathf.Max(y2, y);
}
}
}
}
}
}
| |
#pragma warning disable 0168
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using Microsoft.VisualStudio.Modeling.Shell;
using nHydrate.DslPackage.Objects;
namespace nHydrate.DslPackage.Forms
{
public partial class FindWindowControl : UserControl
{
#region Settings
public class Settings
{
public bool AllowEntity { get; set; } = true;
public bool AllowView { get; set; } = true;
public bool AllowField { get; set; }
}
#endregion
#region Class Members
public delegate void RefreshDelegate();
private nHydrate.Dsl.nHydrateModel _model = null;
private DiagramDocView _diagram = null;
private ModelingDocData _docData = null;
private List<Microsoft.VisualStudio.Modeling.ModelElement> _modelElements = new List<Microsoft.VisualStudio.Modeling.ModelElement>();
private double _splitterTopHeightValue = 0.7;
private List<FindWindowColumnItem> _mainColumns = new List<FindWindowColumnItem>();
private List<FindWindowColumnItem> _subColumns = new List<FindWindowColumnItem>();
private readonly Settings _settings = new Settings();
#endregion
#region Constructors
public FindWindowControl()
{
InitializeComponent();
lvwMain.DoubleClick += lvwMain_DoubleClick;
lvwMain.KeyDown += lvwMain_KeyDown;
lvwMain.SelectedIndexChanged += lvwMain_SelectedIndexChanged;
lvwMain.ColumnClick += lvwMain_ColumnClick;
lvwMain.AfterLabelEdit += lvwMain_AfterLabelEdit;
lvwSubItem.DoubleClick += lvwSubItem_DoubleClick;
lvwSubItem.KeyDown += lvwSubItem_KeyDown;
lvwSubItem.SelectedIndexChanged += lvwSubItem_SelectedIndexChanged;
lvwSubItem.AfterLabelEdit += lvwSubItem_AfterLabelEdit;
txtSearch.TextChanged += txtSearch_TextChanged;
txtSearch.GotFocus += txtSearch_GotFocus;
txtSearch.Enter += txtSearch_Enter;
cmdSettings.Click += cmdSettings_Click;
#region Setup Main Columns
_mainColumns.Add(new FindWindowColumnItem() { Name = "Type", Visible = true, Type = FindWindowColumnTypeConstants.DataType, ColumnHeader = new ColumnHeader() { Text = "Type", Width = 130 } });
_mainColumns.Add(new FindWindowColumnItem() { Name = "Code Facade", Visible = false, Type = FindWindowColumnTypeConstants.CodeFacade, ColumnHeader = new ColumnHeader() { Text = "Code Facade" } });
_mainColumns.Add(new FindWindowColumnItem() { Name = "Typed Entity", Visible = false, Type = FindWindowColumnTypeConstants.TypedEntity, ColumnHeader = new ColumnHeader() { Text = "Typed Entity" } });
_mainColumns.Add(new FindWindowColumnItem() { Name = "Schema", Visible = false, Type = FindWindowColumnTypeConstants.Schema, ColumnHeader = new ColumnHeader() { Text = "Schema" } });
_mainColumns.Add(new FindWindowColumnItem() { Name = "Is Associative", Visible = false, Type = FindWindowColumnTypeConstants.IsAssociative, ColumnHeader = new ColumnHeader() { Text = "Is Associative" } });
_mainColumns.Add(new FindWindowColumnItem() { Name = "Immutable", Visible = false, Type = FindWindowColumnTypeConstants.Immutable, ColumnHeader = new ColumnHeader() { Text = "Immutable" } });
SetupColumnsMain();
#endregion
#region Setup Sub Columns
_subColumns.Add(new FindWindowColumnItem() { Name = "Datatype", Visible = false, Type = FindWindowColumnTypeConstants.DataType, ColumnHeader = new ColumnHeader() { Text = "Datatype", Width = 130 } });
_subColumns.Add(new FindWindowColumnItem() { Name = "Length", Visible = false, Type = FindWindowColumnTypeConstants.Length, ColumnHeader = new ColumnHeader() { Text = "Length" } });
_subColumns.Add(new FindWindowColumnItem() { Name = "Nullable", Visible = false, Type = FindWindowColumnTypeConstants.Nullable, ColumnHeader = new ColumnHeader() { Text = "Nullable" } });
_subColumns.Add(new FindWindowColumnItem() { Name = "Primary Key", Visible = false, Type = FindWindowColumnTypeConstants.PrimaryKey, ColumnHeader = new ColumnHeader() { Text = "Primary Key" } });
_subColumns.Add(new FindWindowColumnItem() { Name = "Identity", Visible = false, Type = FindWindowColumnTypeConstants.Identity, ColumnHeader = new ColumnHeader() { Text = "Identity" } });
_subColumns.Add(new FindWindowColumnItem() { Name = "Default", Visible = false, Type = FindWindowColumnTypeConstants.Default, ColumnHeader = new ColumnHeader() { Text = "Default" } });
_subColumns.Add(new FindWindowColumnItem() { Name = "Code Facade", Visible = false, Type = FindWindowColumnTypeConstants.CodeFacade, ColumnHeader = new ColumnHeader() { Text = "Code Facade" } });
SetupColumnsSub();
#endregion
//lvwSubItem.Columns.Add(string.Empty, lvwMain.Width - 130 - 40);
lvwMain.Size = new System.Drawing.Size(lvwMain.Size.Width, (int)(this.Height * 0.7));
splitter1.SplitterMoved += splitter1_SplitterMoved;
this.Resize += FindWindowControl_Resize;
contextMenuMain.Opening += mainPopupMenu_Popup;
menuItemMainSelect.Click += SelectMenu_Click;
menuItemMainRefresh.Click += RefreshMenu_Click;
menuItemMainDelete.Click += DeleteMenu_Click;
menuItemMainRelationships.Click += menuItemMainRelationships_Click;
menuItemMainShowRelatedEntities.Click += menuItemMainShowRelatedEntities_Click;
menuItemMainStaticData.Click += menuItemMainStaticData_Click;
menuItemMainViewIndexes.Click += menuItemMainViewIndexes_Click;
menuItemMainSetupColumns.Click += menuItemMainSetupColumns_Click;
contextMenuSub.Opening += subPopupMenu_Popup;
menuItemSubSelect.Click += SelectSubMenu_Click;
menuItemSubDelete.Click += DeleteSubMenu_Click;
menuItemSubSetupColumns.Click += menuItemSubSetupColumns_Click;
}
private void cmdSettings_Click(object sender, EventArgs e)
{
var F = new FindWindowPopupOptionsForm(_settings, this.DisplayObjects);
var l = cmdSettings.Parent.PointToScreen(new Point(0, 0));
l = new Point(l.X, l.Y + pnlType.Size.Height);
F.Location = l;
F.Size = new System.Drawing.Size(pnlType.Width, F.Height);
F.Show();
}
#endregion
#region Methods
private void SetupColumnsMain()
{
_lastColumnClick = -1;
_lastSort = SortOrder.Ascending;
lvwMain.ListViewItemSorter = null;
lvwMain.Sort();
lvwMain.Items.Clear();
lvwMain.Columns.Clear();
lvwMain.Columns.Add("Name", lvwMain.Width - 130 - 40);
foreach (var column in _mainColumns.Where(x => x.Visible))
{
lvwMain.Columns.Add(column.ColumnHeader);
}
if (lvwMain.Columns.Count == 1)
{
lvwMain.HeaderStyle = ColumnHeaderStyle.None;
lvwMain.FullRowSelect = false;
}
else
{
lvwMain.HeaderStyle = ColumnHeaderStyle.Clickable;
lvwMain.FullRowSelect = true;
}
DisplayObjects();
}
private void SetupColumnsSub()
{
lvwSubItem.Items.Clear();
lvwSubItem.Columns.Clear();
lvwSubItem.Columns.Add("Name", lvwSubItem.Width - 130 - 40);
foreach (var column in _subColumns.Where(x => x.Visible))
{
lvwSubItem.Columns.Add(column.ColumnHeader);
}
if (lvwSubItem.Columns.Count == 1)
{
lvwSubItem.HeaderStyle = ColumnHeaderStyle.None;
lvwSubItem.FullRowSelect = false;
}
else
{
lvwSubItem.HeaderStyle = ColumnHeaderStyle.Nonclickable;
lvwSubItem.FullRowSelect = true;
}
DisplaySubObjects();
}
public void SetupObjects(nHydrate.Dsl.nHydrateModel model, DiagramDocView diagram, ModelingDocData docView)
{
_model = model;
_diagram = diagram;
_docData = docView;
_modelElements.Clear();
//Add Entities
foreach (var item in _model.Entities.OrderBy(x => x.Name))
{
_modelElements.Add(item);
}
//Add Views
foreach (var item in _model.Views.OrderBy(x => x.Name))
{
_modelElements.Add(item);
}
this.DisplayObjects();
}
private void DeleteObjects()
{
if (lvwMain.SelectedItems.Count == 0)
return;
if (MessageBox.Show("Do you wish to delete the selected objects?", "Delete?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
var allShapes = _docData.Store.ElementDirectory.AllElements.Where(x => x is Microsoft.VisualStudio.Modeling.Diagrams.ShapeElement).Cast<Microsoft.VisualStudio.Modeling.Diagrams.ShapeElement>();
_model.IsLoading = true;
try
{
using (var transaction = _model.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
{
foreach (ListViewItem item in lvwMain.SelectedItems)
{
var si = item.Tag as Microsoft.VisualStudio.Modeling.ModelElement;
var selected = allShapes.FirstOrDefault(x => x.ModelElement == si);
if (selected != null)
{
if (si is nHydrate.Dsl.Entity) _model.Entities.Remove((nHydrate.Dsl.Entity)si);
else if (si is nHydrate.Dsl.View) _model.Views.Remove((nHydrate.Dsl.View)si);
_modelElements.Remove(si);
}
}
transaction.Commit();
}
}
catch (Exception ex)
{
throw;
}
finally
{
_model.IsLoading = false;
}
DisplayObjects();
}
}
private void DeleteSubObjects()
{
if (lvwSubItem.SelectedItems.Count == 0)
return;
if (MessageBox.Show("Do you wish to delete the selected objects?", "Delete?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_model.IsLoading = true;
try
{
using (var transaction = _model.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
{
foreach (ListViewItem item in lvwSubItem.SelectedItems)
{
var si = item.Tag as Microsoft.VisualStudio.Modeling.ModelElement;
if (si != null)
{
if (si is nHydrate.Dsl.Field)
{
var subItem = si as nHydrate.Dsl.Field;
subItem.Entity.Fields.Remove(subItem);
}
else if (si is nHydrate.Dsl.ViewField)
{
var subItem = si as nHydrate.Dsl.ViewField;
subItem.View.Fields.Remove(subItem);
}
}
}
transaction.Commit();
}
}
catch (Exception ex)
{
throw;
}
finally
{
_model.IsLoading = false;
}
DisplaySubObjects();
}
}
public void RefreshFromDatabase()
{
if (lvwMain.SelectedItems.Count == 0)
return;
var item = lvwMain.SelectedItems[lvwMain.SelectedItems.Count - 1];
var si = item.Tag as nHydrate.Dsl.IDatabaseEntity;
var F = new nHydrate.DslPackage.Forms.RefreshItemFromDatabase(
_model,
si,
_docData.Store,
_docData);
if (F.ShowDialog() == DialogResult.OK)
{
}
}
private void SelectObject()
{
if (lvwMain.SelectedItems.Count == 0)
return;
var item = lvwMain.SelectedItems[lvwMain.SelectedItems.Count - 1];
lvwMain.SelectedItems.Clear();
item.Selected = true;
var allShapes = _docData.Store.ElementDirectory.AllElements
.Where(x => x is Microsoft.VisualStudio.Modeling.Diagrams.ShapeElement)
.Cast<Microsoft.VisualStudio.Modeling.Diagrams.ShapeElement>()
.ToList();
var si = item.Tag as Microsoft.VisualStudio.Modeling.ModelElement;
var selectedShape = allShapes.FirstOrDefault(x => x.ModelElement == si);
if (selectedShape == null)
{
//Do Nothing
}
else if (!selectedShape.IsVisible)
{
MessageBox.Show("The selected object is not visible on the diagram.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
var r = _diagram.SelectObjects(1, new object[] { selectedShape }, 0);
if (((nHydrateDocData)_docData).ModelExplorerToolWindow != null)
((nHydrateDocData)_docData).ModelExplorerToolWindow.SelectElement(selectedShape.ModelElement, false);
_diagram.Show();
}
}
private void SelectSubObject()
{
if (lvwSubItem.SelectedItems.Count == 0)
return;
var item = lvwSubItem.SelectedItems[lvwSubItem.SelectedItems.Count - 1];
lvwSubItem.SelectedItems.Clear();
item.Selected = true;
var allShapes = _docData.Store.ElementDirectory.AllElements.Where(x => x is Microsoft.VisualStudio.Modeling.Diagrams.ShapeElement).Cast<Microsoft.VisualStudio.Modeling.Diagrams.ShapeElement>();
var si = item.Tag as nHydrate.Dsl.IContainerParent;
if (si == null) return;
var selectedShape = allShapes.FirstOrDefault(x => x.ModelElement == si.ContainerParent);
if (selectedShape == null)
{
//Do Nothing
}
else if (!selectedShape.IsVisible)
{
MessageBox.Show("The selected object is not visible on the diagram.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
_diagram.SelectObjects(1, new object[] { selectedShape }, 0);
_diagram.SetSelectedComponents(new object[] { si });
if (((nHydrateDocData)_docData).ModelExplorerToolWindow != null)
((nHydrateDocData)_docData).ModelExplorerToolWindow.SelectElement(si as Microsoft.VisualStudio.Modeling.ModelElement, false);
_diagram.Show();
}
}
private void DisplayObjects()
{
Microsoft.VisualStudio.Modeling.ModelElement selectedObject = null;
if (lvwMain.SelectedItems.Count > 0)
{
selectedObject = lvwMain.SelectedItems[0].Tag as Microsoft.VisualStudio.Modeling.ModelElement;
}
lvwMain.Items.Clear();
foreach (var modelObject in _modelElements)
{
//Add Entities
if (modelObject is nHydrate.Dsl.Entity && _settings.AllowEntity)
{
var item = modelObject as nHydrate.Dsl.Entity;
var marked = false;
if (IsSearchMatch(item.Name))
marked = true;
else if (_settings.AllowField && item.Fields.Any(x => IsSearchMatch(x.Name)))
marked = true;
if (marked)
{
var li = new ListViewItem();
_mainColumns.Where(x => x.Visible).ToList().ForEach(x => li.SubItems.Add(string.Empty));
lvwMain.Items.Add(li);
SetListItemValue(li, _mainColumns.FirstOrDefault(x => x.Type == FindWindowColumnTypeConstants.DataType), "Entity");
SetListItemValue(li, _mainColumns.FirstOrDefault(x => x.Type == FindWindowColumnTypeConstants.CodeFacade), item.CodeFacade);
SetListItemValue(li, _mainColumns.FirstOrDefault(x => x.Type == FindWindowColumnTypeConstants.TypedEntity), item.TypedEntity.ToString());
SetListItemValue(li, _mainColumns.FirstOrDefault(x => x.Type == FindWindowColumnTypeConstants.Schema), item.Schema);
SetListItemValue(li, _mainColumns.FirstOrDefault(x => x.Type == FindWindowColumnTypeConstants.IsAssociative), item.IsAssociative.ToString().ToLower());
SetListItemValue(li, _mainColumns.FirstOrDefault(x => x.Type == FindWindowColumnTypeConstants.Immutable), item.Immutable.ToString().ToLower());
li.ImageIndex = 0;
li.Text = item.Name;
li.Tag = item;
}
}
//Add Views
if (modelObject is nHydrate.Dsl.View && _settings.AllowView)
{
var item = modelObject as nHydrate.Dsl.View;
var marked = false;
if (IsSearchMatch(item.Name))
marked = true;
else if (_settings.AllowField && item.Fields.Any(x => IsSearchMatch(x.Name)))
marked = true;
if (marked)
{
var li = new ListViewItem();
_mainColumns.Where(x => x.Visible).ToList().ForEach(x => li.SubItems.Add(string.Empty));
lvwMain.Items.Add(li);
SetListItemValue(li, _mainColumns.FirstOrDefault(x => x.Type == FindWindowColumnTypeConstants.DataType), "View");
SetListItemValue(li, _mainColumns.FirstOrDefault(x => x.Type == FindWindowColumnTypeConstants.CodeFacade), item.CodeFacade);
SetListItemValue(li, _mainColumns.FirstOrDefault(x => x.Type == FindWindowColumnTypeConstants.Schema), item.Schema);
li.ImageIndex = 1;
li.Text = item.Name;
li.Tag = item;
}
}
}
//Re-select
if (selectedObject != null)
{
var sel = lvwMain.Items.ToList().FirstOrDefault(x => x.Tag == selectedObject);
if (sel != null)
{
sel.Selected = true;
}
}
DisplaySubObjects();
}
private void DisplaySubObjects()
{
if (lvwMain.SelectedItems.Count != 1)
{
lvwSubItem.Items.Clear();
return;
}
Microsoft.VisualStudio.Modeling.ModelElement selectedObject = null;
if (lvwSubItem.SelectedItems.Count > 0)
{
selectedObject = lvwSubItem.SelectedItems[0].Tag as Microsoft.VisualStudio.Modeling.ModelElement;
}
lvwSubItem.Items.Clear();
var si = lvwMain.SelectedItems[0].Tag as Microsoft.VisualStudio.Modeling.ModelElement;
if (si != null)
{
if (si is nHydrate.Dsl.Entity) LoadSubItems((nHydrate.Dsl.Entity)si);
else if (si is nHydrate.Dsl.View) LoadSubItems((nHydrate.Dsl.View)si);
}
//Re-select
if (selectedObject != null)
{
var sel = lvwSubItem.Items.ToList().FirstOrDefault(x => x.Tag == selectedObject);
if (sel != null) sel.Selected = true;
}
}
private void SetListItemValue(ListViewItem item, FindWindowColumnItem column, string value)
{
if (column == null)
return;
var typeColIndex = item.ListView.Columns.IndexOf(column.ColumnHeader);
if (typeColIndex != -1)
item.SubItems[typeColIndex].Text = value;
}
private bool IsSearchMatch(string name)
{
if (txtSearch.Text == string.Empty) return true;
var t = txtSearch.Text.ToLower();
return name.ToLower().Contains(t);
}
private void LoadSubItems(nHydrate.Dsl.Entity item)
{
foreach (var field in item.Fields.OrderBy(x => x.Name))
{
var newItem = new ListViewItem() { Text = field.Name, ImageIndex = 4, Tag = field };
_subColumns.Where(x => x.Visible).ToList().ForEach(x => newItem.SubItems.Add(string.Empty));
lvwSubItem.Items.Add(newItem);
SetListItemValue(newItem, _subColumns.FirstOrDefault(x => x.Type == FindWindowColumnTypeConstants.CodeFacade), field.CodeFacade);
SetListItemValue(newItem, _subColumns.FirstOrDefault(x => x.Type == FindWindowColumnTypeConstants.DataType), field.DataType.ToString());
SetListItemValue(newItem, _subColumns.FirstOrDefault(x => x.Type == FindWindowColumnTypeConstants.Default), field.Default);
SetListItemValue(newItem, _subColumns.FirstOrDefault(x => x.Type == FindWindowColumnTypeConstants.Identity), field.Identity.ToString());
SetListItemValue(newItem, _subColumns.FirstOrDefault(x => x.Type == FindWindowColumnTypeConstants.Length), field.Length.ToString());
SetListItemValue(newItem, _subColumns.FirstOrDefault(x => x.Type == FindWindowColumnTypeConstants.Nullable), field.Nullable.ToString().ToLower());
SetListItemValue(newItem, _subColumns.FirstOrDefault(x => x.Type == FindWindowColumnTypeConstants.PrimaryKey), field.IsPrimaryKey.ToString().ToLower());
}
}
private void LoadSubItems(nHydrate.Dsl.View item)
{
foreach (var field in item.Fields.OrderBy(x => x.Name))
{
var newItem = new ListViewItem() { Text = field.Name, ImageIndex = 4, Tag = field };
_subColumns.Where(x => x.Visible).ToList().ForEach(x => newItem.SubItems.Add(string.Empty));
lvwSubItem.Items.Add(newItem);
SetListItemValue(newItem, _subColumns.FirstOrDefault(x => x.Type == FindWindowColumnTypeConstants.CodeFacade), field.CodeFacade);
SetListItemValue(newItem, _subColumns.FirstOrDefault(x => x.Type == FindWindowColumnTypeConstants.DataType), field.DataType.ToString());
SetListItemValue(newItem, _subColumns.FirstOrDefault(x => x.Type == FindWindowColumnTypeConstants.Default), field.Default);
SetListItemValue(newItem, _subColumns.FirstOrDefault(x => x.Type == FindWindowColumnTypeConstants.Length), field.Length.ToString());
SetListItemValue(newItem, _subColumns.FirstOrDefault(x => x.Type == FindWindowColumnTypeConstants.Nullable), field.Nullable.ToString().ToLower());
}
}
#endregion
#region Event Handlers
private void FindWindowControl_KeyUp(object sender, KeyEventArgs e)
{
e.Handled = true;
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
DisplayObjects();
}
private void lvwSubItem_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
SelectSubObject();
}
else if (e.KeyCode == Keys.Delete)
{
DeleteSubObjects();
}
else if (e.KeyCode == Keys.F2)
{
if (lvwSubItem.SelectedItems.Count > 0)
lvwSubItem.SelectedItems[0].BeginEdit();
}
}
private void lvwMain_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
SelectObject();
}
else if (e.KeyCode == Keys.Delete)
{
DeleteObjects();
}
else if (e.KeyCode == Keys.F2)
{
if (lvwMain.SelectedItems.Count > 0)
lvwMain.SelectedItems[0].BeginEdit();
}
}
private void lvwMain_DoubleClick(object sender, EventArgs e)
{
SelectObject();
}
private void lvwSubItem_DoubleClick(object sender, EventArgs e)
{
SelectSubObject();
}
private void txtSearch_Enter(object sender, EventArgs e)
{
var r = _diagram.SelectObjects(0, new object[] { }, 0);
}
private void txtSearch_GotFocus(object sender, EventArgs e)
{
var r = _diagram.SelectObjects(0, new object[] { }, 0);
}
private void lvwSubItem_SelectedIndexChanged(object sender, EventArgs e)
{
if (lvwSubItem.SelectedItems.Count > 0)
{
var element = lvwSubItem.SelectedItems[0].Tag as Microsoft.VisualStudio.Modeling.ModelElement;
(_docData as nHydrateDocData).ModelExplorerToolWindow.SelectElement(element, false);
}
}
private void lvwMain_SelectedIndexChanged(object sender, EventArgs e)
{
DisplaySubObjects();
if (lvwMain.SelectedItems.Count > 0)
{
var element = lvwMain.SelectedItems[0].Tag as Microsoft.VisualStudio.Modeling.ModelElement;
(_docData as nHydrateDocData).ModelExplorerToolWindow.SelectElement(element, false);
}
}
private void FindWindowControl_Resize(object sender, EventArgs e)
{
lvwMain.Size = new System.Drawing.Size(lvwMain.Size.Width, (int)(this.Height * _splitterTopHeightValue));
}
private void splitter1_SplitterMoved(object sender, SplitterEventArgs e)
{
_splitterTopHeightValue = (lvwMain.Height * 1.0) / this.Height;
}
private int _lastColumnClick = -1;
private SortOrder _lastSort = SortOrder.Ascending;
private void lvwMain_ColumnClick(object sender, ColumnClickEventArgs e)
{
if (_lastColumnClick == e.Column)
{
if (_lastSort == SortOrder.Ascending) _lastSort = SortOrder.Descending; else _lastSort = SortOrder.Ascending;
}
else
{
_lastSort = SortOrder.Ascending;
}
lvwMain.ListViewItemSorter = new nHydrate.Generator.Common.ListViewItemComparer(e.Column, _lastSort);
_lastColumnClick = e.Column;
lvwMain.Sort();
}
private void SelectMenu_Click(object sender, EventArgs e)
{
SelectObject();
}
private void DeleteMenu_Click(object sender, EventArgs e)
{
DeleteObjects();
}
private void RefreshMenu_Click(object sender, EventArgs e)
{
RefreshFromDatabase();
}
private void SelectSubMenu_Click(object sender, EventArgs e)
{
SelectSubObject();
}
private void DeleteSubMenu_Click(object sender, EventArgs e)
{
DeleteSubObjects();
}
private void menuItemSubSetupColumns_Click(object sender, EventArgs e)
{
var F = new FindWindowColumnSetupForm(_subColumns);
if (F.ShowDialog() == DialogResult.OK)
{
SetupColumnsSub();
}
}
private void menuItemMainSetupColumns_Click(object sender, EventArgs e)
{
var F = new FindWindowColumnSetupForm(_mainColumns);
if (F.ShowDialog() == DialogResult.OK)
{
SetupColumnsMain();
}
}
private void menuItemMainViewIndexes_Click(object sender, EventArgs e)
{
if (lvwMain.SelectedItems.Count == 1)
{
var item = lvwMain.SelectedItems[0].Tag as Microsoft.VisualStudio.Modeling.ModelElement;
var list = new List<nHydrate.Dsl.Entity>();
list.Add(item as nHydrate.Dsl.Entity);
var F = new nHydrate.DslPackage.Forms.IndexesForm(list, _model, _model.Store);
F.ShowDialog();
}
}
private void menuItemMainStaticData_Click(object sender, EventArgs e)
{
if (lvwMain.SelectedItems.Count == 1)
{
var item = lvwMain.SelectedItems[0].Tag as Microsoft.VisualStudio.Modeling.ModelElement;
var F = new nHydrate.DslPackage.Forms.StaticDataForm(item as nHydrate.Dsl.Entity, _model.Store);
F.ShowDialog();
}
}
private void menuItemMainShowRelatedEntities_Click(object sender, EventArgs e)
{
if (lvwMain.SelectedItems.Count == 1)
{
var item = lvwMain.SelectedItems[0].Tag as Microsoft.VisualStudio.Modeling.ModelElement;
var F = new nHydrate.DslPackage.Forms.TableExtendedPropertiesForm(item as nHydrate.Dsl.Entity, _diagram.CurrentDiagram);
F.ShowDialog();
}
}
private void menuItemMainRelationships_Click(object sender, EventArgs e)
{
if (lvwMain.SelectedItems.Count == 1)
{
var item = lvwMain.SelectedItems[0].Tag as Microsoft.VisualStudio.Modeling.ModelElement;
var shape = _model.Store.ElementDirectory.AllElements
.Where(x => x is Microsoft.VisualStudio.Modeling.Diagrams.CompartmentShape)
.Cast<Microsoft.VisualStudio.Modeling.Diagrams.CompartmentShape>()
.FirstOrDefault(x => x.ModelElement.Id == item.Id) as nHydrate.Dsl.EntityShape;
if (shape != null)
{
var F = new nHydrate.DslPackage.Forms.RelationCollectionForm(_model, shape, _model.Store, _diagram.CurrentDiagram, _docData as nHydrateDocData);
F.ShowDialog();
}
}
}
private void mainPopupMenu_Popup(object sender, CancelEventArgs e)
{
menuItemMainSep1.Visible = false;
menuItemMainStaticData.Visible = false;
menuItemMainViewIndexes.Visible = false;
menuItemMainShowRelatedEntities.Visible = false;
menuItemMainRefresh.Visible = false;
menuItemMainRelationships.Visible = false;
menuItemMainSelect.Visible = false;
menuItemMainDelete.Visible = false;
if (lvwMain.SelectedItems.Count == 1)
{
var item = lvwMain.SelectedItems[0].Tag as Microsoft.VisualStudio.Modeling.ModelElement;
if (item is nHydrate.Dsl.Entity)
{
foreach (var menuItem in contextMenuMain.Items)
{
if (menuItem is ToolStripMenuItem)
((ToolStripMenuItem)menuItem).Visible = true;
}
}
menuItemMainSelect.Visible = true;
menuItemMainSep1.Visible = true;
menuItemMainRefresh.Visible = true;
menuItemMainDelete.Visible = true;
}
}
private void subPopupMenu_Popup(object sender, CancelEventArgs e)
{
menuItemSubSelect.Visible = (lvwSubItem.SelectedItems.Count == 1);
menuItemSubDelete.Visible = (lvwSubItem.SelectedItems.Count > 0);
}
private void lvwSubItem_AfterLabelEdit(object sender, LabelEditEventArgs e)
{
if (string.IsNullOrEmpty(e.Label))
{
e.CancelEdit = true;
return;
}
using (var transaction = _docData.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
{
var element = lvwSubItem.Items[e.Item].Tag as Microsoft.VisualStudio.Modeling.ModelElement;
nHydrate.DslPackage.Objects.Utils.SetPropertyValue<string>(element, "Name", e.Label);
transaction.Commit();
}
}
private void lvwMain_AfterLabelEdit(object sender, LabelEditEventArgs e)
{
if (string.IsNullOrEmpty(e.Label))
{
e.CancelEdit = true;
return;
}
using (var transaction = _docData.Store.TransactionManager.BeginTransaction(Guid.NewGuid().ToString()))
{
var element = lvwMain.Items[e.Item].Tag as Microsoft.VisualStudio.Modeling.ModelElement;
nHydrate.DslPackage.Objects.Utils.SetPropertyValue<string>(element, "Name", e.Label);
transaction.Commit();
}
}
#endregion
}
}
| |
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// 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 Gallio.Loader;
using Gallio.Runtime;
namespace Gallio.VisualStudio.Shell.Core
{
/// <summary>
/// Initializes the Gallio runtime and the <see cref="DefaultShell" />
/// when both the Shell Add-In and Shell Package have been installed and activated.
/// </summary>
public class ShellProxy
{
private static readonly ShellProxy instance = new ShellProxy();
private ShellAddInHandler addInHandler;
private ShellPackage package;
private ShellHolder holder;
internal delegate void HookAccessor(ShellHooks hooks);
private ShellProxy()
{
}
/// <summary>
/// Gets the singleton instance of the proxy.
/// </summary>
public static ShellProxy Instance
{
get { return instance; }
}
/// <summary>
/// Gets the add-in handler, or null if the add-in is not connected.
/// </summary>
public ShellAddInHandler AddInHandler
{
get { return addInHandler; }
}
/// <summary>
/// Gets the add-in handler, or null if the package is not initialized.
/// </summary>
public ShellPackage Package
{
get { return package; }
}
/// <summary>
/// Called when the Shell Add-In has been connected.
/// </summary>
/// <param name="addInHandler">The add-in handler.</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="addInHandler"/> is null.</exception>
/// <exception cref="InvalidOperationException">Thrown if a different <paramref name="addInHandler"/> has already reported being connected.</exception>
public void AddInConnected(ShellAddInHandler addInHandler)
{
if (addInHandler == null)
throw new ArgumentNullException("addInHandler");
ShellLock.WithWriterLock(() =>
{
if (this.addInHandler != null)
{
if (this.addInHandler == addInHandler)
return;
throw new InvalidOperationException("Multiple add-in handlers appear to be attempting to activate the shell.");
}
this.addInHandler = addInHandler;
UpdateShellActivationWithWriterLockHeld();
});
}
/// <summary>
/// Called when the Shell Add-In has been disconnected.
/// </summary>
public void AddInDisconnected()
{
ShellLock.WithWriterLock(() =>
{
addInHandler = null;
UpdateShellActivationWithWriterLockHeld();
});
}
/// <summary>
/// Called when the Shell package has been initialized.
/// </summary>
/// <param name="package">The shell package</param>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="package"/> is null.</exception>
/// <exception cref="InvalidOperationException">Thrown if a different <paramref name="package"/> has already reported being initialized.</exception>
public void PackageInitialized(ShellPackage package)
{
if (package == null)
throw new ArgumentNullException("package");
ShellLock.WithWriterLock(() =>
{
if (this.package != null)
{
if (this.package == package)
return;
throw new InvalidOperationException(
"Multiple packages appear to be attempting to activate the shell.");
}
this.package = package;
UpdateShellActivationWithWriterLockHeld();
});
}
/// <summary>
/// Called when the Shell package has been disposed.
/// </summary>
public void PackageDisposed()
{
ShellLock.WithWriterLock(() =>
{
package = null;
UpdateShellActivationWithWriterLockHeld();
});
}
internal void InvokeHook(HookAccessor accessor)
{
ShellLock.WithReaderLock(() =>
{
if (holder != null)
holder.InvokeHook(accessor);
});
}
private void UpdateShellActivationWithWriterLockHeld()
{
if (package != null && addInHandler != null)
{
SetupRuntime();
if (holder == null)
holder = ShellHolder.Initialize(package, addInHandler);
}
else
{
if (holder != null)
{
try
{
holder.Dispose();
}
finally
{
holder = null;
}
}
}
}
private static void SetupRuntime()
{
LoaderManager.InitializeAndSetupRuntimeIfNeeded();
}
private sealed class ShellHolder : IDisposable
{
private readonly DefaultShell shell;
private ShellHolder(DefaultShell shell)
{
this.shell = shell;
}
public static ShellHolder Initialize(ShellPackage shellPackage, ShellAddInHandler shellAddInHandler)
{
DefaultShell shell = ShellAccessor.Instance;
shell.Initialize(shellPackage, shellAddInHandler);
return new ShellHolder(shell);
}
public void Dispose()
{
shell.Shutdown();
}
public void InvokeHook(HookAccessor accessor)
{
accessor(shell.ShellHooks);
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI
{
using System;
using NPOI.POIFS.Common;
using NPOI.Util;
using NPOI.OpenXml4Net.Exceptions;
using System.IO;
using NPOI.OpenXml4Net.OPC;
using System.Collections.Generic;
using NPOI.OpenXml4Net;
using System.Reflection;
public abstract class POIXMLDocument : POIXMLDocumentPart
{
public static String DOCUMENT_CREATOR = "NPOI";
// OLE embeddings relation name
public static String OLE_OBJECT_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject";
// Embedded OPC documents relation name
public static String PACK_OBJECT_REL_TYPE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/package";
/** The OPC Package */
private OPCPackage pkg;
/**
* The properties of the OPC namespace, opened as needed
*/
private POIXMLProperties properties;
protected POIXMLDocument(OPCPackage pkg)
: base(pkg)
{
this.pkg = pkg;
}
/**
* Wrapper to open a namespace, returning an IOException
* in the event of a problem.
* Works around shortcomings in java's this() constructor calls
*/
public static OPCPackage OpenPackage(String path)
{
try
{
return OPCPackage.Open(path);
}
catch (InvalidFormatException e)
{
throw new IOException(e.ToString());
}
}
public OPCPackage Package
{
get
{
return this.pkg;
}
}
protected PackagePart CorePart
{
get
{
return GetPackagePart();
}
}
/**
* Retrieves all the PackageParts which are defined as
* relationships of the base document with the
* specified content type.
*/
protected PackagePart[] GetRelatedByType(String contentType)
{
PackageRelationshipCollection partsC =
GetPackagePart().GetRelationshipsByType(contentType);
PackagePart[] parts = new PackagePart[partsC.Size];
int count = 0;
foreach (PackageRelationship rel in partsC)
{
parts[count] = GetPackagePart().GetRelatedPart(rel);
count++;
}
return parts;
}
/**
* Checks that the supplied Stream (which MUST
* support mark and reSet, or be a PushbackStream)
* has a OOXML (zip) header at the start of it.
* If your Stream does not support mark / reSet,
* then wrap it in a PushBackStream, then be
* sure to always use that, and not the original!
* @param inp An Stream which supports either mark/reSet, or is a PushbackStream
*/
public static bool HasOOXMLHeader(Stream inp)
{
// We want to peek at the first 4 bytes
byte[] header = new byte[4];
IOUtils.ReadFully(inp, header);
// Wind back those 4 bytes
if (inp is PushbackStream)
{
PushbackStream pin = (PushbackStream)inp;
pin.Position = pin.Position - 4;
}
else
{
inp.Position = 0;
}
// Did it match the ooxml zip signature?
return (
header[0] == POIFSConstants.OOXML_FILE_HEADER[0] &&
header[1] == POIFSConstants.OOXML_FILE_HEADER[1] &&
header[2] == POIFSConstants.OOXML_FILE_HEADER[2] &&
header[3] == POIFSConstants.OOXML_FILE_HEADER[3]
);
}
/**
* Get the document properties. This gives you access to the
* core ooxml properties, and the extended ooxml properties.
*/
public POIXMLProperties GetProperties()
{
if (properties == null)
{
try
{
properties = new POIXMLProperties(pkg);
}
catch (Exception e)
{
throw new POIXMLException(e);
}
}
return properties;
}
/**
* Get the document's embedded files.
*/
public abstract List<PackagePart> GetAllEmbedds();
protected void Load(POIXMLFactory factory)
{
Dictionary<PackagePart, POIXMLDocumentPart> context = new Dictionary<PackagePart, POIXMLDocumentPart>();
try
{
Read(factory, context);
}
catch (OpenXml4NetException e)
{
throw new POIXMLException(e);
}
OnDocumentRead();
context.Clear();
}
/**
* Write out this document to an Outputstream.
*
* @param stream - the java Stream you wish to write the file to
*
* @exception IOException if anything can't be written.
*/
public void Write(Stream stream)
{
if (!this.GetProperties().CustomProperties.Contains("Generator"))
this.GetProperties().CustomProperties.AddProperty("Generator", "NPOI");
if (!this.GetProperties().CustomProperties.Contains("Generator Version"))
this.GetProperties().CustomProperties.AddProperty("Generator Version", Assembly.GetExecutingAssembly().GetName().Version.ToString(3));
//force all children to commit their Changes into the underlying OOXML Package
List<PackagePart> context = new List<PackagePart>();
OnSave(context);
context.Clear();
//save extended and custom properties
GetProperties().Commit();
Package.Save(stream);
}
}
}
| |
#region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace Irony.Parsing.Construction
{
// Methods constructing LALR automaton.
// See _about_parser_construction.txt file in this folder for important comments
internal partial class ParserDataBuilder
{
private LanguageData _language;
private ParserData _data;
private Grammar _grammar;
private ParserStateHash _stateHash = new ParserStateHash();
internal ParserDataBuilder(LanguageData language)
{
this._language = language;
this._grammar = this._language.Grammar;
}
public void Build()
{
this._stateHash.Clear();
this._data = this._language.ParserData;
this.CreateParserStates();
var itemsNeedLookaheads = this.GetReduceItemsInInadequateState();
this.ComputeTransitions(itemsNeedLookaheads);
this.ComputeLookaheads(itemsNeedLookaheads);
this.ComputeStatesExpectedTerminals();
this.ComputeConflicts();
this.ApplyHints();
this.HandleUnresolvedConflicts();
this.CreateRemainingReduceActions();
//Create error action - if it is not created yet by some hint or custom code
if (this._data.ErrorAction == null)
{
this._data.ErrorAction = new ErrorRecoveryParserAction();
}
}//method
#region Creating parser states
private void CreateParserStates()
{
var grammarData = this._language.GrammarData;
//1. Base automaton: create states for main augmented root for the grammar
this._data.InitialState = this.CreateInitialState(grammarData.AugmentedRoot);
this.ExpandParserStateList(0);
this.CreateAcceptAction(this._data.InitialState, grammarData.AugmentedRoot);
//2. Expand automaton: add parser states from additional roots
foreach (var augmRoot in grammarData.AugmentedSnippetRoots)
{
var initialState = this.CreateInitialState(augmRoot);
this.ExpandParserStateList(this._data.States.Count - 1); //start with just added state - it is the last state in the list
this.CreateAcceptAction(initialState, augmRoot);
}
}
private void CreateAcceptAction(ParserState initialState, NonTerminal augmentedRoot)
{
var root = augmentedRoot.Productions[0].RValues[0];
var shiftAction = initialState.Actions[root] as ShiftParserAction;
var shiftOverRootState = shiftAction.NewState;
shiftOverRootState.Actions[this._grammar.Eof] = new AcceptParserAction();
}
private ParserState CreateInitialState(NonTerminal augmentedRoot)
{
//for an augmented root there is an initial production "Root' -> .Root"; so we need the LR0 item at 0 index
var iniItemSet = new LR0ItemSet();
iniItemSet.Add(augmentedRoot.Productions[0].LR0Items[0]);
var initialState = this.FindOrCreateState(iniItemSet);
var rootNt = augmentedRoot.Productions[0].RValues[0] as NonTerminal;
this._data.InitialStates[rootNt] = initialState;
return initialState;
}
private void ExpandParserStateList(int initialIndex)
{
// Iterate through states (while new ones are created) and create shift transitions and new states
for (int index = initialIndex; index < this._data.States.Count; index++)
{
var state = this._data.States[index];
//Get all possible shifts
foreach (var term in state.BuilderData.ShiftTerms)
{
var shiftItems = state.BuilderData.ShiftItems.SelectByCurrent(term);
//Get set of shifted cores and find/create target state
var shiftedCoreItems = shiftItems.GetShiftedCores();
var newState = this.FindOrCreateState(shiftedCoreItems);
//Create shift action
var newAction = new ShiftParserAction(term, newState);
state.Actions[term] = newAction;
//Link items in old/new states
foreach (var shiftItem in shiftItems)
{
shiftItem.ShiftedItem = newState.BuilderData.AllItems.FindByCore(shiftItem.Core.ShiftedItem);
}//foreach shiftItem
}//foreach term
} //for index
}//method
private ParserState FindOrCreateState(LR0ItemSet coreItems)
{
string key = ComputeLR0ItemSetKey(coreItems);
ParserState state;
if (this._stateHash.TryGetValue(key, out state))
{
return state;
}
//create new state
state = new ParserState("S" + this._data.States.Count);
state.BuilderData = new ParserStateData(state, coreItems);
this._data.States.Add(state);
this._stateHash[key] = state;
return state;
}
#endregion
#region Compute transitions, lookbacks, lookaheads
//We compute only transitions that are really needed to compute lookaheads in inadequate states.
// We start with reduce items in inadequate state and find their lookbacks - this is initial list of transitions.
// Then for each transition in the list we check if it has items with nullable tails; for those items we compute
// lookbacks - these are new or already existing transitons - and so on, we repeat the operation until no new transitions
// are created.
private void ComputeTransitions(LRItemSet forItems)
{
var newItemsNeedLookbacks = forItems;
while (newItemsNeedLookbacks.Count > 0)
{
var newTransitions = this.CreateLookbackTransitions(newItemsNeedLookbacks);
newItemsNeedLookbacks = this.SelectNewItemsThatNeedLookback(newTransitions);
}
}
private LRItemSet SelectNewItemsThatNeedLookback(TransitionList transitions)
{
//Select items with nullable tails that don't have lookbacks yet
var items = new LRItemSet();
foreach (var trans in transitions)
{
foreach (var item in trans.Items)
{
if (item.Core.TailIsNullable && item.Lookbacks.Count == 0)
{
//only if it does not have lookbacks yet
items.Add(item);
}
}
}
return items;
}
private LRItemSet GetReduceItemsInInadequateState()
{
var result = new LRItemSet();
foreach (var state in this._data.States)
{
if (state.BuilderData.IsInadequate)
{
result.UnionWith(state.BuilderData.ReduceItems);
}
}
return result;
}
private TransitionList CreateLookbackTransitions(LRItemSet sourceItems)
{
var newTransitions = new TransitionList();
//Build set of initial cores - this is optimization for performance
//We need to find all initial items in all states that shift into one of sourceItems
// Each such initial item would have the core from the "initial" cores set that we build from source items.
var iniCores = new LR0ItemSet();
foreach (var sourceItem in sourceItems)
{
iniCores.Add(sourceItem.Core.Production.LR0Items[0]);
}
//find
foreach (var state in this._data.States)
{
foreach (var iniItem in state.BuilderData.InitialItems)
{
if (!iniCores.Contains(iniItem.Core))
{
continue;
}
var iniItemNt = iniItem.Core.Production.LValue; // iniItem's non-terminal (left side of production)
Transition lookback = null; // local var for lookback - transition over iniItemNt
var currItem = iniItem; // iniItem is initial item for all currItem's in the shift chain.
while (currItem != null)
{
if (sourceItems.Contains(currItem))
{
// We create transitions lazily, only when we actually need them. Check if we have iniItem's transition
// in local variable; if not, get it from state's transitions table; if not found, create it.
if (lookback == null && !state.BuilderData.Transitions.TryGetValue(iniItemNt, out lookback))
{
lookback = new Transition(state, iniItemNt);
newTransitions.Add(lookback);
}
//Now for currItem, either add trans to Lookbacks, or "include" it into currItem.Transition
// We need lookbacks ONLY for final items; for non-Final items we need proper Include lists on transitions
if (currItem.Core.IsFinal)
{
currItem.Lookbacks.Add(lookback);
}
else
{
// if (currItem.Transition != null)
// Note: looks like checking for currItem.Transition is redundant - currItem is either:
// - Final - always the case for the first run of this method;
// - it has a transition after the first run, due to the way we select sourceItems list
// in SelectNewItemsThatNeedLookback (by transitions)
currItem.Transition.Include(lookback);
}
}//if
//move to next item
currItem = currItem.ShiftedItem;
}//while
}//foreach iniItem
}//foreach state
return newTransitions;
}
private void ComputeLookaheads(LRItemSet forItems)
{
foreach (var reduceItem in forItems)
{
// Find all source states - those that contribute lookaheads
var sourceStates = new ParserStateSet();
foreach (var lookbackTrans in reduceItem.Lookbacks)
{
sourceStates.Add(lookbackTrans.ToState);
sourceStates.UnionWith(lookbackTrans.ToState.BuilderData.ReadStateSet);
foreach (var includeTrans in lookbackTrans.Includes)
{
sourceStates.Add(includeTrans.ToState);
sourceStates.UnionWith(includeTrans.ToState.BuilderData.ReadStateSet);
}//foreach includeTrans
}//foreach lookbackTrans
//Now merge all shift terminals from all source states
foreach (var state in sourceStates)
{
reduceItem.Lookaheads.UnionWith(state.BuilderData.ShiftTerminals);
}
//Remove SyntaxError - it is pseudo terminal
if (reduceItem.Lookaheads.Contains(this._grammar.SyntaxError))
{
reduceItem.Lookaheads.Remove(this._grammar.SyntaxError);
}
//Sanity check
if (reduceItem.Lookaheads.Count == 0)
{
this._language.Errors.Add(GrammarErrorLevel.InternalError, reduceItem.State, "Reduce item '{0}' in state {1} has no lookaheads.", reduceItem.Core, reduceItem.State);
}
}//foreach reduceItem
}//method
#endregion
#region Analyzing and resolving conflicts
private void ComputeConflicts()
{
foreach (var state in this._data.States)
{
if (!state.BuilderData.IsInadequate)
{
continue;
}
//first detect conflicts
var stateData = state.BuilderData;
stateData.Conflicts.Clear();
var allLkhds = new BnfTermSet();
//reduce/reduce --------------------------------------------------------------------------------------
foreach (var item in stateData.ReduceItems)
{
foreach (var lkh in item.Lookaheads)
{
if (allLkhds.Contains(lkh))
{
state.BuilderData.Conflicts.Add(lkh);
}
allLkhds.Add(lkh);
}//foreach lkh
}//foreach item
//shift/reduce ---------------------------------------------------------------------------------------
foreach (var term in stateData.ShiftTerminals)
{
if (allLkhds.Contains(term))
{
stateData.Conflicts.Add(term);
}
}
}
}//method
private void ApplyHints()
{
foreach (var state in this._data.States)
{
var stateData = state.BuilderData;
//Add automatic precedence hints
if (stateData.Conflicts.Count > 0)
{
foreach (var conflict in stateData.Conflicts.ToList())
{
if (conflict.Flags.IsSet(TermFlags.IsOperator))
{
//Find any reduce item with this lookahead and add PrecedenceHint
var reduceItem = stateData.ReduceItems.SelectByLookahead(conflict).First();
var precHint = new PrecedenceHint();
reduceItem.Core.Hints.Add(precHint);
}
}
}
// Apply (activate) hints - these should resolve conflicts as well
foreach (var item in state.BuilderData.AllItems)
{
foreach (var hint in item.Core.Hints)
{
hint.Apply(this._language, item);
}
}
}//foreach
}//method
//Resolve to default actions
private void HandleUnresolvedConflicts()
{
foreach (var state in this._data.States)
{
if (state.BuilderData.Conflicts.Count == 0)
{
continue;
}
var shiftReduceConflicts = state.BuilderData.GetShiftReduceConflicts();
var reduceReduceConflicts = state.BuilderData.GetReduceReduceConflicts();
var stateData = state.BuilderData;
if (shiftReduceConflicts.Count > 0)
{
this._language.Errors.Add(GrammarErrorLevel.Conflict, state, Resources.ErrSRConflict, state, shiftReduceConflicts.ToString());
}
if (reduceReduceConflicts.Count > 0)
{
this._language.Errors.Add(GrammarErrorLevel.Conflict, state, Resources.ErrRRConflict, state, reduceReduceConflicts.ToString());
}
//Create default actions for these conflicts. For shift-reduce, default action is shift, and shift action already
// exist for all shifts from the state, so we don't need to do anything, only report it
//For reduce-reduce create reduce actions for the first reduce item (whatever comes first in the set).
foreach (var conflict in reduceReduceConflicts)
{
var reduceItems = stateData.ReduceItems.SelectByLookahead(conflict);
var firstProd = reduceItems.First().Core.Production;
var action = new ReduceParserAction(firstProd);
state.Actions[conflict] = action;
}
//stateData.Conflicts.Clear(); -- do not clear them, let the set keep the auto-resolved conflicts, may find more use for this later
}
}
#endregion
#region final actions: creating remaining reduce actions, computing expected terminals, cleaning up state data
//Create reduce actions for states with a single reduce item (and no shifts)
private void CreateRemainingReduceActions()
{
foreach (var state in this._data.States)
{
if (state.DefaultAction != null)
{
continue;
}
var stateData = state.BuilderData;
if (stateData.ShiftItems.Count == 0 && stateData.ReduceItems.Count == 1)
{
state.DefaultAction = ReduceParserAction.Create(stateData.ReduceItems.First().Core.Production);
continue; //next state; if we have default reduce action, we don't need to fill actions dictionary for lookaheads
}
//create actions
foreach (var item in state.BuilderData.ReduceItems)
{
var action = ReduceParserAction.Create(item.Core.Production);
foreach (var lkh in item.Lookaheads)
{
if (state.Actions.ContainsKey(lkh))
{
continue;
}
state.Actions[lkh] = action;
}
}//foreach item
}//foreach state
}
//Note that for states with a single reduce item the result is empty
private void ComputeStatesExpectedTerminals()
{
foreach (var state in this._data.States)
{
state.ExpectedTerminals.UnionWith(state.BuilderData.ShiftTerminals);
//Add lookaheads from reduce items
foreach (var reduceItem in state.BuilderData.ReduceItems)
{
state.ExpectedTerminals.UnionWith(reduceItem.Lookaheads);
}
this.RemoveTerminals(state.ExpectedTerminals, this._grammar.SyntaxError, this._grammar.Eof);
}//foreach state
}
private void RemoveTerminals(TerminalSet terms, params Terminal[] termsToRemove)
{
foreach (var termToRemove in termsToRemove)
{
if (terms.Contains(termToRemove))
{
terms.Remove(termToRemove);
}
}
}
public void CleanupStateData()
{
foreach (var state in this._data.States)
{
state.ClearData();
}
}
#endregion
#region Utilities: ComputeLR0ItemSetKey
//Parser states are distinguished by the subset of kernel LR0 items.
// So when we derive new LR0-item list by shift operation,
// we need to find out if we have already a state with the same LR0Item list.
// We do it by looking up in a state hash by a key - [LR0 item list key].
// Each list's key is a concatenation of items' IDs separated by ','.
// Before producing the key for a list, the list must be sorted;
// thus we garantee one-to-one correspondence between LR0Item sets and keys.
// And of course, we count only kernel items (with dot NOT in the first position).
public static string ComputeLR0ItemSetKey(LR0ItemSet items)
{
if (items.Count == 0)
{
return string.Empty;
}
//Copy non-initial items to separate list, and then sort it
LR0ItemList itemList = new LR0ItemList();
foreach (var item in items)
{
itemList.Add(item);
}
//quick shortcut
if (itemList.Count == 1)
{
return itemList[0].ID.ToString();
}
itemList.Sort(CompareLR0Items); //Sort by ID
//now build the key
StringBuilder sb = new StringBuilder(100);
foreach (LR0Item item in itemList)
{
sb.Append(item.ID);
sb.Append(",");
}//foreach
return sb.ToString();
}
private static int CompareLR0Items(LR0Item x, LR0Item y)
{
if (x.ID < y.ID)
{
return -1;
}
if (x.ID == y.ID)
{
return 0;
}
return 1;
}
#endregion
#region comments
// Computes set of expected terms in a parser state. While there may be extended list of symbols expected at some point,
// we want to reorganize and reduce it. For example, if the current state expects all arithmetic operators as an input,
// it would be better to not list all operators (+, -, *, /, etc) but simply put "operator" covering them all.
// To achieve this grammar writer can group operators (or any other terminals) into named groups using Grammar's methods
// AddTermReportGroup, AddNoReportGroup etc. Then instead of reporting each operator separately, Irony would include
// a single "group name" to represent them all.
// The "expected report set" is not computed during parser construction (it would bite considerable time), but on demand during parsing,
// when error is detected and the expected set is actually needed for error message.
// Multi-threading concerns. When used in multi-threaded environment (web server), the LanguageData would be shared in
// application-wide cache to avoid rebuilding the parser data on every request. The LanguageData is immutable, except
// this one case - the expected sets are constructed late by CoreParser on the when-needed basis.
// We don't do any locking here, just compute the set and on return from this function the state field is assigned.
// We assume that this field assignment is an atomic, concurrency-safe operation. The worst thing that might happen
// is "double-effort" when two threads start computing the same set around the same time, and the last one to finish would
// leave its result in the state field.
#endregion
internal static StringSet ComputeGroupedExpectedSetForState(Grammar grammar, ParserState state)
{
var terms = new TerminalSet();
terms.UnionWith(state.ExpectedTerminals);
var result = new StringSet();
//Eliminate no-report terminals
foreach (var group in grammar.TermReportGroups)
{
if (group.GroupType == TermReportGroupType.DoNotReport)
{
terms.ExceptWith(group.Terminals);
}
}
//Add normal and operator groups
foreach (var group in grammar.TermReportGroups)
{
if ((group.GroupType == TermReportGroupType.Normal || group.GroupType == TermReportGroupType.Operator) &&
terms.Overlaps(group.Terminals))
{
result.Add(group.Alias);
terms.ExceptWith(group.Terminals);
}
}
//Add remaining terminals "as is"
foreach (var terminal in terms)
{
result.Add(terminal.ErrorAlias);
}
return result;
}
}//class
}//namespace
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Principal;
using System.Diagnostics.Contracts;
namespace System.Security.AccessControl
{
public enum AccessControlType
{
Allow = 0,
Deny = 1,
}
public abstract class AuthorizationRule
{
#region Private Members
private readonly IdentityReference _identity;
private readonly int _accessMask;
private readonly bool _isInherited;
private readonly InheritanceFlags _inheritanceFlags;
private readonly PropagationFlags _propagationFlags;
#endregion
#region Constructors
internal protected AuthorizationRule(
IdentityReference identity,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags )
{
if ( identity == null )
{
throw new ArgumentNullException( "identity" );
}
if ( accessMask == 0 )
{
throw new ArgumentException(
SR.Argument_ArgumentZero,
"accessMask" );
}
if ( inheritanceFlags < InheritanceFlags.None || inheritanceFlags > (InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit) )
{
throw new ArgumentOutOfRangeException(
"inheritanceFlags",
SR.Format( SR.Argument_InvalidEnumValue, inheritanceFlags, "InheritanceFlags" ));
}
if ( propagationFlags < PropagationFlags.None || propagationFlags > (PropagationFlags.NoPropagateInherit | PropagationFlags.InheritOnly) )
{
throw new ArgumentOutOfRangeException(
"propagationFlags",
SR.Format(SR.Argument_InvalidEnumValue, inheritanceFlags, "PropagationFlags"));
}
Contract.EndContractBlock();
if (identity.IsValidTargetType(typeof(SecurityIdentifier)) == false)
{
throw new ArgumentException(
SR.Arg_MustBeIdentityReferenceType,
"identity");
}
_identity = identity;
_accessMask = accessMask;
_isInherited = isInherited;
_inheritanceFlags = inheritanceFlags;
if ( inheritanceFlags != 0 )
{
_propagationFlags = propagationFlags;
}
else
{
_propagationFlags = 0;
}
}
#endregion
#region Properties
public IdentityReference IdentityReference
{
get { return _identity; }
}
internal protected int AccessMask
{
get { return _accessMask; }
}
public bool IsInherited
{
get { return _isInherited; }
}
public InheritanceFlags InheritanceFlags
{
get { return _inheritanceFlags; }
}
public PropagationFlags PropagationFlags
{
get { return _propagationFlags; }
}
#endregion
}
public abstract class AccessRule : AuthorizationRule
{
#region Private Methods
private readonly AccessControlType _type;
#endregion
#region Constructors
protected AccessRule(
IdentityReference identity,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AccessControlType type )
: base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags )
{
if ( type != AccessControlType.Allow &&
type != AccessControlType.Deny )
{
throw new ArgumentOutOfRangeException(
"type",
SR.ArgumentOutOfRange_Enum );
}
if ( inheritanceFlags < InheritanceFlags.None || inheritanceFlags > (InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit) )
{
throw new ArgumentOutOfRangeException(
"inheritanceFlags",
SR.Format(SR.Argument_InvalidEnumValue, inheritanceFlags, "InheritanceFlags"));
}
if ( propagationFlags < PropagationFlags.None || propagationFlags > (PropagationFlags.NoPropagateInherit | PropagationFlags.InheritOnly) )
{
throw new ArgumentOutOfRangeException(
"propagationFlags",
SR.Format(SR.Argument_InvalidEnumValue, inheritanceFlags, "PropagationFlags"));
}
Contract.EndContractBlock();
_type = type;
}
#endregion
#region Properties
public AccessControlType AccessControlType
{
get { return _type; }
}
#endregion
}
public abstract class ObjectAccessRule: AccessRule
{
#region Private Members
private readonly Guid _objectType;
private readonly Guid _inheritedObjectType;
private readonly ObjectAceFlags _objectFlags = ObjectAceFlags.None;
#endregion
#region Constructors
protected ObjectAccessRule( IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, Guid objectType, Guid inheritedObjectType, AccessControlType type )
: base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags, type )
{
if (( !objectType.Equals( Guid.Empty )) && (( accessMask & ObjectAce.AccessMaskWithObjectType ) != 0 ))
{
_objectType = objectType;
_objectFlags |= ObjectAceFlags.ObjectAceTypePresent;
}
else
{
_objectType = Guid.Empty;
}
if (( !inheritedObjectType.Equals( Guid.Empty )) && ((inheritanceFlags & InheritanceFlags.ContainerInherit ) != 0 ))
{
_inheritedObjectType = inheritedObjectType;
_objectFlags |= ObjectAceFlags.InheritedObjectAceTypePresent;
}
else
{
_inheritedObjectType = Guid.Empty;
}
}
#endregion
#region Properties
public Guid ObjectType
{
get { return _objectType; }
}
public Guid InheritedObjectType
{
get { return _inheritedObjectType; }
}
public ObjectAceFlags ObjectFlags
{
get { return _objectFlags; }
}
#endregion
}
public abstract class AuditRule : AuthorizationRule
{
#region Private Members
private readonly AuditFlags _flags;
#endregion
#region Constructors
protected AuditRule(
IdentityReference identity,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AuditFlags auditFlags )
: base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags )
{
if ( auditFlags == AuditFlags.None )
{
throw new ArgumentException(
SR.Arg_EnumAtLeastOneFlag ,
"auditFlags" );
}
else if (( auditFlags & ~( AuditFlags.Success | AuditFlags.Failure )) != 0 )
{
throw new ArgumentOutOfRangeException(
"auditFlags",
SR.ArgumentOutOfRange_Enum );
}
_flags = auditFlags;
}
#endregion
#region Public Properties
public AuditFlags AuditFlags
{
get { return _flags; }
}
#endregion
}
public abstract class ObjectAuditRule: AuditRule
{
#region Private Members
private readonly Guid _objectType;
private readonly Guid _inheritedObjectType;
private readonly ObjectAceFlags _objectFlags = ObjectAceFlags.None;
#endregion
#region Constructors
protected ObjectAuditRule( IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, Guid objectType, Guid inheritedObjectType, AuditFlags auditFlags )
: base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags, auditFlags )
{
if (( !objectType.Equals( Guid.Empty )) && (( accessMask & ObjectAce.AccessMaskWithObjectType ) != 0 ))
{
_objectType = objectType;
_objectFlags |= ObjectAceFlags.ObjectAceTypePresent;
}
else
{
_objectType = Guid.Empty;
}
if (( !inheritedObjectType.Equals( Guid.Empty )) && ((inheritanceFlags & InheritanceFlags.ContainerInherit ) != 0 ))
{
_inheritedObjectType = inheritedObjectType;
_objectFlags |= ObjectAceFlags.InheritedObjectAceTypePresent;
}
else
{
_inheritedObjectType = Guid.Empty;
}
}
#endregion
#region Public Properties
public Guid ObjectType
{
get { return _objectType; }
}
public Guid InheritedObjectType
{
get { return _inheritedObjectType; }
}
public ObjectAceFlags ObjectFlags
{
get { return _objectFlags; }
}
#endregion
}
public sealed class AuthorizationRuleCollection : ICollection, IEnumerable // TODO: Is this right? Was previously ReadOnlyCollectionBase
{
#region ReadOnlyCollectionBase APIs
// Goo to translate this from ReadOnlyCollectionBase to ICollection
Object _syncRoot;
List<AuthorizationRule> list;
List<AuthorizationRule> InnerList
{
get
{
if (list == null)
list = new List<AuthorizationRule>();
return list;
}
}
public int Count
{
get { return InnerList.Count; }
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
void ICollection.CopyTo(Array array, int index)
{
InnerList.CopyTo((AuthorizationRule[])array, index);
}
IEnumerator IEnumerable.GetEnumerator()
{
return InnerList.GetEnumerator();
}
#endregion
#region Constructors
public AuthorizationRuleCollection()
: base()
{
}
#endregion
#region Public methods
public void AddRule(AuthorizationRule rule)
{
InnerList.Add( rule );
}
#endregion
#region ICollection Members
public void CopyTo( AuthorizationRule[] rules, int index )
{
(( ICollection )this ).CopyTo( rules, index );
}
#endregion
#region Public properties
public AuthorizationRule this[int index]
{
get { return InnerList[index] as AuthorizationRule; }
}
#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;
using System.Collections.Generic;
namespace System.Linq.Expressions.Tests
{
partial class ExpressionCatalog
{
private static readonly Type[] s_unaryArithTypesUnaryPlus = new[] { typeof(S1), typeof(ushort), typeof(short), typeof(uint), typeof(int), typeof(ulong), typeof(long), typeof(float), typeof(double) };
private static readonly Type[] s_unaryArithTypesOnesComplement = new[] { typeof(S1), typeof(ushort), typeof(short), typeof(uint), typeof(int), typeof(ulong), typeof(long) };
private static readonly Type[] s_unaryArithTypesNegate = new[] { typeof(S1), typeof(short), typeof(int), typeof(long), typeof(float), typeof(double) };
private static readonly Type[] s_unaryLogicTypes = new[] { typeof(S2), typeof(bool) };
private static readonly Type[] s_unaryIncrDecrTypes = new[] { typeof(S1), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(float), typeof(double) };
private static IEnumerable<Expression> UnaryPlus()
{
foreach (var t in s_unaryArithTypesUnaryPlus)
{
foreach (var o in s_exprs[t])
{
yield return Expression.UnaryPlus(o);
}
}
}
private static IEnumerable<Expression> UnaryPlus_Nullable()
{
foreach (var t in s_unaryArithTypesUnaryPlus)
{
foreach (var o in s_nullableExprs[t])
{
yield return Expression.UnaryPlus(o);
}
}
}
private static IEnumerable<Expression> Negate()
{
foreach (var t in s_unaryArithTypesNegate)
{
foreach (var o in s_exprs[t])
{
yield return Expression.Negate(o);
}
}
}
private static IEnumerable<Expression> Negate_Nullable()
{
foreach (var t in s_unaryArithTypesNegate)
{
foreach (var o in s_nullableExprs[t])
{
yield return Expression.Negate(o);
}
}
}
private static IEnumerable<Expression> NegateChecked()
{
foreach (var t in s_unaryArithTypesNegate)
{
foreach (var o in s_exprs[t])
{
yield return Expression.NegateChecked(o);
}
}
}
private static IEnumerable<Expression> NegateChecked_Nullable()
{
foreach (var t in s_unaryArithTypesNegate)
{
foreach (var o in s_nullableExprs[t])
{
yield return Expression.NegateChecked(o);
}
}
}
private static IEnumerable<Expression> OnesComplement()
{
foreach (var t in s_unaryArithTypesOnesComplement)
{
foreach (var o in s_exprs[t])
{
yield return Expression.OnesComplement(o);
}
}
}
private static IEnumerable<Expression> OnesComplement_Nullable()
{
foreach (var t in s_unaryArithTypesOnesComplement)
{
foreach (var o in s_nullableExprs[t])
{
yield return Expression.OnesComplement(o);
}
}
}
private static IEnumerable<Expression> IsTrue()
{
foreach (var t in s_unaryLogicTypes)
{
foreach (var o in s_exprs[t])
{
yield return Expression.IsTrue(o);
}
}
}
private static IEnumerable<Expression> IsTrue_Nullable()
{
foreach (var t in s_unaryLogicTypes)
{
foreach (var o in s_nullableExprs[t])
{
yield return Expression.IsTrue(o);
}
}
}
private static IEnumerable<Expression> IsFalse()
{
foreach (var t in s_unaryLogicTypes)
{
foreach (var o in s_exprs[t])
{
yield return Expression.IsFalse(o);
}
}
}
private static IEnumerable<Expression> IsFalse_Nullable()
{
foreach (var t in s_unaryLogicTypes)
{
foreach (var o in s_nullableExprs[t])
{
yield return Expression.IsFalse(o);
}
}
}
private static IEnumerable<Expression> Not()
{
foreach (var t in s_unaryLogicTypes)
{
foreach (var o in s_exprs[t])
{
yield return Expression.Not(o);
}
}
}
private static IEnumerable<Expression> Not_Nullable()
{
foreach (var t in s_unaryLogicTypes)
{
foreach (var o in s_nullableExprs[t])
{
yield return Expression.Not(o);
}
}
}
private static IEnumerable<Expression> Increment()
{
foreach (var t in s_unaryIncrDecrTypes)
{
foreach (var o in s_exprs[t])
{
yield return Expression.Increment(o);
}
}
}
private static IEnumerable<Expression> Increment_Nullable()
{
foreach (var t in s_unaryIncrDecrTypes)
{
foreach (var o in s_nullableExprs[t])
{
yield return Expression.Increment(o);
}
}
}
private static IEnumerable<Expression> Decrement()
{
foreach (var t in s_unaryIncrDecrTypes)
{
foreach (var o in s_exprs[t])
{
yield return Expression.Decrement(o);
}
}
}
private static IEnumerable<Expression> Decrement_Nullable()
{
foreach (var t in s_unaryIncrDecrTypes)
{
foreach (var o in s_nullableExprs[t])
{
yield return Expression.Decrement(o);
}
}
}
}
}
| |
// Copyright (c) 2015 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections;
using System.Web.SessionState;
using System.Collections.Specialized;
using System.Reflection;
using Alachisoft.NCache.Serialization.Surrogates;
using System.Collections.Generic;
namespace Alachisoft.NCache.Serialization
{
/// <summary>
/// Provides the common type identification system. Takes care of registering type surrogates
/// and type handles. Provides methods to register <see cref="ICompactSerializable"/> implementations
/// utilizing the built-in surrogate for <see cref="ICompactSerializable"/>.
/// </summary>
public sealed class TypeSurrogateSelector
{
private static readonly Type s_typeofList = typeof(List<>);
private static IDictionary typeSurrogateMap = Hashtable.Synchronized(new Hashtable());
private static IDictionary handleSurrogateMap = Hashtable.Synchronized(new Hashtable());
private static ISerializationSurrogate nullSurrogate = new NullSerializationSurrogate();
private static ISerializationSurrogate defaultSurrogate = new ObjectSerializationSurrogate(typeof(object));
private static ISerializationSurrogate defaultArraySurrogate = new ObjectArraySerializationSurrogate();
private static short typeHandle = short.MinValue;
private static short CUSTOM_TYPE_RANGE = 1000;
/// <summary>
/// Static constructor registers built-in surrogates with the system.
/// </summary>
static TypeSurrogateSelector()
{
RegisterTypeSurrogate(nullSurrogate);
RegisterTypeSurrogate(defaultSurrogate);
RegisterTypeSurrogate(defaultArraySurrogate);
RegisterBuiltinSurrogates();
}
/// <summary>
/// Finds and returns an appropriate <see cref="ISerializationSurrogate"/> for the given
/// object.
/// </summary>
/// <param name="graph">specified object</param>
/// <returns><see cref="ISerializationSurrogate"/> object</returns>
static internal ISerializationSurrogate GetSurrogateForObject(object graph, string cacheContext)
{
if (graph == null)
return nullSurrogate;
Type type = null;
if (graph is ArrayList)
type = typeof(ArrayList);
else if (graph is Hashtable)
type = typeof(Hashtable);
else if (graph is SortedList)
type = typeof(SortedList);
else if (graph.GetType().IsGenericType && typeof(List<>).Equals(graph.GetType().GetGenericTypeDefinition()) && graph.GetType().FullName.Contains("System.Collections.Generic"))
///Its IList<> but see if it is a user defined type that derived from IList<>
type = typeof(IList<>);
else if (graph.GetType().IsGenericType && typeof(Dictionary<,>).Equals(graph.GetType().GetGenericTypeDefinition()) && graph.GetType().FullName.Contains("System.Collections.Generic"))
type = typeof(IDictionary<,>);
else if (graph.GetType().IsArray && UserTypeSurrogateExists(graph.GetType().GetElementType(), cacheContext))
type = (new ObjectArraySerializationSurrogate()).ActualType;
else
type = graph.GetType();
return GetSurrogateForType(type, cacheContext);
}
private static bool UserTypeSurrogateExists(Type type, string cacheContext)
{
bool exists = false;
return exists;
}
/// <summary>
/// Finds and returns an appropriate <see cref="ISerializationSurrogate"/> for the given
/// type if not found returns defaultSurrogate
/// </summary>
/// <param name="type">specified type</param>
/// <param name="cacheContext">CacheName, incase of null only builting registered map is searched</param>
/// <returns><see cref="ISerializationSurrogate"/> object</returns>
static public ISerializationSurrogate GetSurrogateForType(Type type,string cacheContext)
{
ISerializationSurrogate surrogate = (ISerializationSurrogate)typeSurrogateMap[type];
if (surrogate == null)
surrogate = defaultSurrogate;
return surrogate;
}
/// <summary>
/// Finds and returns <see cref="ISerializationSurrogate"/> for the given
/// type if not found returns null
/// </summary>
/// <param name="type">specified type</param>
/// <returns><see cref="ISerializationSurrogate"/> object</returns>
static internal ISerializationSurrogate GetSurrogateForTypeStrict(Type type)
{
ISerializationSurrogate surrogate = null;
surrogate = (ISerializationSurrogate)typeSurrogateMap[type];
return surrogate;
}
/// <summary>
/// Finds and returns an appropriate <see cref="ISerializationSurrogate"/> for the given
/// type handle.
/// </summary>
/// <param name="handle">type handle</param>
/// <returns><see cref="ISerializationSurrogate"/>Object otherwise returns null if typeHandle is base Handle if Portable</returns>
static internal ISerializationSurrogate GetSurrogateForTypeHandle(short handle,string cacheContext)
{
ISerializationSurrogate surrogate = null;
if(handle < CUSTOM_TYPE_RANGE)
surrogate = (ISerializationSurrogate)handleSurrogateMap[handle];
if (surrogate == null)
surrogate = defaultSurrogate;
return surrogate;
}
#region / ISerializationSurrogate registration specific /
/// <summary>
/// Registers built-in surrogates with the system.
/// </summary>
static public void RegisterBuiltinSurrogates()
{
RegisterTypeSurrogate(new BooleanSerializationSurrogate());
RegisterTypeSurrogate(new ByteSerializationSurrogate());
RegisterTypeSurrogate(new CharSerializationSurrogate());
RegisterTypeSurrogate(new SingleSerializationSurrogate());
RegisterTypeSurrogate(new DoubleSerializationSurrogate());
RegisterTypeSurrogate(new DecimalSerializationSurrogate());
RegisterTypeSurrogate(new Int16SerializationSurrogate());
RegisterTypeSurrogate(new Int32SerializationSurrogate());
RegisterTypeSurrogate(new Int64SerializationSurrogate());
RegisterTypeSurrogate(new StringSerializationSurrogate());
RegisterTypeSurrogate(new DateTimeSerializationSurrogate());
RegisterTypeSurrogate(new NullSerializationSurrogate());
RegisterTypeSurrogate(new BooleanArraySerializationSurrogate());
RegisterTypeSurrogate(new ByteArraySerializationSurrogate());
RegisterTypeSurrogate(new CharArraySerializationSurrogate());
RegisterTypeSurrogate(new SingleArraySerializationSurrogate());
RegisterTypeSurrogate(new DoubleArraySerializationSurrogate());
RegisterTypeSurrogate(new Int16ArraySerializationSurrogate());
RegisterTypeSurrogate(new Int32ArraySerializationSurrogate());
RegisterTypeSurrogate(new Int64ArraySerializationSurrogate());
RegisterTypeSurrogate(new StringArraySerializationSurrogate());
RegisterTypeSurrogate(new AverageResultSerializationSurrogate());
//End of File for Java, ie denotes further types are not supported in java
RegisterTypeSurrogate(new EOFJavaSerializationSurrogate());
//End of File for Net, provided by Java ie it denotes not supported in Dot Net
RegisterTypeSurrogate(new EOFNetSerializationSurrogate());
//Skip this value Surrogate
RegisterTypeSurrogate(new SkipSerializationSurrogate());
RegisterTypeSurrogate(new DecimalArraySerializationSurrogate());
RegisterTypeSurrogate(new DateTimeArraySerializationSurrogate());
RegisterTypeSurrogate(new GuidArraySerializationSurrogate());
RegisterTypeSurrogate(new SByteArraySerializationSurrogate());
RegisterTypeSurrogate(new UInt16ArraySerializationSurrogate());
RegisterTypeSurrogate(new UInt32ArraySerializationSurrogate());
RegisterTypeSurrogate(new UInt64ArraySerializationSurrogate());
RegisterTypeSurrogate(new GuidSerializationSurrogate());
RegisterTypeSurrogate(new SByteSerializationSurrogate());
RegisterTypeSurrogate(new UInt16SerializationSurrogate());
RegisterTypeSurrogate(new UInt32SerializationSurrogate());
RegisterTypeSurrogate(new UInt64SerializationSurrogate());
RegisterTypeSurrogate(new ArraySerializationSurrogate(typeof(Array)));
RegisterTypeSurrogate(new IListSerializationSurrogate(typeof(ArrayList)));
///Generics are not supportorted onwards from 4.1
//RegisterTypeSurrogate(new GenericIListSerializationSurrogate(typeof(IList<>)));
RegisterTypeSurrogate(new NullSerializationSurrogate());
RegisterTypeSurrogate(new IDictionarySerializationSurrogate(typeof(Hashtable)));
RegisterTypeSurrogate(new IDictionarySerializationSurrogate(typeof(SortedList)));
///Generics are not supportorted onwards from 4.1
RegisterTypeSurrogate(new NullSerializationSurrogate());
RegisterTypeSurrogate(new SessionStateCollectionSerializationSurrogate(typeof(SessionStateItemCollection)));
RegisterTypeSurrogate(new SessionStateStaticObjectCollectionSerializationSurrogate(typeof(System.Web.HttpStaticObjectsCollection)));
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<Boolean>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<Byte>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<Char>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<Single>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<Double>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<Decimal>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<Int16>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<Int32>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<Int64>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<DateTime>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<Guid>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<SByte>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<UInt16>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<UInt32>());
RegisterTypeSurrogate(new NullableArraySerializationSurrogate<UInt64>());
}
/// <summary>
/// Registers the specified <see cref="ISerializationSurrogate"/> with the system.
/// </summary>
/// <param name="surrogate">specified surrogate</param>
/// <returns>false if the surrogated type already has a surrogate</returns>
static public bool RegisterTypeSurrogate(ISerializationSurrogate surrogate)
{
for (; ; )
{
try
{
return RegisterTypeSurrogate(surrogate, ++typeHandle);
}
catch (ArgumentException) { }
catch (Exception)
{
throw;
}
}
}
/// <summary>
/// Registers the specified <see cref="ISerializationSurrogate"/> with the given type handle.
/// Gives more control over the way type handles are generated by the system and allows the
/// user to supply *HARD* handles for better interoperability among applications.
/// </summary>
/// <param name="surrogate">specified surrogate</param>
/// <param name="typeHandle">specified HARD handle for type</param>
/// <returns>false if the surrogated type already has a surrogate</returns>
static public bool RegisterTypeSurrogate(ISerializationSurrogate surrogate, short typehandle)
{
if (surrogate == null) throw new ArgumentNullException("surrogate");
lock (typeSurrogateMap.SyncRoot)
{
if (handleSurrogateMap.Contains(typehandle))
throw new ArgumentException("Specified type handle is already registered.");
if (!typeSurrogateMap.Contains(surrogate.ActualType))
{
surrogate.TypeHandle = typehandle;
typeSurrogateMap.Add(surrogate.ActualType, surrogate);
handleSurrogateMap.Add(surrogate.TypeHandle, surrogate);
return true;
}
}
return false;
}
/// <summary>
/// Unregisters all surrogates associalted with the caceh context.
/// </summary>
/// <param name="cacheContext"></param>
static public void UnregisterAllSurrogates(string cacheContext)
{
}
/// <summary>
/// Unregisters all surrogates, except null and default ones.
/// </summary>
static public void UnregisterAllSurrogates()
{
lock (typeSurrogateMap.SyncRoot)
{
typeSurrogateMap.Clear();
handleSurrogateMap.Clear();
typeHandle = short.MinValue;
RegisterTypeSurrogate(nullSurrogate);
RegisterTypeSurrogate(defaultSurrogate);
}
}
#endregion
}
}
| |
namespace Rison
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
public class RisonEncoder : IRisonEncoder
{
private StringBuilder output;
public string Encode<T>(T obj)
{
output = new StringBuilder();
WriteValue(obj);
return output.ToString();
}
private void WriteValue(object obj)
{
if (obj == null)
{
WriteNull();
}
else if (obj is char)
{
WriteString(((char) obj).ToString());
}
else if (obj is string)
{
WriteString((string) obj);
}
else if (obj is bool)
{
WriteBool((bool) obj);
}
else if (obj.IsNumber())
{
WriteNumber(obj);
}
else if (obj is DateTime)
{
WriteDateTime((DateTime) obj);
}
else if (obj is Guid || obj is Enum)
{
WriteString(obj.ToString());
}
else if (obj is IDictionary)
{
WriteDictionary((IDictionary) obj);
}
else if (obj is IEnumerable)
{
WriteEnumerable((IEnumerable) obj);
}
else
{
WriteObject(obj);
}
}
private void WriteNull()
{
output.Append("!n");
}
private void WriteBool(bool obj)
{
output.Append(obj ? "!t" : "!f");
}
private void WriteNumber(object obj)
{
var numberAsString = ((IConvertible) obj).ToString(NumberFormatInfo.InvariantInfo);
output.Append(numberAsString.ToLower().Replace("+", ""));
}
private void WriteDateTime(DateTime dateTime)
{
var s = dateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.fffK");
WriteString(s);
}
private void WritePair(string name, object value)
{
output.Append(name);
output.Append(':');
WriteValue(value);
}
private void WriteString(string s)
{
output.Append('\"');
output.Append(s);
output.Append('\"');
}
private void WriteEnumerable(IEnumerable enumerable)
{
output.Append("!(");
var pendingSeperator = false;
foreach (var obj in enumerable)
{
if (pendingSeperator) output.Append(',');
WriteValue(obj);
pendingSeperator = true;
}
output.Append(')');
}
private void WriteDictionary(IDictionary dictionary)
{
output.Append("!(");
var pendingSeparator = false;
foreach (DictionaryEntry entry in dictionary)
{
if (pendingSeparator) output.Append(',');
output.Append('(');
WritePair("k", entry.Key);
output.Append(",");
WritePair("v", entry.Value);
output.Append(')');
pendingSeparator = true;
}
output.Append(')');
}
private void WriteObject(object obj)
{
output.Append('(');
var pendingSeperator = false;
var getters = GetGetters(obj.GetType());
foreach (var getter in getters)
{
if (pendingSeperator) output.Append(',');
var o = getter.Value(obj);
WritePair(getter.Key, o);
pendingSeperator = true;
}
output.Append(')');
}
private static IEnumerable<KeyValuePair<string, Func<object, object>>> GetGetters(Type type)
{
var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
var getters = (from property in properties
where property.CanWrite
let getMethod = CreateGetMethod(property)
where getMethod != null
select new KeyValuePair<string, Func<object, object>>(property.Name, getMethod)).ToList();
var fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public);
getters.AddRange(from field in fields
let getField = CreateGetField(type, field)
where getField != null
select new KeyValuePair<string, Func<object, object>>(field.Name, getField));
return getters;
}
private static Func<object, object> CreateGetMethod(PropertyInfo propertyInfo)
{
var getMethod = propertyInfo.GetGetMethod();
if (getMethod == null)
{
return null;
}
var arguments = new Type[1];
arguments[0] = typeof(object);
var getter = new DynamicMethod("_", typeof(object), arguments);
var il = getter.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Castclass, propertyInfo.DeclaringType);
il.EmitCall(OpCodes.Callvirt, getMethod, null);
if (!propertyInfo.PropertyType.IsClass)
{
il.Emit(OpCodes.Box, propertyInfo.PropertyType);
}
il.Emit(OpCodes.Ret);
return (Func<object, object>)getter.CreateDelegate(typeof(Func<object, object>));
}
private static Func<object, object> CreateGetField(Type type, FieldInfo fieldInfo)
{
var dynamicGet = new DynamicMethod("_", typeof(object), new[] { typeof(object) }, type, true);
var il = dynamicGet.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, fieldInfo);
if (fieldInfo.FieldType.IsValueType)
{
il.Emit(OpCodes.Box, fieldInfo.FieldType);
}
il.Emit(OpCodes.Ret);
return (Func<object, object>)dynamicGet.CreateDelegate(typeof(Func<object, object>));
}
}
}
| |
// 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 OrSingle()
{
var test = new SimpleBinaryOpTest__OrSingle();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__OrSingle
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Single> _fld1;
public Vector128<Single> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__OrSingle testClass)
{
var result = Sse.Or(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__OrSingle testClass)
{
fixed (Vector128<Single>* pFld1 = &_fld1)
fixed (Vector128<Single>* pFld2 = &_fld2)
{
var result = Sse.Or(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single);
private static Single[] _data1 = new Single[Op1ElementCount];
private static Single[] _data2 = new Single[Op2ElementCount];
private static Vector128<Single> _clsVar1;
private static Vector128<Single> _clsVar2;
private Vector128<Single> _fld1;
private Vector128<Single> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__OrSingle()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
}
public SimpleBinaryOpTest__OrSingle()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); }
_dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse.Or(
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse.Or(
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse.Or(
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse).GetMethod(nameof(Sse.Or), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse).GetMethod(nameof(Sse.Or), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse).GetMethod(nameof(Sse.Or), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) })
.Invoke(null, new object[] {
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)),
Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse.Or(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Single>* pClsVar1 = &_clsVar1)
fixed (Vector128<Single>* pClsVar2 = &_clsVar2)
{
var result = Sse.Or(
Sse.LoadVector128((Single*)(pClsVar1)),
Sse.LoadVector128((Single*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr);
var result = Sse.Or(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr));
var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.Or(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr));
var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr));
var result = Sse.Or(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__OrSingle();
var result = Sse.Or(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__OrSingle();
fixed (Vector128<Single>* pFld1 = &test._fld1)
fixed (Vector128<Single>* pFld2 = &test._fld2)
{
var result = Sse.Or(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse.Or(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Single>* pFld1 = &_fld1)
fixed (Vector128<Single>* pFld2 = &_fld2)
{
var result = Sse.Or(
Sse.LoadVector128((Single*)(pFld1)),
Sse.LoadVector128((Single*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse.Or(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse.Or(
Sse.LoadVector128((Single*)(&test._fld1)),
Sse.LoadVector128((Single*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Single[] inArray1 = new Single[Op1ElementCount];
Single[] inArray2 = new Single[Op2ElementCount];
Single[] outArray = new Single[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((BitConverter.SingleToInt32Bits(left[0]) | BitConverter.SingleToInt32Bits(right[0])) != BitConverter.SingleToInt32Bits(result[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((BitConverter.SingleToInt32Bits(left[0]) | BitConverter.SingleToInt32Bits(right[0])) != BitConverter.SingleToInt32Bits(result[0]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse)}.{nameof(Sse.Or)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
//
// System.Web.HttpCookie
//
// Author:
// Patrik Torstensson (Patrik.Torstensson@labs2.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Globalization;
using System.Text;
using System.Web;
using System.Collections.Specialized;
namespace System.Web
{
public sealed class HttpCookie
{
string _Name;
string _Value;
string _Domain;
DateTime _Expires;
bool _ExpiresSet;
string _Path;
bool _Secure = false;
HttpValueCollection _Values;
internal HttpCookie ()
{
_Path = "/";
}
public HttpCookie (string name)
{
_Path = "/";
_Name = name;
}
public HttpCookie (string name, string value)
{
_Name = name;
_Value = value;
_Path = "/";
}
internal HttpCookie (string name, string value, string path, DateTime expires)
{
_Name = name;
_Value = value;
_Path = path;
if (expires != DateTime.MinValue)
Expires = expires;
}
internal HttpResponseHeader GetCookieHeader ()
{
StringBuilder oSetCookie = new StringBuilder ();
if (null != _Name && _Name.Length > 0) {
oSetCookie.Append (_Name);
oSetCookie.Append ("=");
}
if (null != _Values) {
oSetCookie.Append (_Values.ToString (false));
} else if (null != _Value) {
oSetCookie.Append (_Value);
}
if (null != _Domain && _Domain.Length > 0) {
oSetCookie.Append ("; domain=");
oSetCookie.Append (_Domain);
}
if (null != _Path && Path.Length > 0) {
oSetCookie.Append ("; path=");
oSetCookie.Append (_Path);
}
if (_ExpiresSet && _Expires != DateTime.MinValue) {
oSetCookie.Append ("; expires=");
DateTime ut = _Expires.ToUniversalTime ();
oSetCookie.Append (ut.ToString ("ddd, dd-MMM-yyyy HH':'mm':'ss 'GMT'",
DateTimeFormatInfo.InvariantInfo));
}
if (_Secure)
oSetCookie.Append ("; secure");
return new HttpResponseHeader (HttpWorkerRequest.HeaderSetCookie, oSetCookie.ToString());
}
public string Domain
{
get { return _Domain; }
set { _Domain = value; }
}
public DateTime Expires
{
get {
if (!_ExpiresSet)
return DateTime.MinValue;
return _Expires;
}
set {
_ExpiresSet = true;
_Expires = value;
}
}
public bool HasKeys
{
get {
return Values.HasKeys ();
}
}
public string this [string key]
{
get { return Values [key]; }
set { Values [key] = value; }
}
public string Name
{
get { return _Name; }
set { _Name = value; }
}
public string Path
{
get { return _Path; }
set { _Path = value; }
}
public bool Secure
{
get { return _Secure; }
set { _Secure = value; }
}
public string Value
{
get {
if (null != _Values)
return _Values.ToString (false);
return _Value;
}
set {
if (null != _Values) {
_Values.Reset ();
_Values.Add (null, value);
return;
}
_Value = value;
}
}
public NameValueCollection Values
{
get {
if (null == _Values) {
_Values = new HttpValueCollection ();
if (null != _Value) {
// Do we have multiple keys
if (_Value.IndexOf ("&") >= 0 || _Value.IndexOf ("=") >= 0) {
_Values.FillFromCookieString (_Value);
} else {
_Values.Add (null, _Value);
}
_Value = null;
}
}
return _Values;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Android.Runtime;
namespace Com.Tencent.Mapsdk.Raster.Model {
// Metadata.xml XPath class reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='LatLngBounds']"
[global::Android.Runtime.Register ("com/tencent/mapsdk/raster/model/LatLngBounds", DoNotGenerateAcw=true)]
public partial class LatLngBounds : global::Java.Lang.Object {
// Metadata.xml XPath class reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='LatLngBounds.Builder']"
[global::Android.Runtime.Register ("com/tencent/mapsdk/raster/model/LatLngBounds$Builder", DoNotGenerateAcw=true)]
public sealed partial class Builder : global::Java.Lang.Object {
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("com/tencent/mapsdk/raster/model/LatLngBounds$Builder", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (Builder); }
}
internal Builder (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor;
// Metadata.xml XPath constructor reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='LatLngBounds.Builder']/constructor[@name='LatLngBounds.Builder' and count(parameter)=0]"
[Register (".ctor", "()V", "")]
public Builder () : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
if (GetType () != typeof (Builder)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "()V"),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "()V");
return;
}
if (id_ctor == IntPtr.Zero)
id_ctor = JNIEnv.GetMethodID (class_ref, "<init>", "()V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor);
}
static IntPtr id_build;
// Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='LatLngBounds.Builder']/method[@name='build' and count(parameter)=0]"
[Register ("build", "()Lcom/tencent/mapsdk/raster/model/LatLngBounds;", "")]
public global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds Build ()
{
if (id_build == IntPtr.Zero)
id_build = JNIEnv.GetMethodID (class_ref, "build", "()Lcom/tencent/mapsdk/raster/model/LatLngBounds;");
return global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds> (JNIEnv.CallObjectMethod (Handle, id_build), JniHandleOwnership.TransferLocalRef);
}
static IntPtr id_include_Lcom_tencent_mapsdk_raster_model_LatLng_;
// Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='LatLngBounds.Builder']/method[@name='include' and count(parameter)=1 and parameter[1][@type='com.tencent.mapsdk.raster.model.LatLng']]"
[Register ("include", "(Lcom/tencent/mapsdk/raster/model/LatLng;)Lcom/tencent/mapsdk/raster/model/LatLngBounds$Builder;", "")]
public global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds.Builder Include (global::Com.Tencent.Mapsdk.Raster.Model.LatLng p0)
{
if (id_include_Lcom_tencent_mapsdk_raster_model_LatLng_ == IntPtr.Zero)
id_include_Lcom_tencent_mapsdk_raster_model_LatLng_ = JNIEnv.GetMethodID (class_ref, "include", "(Lcom/tencent/mapsdk/raster/model/LatLng;)Lcom/tencent/mapsdk/raster/model/LatLngBounds$Builder;");
global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds.Builder __ret = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds.Builder> (JNIEnv.CallObjectMethod (Handle, id_include_Lcom_tencent_mapsdk_raster_model_LatLng_, new JValue (p0)), JniHandleOwnership.TransferLocalRef);
return __ret;
}
}
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("com/tencent/mapsdk/raster/model/LatLngBounds", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (LatLngBounds); }
}
protected LatLngBounds (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor_Lcom_tencent_mapsdk_raster_model_LatLng_Lcom_tencent_mapsdk_raster_model_LatLng_;
// Metadata.xml XPath constructor reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='LatLngBounds']/constructor[@name='LatLngBounds' and count(parameter)=2 and parameter[1][@type='com.tencent.mapsdk.raster.model.LatLng'] and parameter[2][@type='com.tencent.mapsdk.raster.model.LatLng']]"
[Register (".ctor", "(Lcom/tencent/mapsdk/raster/model/LatLng;Lcom/tencent/mapsdk/raster/model/LatLng;)V", "")]
public LatLngBounds (global::Com.Tencent.Mapsdk.Raster.Model.LatLng p0, global::Com.Tencent.Mapsdk.Raster.Model.LatLng p1) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
if (GetType () != typeof (LatLngBounds)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Lcom/tencent/mapsdk/raster/model/LatLng;Lcom/tencent/mapsdk/raster/model/LatLng;)V", new JValue (p0), new JValue (p1)),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Lcom/tencent/mapsdk/raster/model/LatLng;Lcom/tencent/mapsdk/raster/model/LatLng;)V", new JValue (p0), new JValue (p1));
return;
}
if (id_ctor_Lcom_tencent_mapsdk_raster_model_LatLng_Lcom_tencent_mapsdk_raster_model_LatLng_ == IntPtr.Zero)
id_ctor_Lcom_tencent_mapsdk_raster_model_LatLng_Lcom_tencent_mapsdk_raster_model_LatLng_ = JNIEnv.GetMethodID (class_ref, "<init>", "(Lcom/tencent/mapsdk/raster/model/LatLng;Lcom/tencent/mapsdk/raster/model/LatLng;)V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Lcom_tencent_mapsdk_raster_model_LatLng_Lcom_tencent_mapsdk_raster_model_LatLng_, new JValue (p0), new JValue (p1)),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Lcom_tencent_mapsdk_raster_model_LatLng_Lcom_tencent_mapsdk_raster_model_LatLng_, new JValue (p0), new JValue (p1));
}
static Delegate cb_getNortheast;
#pragma warning disable 0169
static Delegate GetGetNortheastHandler ()
{
if (cb_getNortheast == null)
cb_getNortheast = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetNortheast);
return cb_getNortheast;
}
static IntPtr n_GetNortheast (IntPtr jnienv, IntPtr native__this)
{
global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.ToLocalJniHandle (__this.Northeast);
}
#pragma warning restore 0169
static IntPtr id_getNortheast;
public virtual global::Com.Tencent.Mapsdk.Raster.Model.LatLng Northeast {
// Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='LatLngBounds']/method[@name='getNortheast' and count(parameter)=0]"
[Register ("getNortheast", "()Lcom/tencent/mapsdk/raster/model/LatLng;", "GetGetNortheastHandler")]
get {
if (id_getNortheast == IntPtr.Zero)
id_getNortheast = JNIEnv.GetMethodID (class_ref, "getNortheast", "()Lcom/tencent/mapsdk/raster/model/LatLng;");
if (GetType () == ThresholdType)
return global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.LatLng> (JNIEnv.CallObjectMethod (Handle, id_getNortheast), JniHandleOwnership.TransferLocalRef);
else
return global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.LatLng> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getNortheast", "()Lcom/tencent/mapsdk/raster/model/LatLng;")), JniHandleOwnership.TransferLocalRef);
}
}
static Delegate cb_getSouthwest;
#pragma warning disable 0169
static Delegate GetGetSouthwestHandler ()
{
if (cb_getSouthwest == null)
cb_getSouthwest = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr>) n_GetSouthwest);
return cb_getSouthwest;
}
static IntPtr n_GetSouthwest (IntPtr jnienv, IntPtr native__this)
{
global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
return JNIEnv.ToLocalJniHandle (__this.Southwest);
}
#pragma warning restore 0169
static IntPtr id_getSouthwest;
public virtual global::Com.Tencent.Mapsdk.Raster.Model.LatLng Southwest {
// Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='LatLngBounds']/method[@name='getSouthwest' and count(parameter)=0]"
[Register ("getSouthwest", "()Lcom/tencent/mapsdk/raster/model/LatLng;", "GetGetSouthwestHandler")]
get {
if (id_getSouthwest == IntPtr.Zero)
id_getSouthwest = JNIEnv.GetMethodID (class_ref, "getSouthwest", "()Lcom/tencent/mapsdk/raster/model/LatLng;");
if (GetType () == ThresholdType)
return global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.LatLng> (JNIEnv.CallObjectMethod (Handle, id_getSouthwest), JniHandleOwnership.TransferLocalRef);
else
return global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.LatLng> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "getSouthwest", "()Lcom/tencent/mapsdk/raster/model/LatLng;")), JniHandleOwnership.TransferLocalRef);
}
}
static IntPtr id_builder;
// Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='LatLngBounds']/method[@name='builder' and count(parameter)=0]"
[Register ("builder", "()Lcom/tencent/mapsdk/raster/model/LatLngBounds$Builder;", "")]
public static global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds.Builder InvokeBuilder ()
{
if (id_builder == IntPtr.Zero)
id_builder = JNIEnv.GetStaticMethodID (class_ref, "builder", "()Lcom/tencent/mapsdk/raster/model/LatLngBounds$Builder;");
return global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds.Builder> (JNIEnv.CallStaticObjectMethod (class_ref, id_builder), JniHandleOwnership.TransferLocalRef);
}
static Delegate cb_contains_Lcom_tencent_mapsdk_raster_model_LatLng_;
#pragma warning disable 0169
static Delegate GetContains_Lcom_tencent_mapsdk_raster_model_LatLng_Handler ()
{
if (cb_contains_Lcom_tencent_mapsdk_raster_model_LatLng_ == null)
cb_contains_Lcom_tencent_mapsdk_raster_model_LatLng_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, bool>) n_Contains_Lcom_tencent_mapsdk_raster_model_LatLng_);
return cb_contains_Lcom_tencent_mapsdk_raster_model_LatLng_;
}
static bool n_Contains_Lcom_tencent_mapsdk_raster_model_LatLng_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Com.Tencent.Mapsdk.Raster.Model.LatLng p0 = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.LatLng> (native_p0, JniHandleOwnership.DoNotTransfer);
bool __ret = __this.Contains (p0);
return __ret;
}
#pragma warning restore 0169
static IntPtr id_contains_Lcom_tencent_mapsdk_raster_model_LatLng_;
// Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='LatLngBounds']/method[@name='contains' and count(parameter)=1 and parameter[1][@type='com.tencent.mapsdk.raster.model.LatLng']]"
[Register ("contains", "(Lcom/tencent/mapsdk/raster/model/LatLng;)Z", "GetContains_Lcom_tencent_mapsdk_raster_model_LatLng_Handler")]
public virtual bool Contains (global::Com.Tencent.Mapsdk.Raster.Model.LatLng p0)
{
if (id_contains_Lcom_tencent_mapsdk_raster_model_LatLng_ == IntPtr.Zero)
id_contains_Lcom_tencent_mapsdk_raster_model_LatLng_ = JNIEnv.GetMethodID (class_ref, "contains", "(Lcom/tencent/mapsdk/raster/model/LatLng;)Z");
bool __ret;
if (GetType () == ThresholdType)
__ret = JNIEnv.CallBooleanMethod (Handle, id_contains_Lcom_tencent_mapsdk_raster_model_LatLng_, new JValue (p0));
else
__ret = JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "contains", "(Lcom/tencent/mapsdk/raster/model/LatLng;)Z"), new JValue (p0));
return __ret;
}
static Delegate cb_contains_Lcom_tencent_mapsdk_raster_model_LatLngBounds_;
#pragma warning disable 0169
static Delegate GetContains_Lcom_tencent_mapsdk_raster_model_LatLngBounds_Handler ()
{
if (cb_contains_Lcom_tencent_mapsdk_raster_model_LatLngBounds_ == null)
cb_contains_Lcom_tencent_mapsdk_raster_model_LatLngBounds_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, bool>) n_Contains_Lcom_tencent_mapsdk_raster_model_LatLngBounds_);
return cb_contains_Lcom_tencent_mapsdk_raster_model_LatLngBounds_;
}
static bool n_Contains_Lcom_tencent_mapsdk_raster_model_LatLngBounds_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds p0 = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds> (native_p0, JniHandleOwnership.DoNotTransfer);
bool __ret = __this.Contains (p0);
return __ret;
}
#pragma warning restore 0169
static IntPtr id_contains_Lcom_tencent_mapsdk_raster_model_LatLngBounds_;
// Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='LatLngBounds']/method[@name='contains' and count(parameter)=1 and parameter[1][@type='com.tencent.mapsdk.raster.model.LatLngBounds']]"
[Register ("contains", "(Lcom/tencent/mapsdk/raster/model/LatLngBounds;)Z", "GetContains_Lcom_tencent_mapsdk_raster_model_LatLngBounds_Handler")]
public virtual bool Contains (global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds p0)
{
if (id_contains_Lcom_tencent_mapsdk_raster_model_LatLngBounds_ == IntPtr.Zero)
id_contains_Lcom_tencent_mapsdk_raster_model_LatLngBounds_ = JNIEnv.GetMethodID (class_ref, "contains", "(Lcom/tencent/mapsdk/raster/model/LatLngBounds;)Z");
bool __ret;
if (GetType () == ThresholdType)
__ret = JNIEnv.CallBooleanMethod (Handle, id_contains_Lcom_tencent_mapsdk_raster_model_LatLngBounds_, new JValue (p0));
else
__ret = JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "contains", "(Lcom/tencent/mapsdk/raster/model/LatLngBounds;)Z"), new JValue (p0));
return __ret;
}
static IntPtr id_equals_Ljava_lang_Object_;
// Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='LatLngBounds']/method[@name='equals' and count(parameter)=1 and parameter[1][@type='java.lang.Object']]"
[Register ("equals", "(Ljava/lang/Object;)Z", "")]
public override sealed bool Equals (global::Java.Lang.Object p0)
{
if (id_equals_Ljava_lang_Object_ == IntPtr.Zero)
id_equals_Ljava_lang_Object_ = JNIEnv.GetMethodID (class_ref, "equals", "(Ljava/lang/Object;)Z");
bool __ret = JNIEnv.CallBooleanMethod (Handle, id_equals_Ljava_lang_Object_, new JValue (p0));
return __ret;
}
static IntPtr id_hashCode;
// Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='LatLngBounds']/method[@name='hashCode' and count(parameter)=0]"
[Register ("hashCode", "()I", "")]
public override sealed int GetHashCode ()
{
if (id_hashCode == IntPtr.Zero)
id_hashCode = JNIEnv.GetMethodID (class_ref, "hashCode", "()I");
return JNIEnv.CallIntMethod (Handle, id_hashCode);
}
static Delegate cb_including_Lcom_tencent_mapsdk_raster_model_LatLng_;
#pragma warning disable 0169
static Delegate GetIncluding_Lcom_tencent_mapsdk_raster_model_LatLng_Handler ()
{
if (cb_including_Lcom_tencent_mapsdk_raster_model_LatLng_ == null)
cb_including_Lcom_tencent_mapsdk_raster_model_LatLng_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, IntPtr>) n_Including_Lcom_tencent_mapsdk_raster_model_LatLng_);
return cb_including_Lcom_tencent_mapsdk_raster_model_LatLng_;
}
static IntPtr n_Including_Lcom_tencent_mapsdk_raster_model_LatLng_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Com.Tencent.Mapsdk.Raster.Model.LatLng p0 = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.LatLng> (native_p0, JniHandleOwnership.DoNotTransfer);
IntPtr __ret = JNIEnv.ToLocalJniHandle (__this.Including (p0));
return __ret;
}
#pragma warning restore 0169
static IntPtr id_including_Lcom_tencent_mapsdk_raster_model_LatLng_;
// Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='LatLngBounds']/method[@name='including' and count(parameter)=1 and parameter[1][@type='com.tencent.mapsdk.raster.model.LatLng']]"
[Register ("including", "(Lcom/tencent/mapsdk/raster/model/LatLng;)Lcom/tencent/mapsdk/raster/model/LatLngBounds;", "GetIncluding_Lcom_tencent_mapsdk_raster_model_LatLng_Handler")]
public virtual global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds Including (global::Com.Tencent.Mapsdk.Raster.Model.LatLng p0)
{
if (id_including_Lcom_tencent_mapsdk_raster_model_LatLng_ == IntPtr.Zero)
id_including_Lcom_tencent_mapsdk_raster_model_LatLng_ = JNIEnv.GetMethodID (class_ref, "including", "(Lcom/tencent/mapsdk/raster/model/LatLng;)Lcom/tencent/mapsdk/raster/model/LatLngBounds;");
global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds __ret;
if (GetType () == ThresholdType)
__ret = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds> (JNIEnv.CallObjectMethod (Handle, id_including_Lcom_tencent_mapsdk_raster_model_LatLng_, new JValue (p0)), JniHandleOwnership.TransferLocalRef);
else
__ret = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds> (JNIEnv.CallNonvirtualObjectMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "including", "(Lcom/tencent/mapsdk/raster/model/LatLng;)Lcom/tencent/mapsdk/raster/model/LatLngBounds;"), new JValue (p0)), JniHandleOwnership.TransferLocalRef);
return __ret;
}
static Delegate cb_intersects_Lcom_tencent_mapsdk_raster_model_LatLngBounds_;
#pragma warning disable 0169
static Delegate GetIntersects_Lcom_tencent_mapsdk_raster_model_LatLngBounds_Handler ()
{
if (cb_intersects_Lcom_tencent_mapsdk_raster_model_LatLngBounds_ == null)
cb_intersects_Lcom_tencent_mapsdk_raster_model_LatLngBounds_ = JNINativeWrapper.CreateDelegate ((Func<IntPtr, IntPtr, IntPtr, bool>) n_Intersects_Lcom_tencent_mapsdk_raster_model_LatLngBounds_);
return cb_intersects_Lcom_tencent_mapsdk_raster_model_LatLngBounds_;
}
static bool n_Intersects_Lcom_tencent_mapsdk_raster_model_LatLngBounds_ (IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds __this = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds> (jnienv, native__this, JniHandleOwnership.DoNotTransfer);
global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds p0 = global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds> (native_p0, JniHandleOwnership.DoNotTransfer);
bool __ret = __this.Intersects (p0);
return __ret;
}
#pragma warning restore 0169
static IntPtr id_intersects_Lcom_tencent_mapsdk_raster_model_LatLngBounds_;
// Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='LatLngBounds']/method[@name='intersects' and count(parameter)=1 and parameter[1][@type='com.tencent.mapsdk.raster.model.LatLngBounds']]"
[Register ("intersects", "(Lcom/tencent/mapsdk/raster/model/LatLngBounds;)Z", "GetIntersects_Lcom_tencent_mapsdk_raster_model_LatLngBounds_Handler")]
public virtual bool Intersects (global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds p0)
{
if (id_intersects_Lcom_tencent_mapsdk_raster_model_LatLngBounds_ == IntPtr.Zero)
id_intersects_Lcom_tencent_mapsdk_raster_model_LatLngBounds_ = JNIEnv.GetMethodID (class_ref, "intersects", "(Lcom/tencent/mapsdk/raster/model/LatLngBounds;)Z");
bool __ret;
if (GetType () == ThresholdType)
__ret = JNIEnv.CallBooleanMethod (Handle, id_intersects_Lcom_tencent_mapsdk_raster_model_LatLngBounds_, new JValue (p0));
else
__ret = JNIEnv.CallNonvirtualBooleanMethod (Handle, ThresholdClass, JNIEnv.GetMethodID (ThresholdClass, "intersects", "(Lcom/tencent/mapsdk/raster/model/LatLngBounds;)Z"), new JValue (p0));
return __ret;
}
static IntPtr id_toString;
// Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='LatLngBounds']/method[@name='toString' and count(parameter)=0]"
[Register ("toString", "()Ljava/lang/String;", "")]
public override sealed string ToString ()
{
if (id_toString == IntPtr.Zero)
id_toString = JNIEnv.GetMethodID (class_ref, "toString", "()Ljava/lang/String;");
return JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_toString), JniHandleOwnership.TransferLocalRef);
}
}
}
| |
// 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.Text;
using Xunit;
namespace System.Net.Primitives.PalTests
{
public class IPAddressPalTests
{
[Fact]
public void IPv4StringToAddress_Valid()
{
const string AddressString = "127.0.64.255";
var bytes = new byte[IPAddressParserStatics.IPv4AddressBytes];
ushort port;
uint err = IPAddressPal.Ipv4StringToAddress(AddressString, bytes, out port);
Assert.Equal(IPAddressPal.SuccessErrorCode, err);
Assert.Equal(127, bytes[0]);
Assert.Equal(0, bytes[1]);
Assert.Equal(64, bytes[2]);
Assert.Equal(255, bytes[3]);
Assert.Equal(0, port);
}
[Fact]
public void IPv4StringToAddress_Valid_ClassB()
{
const string AddressString = "128.64.256";
var bytes = new byte[IPAddressParserStatics.IPv4AddressBytes];
ushort port;
uint err = IPAddressPal.Ipv4StringToAddress(AddressString, bytes, out port);
Assert.Equal(IPAddressPal.SuccessErrorCode, err);
Assert.Equal(128, bytes[0]);
Assert.Equal(64, bytes[1]);
Assert.Equal(1, bytes[2]);
Assert.Equal(0, bytes[3]);
Assert.Equal(0, port);
}
[Fact]
public void IPv4StringToAddress_Valid_ClassC()
{
const string AddressString = "192.65536";
var bytes = new byte[IPAddressParserStatics.IPv4AddressBytes];
ushort port;
uint err = IPAddressPal.Ipv4StringToAddress(AddressString, bytes, out port);
Assert.Equal(IPAddressPal.SuccessErrorCode, err);
Assert.Equal(192, bytes[0]);
Assert.Equal(1, bytes[1]);
Assert.Equal(0, bytes[2]);
Assert.Equal(0, bytes[3]);
Assert.Equal(0, port);
}
[Fact]
public void IPv4StringToAddress_Valid_ClassA()
{
const string AddressString = "2130706433";
var bytes = new byte[IPAddressParserStatics.IPv4AddressBytes];
ushort port;
uint err = IPAddressPal.Ipv4StringToAddress(AddressString, bytes, out port);
Assert.Equal(IPAddressPal.SuccessErrorCode, err);
Assert.Equal(127, bytes[0]);
Assert.Equal(0, bytes[1]);
Assert.Equal(0, bytes[2]);
Assert.Equal(1, bytes[3]);
Assert.Equal(0, port);
}
[Fact]
public void IPv4StringToAddress_Invalid_Empty()
{
const string AddressString = "";
var bytes = new byte[IPAddressParserStatics.IPv4AddressBytes];
ushort port;
uint err = IPAddressPal.Ipv4StringToAddress(AddressString, bytes, out port);
Assert.NotEqual(err, IPAddressPal.SuccessErrorCode);
}
[Fact]
public void IPv4StringToAddress_Invalid_NotAnAddress()
{
const string AddressString = "hello, world";
var bytes = new byte[IPAddressParserStatics.IPv4AddressBytes];
ushort port;
uint err = IPAddressPal.Ipv4StringToAddress(AddressString, bytes, out port);
Assert.NotEqual(err, IPAddressPal.SuccessErrorCode);
}
[Fact]
public void IPv4StringToAddress_Invalid_Port()
{
const string AddressString = "127.0.64.255:80";
var bytes = new byte[IPAddressParserStatics.IPv4AddressBytes];
ushort port;
uint err = IPAddressPal.Ipv4StringToAddress(AddressString, bytes, out port);
Assert.True(err != IPAddressPal.SuccessErrorCode || port != 0);
}
public static object[][] ValidIPv4Addresses = new object[][] {
new object[] { new byte[] { 0, 0, 0, 0 }, "0.0.0.0" },
new object[] { new byte[] { 127, 0, 64, 255 }, "127.0.64.255" },
new object[] { new byte[] { 128, 64, 1, 0 }, "128.64.1.0" },
new object[] { new byte[] { 192, 0, 0, 1 }, "192.0.0.1" },
new object[] { new byte[] { 255, 255, 255, 255 }, "255.255.255.255" }
};
[Theory, MemberData("ValidIPv4Addresses")]
public void IPv4AddressToString_Valid(byte[] bytes, string addressString)
{
var buffer = new StringBuilder(IPAddressParser.INET_ADDRSTRLEN);
uint err = IPAddressPal.Ipv4AddressToString(bytes, buffer);
Assert.Equal(IPAddressPal.SuccessErrorCode, err);
Assert.Equal(addressString, buffer.ToString());
}
[Theory, MemberData("ValidIPv4Addresses")]
public void IPv4AddressToString_RoundTrip(byte[] bytes, string addressString)
{
var buffer = new StringBuilder(IPAddressParser.INET_ADDRSTRLEN);
uint err = IPAddressPal.Ipv4AddressToString(bytes, buffer);
Assert.Equal(IPAddressPal.SuccessErrorCode, err);
var actualAddressString = buffer.ToString();
Assert.Equal(addressString, actualAddressString);
var roundTrippedBytes = new byte[IPAddressParserStatics.IPv4AddressBytes];
ushort port;
err = IPAddressPal.Ipv4StringToAddress(actualAddressString, roundTrippedBytes, out port);
Assert.Equal(IPAddressPal.SuccessErrorCode, err);
Assert.Equal(bytes[0], roundTrippedBytes[0]);
Assert.Equal(bytes[1], roundTrippedBytes[1]);
Assert.Equal(bytes[2], roundTrippedBytes[2]);
Assert.Equal(bytes[3], roundTrippedBytes[3]);
Assert.Equal(0, port);
}
[Theory, MemberData("ValidIPv4Addresses")]
public void IPv4StringToAddress_RoundTrip(byte[] bytes, string addressString)
{
var actualBytes = new byte[IPAddressParserStatics.IPv4AddressBytes];
ushort port;
uint err = IPAddressPal.Ipv4StringToAddress(addressString, actualBytes, out port);
Assert.Equal(IPAddressPal.SuccessErrorCode, err);
Assert.Equal(bytes[0], actualBytes[0]);
Assert.Equal(bytes[1], actualBytes[1]);
Assert.Equal(bytes[2], actualBytes[2]);
Assert.Equal(bytes[3], actualBytes[3]);
Assert.Equal(0, port);
var buffer = new StringBuilder(IPAddressParser.INET_ADDRSTRLEN);
err = IPAddressPal.Ipv4AddressToString(actualBytes, buffer);
Assert.Equal(IPAddressPal.SuccessErrorCode, err);
var roundTrippedAddressString = buffer.ToString();
Assert.Equal(addressString, roundTrippedAddressString);
}
[Fact]
public void IPv6StringToAddress_Valid_Localhost()
{
const string AddressString = "::1";
var expectedBytes = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
var bytes = new byte[IPAddressParserStatics.IPv6AddressBytes];
Assert.Equal(bytes.Length, expectedBytes.Length);
uint scope;
uint err = IPAddressPal.Ipv6StringToAddress(AddressString, bytes, out scope);
Assert.Equal(IPAddressPal.SuccessErrorCode, err);
for (int i = 0; i < expectedBytes.Length; i++)
{
Assert.Equal(expectedBytes[i], bytes[i]);
}
Assert.Equal(0, (int)scope);
}
[Fact]
public void IPv6StringToAddress_Valid()
{
const string AddressString = "2001:db8:aaaa:bbbb:cccc:dddd:eeee:1";
var expectedBytes = new byte[] { 0x20, 0x01, 0x0d, 0x0b8, 0xaa, 0xaa, 0xbb, 0xbb, 0xcc, 0xcc, 0xdd, 0xdd, 0xee, 0xee, 0x00, 0x01 };
var bytes = new byte[IPAddressParserStatics.IPv6AddressBytes];
Assert.Equal(bytes.Length, expectedBytes.Length);
uint scope;
uint err = IPAddressPal.Ipv6StringToAddress(AddressString, bytes, out scope);
Assert.Equal(IPAddressPal.SuccessErrorCode, err);
for (int i = 0; i < expectedBytes.Length; i++)
{
Assert.Equal(expectedBytes[i], bytes[i]);
}
Assert.Equal(0, (int)scope);
}
[Fact]
public void IPv6StringToAddress_Valid_Bracketed()
{
const string AddressString = "[2001:db8:aaaa:bbbb:cccc:dddd:eeee:1]";
var expectedBytes = new byte[] { 0x20, 0x01, 0x0d, 0x0b8, 0xaa, 0xaa, 0xbb, 0xbb, 0xcc, 0xcc, 0xdd, 0xdd, 0xee, 0xee, 0x00, 0x01 };
var bytes = new byte[IPAddressParserStatics.IPv6AddressBytes];
Assert.Equal(bytes.Length, expectedBytes.Length);
uint scope;
uint err = IPAddressPal.Ipv6StringToAddress(AddressString, bytes, out scope);
Assert.Equal(IPAddressPal.SuccessErrorCode, err);
for (int i = 0; i < expectedBytes.Length; i++)
{
Assert.Equal(expectedBytes[i], bytes[i]);
}
Assert.Equal(0, (int)scope);
}
[Fact]
public void IPv6StringToAddress_Valid_Port()
{
const string AddressString = "[2001:db8:aaaa:bbbb:cccc:dddd:eeee:1]:80";
var expectedBytes = new byte[] { 0x20, 0x01, 0x0d, 0x0b8, 0xaa, 0xaa, 0xbb, 0xbb, 0xcc, 0xcc, 0xdd, 0xdd, 0xee, 0xee, 0x00, 0x01 };
var bytes = new byte[IPAddressParserStatics.IPv6AddressBytes];
Assert.Equal(bytes.Length, expectedBytes.Length);
uint scope;
uint err = IPAddressPal.Ipv6StringToAddress(AddressString, bytes, out scope);
Assert.Equal(IPAddressPal.SuccessErrorCode, err);
for (int i = 0; i < expectedBytes.Length; i++)
{
Assert.Equal(expectedBytes[i], bytes[i]);
}
Assert.Equal(0, (int)scope);
}
[Fact]
public void IPv6StringToAddress_Valid_Port_2()
{
const string AddressString = "[2001:db8:aaaa:bbbb:cccc:dddd:eeee:1]:";
var expectedBytes = new byte[] { 0x20, 0x01, 0x0d, 0x0b8, 0xaa, 0xaa, 0xbb, 0xbb, 0xcc, 0xcc, 0xdd, 0xdd, 0xee, 0xee, 0x00, 0x01 };
var bytes = new byte[IPAddressParserStatics.IPv6AddressBytes];
Assert.Equal(bytes.Length, expectedBytes.Length);
uint scope;
uint err = IPAddressPal.Ipv6StringToAddress(AddressString, bytes, out scope);
Assert.Equal(IPAddressPal.SuccessErrorCode, err);
for (int i = 0; i < expectedBytes.Length; i++)
{
Assert.Equal(expectedBytes[i], bytes[i]);
}
Assert.Equal(0, (int)scope);
}
[Fact]
public void IPv6StringToAddress_Valid_Compressed()
{
const string AddressString = "2001:db8::1";
var expectedBytes = new byte[] { 0x20, 0x01, 0x0d, 0x0b8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 };
var bytes = new byte[IPAddressParserStatics.IPv6AddressBytes];
Assert.Equal(bytes.Length, expectedBytes.Length);
uint scope;
uint err = IPAddressPal.Ipv6StringToAddress(AddressString, bytes, out scope);
Assert.Equal(IPAddressPal.SuccessErrorCode, err);
for (int i = 0; i < expectedBytes.Length; i++)
{
Assert.Equal(expectedBytes[i], bytes[i]);
}
Assert.Equal(0, (int)scope);
}
[Fact]
public void IPv6StringToAddress_Valid_IPv4Compatible()
{
const string AddressString = "::ffff:222.1.41.90";
var expectedBytes = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 222, 1, 41, 90 };
var bytes = new byte[IPAddressParserStatics.IPv6AddressBytes];
Assert.Equal(bytes.Length, expectedBytes.Length);
uint scope;
uint err = IPAddressPal.Ipv6StringToAddress(AddressString, bytes, out scope);
Assert.Equal(IPAddressPal.SuccessErrorCode, err);
for (int i = 0; i < expectedBytes.Length; i++)
{
Assert.Equal(expectedBytes[i], bytes[i]);
}
Assert.Equal(0, (int)scope);
}
[Fact]
public void IPv6StringToAddress_Invalid_Empty()
{
const string AddressString = "";
var bytes = new byte[IPAddressParserStatics.IPv6AddressBytes];
uint scope;
uint err = IPAddressPal.Ipv6StringToAddress(AddressString, bytes, out scope);
Assert.NotEqual(err, IPAddressPal.SuccessErrorCode);
}
[Fact]
public void IPv6StringToAddress_Invalid_NotAnAddress()
{
const string AddressString = "hello, world";
var bytes = new byte[IPAddressParserStatics.IPv6AddressBytes];
uint scope;
uint err = IPAddressPal.Ipv6StringToAddress(AddressString, bytes, out scope);
Assert.NotEqual(err, IPAddressPal.SuccessErrorCode);
}
[Fact]
public void IPv6StringToAddress_Invalid_Port()
{
const string AddressString = "[2001:db8::1]:xx";
var bytes = new byte[IPAddressParserStatics.IPv6AddressBytes];
uint scope;
uint err = IPAddressPal.Ipv6StringToAddress(AddressString, bytes, out scope);
Assert.NotEqual(err, IPAddressPal.SuccessErrorCode);
}
[Fact]
public void IPv6StringToAddress_Invalid_Compression()
{
const string AddressString = "2001::db8::1";
var bytes = new byte[IPAddressParserStatics.IPv6AddressBytes];
uint scope;
uint err = IPAddressPal.Ipv6StringToAddress(AddressString, bytes, out scope);
Assert.NotEqual(err, IPAddressPal.SuccessErrorCode);
}
public static object[][] ValidIPv6Addresses = new object[][] {
new object[] {
new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
"::1"
},
new object[] {
new byte[] { 0x20, 0x01, 0x0d, 0x0b8, 0xaa, 0xaa, 0xbb, 0xbb, 0xcc, 0xcc, 0xdd, 0xdd, 0xee, 0xee, 0x00, 0x01 },
"2001:db8:aaaa:bbbb:cccc:dddd:eeee:1"
},
new object[] {
new byte[] { 0x20, 0x01, 0x0d, 0x0b8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 },
"2001:db8::1"
},
new object[] {
new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 222, 1, 41, 90 },
"::ffff:222.1.41.90"
}
};
[Theory, MemberData("ValidIPv6Addresses")]
public void IPv6AddressToString_Valid(byte[] bytes, string addressString)
{
var buffer = new StringBuilder(IPAddressParser.INET6_ADDRSTRLEN);
uint err = IPAddressPal.Ipv6AddressToString(bytes, 0, buffer);
Assert.Equal(IPAddressPal.SuccessErrorCode, err);
Assert.Equal(addressString, buffer.ToString());
}
[Theory, MemberData("ValidIPv6Addresses")]
public void IPv6AddressToString_RoundTrip(byte[] bytes, string addressString)
{
var buffer = new StringBuilder(IPAddressParser.INET6_ADDRSTRLEN);
uint err = IPAddressPal.Ipv6AddressToString(bytes, 0, buffer);
Assert.Equal(IPAddressPal.SuccessErrorCode, err);
var actualAddressString = buffer.ToString();
Assert.Equal(addressString, actualAddressString);
var roundTrippedBytes = new byte[IPAddressParserStatics.IPv6AddressBytes];
uint scope;
err = IPAddressPal.Ipv6StringToAddress(actualAddressString, roundTrippedBytes, out scope);
Assert.Equal(IPAddressPal.SuccessErrorCode, err);
for (int i = 0; i < bytes.Length; i++)
{
Assert.Equal(bytes[i], roundTrippedBytes[i]);
}
Assert.Equal(0, (int)scope);
}
[Theory, MemberData("ValidIPv6Addresses")]
public void IPv6StringToAddress_RoundTrip(byte[] bytes, string addressString)
{
var actualBytes = new byte[IPAddressParserStatics.IPv6AddressBytes];
uint scope;
uint err = IPAddressPal.Ipv6StringToAddress(addressString, actualBytes, out scope);
Assert.Equal(IPAddressPal.SuccessErrorCode, err);
for (int i = 0; i < bytes.Length; i++)
{
Assert.Equal(bytes[i], actualBytes[i]);
}
Assert.Equal(0, (int)scope);
var buffer = new StringBuilder(IPAddressParser.INET6_ADDRSTRLEN);
err = IPAddressPal.Ipv6AddressToString(actualBytes, 0, buffer);
Assert.Equal(IPAddressPal.SuccessErrorCode, err);
var roundTrippedAddressString = buffer.ToString();
Assert.Equal(addressString, roundTrippedAddressString);
}
}
}
| |
/******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2015-2017 Baldur Karlsson
* Copyright (c) 2014 Crytek
*
* 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.Runtime.InteropServices;
using System.Collections.Generic;
namespace renderdoc
{
// this isn't an Interop struct, since it needs to be passed C# -> C++ and
// it's not POD which we don't support. It's here just as a utility container
public class EnvironmentModification
{
public string variable;
public string value;
public EnvironmentModificationType type;
public EnvironmentSeparator separator;
public string GetTypeString()
{
string ret;
if (type == EnvironmentModificationType.Append)
ret = String.Format("Append, {0}", separator.Str());
else if (type == EnvironmentModificationType.Prepend)
ret = String.Format("Prepend, {0}", separator.Str());
else
ret = "Set";
return ret;
}
public string GetDescription()
{
string ret;
if (type == EnvironmentModificationType.Append)
ret = String.Format("Append {0} with {1} using {2}", variable, value, separator.Str());
else if (type == EnvironmentModificationType.Prepend)
ret = String.Format("Prepend {0} with {1} using {2}", variable, value, separator.Str());
else
ret = String.Format("Set {0} to {1}", variable, value);
return ret;
}
}
[StructLayout(LayoutKind.Sequential)]
public class TargetControlMessage
{
public TargetControlMessageType Type;
[StructLayout(LayoutKind.Sequential)]
public struct NewCaptureData
{
public UInt32 ID;
public UInt64 timestamp;
[CustomMarshalAs(CustomUnmanagedType.TemplatedArray)]
public byte[] thumbnail;
[CustomMarshalAs(CustomUnmanagedType.UTF8TemplatedString)]
public string path;
public bool local;
};
[CustomMarshalAs(CustomUnmanagedType.CustomClass)]
public NewCaptureData NewCapture;
[StructLayout(LayoutKind.Sequential)]
public struct RegisterAPIData
{
[CustomMarshalAs(CustomUnmanagedType.UTF8TemplatedString)]
public string APIName;
};
[CustomMarshalAs(CustomUnmanagedType.CustomClass)]
public RegisterAPIData RegisterAPI;
[StructLayout(LayoutKind.Sequential)]
public struct BusyData
{
[CustomMarshalAs(CustomUnmanagedType.UTF8TemplatedString)]
public string ClientName;
};
[CustomMarshalAs(CustomUnmanagedType.CustomClass)]
public BusyData Busy;
[StructLayout(LayoutKind.Sequential)]
public struct NewChildData
{
public UInt32 PID;
public UInt32 ident;
};
[CustomMarshalAs(CustomUnmanagedType.CustomClass)]
public NewChildData NewChild;
};
public class ReplayOutput
{
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayOutput_SetOutputConfig(IntPtr real, OutputConfig o);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayOutput_SetTextureDisplay(IntPtr real, TextureDisplay o);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayOutput_SetMeshDisplay(IntPtr real, MeshDisplay o);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayOutput_ClearThumbnails(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayOutput_AddThumbnail(IntPtr real, UInt32 windowSystem, IntPtr wnd, ResourceId texID, FormatComponentType typeHint);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayOutput_Display(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayOutput_SetPixelContext(IntPtr real, UInt32 windowSystem, IntPtr wnd);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayOutput_SetPixelContextLocation(IntPtr real, UInt32 x, UInt32 y);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayOutput_DisablePixelContext(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayOutput_GetCustomShaderTexID(IntPtr real, ref ResourceId texid);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayOutput_GetMinMax(IntPtr real, IntPtr outminval, IntPtr outmaxval);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayOutput_GetHistogram(IntPtr real, float minval, float maxval, bool[] channels, IntPtr outhistogram);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayOutput_PickPixel(IntPtr real, ResourceId texID, bool customShader,
UInt32 x, UInt32 y, UInt32 sliceFace, UInt32 mip, UInt32 sample, IntPtr outval);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern UInt32 ReplayOutput_PickVertex(IntPtr real, UInt32 eventID, UInt32 x, UInt32 y, IntPtr outPickedInstance);
private IntPtr m_Real = IntPtr.Zero;
public ReplayOutput(IntPtr real) { m_Real = real; }
public bool SetOutputConfig(OutputConfig o)
{
return ReplayOutput_SetOutputConfig(m_Real, o);
}
public bool SetTextureDisplay(TextureDisplay o)
{
return ReplayOutput_SetTextureDisplay(m_Real, o);
}
public bool SetMeshDisplay(MeshDisplay o)
{
return ReplayOutput_SetMeshDisplay(m_Real, o);
}
public bool ClearThumbnails()
{
return ReplayOutput_ClearThumbnails(m_Real);
}
public bool AddThumbnail(IntPtr wnd, ResourceId texID, FormatComponentType typeHint)
{
// 1 == eWindowingSystem_Win32
return ReplayOutput_AddThumbnail(m_Real, 1u, wnd, texID, typeHint);
}
public bool Display()
{
return ReplayOutput_Display(m_Real);
}
public bool SetPixelContext(IntPtr wnd)
{
// 1 == eWindowingSystem_Win32
return ReplayOutput_SetPixelContext(m_Real, 1u, wnd);
}
public bool SetPixelContextLocation(UInt32 x, UInt32 y)
{
return ReplayOutput_SetPixelContextLocation(m_Real, x, y);
}
public void DisablePixelContext()
{
ReplayOutput_DisablePixelContext(m_Real);
}
public ResourceId GetCustomShaderTexID()
{
ResourceId ret = ResourceId.Null;
ReplayOutput_GetCustomShaderTexID(m_Real, ref ret);
return ret;
}
public bool GetMinMax(out PixelValue minval, out PixelValue maxval)
{
IntPtr mem1 = CustomMarshal.Alloc(typeof(PixelValue));
IntPtr mem2 = CustomMarshal.Alloc(typeof(PixelValue));
bool success = ReplayOutput_GetMinMax(m_Real, mem1, mem2);
if (success)
{
minval = (PixelValue)CustomMarshal.PtrToStructure(mem1, typeof(PixelValue), true);
maxval = (PixelValue)CustomMarshal.PtrToStructure(mem2, typeof(PixelValue), true);
}
else
{
minval = null;
maxval = null;
}
CustomMarshal.Free(mem1);
CustomMarshal.Free(mem2);
return success;
}
public bool GetHistogram(float minval, float maxval,
bool Red, bool Green, bool Blue, bool Alpha,
out UInt32[] histogram)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
bool[] channels = new bool[] { Red, Green, Blue, Alpha };
bool success = ReplayOutput_GetHistogram(m_Real, minval, maxval, channels, mem);
histogram = null;
if (success)
histogram = (UInt32[])CustomMarshal.GetTemplatedArray(mem, typeof(UInt32), true);
CustomMarshal.Free(mem);
return success;
}
public PixelValue PickPixel(ResourceId texID, bool customShader, UInt32 x, UInt32 y, UInt32 sliceFace, UInt32 mip, UInt32 sample)
{
IntPtr mem = CustomMarshal.Alloc(typeof(PixelValue));
bool success = ReplayOutput_PickPixel(m_Real, texID, customShader, x, y, sliceFace, mip, sample, mem);
PixelValue ret = null;
if(success)
ret = (PixelValue)CustomMarshal.PtrToStructure(mem, typeof(PixelValue), false);
CustomMarshal.Free(mem);
return ret;
}
public UInt32 PickVertex(UInt32 eventID, UInt32 x, UInt32 y, out UInt32 pickedInstance)
{
IntPtr mem = CustomMarshal.Alloc(typeof(UInt32));
UInt32 pickedVertex = ReplayOutput_PickVertex(m_Real, eventID, x, y, mem);
pickedInstance = (UInt32)CustomMarshal.PtrToStructure(mem, typeof(UInt32), true);
CustomMarshal.Free(mem);
return pickedVertex;
}
};
public class ReplayRenderer
{
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_Shutdown(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_GetAPIProperties(IntPtr real, IntPtr propsOut);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr ReplayRenderer_CreateOutput(IntPtr real, UInt32 windowSystem, IntPtr WindowHandle, OutputType type);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_ShutdownOutput(IntPtr real, IntPtr replayOutput);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_FileChanged(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_HasCallstacks(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_InitResolver(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_SetFrameEvent(IntPtr real, UInt32 eventID, bool force);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_GetD3D11PipelineState(IntPtr real, IntPtr mem);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_GetD3D12PipelineState(IntPtr real, IntPtr mem);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_GetGLPipelineState(IntPtr real, IntPtr mem);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_GetVulkanPipelineState(IntPtr real, IntPtr mem);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_BuildCustomShader(IntPtr real, IntPtr entry, IntPtr source, UInt32 compileFlags, ShaderStageType type, ref ResourceId shaderID, IntPtr errorMem);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_FreeCustomShader(IntPtr real, ResourceId id);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void ReplayRenderer_BuildTargetShader(IntPtr real, IntPtr entry, IntPtr source, UInt32 compileFlags, ShaderStageType type, ref ResourceId shaderID, IntPtr errorMem);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_ReplaceResource(IntPtr real, ResourceId from, ResourceId to);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_RemoveReplacement(IntPtr real, ResourceId id);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_FreeTargetResource(IntPtr real, ResourceId id);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_GetFrameInfo(IntPtr real, IntPtr outframe);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_GetDrawcalls(IntPtr real, IntPtr outdraws);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_FetchCounters(IntPtr real, IntPtr counters, UInt32 numCounters, IntPtr outresults);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_EnumerateCounters(IntPtr real, IntPtr outcounters);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_DescribeCounter(IntPtr real, UInt32 counter, IntPtr outdesc);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_GetTextures(IntPtr real, IntPtr outtexs);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_GetBuffers(IntPtr real, IntPtr outbufs);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_GetResolve(IntPtr real, UInt64[] callstack, UInt32 callstackLen, IntPtr outtrace);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_GetDebugMessages(IntPtr real, IntPtr outmsgs);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_PixelHistory(IntPtr real, ResourceId target, UInt32 x, UInt32 y, UInt32 slice, UInt32 mip, UInt32 sampleIdx, FormatComponentType typeHint, IntPtr history);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_DebugVertex(IntPtr real, UInt32 vertid, UInt32 instid, UInt32 idx, UInt32 instOffset, UInt32 vertOffset, IntPtr outtrace);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_DebugPixel(IntPtr real, UInt32 x, UInt32 y, UInt32 sample, UInt32 primitive, IntPtr outtrace);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_DebugThread(IntPtr real, UInt32[] groupid, UInt32[] threadid, IntPtr outtrace);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_GetUsage(IntPtr real, ResourceId id, IntPtr outusage);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_GetCBufferVariableContents(IntPtr real, ResourceId shader, IntPtr entryPoint, UInt32 cbufslot, ResourceId buffer, UInt64 offs, IntPtr outvars);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_SaveTexture(IntPtr real, TextureSave saveData, IntPtr path);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_GetPostVSData(IntPtr real, UInt32 instID, MeshDataStage stage, IntPtr outdata);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_GetBufferData(IntPtr real, ResourceId buff, UInt64 offset, UInt64 len, IntPtr outdata);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool ReplayRenderer_GetTextureData(IntPtr real, ResourceId tex, UInt32 arrayIdx, UInt32 mip, IntPtr outdata);
private IntPtr m_Real = IntPtr.Zero;
public IntPtr Real { get { return m_Real; } }
public ReplayRenderer(IntPtr real) { m_Real = real; }
public void Shutdown()
{
if (m_Real != IntPtr.Zero)
{
ReplayRenderer_Shutdown(m_Real);
m_Real = IntPtr.Zero;
}
}
public APIProperties GetAPIProperties()
{
IntPtr mem = CustomMarshal.Alloc(typeof(APIProperties));
ReplayRenderer_GetAPIProperties(m_Real, mem);
APIProperties ret = (APIProperties)CustomMarshal.PtrToStructure(mem, typeof(APIProperties), true);
CustomMarshal.Free(mem);
return ret;
}
public ReplayOutput CreateOutput(IntPtr WindowHandle, OutputType type)
{
// 0 == eWindowingSystem_Unknown
// 1 == eWindowingSystem_Win32
IntPtr ret = ReplayRenderer_CreateOutput(m_Real, WindowHandle == IntPtr.Zero ? 0u : 1u, WindowHandle, type);
if (ret == IntPtr.Zero)
return null;
return new ReplayOutput(ret);
}
public void FileChanged()
{ ReplayRenderer_FileChanged(m_Real); }
public bool HasCallstacks()
{ return ReplayRenderer_HasCallstacks(m_Real); }
public bool InitResolver()
{ return ReplayRenderer_InitResolver(m_Real); }
public bool SetFrameEvent(UInt32 eventID, bool force)
{ return ReplayRenderer_SetFrameEvent(m_Real, eventID, force); }
public GLPipelineState GetGLPipelineState()
{
IntPtr mem = CustomMarshal.Alloc(typeof(GLPipelineState));
bool success = ReplayRenderer_GetGLPipelineState(m_Real, mem);
GLPipelineState ret = null;
if (success)
ret = (GLPipelineState)CustomMarshal.PtrToStructure(mem, typeof(GLPipelineState), true);
CustomMarshal.Free(mem);
return ret;
}
public D3D11PipelineState GetD3D11PipelineState()
{
IntPtr mem = CustomMarshal.Alloc(typeof(D3D11PipelineState));
bool success = ReplayRenderer_GetD3D11PipelineState(m_Real, mem);
D3D11PipelineState ret = null;
if (success)
ret = (D3D11PipelineState)CustomMarshal.PtrToStructure(mem, typeof(D3D11PipelineState), true);
CustomMarshal.Free(mem);
return ret;
}
public D3D12PipelineState GetD3D12PipelineState()
{
IntPtr mem = CustomMarshal.Alloc(typeof(D3D12PipelineState));
bool success = ReplayRenderer_GetD3D12PipelineState(m_Real, mem);
D3D12PipelineState ret = null;
if (success)
ret = (D3D12PipelineState)CustomMarshal.PtrToStructure(mem, typeof(D3D12PipelineState), true);
CustomMarshal.Free(mem);
return ret;
}
public VulkanPipelineState GetVulkanPipelineState()
{
IntPtr mem = CustomMarshal.Alloc(typeof(VulkanPipelineState));
bool success = ReplayRenderer_GetVulkanPipelineState(m_Real, mem);
VulkanPipelineState ret = null;
if (success)
ret = (VulkanPipelineState)CustomMarshal.PtrToStructure(mem, typeof(VulkanPipelineState), true);
CustomMarshal.Free(mem);
return ret;
}
public ResourceId BuildCustomShader(string entry, string source, UInt32 compileFlags, ShaderStageType type, out string errors)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
ResourceId ret = ResourceId.Null;
IntPtr entry_mem = CustomMarshal.MakeUTF8String(entry);
IntPtr source_mem = CustomMarshal.MakeUTF8String(source);
ReplayRenderer_BuildCustomShader(m_Real, entry_mem, source_mem, compileFlags, type, ref ret, mem);
CustomMarshal.Free(entry_mem);
CustomMarshal.Free(source_mem);
errors = CustomMarshal.TemplatedArrayToString(mem, true);
CustomMarshal.Free(mem);
return ret;
}
public bool FreeCustomShader(ResourceId id)
{ return ReplayRenderer_FreeCustomShader(m_Real, id); }
public ResourceId BuildTargetShader(string entry, string source, UInt32 compileFlags, ShaderStageType type, out string errors)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
ResourceId ret = ResourceId.Null;
IntPtr entry_mem = CustomMarshal.MakeUTF8String(entry);
IntPtr source_mem = CustomMarshal.MakeUTF8String(source);
ReplayRenderer_BuildTargetShader(m_Real, entry_mem, source_mem, compileFlags, type, ref ret, mem);
CustomMarshal.Free(entry_mem);
CustomMarshal.Free(source_mem);
errors = CustomMarshal.TemplatedArrayToString(mem, true);
CustomMarshal.Free(mem);
return ret;
}
public bool ReplaceResource(ResourceId from, ResourceId to)
{ return ReplayRenderer_ReplaceResource(m_Real, from, to); }
public bool RemoveReplacement(ResourceId id)
{ return ReplayRenderer_RemoveReplacement(m_Real, id); }
public bool FreeTargetResource(ResourceId id)
{ return ReplayRenderer_FreeTargetResource(m_Real, id); }
public FetchFrameInfo GetFrameInfo()
{
IntPtr mem = CustomMarshal.Alloc(typeof(FetchFrameInfo));
bool success = ReplayRenderer_GetFrameInfo(m_Real, mem);
FetchFrameInfo ret = null;
if (success)
ret = (FetchFrameInfo)CustomMarshal.PtrToStructure(mem, typeof(FetchFrameInfo), true);
CustomMarshal.Free(mem);
return ret;
}
private void PopulateDraws(ref Dictionary<Int64, FetchDrawcall> map, FetchDrawcall[] draws)
{
if (draws.Length == 0) return;
foreach (var d in draws)
{
map.Add((Int64)d.eventID, d);
PopulateDraws(ref map, d.children);
}
}
private void FixupDraws(Dictionary<Int64, FetchDrawcall> map, FetchDrawcall[] draws)
{
if (draws.Length == 0) return;
foreach (var d in draws)
{
if (d.previousDrawcall != 0 && map.ContainsKey(d.previousDrawcall)) d.previous = map[d.previousDrawcall];
if (d.nextDrawcall != 0 && map.ContainsKey(d.nextDrawcall)) d.next = map[d.nextDrawcall];
if (d.parentDrawcall != 0 && map.ContainsKey(d.parentDrawcall)) d.parent = map[d.parentDrawcall];
FixupDraws(map, d.children);
}
}
public Dictionary<uint, List<CounterResult>> FetchCounters(UInt32[] counters)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
IntPtr countersmem = CustomMarshal.Alloc(typeof(UInt32), counters.Length);
// there's no Marshal.Copy for uint[], which is stupid.
for (int i = 0; i < counters.Length; i++)
Marshal.WriteInt32(countersmem, sizeof(UInt32) * i, (int)counters[i]);
bool success = ReplayRenderer_FetchCounters(m_Real, countersmem, (uint)counters.Length, mem);
CustomMarshal.Free(countersmem);
Dictionary<uint, List<CounterResult>> ret = null;
if (success)
{
CounterResult[] resultArray = (CounterResult[])CustomMarshal.GetTemplatedArray(mem, typeof(CounterResult), true);
// fixup previous/next/parent pointers
ret = new Dictionary<uint, List<CounterResult>>();
foreach (var result in resultArray)
{
if (!ret.ContainsKey(result.eventID))
ret.Add(result.eventID, new List<CounterResult>());
ret[result.eventID].Add(result);
}
}
CustomMarshal.Free(mem);
return ret;
}
public UInt32[] EnumerateCounters()
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
bool success = ReplayRenderer_EnumerateCounters(m_Real, mem);
UInt32[] ret = null;
if (success)
{
ret = (UInt32[])CustomMarshal.GetTemplatedArray(mem, typeof(UInt32), true);
}
CustomMarshal.Free(mem);
return ret;
}
public CounterDescription DescribeCounter(UInt32 counterID)
{
IntPtr mem = CustomMarshal.Alloc(typeof(CounterDescription));
bool success = ReplayRenderer_DescribeCounter(m_Real, counterID, mem);
CounterDescription ret = null;
if (success)
{
ret = (CounterDescription)CustomMarshal.PtrToStructure(mem, typeof(CounterDescription), false);
}
CustomMarshal.Free(mem);
return ret;
}
public FetchDrawcall[] GetDrawcalls()
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
bool success = ReplayRenderer_GetDrawcalls(m_Real, mem);
FetchDrawcall[] ret = null;
if (success)
{
ret = (FetchDrawcall[])CustomMarshal.GetTemplatedArray(mem, typeof(FetchDrawcall), true);
// fixup previous/next/parent pointers
var map = new Dictionary<Int64, FetchDrawcall>();
PopulateDraws(ref map, ret);
FixupDraws(map, ret);
}
CustomMarshal.Free(mem);
return ret;
}
public FetchTexture[] GetTextures()
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
bool success = ReplayRenderer_GetTextures(m_Real, mem);
FetchTexture[] ret = null;
if (success)
ret = (FetchTexture[])CustomMarshal.GetTemplatedArray(mem, typeof(FetchTexture), true);
CustomMarshal.Free(mem);
return ret;
}
public FetchBuffer[] GetBuffers()
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
bool success = ReplayRenderer_GetBuffers(m_Real, mem);
FetchBuffer[] ret = null;
if (success)
ret = (FetchBuffer[])CustomMarshal.GetTemplatedArray(mem, typeof(FetchBuffer), true);
CustomMarshal.Free(mem);
return ret;
}
public string[] GetResolve(UInt64[] callstack)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
UInt32 len = (UInt32)callstack.Length;
bool success = ReplayRenderer_GetResolve(m_Real, callstack, len, mem);
string[] ret = null;
if (success)
ret = CustomMarshal.TemplatedArrayToStringArray(mem, true);
CustomMarshal.Free(mem);
return ret;
}
public DebugMessage[] GetDebugMessages()
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
bool success = ReplayRenderer_GetDebugMessages(m_Real, mem);
DebugMessage[] ret = null;
if (success)
ret = (DebugMessage[])CustomMarshal.GetTemplatedArray(mem, typeof(DebugMessage), true);
CustomMarshal.Free(mem);
return ret;
}
public PixelModification[] PixelHistory(ResourceId target, UInt32 x, UInt32 y, UInt32 slice, UInt32 mip, UInt32 sampleIdx, FormatComponentType typeHint)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
bool success = ReplayRenderer_PixelHistory(m_Real, target, x, y, slice, mip, sampleIdx, typeHint, mem);
PixelModification[] ret = null;
if (success)
ret = (PixelModification[])CustomMarshal.GetTemplatedArray(mem, typeof(PixelModification), true);
CustomMarshal.Free(mem);
return ret;
}
public ShaderDebugTrace DebugVertex(UInt32 vertid, UInt32 instid, UInt32 idx, UInt32 instOffset, UInt32 vertOffset)
{
IntPtr mem = CustomMarshal.Alloc(typeof(ShaderDebugTrace));
bool success = ReplayRenderer_DebugVertex(m_Real, vertid, instid, idx, instOffset, vertOffset, mem);
ShaderDebugTrace ret = null;
if (success)
ret = (ShaderDebugTrace)CustomMarshal.PtrToStructure(mem, typeof(ShaderDebugTrace), true);
CustomMarshal.Free(mem);
return ret;
}
public ShaderDebugTrace DebugPixel(UInt32 x, UInt32 y, UInt32 sample, UInt32 primitive)
{
IntPtr mem = CustomMarshal.Alloc(typeof(ShaderDebugTrace));
bool success = ReplayRenderer_DebugPixel(m_Real, x, y, sample, primitive, mem);
ShaderDebugTrace ret = null;
if (success)
ret = (ShaderDebugTrace)CustomMarshal.PtrToStructure(mem, typeof(ShaderDebugTrace), true);
CustomMarshal.Free(mem);
return ret;
}
public ShaderDebugTrace DebugThread(UInt32[] groupid, UInt32[] threadid)
{
IntPtr mem = CustomMarshal.Alloc(typeof(ShaderDebugTrace));
bool success = ReplayRenderer_DebugThread(m_Real, groupid, threadid, mem);
ShaderDebugTrace ret = null;
if (success)
ret = (ShaderDebugTrace)CustomMarshal.PtrToStructure(mem, typeof(ShaderDebugTrace), true);
CustomMarshal.Free(mem);
return ret;
}
public EventUsage[] GetUsage(ResourceId id)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
bool success = ReplayRenderer_GetUsage(m_Real, id, mem);
EventUsage[] ret = null;
if (success)
ret = (EventUsage[])CustomMarshal.GetTemplatedArray(mem, typeof(EventUsage), true);
CustomMarshal.Free(mem);
return ret;
}
public ShaderVariable[] GetCBufferVariableContents(ResourceId shader, string entryPoint, UInt32 cbufslot, ResourceId buffer, UInt64 offs)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
IntPtr entry_mem = CustomMarshal.MakeUTF8String(entryPoint);
bool success = ReplayRenderer_GetCBufferVariableContents(m_Real, shader, entry_mem, cbufslot, buffer, offs, mem);
ShaderVariable[] ret = null;
if (success)
ret = (ShaderVariable[])CustomMarshal.GetTemplatedArray(mem, typeof(ShaderVariable), true);
CustomMarshal.Free(entry_mem);
CustomMarshal.Free(mem);
return ret;
}
public bool SaveTexture(TextureSave saveData, string path)
{
IntPtr path_mem = CustomMarshal.MakeUTF8String(path);
bool ret = ReplayRenderer_SaveTexture(m_Real, saveData, path_mem);
CustomMarshal.Free(path_mem);
return ret;
}
public MeshFormat GetPostVSData(UInt32 instID, MeshDataStage stage)
{
IntPtr mem = CustomMarshal.Alloc(typeof(MeshFormat));
MeshFormat ret = new MeshFormat();
ret.buf = ResourceId.Null;
bool success = ReplayRenderer_GetPostVSData(m_Real, instID, stage, mem);
if (success)
ret = (MeshFormat)CustomMarshal.PtrToStructure(mem, typeof(MeshFormat), true);
CustomMarshal.Free(mem);
return ret;
}
public byte[] GetBufferData(ResourceId buff, UInt64 offset, UInt64 len)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
bool success = ReplayRenderer_GetBufferData(m_Real, buff, offset, len, mem);
byte[] ret = new byte[] { };
if (success)
ret = (byte[])CustomMarshal.GetTemplatedArray(mem, typeof(byte), true);
CustomMarshal.Free(mem);
return ret;
}
public byte[] GetTextureData(ResourceId tex, UInt32 arrayIdx, UInt32 mip)
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
bool success = ReplayRenderer_GetTextureData(m_Real, tex, arrayIdx, mip, mem);
byte[] ret = new byte[] { };
if (success)
ret = (byte[])CustomMarshal.GetTemplatedArray(mem, typeof(byte), true);
CustomMarshal.Free(mem);
return ret;
}
};
public class RemoteServer
{
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_ShutdownConnection(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_ShutdownServerAndConnection(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool RemoteServer_Ping(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool RemoteServer_LocalProxies(IntPtr real, IntPtr outlist);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern bool RemoteServer_RemoteSupportedReplays(IntPtr real, IntPtr outlist);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_GetHomeFolder(IntPtr real, IntPtr outfolder);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_ListFolder(IntPtr real, IntPtr path, IntPtr outlist);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern UInt32 RemoteServer_ExecuteAndInject(IntPtr real, IntPtr app, IntPtr workingDir, IntPtr cmdLine, IntPtr env, CaptureOptions opts);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_TakeOwnershipCapture(IntPtr real, IntPtr filename);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_CopyCaptureToRemote(IntPtr real, IntPtr filename, ref float progress, IntPtr remotepath);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_CopyCaptureFromRemote(IntPtr real, IntPtr remotepath, IntPtr localpath, ref float progress);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern ReplayCreateStatus RemoteServer_OpenCapture(IntPtr real, UInt32 proxyid, IntPtr logfile, ref float progress, ref IntPtr rendPtr);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RemoteServer_CloseCapture(IntPtr real, IntPtr rendPtr);
// static exports for lists of environment modifications
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr RENDERDOC_MakeEnvironmentModificationList(int numElems);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RENDERDOC_SetEnvironmentModification(IntPtr mem, int idx, IntPtr variable, IntPtr value,
EnvironmentModificationType type, EnvironmentSeparator separator);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void RENDERDOC_FreeEnvironmentModificationList(IntPtr mem);
private IntPtr m_Real = IntPtr.Zero;
public RemoteServer(IntPtr real) { m_Real = real; }
public void ShutdownConnection()
{
if (m_Real != IntPtr.Zero)
{
RemoteServer_ShutdownConnection(m_Real);
m_Real = IntPtr.Zero;
}
}
public void ShutdownServerAndConnection()
{
if (m_Real != IntPtr.Zero)
{
RemoteServer_ShutdownServerAndConnection(m_Real);
m_Real = IntPtr.Zero;
}
}
public string GetHomeFolder()
{
IntPtr homepath_mem = CustomMarshal.Alloc(typeof(templated_array));
RemoteServer_GetHomeFolder(m_Real, homepath_mem);
string home = CustomMarshal.TemplatedArrayToString(homepath_mem, true);
CustomMarshal.Free(homepath_mem);
// normalise to /s and with no trailing /s
home = home.Replace('\\', '/');
if (home[home.Length - 1] == '/')
home = home.Remove(0, home.Length - 1);
return home;
}
public DirectoryFile[] ListFolder(string path)
{
IntPtr path_mem = CustomMarshal.MakeUTF8String(path);
IntPtr out_mem = CustomMarshal.Alloc(typeof(templated_array));
RemoteServer_ListFolder(m_Real, path_mem, out_mem);
DirectoryFile[] ret = (DirectoryFile[])CustomMarshal.GetTemplatedArray(out_mem, typeof(DirectoryFile), true);
CustomMarshal.Free(out_mem);
CustomMarshal.Free(path_mem);
Array.Sort(ret);
return ret;
}
public bool Ping()
{
return RemoteServer_Ping(m_Real);
}
public string[] LocalProxies()
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
bool success = RemoteServer_LocalProxies(m_Real, mem);
string[] ret = null;
if (success)
ret = CustomMarshal.TemplatedArrayToStringArray(mem, true);
CustomMarshal.Free(mem);
return ret;
}
public string[] RemoteSupportedReplays()
{
IntPtr mem = CustomMarshal.Alloc(typeof(templated_array));
bool success = RemoteServer_RemoteSupportedReplays(m_Real, mem);
string[] ret = null;
if (success)
ret = CustomMarshal.TemplatedArrayToStringArray(mem, true);
CustomMarshal.Free(mem);
return ret;
}
public UInt32 ExecuteAndInject(string app, string workingDir, string cmdLine, EnvironmentModification[] env, CaptureOptions opts)
{
IntPtr app_mem = CustomMarshal.MakeUTF8String(app);
IntPtr workingDir_mem = CustomMarshal.MakeUTF8String(workingDir);
IntPtr cmdLine_mem = CustomMarshal.MakeUTF8String(cmdLine);
IntPtr env_mem = RENDERDOC_MakeEnvironmentModificationList(env.Length);
for (int i = 0; i < env.Length; i++)
{
IntPtr var_mem = CustomMarshal.MakeUTF8String(env[i].variable);
IntPtr val_mem = CustomMarshal.MakeUTF8String(env[i].value);
RENDERDOC_SetEnvironmentModification(env_mem, i, var_mem, val_mem, env[i].type, env[i].separator);
CustomMarshal.Free(var_mem);
CustomMarshal.Free(val_mem);
}
UInt32 ret = RemoteServer_ExecuteAndInject(m_Real, app_mem, workingDir_mem, cmdLine_mem, env_mem, opts);
RENDERDOC_FreeEnvironmentModificationList(env_mem);
CustomMarshal.Free(app_mem);
CustomMarshal.Free(workingDir_mem);
CustomMarshal.Free(cmdLine_mem);
return ret;
}
public void TakeOwnershipCapture(string filename)
{
IntPtr filename_mem = CustomMarshal.MakeUTF8String(filename);
RemoteServer_TakeOwnershipCapture(m_Real, filename_mem);
CustomMarshal.Free(filename_mem);
}
public string CopyCaptureToRemote(string filename, ref float progress)
{
IntPtr remotepath = CustomMarshal.Alloc(typeof(templated_array));
IntPtr filename_mem = CustomMarshal.MakeUTF8String(filename);
RemoteServer_CopyCaptureToRemote(m_Real, filename_mem, ref progress, remotepath);
CustomMarshal.Free(filename_mem);
string remote = CustomMarshal.TemplatedArrayToString(remotepath, true);
CustomMarshal.Free(remotepath);
return remote;
}
public void CopyCaptureFromRemote(string remotepath, string localpath, ref float progress)
{
IntPtr remotepath_mem = CustomMarshal.MakeUTF8String(remotepath);
IntPtr localpath_mem = CustomMarshal.MakeUTF8String(localpath);
RemoteServer_CopyCaptureFromRemote(m_Real, remotepath_mem, localpath_mem, ref progress);
CustomMarshal.Free(remotepath_mem);
CustomMarshal.Free(localpath_mem);
}
public ReplayRenderer OpenCapture(int proxyid, string logfile, ref float progress)
{
IntPtr rendPtr = IntPtr.Zero;
IntPtr logfile_mem = CustomMarshal.MakeUTF8String(logfile);
ReplayCreateStatus ret = RemoteServer_OpenCapture(m_Real, proxyid == -1 ? UInt32.MaxValue : (UInt32)proxyid, logfile_mem, ref progress, ref rendPtr);
CustomMarshal.Free(logfile_mem);
if (rendPtr == IntPtr.Zero || ret != ReplayCreateStatus.Success)
{
throw new ReplayCreateException(ret, "Failed to set up local proxy replay with remote connection");
}
return new ReplayRenderer(rendPtr);
}
public void CloseCapture(ReplayRenderer renderer)
{
RemoteServer_CloseCapture(m_Real, renderer.Real);
}
};
public class TargetControl
{
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void TargetControl_Shutdown(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr TargetControl_GetTarget(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr TargetControl_GetAPI(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern UInt32 TargetControl_GetPID(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr TargetControl_GetBusyClient(IntPtr real);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void TargetControl_TriggerCapture(IntPtr real, UInt32 numFrames);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void TargetControl_QueueCapture(IntPtr real, UInt32 frameNumber);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void TargetControl_CopyCapture(IntPtr real, UInt32 remoteID, IntPtr localpath);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void TargetControl_DeleteCapture(IntPtr real, UInt32 remoteID);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern void TargetControl_ReceiveMessage(IntPtr real, IntPtr outmsg);
[DllImport("renderdoc.dll", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern UInt32 RENDERDOC_EnumerateRemoteConnections(IntPtr host, UInt32[] idents);
private IntPtr m_Real = IntPtr.Zero;
private bool m_Connected;
public TargetControl(IntPtr real)
{
m_Real = real;
if (real == IntPtr.Zero)
{
m_Connected = false;
Target = "";
API = "";
BusyClient = "";
}
else
{
m_Connected = true;
Target = CustomMarshal.PtrToStringUTF8(TargetControl_GetTarget(m_Real));
API = CustomMarshal.PtrToStringUTF8(TargetControl_GetAPI(m_Real));
PID = TargetControl_GetPID(m_Real);
BusyClient = CustomMarshal.PtrToStringUTF8(TargetControl_GetBusyClient(m_Real));
}
CaptureExists = false;
CaptureCopied = false;
InfoUpdated = false;
}
public static UInt32[] GetRemoteIdents(string host)
{
UInt32 numIdents = RENDERDOC_EnumerateRemoteConnections(IntPtr.Zero, null);
UInt32[] idents = new UInt32[numIdents];
IntPtr host_mem = CustomMarshal.MakeUTF8String(host);
RENDERDOC_EnumerateRemoteConnections(host_mem, idents);
CustomMarshal.Free(host_mem);
return idents;
}
public bool Connected { get { return m_Connected; } }
public void Shutdown()
{
m_Connected = false;
if (m_Real != IntPtr.Zero) TargetControl_Shutdown(m_Real);
m_Real = IntPtr.Zero;
}
public void TriggerCapture(UInt32 numFrames)
{
TargetControl_TriggerCapture(m_Real, numFrames);
}
public void QueueCapture(UInt32 frameNum)
{
TargetControl_QueueCapture(m_Real, frameNum);
}
public void CopyCapture(UInt32 id, string localpath)
{
IntPtr localpath_mem = CustomMarshal.MakeUTF8String(localpath);
TargetControl_CopyCapture(m_Real, id, localpath_mem);
CustomMarshal.Free(localpath_mem);
}
public void DeleteCapture(UInt32 id)
{
TargetControl_DeleteCapture(m_Real, id);
}
public void ReceiveMessage()
{
if (m_Real != IntPtr.Zero)
{
TargetControlMessage msg = null;
{
IntPtr mem = CustomMarshal.Alloc(typeof(TargetControlMessage));
TargetControl_ReceiveMessage(m_Real, mem);
if (mem != IntPtr.Zero)
msg = (TargetControlMessage)CustomMarshal.PtrToStructure(mem, typeof(TargetControlMessage), true);
CustomMarshal.Free(mem);
}
if (msg == null)
return;
if (msg.Type == TargetControlMessageType.Disconnected)
{
m_Connected = false;
TargetControl_Shutdown(m_Real);
m_Real = IntPtr.Zero;
}
else if (msg.Type == TargetControlMessageType.NewCapture)
{
CaptureFile = msg.NewCapture;
CaptureExists = true;
}
else if (msg.Type == TargetControlMessageType.CaptureCopied)
{
CaptureFile.ID = msg.NewCapture.ID;
CaptureFile.path = msg.NewCapture.path;
CaptureCopied = true;
}
else if (msg.Type == TargetControlMessageType.RegisterAPI)
{
API = msg.RegisterAPI.APIName;
InfoUpdated = true;
}
else if (msg.Type == TargetControlMessageType.NewChild)
{
NewChild = msg.NewChild;
ChildAdded = true;
}
}
}
public string BusyClient;
public string Target;
public string API;
public UInt32 PID;
public bool CaptureExists;
public bool ChildAdded;
public bool CaptureCopied;
public bool InfoUpdated;
public TargetControlMessage.NewCaptureData CaptureFile = new TargetControlMessage.NewCaptureData();
public TargetControlMessage.NewChildData NewChild = new TargetControlMessage.NewChildData();
};
};
| |
/* 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.Windows.Forms;
using XenAdmin.Actions;
using XenAdmin.Actions.GUIActions;
using XenAdmin.Network;
using XenAdmin.Core;
using XenAPI;
namespace XenAdmin.Dialogs.WarningDialogs
{
public partial class CloseXenCenterWarningDialog : XenDialogBase
{
public CloseXenCenterWarningDialog()
: this(null)
{}
public CloseXenCenterWarningDialog(IXenConnection connection)
{
InitializeComponent();
if (connection != null)
{
this.connection = connection;
label2.Text = String.Format(Messages.DISCONNECT_WARNING, Helpers.GetName(connection).Ellipsise(50));
ExitButton.Text = Messages.DISCONNECT_ANYWAY;
DontExitButton.Text = Messages.DISCONNECT_CANCEL;
}
ConnectionsManager.History.CollectionChanged += History_CollectionChanged;
BuildList();
}
internal override string HelpName
{
get
{
return connection == null ? Name : "DisconnectServerWarningDialog";
}
}
private void BuildList()
{
try
{
dataGridViewActions.SuspendLayout();
dataGridViewActions.Rows.Clear();
var actions = ConnectionsManager.History.FindAll(CanAddRowAction);
SortActions(actions);
var rows = new List<DataGridViewActionRow>();
foreach (var action in actions)
{
var row = new DataGridViewActionRow(action);
rows.Add(row);
}
dataGridViewActions.Rows.AddRange(rows.ToArray());
foreach (DataGridViewActionRow row in dataGridViewActions.Rows)
RegisterActionEvents(row.Action);
}
finally
{
dataGridViewActions.ResumeLayout();
}
}
private bool CanAddRowAction(ActionBase action)
{
if (action.IsCompleted || action is MeddlingAction)
return false;
AsyncAction a = action as AsyncAction;
if (a != null && a.Cancelling)
return false;
if (connection == null)
return true;
var xo = action.Pool ?? action.Host ?? action.VM ?? action.SR as IXenObject;
if (xo == null || xo.Connection != connection)
return false;
return true;
}
private void RemoveActionRow(ActionBase action)
{
var row = FindRowFromAction(action);
if (row != null)
{
action.Changed -= action_Changed;
action.Completed -= action_Changed;
dataGridViewActions.Rows.Remove(row);
if (dataGridViewActions.RowCount == 0)
Close();
}
}
private DataGridViewActionRow FindRowFromAction(ActionBase action)
{
foreach (DataGridViewRow row in dataGridViewActions.Rows)
{
var actionRow = row as DataGridViewActionRow;
if (actionRow == null)
continue;
if (actionRow.Action == action)
return actionRow;
}
return null;
}
private void RegisterActionEvents(ActionBase action)
{
action.Completed -= action_Completed;
action.Changed -= action_Changed;
action.Completed += action_Completed;
action.Changed += action_Changed;
}
private void SortActions(List<ActionBase> actions)
{
if (dataGridViewActions.SortedColumn != null)
{
if (dataGridViewActions.SortedColumn.Index == columnStatus.Index)
actions.Sort(ActionBaseExtensions.CompareOnStatus);
else if (dataGridViewActions.SortedColumn.Index == columnMessage.Index)
actions.Sort(ActionBaseExtensions.CompareOnTitle);
else if (dataGridViewActions.SortedColumn.Index == columnLocation.Index)
actions.Sort(ActionBaseExtensions.CompareOnLocation);
else if (dataGridViewActions.SortedColumn.Index == columnDate.Index)
actions.Sort(ActionBaseExtensions.CompareOnDateStarted);
if (dataGridViewActions.SortOrder == SortOrder.Descending)
actions.Reverse();
}
}
private void ToggleExpandedState(int rowIndex)
{
var row = dataGridViewActions.Rows[rowIndex] as DataGridViewActionRow;
if (row == null)
return;
if (row.Expanded)
{
row.Cells[columnExpander.Index].Value = Properties.Resources.contracted_triangle;
row.Cells[columnMessage.Index].Value = row.Action.GetTitle();
}
else
{
row.Cells[columnExpander.Index].Value = Properties.Resources.expanded_triangle;
row.Cells[columnMessage.Index].Value = row.Action.GetDetails();
}
row.Expanded = !row.Expanded;
}
private void History_CollectionChanged(object sender, CollectionChangeEventArgs e)
{
Program.BeginInvoke(this, () =>
{
ActionBase action = (ActionBase)e.Element;
switch (e.Action)
{
case CollectionChangeAction.Add:
var actions = ConnectionsManager.History.FindAll(CanAddRowAction);
SortActions(actions);
var index = actions.IndexOf(action);
if (index > -1)
{
var row = new DataGridViewActionRow(action);
dataGridViewActions.Rows.Insert(0, row);
RegisterActionEvents(action);
}
break;
case CollectionChangeAction.Remove:
RemoveActionRow(action);
break;
case CollectionChangeAction.Refresh:
BuildList();
break;
}
});
}
private void action_Changed(ActionBase action)
{
if (!action.IsCompleted)
return;
Program.Invoke(this, () => RemoveActionRow(action));
}
private void action_Completed(ActionBase action)
{
Program.Invoke(this, () => RemoveActionRow(action));
}
private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
{
// If you click on the headers you can get -1 as the index.
if (e.ColumnIndex < 0 || e.RowIndex < 0 || e.ColumnIndex != columnExpander.Index)
return;
ToggleExpandedState(e.RowIndex);
}
private void datagridViewActions_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (dataGridViewActions.Columns[e.ColumnIndex].SortMode == DataGridViewColumnSortMode.Automatic)
BuildList();
}
#region Nested classes
private class DataGridViewActionRow : DataGridViewRow
{
private DataGridViewImageCell expanderCell = new DataGridViewImageCell();
private DataGridViewImageCell statusCell = new DataGridViewImageCell();
private DataGridViewTextBoxCell messageCell = new DataGridViewTextBoxCell();
private DataGridViewTextBoxCell locationCell = new DataGridViewTextBoxCell();
private DataGridViewTextBoxCell dateCell = new DataGridViewTextBoxCell();
public ActionBase Action { get; private set; }
public bool Expanded { get; set; }
public DataGridViewActionRow(ActionBase action)
{
Action = action;
Cells.AddRange(expanderCell, statusCell, messageCell, locationCell, dateCell);
RefreshSelf();
}
public void RefreshSelf()
{
statusCell.Value = Action.GetImage();
if (Expanded)
{
expanderCell.Value = Properties.Resources.expanded_triangle;
messageCell.Value = Action.GetDetails();
}
else
{
expanderCell.Value = Properties.Resources.contracted_triangle;
messageCell.Value = Action.GetTitle();
}
locationCell.Value = Action.GetLocation();
dateCell.Value = HelpersGUI.DateTimeToString(Action.Started.ToLocalTime(), Messages.DATEFORMAT_DMY_HM, true);
}
}
#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.
namespace System.Drawing
{
using System.Collections;
using System.Diagnostics;
using System.Globalization;
// Miscellaneous utilities
internal static class ClientUtils
{
// ExecutionEngineException is obsolete and shouldn't be used (to catch, throw or reference) anymore.
// Pragma added to prevent converting the "type is obsolete" warning into build error.
// File owner should fix this.
#pragma warning disable 618
public static bool IsCriticalException(Exception ex)
{
return ex is NullReferenceException
|| ex is StackOverflowException
|| ex is OutOfMemoryException
|| ex is System.Threading.ThreadAbortException
|| ex is ExecutionEngineException
|| ex is IndexOutOfRangeException
|| ex is AccessViolationException;
}
#pragma warning restore 618
public static bool IsSecurityOrCriticalException(Exception ex)
{
return (ex is System.Security.SecurityException) || IsCriticalException(ex);
}
public static int GetBitCount(uint x)
{
int count = 0;
while (x > 0)
{
x &= x - 1;
count++;
}
return count;
}
// Sequential version
// assumes sequential enum members 0,1,2,3,4 -etc.
//
public static bool IsEnumValid(Enum enumValue, int value, int minValue, int maxValue)
{
bool valid = (value >= minValue) && (value <= maxValue);
#if DEBUG
Debug_SequentialEnumIsDefinedCheck(enumValue, minValue, maxValue);
#endif
return valid;
}
// Useful for sequential enum values which only use powers of two 0,1,2,4,8 etc: IsEnumValid(val, min, max, 1)
// Valid example: TextImageRelation 0,1,2,4,8 - only one bit can ever be on, and the value is between 0 and 8.
//
// ClientUtils.IsEnumValid((int)(relation), /*min*/(int)TextImageRelation.None, (int)TextImageRelation.TextBeforeImage,1);
//
public static bool IsEnumValid(Enum enumValue, int value, int minValue, int maxValue, int maxNumberOfBitsOn)
{
System.Diagnostics.Debug.Assert(maxNumberOfBitsOn >= 0 && maxNumberOfBitsOn < 32, "expect this to be greater than zero and less than 32");
bool valid = (value >= minValue) && (value <= maxValue);
//Note: if it's 0, it'll have no bits on. If it's a power of 2, it'll have 1.
valid = (valid && GetBitCount((uint)value) <= maxNumberOfBitsOn);
#if DEBUG
Debug_NonSequentialEnumIsDefinedCheck(enumValue, minValue, maxValue, maxNumberOfBitsOn, valid);
#endif
return valid;
}
// Useful for enums that are a subset of a bitmask
// Valid example: EdgeEffects 0, 0x800 (FillInterior), 0x1000 (Flat), 0x4000(Soft), 0x8000(Mono)
//
// ClientUtils.IsEnumValid((int)(effects), /*mask*/ FillInterior | Flat | Soft | Mono,
// ,2);
//
public static bool IsEnumValid_Masked(Enum enumValue, int value, UInt32 mask)
{
bool valid = ((value & mask) == value);
#if DEBUG
Debug_ValidateMask(enumValue, mask);
#endif
return valid;
}
// Useful for cases where you have discontiguous members of the enum.
// Valid example: AutoComplete source.
// if (!ClientUtils.IsEnumValid(value, AutoCompleteSource.None,
// AutoCompleteSource.AllSystemSources
// AutoCompleteSource.AllUrl,
// AutoCompleteSource.CustomSource,
// AutoCompleteSource.FileSystem,
// AutoCompleteSource.FileSystemDirectories,
// AutoCompleteSource.HistoryList,
// AutoCompleteSource.ListItems,
// AutoCompleteSource.RecentlyUsedList))
//
// PERF tip: put the default value in the enum towards the front of the argument list.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public static bool IsEnumValid_NotSequential(System.Enum enumValue, int value, params int[] enumValues)
{
System.Diagnostics.Debug.Assert(Enum.GetValues(enumValue.GetType()).Length == enumValues.Length, "Not all the enum members were passed in.");
for (int i = 0; i < enumValues.Length; i++)
{
if (enumValues[i] == value)
{
return true;
}
}
return false;
}
#if DEBUG
[ThreadStatic]
private static Hashtable t_enumValueInfo;
public const int MaxCache = 300; // we think we're going to get O(100) of these, put in a tripwire if it gets larger.
private class SequentialEnumInfo
{
public SequentialEnumInfo(Type t)
{
int actualMinimum = int.MaxValue;
int actualMaximum = int.MinValue;
int countEnumVals = 0;
foreach (int iVal in Enum.GetValues(t))
{
actualMinimum = Math.Min(actualMinimum, iVal);
actualMaximum = Math.Max(actualMaximum, iVal);
countEnumVals++;
}
Debug.Assert(countEnumVals - 1 == actualMaximum - actualMinimum);
MinValue = actualMinimum;
MaxValue = actualMaximum;
}
public int MinValue;
public int MaxValue;
}
private static void Debug_SequentialEnumIsDefinedCheck(Enum value, int minVal, int maxVal)
{
Type enumType = value.GetType();
if (t_enumValueInfo == null)
{
t_enumValueInfo = new Hashtable();
}
SequentialEnumInfo sequentialEnumInfo = null;
if (t_enumValueInfo.ContainsKey(enumType))
{
sequentialEnumInfo = t_enumValueInfo[enumType] as SequentialEnumInfo;
}
if (sequentialEnumInfo == null)
{
sequentialEnumInfo = new SequentialEnumInfo(enumType);
Debug.Assert(t_enumValueInfo.Count <= MaxCache);
t_enumValueInfo[enumType] = sequentialEnumInfo;
}
Debug.Assert(minVal == sequentialEnumInfo.MinValue, "Minimum passed in is not the actual minimum for the enum. Consider changing the parameters or using a different function.");
Debug.Assert(maxVal == sequentialEnumInfo.MaxValue, "Maximum passed in is not the actual maximum for the enum. Consider changing the parameters or using a different function.");
}
private static void Debug_ValidateMask(Enum value, uint mask)
{
Type enumType = value.GetType();
uint newMask = 0;
foreach (int iVal in Enum.GetValues(enumType))
{
newMask = newMask | (uint)iVal;
}
Debug.Assert(newMask == mask, "Mask not valid in IsEnumValid!");
}
private static void Debug_NonSequentialEnumIsDefinedCheck(Enum value, int minVal, int maxVal, int maxBitsOn, bool isValid)
{
Type enumType = value.GetType();
int actualMinimum = int.MaxValue;
int actualMaximum = int.MinValue;
int checkedValue = Convert.ToInt32(value, CultureInfo.InvariantCulture);
int maxBitsFound = 0;
bool foundValue = false;
foreach (int iVal in Enum.GetValues(enumType))
{
actualMinimum = Math.Min(actualMinimum, iVal);
actualMaximum = Math.Max(actualMaximum, iVal);
maxBitsFound = Math.Max(maxBitsFound, GetBitCount((uint)iVal));
if (checkedValue == iVal)
{
foundValue = true;
}
}
Debug.Assert(minVal == actualMinimum, "Minimum passed in is not the actual minimum for the enum. Consider changing the parameters or using a different function.");
Debug.Assert(minVal == actualMinimum, "Maximum passed in is not the actual maximum for the enum. Consider changing the parameters or using a different function.");
Debug.Assert(maxBitsFound == maxBitsOn, "Incorrect usage of IsEnumValid function. The bits set to 1 in this enum was found to be: " + maxBitsFound.ToString(CultureInfo.InvariantCulture) + "this does not match what's passed in: " + maxBitsOn.ToString(CultureInfo.InvariantCulture));
Debug.Assert(foundValue == isValid, string.Format(CultureInfo.InvariantCulture, "Returning {0} but we actually {1} found the value in the enum! Consider using a different overload to IsValidEnum.", isValid, ((foundValue) ? "have" : "have not")));
}
#endif
/// <devdoc>
/// WeakRefCollection - a collection that holds onto weak references
///
/// Essentially you pass in the object as it is, and under the covers
/// we only hold a weak reference to the object.
///
/// -----------------------------------------------------------------
/// !!!IMPORTANT USAGE NOTE!!!
/// Users of this class should set the RefCheckThreshold property
/// explicitly or call ScavengeReferences every once in a while to
/// remove dead references.
/// Also avoid calling Remove(item). Instead call RemoveByHashCode(item)
/// to make sure dead refs are removed.
/// -----------------------------------------------------------------
///
/// </devdoc>
internal class WeakRefCollection : IList
{
private int _refCheckThreshold = Int32.MaxValue; // this means this is disabled by default.
private ArrayList _innerList;
internal WeakRefCollection()
{
_innerList = new ArrayList(4);
}
internal WeakRefCollection(int size)
{
_innerList = new ArrayList(size);
}
internal ArrayList InnerList
{
get { return _innerList; }
}
/// <summary>
/// Indicates the value where the collection should check its items to remove dead weakref left over.
/// Note: When GC collects weak refs from this collection the WeakRefObject identity changes since its
/// Target becomes null. This makes the item unrecognizable by the collection and cannot be
/// removed - Remove(item) and Contains(item) will not find it anymore.
///
/// </summary>
public int RefCheckThreshold
{
get
{
return _refCheckThreshold;
}
set
{
_refCheckThreshold = value;
}
}
public object this[int index]
{
get
{
WeakRefObject weakRef = InnerList[index] as WeakRefObject;
if ((weakRef != null) && (weakRef.IsAlive))
{
return weakRef.Target;
}
return null;
}
set
{
InnerList[index] = CreateWeakRefObject(value);
}
}
public void ScavengeReferences()
{
int currentIndex = 0;
int currentCount = Count;
for (int i = 0; i < currentCount; i++)
{
object item = this[currentIndex];
if (item == null)
{
InnerList.RemoveAt(currentIndex);
}
else
{ // only incriment if we have not removed the item
currentIndex++;
}
}
}
public override bool Equals(object obj)
{
WeakRefCollection other = obj as WeakRefCollection;
if (other == this)
{
return true;
}
if (other == null || Count != other.Count)
{
return false;
}
for (int i = 0; i < Count; i++)
{
if (InnerList[i] != other.InnerList[i])
{
if (InnerList[i] == null || !InnerList[i].Equals(other.InnerList[i]))
{
return false;
}
}
}
return true;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
private WeakRefObject CreateWeakRefObject(object value)
{
if (value == null)
{
return null;
}
return new WeakRefObject(value);
}
private static void Copy(WeakRefCollection sourceList, int sourceIndex, WeakRefCollection destinationList, int destinationIndex, int length)
{
if (sourceIndex < destinationIndex)
{
// We need to copy from the back forward to prevent overwrite if source and
// destination lists are the same, so we need to flip the source/dest indices
// to point at the end of the spans to be copied.
sourceIndex = sourceIndex + length;
destinationIndex = destinationIndex + length;
for (; length > 0; length--)
{
destinationList.InnerList[--destinationIndex] = sourceList.InnerList[--sourceIndex];
}
}
else
{
for (; length > 0; length--)
{
destinationList.InnerList[destinationIndex++] = sourceList.InnerList[sourceIndex++];
}
}
}
/// <summary>
/// Removes the value using its hash code as its identity.
/// This is needed because the underlying item in the collection may have already been collected
/// changing the identity of the WeakRefObject making it impossible for the collection to identify
/// it. See WeakRefObject for more info.
/// </summary>
public void RemoveByHashCode(object value)
{
if (value == null)
{
return;
}
int hash = value.GetHashCode();
for (int idx = 0; idx < InnerList.Count; idx++)
{
if (InnerList[idx] != null && InnerList[idx].GetHashCode() == hash)
{
RemoveAt(idx);
return;
}
}
}
#region IList Members
public void Clear() { InnerList.Clear(); }
public bool IsFixedSize { get { return InnerList.IsFixedSize; } }
public bool Contains(object value) { return InnerList.Contains(CreateWeakRefObject(value)); }
public void RemoveAt(int index) { InnerList.RemoveAt(index); }
public void Remove(object value) { InnerList.Remove(CreateWeakRefObject(value)); }
public int IndexOf(object value) { return InnerList.IndexOf(CreateWeakRefObject(value)); }
public void Insert(int index, object value) { InnerList.Insert(index, CreateWeakRefObject(value)); }
public int Add(object value)
{
if (Count > RefCheckThreshold)
{
ScavengeReferences();
}
return InnerList.Add(CreateWeakRefObject(value));
}
#endregion
#region ICollection Members
/// <include file='doc\ArrangedElementCollection.uex' path='docs/doc[@for="ArrangedElementCollection.Count"]/*' />
public int Count { get { return InnerList.Count; } }
object ICollection.SyncRoot { get { return InnerList.SyncRoot; } }
public bool IsReadOnly { get { return InnerList.IsReadOnly; } }
public void CopyTo(Array array, int index) { InnerList.CopyTo(array, index); }
bool ICollection.IsSynchronized { get { return InnerList.IsSynchronized; } }
#endregion
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
return InnerList.GetEnumerator();
}
#endregion
/// <summary>
/// Wraps a weak ref object.
/// WARNING: Use this class carefully!
/// When the weak ref is collected, this object looses its identity. This is bad when the object
/// has been added to a collection since Contains(WeakRef(item)) and Remove(WeakRef(item)) would
/// not be able to identify the item.
/// </summary>
internal class WeakRefObject
{
private int _hash;
private WeakReference _weakHolder;
internal WeakRefObject(object obj)
{
Debug.Assert(obj != null, "Unexpected null object!");
_weakHolder = new WeakReference(obj);
_hash = obj.GetHashCode();
}
internal bool IsAlive
{
get { return _weakHolder.IsAlive; }
}
internal object Target
{
get
{
return _weakHolder.Target;
}
}
public override int GetHashCode()
{
return _hash;
}
public override bool Equals(object obj)
{
WeakRefObject other = obj as WeakRefObject;
if (other == this)
{
return true;
}
if (other == null)
{
return false;
}
if (other.Target != Target)
{
if (Target == null || !Target.Equals(other.Target))
{
return false;
}
}
return true;
}
}
}
}
}
| |
// ===========================================================
// Copyright (C) 2014-2015 Kendar.org
//
// 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 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.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Node.Cs.Lib.Utils
{
public static class MimeResolver
{
public static string Resolve(string ext)
{
ext = ext.Trim('.').ToLowerInvariant();
if (_mimeTypes.ContainsKey(ext)) return _mimeTypes[ext];
return "application/octet-stream";
}
private static Dictionary<string, string> _mimeTypes = new Dictionary<string, string>
{
{ "123", "application/vnd.lotus-1-2-3" },
{ "3dml", "text/vnd.in3d.3dml" },
{ "3g2", "video/3gpp2" },
{ "3gp", "video/3gpp" },
{ "7z", "application/x-7z-compressed" },
{ "aab", "application/x-authorware-bin" },
{ "aac", "audio/x-aac" },
{ "aam", "application/x-authorware-map" },
{ "aas", "application/x-authorware-seg" },
{ "abw", "application/x-abiword" },
{ "ac", "application/pkix-attr-cert" },
{ "acc", "application/vnd.americandynamics.acc" },
{ "ace", "application/x-ace-compressed" },
{ "acu", "application/vnd.acucobol" },
{ "acutc", "application/vnd.acucorp" },
{ "adp", "audio/adpcm" },
{ "aep", "application/vnd.audiograph" },
{ "afm", "application/x-font-type1" },
{ "afp", "application/vnd.ibm.modcap" },
{ "ahead", "application/vnd.ahead.space" },
{ "ai", "application/postscript" },
{ "aif", "audio/x-aiff" },
{ "aifc", "audio/x-aiff" },
{ "aiff", "audio/x-aiff" },
{ "air", "application/vnd.adobe.air-application-installer-package+zip" },
{ "ait", "application/vnd.dvb.ait" },
{ "ami", "application/vnd.amiga.ami" },
{ "apk", "application/vnd.android.package-archive" },
{ "application", "application/x-ms-application" },
{ "apr", "application/vnd.lotus-approach" },
{ "asc", "application/pgp-signature" },
{ "asf", "video/x-ms-asf" },
{ "asm", "text/x-asm" },
{ "aso", "application/vnd.accpac.simply.aso" },
{ "asx", "video/x-ms-asf" },
{ "atc", "application/vnd.acucorp" },
{ "atom", "application/atom+xml" },
{ "atomcat", "application/atomcat+xml" },
{ "atomsvc", "application/atomsvc+xml" },
{ "atx", "application/vnd.antix.game-component" },
{ "au", "audio/basic" },
{ "avi", "video/x-msvideo" },
{ "aw", "application/applixware" },
{ "azf", "application/vnd.airzip.filesecure.azf" },
{ "azs", "application/vnd.airzip.filesecure.azs" },
{ "azw", "application/vnd.amazon.ebook" },
{ "bat", "application/x-msdownload" },
{ "bcpio", "application/x-bcpio" },
{ "bdf", "application/x-font-bdf" },
{ "bdm", "application/vnd.syncml.dm+wbxml" },
{ "bed", "application/vnd.realvnc.bed" },
{ "bh2", "application/vnd.fujitsu.oasysprs" },
{ "bin", "application/octet-stream" },
{ "bmi", "application/vnd.bmi" },
{ "bmp", "image/bmp" },
{ "book", "application/vnd.framemaker" },
{ "box", "application/vnd.previewsystems.box" },
{ "boz", "application/x-bzip2" },
{ "bpk", "application/octet-stream" },
{ "btif", "image/prs.btif" },
{ "bz", "application/x-bzip" },
{ "bz2", "application/x-bzip2" },
{ "c", "text/x-c" },
{ "c11amc", "application/vnd.cluetrust.cartomobile-config" },
{ "c11amz", "application/vnd.cluetrust.cartomobile-config-pkg" },
{ "c4d", "application/vnd.clonk.c4group" },
{ "c4f", "application/vnd.clonk.c4group" },
{ "c4g", "application/vnd.clonk.c4group" },
{ "c4p", "application/vnd.clonk.c4group" },
{ "c4u", "application/vnd.clonk.c4group" },
{ "cab", "application/vnd.ms-cab-compressed" },
{ "car", "application/vnd.curl.car" },
{ "cat", "application/vnd.ms-pki.seccat" },
{ "cc", "text/x-c" },
{ "cct", "application/x-director" },
{ "ccxml", "application/ccxml+xml" },
{ "cdbcmsg", "application/vnd.contact.cmsg" },
{ "cdf", "application/x-netcdf" },
{ "cdkey", "application/vnd.mediastation.cdkey" },
{ "cdmia", "application/cdmi-capability" },
{ "cdmic", "application/cdmi-container" },
{ "cdmid", "application/cdmi-domain" },
{ "cdmio", "application/cdmi-object" },
{ "cdmiq", "application/cdmi-queue" },
{ "cdx", "chemical/x-cdx" },
{ "cdxml", "application/vnd.chemdraw+xml" },
{ "cdy", "application/vnd.cinderella" },
{ "cer", "application/pkix-cert" },
{ "cgm", "image/cgm" },
{ "chat", "application/x-chat" },
{ "chm", "application/vnd.ms-htmlhelp" },
{ "chrt", "application/vnd.kde.kchart" },
{ "cif", "chemical/x-cif" },
{ "cii", "application/vnd.anser-web-certificate-issue-initiation" },
{ "cil", "application/vnd.ms-artgalry" },
{ "cla", "application/vnd.claymore" },
{ "class", "application/java-vm" },
{ "clkk", "application/vnd.crick.clicker.keyboard" },
{ "clkp", "application/vnd.crick.clicker.palette" },
{ "clkt", "application/vnd.crick.clicker.template" },
{ "clkw", "application/vnd.crick.clicker.wordbank" },
{ "clkx", "application/vnd.crick.clicker" },
{ "clp", "application/x-msclip" },
{ "cmc", "application/vnd.cosmocaller" },
{ "cmdf", "chemical/x-cmdf" },
{ "cml", "chemical/x-cml" },
{ "cmp", "application/vnd.yellowriver-custom-menu" },
{ "cmx", "image/x-cmx" },
{ "cod", "application/vnd.rim.cod" },
{ "com", "application/x-msdownload" },
{ "conf", "text/plain" },
{ "cpio", "application/x-cpio" },
{ "cpp", "text/x-c" },
{ "cpt", "application/mac-compactpro" },
{ "crd", "application/x-mscardfile" },
{ "crl", "application/pkix-crl" },
{ "crt", "application/x-x509-ca-cert" },
{ "cryptonote", "application/vnd.rig.cryptonote" },
{ "csh", "application/x-csh" },
{ "csml", "chemical/x-csml" },
{ "csp", "application/vnd.commonspace" },
{ "css", "text/css" },
{ "cst", "application/x-director" },
{ "csv", "text/csv" },
{ "cu", "application/cu-seeme" },
{ "curl", "text/vnd.curl" },
{ "cww", "application/prs.cww" },
{ "cxt", "application/x-director" },
{ "cxx", "text/x-c" },
{ "dae", "model/vnd.collada+xml" },
{ "daf", "application/vnd.mobius.daf" },
{ "dataless", "application/vnd.fdsn.seed" },
{ "davmount", "application/davmount+xml" },
{ "dcr", "application/x-director" },
{ "dcurl", "text/vnd.curl.dcurl" },
{ "dd2", "application/vnd.oma.dd2+xml" },
{ "ddd", "application/vnd.fujixerox.ddd" },
{ "deb", "application/x-debian-package" },
{ "def", "text/plain" },
{ "deploy", "application/octet-stream" },
{ "der", "application/x-x509-ca-cert" },
{ "dfac", "application/vnd.dreamfactory" },
{ "dic", "text/x-c" },
{ "dir", "application/x-director" },
{ "dis", "application/vnd.mobius.dis" },
{ "dist", "application/octet-stream" },
{ "distz", "application/octet-stream" },
{ "djv", "image/vnd.djvu" },
{ "djvu", "image/vnd.djvu" },
{ "dll", "application/x-msdownload" },
{ "dmg", "application/octet-stream" },
{ "dms", "application/octet-stream" },
{ "dna", "application/vnd.dna" },
{ "doc", "application/msword" },
{ "docm", "application/vnd.ms-word.document.macroenabled.12" },
{ "docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" },
{ "dot", "application/msword" },
{ "dotm", "application/vnd.ms-word.template.macroenabled.12" },
{ "dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template" },
{ "dp", "application/vnd.osgi.dp" },
{ "dpg", "application/vnd.dpgraph" },
{ "dra", "audio/vnd.dra" },
{ "dsc", "text/prs.lines.tag" },
{ "dssc", "application/dssc+der" },
{ "dtb", "application/x-dtbook+xml" },
{ "dtd", "application/xml-dtd" },
{ "dts", "audio/vnd.dts" },
{ "dtshd", "audio/vnd.dts.hd" },
{ "dump", "application/octet-stream" },
{ "dvi", "application/x-dvi" },
{ "dwf", "model/vnd.dwf" },
{ "dwg", "image/vnd.dwg" },
{ "dxf", "image/vnd.dxf" },
{ "dxp", "application/vnd.spotfire.dxp" },
{ "dxr", "application/x-director" },
{ "ecelp4800", "audio/vnd.nuera.ecelp4800" },
{ "ecelp7470", "audio/vnd.nuera.ecelp7470" },
{ "ecelp9600", "audio/vnd.nuera.ecelp9600" },
{ "ecma", "application/ecmascript" },
{ "edm", "application/vnd.novadigm.edm" },
{ "edx", "application/vnd.novadigm.edx" },
{ "efif", "application/vnd.picsel" },
{ "ei6", "application/vnd.pg.osasli" },
{ "elc", "application/octet-stream" },
{ "eml", "message/rfc822" },
{ "emma", "application/emma+xml" },
{ "eol", "audio/vnd.digital-winds" },
{ "eot", "application/vnd.ms-fontobject" },
{ "eps", "application/postscript" },
{ "epub", "application/epub+zip" },
{ "es3", "application/vnd.eszigno3+xml" },
{ "esf", "application/vnd.epson.esf" },
{ "et3", "application/vnd.eszigno3+xml" },
{ "etx", "text/x-setext" },
{ "exe", "application/x-msdownload" },
{ "exi", "application/exi" },
{ "ext", "application/vnd.novadigm.ext" },
{ "ez", "application/andrew-inset" },
{ "ez2", "application/vnd.ezpix-album" },
{ "ez3", "application/vnd.ezpix-package" },
{ "f", "text/x-fortran" },
{ "f4v", "video/x-f4v" },
{ "f77", "text/x-fortran" },
{ "f90", "text/x-fortran" },
{ "fbs", "image/vnd.fastbidsheet" },
{ "fcs", "application/vnd.isac.fcs" },
{ "fdf", "application/vnd.fdf" },
{ "fe_launch", "application/vnd.denovo.fcselayout-link" },
{ "fg5", "application/vnd.fujitsu.oasysgp" },
{ "fgd", "application/x-director" },
{ "fh", "image/x-freehand" },
{ "fh4", "image/x-freehand" },
{ "fh5", "image/x-freehand" },
{ "fh7", "image/x-freehand" },
{ "fhc", "image/x-freehand" },
{ "fig", "application/x-xfig" },
{ "fli", "video/x-fli" },
{ "flo", "application/vnd.micrografx.flo" },
{ "flv", "video/x-flv" },
{ "flw", "application/vnd.kde.kivio" },
{ "flx", "text/vnd.fmi.flexstor" },
{ "fly", "text/vnd.fly" },
{ "fm", "application/vnd.framemaker" },
{ "fnc", "application/vnd.frogans.fnc" },
{ "for", "text/x-fortran" },
{ "fpx", "image/vnd.fpx" },
{ "frame", "application/vnd.framemaker" },
{ "fsc", "application/vnd.fsc.weblaunch" },
{ "fst", "image/vnd.fst" },
{ "ftc", "application/vnd.fluxtime.clip" },
{ "fti", "application/vnd.anser-web-funds-transfer-initiation" },
{ "fvt", "video/vnd.fvt" },
{ "fxp", "application/vnd.adobe.fxp" },
{ "fxpl", "application/vnd.adobe.fxp" },
{ "fzs", "application/vnd.fuzzysheet" },
{ "g2w", "application/vnd.geoplan" },
{ "g3", "image/g3fax" },
{ "g3w", "application/vnd.geospace" },
{ "gac", "application/vnd.groove-account" },
{ "gdl", "model/vnd.gdl" },
{ "geo", "application/vnd.dynageo" },
{ "gex", "application/vnd.geometry-explorer" },
{ "ggb", "application/vnd.geogebra.file" },
{ "ggt", "application/vnd.geogebra.tool" },
{ "ghf", "application/vnd.groove-help" },
{ "gif", "image/gif" },
{ "gim", "application/vnd.groove-identity-message" },
{ "gmx", "application/vnd.gmx" },
{ "gnumeric", "application/x-gnumeric" },
{ "gph", "application/vnd.flographit" },
{ "gqf", "application/vnd.grafeq" },
{ "gqs", "application/vnd.grafeq" },
{ "gram", "application/srgs" },
{ "gre", "application/vnd.geometry-explorer" },
{ "grv", "application/vnd.groove-injector" },
{ "grxml", "application/srgs+xml" },
{ "gsf", "application/x-font-ghostscript" },
{ "gtar", "application/x-gtar" },
{ "gtm", "application/vnd.groove-tool-message" },
{ "gtw", "model/vnd.gtw" },
{ "gv", "text/vnd.graphviz" },
{ "gxt", "application/vnd.geonext" },
{ "h", "text/x-c" },
{ "h261", "video/h261" },
{ "h263", "video/h263" },
{ "h264", "video/h264" },
{ "hal", "application/vnd.hal+xml" },
{ "hbci", "application/vnd.hbci" },
{ "hdf", "application/x-hdf" },
{ "hh", "text/x-c" },
{ "hlp", "application/winhlp" },
{ "hpgl", "application/vnd.hp-hpgl" },
{ "hpid", "application/vnd.hp-hpid" },
{ "hps", "application/vnd.hp-hps" },
{ "hqx", "application/mac-binhex40" },
{ "htke", "application/vnd.kenameaapp" },
{ "htm", "text/html" },
{ "html", "text/html" },
{ "hvd", "application/vnd.yamaha.hv-dic" },
{ "hvp", "application/vnd.yamaha.hv-voice" },
{ "hvs", "application/vnd.yamaha.hv-script" },
{ "i2g", "application/vnd.intergeo" },
{ "icc", "application/vnd.iccprofile" },
{ "ice", "x-conference/x-cooltalk" },
{ "icm", "application/vnd.iccprofile" },
{ "ico", "image/x-icon" },
{ "ics", "text/calendar" },
{ "ief", "image/ief" },
{ "ifb", "text/calendar" },
{ "ifm", "application/vnd.shana.informed.formdata" },
{ "iges", "model/iges" },
{ "igl", "application/vnd.igloader" },
{ "igm", "application/vnd.insors.igm" },
{ "igs", "model/iges" },
{ "igx", "application/vnd.micrografx.igx" },
{ "iif", "application/vnd.shana.informed.interchange" },
{ "imp", "application/vnd.accpac.simply.imp" },
{ "ims", "application/vnd.ms-ims" },
{ "in", "text/plain" },
{ "ipfix", "application/ipfix" },
{ "ipk", "application/vnd.shana.informed.package" },
{ "irm", "application/vnd.ibm.rights-management" },
{ "irp", "application/vnd.irepository.package+xml" },
{ "iso", "application/octet-stream" },
{ "itp", "application/vnd.shana.informed.formtemplate" },
{ "ivp", "application/vnd.immervision-ivp" },
{ "ivu", "application/vnd.immervision-ivu" },
{ "jad", "text/vnd.sun.j2me.app-descriptor" },
{ "jam", "application/vnd.jam" },
{ "jar", "application/java-archive" },
{ "java", "text/x-java-source" },
{ "jisp", "application/vnd.jisp" },
{ "jlt", "application/vnd.hp-jlyt" },
{ "jnlp", "application/x-java-jnlp-file" },
{ "joda", "application/vnd.joost.joda-archive" },
{ "jpe", "image/jpeg" },
{ "jpeg", "image/jpeg" },
{ "jpg", "image/jpeg" },
{ "jpgm", "video/jpm" },
{ "jpgv", "video/jpeg" },
{ "jpm", "video/jpm" },
{ "js", "application/javascript" },
{ "json", "application/json" },
{ "kar", "audio/midi" },
{ "karbon", "application/vnd.kde.karbon" },
{ "kfo", "application/vnd.kde.kformula" },
{ "kia", "application/vnd.kidspiration" },
{ "kml", "application/vnd.google-earth.kml+xml" },
{ "kmz", "application/vnd.google-earth.kmz" },
{ "kne", "application/vnd.kinar" },
{ "knp", "application/vnd.kinar" },
{ "kon", "application/vnd.kde.kontour" },
{ "kpr", "application/vnd.kde.kpresenter" },
{ "kpt", "application/vnd.kde.kpresenter" },
{ "ksp", "application/vnd.kde.kspread" },
{ "ktr", "application/vnd.kahootz" },
{ "ktx", "image/ktx" },
{ "ktz", "application/vnd.kahootz" },
{ "kwd", "application/vnd.kde.kword" },
{ "kwt", "application/vnd.kde.kword" },
{ "lasxml", "application/vnd.las.las+xml" },
{ "latex", "application/x-latex" },
{ "lbd", "application/vnd.llamagraphics.life-balance.desktop" },
{ "lbe", "application/vnd.llamagraphics.life-balance.exchange+xml" },
{ "les", "application/vnd.hhe.lesson-player" },
{ "lha", "application/octet-stream" },
{ "link66", "application/vnd.route66.link66+xml" },
{ "list", "text/plain" },
{ "list3820", "application/vnd.ibm.modcap" },
{ "listafp", "application/vnd.ibm.modcap" },
{ "log", "text/plain" },
{ "lostxml", "application/lost+xml" },
{ "lrf", "application/octet-stream" },
{ "lrm", "application/vnd.ms-lrm" },
{ "ltf", "application/vnd.frogans.ltf" },
{ "lvp", "audio/vnd.lucent.voice" },
{ "lwp", "application/vnd.lotus-wordpro" },
{ "lzh", "application/octet-stream" },
{ "m13", "application/x-msmediaview" },
{ "m14", "application/x-msmediaview" },
{ "m1v", "video/mpeg" },
{ "m21", "application/mp21" },
{ "m2a", "audio/mpeg" },
{ "m2v", "video/mpeg" },
{ "m3a", "audio/mpeg" },
{ "m3u", "audio/x-mpegurl" },
{ "m3u8", "application/vnd.apple.mpegurl" },
{ "m4u", "video/vnd.mpegurl" },
{ "m4v", "video/x-m4v" },
{ "ma", "application/mathematica" },
{ "mads", "application/mads+xml" },
{ "mag", "application/vnd.ecowin.chart" },
{ "maker", "application/vnd.framemaker" },
{ "man", "text/troff" },
{ "mathml", "application/mathml+xml" },
{ "mb", "application/mathematica" },
{ "mbk", "application/vnd.mobius.mbk" },
{ "mbox", "application/mbox" },
{ "mc1", "application/vnd.medcalcdata" },
{ "mcd", "application/vnd.mcd" },
{ "mcurl", "text/vnd.curl.mcurl" },
{ "mdb", "application/x-msaccess" },
{ "mdi", "image/vnd.ms-modi" },
{ "me", "text/troff" },
{ "mesh", "model/mesh" },
{ "meta4", "application/metalink4+xml" },
{ "mets", "application/mets+xml" },
{ "mfm", "application/vnd.mfmp" },
{ "mgp", "application/vnd.osgeo.mapguide.package" },
{ "mgz", "application/vnd.proteus.magazine" },
{ "mid", "audio/midi" },
{ "midi", "audio/midi" },
{ "mif", "application/vnd.mif" },
{ "mime", "message/rfc822" },
{ "mj2", "video/mj2" },
{ "mjp2", "video/mj2" },
{ "mlp", "application/vnd.dolby.mlp" },
{ "mmd", "application/vnd.chipnuts.karaoke-mmd" },
{ "mmf", "application/vnd.smaf" },
{ "mmr", "image/vnd.fujixerox.edmics-mmr" },
{ "mny", "application/x-msmoney" },
{ "mobi", "application/x-mobipocket-ebook" },
{ "mods", "application/mods+xml" },
{ "mov", "video/quicktime" },
{ "movie", "video/x-sgi-movie" },
{ "mp2", "audio/mpeg" },
{ "mp21", "application/mp21" },
{ "mp2a", "audio/mpeg" },
{ "mp3", "audio/mpeg" },
{ "mp4", "video/mp4" },
{ "mp4a", "audio/mp4" },
{ "mp4s", "application/mp4" },
{ "mp4v", "video/mp4" },
{ "mpc", "application/vnd.mophun.certificate" },
{ "mpe", "video/mpeg" },
{ "mpeg", "video/mpeg" },
{ "mpg", "video/mpeg" },
{ "mpg4", "video/mp4" },
{ "mpga", "audio/mpeg" },
{ "mpkg", "application/vnd.apple.installer+xml" },
{ "mpm", "application/vnd.blueice.multipass" },
{ "mpn", "application/vnd.mophun.application" },
{ "mpp", "application/vnd.ms-project" },
{ "mpt", "application/vnd.ms-project" },
{ "mpy", "application/vnd.ibm.minipay" },
{ "mqy", "application/vnd.mobius.mqy" },
{ "mrc", "application/marc" },
{ "mrcx", "application/marcxml+xml" },
{ "ms", "text/troff" },
{ "mscml", "application/mediaservercontrol+xml" },
{ "mseed", "application/vnd.fdsn.mseed" },
{ "mseq", "application/vnd.mseq" },
{ "msf", "application/vnd.epson.msf" },
{ "msh", "model/mesh" },
{ "msi", "application/x-msdownload" },
{ "msl", "application/vnd.mobius.msl" },
{ "msty", "application/vnd.muvee.style" },
{ "mts", "model/vnd.mts" },
{ "mus", "application/vnd.musician" },
{ "musicxml", "application/vnd.recordare.musicxml+xml" },
{ "mvb", "application/x-msmediaview" },
{ "mwf", "application/vnd.mfer" },
{ "mxf", "application/mxf" },
{ "mxl", "application/vnd.recordare.musicxml" },
{ "mxml", "application/xv+xml" },
{ "mxs", "application/vnd.triscape.mxs" },
{ "mxu", "video/vnd.mpegurl" },
{ "n3", "text/n3" },
{ "nb", "application/mathematica" },
{ "nbp", "application/vnd.wolfram.player" },
{ "nc", "application/x-netcdf" },
{ "ncx", "application/x-dtbncx+xml" },
{ "n-gage", "application/vnd.nokia.n-gage.symbian.install" },
{ "ngdat", "application/vnd.nokia.n-gage.data" },
{ "nlu", "application/vnd.neurolanguage.nlu" },
{ "nml", "application/vnd.enliven" },
{ "nnd", "application/vnd.noblenet-directory" },
{ "nns", "application/vnd.noblenet-sealer" },
{ "nnw", "application/vnd.noblenet-web" },
{ "npx", "image/vnd.net-fpx" },
{ "nsf", "application/vnd.lotus-notes" },
{ "oa2", "application/vnd.fujitsu.oasys2" },
{ "oa3", "application/vnd.fujitsu.oasys3" },
{ "oas", "application/vnd.fujitsu.oasys" },
{ "obd", "application/x-msbinder" },
{ "oda", "application/oda" },
{ "odb", "application/vnd.oasis.opendocument.database" },
{ "odc", "application/vnd.oasis.opendocument.chart" },
{ "odf", "application/vnd.oasis.opendocument.formula" },
{ "odft", "application/vnd.oasis.opendocument.formula-template" },
{ "odg", "application/vnd.oasis.opendocument.graphics" },
{ "odi", "application/vnd.oasis.opendocument.image" },
{ "odm", "application/vnd.oasis.opendocument.text-master" },
{ "odp", "application/vnd.oasis.opendocument.presentation" },
{ "ods", "application/vnd.oasis.opendocument.spreadsheet" },
{ "odt", "application/vnd.oasis.opendocument.text" },
{ "oga", "audio/ogg" },
{ "ogg", "audio/ogg" },
{ "ogv", "video/ogg" },
{ "ogx", "application/ogg" },
{ "onepkg", "application/onenote" },
{ "onetmp", "application/onenote" },
{ "onetoc", "application/onenote" },
{ "onetoc2", "application/onenote" },
{ "opf", "application/oebps-package+xml" },
{ "oprc", "application/vnd.palm" },
{ "org", "application/vnd.lotus-organizer" },
{ "osf", "application/vnd.yamaha.openscoreformat" },
{ "osfpvg", "application/vnd.yamaha.openscoreformat.osfpvg+xml" },
{ "otc", "application/vnd.oasis.opendocument.chart-template" },
{ "otf", "application/x-font-otf" },
{ "otg", "application/vnd.oasis.opendocument.graphics-template" },
{ "oth", "application/vnd.oasis.opendocument.text-web" },
{ "oti", "application/vnd.oasis.opendocument.image-template" },
{ "otp", "application/vnd.oasis.opendocument.presentation-template" },
{ "ots", "application/vnd.oasis.opendocument.spreadsheet-template" },
{ "ott", "application/vnd.oasis.opendocument.text-template" },
{ "oxt", "application/vnd.openofficeorg.extension" },
{ "p", "text/x-pascal" },
{ "p10", "application/pkcs10" },
{ "p12", "application/x-pkcs12" },
{ "p7b", "application/x-pkcs7-certificates" },
{ "p7c", "application/pkcs7-mime" },
{ "p7m", "application/pkcs7-mime" },
{ "p7r", "application/x-pkcs7-certreqresp" },
{ "p7s", "application/pkcs7-signature" },
{ "p8", "application/pkcs8" },
{ "pas", "text/x-pascal" },
{ "paw", "application/vnd.pawaafile" },
{ "pbd", "application/vnd.powerbuilder6" },
{ "pbm", "image/x-portable-bitmap" },
{ "pcf", "application/x-font-pcf" },
{ "pcl", "application/vnd.hp-pcl" },
{ "pclxl", "application/vnd.hp-pclxl" },
{ "pct", "image/x-pict" },
{ "pcurl", "application/vnd.curl.pcurl" },
{ "pcx", "image/x-pcx" },
{ "pdb", "application/vnd.palm" },
{ "pdf", "application/pdf" },
{ "pfa", "application/x-font-type1" },
{ "pfb", "application/x-font-type1" },
{ "pfm", "application/x-font-type1" },
{ "pfr", "application/font-tdpfr" },
{ "pfx", "application/x-pkcs12" },
{ "pgm", "image/x-portable-graymap" },
{ "pgn", "application/x-chess-pgn" },
{ "pgp", "application/pgp-encrypted" },
{ "pic", "image/x-pict" },
{ "pkg", "application/octet-stream" },
{ "pki", "application/pkixcmp" },
{ "pkipath", "application/pkix-pkipath" },
{ "plb", "application/vnd.3gpp.pic-bw-large" },
{ "plc", "application/vnd.mobius.plc" },
{ "plf", "application/vnd.pocketlearn" },
{ "pls", "application/pls+xml" },
{ "pml", "application/vnd.ctc-posml" },
{ "png", "image/png" },
{ "pnm", "image/x-portable-anymap" },
{ "portpkg", "application/vnd.macports.portpkg" },
{ "pot", "application/vnd.ms-powerpoint" },
{ "potm", "application/vnd.ms-powerpoint.template.macroenabled.12" },
{ "potx", "application/vnd.openxmlformats-officedocument.presentationml.template" },
{ "ppam", "application/vnd.ms-powerpoint.addin.macroenabled.12" },
{ "ppd", "application/vnd.cups-ppd" },
{ "ppm", "image/x-portable-pixmap" },
{ "pps", "application/vnd.ms-powerpoint" },
{ "ppsm", "application/vnd.ms-powerpoint.slideshow.macroenabled.12" },
{ "ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow" },
{ "ppt", "application/vnd.ms-powerpoint" },
{ "pptm", "application/vnd.ms-powerpoint.presentation.macroenabled.12" },
{ "pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation" },
{ "pqa", "application/vnd.palm" },
{ "prc", "application/x-mobipocket-ebook" },
{ "pre", "application/vnd.lotus-freelance" },
{ "prf", "application/pics-rules" },
{ "ps", "application/postscript" },
{ "psb", "application/vnd.3gpp.pic-bw-small" },
{ "psd", "image/vnd.adobe.photoshop" },
{ "psf", "application/x-font-linux-psf" },
{ "pskcxml", "application/pskc+xml" },
{ "ptid", "application/vnd.pvi.ptid1" },
{ "pub", "application/x-mspublisher" },
{ "pvb", "application/vnd.3gpp.pic-bw-var" },
{ "pwn", "application/vnd.3m.post-it-notes" },
{ "pya", "audio/vnd.ms-playready.media.pya" },
{ "pyv", "video/vnd.ms-playready.media.pyv" },
{ "qam", "application/vnd.epson.quickanime" },
{ "qbo", "application/vnd.intu.qbo" },
{ "qfx", "application/vnd.intu.qfx" },
{ "qps", "application/vnd.publishare-delta-tree" },
{ "qt", "video/quicktime" },
{ "qwd", "application/vnd.quark.quarkxpress" },
{ "qwt", "application/vnd.quark.quarkxpress" },
{ "qxb", "application/vnd.quark.quarkxpress" },
{ "qxd", "application/vnd.quark.quarkxpress" },
{ "qxl", "application/vnd.quark.quarkxpress" },
{ "qxt", "application/vnd.quark.quarkxpress" },
{ "ra", "audio/x-pn-realaudio" },
{ "ram", "audio/x-pn-realaudio" },
{ "rar", "application/x-rar-compressed" },
{ "ras", "image/x-cmu-raster" },
{ "rcprofile", "application/vnd.ipunplugged.rcprofile" },
{ "rdf", "application/rdf+xml" },
{ "rdz", "application/vnd.data-vision.rdz" },
{ "rep", "application/vnd.businessobjects" },
{ "res", "application/x-dtbresource+xml" },
{ "rgb", "image/x-rgb" },
{ "rif", "application/reginfo+xml" },
{ "rip", "audio/vnd.rip" },
{ "rl", "application/resource-lists+xml" },
{ "rlc", "image/vnd.fujixerox.edmics-rlc" },
{ "rld", "application/resource-lists-diff+xml" },
{ "rm", "application/vnd.rn-realmedia" },
{ "rmi", "audio/midi" },
{ "rmp", "audio/x-pn-realaudio-plugin" },
{ "rms", "application/vnd.jcp.javame.midlet-rms" },
{ "rnc", "application/relax-ng-compact-syntax" },
{ "roff", "text/troff" },
{ "rp9", "application/vnd.cloanto.rp9" },
{ "rpss", "application/vnd.nokia.radio-presets" },
{ "rpst", "application/vnd.nokia.radio-preset" },
{ "rq", "application/sparql-query" },
{ "rs", "application/rls-services+xml" },
{ "rsd", "application/rsd+xml" },
{ "rss", "application/rss+xml" },
{ "rtf", "application/rtf" },
{ "rtx", "text/richtext" },
{ "s", "text/x-asm" },
{ "saf", "application/vnd.yamaha.smaf-audio" },
{ "sbml", "application/sbml+xml" },
{ "sc", "application/vnd.ibm.secure-container" },
{ "scd", "application/x-msschedule" },
{ "scm", "application/vnd.lotus-screencam" },
{ "scq", "application/scvp-cv-request" },
{ "scs", "application/scvp-cv-response" },
{ "scurl", "text/vnd.curl.scurl" },
{ "sda", "application/vnd.stardivision.draw" },
{ "sdc", "application/vnd.stardivision.calc" },
{ "sdd", "application/vnd.stardivision.impress" },
{ "sdkd", "application/vnd.solent.sdkm+xml" },
{ "sdkm", "application/vnd.solent.sdkm+xml" },
{ "sdp", "application/sdp" },
{ "sdw", "application/vnd.stardivision.writer" },
{ "see", "application/vnd.seemail" },
{ "seed", "application/vnd.fdsn.seed" },
{ "sema", "application/vnd.sema" },
{ "semd", "application/vnd.semd" },
{ "semf", "application/vnd.semf" },
{ "ser", "application/java-serialized-object" },
{ "setpay", "application/set-payment-initiation" },
{ "setreg", "application/set-registration-initiation" },
{ "sfd-hdstx", "application/vnd.hydrostatix.sof-data" },
{ "sfs", "application/vnd.spotfire.sfs" },
{ "sgl", "application/vnd.stardivision.writer-global" },
{ "sgm", "text/sgml" },
{ "sgml", "text/sgml" },
{ "sh", "application/x-sh" },
{ "shar", "application/x-shar" },
{ "shf", "application/shf+xml" },
{ "sig", "application/pgp-signature" },
{ "silo", "model/mesh" },
{ "sis", "application/vnd.symbian.install" },
{ "sisx", "application/vnd.symbian.install" },
{ "sit", "application/x-stuffit" },
{ "sitx", "application/x-stuffitx" },
{ "skd", "application/vnd.koan" },
{ "skm", "application/vnd.koan" },
{ "skp", "application/vnd.koan" },
{ "skt", "application/vnd.koan" },
{ "sldm", "application/vnd.ms-powerpoint.slide.macroenabled.12" },
{ "sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide" },
{ "slt", "application/vnd.epson.salt" },
{ "sm", "application/vnd.stepmania.stepchart" },
{ "smf", "application/vnd.stardivision.math" },
{ "smi", "application/smil+xml" },
{ "smil", "application/smil+xml" },
{ "snd", "audio/basic" },
{ "snf", "application/x-font-snf" },
{ "so", "application/octet-stream" },
{ "spc", "application/x-pkcs7-certificates" },
{ "spf", "application/vnd.yamaha.smaf-phrase" },
{ "spl", "application/x-futuresplash" },
{ "spot", "text/vnd.in3d.spot" },
{ "spp", "application/scvp-vp-response" },
{ "spq", "application/scvp-vp-request" },
{ "spx", "audio/ogg" },
{ "src", "application/x-wais-source" },
{ "sru", "application/sru+xml" },
{ "srx", "application/sparql-results+xml" },
{ "sse", "application/vnd.kodak-descriptor" },
{ "ssf", "application/vnd.epson.ssf" },
{ "ssml", "application/ssml+xml" },
{ "st", "application/vnd.sailingtracker.track" },
{ "stc", "application/vnd.sun.xml.calc.template" },
{ "std", "application/vnd.sun.xml.draw.template" },
{ "stf", "application/vnd.wt.stf" },
{ "sti", "application/vnd.sun.xml.impress.template" },
{ "stk", "application/hyperstudio" },
{ "stl", "application/vnd.ms-pki.stl" },
{ "str", "application/vnd.pg.format" },
{ "stw", "application/vnd.sun.xml.writer.template" },
{ "sub", "image/vnd.dvb.subtitle" },
{ "sus", "application/vnd.sus-calendar" },
{ "susp", "application/vnd.sus-calendar" },
{ "sv4cpio", "application/x-sv4cpio" },
{ "sv4crc", "application/x-sv4crc" },
{ "svc", "application/vnd.dvb.service" },
{ "svd", "application/vnd.svd" },
{ "svg", "image/svg+xml" },
{ "svgz", "image/svg+xml" },
{ "swa", "application/x-director" },
{ "swf", "application/x-shockwave-flash" },
{ "swi", "application/vnd.aristanetworks.swi" },
{ "sxc", "application/vnd.sun.xml.calc" },
{ "sxd", "application/vnd.sun.xml.draw" },
{ "sxg", "application/vnd.sun.xml.writer.global" },
{ "sxi", "application/vnd.sun.xml.impress" },
{ "sxm", "application/vnd.sun.xml.math" },
{ "sxw", "application/vnd.sun.xml.writer" },
{ "t", "text/troff" },
{ "tao", "application/vnd.tao.intent-module-archive" },
{ "tar", "application/x-tar" },
{ "tcap", "application/vnd.3gpp2.tcap" },
{ "tcl", "application/x-tcl" },
{ "teacher", "application/vnd.smart.teacher" },
{ "tei", "application/tei+xml" },
{ "teicorpus", "application/tei+xml" },
{ "tex", "application/x-tex" },
{ "texi", "application/x-texinfo" },
{ "texinfo", "application/x-texinfo" },
{ "text", "text/plain" },
{ "tfi", "application/thraud+xml" },
{ "tfm", "application/x-tex-tfm" },
{ "thmx", "application/vnd.ms-officetheme" },
{ "tif", "image/tiff" },
{ "tiff", "image/tiff" },
{ "tmo", "application/vnd.tmobile-livetv" },
{ "torrent", "application/x-bittorrent" },
{ "tpl", "application/vnd.groove-tool-template" },
{ "tpt", "application/vnd.trid.tpt" },
{ "tr", "text/troff" },
{ "tra", "application/vnd.trueapp" },
{ "trm", "application/x-msterminal" },
{ "tsd", "application/timestamped-data" },
{ "tsv", "text/tab-separated-values" },
{ "ttc", "application/x-font-ttf" },
{ "ttf", "application/x-font-ttf" },
{ "ttl", "text/turtle" },
{ "twd", "application/vnd.simtech-mindmapper" },
{ "twds", "application/vnd.simtech-mindmapper" },
{ "txd", "application/vnd.genomatix.tuxedo" },
{ "txf", "application/vnd.mobius.txf" },
{ "txt", "text/plain" },
{ "u32", "application/x-authorware-bin" },
{ "udeb", "application/x-debian-package" },
{ "ufd", "application/vnd.ufdl" },
{ "ufdl", "application/vnd.ufdl" },
{ "umj", "application/vnd.umajin" },
{ "unityweb", "application/vnd.unity" },
{ "uoml", "application/vnd.uoml+xml" },
{ "uri", "text/uri-list" },
{ "uris", "text/uri-list" },
{ "urls", "text/uri-list" },
{ "ustar", "application/x-ustar" },
{ "utz", "application/vnd.uiq.theme" },
{ "uu", "text/x-uuencode" },
{ "uva", "audio/vnd.dece.audio" },
{ "uvd", "application/vnd.dece.data" },
{ "uvf", "application/vnd.dece.data" },
{ "uvg", "image/vnd.dece.graphic" },
{ "uvh", "video/vnd.dece.hd" },
{ "uvi", "image/vnd.dece.graphic" },
{ "uvm", "video/vnd.dece.mobile" },
{ "uvp", "video/vnd.dece.pd" },
{ "uvs", "video/vnd.dece.sd" },
{ "uvt", "application/vnd.dece.ttml+xml" },
{ "uvu", "video/vnd.uvvu.mp4" },
{ "uvv", "video/vnd.dece.video" },
{ "uvva", "audio/vnd.dece.audio" },
{ "uvvd", "application/vnd.dece.data" },
{ "uvvf", "application/vnd.dece.data" },
{ "uvvg", "image/vnd.dece.graphic" },
{ "uvvh", "video/vnd.dece.hd" },
{ "uvvi", "image/vnd.dece.graphic" },
{ "uvvm", "video/vnd.dece.mobile" },
{ "uvvp", "video/vnd.dece.pd" },
{ "uvvs", "video/vnd.dece.sd" },
{ "uvvt", "application/vnd.dece.ttml+xml" },
{ "uvvu", "video/vnd.uvvu.mp4" },
{ "uvvv", "video/vnd.dece.video" },
{ "uvvx", "application/vnd.dece.unspecified" },
{ "uvx", "application/vnd.dece.unspecified" },
{ "vcd", "application/x-cdlink" },
{ "vcf", "text/x-vcard" },
{ "vcg", "application/vnd.groove-vcard" },
{ "vcs", "text/x-vcalendar" },
{ "vcx", "application/vnd.vcx" },
{ "vis", "application/vnd.visionary" },
{ "viv", "video/vnd.vivo" },
{ "vor", "application/vnd.stardivision.writer" },
{ "vox", "application/x-authorware-bin" },
{ "vrml", "model/vrml" },
{ "vsd", "application/vnd.visio" },
{ "vsf", "application/vnd.vsf" },
{ "vss", "application/vnd.visio" },
{ "vst", "application/vnd.visio" },
{ "vsw", "application/vnd.visio" },
{ "vtu", "model/vnd.vtu" },
{ "vxml", "application/voicexml+xml" },
{ "w3d", "application/x-director" },
{ "wad", "application/x-doom" },
{ "wav", "audio/x-wav" },
{ "wax", "audio/x-ms-wax" },
{ "wbmp", "image/vnd.wap.wbmp" },
{ "wbs", "application/vnd.criticaltools.wbs+xml" },
{ "wbxml", "application/vnd.wap.wbxml" },
{ "wcm", "application/vnd.ms-works" },
{ "wdb", "application/vnd.ms-works" },
{ "weba", "audio/webm" },
{ "webm", "video/webm" },
{ "webp", "image/webp" },
{ "wg", "application/vnd.pmi.widget" },
{ "wgt", "application/widget" },
{ "wks", "application/vnd.ms-works" },
{ "wm", "video/x-ms-wm" },
{ "wma", "audio/x-ms-wma" },
{ "wmd", "application/x-ms-wmd" },
{ "wmf", "application/x-msmetafile" },
{ "wml", "text/vnd.wap.wml" },
{ "wmlc", "application/vnd.wap.wmlc" },
{ "wmls", "text/vnd.wap.wmlscript" },
{ "wmlsc", "application/vnd.wap.wmlscriptc" },
{ "wmv", "video/x-ms-wmv" },
{ "wmx", "video/x-ms-wmx" },
{ "wmz", "application/x-ms-wmz" },
{ "woff", "application/x-font-woff" },
{ "wpd", "application/vnd.wordperfect" },
{ "wpl", "application/vnd.ms-wpl" },
{ "wps", "application/vnd.ms-works" },
{ "wqd", "application/vnd.wqd" },
{ "wri", "application/x-mswrite" },
{ "wrl", "model/vrml" },
{ "wsdl", "application/wsdl+xml" },
{ "wspolicy", "application/wspolicy+xml" },
{ "wtb", "application/vnd.webturbo" },
{ "wvx", "video/x-ms-wvx" },
{ "x32", "application/x-authorware-bin" },
{ "x3d", "application/vnd.hzn-3d-crossword" },
{ "xap", "application/x-silverlight-app" },
{ "xar", "application/vnd.xara" },
{ "xbap", "application/x-ms-xbap" },
{ "xbd", "application/vnd.fujixerox.docuworks.binder" },
{ "xbm", "image/x-xbitmap" },
{ "xdf", "application/xcap-diff+xml" },
{ "xdm", "application/vnd.syncml.dm+xml" },
{ "xdp", "application/vnd.adobe.xdp+xml" },
{ "xdssc", "application/dssc+xml" },
{ "xdw", "application/vnd.fujixerox.docuworks" },
{ "xenc", "application/xenc+xml" },
{ "xer", "application/patch-ops-error+xml" },
{ "xfdf", "application/vnd.adobe.xfdf" },
{ "xfdl", "application/vnd.xfdl" },
{ "xht", "application/xhtml+xml" },
{ "xhtml", "application/xhtml+xml" },
{ "xhvml", "application/xv+xml" },
{ "xif", "image/vnd.xiff" },
{ "xla", "application/vnd.ms-excel" },
{ "xlam", "application/vnd.ms-excel.addin.macroenabled.12" },
{ "xlc", "application/vnd.ms-excel" },
{ "xlm", "application/vnd.ms-excel" },
{ "xls", "application/vnd.ms-excel" },
{ "xlsb", "application/vnd.ms-excel.sheet.binary.macroenabled.12" },
{ "xlsm", "application/vnd.ms-excel.sheet.macroenabled.12" },
{ "xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" },
{ "xlt", "application/vnd.ms-excel" },
{ "xltm", "application/vnd.ms-excel.template.macroenabled.12" },
{ "xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template" },
{ "xlw", "application/vnd.ms-excel" },
{ "xml", "application/xml" },
{ "xo", "application/vnd.olpc-sugar" },
{ "xop", "application/xop+xml" },
{ "xpi", "application/x-xpinstall" },
{ "xpm", "image/x-xpixmap" },
{ "xpr", "application/vnd.is-xpr" },
{ "xps", "application/vnd.ms-xpsdocument" },
{ "xpw", "application/vnd.intercon.formnet" },
{ "xpx", "application/vnd.intercon.formnet" },
{ "xsl", "application/xml" },
{ "xslt", "application/xslt+xml" },
{ "xsm", "application/vnd.syncml+xml" },
{ "xspf", "application/xspf+xml" },
{ "xul", "application/vnd.mozilla.xul+xml" },
{ "xvm", "application/xv+xml" },
{ "xvml", "application/xv+xml" },
{ "xwd", "image/x-xwindowdump" },
{ "xyz", "chemical/x-xyz" },
{ "yang", "application/yang" },
{ "yin", "application/yin+xml" },
{ "zaz", "application/vnd.zzazz.deck+xml" },
{ "zip", "application/zip" },
{ "zir", "application/vnd.zul" },
{ "zirz", "application/vnd.zul" },
{ "zmm", "application/vnd.handheld-entertainment+xml" },
};
}
}
| |
// 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 Microsoft.Win32.SafeHandles;
using System;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Security.AccessControl;
using System.Security.Principal;
namespace Thrift.Transport.Server
{
// ReSharper disable once InconsistentNaming
public class TNamedPipeServerTransport : TServerTransport
{
/// <summary>
/// This is the address of the Pipe on the localhost.
/// </summary>
private readonly string _pipeAddress;
private bool _asyncMode = true;
private volatile bool _isPending = true;
private NamedPipeServerStream _stream = null;
public TNamedPipeServerTransport(string pipeAddress, TConfiguration config)
: base(config)
{
_pipeAddress = pipeAddress;
}
public override void Listen()
{
// nothing to do here
}
public override void Close()
{
if (_stream != null)
{
try
{
if (_stream.IsConnected)
_stream.Disconnect();
_stream.Dispose();
}
finally
{
_stream = null;
_isPending = false;
}
}
}
public override bool IsClientPending()
{
return _isPending;
}
private void EnsurePipeInstance()
{
if (_stream == null)
{
const PipeDirection direction = PipeDirection.InOut;
const int maxconn = NamedPipeServerStream.MaxAllowedServerInstances;
const PipeTransmissionMode mode = PipeTransmissionMode.Byte;
const int inbuf = 4096;
const int outbuf = 4096;
var options = _asyncMode ? PipeOptions.Asynchronous : PipeOptions.None;
// TODO: "CreatePipeNative" ist only a workaround, and there are have basically two possible outcomes:
// - once NamedPipeServerStream() gets a CTOR that supports pipesec, remove CreatePipeNative()
// - if 31190 gets resolved before, use _stream.SetAccessControl(pipesec) instead of CreatePipeNative()
// EITHER WAY,
// - if CreatePipeNative() finally gets removed, also remove "allow unsafe code" from the project settings
try
{
var handle = CreatePipeNative(_pipeAddress, inbuf, outbuf);
if ((handle != null) && (!handle.IsInvalid))
{
_stream = new NamedPipeServerStream(PipeDirection.InOut, _asyncMode, false, handle);
handle = null; // we don't own it any longer
}
else
{
handle?.Dispose();
_stream = new NamedPipeServerStream(_pipeAddress, direction, maxconn, mode, options, inbuf, outbuf/*, pipesec*/);
}
}
catch (NotImplementedException) // Mono still does not support async, fallback to sync
{
if (_asyncMode)
{
options &= (~PipeOptions.Asynchronous);
_stream = new NamedPipeServerStream(_pipeAddress, direction, maxconn, mode, options, inbuf, outbuf);
_asyncMode = false;
}
else
{
throw;
}
}
}
}
#region CreatePipeNative workaround
[StructLayout(LayoutKind.Sequential)]
internal class SECURITY_ATTRIBUTES
{
internal int nLength = 0;
internal IntPtr lpSecurityDescriptor = IntPtr.Zero;
internal int bInheritHandle = 0;
}
private const string Kernel32 = "kernel32.dll";
[DllImport(Kernel32, SetLastError = true)]
internal static extern IntPtr CreateNamedPipe(
string lpName, uint dwOpenMode, uint dwPipeMode,
uint nMaxInstances, uint nOutBufferSize, uint nInBufferSize, uint nDefaultTimeOut,
SECURITY_ATTRIBUTES pipeSecurityDescriptor
);
// Workaround: create the pipe via API call
// we have to do it this way, since NamedPipeServerStream() for netstd still lacks a few CTORs
// and _stream.SetAccessControl(pipesec); only keeps throwing ACCESS_DENIED errors at us
// References:
// - https://github.com/dotnet/corefx/issues/30170 (closed, continued in 31190)
// - https://github.com/dotnet/corefx/issues/31190 System.IO.Pipes.AccessControl package does not work
// - https://github.com/dotnet/corefx/issues/24040 NamedPipeServerStream: Provide support for WRITE_DAC
// - https://github.com/dotnet/corefx/issues/34400 Have a mechanism for lower privileged user to connect to a privileged user's pipe
private SafePipeHandle CreatePipeNative(string name, int inbuf, int outbuf)
{
if (Environment.OSVersion.Platform != PlatformID.Win32NT)
return null; // Windows only
var pinningHandle = new GCHandle();
try
{
// owner gets full access, everyone else read/write
var pipesec = new PipeSecurity();
using (var currentIdentity = WindowsIdentity.GetCurrent())
{
var sidOwner = currentIdentity.Owner;
var sidWorld = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
pipesec.SetOwner(sidOwner);
pipesec.AddAccessRule(new PipeAccessRule(sidOwner, PipeAccessRights.FullControl, AccessControlType.Allow));
pipesec.AddAccessRule(new PipeAccessRule(sidWorld, PipeAccessRights.ReadWrite, AccessControlType.Allow));
}
// create a security descriptor and assign it to the security attribs
var secAttrs = new SECURITY_ATTRIBUTES();
byte[] sdBytes = pipesec.GetSecurityDescriptorBinaryForm();
pinningHandle = GCHandle.Alloc(sdBytes, GCHandleType.Pinned);
unsafe {
fixed (byte* pSD = sdBytes) {
secAttrs.lpSecurityDescriptor = (IntPtr)pSD;
}
}
// a bunch of constants we will need shortly
const int PIPE_ACCESS_DUPLEX = 0x00000003;
const int FILE_FLAG_OVERLAPPED = 0x40000000;
const int WRITE_DAC = 0x00040000;
const int PIPE_TYPE_BYTE = 0x00000000;
const int PIPE_READMODE_BYTE = 0x00000000;
const int PIPE_UNLIMITED_INSTANCES = 255;
// create the pipe via API call
var rawHandle = CreateNamedPipe(
@"\\.\pipe\" + name,
PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | WRITE_DAC,
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
PIPE_UNLIMITED_INSTANCES, (uint)inbuf, (uint)outbuf,
5 * 1000,
secAttrs
);
// make a SafePipeHandle() from it
var handle = new SafePipeHandle(rawHandle, true);
if (handle.IsInvalid)
throw new Win32Exception(Marshal.GetLastWin32Error());
// return it (to be packaged)
return handle;
}
finally
{
if (pinningHandle.IsAllocated)
pinningHandle.Free();
}
}
#endregion
protected override async ValueTask<TTransport> AcceptImplementationAsync(CancellationToken cancellationToken)
{
try
{
EnsurePipeInstance();
await _stream.WaitForConnectionAsync(cancellationToken);
var trans = new ServerTransport(_stream, Configuration);
_stream = null; // pass ownership to ServerTransport
//_isPending = false;
return trans;
}
catch (TTransportException)
{
Close();
throw;
}
catch (Exception e)
{
Close();
throw new TTransportException(TTransportException.ExceptionType.NotOpen, e.Message);
}
}
private class ServerTransport : TEndpointTransport
{
private readonly NamedPipeServerStream PipeStream;
public ServerTransport(NamedPipeServerStream stream, TConfiguration config)
: base(config)
{
PipeStream = stream;
}
public override bool IsOpen => PipeStream != null && PipeStream.IsConnected;
public override async Task OpenAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
}
public override void Close()
{
PipeStream?.Dispose();
}
public override async ValueTask<int> ReadAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken)
{
if (PipeStream == null)
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen);
}
CheckReadBytesAvailable(length);
var numBytes = await PipeStream.ReadAsync(buffer, offset, length, cancellationToken);
CountConsumedMessageBytes(numBytes);
return numBytes;
}
public override async Task WriteAsync(byte[] buffer, int offset, int length, CancellationToken cancellationToken)
{
if (PipeStream == null)
{
throw new TTransportException(TTransportException.ExceptionType.NotOpen);
}
// if necessary, send the data in chunks
// there's a system limit around 0x10000 bytes that we hit otherwise
// MSDN: "Pipe write operations across a network are limited to 65,535 bytes per write. For more information regarding pipes, see the Remarks section."
var nBytes = Math.Min(15 * 4096, length); // 16 would exceed the limit
while (nBytes > 0)
{
await PipeStream.WriteAsync(buffer, offset, nBytes, cancellationToken);
offset += nBytes;
length -= nBytes;
nBytes = Math.Min(nBytes, length);
}
}
public override async Task FlushAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
await Task.FromCanceled(cancellationToken);
}
ResetConsumedMessageSize();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
PipeStream?.Dispose();
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Diagnostics;
using Microsoft.Win32;
using System.Globalization;
using System.Security;
using System.Xml.Schema;
using System.Xml.XmlConfiguration;
using System.Runtime.Versioning;
namespace System.Xml
{
// XmlReaderSettings class specifies basic features of an XmlReader.
public sealed class XmlReaderSettings
{
//
// Fields
//
private bool _useAsync;
// Nametable
private XmlNameTable _nameTable;
// XmlResolver
private XmlResolver _xmlResolver = null;
// Text settings
private int _lineNumberOffset;
private int _linePositionOffset;
// Conformance settings
private ConformanceLevel _conformanceLevel;
private bool _checkCharacters;
private long _maxCharactersInDocument;
private long _maxCharactersFromEntities;
// Filtering settings
private bool _ignoreWhitespace;
private bool _ignorePIs;
private bool _ignoreComments;
// security settings
private DtdProcessing _dtdProcessing;
//Validation settings
private ValidationType _validationType;
private XmlSchemaValidationFlags _validationFlags;
private XmlSchemaSet _schemas;
private ValidationEventHandler _valEventHandler;
// other settings
private bool _closeInput;
// read-only flag
private bool _isReadOnly;
//
// Constructor
//
public XmlReaderSettings()
{
Initialize();
}
// introduced for supporting design-time loading of phone assemblies
[Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public XmlReaderSettings(XmlResolver resolver)
{
Initialize(resolver);
}
//
// Properties
//
public bool Async
{
get
{
return _useAsync;
}
set
{
CheckReadOnly("Async");
_useAsync = value;
}
}
// Nametable
public XmlNameTable NameTable
{
get
{
return _nameTable;
}
set
{
CheckReadOnly("NameTable");
_nameTable = value;
}
}
// XmlResolver
internal bool IsXmlResolverSet
{
get;
set; // keep set internal as we need to call it from the schema validation code
}
public XmlResolver XmlResolver
{
set
{
CheckReadOnly("XmlResolver");
_xmlResolver = value;
IsXmlResolverSet = true;
}
}
internal XmlResolver GetXmlResolver()
{
return _xmlResolver;
}
//This is used by get XmlResolver in Xsd.
//Check if the config set to prohibit default resovler
//notice we must keep GetXmlResolver() to avoid dead lock when init System.Config.ConfigurationManager
internal XmlResolver GetXmlResolver_CheckConfig()
{
if (LocalAppContextSwitches.ProhibitDefaultUrlResolver && !IsXmlResolverSet)
return null;
else
return _xmlResolver;
}
// Text settings
public int LineNumberOffset
{
get
{
return _lineNumberOffset;
}
set
{
CheckReadOnly("LineNumberOffset");
_lineNumberOffset = value;
}
}
public int LinePositionOffset
{
get
{
return _linePositionOffset;
}
set
{
CheckReadOnly("LinePositionOffset");
_linePositionOffset = value;
}
}
// Conformance settings
public ConformanceLevel ConformanceLevel
{
get
{
return _conformanceLevel;
}
set
{
CheckReadOnly("ConformanceLevel");
if ((uint)value > (uint)ConformanceLevel.Document)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_conformanceLevel = value;
}
}
public bool CheckCharacters
{
get
{
return _checkCharacters;
}
set
{
CheckReadOnly("CheckCharacters");
_checkCharacters = value;
}
}
public long MaxCharactersInDocument
{
get
{
return _maxCharactersInDocument;
}
set
{
CheckReadOnly("MaxCharactersInDocument");
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_maxCharactersInDocument = value;
}
}
public long MaxCharactersFromEntities
{
get
{
return _maxCharactersFromEntities;
}
set
{
CheckReadOnly("MaxCharactersFromEntities");
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_maxCharactersFromEntities = value;
}
}
// Filtering settings
public bool IgnoreWhitespace
{
get
{
return _ignoreWhitespace;
}
set
{
CheckReadOnly("IgnoreWhitespace");
_ignoreWhitespace = value;
}
}
public bool IgnoreProcessingInstructions
{
get
{
return _ignorePIs;
}
set
{
CheckReadOnly("IgnoreProcessingInstructions");
_ignorePIs = value;
}
}
public bool IgnoreComments
{
get
{
return _ignoreComments;
}
set
{
CheckReadOnly("IgnoreComments");
_ignoreComments = value;
}
}
[Obsolete("Use XmlReaderSettings.DtdProcessing property instead.")]
public bool ProhibitDtd
{
get
{
return _dtdProcessing == DtdProcessing.Prohibit;
}
set
{
CheckReadOnly("ProhibitDtd");
_dtdProcessing = value ? DtdProcessing.Prohibit : DtdProcessing.Parse;
}
}
public DtdProcessing DtdProcessing
{
get
{
return _dtdProcessing;
}
set
{
CheckReadOnly("DtdProcessing");
if ((uint)value > (uint)DtdProcessing.Parse)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_dtdProcessing = value;
}
}
public bool CloseInput
{
get
{
return _closeInput;
}
set
{
CheckReadOnly("CloseInput");
_closeInput = value;
}
}
public ValidationType ValidationType
{
get
{
return _validationType;
}
set
{
CheckReadOnly("ValidationType");
if ((uint)value > (uint)ValidationType.Schema)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_validationType = value;
}
}
public XmlSchemaValidationFlags ValidationFlags
{
get
{
return _validationFlags;
}
set
{
CheckReadOnly("ValidationFlags");
if ((uint)value > (uint)(XmlSchemaValidationFlags.ProcessInlineSchema | XmlSchemaValidationFlags.ProcessSchemaLocation |
XmlSchemaValidationFlags.ReportValidationWarnings | XmlSchemaValidationFlags.ProcessIdentityConstraints |
XmlSchemaValidationFlags.AllowXmlAttributes))
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_validationFlags = value;
}
}
public XmlSchemaSet Schemas
{
get
{
if (_schemas == null)
{
_schemas = new XmlSchemaSet();
}
return _schemas;
}
set
{
CheckReadOnly("Schemas");
_schemas = value;
}
}
public event ValidationEventHandler ValidationEventHandler
{
add
{
CheckReadOnly("ValidationEventHandler");
_valEventHandler += value;
}
remove
{
CheckReadOnly("ValidationEventHandler");
_valEventHandler -= value;
}
}
//
// Public methods
//
public void Reset()
{
CheckReadOnly("Reset");
Initialize();
}
public XmlReaderSettings Clone()
{
XmlReaderSettings clonedSettings = this.MemberwiseClone() as XmlReaderSettings;
clonedSettings.ReadOnly = false;
return clonedSettings;
}
//
// Internal methods
//
internal ValidationEventHandler GetEventHandler()
{
return _valEventHandler;
}
internal XmlReader CreateReader(String inputUri, XmlParserContext inputContext)
{
if (inputUri == null)
{
throw new ArgumentNullException(nameof(inputUri));
}
if (inputUri.Length == 0)
{
throw new ArgumentException(SR.XmlConvert_BadUri, nameof(inputUri));
}
// resolve and open the url
XmlResolver tmpResolver = this.GetXmlResolver();
if (tmpResolver == null)
{
tmpResolver = CreateDefaultResolver();
}
// create text XML reader
XmlReader reader = new XmlTextReaderImpl(inputUri, this, inputContext, tmpResolver);
// wrap with validating reader
if (this.ValidationType != ValidationType.None)
{
reader = AddValidation(reader);
}
if (_useAsync)
{
reader = XmlAsyncCheckReader.CreateAsyncCheckWrapper(reader);
}
return reader;
}
internal XmlReader CreateReader(Stream input, Uri baseUri, string baseUriString, XmlParserContext inputContext)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
if (baseUriString == null)
{
if (baseUri == null)
{
baseUriString = string.Empty;
}
else
{
baseUriString = baseUri.ToString();
}
}
// create text XML reader
XmlReader reader = new XmlTextReaderImpl(input, null, 0, this, baseUri, baseUriString, inputContext, _closeInput);
// wrap with validating reader
if (this.ValidationType != ValidationType.None)
{
reader = AddValidation(reader);
}
if (_useAsync)
{
reader = XmlAsyncCheckReader.CreateAsyncCheckWrapper(reader);
}
return reader;
}
internal XmlReader CreateReader(TextReader input, string baseUriString, XmlParserContext inputContext)
{
if (input == null)
{
throw new ArgumentNullException(nameof(input));
}
if (baseUriString == null)
{
baseUriString = string.Empty;
}
// create xml text reader
XmlReader reader = new XmlTextReaderImpl(input, this, baseUriString, inputContext);
// wrap with validating reader
if (this.ValidationType != ValidationType.None)
{
reader = AddValidation(reader);
}
if (_useAsync)
{
reader = XmlAsyncCheckReader.CreateAsyncCheckWrapper(reader);
}
return reader;
}
internal XmlReader CreateReader(XmlReader reader)
{
if (reader == null)
{
throw new ArgumentNullException(nameof(reader));
}
return AddValidationAndConformanceWrapper(reader);
}
internal bool ReadOnly
{
get
{
return _isReadOnly;
}
set
{
_isReadOnly = value;
}
}
private void CheckReadOnly(string propertyName)
{
if (_isReadOnly)
{
throw new XmlException(SR.Xml_ReadOnlyProperty, this.GetType().Name + '.' + propertyName);
}
}
//
// Private methods
//
private void Initialize()
{
Initialize(null);
}
private void Initialize(XmlResolver resolver)
{
_nameTable = null;
if (!EnableLegacyXmlSettings())
{
_xmlResolver = resolver;
// limit the entity resolving to 10 million character. the caller can still
// override it to any other value or set it to zero for unlimiting it
_maxCharactersFromEntities = (long)1e7;
}
else
{
_xmlResolver = (resolver == null ? CreateDefaultResolver() : resolver);
_maxCharactersFromEntities = 0;
}
_lineNumberOffset = 0;
_linePositionOffset = 0;
_checkCharacters = true;
_conformanceLevel = ConformanceLevel.Document;
_ignoreWhitespace = false;
_ignorePIs = false;
_ignoreComments = false;
_dtdProcessing = DtdProcessing.Prohibit;
_closeInput = false;
_maxCharactersInDocument = 0;
_schemas = null;
_validationType = ValidationType.None;
_validationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints;
_validationFlags |= XmlSchemaValidationFlags.AllowXmlAttributes;
_useAsync = false;
_isReadOnly = false;
IsXmlResolverSet = false;
}
private static XmlResolver CreateDefaultResolver()
{
return new XmlSystemPathResolver();
}
internal XmlReader AddValidation(XmlReader reader)
{
if (_validationType == ValidationType.Schema)
{
XmlResolver resolver = GetXmlResolver_CheckConfig();
if (resolver == null &&
!this.IsXmlResolverSet &&
!EnableLegacyXmlSettings())
{
resolver = new XmlUrlResolver();
}
reader = new XsdValidatingReader(reader, resolver, this);
}
else if (_validationType == ValidationType.DTD)
{
reader = CreateDtdValidatingReader(reader);
}
return reader;
}
private XmlReader AddValidationAndConformanceWrapper(XmlReader reader)
{
// wrap with DTD validating reader
if (_validationType == ValidationType.DTD)
{
reader = CreateDtdValidatingReader(reader);
}
// add conformance checking (must go after DTD validation because XmlValidatingReader works only on XmlTextReader),
// but before XSD validation because of typed value access
reader = AddConformanceWrapper(reader);
if (_validationType == ValidationType.Schema)
{
reader = new XsdValidatingReader(reader, GetXmlResolver_CheckConfig(), this);
}
return reader;
}
private XmlValidatingReaderImpl CreateDtdValidatingReader(XmlReader baseReader)
{
return new XmlValidatingReaderImpl(baseReader, this.GetEventHandler(), (this.ValidationFlags & XmlSchemaValidationFlags.ProcessIdentityConstraints) != 0);
}
internal XmlReader AddConformanceWrapper(XmlReader baseReader)
{
XmlReaderSettings baseReaderSettings = baseReader.Settings;
bool checkChars = false;
bool noWhitespace = false;
bool noComments = false;
bool noPIs = false;
DtdProcessing dtdProc = (DtdProcessing)(-1);
bool needWrap = false;
if (baseReaderSettings == null)
{
#pragma warning disable 618
if (_conformanceLevel != ConformanceLevel.Auto && _conformanceLevel != XmlReader.GetV1ConformanceLevel(baseReader))
{
throw new InvalidOperationException(SR.Format(SR.Xml_IncompatibleConformanceLevel, _conformanceLevel.ToString()));
}
// get the V1 XmlTextReader ref
XmlTextReader v1XmlTextReader = baseReader as XmlTextReader;
if (v1XmlTextReader == null)
{
XmlValidatingReader vr = baseReader as XmlValidatingReader;
if (vr != null)
{
v1XmlTextReader = (XmlTextReader)vr.Reader;
}
}
// assume the V1 readers already do all conformance checking;
// wrap only if IgnoreWhitespace, IgnoreComments, IgnoreProcessingInstructions or ProhibitDtd is true;
if (_ignoreWhitespace)
{
WhitespaceHandling wh = WhitespaceHandling.All;
// special-case our V1 readers to see if whey already filter whitespaces
if (v1XmlTextReader != null)
{
wh = v1XmlTextReader.WhitespaceHandling;
}
if (wh == WhitespaceHandling.All)
{
noWhitespace = true;
needWrap = true;
}
}
if (_ignoreComments)
{
noComments = true;
needWrap = true;
}
if (_ignorePIs)
{
noPIs = true;
needWrap = true;
}
// DTD processing
DtdProcessing baseDtdProcessing = DtdProcessing.Parse;
if (v1XmlTextReader != null)
{
baseDtdProcessing = v1XmlTextReader.DtdProcessing;
}
if ((_dtdProcessing == DtdProcessing.Prohibit && baseDtdProcessing != DtdProcessing.Prohibit) ||
(_dtdProcessing == DtdProcessing.Ignore && baseDtdProcessing == DtdProcessing.Parse))
{
dtdProc = _dtdProcessing;
needWrap = true;
}
#pragma warning restore 618
}
else
{
if (_conformanceLevel != baseReaderSettings.ConformanceLevel && _conformanceLevel != ConformanceLevel.Auto)
{
throw new InvalidOperationException(SR.Format(SR.Xml_IncompatibleConformanceLevel, _conformanceLevel.ToString()));
}
if (_checkCharacters && !baseReaderSettings.CheckCharacters)
{
checkChars = true;
needWrap = true;
}
if (_ignoreWhitespace && !baseReaderSettings.IgnoreWhitespace)
{
noWhitespace = true;
needWrap = true;
}
if (_ignoreComments && !baseReaderSettings.IgnoreComments)
{
noComments = true;
needWrap = true;
}
if (_ignorePIs && !baseReaderSettings.IgnoreProcessingInstructions)
{
noPIs = true;
needWrap = true;
}
if ((_dtdProcessing == DtdProcessing.Prohibit && baseReaderSettings.DtdProcessing != DtdProcessing.Prohibit) ||
(_dtdProcessing == DtdProcessing.Ignore && baseReaderSettings.DtdProcessing == DtdProcessing.Parse))
{
dtdProc = _dtdProcessing;
needWrap = true;
}
}
if (needWrap)
{
IXmlNamespaceResolver readerAsNSResolver = baseReader as IXmlNamespaceResolver;
if (readerAsNSResolver != null)
{
return new XmlCharCheckingReaderWithNS(baseReader, readerAsNSResolver, checkChars, noWhitespace, noComments, noPIs, dtdProc);
}
else
{
return new XmlCharCheckingReader(baseReader, checkChars, noWhitespace, noComments, noPIs, dtdProc);
}
}
else
{
return baseReader;
}
}
private static bool? s_enableLegacyXmlSettings = null;
static internal bool EnableLegacyXmlSettings()
{
if (s_enableLegacyXmlSettings.HasValue)
{
return s_enableLegacyXmlSettings.Value;
}
if (!System.Xml.BinaryCompatibility.TargetsAtLeast_Desktop_V4_5_2)
{
s_enableLegacyXmlSettings = true;
return s_enableLegacyXmlSettings.Value;
}
bool enableSettings = false; // default value
if (!ReadSettingsFromRegistry(Registry.LocalMachine, ref enableSettings))
{
// still ok if this call return false too as we'll use the default value which is false
ReadSettingsFromRegistry(Registry.CurrentUser, ref enableSettings);
}
s_enableLegacyXmlSettings = enableSettings;
return s_enableLegacyXmlSettings.Value;
}
[SecuritySafeCritical]
private static bool ReadSettingsFromRegistry(RegistryKey hive, ref bool value)
{
const string regValueName = "EnableLegacyXmlSettings";
const string regValuePath = @"SOFTWARE\Microsoft\.NETFramework\XML";
try
{
using (RegistryKey xmlRegKey = hive.OpenSubKey(regValuePath, false))
{
if (xmlRegKey != null)
{
if (xmlRegKey.GetValueKind(regValueName) == RegistryValueKind.DWord)
{
value = ((int)xmlRegKey.GetValue(regValueName)) == 1;
return true;
}
}
}
}
catch { /* use the default if we couldn't read the key */ }
return false;
}
}
}
| |
/************************************************************************************
Filename : OVRDevice.cs
Content : Interface for the Oculus Rift Device
Created : February 14, 2013
Authors : Peter Giokaris, David Borel
Copyright : Copyright 2014 Oculus VR, Inc. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.1 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.1
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
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 UnityEngine;
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using OVR;
//-------------------------------------------------------------------------------------
// ***** OVRDevice
//
/// <summary>
/// OVRDevice is the main interface to the Oculus Rift hardware. It includes wrapper functions
/// for all exported C++ functions, as well as helper functions that use the stored Oculus
/// variables to help set up camera behavior.
///
/// This component is added to the OVRCameraController prefab. It can be part of any
/// game object that one sees fit to place it. However, it should only be declared once,
/// since there are public members that allow for tweaking certain Rift values in the
/// Unity inspector.
///
/// </summary>
public class OVRDevice : MonoBehaviour
{
/// <summary>
/// The current HMD's nominal refresh rate.
/// </summary>
public static float SimulationRate = 60f;
public static Hmd HMD;
// PUBLIC
/// <summary>
/// Only used if prediction is on and timewarp is disabled (see OVRCameraController).
/// </summary>
public static float PredictionTime = 0.03f; // 30 ms
// if off, tracker will not reset when new scene is loaded
public static bool ResetTrackerOnLoad = true;
// Records whether or not we're running on an unsupported platform
[HideInInspector]
public static bool SupportedPlatform;
#region MonoBehaviour Message Handlers
void Awake()
{
string[] args = System.Environment.GetCommandLineArgs();
for (int i = 0; i < args.Length; ++i)
{
if (args[i] == "-fullscreen")
{
Debug.Log("Going to Full-Screen");
Screen.fullScreen = true;
}
else if (args[i] == "-window")
{
Debug.Log("Going to Window");
Screen.fullScreen = false;
}
}
// Detect whether this platform is a supported platform
RuntimePlatform currPlatform = Application.platform;
SupportedPlatform |= currPlatform == RuntimePlatform.Android;
SupportedPlatform |= currPlatform == RuntimePlatform.LinuxPlayer;
SupportedPlatform |= currPlatform == RuntimePlatform.OSXEditor;
SupportedPlatform |= currPlatform == RuntimePlatform.OSXPlayer;
SupportedPlatform |= currPlatform == RuntimePlatform.WindowsEditor;
SupportedPlatform |= currPlatform == RuntimePlatform.WindowsPlayer;
if (!SupportedPlatform)
{
Debug.LogWarning("This platform is unsupported");
return;
}
if (HMD != null)
return;
HMD = Hmd.GetHmd();
//HACK: Forcing LP off until service initializes it properly.
SetLowPersistenceMode(true);
}
void Update()
{
if (HMD != null && Input.anyKeyDown && HMD.GetHSWDisplayState().Displayed)
HMD.DismissHSWDisplay();
}
#endregion
#if false
/// <summary>
/// Destroy this instance.
/// </summary>
void OnDestroy()
{
// We may want to turn this off so that values are maintained between level / scene loads
if (!ResetTrackerOnLoad || HMD == null)
return;
HMD.Destroy();
Hmd.Shutdown();
HMD = null;
}
#endif
// * * * * * * * * * * * *
// PUBLIC FUNCTIONS
// * * * * * * * * * * * *
/// <summary>
/// Determines if is HMD present.
/// </summary>
/// <returns><c>true</c> if is HMD present; otherwise, <c>false</c>.</returns>
public static bool IsHMDPresent()
{
if (HMD == null || !SupportedPlatform)
return false;
ovrTrackingState ss = HMD.GetTrackingState();
return (ss.StatusFlags & (uint)ovrStatusBits.ovrStatus_HmdConnected) != 0;
}
/// <summary>
/// Determines if is sensor present.
/// </summary>
/// <returns><c>true</c> if is sensor present; otherwise, <c>false</c>.</returns>
public static bool IsSensorPresent()
{
if (HMD == null || !SupportedPlatform)
return false;
ovrHmdDesc desc = HMD.GetDesc();
return (desc.HmdCaps & (uint)ovrHmdCaps.ovrHmdCap_Present) != 0;
}
/// <summary>
/// Resets the orientation.
/// </summary>
/// <returns><c>true</c>, if orientation was reset, <c>false</c> otherwise.</returns>
public static bool ResetOrientation()
{
if (HMD == null || !SupportedPlatform)
return false;
HMD.RecenterPose();
return true;
}
// Latest absolute sensor readings (note: in right-hand co-ordinates)
/// <summary>
/// Gets the acceleration.
/// </summary>
/// <returns><c>true</c>, if acceleration was gotten, <c>false</c> otherwise.</returns>
/// <param name="x">The x coordinate.</param>
/// <param name="y">The y coordinate.</param>
/// <param name="z">The z coordinate.</param>
public static bool GetAcceleration(ref float x, ref float y, ref float z)
{
if (HMD == null || !SupportedPlatform)
return false;
ovrTrackingState ss = HMD.GetTrackingState();
x = ss.HeadPose.LinearAcceleration.x;
y = ss.HeadPose.LinearAcceleration.y;
z = ss.HeadPose.LinearAcceleration.z;
return true;
}
/// <summary>
/// Gets the angular velocity.
/// </summary>
/// <returns><c>true</c>, if angular velocity was gotten, <c>false</c> otherwise.</returns>
/// <param name="x">The x coordinate.</param>
/// <param name="y">The y coordinate.</param>
/// <param name="z">The z coordinate.</param>
public static bool GetAngularVelocity(ref float x, ref float y, ref float z)
{
if (HMD == null || !SupportedPlatform)
return false;
ovrTrackingState ss = HMD.GetTrackingState();
x = ss.HeadPose.AngularVelocity.x;
y = ss.HeadPose.AngularVelocity.y;
z = ss.HeadPose.AngularVelocity.z;
return true;
}
/// <summary>
/// Gets the IPD.
/// </summary>
/// <returns><c>true</c>, if IP was gotten, <c>false</c> otherwise.</returns>
/// <param name="IPD">IP.</param>
public static bool GetIPD(ref float IPD)
{
if (HMD == null || !SupportedPlatform)
return false;
IPD = HMD.GetFloat(Hmd.OVR_KEY_IPD, Hmd.OVR_DEFAULT_IPD);
return true;
}
/// <summary>
/// Orients the sensor.
/// </summary>
/// <param name="q">Q.</param>
public static void OrientSensor(ref Quaternion q)
{
// Change the co-ordinate system from right-handed to Unity left-handed
/*
q.x = x;
q.y = y;
q.z = -z;
q = Quaternion.Inverse(q);
*/
// The following does the exact same conversion as above
q.x = -q.x;
q.y = -q.y;
}
/// <summary>
/// Gets the height of the player eye.
/// </summary>
/// <returns><c>true</c>, if player eye height was gotten, <c>false</c> otherwise.</returns>
/// <param name="eyeHeight">Eye height.</param>
public static bool GetPlayerEyeHeight(ref float eyeHeight)
{
if (HMD == null || !SupportedPlatform)
return false;
eyeHeight = HMD.GetFloat(Hmd.OVR_KEY_EYE_HEIGHT, Hmd.OVR_DEFAULT_PLAYER_HEIGHT);
return true;
}
// CAMERA VISION FUNCTIONS
/// <summary>
/// Determines if is camera present.
/// </summary>
/// <returns><c>true</c> if is camera present; otherwise, <c>false</c>.</returns>
public static bool IsCameraPresent()
{
if (HMD == null || !SupportedPlatform)
return false;
ovrTrackingState ss = HMD.GetTrackingState();
return (ss.StatusFlags & (uint)ovrStatusBits.ovrStatus_PositionConnected) != 0;
}
/// <summary>
/// Determines if is camera tracking.
/// </summary>
/// <returns><c>true</c> if is camera tracking; otherwise, <c>false</c>.</returns>
public static bool IsCameraTracking()
{
if (HMD == null || !SupportedPlatform)
return false;
ovrTrackingState ss = HMD.GetTrackingState();
return (ss.StatusFlags & (uint)ovrStatusBits.ovrStatus_PositionTracked) != 0;
}
/// <summary>
/// Gets the camera position orientation.
/// </summary>
/// <returns><c>true</c>, if camera position orientation was gotten, <c>false</c> otherwise.</returns>
/// <param name="p">P.</param>
/// <param name="o">O.</param>
public static bool
GetCameraPositionOrientation(ref Vector3 p, ref Quaternion o, double predictionTime = 0f)
{
if (HMD == null || !SupportedPlatform)
return false;
float px = 0, py = 0, pz = 0, ow = 0, ox = 0, oy = 0, oz = 0;
double abs_time_plus_pred = Hmd.GetTimeInSeconds() + predictionTime;
ovrTrackingState ss = HMD.GetTrackingState(abs_time_plus_pred);
px = ss.HeadPose.ThePose.Position.x;
py = ss.HeadPose.ThePose.Position.y;
pz = ss.HeadPose.ThePose.Position.z;
ox = ss.HeadPose.ThePose.Orientation.x;
oy = ss.HeadPose.ThePose.Orientation.y;
oz = ss.HeadPose.ThePose.Orientation.z;
ow = ss.HeadPose.ThePose.Orientation.w;
p.x = px; p.y = py; p.z = -pz;
o.w = ow; o.x = ox; o.y = oy; o.z = oz;
// Convert to Left hand CS
OrientSensor(ref o);
return true;
}
/// <summary>
/// Gets the camera projection matrix.
/// </summary>
/// <returns><c>true</c>, if camera projection matrix was gotten, <c>false</c> otherwise.</returns>
/// <param name="eyeId">Eye Id - Left = 0, Right = 1.</param>
/// <param name="nearClip">Near Clip Plane of the camera.</param>
/// <param name="farClip">Far Clip Plane of the camera.</param>
/// <param name="mat">The generated camera projection matrix.</param>
public static bool GetCameraProjection(int eyeId, float nearClip, float farClip, ref Matrix4x4 mat)
{
if (HMD == null || !SupportedPlatform)
return false;
ovrFovPort fov = HMD.GetDesc().DefaultEyeFov[eyeId];
mat = Hmd.GetProjection(fov, nearClip, farClip, true).ToMatrix4x4();
return true;
}
/// <summary>
/// Sets the vision enabled.
/// </summary>
/// <param name="on">If set to <c>true</c> on.</param>
public static void SetVisionEnabled(bool on)
{
if (HMD == null || !SupportedPlatform)
return;
uint trackingCaps = (uint)ovrTrackingCaps.ovrTrackingCap_Orientation | (uint)ovrTrackingCaps.ovrTrackingCap_MagYawCorrection;
if (on)
trackingCaps |= (uint)ovrTrackingCaps.ovrTrackingCap_Position;
HMD.RecenterPose();
HMD.ConfigureTracking(trackingCaps, 0);
}
/// <summary>
/// Sets the low Persistence mode.
/// </summary>
/// <param name="on">If set to <c>true</c> on.</param>
public static void SetLowPersistenceMode(bool on)
{
if (HMD == null || !SupportedPlatform)
return;
uint caps = HMD.GetEnabledCaps();
if(on)
caps |= (uint)ovrHmdCaps.ovrHmdCap_LowPersistence;
else
caps &= ~(uint)ovrHmdCaps.ovrHmdCap_LowPersistence;
HMD.SetEnabledCaps(caps);
}
/// <summary>
/// Gets the FOV and resolution.
/// </summary>
public static void GetImageInfo(ref int resH, ref int resV, ref float fovH, ref float fovV)
{
// Always set to safe values :)
resH = 1280;
resV = 800;
fovH = fovV = 90.0f;
if (HMD == null || !SupportedPlatform)
return;
ovrHmdDesc desc = HMD.GetDesc();
ovrFovPort fov = desc.DefaultEyeFov[0];
fov.LeftTan = fov.RightTan = Mathf.Max(fov.LeftTan, fov.RightTan);
fov.UpTan = fov.DownTan = Mathf.Max(fov.UpTan, fov.DownTan);
// Configure Stereo settings. Default pixel density is 1.0f.
float desiredPixelDensity = 1.0f;
ovrSizei texSize = HMD.GetFovTextureSize(ovrEyeType.ovrEye_Left, fov, desiredPixelDensity);
resH = texSize.w;
resV = texSize.h;
fovH = 2f * Mathf.Rad2Deg * Mathf.Atan( fov.LeftTan );
fovV = 2f * Mathf.Rad2Deg * Mathf.Atan( fov.UpTan );
}
/// <summary>
/// Get resolution of eye texture
/// </summary>
/// <param name="w">Width</param>
/// <param name="h">Height</param>
public static void GetResolutionEyeTexture(ref int w, ref int h)
{
if (HMD == null || !SupportedPlatform)
return;
ovrHmdDesc desc = HMD.GetDesc();
ovrFovPort[] eyeFov = new ovrFovPort[2];
eyeFov[0] = desc.DefaultEyeFov[0];
eyeFov[1] = desc.DefaultEyeFov[1];
ovrSizei recommenedTex0Size = HMD.GetFovTextureSize(ovrEyeType.ovrEye_Left, desc.DefaultEyeFov[0], 1.0f);
ovrSizei recommenedTex1Size = HMD.GetFovTextureSize(ovrEyeType.ovrEye_Left, desc.DefaultEyeFov[1], 1.0f);
w = recommenedTex0Size.w + recommenedTex1Size.w;
h = (recommenedTex0Size.h + recommenedTex1Size.h)/2;
}
/// <summary>
/// Get latency values
/// </summary>
/// <param name="Ren">Ren</param>
/// <param name="TWrp">TWrp</param>
/// <param name="PostPresent">PostPresent</param>
public static void GetLatencyValues(ref float Ren, ref float TWrp, ref float PostPresent)
{
if (HMD == null || !SupportedPlatform)
return;
float[] values = { 0.0f, 0.0f, 0.0f };
float[] latencies = HMD.GetFloatArray("DK2Latency", values);
Ren = latencies[0];
TWrp = latencies[1];
PostPresent = latencies[2];
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter;
using Microsoft.Protocols.TestSuites.FileSharing.Common.TestSuite;
using Microsoft.Protocols.TestTools;
using Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Smb2;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
namespace Microsoft.Protocols.TestSuites.FileSharing.SMB2.TestSuite
{
/// <summary>
/// This test class is for testing negotiation using SMB3.0.
/// </summary>
[TestClass]
public class Negotiation : SMB2TestBase
{
#region Variables
private Smb2FunctionalClient client;
private uint status;
public static List<DialectRevision> allDialects;
#endregion
#region Initilization
[ClassInitialize()]
public static void ClassInitialize(TestContext testContext)
{
TestClassBase.Initialize(testContext);
}
[ClassCleanup()]
public static void ClassCleanup()
{
TestClassBase.Cleanup();
}
protected override void TestInitialize()
{
base.TestInitialize();
status = 0;
client = new Smb2FunctionalClient(TestConfig.Timeout, TestConfig, BaseTestSite);
BaseTestSite.Log.Add(LogEntryKind.Debug, "Connect to server:" + TestConfig.SutComputerName);
client.ConnectToServer(TestConfig.UnderlyingTransport, TestConfig.SutComputerName, TestConfig.SutIPAddress);
}
protected override void TestCleanup()
{
client.Disconnect();
base.TestCleanup();
}
#endregion
#region Test cases
[TestMethod]
[TestCategory(TestCategories.Bvt)]
[TestCategory(TestCategories.Smb21)]
[TestCategory(TestCategories.Negotiate)]
[Description("This test case is designed to test whether server can handle NEGOTIATE with Smb2 dialect wildcard.")]
public void BVT_Negotiate_Compatible_Wildcard()
{
//Send wildcard revision number to verify if the server supports SMB2.1 or future dialect revisions.
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"Send MultiProtocolNegotiate request with dialects: SMB 2.002, SMB 2.???");
string[] dialects = new string[] { "SMB 2.002", "SMB 2.???" };
bool isSmb2002Selected = false;
status = client.MultiProtocolNegotiate(
dialects,
(Packet_Header header, NEGOTIATE_Response response) =>
{
BaseTestSite.Log.Add(
LogEntryKind.Debug,
"The selected dialect is " + response.DialectRevision);
if (TestConfig.MaxSmbVersionSupported == DialectRevision.Smb2002)
{
BaseTestSite.Assert.AreEqual(
DialectRevision.Smb2002,
response.DialectRevision,
"The server is expected to use dialect: {0}", DialectRevision.Smb2002);
isSmb2002Selected = true;
}
else
{
BaseTestSite.Assert.AreEqual(
DialectRevision.Smb2Wildcard,
response.DialectRevision,
"The server is expected to use dialect: {0}", DialectRevision.Smb2Wildcard);
}
});
if (isSmb2002Selected)
{
return;
}
//According to server response, send new dialects for negotiation.
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"Send Negotiate request with dialects: Smb2002, Smb21, Smb30, SMB302");
status = client.Negotiate(
Packet_Header_Flags_Values.NONE,
TestConfig.RequestDialects,
checker: (Packet_Header header, NEGOTIATE_Response response) =>
{
BaseTestSite.Assert.AreEqual(
Smb2Status.STATUS_SUCCESS,
header.Status,
"{0} should succeed, actually server returns {1}.", header.Command, Smb2Status.GetStatusCode(header.Status));
});
}
[TestMethod]
[TestCategory(TestCategories.Bvt)]
[TestCategory(TestCategories.Smb21)]
[TestCategory(TestCategories.Negotiate)]
[Description("This test case is designed to test whether server can handle compatible NEGOTIATE with dialect Smb 2.002.")]
public void BVT_Negotiate_Compatible_2002()
{
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"Send MultiProtocolNegotiate request with dialects: SMB 2.002");
string[] dialects = new string[] { "SMB 2.002"};
status = client.MultiProtocolNegotiate(
dialects,
(Packet_Header header, NEGOTIATE_Response response) =>
{
BaseTestSite.Log.Add(
LogEntryKind.Debug,
"The selected dialect is " + response.DialectRevision);
BaseTestSite.Assert.AreEqual(
DialectRevision.Smb2002,
response.DialectRevision,
"The server is expected to use dialect: {0}", DialectRevision.Smb2002);
});
}
[TestMethod]
[TestCategory(TestCategories.Bvt)]
[TestCategory(TestCategories.Smb2002)]
[TestCategory(TestCategories.Negotiate)]
[Description("This test case is designed to test whether server can handle NEGOTIATE with Signing Required.")]
public void BVT_Negotiate_SigningEnabled()
{
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"Send Negotiate request with dialects: Smb2002, Smb21, Smb30, SMB302 and Signing Required.");
status = client.Negotiate(
Packet_Header_Flags_Values.NONE,
TestConfig.RequestDialects,
securityMode: SecurityMode_Values.NEGOTIATE_SIGNING_REQUIRED,
checker: (Packet_Header header, NEGOTIATE_Response response) =>
{
BaseTestSite.Assert.AreEqual(
Smb2Status.STATUS_SUCCESS,
header.Status,
"{0} should succeed, actually server returns {1}.", header.Command, Smb2Status.GetStatusCode(header.Status));
});
}
[TestMethod]
[TestCategory(TestCategories.Bvt)]
[TestCategory(TestCategories.Smb2002)]
[TestCategory(TestCategories.Negotiate)]
[Description("This test case is designed to test whether server can handle NEGOTIATE with Smb 2.002 dialect.")]
public void BVT_Negotiate_SMB2002()
{
NegotiateWithSpecificDialect(DialectRevision.Smb2002);
}
[TestMethod]
[TestCategory(TestCategories.Bvt)]
[TestCategory(TestCategories.Smb2002)]
[TestCategory(TestCategories.Negotiate)]
[Description("This test case is designed to test whether server can handle NEGOTIATE with Smb 2.1 dialect.")]
public void BVT_Negotiate_SMB21()
{
NegotiateWithSpecificDialect(DialectRevision.Smb21);
}
[TestMethod]
[TestCategory(TestCategories.Bvt)]
[TestCategory(TestCategories.Smb2002)]
[TestCategory(TestCategories.Negotiate)]
[Description("This test case is designed to test whether server can handle NEGOTIATE with Smb 3.0 dialect.")]
public void BVT_Negotiate_SMB30()
{
NegotiateWithSpecificDialect(DialectRevision.Smb30);
}
[TestMethod]
[TestCategory(TestCategories.Bvt)]
[TestCategory(TestCategories.Smb2002)]
[TestCategory(TestCategories.Negotiate)]
[Description("This test case is designed to test whether server can handle NEGOTIATE with Smb 3.02 dialect.")]
public void BVT_Negotiate_SMB302()
{
NegotiateWithSpecificDialect(DialectRevision.Smb302);
}
[TestMethod]
[TestCategory(TestCategories.Bvt)]
[TestCategory(TestCategories.Smb2002)]
[TestCategory(TestCategories.Negotiate)]
[Description("This test case is designed to test whether server (including the server doesn't implement dialect 3.11) " +
" can handle NEGOTIATE with SMB 3.11 dialect and Negotiate Contexts.")]
public void BVT_Negotiate_SMB311()
{
DialectRevision clientMaxDialectSupported = DialectRevision.Smb311;
PreauthIntegrityHashID[] preauthHashAlgs = new PreauthIntegrityHashID[] { PreauthIntegrityHashID.SHA_512 };
EncryptionAlgorithm[] encryptionAlgs = new EncryptionAlgorithm[] {
EncryptionAlgorithm.ENCRYPTION_AES128_GCM,
EncryptionAlgorithm.ENCRYPTION_AES128_CCM };
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"Send Negotiate request with dialect SMB 3.11, SMB2_PREAUTH_INTEGRITY_CAPABILITIES context and " +
"SMB2_ENCRYPTION_CAPABILITIES context.");
NegotiateWithNegotiateContexts(
clientMaxDialectSupported,
preauthHashAlgs,
encryptionAlgs,
checker: (Packet_Header header, NEGOTIATE_Response response) =>
{
CheckNegotiateResponse(header, response, clientMaxDialectSupported, encryptionAlgs);
}
);
}
[TestMethod]
[TestCategory(TestCategories.Bvt)]
[TestCategory(TestCategories.Smb311)]
[TestCategory(TestCategories.Negotiate)]
[Description("This test case is designed to test whether server can handle NEGOTIATE with " +
"Smb 3.11 dialect and SMB2_PREAUTH_INTEGRITY_CAPABILITIES context")]
public void BVT_Negotiate_SMB311_Preauthentication()
{
DialectRevision clientMaxDialectSupported = DialectRevision.Smb311;
PreauthIntegrityHashID[] preauthHashAlgs = new PreauthIntegrityHashID[] { PreauthIntegrityHashID.SHA_512 };
if (TestConfig.MaxSmbVersionSupported < DialectRevision.Smb311)
BaseTestSite.Assert.Inconclusive("Stop to run this test case because the configured server max dialect is lower than 3.11.");
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"Send Negotiate request with dialect SMB 3.11 and SMB2_PREAUTH_INTEGRITY_CAPABILITIES context.");
NegotiateWithNegotiateContexts(
clientMaxDialectSupported,
preauthHashAlgs,
null,
checker: (Packet_Header header, NEGOTIATE_Response response) =>
{
CheckNegotiateResponse(header, response, clientMaxDialectSupported, null);
}
);
}
[TestMethod]
[TestCategory(TestCategories.Bvt)]
[TestCategory(TestCategories.Smb311)]
[TestCategory(TestCategories.Negotiate)]
[Description("This test case is designed to test whether server can handle NEGOTIATE with " +
"Smb 3.11 dialect and SMB2_PREAUTH_INTEGRITY_CAPABILITIES context and " +
"SMB2_ENCRYPTION_CAPABILITIES context with AES-128-CCM preferred.")]
public void BVT_Negotiate_SMB311_Preauthentication_Encryption_CCM()
{
DialectRevision clientMaxDialectSupported = DialectRevision.Smb311;
PreauthIntegrityHashID[] preauthHashAlgs = new PreauthIntegrityHashID[] { PreauthIntegrityHashID.SHA_512 };
EncryptionAlgorithm[] encryptionAlgs = new EncryptionAlgorithm[] {
EncryptionAlgorithm.ENCRYPTION_AES128_CCM,
EncryptionAlgorithm.ENCRYPTION_AES128_GCM };
if (TestConfig.MaxSmbVersionSupported < DialectRevision.Smb311)
BaseTestSite.Assert.Inconclusive("Stop to run this test case because the configured server max dialect is lower than 3.11.");
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"Send Negotiate request with dialect SMB 3.11, SMB2_PREAUTH_INTEGRITY_CAPABILITIES context and " +
"SMB2_ENCRYPTION_CAPABILITIES context with AES-128-CCM preferred.");
NegotiateWithNegotiateContexts(
clientMaxDialectSupported,
preauthHashAlgs,
encryptionAlgs,
checker: (Packet_Header header, NEGOTIATE_Response response) =>
{
CheckNegotiateResponse(header, response, clientMaxDialectSupported, encryptionAlgs);
}
);
}
[TestMethod]
[TestCategory(TestCategories.Bvt)]
[TestCategory(TestCategories.Smb311)]
[TestCategory(TestCategories.Negotiate)]
[Description("This test case is designed to test whether server can handle NEGOTIATE with " +
"Smb 3.11 dialect and SMB2_PREAUTH_INTEGRITY_CAPABILITIES context and " +
"SMB2_ENCRYPTION_CAPABILITIES context with AES-128-GCM preferred.")]
public void BVT_Negotiate_SMB311_Preauthentication_Encryption_GCM()
{
DialectRevision clientMaxDialectSupported = DialectRevision.Smb311;
PreauthIntegrityHashID[] preauthHashAlgs = new PreauthIntegrityHashID[] { PreauthIntegrityHashID.SHA_512 };
EncryptionAlgorithm[] encryptionAlgs = new EncryptionAlgorithm[] {
EncryptionAlgorithm.ENCRYPTION_AES128_GCM,
EncryptionAlgorithm.ENCRYPTION_AES128_CCM };
if (TestConfig.MaxSmbVersionSupported < DialectRevision.Smb311)
BaseTestSite.Assert.Inconclusive("Stop to run this test case because the configured server max dialect is lower than 3.11.");
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"Send Negotiate request with dialect SMB 3.11, SMB2_PREAUTH_INTEGRITY_CAPABILITIES context and " +
"SMB2_ENCRYPTION_CAPABILITIES context with AES-128-GCM preferred.");
NegotiateWithNegotiateContexts(
clientMaxDialectSupported,
preauthHashAlgs,
encryptionAlgs,
checker: (Packet_Header header, NEGOTIATE_Response response) =>
{
CheckNegotiateResponse(header, response, clientMaxDialectSupported, encryptionAlgs);
}
);
}
[TestMethod]
[TestCategory(TestCategories.Smb311)]
[TestCategory(TestCategories.Negotiate)]
[TestCategory(TestCategories.UnexpectedContext)]
[Description("This test case is designed to test whether server can handle NEGOTIATE with " +
"Smb 3.11 dialect and without any Negotiate Contexts.")]
public void Negotiate_SMB311_WithoutAnyContexts()
{
if (TestConfig.MaxSmbVersionSupported < DialectRevision.Smb311)
BaseTestSite.Assert.Inconclusive("Stop to run this test case because the configured server max dialect is lower than 3.11.");
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Send Negotiate request with dialect SMB 3.11, and without any Negotiate Contexts.");
client.NegotiateWithContexts(
Packet_Header_Flags_Values.NONE,
Smb2Utility.GetDialects(DialectRevision.Smb311),
preauthHashAlgs: null,
encryptionAlgs: null,
checker: (Packet_Header header, NEGOTIATE_Response response) =>
{
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Verify server fails the negotiate request with STATUS_INVALID_PARAMETER.");
BaseTestSite.Assert.AreEqual(Smb2Status.STATUS_INVALID_PARAMETER, header.Status,
"[MS-SMB2] 3.3.5.4 If the negotiate context list does not contain exactly one SMB2_PREAUTH_INTEGRITY_CAPABILITIES negotiate context, " +
"then the server MUST fail the negotiate request with STATUS_INVALID_PARAMETER.");
});
}
[TestMethod]
[TestCategory(TestCategories.Smb311)]
[TestCategory(TestCategories.Negotiate)]
[TestCategory(TestCategories.UnexpectedContext)]
[Description("This test case is designed to test whether server can handle NEGOTIATE with " +
"Smb 3.11 dialect, with SMB2_ENCRYPTION_CAPABILITIES Context and without SMB2_PREAUTH_INTEGRITY_CAPABILITIES Context.")]
public void Negotiate_SMB311_WithEncryptionContextWithoutIntegrityContext()
{
if (TestConfig.MaxSmbVersionSupported < DialectRevision.Smb311)
BaseTestSite.Assert.Inconclusive("Stop to run this test case because the configured server max dialect is lower than 3.11.");
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Send Negotiate request with dialect SMB 3.11, with SMB2_ENCRYPTION_CAPABILITIES context, " +
"without SMB2_PREAUTH_INTEGRITY_CAPABILITIES context.");
client.NegotiateWithContexts(
Packet_Header_Flags_Values.NONE,
Smb2Utility.GetDialects(DialectRevision.Smb311),
preauthHashAlgs: null,
encryptionAlgs: new EncryptionAlgorithm[] {
EncryptionAlgorithm.ENCRYPTION_AES128_GCM,
EncryptionAlgorithm.ENCRYPTION_AES128_CCM },
checker: (Packet_Header header, NEGOTIATE_Response response) =>
{
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Verify server fails the negotiate request with STATUS_INVALID_PARAMETER.");
BaseTestSite.Assert.AreEqual(Smb2Status.STATUS_INVALID_PARAMETER, header.Status,
"[MS-SMB2] 3.3.5.4 If the negotiate context list does not contain exactly one SMB2_PREAUTH_INTEGRITY_CAPABILITIES negotiate context, " +
"then the server MUST fail the negotiate request with STATUS_INVALID_PARAMETER.");
});
}
[TestMethod]
[TestCategory(TestCategories.Smb311)]
[TestCategory(TestCategories.Negotiate)]
[TestCategory(TestCategories.UnexpectedFields)]
[Description("This test case is designed to test whether server can handle NEGOTIATE with " +
"Smb 3.11 dialect and with an invalid HashAlgorithm in SMB2_PREAUTH_INTEGRITY_CAPABILITIES Context.")]
public void Negotiate_SMB311_InvalidHashAlgorithm()
{
PreauthIntegrityHashID[] preauthHashAlgs = new PreauthIntegrityHashID[] { PreauthIntegrityHashID.HashAlgorithm_Invalid };
if (TestConfig.MaxSmbVersionSupported < DialectRevision.Smb311)
BaseTestSite.Assert.Inconclusive("Stop to run this test case because the configured server max dialect is lower than 3.11.");
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"Send Negotiate request with dialect SMB 3.11, SMB2_PREAUTH_INTEGRITY_CAPABILITIES context and " +
"set HashAlgorithm to an invalid value: 0xFFFF.");
NegotiateWithNegotiateContexts(
DialectRevision.Smb311,
preauthHashAlgs,
encryptionAlgs: null,
checker: (Packet_Header header, NEGOTIATE_Response response) =>
{
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Verify server fails the negotiate request with STATUS_SMB_NO_PREAUTH_INTEGRITY_HASH_OVERLAP.");
BaseTestSite.Assert.AreEqual(Smb2Status.STATUS_SMB_NO_PREAUTH_INTEGRITY_HASH_OVERLAP, header.Status,
"[MS-SMB2] 3.3.5.4 If the SMB2_PREAUTH_INTEGRITY_CAPABILITIES HashAlgorithms array does not contain any hash algorithms " +
"that the server supports, then the server MUST fail the negotiate request with STATUS_SMB_NO_PREAUTH_INTEGRITY_HASH_OVERLAP (0xC05D0000).");
});
}
[TestMethod]
[TestCategory(TestCategories.Smb311)]
[TestCategory(TestCategories.Negotiate)]
[TestCategory(TestCategories.UnexpectedFields)]
[Description("This test case is designed to test whether server can handle NEGOTIATE with " +
"Smb 3.11 dialect and with an invalid Cipher in SMB2_ENCRYPTION_CAPABILITIES Context.")]
public void Negotiate_SMB311_InvalidCipher()
{
EncryptionAlgorithm[] encryptionAlgs = new EncryptionAlgorithm[] {
EncryptionAlgorithm.ENCRYPTION_INVALID };
if (TestConfig.MaxSmbVersionSupported < DialectRevision.Smb311)
BaseTestSite.Assert.Inconclusive("Stop to run this test case because the configured server max dialect is lower than 3.11.");
BaseTestSite.Log.Add(
LogEntryKind.TestStep,
"Send Negotiate request with dialect SMB 3.11, SMB2_ENCRYPTION_CAPABILITIES context and " +
"set Cipher to an invalid value: 0xFFFF.");
NegotiateWithNegotiateContexts(
DialectRevision.Smb311,
new PreauthIntegrityHashID[] { PreauthIntegrityHashID.SHA_512 },
encryptionAlgs,
checker: (Packet_Header header, NEGOTIATE_Response response) =>
{
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Verify that server sets Connection.CipherId to 0 from the response.");
BaseTestSite.Assert.AreEqual((EncryptionAlgorithm)0, client.SelectedCipherID,
"[MS-SMB2] 3.3.5.4 If the client and server have no common cipher, then the server must set Connection.CipherId to 0.");
}
);
}
#endregion
#region private methods
private void NegotiateWithSpecificDialect(DialectRevision clientMaxDialectSupported)
{
DialectRevision serverMaxDialectSupported = TestConfig.MaxSmbVersionSupported;
DialectRevision[] negotiateDialects = Smb2Utility.GetDialects(clientMaxDialectSupported);
if (clientMaxDialectSupported > TestConfig.MaxSmbVersionClientSupported)
{
BaseTestSite.Assert.Inconclusive("Stop to run this test case because the configured MaxSmbVersionClientSupported {0} is lower than {1}.",
TestConfig.MaxSmbVersionClientSupported,
clientMaxDialectSupported);
}
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Send Negotiate request with maximum dialect: {0}.", clientMaxDialectSupported);
client.Negotiate(
Packet_Header_Flags_Values.NONE,
negotiateDialects,
checker: (Packet_Header header, NEGOTIATE_Response response) =>
{
DialectRevision expectedDialect = clientMaxDialectSupported < serverMaxDialectSupported
? clientMaxDialectSupported : serverMaxDialectSupported;
BaseTestSite.Log.Add(LogEntryKind.TestStep, "Check negotiate response contains expected dialect.");
BaseTestSite.Assert.AreEqual(
Smb2Status.STATUS_SUCCESS,
header.Status,
"{0} should succeed, actually server returns {1}.", header.Command, Smb2Status.GetStatusCode(header.Status));
BaseTestSite.Assert.AreEqual(expectedDialect, response.DialectRevision, "Selected dialect should be {0}", expectedDialect);
});
}
private void NegotiateWithNegotiateContexts(
DialectRevision clientMaxDialectSupported,
PreauthIntegrityHashID[] preauthHashAlgs,
EncryptionAlgorithm[] encryptionAlgs = null,
ResponseChecker<NEGOTIATE_Response> checker = null)
{
// ensure clientMaxDialectSupported higher than 3.11
if (clientMaxDialectSupported < DialectRevision.Smb311) clientMaxDialectSupported = DialectRevision.Smb311;
DialectRevision[] negotiateDialects = Smb2Utility.GetDialects(clientMaxDialectSupported);
if (clientMaxDialectSupported > TestConfig.MaxSmbVersionClientSupported)
{
BaseTestSite.Assert.Inconclusive("Stop to run this test case because the configured MaxSmbVersionClientSupported {0} is lower than {1}.",
TestConfig.MaxSmbVersionClientSupported,
clientMaxDialectSupported);
}
status = client.NegotiateWithContexts(
Packet_Header_Flags_Values.NONE,
negotiateDialects,
preauthHashAlgs: preauthHashAlgs,
encryptionAlgs: encryptionAlgs,
checker: checker);
}
private void CheckNegotiateResponse(
Packet_Header header,
NEGOTIATE_Response response,
DialectRevision clientMaxDialectSupported,
EncryptionAlgorithm[] encryptionAlgs)
{
DialectRevision expectedDialect = clientMaxDialectSupported < TestConfig.MaxSmbVersionSupported
? clientMaxDialectSupported : TestConfig.MaxSmbVersionSupported;
BaseTestSite.Assert.AreEqual(
Smb2Status.STATUS_SUCCESS,
header.Status,
"{0} should succeed, actually server returns {1}.", header.Command, Smb2Status.GetStatusCode(header.Status));
BaseTestSite.Assert.AreEqual(expectedDialect, response.DialectRevision, "Selected dialect should be {0}", expectedDialect);
if (expectedDialect >= DialectRevision.Smb311)
{
BaseTestSite.Assert.AreEqual(
PreauthIntegrityHashID.SHA_512,
client.SelectedPreauthIntegrityHashID,
"[MS-SMB2] 3.3.5.4 The server MUST set Connection.PreauthIntegrityHashId to one of the hash algorithms " +
"in the client's SMB2_PREAUTH_INTEGRITY_CAPABILITIES HashAlgorithms array.");
if (encryptionAlgs != null)
{
BaseTestSite.Assert.IsTrue(
TestConfig.SupportedEncryptionAlgorithmList.Contains(client.SelectedCipherID),
"[MS-SMB2] 3.3.5.4 The server MUST set Connection.CipherId to one of the ciphers in the client's " +
"SMB2_ENCRYPTION_CAPABILITIES Ciphers array in an implementation-specific manner.");
}
else
{
BaseTestSite.Assert.AreEqual(
EncryptionAlgorithm.ENCRYPTION_NONE,
client.SelectedCipherID,
"[MS-SMB2] if client doesn't present SMB2_ENCRYPTION_CAPABILITIES context in negotiate request, " +
"server should not present this context in negotiate response.");
}
}
else
{
// If server supported dialect version is lower than 3.11, server should ignore the negotiate contexts.
BaseTestSite.Assert.AreEqual(
PreauthIntegrityHashID.HashAlgorithm_NONE,
client.SelectedPreauthIntegrityHashID,
"[MS-SMB2] The server must ignore the SMB2_PREAUTH_INTEGRITY_CAPABILITIES context if Connection.Dialect is less than 3.11. ");
BaseTestSite.Assert.AreEqual(
EncryptionAlgorithm.ENCRYPTION_NONE,
client.SelectedCipherID,
"[MS-SMB2] The server must ignore the SMB2_ENCRYPTION_CAPABILITIES context if Connection.Dialect is less than 3.11. ");
}
}
#endregion
}
}
| |
//Copyright (C) 2005 Richard J. Northedge
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//This file is based on the GISModelReader.java source file found in the
//original java implementation of MaxEnt. That source file contains the following header:
// Copyright (C) 2001 Jason Baldridge and Gann Bierner
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
using System;
using System.Collections.Generic;
namespace SharpEntropy.IO
{
/// <summary>
/// Abstract parent class for readers of GIS models.
/// </summary>
/// <author>
/// Jason Baldridge
/// </author>
/// <author>
/// Richard J. Northedge
/// </author>
/// <version>
/// based on GISModelReader.java, $Revision: 1.5 $, $Date: 2004/06/11 20:51:36 $
/// </version>
public abstract class GisModelReader : IGisModelReader
{
private char[] _spaces;
private int _correctionConstant;
private double _correctionParameter;
private string[] _outcomeLabels;
private int[][] _outcomePatterns;
private int _predicateCount;
private Dictionary<string, PatternedPredicate> _predicates;
/// <summary>
/// The number of predicates contained in the model.
/// </summary>
protected int PredicateCount
{
get
{
return _predicateCount;
}
}
/// <summary>
/// Retrieve a model from disk.
///
/// <p>This method delegates to worker methods for each part of this
/// sequence. If you are creating a reader that conforms largely to this
/// sequence but varies at one or more points, override the relevant worker
/// method(s) to achieve the required format.</p>
///
/// <p>If you are creating a reader for a format which does not follow this
/// sequence at all, override this method and ignore the
/// other ReadX methods provided in this abstract class.</p>
/// </summary>
/// <remarks>
/// Thie method assumes that models are saved in the
/// following sequence:
///
/// <p>GIS (model type identifier)</p>
/// <p>1. the correction constant (int)</p>
/// <p>2. the correction constant parameter (double)</p>
/// <p>3. outcomes</p>
/// <p>3a. number of outcomes (int)</p>
/// <p>3b. outcome names (string array - length specified in 3a)</p>
/// <p>4. predicates</p>
/// <p>4a. outcome patterns</p>
/// <p>4ai. number of outcome patterns (int)</p>
/// <p>4aii. outcome pattern values (each stored in a space delimited string)</p>
/// <p>4b. predicate labels</p>
/// <p>4bi. number of predicates (int)</p>
/// <p>4bii. predicate names (string array - length specified in 4bi)</p>
/// <p>4c. predicate parameters (double values)</p>
/// </remarks>
protected virtual void ReadModel()
{
_spaces = new char[] {' '}; //cached constant to improve performance
CheckModelType();
_correctionConstant = ReadCorrectionConstant();
_correctionParameter = ReadCorrectionParameter();
_outcomeLabels = ReadOutcomes();
ReadPredicates(out _outcomePatterns, out _predicates);
}
/// <summary>
/// Checks the model file being read from begins with the sequence of characters
/// "GIS".
/// </summary>
protected virtual void CheckModelType()
{
string modelType = ReadString();
if (modelType != "GIS")
{
// TODO : consider a custom exception
throw new Exception("Error: attempting to load a " + modelType + " model as a GIS model." + " You should expect problems.");
}
}
/// <summary>
/// Reads the correction constant from the model file.
/// </summary>
protected virtual int ReadCorrectionConstant()
{
return ReadInt32();
}
/// <summary>
/// Reads the correction constant parameter from the model file.
/// </summary>
protected virtual double ReadCorrectionParameter()
{
return ReadDouble();
}
/// <summary>
/// Reads the outcome names from the model file.
/// </summary>
protected virtual string[] ReadOutcomes()
{
int outcomeCount = ReadInt32();
var outcomeLabels = new string[outcomeCount];
for (int currentLabel = 0; currentLabel < outcomeCount; currentLabel++)
{
outcomeLabels[currentLabel] = ReadString();
}
return outcomeLabels;
}
/// <summary>
/// Reads the predicate information from the model file, placing the data in two
/// structures - an array of outcome patterns, and a Dictionary of predicates
/// keyed by predicate name.
/// </summary>
protected virtual void ReadPredicates(out int[][] outcomePatterns, out Dictionary<string, PatternedPredicate> predicates)
{
outcomePatterns = ReadOutcomePatterns();
string[] asPredicateLabels = ReadPredicateLabels();
predicates = ReadParameters(outcomePatterns, asPredicateLabels);
}
/// <summary>
/// Reads the outcome pattern information from the model file.
/// </summary>
protected virtual int[][] ReadOutcomePatterns()
{
//get the number of outcome patterns (that is, the number of unique combinations of outcomes in the model)
int outcomePatternCount = ReadInt32();
//initialize an array of outcome patterns. Each outcome pattern is itself an array of integers
var outcomePatterns = new int[outcomePatternCount][];
//for each outcome pattern
for (int currentOutcomePattern = 0; currentOutcomePattern < outcomePatternCount; currentOutcomePattern++)
{
//read a space delimited string from the model file containing the information for the integer array.
//The first value in the integer array is the number of predicates related to this outcome pattern; the
//other values make up the outcome IDs for this pattern.
string[] tokens = ReadString().Split(_spaces);
//convert this string to the array of integers required for the pattern
var patternData = new int[tokens.Length];
for (int currentPatternValue = 0; currentPatternValue < tokens.Length; currentPatternValue++)
{
patternData[currentPatternValue] = int.Parse(tokens[currentPatternValue], System.Globalization.CultureInfo.InvariantCulture);
}
outcomePatterns[currentOutcomePattern] = patternData;
}
return outcomePatterns;
}
/// <summary>
/// Reads the outcome labels from the model file.
/// </summary>
protected virtual string[] ReadPredicateLabels()
{
_predicateCount = ReadInt32();
var predicateLabels = new string[_predicateCount];
for (int currentPredicate = 0; currentPredicate < _predicateCount; currentPredicate++)
{
predicateLabels[currentPredicate] = ReadString();
}
return predicateLabels;
}
/// <summary>
/// Reads the predicate parameter information from the model file.
/// </summary>
protected virtual Dictionary<string, PatternedPredicate> ReadParameters(int[][] outcomePatterns, string[] predicateLabels)
{
var predicates = new Dictionary<string, PatternedPredicate>(predicateLabels.Length);
int parameterIndex = 0;
for (int currentOutcomePattern = 0; currentOutcomePattern < outcomePatterns.Length; currentOutcomePattern++)
{
for (int currentOutcomeInfo = 0; currentOutcomeInfo < outcomePatterns[currentOutcomePattern][0]; currentOutcomeInfo++)
{
var parameters = new double[outcomePatterns[currentOutcomePattern].Length - 1];
for (int currentParameter = 0; currentParameter < outcomePatterns[currentOutcomePattern].Length - 1; currentParameter++)
{
parameters[currentParameter] = ReadDouble();
}
predicates.Add(predicateLabels[parameterIndex], new PatternedPredicate(currentOutcomePattern, parameters));
parameterIndex++;
}
}
return predicates;
}
/// <summary>
/// Implement as needed for the format the model is stored in.
/// </summary>
protected abstract int ReadInt32();
/// <summary>
/// Implement as needed for the format the model is stored in.
/// </summary>
protected abstract double ReadDouble();
/// <summary>
/// Implement as needed for the format the model is stored in.
/// </summary>
protected abstract string ReadString();
/// <summary>
/// The model's correction constant.
/// </summary>
public int CorrectionConstant
{
get
{
return _correctionConstant;
}
}
/// <summary>
/// The model's correction constant parameter.
/// </summary>
public double CorrectionParameter
{
get
{
return _correctionParameter;
}
}
/// <summary>
/// Returns the labels for all the outcomes in the model.
/// </summary>
/// <returns>
/// string array containing outcome labels.
/// </returns>
public string[] GetOutcomeLabels()
{
return _outcomeLabels;
}
/// <summary>
/// Returns the outcome patterns in the model.
/// </summary>
/// <returns>
/// Array of integer arrays containing the information for
/// each outcome pattern in the model.
/// </returns>
public int[][] GetOutcomePatterns()
{
return _outcomePatterns;
}
/// <summary>
/// Returns the predicates in the model.
/// </summary>
/// <returns>
/// Dictionary containing PatternedPredicate objects keyed
/// by predicate label.
/// </returns>
public Dictionary<string, PatternedPredicate> GetPredicates()
{
return _predicates;
}
/// <summary>
/// Returns model information for a predicate, given the predicate label.
/// </summary>
/// <param name="predicateLabel">
/// The predicate label to fetch information for.
/// </param>
/// <param name="featureCounts">
/// Array to be passed in to the method; it should have a length equal to the number of outcomes
/// in the model. The method increments the count of each outcome that is active in the specified
/// predicate.
/// </param>
/// <param name="outcomeSums">
/// Array to be passed in to the method; it should have a length equal to the number of outcomes
/// in the model. The method adds the parameter values for each of the active outcomes in the
/// predicate.
/// </param>
public virtual void GetPredicateData(string predicateLabel, int[] featureCounts, double[] outcomeSums)
{
try
{
if (predicateLabel != null && _predicates.ContainsKey(predicateLabel))
{
PatternedPredicate predicate = _predicates[predicateLabel];
int[] activeOutcomes = _outcomePatterns[predicate.OutcomePattern];
for (int currentActiveOutcome = 1; currentActiveOutcome < activeOutcomes.Length; currentActiveOutcome++)
{
int outcomeIndex = activeOutcomes[currentActiveOutcome];
featureCounts[outcomeIndex]++;
outcomeSums[outcomeIndex] += predicate.GetParameter(currentActiveOutcome - 1);
}
}
}
catch (ArgumentNullException ex)
{
throw new ArgumentException(string.Format("Try to find key '{0}' in predicates dictionary ({1} entries)", predicateLabel, _predicates.Count), ex);
}
}
}
}
| |
//
// ReflectionHelper.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2005 Jb Evain
// (C) 2006 Evaluant RC S.A.
// (C) 2007 Jb Evain
//
// 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 Mono.Cecil {
using System;
using System.Collections;
using SR = System.Reflection;
using System.Text;
internal sealed class ReflectionHelper {
ModuleDefinition m_module;
public ReflectionHelper (ModuleDefinition module)
{
m_module = module;
}
public AssemblyNameReference ImportAssembly (SR.Assembly asm)
{
AssemblyNameReference asmRef = GetAssemblyNameReference (asm.GetName ());
if (asmRef != null)
return asmRef;
SR.AssemblyName asmName = asm.GetName ();
asmRef = new AssemblyNameReference (
asmName.Name, asmName.CultureInfo.Name, asmName.Version);
asmRef.PublicKeyToken = asmName.GetPublicKeyToken ();
asmRef.HashAlgorithm = (AssemblyHashAlgorithm) asmName.HashAlgorithm;
asmRef.Culture = asmName.CultureInfo.ToString ();
m_module.AssemblyReferences.Add (asmRef);
return asmRef;
}
AssemblyNameReference GetAssemblyNameReference (SR.AssemblyName name)
{
foreach (AssemblyNameReference reference in m_module.AssemblyReferences)
if (reference.FullName == name.FullName)
return reference;
return null;
}
public static string GetTypeSignature (Type t)
{
if (t.HasElementType) {
if (t.IsPointer)
return string.Concat (GetTypeSignature (t.GetElementType ()), "*");
else if (t.IsArray) // deal with complex arrays
return string.Concat (GetTypeSignature (t.GetElementType ()), "[]");
else if (t.IsByRef)
return string.Concat (GetTypeSignature (t.GetElementType ()), "&");
}
if (IsGenericTypeSpec (t)) {
StringBuilder sb = new StringBuilder ();
sb.Append (GetTypeSignature (GetGenericTypeDefinition (t)));
sb.Append ("<");
Type [] genArgs = GetGenericArguments (t);
for (int i = 0; i < genArgs.Length; i++) {
if (i > 0)
sb.Append (",");
sb.Append (GetTypeSignature (genArgs [i]));
}
sb.Append (">");
return sb.ToString ();
}
if (IsGenericParameter (t))
return t.Name;
if (t.DeclaringType != null)
return string.Concat (t.DeclaringType.FullName, "/", t.Name);
if (t.Namespace == null || t.Namespace.Length == 0)
return t.Name;
return string.Concat (t.Namespace, ".", t.Name);
}
static bool GetProperty (object o, string prop)
{
SR.PropertyInfo pi = o.GetType ().GetProperty (prop);
if (pi == null)
return false;
return (bool) pi.GetValue (o, null);
}
public static bool IsGenericType (Type t)
{
return GetProperty (t, "IsGenericType");
}
static bool IsGenericParameter (Type t)
{
return GetProperty (t, "IsGenericParameter");
}
static bool IsGenericTypeDefinition (Type t)
{
return GetProperty (t, "IsGenericTypeDefinition");
}
static bool IsGenericTypeSpec (Type t)
{
return IsGenericType (t) && !IsGenericTypeDefinition (t);
}
static Type GetGenericTypeDefinition (Type t)
{
return (Type) t.GetType ().GetMethod ("GetGenericTypeDefinition").Invoke (t, null);
}
static Type [] GetGenericArguments (Type t)
{
return (Type []) t.GetType ().GetMethod ("GetGenericArguments").Invoke (t, null);
}
GenericInstanceType GetGenericType (Type t, TypeReference element, ImportContext context)
{
GenericInstanceType git = new GenericInstanceType (element);
foreach (Type genArg in GetGenericArguments (t))
git.GenericArguments.Add (ImportSystemType (genArg, context));
return git;
}
static bool GenericParameterOfMethod (Type t)
{
return t.GetType ().GetProperty ("DeclaringMethod").GetValue (t, null) != null;
}
static GenericParameter GetGenericParameter (Type t, ImportContext context)
{
int pos = (int) t.GetType ().GetProperty ("GenericParameterPosition").GetValue (t, null);
if (GenericParameterOfMethod (t))
return context.GenericContext.Method.GenericParameters [pos];
else
return context.GenericContext.Type.GenericParameters [pos];
}
TypeReference GetTypeSpec (Type t, ImportContext context)
{
Stack s = new Stack ();
while (t.HasElementType || IsGenericTypeSpec (t)) {
s.Push (t);
if (t.HasElementType)
t = t.GetElementType ();
else if (IsGenericTypeSpec (t)) {
t = (Type) t.GetType ().GetMethod ("GetGenericTypeDefinition").Invoke (t, null);
break;
}
}
TypeReference elementType = ImportSystemType (t, context);
while (s.Count > 0) {
t = (Type) s.Pop ();
if (t.IsPointer)
elementType = new PointerType (elementType);
else if (t.IsArray) // deal with complex arrays
elementType = new ArrayType (elementType);
else if (t.IsByRef)
elementType = new ReferenceType (elementType);
else if (IsGenericTypeSpec (t))
elementType = GetGenericType (t, elementType, context);
else
throw new ReflectionException ("Unknown element type");
}
return elementType;
}
public TypeReference ImportSystemType (Type t, ImportContext context)
{
if (t.HasElementType || IsGenericTypeSpec (t))
return GetTypeSpec (t, context);
if (IsGenericParameter (t))
return GetGenericParameter (t, context);
TypeReference type = m_module.TypeReferences [GetTypeSignature (t)];
if (type != null) {
if (t.IsValueType && !type.IsValueType)
type.IsValueType = true;
return type;
}
AssemblyNameReference asm = ImportAssembly (t.Assembly);
type = new TypeReference (t.Name, t.Namespace, asm, t.IsValueType);
if (IsGenericTypeDefinition (t))
foreach (Type genParam in GetGenericArguments (t))
type.GenericParameters.Add (new GenericParameter (genParam.Name, type));
context.GenericContext.Type = type;
m_module.TypeReferences.Add (type);
return type;
}
static string GetMethodBaseSignature (SR.MethodBase meth, Type declaringType, Type retType)
{
StringBuilder sb = new StringBuilder ();
sb.Append (GetTypeSignature (retType));
sb.Append (' ');
sb.Append (GetTypeSignature (declaringType));
sb.Append ("::");
sb.Append (meth.Name);
if (IsGenericMethodSpec (meth)) {
sb.Append ("<");
Type [] genArgs = GetGenericArguments (meth as SR.MethodInfo);
for (int i = 0; i < genArgs.Length; i++) {
if (i > 0)
sb.Append (",");
sb.Append (GetTypeSignature (genArgs [i]));
}
sb.Append (">");
}
sb.Append ("(");
SR.ParameterInfo [] parameters = meth.GetParameters ();
for (int i = 0; i < parameters.Length; i++) {
if (i > 0)
sb.Append (", ");
sb.Append (GetTypeSignature (parameters [i].ParameterType));
}
sb.Append (")");
return sb.ToString ();
}
static bool IsGenericMethod (SR.MethodBase mb)
{
return GetProperty (mb, "IsGenericMethod");
}
static bool IsGenericMethodDefinition (SR.MethodBase mb)
{
return GetProperty (mb, "IsGenericMethodDefinition");
}
static bool IsGenericMethodSpec (SR.MethodBase mb)
{
return IsGenericMethod (mb) && !IsGenericMethodDefinition (mb);
}
static Type [] GetGenericArguments (SR.MethodInfo mi)
{
return (Type []) mi.GetType ().GetMethod ("GetGenericArguments").Invoke (mi, null);
}
static int GetMetadataToken (SR.MethodInfo mi)
{
return (int) mi.GetType ().GetProperty ("MetadataToken").GetValue (mi, null);
}
MethodReference ImportGenericInstanceMethod (SR.MethodInfo mi, ImportContext context)
{
SR.MethodInfo gmd = (SR.MethodInfo) mi.GetType ().GetMethod ("GetGenericMethodDefinition").Invoke (mi, null);
GenericInstanceMethod gim = new GenericInstanceMethod (
ImportMethodBase (gmd, gmd.ReturnType, context));
foreach (Type genArg in GetGenericArguments (mi))
gim.GenericArguments.Add (ImportSystemType (genArg, context));
return gim;
}
MethodReference ImportMethodBase (SR.MethodBase mb, Type retType, ImportContext context)
{
if (IsGenericMethod (mb) && !IsGenericMethodDefinition (mb))
return ImportGenericInstanceMethod ((SR.MethodInfo) mb, context);
Type originalDecType = mb.DeclaringType;
Type declaringTypeDef = originalDecType;
while (IsGenericTypeSpec (declaringTypeDef))
declaringTypeDef = GetGenericTypeDefinition (declaringTypeDef);
if (mb.DeclaringType != declaringTypeDef && mb is SR.MethodInfo) {
int mt = GetMetadataToken (mb as SR.MethodInfo);
// hack to get the generic method definition from the constructed method
foreach (SR.MethodInfo mi in declaringTypeDef.GetMethods ()) {
if (GetMetadataToken (mi) == mt) {
mb = mi;
retType = mi.ReturnType;
break;
}
}
}
string sig = GetMethodBaseSignature (mb, originalDecType, retType);
MethodReference meth = (MethodReference) GetMemberReference (sig);
if (meth != null)
return meth;
meth = new MethodReference (
mb.Name,
(mb.CallingConvention & SR.CallingConventions.HasThis) > 0,
(mb.CallingConvention & SR.CallingConventions.ExplicitThis) > 0,
MethodCallingConvention.Default); // TODO: get the real callconv
meth.DeclaringType = ImportSystemType (originalDecType, context);
if (IsGenericMethod (mb))
foreach (Type genParam in GetGenericArguments (mb as SR.MethodInfo))
meth.GenericParameters.Add (new GenericParameter (genParam.Name, meth));
context.GenericContext.Method = meth;
context.GenericContext.Type = ImportSystemType (declaringTypeDef, context);
meth.ReturnType.ReturnType = ImportSystemType (retType, context);
SR.ParameterInfo [] parameters = mb.GetParameters ();
for (int i = 0; i < parameters.Length; i++)
meth.Parameters.Add (new ParameterDefinition (
ImportSystemType (parameters [i].ParameterType, context)));
m_module.MemberReferences.Add (meth);
return meth;
}
public MethodReference ImportConstructorInfo (SR.ConstructorInfo ci, ImportContext context)
{
return ImportMethodBase (ci, typeof (void), context);
}
public MethodReference ImportMethodInfo (SR.MethodInfo mi, ImportContext context)
{
return ImportMethodBase (mi, mi.ReturnType, context);
}
static string GetFieldSignature (SR.FieldInfo field)
{
StringBuilder sb = new StringBuilder ();
sb.Append (GetTypeSignature (field.FieldType));
sb.Append (' ');
sb.Append (GetTypeSignature (field.DeclaringType));
sb.Append ("::");
sb.Append (field.Name);
return sb.ToString ();
}
public FieldReference ImportFieldInfo (SR.FieldInfo fi, ImportContext context)
{
string sig = GetFieldSignature (fi);
FieldReference f = (FieldReference) GetMemberReference (sig);
if (f != null)
return f;
f = new FieldReference (
fi.Name,
ImportSystemType (fi.DeclaringType, context),
ImportSystemType (fi.FieldType, context));
m_module.MemberReferences.Add (f);
return f;
}
MemberReference GetMemberReference (string signature)
{
foreach (MemberReference reference in m_module.MemberReferences)
if (reference.ToString () == signature)
return reference;
return null;
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Concurrency;
using Orleans.Configuration;
using Orleans.GrainReferences;
using Orleans.Metadata;
using Orleans.Runtime.Placement;
using Orleans.Serialization.Invocation;
namespace Orleans.Runtime
{
/// <summary>
/// The central point for creating grain contexts.
/// </summary>
public sealed class GrainContextActivator
{
private readonly object _lockObj = new object();
private readonly IGrainContextActivatorProvider[] _activatorProviders;
private readonly IConfigureGrainContextProvider[] _configuratorProviders;
private readonly GrainPropertiesResolver _resolver;
private ImmutableDictionary<GrainType, ActivatorEntry> _activators = ImmutableDictionary<GrainType, ActivatorEntry>.Empty;
public GrainContextActivator(
IEnumerable<IGrainContextActivatorProvider> providers,
IEnumerable<IConfigureGrainContextProvider> configureContextActions,
GrainPropertiesResolver grainPropertiesResolver)
{
_resolver = grainPropertiesResolver;
_activatorProviders = providers.ToArray();
_configuratorProviders = configureContextActions.ToArray();
}
/// <summary>
/// Creates a new grain context for the provided grain address.
/// </summary>
public IGrainContext CreateInstance(ActivationAddress address)
{
var grainId = address.Grain;
if (!_activators.TryGetValue(grainId.Type, out var activator))
{
activator = this.CreateActivator(grainId.Type);
}
var result = activator.Activator.CreateContext(address);
foreach (var configure in activator.ConfigureActions)
{
configure.Configure(result);
}
return result;
}
private ActivatorEntry CreateActivator(GrainType grainType)
{
lock (_lockObj)
{
if (!_activators.TryGetValue(grainType, out var configuredActivator))
{
IGrainContextActivator unconfiguredActivator = null;
foreach (var provider in this._activatorProviders)
{
if (provider.TryGet(grainType, out unconfiguredActivator))
{
break;
}
}
if (unconfiguredActivator is null)
{
throw new InvalidOperationException($"Unable to find an {nameof(IGrainContextActivatorProvider)} for grain type {grainType}");
}
var properties = _resolver.GetGrainProperties(grainType);
List<IConfigureGrainContext> configureActions = new List<IConfigureGrainContext>();
foreach (var provider in _configuratorProviders)
{
if (provider.TryGetConfigurator(grainType, properties, out var configurator))
{
configureActions.Add(configurator);
}
}
var applicableConfigureActions = configureActions.Count > 0 ? configureActions.ToArray() : Array.Empty<IConfigureGrainContext>();
configuredActivator = new ActivatorEntry(unconfiguredActivator, applicableConfigureActions);
_activators = _activators.SetItem(grainType, configuredActivator);
}
return configuredActivator;
}
}
private readonly struct ActivatorEntry
{
public ActivatorEntry(
IGrainContextActivator activator,
IConfigureGrainContext[] configureActions)
{
this.Activator = activator;
this.ConfigureActions = configureActions;
}
public IGrainContextActivator Activator { get; }
public IConfigureGrainContext[] ConfigureActions { get; }
}
}
/// <summary>
/// Provides a <see cref="IGrainContextActivator"/> for a specified grain type.
/// </summary>
public interface IGrainContextActivatorProvider
{
/// <summary>
/// Returns a grain context activator for the given grain type.
/// </summary>
bool TryGet(GrainType grainType, out IGrainContextActivator activator);
}
/// <summary>
/// Creates a grain context for the given grain address.
/// </summary>
public interface IGrainContextActivator
{
/// <summary>
/// Creates a grain context for the given grain address.
/// </summary>
public IGrainContext CreateContext(ActivationAddress address);
}
/// <summary>
/// Provides a <see cref="IConfigureGrainContext"/> instance for the provided grain type.
/// </summary>
public interface IConfigureGrainContextProvider
{
/// <summary>
/// Provides a <see cref="IConfigureGrainContext"/> instance for the provided grain type.
/// </summary>
bool TryGetConfigurator(GrainType grainType, GrainProperties properties, out IConfigureGrainContext configurator);
}
/// <summary>
/// Configures the provided grain context.
/// </summary>
public interface IConfigureGrainContext
{
/// <summary>
/// Configures the provided grain context.
/// </summary>
void Configure(IGrainContext context);
}
/// <summary>
/// Resolves components which are common to all instances of a given grain type.
/// </summary>
public class GrainTypeSharedContextResolver
{
private readonly ConcurrentDictionary<GrainType, GrainTypeSharedContext> _components = new();
private readonly IConfigureGrainTypeComponents[] _configurators;
private readonly GrainPropertiesResolver _grainPropertiesResolver;
private readonly GrainReferenceActivator _grainReferenceActivator;
private readonly Func<GrainType, GrainTypeSharedContext> _createFunc;
private readonly IClusterManifestProvider _clusterManifestProvider;
private readonly GrainClassMap _grainClassMap;
private readonly IOptions<SiloMessagingOptions> _messagingOptions;
private readonly IOptions<GrainCollectionOptions> _collectionOptions;
private readonly PlacementStrategyResolver _placementStrategyResolver;
private readonly IGrainRuntime _grainRuntime;
private readonly ILogger<Grain> _logger;
private readonly IServiceProvider _serviceProvider;
public GrainTypeSharedContextResolver(
IEnumerable<IConfigureGrainTypeComponents> configurators,
GrainPropertiesResolver grainPropertiesResolver,
GrainReferenceActivator grainReferenceActivator,
IClusterManifestProvider clusterManifestProvider,
GrainClassMap grainClassMap,
PlacementStrategyResolver placementStrategyResolver,
IOptions<SiloMessagingOptions> messagingOptions,
IOptions<GrainCollectionOptions> collectionOptions,
IGrainRuntime grainRuntime,
ILogger<Grain> logger,
IServiceProvider serviceProvider)
{
_configurators = configurators.ToArray();
_grainPropertiesResolver = grainPropertiesResolver;
_grainReferenceActivator = grainReferenceActivator;
_clusterManifestProvider = clusterManifestProvider;
_grainClassMap = grainClassMap;
_placementStrategyResolver = placementStrategyResolver;
_messagingOptions = messagingOptions;
_collectionOptions = collectionOptions;
_grainRuntime = grainRuntime;
_logger = logger;
_serviceProvider = serviceProvider;
_createFunc = Create;
}
/// <summary>
/// Returns shared grain components for the provided grain type.
/// </summary>
public GrainTypeSharedContext GetComponents(GrainType grainType) => _components.GetOrAdd(grainType, _createFunc);
private GrainTypeSharedContext Create(GrainType grainType)
{
var result = new GrainTypeSharedContext(
grainType,
_clusterManifestProvider,
_grainClassMap,
_placementStrategyResolver,
_messagingOptions,
_collectionOptions,
_grainRuntime,
_logger,
_grainReferenceActivator,
_serviceProvider);
var properties = _grainPropertiesResolver.GetGrainProperties(grainType);
foreach (var configurator in _configurators)
{
configurator.Configure(grainType, properties, result);
}
return result;
}
}
/// <summary>
/// Configures shared components which are common for all instances of a given grain type.
/// </summary>
public interface IConfigureGrainTypeComponents
{
/// <summary>
/// Configures shared components which are common for all instances of a given grain type.
/// </summary>
void Configure(GrainType grainType, GrainProperties properties, GrainTypeSharedContext shared);
}
internal class ReentrantSharedComponentsConfigurator : IConfigureGrainTypeComponents
{
public void Configure(GrainType grainType, GrainProperties properties, GrainTypeSharedContext shared)
{
if (properties.Properties.TryGetValue(WellKnownGrainTypeProperties.Reentrant, out var value) && bool.Parse(value))
{
var component = shared.GetComponent<GrainCanInterleave>();
if (component is null)
{
component = new GrainCanInterleave();
shared.SetComponent<GrainCanInterleave>(component);
}
component.MayInterleavePredicates.Add(_ => true);
}
}
}
internal class MayInterleaveConfiguratorProvider : IConfigureGrainContextProvider
{
private readonly GrainClassMap _grainClassMap;
public MayInterleaveConfiguratorProvider(GrainClassMap grainClassMap)
{
_grainClassMap = grainClassMap;
}
public bool TryGetConfigurator(GrainType grainType, GrainProperties properties, out IConfigureGrainContext configurator)
{
if (properties.Properties.TryGetValue(WellKnownGrainTypeProperties.MayInterleavePredicate, out var value)
&& _grainClassMap.TryGetGrainClass(grainType, out var grainClass))
{
var predicate = GetMayInterleavePredicate(grainClass);
configurator = new MayInterleaveConfigurator(message => predicate(message.BodyObject as IInvokable));
return true;
}
configurator = null;
return false;
}
/// <summary>
/// Returns interleave predicate depending on whether class is marked with <see cref="MayInterleaveAttribute"/> or not.
/// </summary>
/// <param name="grainType">Grain class.</param>
private static Func<IInvokable, bool> GetMayInterleavePredicate(Type grainType)
{
var attribute = grainType.GetCustomAttribute<MayInterleaveAttribute>();
if (attribute is null)
{
return null;
}
var callbackMethodName = attribute.CallbackMethodName;
var method = grainType.GetMethod(callbackMethodName, BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
if (method == null)
{
throw new InvalidOperationException(
$"Class {grainType.FullName} doesn't declare public static method " +
$"with name {callbackMethodName} specified in MayInterleave attribute");
}
if (method.ReturnType != typeof(bool) ||
method.GetParameters().Length != 1 ||
method.GetParameters()[0].ParameterType != typeof(IInvokable))
{
throw new InvalidOperationException(
$"Wrong signature of callback method {callbackMethodName} " +
$"specified in MayInterleave attribute for grain class {grainType.FullName}. \n" +
$"Expected: public static bool {callbackMethodName}(IInvokable req)");
}
var parameter = Expression.Parameter(typeof(IInvokable));
var call = Expression.Call(null, method, parameter);
var predicate = Expression.Lambda<Func<IInvokable, bool>>(call, parameter).Compile();
return predicate;
}
}
internal class MayInterleaveConfigurator : IConfigureGrainContext
{
private readonly Func<Message, bool> _mayInterleavePredicate;
public MayInterleaveConfigurator(Func<Message, bool> mayInterleavePredicate)
{
_mayInterleavePredicate = mayInterleavePredicate;
}
public void Configure(IGrainContext context)
{
var component = context.GetComponent<GrainCanInterleave>();
if (component is null)
{
component = new GrainCanInterleave();
context.SetComponent<GrainCanInterleave>(component);
}
component.MayInterleavePredicates.Add(_mayInterleavePredicate);
}
}
internal class GrainCanInterleave
{
public List<Func<Message, bool>> MayInterleavePredicates { get; } = new List<Func<Message, bool>>();
public bool MayInterleave(Message message)
{
foreach (var predicate in this.MayInterleavePredicates)
{
if (predicate(message)) return true;
}
return false;
}
}
internal class ConfigureDefaultGrainActivator : IConfigureGrainTypeComponents
{
private readonly GrainClassMap _grainClassMap;
private readonly ConstructorArgumentFactory _constructorArgumentFactory;
public ConfigureDefaultGrainActivator(GrainClassMap grainClassMap, IServiceProvider serviceProvider)
{
_constructorArgumentFactory = new ConstructorArgumentFactory(serviceProvider);
_grainClassMap = grainClassMap;
}
public void Configure(GrainType grainType, GrainProperties properties, GrainTypeSharedContext shared)
{
if (shared.GetComponent<IGrainActivator>() is object) return;
if (!_grainClassMap.TryGetGrainClass(grainType, out var grainClass))
{
return;
}
var argumentFactory = _constructorArgumentFactory.CreateFactory(grainClass);
var createGrainInstance = ActivatorUtilities.CreateFactory(grainClass, argumentFactory.ArgumentTypes);
var instanceActivator = new DefaultGrainActivator(createGrainInstance, argumentFactory);
shared.SetComponent<IGrainActivator>(instanceActivator);
}
internal class DefaultGrainActivator : IGrainActivator
{
private readonly ObjectFactory _factory;
private readonly ConstructorArgumentFactory.ArgumentFactory _argumentFactory;
public DefaultGrainActivator(ObjectFactory factory, ConstructorArgumentFactory.ArgumentFactory argumentFactory)
{
_factory = factory;
_argumentFactory = argumentFactory;
}
public object CreateInstance(IGrainContext context)
{
var args = _argumentFactory.CreateArguments(context);
return _factory(context.ActivationServices, args);
}
public async ValueTask DisposeInstance(IGrainContext context, object instance)
{
switch (instance)
{
case IAsyncDisposable asyncDisposable:
await asyncDisposable.DisposeAsync();
break;
case IDisposable disposable:
disposable.Dispose();
break;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using xsc = DotNetXmlSwfChart;
namespace testWeb.tests
{
public class StackedColumnOne : ChartTestBase
{
#region ChartInclude
public override DotNetXmlSwfChart.ChartHTML ChartInclude
{
get
{
DotNetXmlSwfChart.ChartHTML chartHtml = new DotNetXmlSwfChart.ChartHTML();
chartHtml.height = 300;
chartHtml.bgColor = "aab0bb";
chartHtml.flashFile = "charts/charts.swf";
chartHtml.libraryPath = "charts/charts_library";
chartHtml.xmlSource = "xmlData.aspx";
return chartHtml;
}
}
#endregion
#region Chart
public override xsc.Chart Chart
{
get
{
xsc.Chart chart = new xsc.Chart();
chart.AddChartType(xsc.XmlSwfChartType.ColumnStacked);
chart.AxisValue = SetAxisValue();
chart.ChartBorder = SetChartBorder();
chart.Data = SetChartData();
chart.ChartGridH = SetChartGridH();
chart.ChartGridV = SetChartGridV();
chart.ChartRectangle = SetChartRectangle();
chart.ChartTransition = SetChartTransition();
chart.DrawTexts = SetDrawTexts();
chart.LegendLabel = SetLegendLabel();
chart.LegendRectangle = SetLegendRectangle();
chart.LegendTransition = SetLegendTransition();
chart.SeriesColors = SetSeriesColors();
return chart;
}
}
#endregion
#region Properties
#region SetAxisValue()
private xsc.AxisValue SetAxisValue()
{
xsc.AxisValue av = new xsc.AxisValue();
av.Font = "Arial";
av.Bold = true;
av.Size = 10;
av.Color = "000000";
av.Alpha = 50;
av.Steps = 6;
av.Prefix = "";
av.Suffix = "";
av.Decimals = 0;
av.Separator = "";
av.ShowMin = true;
return av;
}
#endregion
#region SetChartBorder()
private xsc.ChartBorder SetChartBorder()
{
xsc.ChartBorder cb = new xsc.ChartBorder();
cb.Color = "000000";
cb.TopThickness = 0;
cb.BottomThickness = 3;
cb.LeftThickness = 0;
cb.RightThickness = 0;
return cb;
}
#endregion
#region SetChartData()
private xsc.ChartData SetChartData()
{
xsc.ChartData cd = new xsc.ChartData();
cd.AddDataPoint(new xsc.ChartDataPoint("region A", "2005", -15));
cd.AddDataPoint(new xsc.ChartDataPoint("region A", "2006", 45));
cd.AddDataPoint(new xsc.ChartDataPoint("region A", "2007", 100));
cd.AddDataPoint(new xsc.ChartDataPoint("region B", "2005", 25));
cd.AddDataPoint(new xsc.ChartDataPoint("region B", "2006", 65));
cd.AddDataPoint(new xsc.ChartDataPoint("region B", "2007", 80));
cd.AddDataPoint(new xsc.ChartDataPoint("region C", "2005", 10));
cd.AddDataPoint(new xsc.ChartDataPoint("region C", "2006", 30));
cd.AddDataPoint(new xsc.ChartDataPoint("region C", "2007", 5));
return cd;
}
#endregion
#region SetChartGridH()
private xsc.ChartGrid SetChartGridH()
{
xsc.ChartGrid cg = new xsc.ChartGrid(xsc.ChartGridType.Horizontal);
cg.Alpha = 20;
cg.Color = "000000";
cg.Thickness = 1;
cg.GridLineType = xsc.ChartGridLineType.solid;
return cg;
}
#endregion
#region SetChartGridV()
private xsc.ChartGrid SetChartGridV()
{
xsc.ChartGrid cg = new xsc.ChartGrid(xsc.ChartGridType.Vertical);
cg.Alpha = 20;
cg.Color = "000000";
cg.Thickness = 1;
cg.GridLineType = xsc.ChartGridLineType.dashed;
return cg;
}
#endregion
#region SetChartRectangle()
private xsc.ChartRectangle SetChartRectangle()
{
xsc.ChartRectangle cr = new xsc.ChartRectangle();
cr.X = 125;
cr.Y = 65;
cr.Width = 250;
cr.Height = 200;
cr.PositiveColor = "ffffff";
cr.NegativeColor = "000000";
cr.PositiveAlpha = 75;
cr.NegativeAlpha = 15;
return cr;
}
#endregion
#region SetChartTransition()
private xsc.ChartTransition SetChartTransition()
{
xsc.ChartTransition ct = new xsc.ChartTransition();
ct.TransitionType = xsc.TransitionType.drop;
ct.Delay = 0;
ct.Duration = 2;
ct.Order = xsc.TransitionOrder.series;
return ct;
}
#endregion
#region SetDrawTexts()
private List<xsc.DrawText> SetDrawTexts()
{
List<xsc.DrawText> text = new List<xsc.DrawText>();
xsc.DrawText dt = new xsc.DrawText();
dt.Transition = xsc.TransitionType.slide_up;
dt.Delay = 1;
dt.Duration = 0.5;
dt.Color = "000033";
dt.Alpha = 15;
dt.Font = "Arial";
dt.Rotation = -90;
dt.Bold = true;
dt.Size = 64;
dt.X = 0;
dt.Y = 295;
dt.Width = 300;
dt.Height = 50;
dt.HAlign = xsc.TextHAlign.right;
dt.VAlign = xsc.TextVAlign.middle;
dt.Text = "GROWTH";
text.Add(dt);
dt = new xsc.DrawText();
dt.Transition = xsc.TransitionType.slide_up;
dt.Delay = 1;
dt.Duration = 0.5;
dt.Color = "ffffff";
dt.Alpha = 40;
dt.Font = "Arial";
dt.Rotation = -90;
dt.Bold = true;
dt.Size = 25;
dt.X = 30;
dt.Y = 300;
dt.Width = 300;
dt.Height = 50;
dt.HAlign = xsc.TextHAlign.right;
dt.VAlign = xsc.TextVAlign.middle;
dt.Text = "report";
text.Add(dt);
return text;
}
#endregion
#region SetLegendLabel()
private xsc.LegendLabel SetLegendLabel()
{
xsc.LegendLabel ll = new xsc.LegendLabel();
ll.Layout = xsc.LegendLabelLayout.horizontal;
ll.Font = "Arial";
ll.Bold = true;
ll.Size = 13;
ll.Color = "444466";
ll.Alpha = 90;
return ll;
}
#endregion
#region SetLegendRectangle()
private xsc.LegendRectangle SetLegendRectangle()
{
xsc.LegendRectangle lr = new xsc.LegendRectangle();
lr.X = 125;
lr.Y = 10;
lr.Width = 250;
lr.Height = 10;
lr.Margin = 5;
lr.FillColor = "ffffff";
lr.FillAlpha = 35;
lr.LineAlpha = 0;
lr.LineThickness = 0;
return lr;
}
#endregion
#region SetLegendTransition()
private xsc.LegendTransition SetLegendTransition()
{
xsc.LegendTransition lt = new xsc.LegendTransition();
lt.Type = xsc.TransitionType.slide_left;
lt.Delay = 0;
lt.Duration = 1;
return lt;
}
#endregion
#region SetSeriesColors()
private List<string> SetSeriesColors()
{
List<string> c = new List<string>();
c.Add("4e627c");
c.Add("844648");
c.Add("c89341");
return c;
}
#endregion
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.