context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using Xunit; namespace System.Linq.Expressions.Tests { public class MemberBindTests { private class PropertyAndFields { #pragma warning disable 649 // Assigned through expressions. public string StringProperty { get; set; } public string StringField; public readonly string ReadonlyStringField; public string ReadonlyStringProperty { get { return ""; } } public static string StaticStringProperty { get; set; } public static string StaticStringField; public const string ConstantString = "Constant"; #pragma warning restore 649 } public class Inner { public int Value { get; set; } } public class Outer { public Inner InnerProperty { get; set; } = new Inner(); public Inner InnerField = new Inner(); public Inner ReadonlyInnerProperty { get; } = new Inner(); public Inner WriteonlyInnerProperty { set { } } public readonly Inner ReadonlyInnerField = new Inner(); public static Inner StaticInnerProperty { get; set; } = new Inner(); public static Inner StaticInnerField = new Inner(); public static Inner StaticReadonlyInnerProperty { get; } = new Inner(); public static readonly Inner StaticReadonlyInnerField = new Inner(); public static Inner StaticWriteonlyInnerProperty { set { } } } [Fact] public void NullMethodOrMemberInfo() { AssertExtensions.Throws<ArgumentNullException>("member", () => Expression.MemberBind(default(MemberInfo))); AssertExtensions.Throws<ArgumentNullException>("member", () => Expression.MemberBind(default(MemberInfo), Enumerable.Empty<MemberBinding>())); AssertExtensions.Throws<ArgumentNullException>("propertyAccessor", () => Expression.MemberBind(default(MethodInfo))); AssertExtensions.Throws<ArgumentNullException>("propertyAccessor", () => Expression.MemberBind(default(MethodInfo), Enumerable.Empty<MemberBinding>())); } [Fact] public void NullBindings() { PropertyInfo mem = typeof(PropertyAndFields).GetProperty(nameof(PropertyAndFields.StringProperty)); MethodInfo meth = mem.GetGetMethod(); AssertExtensions.Throws<ArgumentNullException>("bindings", () => Expression.MemberBind(mem, default(MemberBinding[]))); AssertExtensions.Throws<ArgumentNullException>("bindings", () => Expression.MemberBind(mem, default(IEnumerable<MemberBinding>))); AssertExtensions.Throws<ArgumentNullException>("bindings", () => Expression.MemberBind(meth, default(MemberBinding[]))); AssertExtensions.Throws<ArgumentNullException>("bindings", () => Expression.MemberBind(meth, default(IEnumerable<MemberBinding>))); } [Fact] public void NullBindingInBindings() { PropertyInfo mem = typeof(PropertyAndFields).GetProperty(nameof(PropertyAndFields.StringProperty)); MethodInfo meth = mem.GetGetMethod(); AssertExtensions.Throws<ArgumentNullException>("bindings", () => Expression.MemberBind(mem, default(MemberBinding))); AssertExtensions.Throws<ArgumentNullException>("bindings", () => Expression.MemberBind(mem, Enumerable.Repeat<MemberBinding>(null, 1))); AssertExtensions.Throws<ArgumentNullException>("bindings", () => Expression.MemberBind(meth, default(MemberBinding))); AssertExtensions.Throws<ArgumentNullException>("bindings", () => Expression.MemberBind(meth, Enumerable.Repeat<MemberBinding>(null, 1))); } [Fact] public void BindMethodMustBeProperty() { MemberInfo toString = typeof(object).GetMember(nameof(ToString))[0]; MethodInfo toStringMeth = typeof(object).GetMethod(nameof(ToString)); AssertExtensions.Throws<ArgumentException>("member", () => Expression.MemberBind(toString)); AssertExtensions.Throws<ArgumentException>("member", () => Expression.MemberBind(toString, Enumerable.Empty<MemberBinding>())); AssertExtensions.Throws<ArgumentException>("propertyAccessor", () => Expression.MemberBind(toStringMeth)); AssertExtensions.Throws<ArgumentException>("propertyAccessor", () => Expression.MemberBind(toStringMeth, Enumerable.Empty<MemberBinding>())); } [Fact] public void MemberBindingMustBeMemberOfType() { MemberMemberBinding bind = Expression.MemberBind( typeof(Outer).GetProperty(nameof(Outer.InnerProperty)), Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(3)) ); NewExpression newExp = Expression.New(typeof(PropertyAndFields)); Assert.Throws<ArgumentException>(() => Expression.MemberInit(newExp, bind)); } [Fact] public void UpdateSameReturnsSame() { MemberAssignment bind = Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(3)); MemberMemberBinding memberBind = Expression.MemberBind(typeof(Outer).GetProperty(nameof(Outer.InnerProperty)), bind); Assert.Same(memberBind, memberBind.Update(Enumerable.Repeat(bind, 1))); } [Fact] public void UpdateDifferentReturnsDifferent() { MemberAssignment bind = Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(3)); MemberMemberBinding memberBind = Expression.MemberBind(typeof(Outer).GetProperty(nameof(Outer.InnerProperty)), bind); Assert.NotSame(memberBind, memberBind.Update(new[] {Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(3))})); Assert.NotSame(memberBind, memberBind.Update(Enumerable.Empty<MemberBinding>())); } [Fact] public void UpdateNullThrows() { MemberAssignment bind = Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(3)); MemberMemberBinding memberBind = Expression.MemberBind(typeof(Outer).GetProperty(nameof(Outer.InnerProperty)), bind); AssertExtensions.Throws<ArgumentNullException>("bindings", () => memberBind.Update(null)); } [Fact] public void UpdateDoesntRepeatEnumeration() { MemberAssignment bind = Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(3)); MemberMemberBinding memberBind = Expression.MemberBind(typeof(Outer).GetProperty(nameof(Outer.InnerProperty)), bind); Assert.NotSame(memberBind, memberBind.Update(new RunOnceEnumerable<MemberBinding>(new[] { Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(3)) }))); } [Theory, ClassData(typeof(CompilationTypes))] public void InnerProperty(bool useInterpreter) { Expression<Func<Outer>> exp = Expression.Lambda<Func<Outer>>( Expression.MemberInit( Expression.New(typeof(Outer)), Expression.MemberBind( typeof(Outer).GetProperty(nameof(Outer.InnerProperty)), Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(3)) ) ) ); Func<Outer> func = exp.Compile(useInterpreter); Assert.Equal(3, func().InnerProperty.Value); } [Theory, ClassData(typeof(CompilationTypes))] public void InnerField(bool useInterpreter) { Expression<Func<Outer>> exp = Expression.Lambda<Func<Outer>>( Expression.MemberInit( Expression.New(typeof(Outer)), Expression.MemberBind( typeof(Outer).GetField(nameof(Outer.InnerField)), Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(4)) ) ) ); Func<Outer> func = exp.Compile(useInterpreter); Assert.Equal(4, func().InnerField.Value); } [Theory, ClassData(typeof(CompilationTypes))] public void StaticInnerProperty(bool useInterpreter) { Expression<Func<Outer>> exp = Expression.Lambda<Func<Outer>>( Expression.MemberInit( Expression.New(typeof(Outer)), Expression.MemberBind( typeof(Outer).GetProperty(nameof(Outer.StaticInnerProperty)), Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(5)) ) ) ); Assert.Throws<InvalidProgramException>(() => exp.Compile(useInterpreter)); } [Theory, ClassData(typeof(CompilationTypes))] public void StaticInnerField(bool useInterpreter) { Expression<Func<Outer>> exp = Expression.Lambda<Func<Outer>>( Expression.MemberInit( Expression.New(typeof(Outer)), Expression.MemberBind( typeof(Outer).GetField(nameof(Outer.StaticInnerField)), Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(6)) ) ) ); Assert.Throws<InvalidProgramException>(() => exp.Compile(useInterpreter)); } [Theory, ClassData(typeof(CompilationTypes))] public void ReadonlyInnerProperty(bool useInterpreter) { Expression<Func<Outer>> exp = Expression.Lambda<Func<Outer>>( Expression.MemberInit( Expression.New(typeof(Outer)), Expression.MemberBind( typeof(Outer).GetProperty(nameof(Outer.ReadonlyInnerProperty)), Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(7)) ) ) ); Func<Outer> func = exp.Compile(useInterpreter); Assert.Equal(7, func().ReadonlyInnerProperty.Value); } [Theory, ClassData(typeof(CompilationTypes))] public void ReadonlyInnerField(bool useInterpreter) { Expression<Func<Outer>> exp = Expression.Lambda<Func<Outer>>( Expression.MemberInit( Expression.New(typeof(Outer)), Expression.MemberBind( typeof(Outer).GetField(nameof(Outer.ReadonlyInnerField)), Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(8)) ) ) ); Func<Outer> func = exp.Compile(useInterpreter); Assert.Equal(8, func().ReadonlyInnerField.Value); } [Theory, ClassData(typeof(CompilationTypes))] public void StaticReadonlyInnerProperty(bool useInterpreter) { Expression<Func<Outer>> exp = Expression.Lambda<Func<Outer>>( Expression.MemberInit( Expression.New(typeof(Outer)), Expression.MemberBind( typeof(Outer).GetProperty(nameof(Outer.StaticReadonlyInnerProperty)), Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(5)) ) ) ); Assert.Throws<InvalidProgramException>(() => exp.Compile(useInterpreter)); } [Theory, ClassData(typeof(CompilationTypes))] public void StaticReadonlyInnerField(bool useInterpreter) { Expression<Func<Outer>> exp = Expression.Lambda<Func<Outer>>( Expression.MemberInit( Expression.New(typeof(Outer)), Expression.MemberBind( typeof(Outer).GetField(nameof(Outer.StaticReadonlyInnerField)), Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(6)) ) ) ); Assert.Throws<InvalidProgramException>(() => exp.Compile(useInterpreter)); } #if FEATURE_COMPILE [Fact] public void GlobalMethod() { ModuleBuilder module = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run).DefineDynamicModule("Module"); MethodBuilder globalMethod = module.DefineGlobalMethod("GlobalMethod", MethodAttributes.Public | MethodAttributes.Static, typeof(int), Type.EmptyTypes); globalMethod.GetILGenerator().Emit(OpCodes.Ret); module.CreateGlobalFunctions(); MethodInfo globalMethodInfo = module.GetMethod(globalMethod.Name); AssertExtensions.Throws<ArgumentException>("propertyAccessor", () => Expression.MemberBind(globalMethodInfo)); } #endif public void WriteOnlyInnerProperty() { MemberAssignment bind = Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(0)); PropertyInfo property = typeof(Outer).GetProperty(nameof(Outer.WriteonlyInnerProperty)); Assert.Throws<ArgumentException>(() => Expression.MemberBind(property, bind)); } public void StaticWriteOnlyInnerProperty() { MemberAssignment bind = Expression.Bind(typeof(Inner).GetProperty(nameof(Inner.Value)), Expression.Constant(0)); PropertyInfo property = typeof(Outer).GetProperty(nameof(Outer.StaticWriteonlyInnerProperty)); Assert.Throws<ArgumentException>(() => Expression.MemberBind(property, bind)); } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Threading; using NuGet.Resources; namespace NuGet { public static class FileSystemExtensions { public static IEnumerable<string> GetFiles(this IFileSystem fileSystem, string path, string filter) { return fileSystem.GetFiles(path, filter, recursive: false); } public static void AddFiles(this IFileSystem fileSystem, IEnumerable<IPackageFile> files) { AddFiles(fileSystem, files, String.Empty); } public static void AddFiles(this IFileSystem fileSystem, IEnumerable<IPackageFile> files, string rootDir) { AddFiles(fileSystem, files, rootDir, preserveFilePath: true); } /// <summary> /// Add the files to the specified FileSystem /// </summary> /// <param name="fileSystem">The file system.</param> /// <param name="files">The files to add to FileSystem.</param> /// <param name="rootDir">The directory of the FileSystem to copy the files to.</param> /// <param name="preserveFilePath">if set to <c>true</c> preserve full path of the copies files. Otherwise, /// all files with be copied to the <paramref name="rootDir"/>.</param> public static void AddFiles(this IFileSystem fileSystem, IEnumerable<IPackageFile> files, string rootDir, bool preserveFilePath) { foreach (IPackageFile file in files) { string path = Path.Combine(rootDir, preserveFilePath ? file.Path : Path.GetFileName(file.Path)); fileSystem.AddFileWithCheck(path, file.GetStream); } } internal static void DeleteFiles(this IFileSystem fileSystem, IEnumerable<IPackageFile> files) { DeleteFiles(fileSystem, files, String.Empty); } internal static void DeleteFiles(this IFileSystem fileSystem, IEnumerable<IPackageFile> files, string rootDir) { // First get all directories that contain files var directoryLookup = files.ToLookup(p => Path.GetDirectoryName(p.Path)); // Get all directories that this package may have added var directories = from grouping in directoryLookup from directory in GetDirectories(grouping.Key) orderby directory.Length descending select directory; // Remove files from every directory foreach (var directory in directories) { var directoryFiles = directoryLookup.Contains(directory) ? directoryLookup[directory] : Enumerable.Empty<IPackageFile>(); string dirPath = Path.Combine(rootDir, directory); if (!fileSystem.DirectoryExists(dirPath)) { continue; } foreach (var file in directoryFiles) { string path = Path.Combine(rootDir, file.Path); fileSystem.DeleteFileSafe(path, file.GetStream); } // If the directory is empty then delete it if (!fileSystem.GetFilesSafe(dirPath).Any() && !fileSystem.GetDirectoriesSafe(dirPath).Any()) { fileSystem.DeleteDirectorySafe(dirPath, recursive: false); } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to log an exception as a warning and move on")] internal static IEnumerable<string> GetDirectoriesSafe(this IFileSystem fileSystem, string path) { try { return fileSystem.GetDirectories(path); } catch (Exception e) { fileSystem.Logger.Log(MessageLevel.Warning, e.Message); } return Enumerable.Empty<string>(); } internal static IEnumerable<string> GetFilesSafe(this IFileSystem fileSystem, string path) { return GetFilesSafe(fileSystem, path, "*.*"); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to log an exception as a warning and move on")] internal static IEnumerable<string> GetFilesSafe(this IFileSystem fileSystem, string path, string filter) { try { return fileSystem.GetFiles(path, filter); } catch (Exception e) { fileSystem.Logger.Log(MessageLevel.Warning, e.Message); } return Enumerable.Empty<string>(); } internal static void DeleteDirectorySafe(this IFileSystem fileSystem, string path, bool recursive) { DoSafeAction(() => fileSystem.DeleteDirectory(path, recursive), fileSystem.Logger); } internal static void DeleteFileSafe(this IFileSystem fileSystem, string path) { DoSafeAction(() => fileSystem.DeleteFile(path), fileSystem.Logger); } internal static void DeleteFileSafe(this IFileSystem fileSystem, string path, Func<Stream> streamFactory) { // Only delete the file if it exists and the checksum is the same if (fileSystem.FileExists(path)) { bool contentEqual; using (Stream stream = streamFactory(), fileStream = fileSystem.OpenFile(path)) { contentEqual = stream.ContentEquals(fileStream); } if (contentEqual) { fileSystem.DeleteFileSafe(path); } else { // This package installed a file that was modified so warn the user fileSystem.Logger.Log(MessageLevel.Warning, NuGetResources.Warning_FileModified, path); } } } internal static void AddFileWithCheck(this IFileSystem fileSystem, string path, Func<Stream> streamFactory) { if (fileSystem.FileExists(path)) { fileSystem.Logger.Log(MessageLevel.Warning, NuGetResources.Warning_FileAlreadyExists, path); } else { using (Stream stream = streamFactory()) { fileSystem.AddFile(path, stream); } } } [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "The caller is responsible for closing the stream")] internal static void AddFileWithCheck(this IFileSystem fileSystem, string path, Action<Stream> write) { fileSystem.AddFileWithCheck(path, () => { var stream = new MemoryStream(); write(stream); stream.Seek(0, SeekOrigin.Begin); return stream; }); } internal static void AddFile(this IFileSystem fileSystem, string path, Action<Stream> write) { using (var stream = new MemoryStream()) { write(stream); stream.Seek(0, SeekOrigin.Begin); fileSystem.AddFile(path, stream); } } internal static IEnumerable<string> GetDirectories(string path) { foreach (var index in IndexOfAll(path, Path.DirectorySeparatorChar)) { yield return path.Substring(0, index); } yield return path; } private static IEnumerable<int> IndexOfAll(string value, char ch) { int index = -1; do { index = value.IndexOf(ch, index + 1); if (index >= 0) { yield return index; } } while (index >= 0); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want to log an exception as a warning and move on")] private static void DoSafeAction(Action action, ILogger logger) { try { Attempt(action); } catch (Exception e) { logger.Log(MessageLevel.Warning, e.Message); } } private static void Attempt(Action action, int retries = 3, int delayBeforeRetry = 150) { while (retries > 0) { try { action(); break; } catch { retries--; if (retries == 0) { throw; } } Thread.Sleep(delayBeforeRetry); } } } }
using System; using System.Collections.Generic; using System.Linq; using Nop.Core; using Nop.Core.Data; using Nop.Core.Domain.Common; using Nop.Core.Domain.Customers; using Nop.Core.Domain.Logging; using Nop.Data; namespace Nop.Services.Logging { /// <summary> /// Default logger /// </summary> public partial class DefaultLogger : ILogger { #region Fields private readonly IRepository<Log> _logRepository; private readonly IWebHelper _webHelper; private readonly IDbContext _dbContext; private readonly IDataProvider _dataProvider; private readonly CommonSettings _commonSettings; #endregion #region Ctor /// <summary> /// Ctor /// </summary> /// <param name="logRepository">Log repository</param> /// <param name="webHelper">Web helper</param> /// <param name="dbContext">DB context</param> /// <param name="dataProvider">WeData provider</param> /// <param name="commonSettings">Common settings</param> public DefaultLogger(IRepository<Log> logRepository, IWebHelper webHelper, IDbContext dbContext, IDataProvider dataProvider, CommonSettings commonSettings) { this._logRepository = logRepository; this._webHelper = webHelper; this._dbContext = dbContext; this._dataProvider = dataProvider; this._commonSettings = commonSettings; } #endregion #region Utitilities /// <summary> /// Gets a value indicating whether this message should not be logged /// </summary> /// <param name="message">Message</param> /// <returns>Result</returns> protected virtual bool IgnoreLog(string message) { if (_commonSettings.IgnoreLogWordlist.Count == 0) return false; if (String.IsNullOrWhiteSpace(message)) return false; return _commonSettings .IgnoreLogWordlist .Any(x => message.IndexOf(x, StringComparison.InvariantCultureIgnoreCase) >= 0); } #endregion #region Methods /// <summary> /// Determines whether a log level is enabled /// </summary> /// <param name="level">Log level</param> /// <returns>Result</returns> public virtual bool IsEnabled(LogLevel level) { switch(level) { case LogLevel.Debug: return false; default: return true; } } /// <summary> /// Deletes a log item /// </summary> /// <param name="log">Log item</param> public virtual void DeleteLog(Log log) { if (log == null) throw new ArgumentNullException("log"); _logRepository.Delete(log); } /// <summary> /// Clears a log /// </summary> public virtual void ClearLog() { if (_commonSettings.UseStoredProceduresIfSupported && _dataProvider.StoredProceduredSupported) { //although it's not a stored procedure we use it to ensure that a database supports them //we cannot wait until EF team has it implemented - http://data.uservoice.com/forums/72025-entity-framework-feature-suggestions/suggestions/1015357-batch-cud-support //do all databases support "Truncate command"? string logTableName = _dbContext.GetTableName<Log>(); _dbContext.ExecuteSqlCommand(String.Format("TRUNCATE TABLE [{0}]", logTableName)); } else { var log = _logRepository.Table.ToList(); foreach (var logItem in log) _logRepository.Delete(logItem); } } /// <summary> /// Gets all log items /// </summary> /// <param name="fromUtc">Log item creation from; null to load all records</param> /// <param name="toUtc">Log item creation to; null to load all records</param> /// <param name="message">Message</param> /// <param name="logLevel">Log level; null to load all records</param> /// <param name="pageIndex">Page index</param> /// <param name="pageSize">Page size</param> /// <returns>Log item items</returns> public virtual IPagedList<Log> GetAllLogs(DateTime? fromUtc = null, DateTime? toUtc = null, string message = "", LogLevel? logLevel = null, int pageIndex = 0, int pageSize = int.MaxValue) { var query = _logRepository.Table; if (fromUtc.HasValue) query = query.Where(l => fromUtc.Value <= l.CreatedOnUtc); if (toUtc.HasValue) query = query.Where(l => toUtc.Value >= l.CreatedOnUtc); if (logLevel.HasValue) { var logLevelId = (int)logLevel.Value; query = query.Where(l => logLevelId == l.LogLevelId); } if (!String.IsNullOrEmpty(message)) query = query.Where(l => l.ShortMessage.Contains(message) || l.FullMessage.Contains(message)); query = query.OrderByDescending(l => l.CreatedOnUtc); var log = new PagedList<Log>(query, pageIndex, pageSize); return log; } /// <summary> /// Gets a log item /// </summary> /// <param name="logId">Log item identifier</param> /// <returns>Log item</returns> public virtual Log GetLogById(int logId) { if (logId == 0) return null; return _logRepository.GetById(logId); } /// <summary> /// Get log items by identifiers /// </summary> /// <param name="logIds">Log item identifiers</param> /// <returns>Log items</returns> public virtual IList<Log> GetLogByIds(int[] logIds) { if (logIds == null || logIds.Length == 0) return new List<Log>(); var query = from l in _logRepository.Table where logIds.Contains(l.Id) select l; var logItems = query.ToList(); //sort by passed identifiers var sortedLogItems = new List<Log>(); foreach (int id in logIds) { var log = logItems.Find(x => x.Id == id); if (log != null) sortedLogItems.Add(log); } return sortedLogItems; } /// <summary> /// Inserts a log item /// </summary> /// <param name="logLevel">Log level</param> /// <param name="shortMessage">The short message</param> /// <param name="fullMessage">The full message</param> /// <param name="customer">The customer to associate log record with</param> /// <returns>A log item</returns> public virtual Log InsertLog(LogLevel logLevel, string shortMessage, string fullMessage = "", Customer customer = null) { //check ignore word/phrase list? if (IgnoreLog(shortMessage) || IgnoreLog(fullMessage)) return null; var log = new Log { LogLevel = logLevel, ShortMessage = shortMessage, FullMessage = fullMessage, IpAddress = _webHelper.GetCurrentIpAddress(), Customer = customer, PageUrl = _webHelper.GetThisPageUrl(true), ReferrerUrl = _webHelper.GetUrlReferrer(), CreatedOnUtc = DateTime.UtcNow }; _logRepository.Insert(log); return log; } #endregion } }
using System; using System.Collections.ObjectModel; using Core.Interfaces; using Core.Model; using Crypto.Generators; using Crypto.Mappers; using Crypto.Providers; using Crypto.Wrappers; using Moq; using NUnit.Framework; namespace Crypto.Test.Providers { [TestFixture] public class KeyEncryptionProviderTest { private IConfiguration configuration; private Mock<SecureRandomGenerator> secureRandom; private Mock<IKeyProvider<RsaKey>> rsaKeyProvider; private AsymmetricKeyProvider asymmetricKeyProvider; private KeyEncryptionProvider encryptionProvider; private Mock<Pkcs12KeyEncryptionGenerator> pkcsEncryptionGenerator; private Mock<AesKeyEncryptionGenerator> aesEncryptionGenerator; [SetUp] public void SetupPkcsEncryptionProviderTest() { configuration = Mock.Of<IConfiguration>(c => c.Get<int>("SaltLengthInBytes") == 100 && c.Get<int>("KeyDerivationIterationCount") == 10); secureRandom = new Mock<SecureRandomGenerator>(); rsaKeyProvider = new Mock<IKeyProvider<RsaKey>>(); asymmetricKeyProvider = new AsymmetricKeyProvider(new OidToCipherTypeMapper(), new KeyInfoWrapper(), rsaKeyProvider.Object, null, null, null); pkcsEncryptionGenerator = new Mock<Pkcs12KeyEncryptionGenerator>(); pkcsEncryptionGenerator.Setup(e => e.Encrypt(It.IsAny<string>(), It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<byte[]>())) .Returns<string, byte[], int, byte[]>((password, salt, iterationCount, content) => { var generator = new Pkcs12KeyEncryptionGenerator(); return generator.Encrypt(password, salt, iterationCount, content); }); aesEncryptionGenerator = new Mock<AesKeyEncryptionGenerator>(); aesEncryptionGenerator.Setup(e => e.Encrypt(It.IsAny<string>(), It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<byte[]>())) .Returns<string, byte[], int, byte[]>((password, salt, iterationCount, content) => { var generator = new AesKeyEncryptionGenerator(); return generator.Encrypt(password, salt, iterationCount, content); }); encryptionProvider = new KeyEncryptionProvider(configuration, secureRandom.Object, asymmetricKeyProvider, pkcsEncryptionGenerator.Object, aesEncryptionGenerator.Object); } [TestFixture] public class EncryptPrivateKey : KeyEncryptionProviderTest { private IAsymmetricKeyPair keyPair; private IAsymmetricKey result; [SetUp] public void SetupEncryptKey() { var secureRandomGenerator = new SecureRandomGenerator(); var rsaProvider = new RsaKeyProvider(new AsymmetricKeyPairGenerator(secureRandomGenerator)); keyPair = rsaProvider.CreateKeyPair(1024); secureRandom.Setup(sr => sr.NextBytes(100)) .Returns(new byte[] {0x07}); } [TestFixture] public class WithPkcs : EncryptPrivateKey { [SetUp] public void Setup() { result = encryptionProvider.EncryptPrivateKey(keyPair.PrivateKey, "foo", EncryptionType.Pkcs); } [Test] public void ShouldThrowExceptionWhenGivenKeyIsAlreadyEncrypted() { var key = Mock.Of<IAsymmetricKey>(k => k.IsEncrypted); Assert.Throws<InvalidOperationException>(() => { encryptionProvider.EncryptPrivateKey(key, "foo", EncryptionType.Pkcs); }); } [Test] public void ShouldEncryptUsingKeyIterationCountDefinedByConfiguration() { pkcsEncryptionGenerator.Verify(e => e.Encrypt(It.IsAny<string>(), It.IsAny<byte[]>(), 10, It.IsAny<byte[]>())); } [Test] public void ShouldNotEncryptUsingAesGenerator() { aesEncryptionGenerator.Verify(e => e.Encrypt(It.IsAny<string>(), It.IsAny<byte[]>(), 10, It.IsAny<byte[]>()), Times.Never); } [Test] public void ShouldEncryptUsingGivenPassword() { pkcsEncryptionGenerator.Verify(e => e.Encrypt("foo", It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<byte[]>())); } [Test] public void ShouldEncryptUsingSaltGeneratedBySecureRandom() { pkcsEncryptionGenerator.Verify(e => e.Encrypt(It.IsAny<string>(), new byte[]{0x07}, It.IsAny<int>(), It.IsAny<byte[]>())); } [Test] public void ShouldEncryptGivenKey() { pkcsEncryptionGenerator.Verify(e => e.Encrypt(It.IsAny<string>(), It.IsAny<byte[]>(), It.IsAny<int>(), keyPair.PrivateKey.Content)); } [Test] public void ShouldThrowExceptionWhenEncryptionTypeIsNone() { var key = Mock.Of<IAsymmetricKey>(k => k.IsPrivateKey); Assert.Throws<InvalidOperationException>(() => encryptionProvider.EncryptPrivateKey(key, "foo", EncryptionType.None)); } [Test] public void ShouldGenerateSaltOfLengthDefinedByConfiguration() { secureRandom.Verify(sr => sr.NextBytes(100)); } [Test] public void ShouldReturnEncryptedAsymmetricKey() { Assert.IsTrue(result.IsEncrypted); } [Test] public void ShouldHaveEncryptedContent() { CollectionAssert.IsNotEmpty(result.Content); CollectionAssert.AreNotEqual(keyPair.PrivateKey.Content, result.Content); } } [TestFixture] public class WithAes : EncryptPrivateKey { [SetUp] public void Setup() { result = encryptionProvider.EncryptPrivateKey(keyPair.PrivateKey, "foo", EncryptionType.Aes); } [Test] public void ShouldThrowExceptionWhenGivenKeyIsAlreadyEncrypted() { var key = Mock.Of<IAsymmetricKey>(k => k.IsEncrypted); Assert.Throws<InvalidOperationException>(() => { encryptionProvider.EncryptPrivateKey(key, "foo", EncryptionType.Aes); }); } [Test] public void ShouldEncryptUsingKeyIterationCountDefinedByConfiguration() { aesEncryptionGenerator.Verify(e => e.Encrypt(It.IsAny<string>(), It.IsAny<byte[]>(), 10, It.IsAny<byte[]>())); } [Test] public void ShouldNotEncryptUsingPkcsGenerator() { pkcsEncryptionGenerator.Verify(e => e.Encrypt(It.IsAny<string>(), It.IsAny<byte[]>(), 10, It.IsAny<byte[]>()), Times.Never); } [Test] public void ShouldEncryptUsingGivenPassword() { aesEncryptionGenerator.Verify(e => e.Encrypt("foo", It.IsAny<byte[]>(), It.IsAny<int>(), It.IsAny<byte[]>())); } [Test] public void ShouldEncryptUsingSaltGeneratedBySecureRandom() { aesEncryptionGenerator.Verify(e => e.Encrypt(It.IsAny<string>(), new byte[]{0x07}, It.IsAny<int>(), It.IsAny<byte[]>())); } [Test] public void ShouldEncryptGivenKey() { aesEncryptionGenerator.Verify(e => e.Encrypt(It.IsAny<string>(), It.IsAny<byte[]>(), It.IsAny<int>(), keyPair.PrivateKey.Content)); } [Test] public void ShouldThrowExceptionWhenEncryptionTypeIsNone() { var key = Mock.Of<IAsymmetricKey>(k => k.IsPrivateKey); Assert.Throws<InvalidOperationException>(() => encryptionProvider.EncryptPrivateKey(key, "foo", EncryptionType.None)); } [Test] public void ShouldGenerateSaltOfLengthDefinedByConfiguration() { secureRandom.Verify(sr => sr.NextBytes(100)); } [Test] public void ShouldReturnEncryptedAsymmetricKey() { Assert.IsTrue(result.IsEncrypted); } [Test] public void ShouldHaveEncryptedContent() { CollectionAssert.IsNotEmpty(result.Content); CollectionAssert.AreNotEqual(keyPair.PrivateKey.Content, result.Content); } } } [TestFixture] public class DecryptPrivateKey : KeyEncryptionProviderTest { private IAsymmetricKeyPair keyPair; private IAsymmetricKey encryptedKey; private IAsymmetricKey result; [SetUp] public void SetupDecrypt() { var secureRandomGenerator = new SecureRandomGenerator(); var rsaProvider = new RsaKeyProvider(new AsymmetricKeyPairGenerator(secureRandomGenerator)); keyPair = rsaProvider.CreateKeyPair(1024); var oidToCipherTypeMapper = new OidToCipherTypeMapper(); encryptionProvider = new KeyEncryptionProvider(configuration, secureRandomGenerator, new AsymmetricKeyProvider(oidToCipherTypeMapper, new KeyInfoWrapper(), rsaProvider, null, null, null), new Pkcs12KeyEncryptionGenerator(), new AesKeyEncryptionGenerator()); } [TestFixture] public class PkcsEncrypted : DecryptPrivateKey { [SetUp] public void Setup() { encryptedKey = encryptionProvider.EncryptPrivateKey(keyPair.PrivateKey, "foobar", EncryptionType.Pkcs); result = encryptionProvider.DecryptPrivateKey(encryptedKey, "foobar"); } [Test] public void ShouldThrowExceptionWhenIncorrectPasswordIsSupplied() { Assert.Throws<ArgumentException>(() => { encryptionProvider.DecryptPrivateKey(encryptedKey, "foobar1"); }); } [Test] public void ShouldReturnDecryptedPrivateKey() { CollectionAssert.AreEqual(keyPair.PrivateKey.Content, result.Content); } } [TestFixture] public class AesEncrypted : DecryptPrivateKey { [SetUp] public void Setup() { encryptedKey = encryptionProvider.EncryptPrivateKey(keyPair.PrivateKey, "foobar", EncryptionType.Aes); result = encryptionProvider.DecryptPrivateKey(encryptedKey, "foobar"); } [Test] public void ShouldThrowExceptionWhenIncorrectPasswordIsSupplied() { Assert.Throws<ArgumentException>(() => { encryptionProvider.DecryptPrivateKey(encryptedKey, "foobar1"); }); } [Test] public void ShouldReturnDecryptedPrivateKey() { CollectionAssert.AreEqual(keyPair.PrivateKey.Content, result.Content); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Globalization; using System.Linq; using System.Reflection.Emit; using System.Reflection.Metadata.Cil.Instructions; using System.Reflection.Metadata.Ecma335; using System.Text; namespace System.Reflection.Metadata.Cil.Decoder { public struct CilDecoder { #region Public APIs /// <summary> /// Method that given a token defines if it is a type reference token. /// </summary> /// <param name="token">token to solve</param> /// <returns>true if is a type reference false if not</returns> public static bool IsTypeReference(int token) { return GetTokenType(token) == CilTokenType.TypeReference; } /// <summary> /// Method that given a token defines if it is a type definition token. /// </summary> /// <param name="token">token to solve</param> /// <returns>true if is a type definition false if not</returns> public static bool IsTypeDefinition(int token) { return GetTokenType(token) == CilTokenType.TypeDefinition; } /// <summary> /// Method that given a token defines if it is a user string token. /// </summary> /// <param name="token">token to solve</param> /// <returns>true if is a user string false if not</returns> public static bool IsUserString(int token) { return GetTokenType(token) == CilTokenType.UserString; } /// <summary> /// Method that given a token defines if it is a member reference token. /// </summary> /// <param name="token">token to solve</param> /// <returns>true if is a member reference false if not</returns> public static bool IsMemberReference(int token) { return GetTokenType(token) == CilTokenType.MemberReference; } /// <summary> /// Method that given a token defines if it is a method specification token. /// </summary> /// <param name="token">token to solve</param> /// <returns>true if is a method specification false if not</returns> public static bool IsMethodSpecification(int token) { return GetTokenType(token) == CilTokenType.MethodSpecification; } /// <summary> /// Method that given a token defines if it is a method definition token. /// </summary> /// <param name="token">token to solve</param> /// <returns>true if is a method definition false if not</returns> public static bool IsMethodDefinition(int token) { return GetTokenType(token) == CilTokenType.MethodDefinition; } /// <summary> /// Method that given a token defines if it is a field definition token. /// </summary> /// <param name="token">token to solve</param> /// <returns>true if is a field definition false if not</returns> public static bool IsFieldDefinition(int token) { return GetTokenType(token) == CilTokenType.FieldDefinition; } /// <summary> /// Method that given a token defines if it is a type specification token. /// </summary> /// <param name="token">token to solve</param> /// <returns>true if is a type specification false if not</returns> public static bool IsTypeSpecification(int token) { return GetTokenType(token) == CilTokenType.TypeSpecification; } /// <summary> /// Method that given a token defines if it is a standalone signature token. /// </summary> /// <param name="token">token to solve</param> /// <returns>true if is a standalone signature false if not</returns> public static bool IsStandaloneSignature(int token) { return GetTokenType(token) == CilTokenType.Signature; } public static string CreateByteArrayString(byte[] array) { if (array.Length == 0) return "()"; char[] chars = new char[3 + 3 * array.Length]; //3 equals for parenthesis and first space, 3 for 1 (space) + 2(byte). int i = 0; chars[i++] = '('; chars[i++] = ' '; foreach(byte b in array) { chars[i++] = HexadecimalNibble((byte)(b >> 4)); //get every byte char in Hex X2 representation. chars[i++] = HexadecimalNibble((byte)(b & 0xF)); chars[i++] = ' '; } chars[i++] = ')'; return new string(chars); } public static string CreateVersionString(Version version) { int build = version.Build; int revision = version.Revision; if (build == -1) build = 0; if (revision == -1) revision = 0; return String.Format("{0}:{1}:{2}:{3}", version.Major.ToString(), version.Minor.ToString(), build.ToString(), revision.ToString()); } public static string DecodeSignatureParamerTypes(MethodSignature<CilType> signature) { StringBuilder sb = new StringBuilder(); sb.Append('('); var types = signature.ParameterTypes; for (int i = 0; i < types.Length; i++) { if (i > 0) { sb.Append(','); } sb.Append(types[i].ToString()); } sb.Append(')'); return sb.ToString(); } internal static CilEntity DecodeEntityHandle(EntityHandle handle, ref CilReaders readers) { if (handle.Kind == HandleKind.TypeDefinition) { TypeDefinition definition = readers.MdReader.GetTypeDefinition((TypeDefinitionHandle)handle); int token = MetadataTokens.GetToken(handle); CilTypeDefinition type = CilTypeDefinition.Create(definition, ref readers, token); return new CilEntity(type, EntityKind.TypeDefinition); } if (handle.Kind == HandleKind.TypeSpecification) { TypeSpecification specification = readers.MdReader.GetTypeSpecification((TypeSpecificationHandle)handle); CilTypeSpecification type = CilTypeSpecification.Create(specification, ref readers); return new CilEntity(type, EntityKind.TypeSpecification); } if (handle.Kind == HandleKind.TypeReference) { TypeReference reference = readers.MdReader.GetTypeReference((TypeReferenceHandle)handle); int token = MetadataTokens.GetToken(handle); CilTypeReference type = CilTypeReference.Create(reference, ref readers, token); return new CilEntity(type, EntityKind.TypeReference); } throw new BadImageFormatException("Event definition type must be either type reference, type definition or type specification"); } public static MethodSignature<CilType> DecodeMethodSignature(MethodDefinition methodDefinition, CilTypeProvider provider) { return SignatureDecoder.DecodeMethodSignature(methodDefinition.Signature, provider); } public static IEnumerable<CilInstruction> DecodeMethodBody(CilMethodDefinition methodDefinition) { return DecodeMethodBody(methodDefinition.IlReader, methodDefinition._readers.MdReader, methodDefinition.Provider, methodDefinition); } #endregion #region Private and internal helpers internal static bool HasArgument(OpCode opCode) { bool isLoad = opCode == OpCodes.Ldarg || opCode == OpCodes.Ldarga || opCode == OpCodes.Ldarga_S || opCode == OpCodes.Ldarg_S; bool isStore = opCode == OpCodes.Starg_S || opCode == OpCodes.Starg; return isLoad || isStore; } private static IEnumerable<CilInstruction> DecodeMethodBody(BlobReader ilReader, MetadataReader metadataReader, CilTypeProvider provider, CilMethodDefinition methodDefinition) { ilReader.Reset(); int intOperand; ushort shortOperand; int ilOffset = 0; CilInstruction instruction = null; while (ilReader.Offset < ilReader.Length) { OpCode opCode; int expectedSize; byte _byte = ilReader.ReadByte(); /*If the byte read is 0xfe it means is a two byte instruction, so since it is going to read the second byte to get the actual instruction it has to check that the offset is still less than the length.*/ if (_byte == 0xfe && ilReader.Offset < ilReader.Length) { opCode = CilDecoderHelpers.Instance.twoByteOpCodes[ilReader.ReadByte()]; expectedSize = 2; } else { opCode = CilDecoderHelpers.Instance.oneByteOpCodes[_byte]; expectedSize = 1; } switch (opCode.OperandType) { //The instruction size is the expected size (1 or 2 depending if it is a one or two byte instruction) + the size of the operand. case OperandType.InlineField: intOperand = ilReader.ReadInt32(); string fieldInfo = GetFieldInformation(metadataReader, intOperand, provider); instruction = new CilStringInstruction(opCode, fieldInfo, intOperand, expectedSize + (int)CilInstructionSize.Int32); break; case OperandType.InlineString: intOperand = ilReader.ReadInt32(); bool isPrintable; string str = GetArgumentString(metadataReader, intOperand, out isPrintable); instruction = new CilStringInstruction(opCode, str, intOperand, expectedSize + (int)CilInstructionSize.Int32, isPrintable); break; case OperandType.InlineMethod: intOperand = ilReader.ReadInt32(); string methodCall = SolveMethodName(metadataReader, intOperand, provider); instruction = new CilStringInstruction(opCode, methodCall, intOperand, expectedSize + (int)CilInstructionSize.Int32); break; case OperandType.InlineType: intOperand = ilReader.ReadInt32(); string type = GetTypeInformation(metadataReader, intOperand, provider); instruction = new CilStringInstruction(opCode, type, intOperand, expectedSize + (int)CilInstructionSize.Int32); break; case OperandType.InlineTok: intOperand = ilReader.ReadInt32(); string tokenType = GetInlineTokenType(metadataReader, intOperand, provider); instruction = new CilStringInstruction(opCode, tokenType, intOperand, expectedSize + (int)CilInstructionSize.Int32); break; case OperandType.InlineI: instruction = new CilInt32Instruction(opCode, ilReader.ReadInt32(), -1, expectedSize + (int)CilInstructionSize.Int32); break; case OperandType.InlineI8: instruction = new CilInt64Instruction(opCode, ilReader.ReadInt64(), -1, expectedSize + (int)CilInstructionSize.Int64); break; case OperandType.InlineR: instruction = new CilDoubleInstruction(opCode, ilReader.ReadDouble(), -1, expectedSize + (int)CilInstructionSize.Double); break; case OperandType.InlineSwitch: instruction = CreateSwitchInstruction(ref ilReader, expectedSize, ilOffset, opCode); break; case OperandType.ShortInlineBrTarget: instruction = new CilInt16BranchInstruction(opCode, ilReader.ReadSByte(), ilOffset, expectedSize + (int)CilInstructionSize.Byte); break; case OperandType.InlineBrTarget: instruction = new CilBranchInstruction(opCode, ilReader.ReadInt32(), ilOffset, expectedSize + (int)CilInstructionSize.Int32); break; case OperandType.ShortInlineI: instruction = new CilByteInstruction(opCode, ilReader.ReadByte(), -1, expectedSize + (int)CilInstructionSize.Byte); break; case OperandType.ShortInlineR: instruction = new CilSingleInstruction(opCode, ilReader.ReadSingle(), -1, expectedSize + (int)CilInstructionSize.Single); break; case OperandType.InlineNone: instruction = new CilInstructionWithNoValue(opCode, expectedSize); break; case OperandType.ShortInlineVar: byte token = ilReader.ReadByte(); instruction = new CilInt16VariableInstruction(opCode, GetVariableName(opCode, token, methodDefinition), token, expectedSize + (int)CilInstructionSize.Byte); break; case OperandType.InlineVar: shortOperand = ilReader.ReadUInt16(); instruction = new CilVariableInstruction(opCode, GetVariableName(opCode, shortOperand, methodDefinition), shortOperand, expectedSize + (int)CilInstructionSize.Int16); break; case OperandType.InlineSig: intOperand = ilReader.ReadInt32(); instruction = new CilStringInstruction(opCode, GetSignature(metadataReader, intOperand, provider), intOperand, expectedSize + (int)CilInstructionSize.Int32); break; default: break; } ilOffset += instruction.Size; yield return instruction; } } internal static CilLocal[] DecodeLocalSignature(MethodBodyBlock methodBody, MetadataReader metadataReader, CilTypeProvider provider) { if (methodBody.LocalSignature.IsNil) { return new CilLocal[0]; } ImmutableArray<CilType> localTypes = SignatureDecoder.DecodeLocalSignature(methodBody.LocalSignature, provider); CilLocal[] locals = new CilLocal[localTypes.Length]; for (int i = 0; i < localTypes.Length; i++) { string name = "V_" + i; locals[i] = new CilLocal(name, localTypes[i].ToString()); } return locals; } internal static CilParameter[] DecodeParameters(MethodSignature<CilType> signature, ParameterHandleCollection parameters, ref CilReaders readers) { ImmutableArray<CilType> types = signature.ParameterTypes; int requiredCount = Math.Min(signature.RequiredParameterCount, types.Length); if (requiredCount == 0) { return new CilParameter[0]; } CilParameter[] result = new CilParameter[requiredCount]; for (int i = 0; i < requiredCount; i++) { var parameter = readers.MdReader.GetParameter(parameters.ElementAt(i)); result[i] = CilParameter.Create(parameter, ref readers, types[i].ToString()); } return result; } internal static IEnumerable<string> DecodeGenericParameters(MethodDefinition methodDefinition, CilMethodDefinition method) { foreach (var handle in methodDefinition.GetGenericParameters()) { var parameter = method._readers.MdReader.GetGenericParameter(handle); yield return method._readers.MdReader.GetString(parameter.Name); } } internal static CilType DecodeType(EntityHandle type, CilTypeProvider provider) { return SignatureDecoder.DecodeType(type, provider, 0); } private static string GetSignature(MetadataReader metadataReader, int intOperand, CilTypeProvider provider) { if (IsStandaloneSignature(intOperand)) { var handle = MetadataTokens.StandaloneSignatureHandle(intOperand); var standaloneSignature = metadataReader.GetStandaloneSignature(handle); var signature = SignatureDecoder.DecodeMethodSignature(standaloneSignature.Signature, provider); return string.Format("{0}{1}", GetMethodReturnType(signature), provider.GetParameterList(signature)); } throw new ArgumentException("Get signature invalid token"); } private static string GetVariableName(OpCode opCode, int token, CilMethodDefinition methodDefinition) { if (HasArgument(opCode)) { if (methodDefinition.Signature.Header.IsInstance) { token--; //the first parameter is "this". } return methodDefinition.GetParameter(token).Name; } return methodDefinition.GetLocal(token).Name; } private static string GetInlineTokenType(MetadataReader metadataReader, int intOperand, CilTypeProvider provider) { if (IsMethodDefinition(intOperand) || IsMethodSpecification(intOperand) || IsMemberReference(intOperand)) { return "method " + SolveMethodName(metadataReader, intOperand, provider); } if (IsFieldDefinition(intOperand)) { return "field " + GetFieldInformation(metadataReader, intOperand, provider); } return GetTypeInformation(metadataReader, intOperand, provider); } private static string GetTypeInformation(MetadataReader metadataReader, int intOperand, CilTypeProvider provider) { if (IsTypeReference(intOperand)) { var refHandle = MetadataTokens.TypeReferenceHandle(intOperand); return SignatureDecoder.DecodeType(refHandle, provider, 0).ToString(); } if (IsTypeSpecification(intOperand)) { var typeHandle = MetadataTokens.TypeSpecificationHandle(intOperand); return SignatureDecoder.DecodeType(typeHandle, provider, 0).ToString(); } var defHandle = MetadataTokens.TypeDefinitionHandle(intOperand); return SignatureDecoder.DecodeType(defHandle, provider, 0).ToString(); } private static CilInstruction CreateSwitchInstruction(ref BlobReader ilReader, int expectedSize, int ilOffset, OpCode opCode) { uint caseNumber = ilReader.ReadUInt32(); int[] jumps = new int[caseNumber]; for (int i = 0; i < caseNumber; i++) { jumps[i] = ilReader.ReadInt32(); } int size = (int)CilInstructionSize.Int32 + expectedSize; size += (int)caseNumber * (int)CilInstructionSize.Int32; return new CilSwitchInstruction(opCode, ilOffset, jumps, (int)caseNumber, caseNumber, size); } private static string GetArgumentString(MetadataReader metadataReader, int intOperand, out bool isPrintable) { if (IsUserString(intOperand)) { UserStringHandle usrStr = MetadataTokens.UserStringHandle(intOperand); var str = metadataReader.GetUserString(usrStr); str = ProcessAndNormalizeString(str, out isPrintable); return str; } throw new ArgumentException("Invalid argument, must be a user string metadata token."); } private static string ProcessAndNormalizeString(string str, out bool isPrintable) { foreach (char c in str) { UnicodeCategory category = CharUnicodeInfo.GetUnicodeCategory(c); if (category == UnicodeCategory.Control || category == UnicodeCategory.OtherNotAssigned || category == UnicodeCategory.OtherSymbol || c == '"') { byte[] bytes = Encoding.Unicode.GetBytes(str); isPrintable = false; return string.Format("bytearray{0}", CreateByteArrayString(bytes)); } } isPrintable = true; return str; } private static string GetMethodReturnType(MethodSignature<CilType> signature) { string returnTypeStr = signature.ReturnType.ToString(); return signature.Header.IsInstance ? "instance " + returnTypeStr : returnTypeStr; } private static string GetMemberRef(MetadataReader metadataReader, int token, CilTypeProvider provider, string genericParameterSignature = "") { var refHandle = MetadataTokens.MemberReferenceHandle(token); var reference = metadataReader.GetMemberReference(refHandle); var parentToken = MetadataTokens.GetToken(reference.Parent); string type; if (IsTypeSpecification(parentToken)) { var typeSpecificationHandle = MetadataTokens.TypeSpecificationHandle(parentToken); type = SignatureDecoder.DecodeType(typeSpecificationHandle, provider, 0).ToString(); } else { var parentHandle = MetadataTokens.TypeReferenceHandle(parentToken); type = SignatureDecoder.DecodeType(parentHandle, provider, 0).ToString(false); } string signatureValue; string parameters = string.Empty; if (reference.GetKind() == MemberReferenceKind.Method) { MethodSignature<CilType> signature = SignatureDecoder.DecodeMethodSignature(reference.Signature, provider); signatureValue = GetMethodReturnType(signature); parameters = provider.GetParameterList(signature); return String.Format("{0} {1}::{2}{3}{4}", signatureValue, type, GetString(metadataReader, reference.Name), genericParameterSignature,parameters); } signatureValue = SignatureDecoder.DecodeFieldSignature(reference.Signature, provider).ToString(); return String.Format("{0} {1}::{2}{3}", signatureValue, type, GetString(metadataReader, reference.Name), parameters); } internal static string SolveMethodName(MetadataReader metadataReader, int token, CilTypeProvider provider) { string genericParameters = string.Empty; if (IsMethodSpecification(token)) { var methodHandle = MetadataTokens.MethodSpecificationHandle(token); var methodSpec = metadataReader.GetMethodSpecification(methodHandle); token = MetadataTokens.GetToken(methodSpec.Method); genericParameters = GetGenericParametersSignature(methodSpec, provider); } if (IsMemberReference(token)) { return GetMemberRef(metadataReader, token, provider, genericParameters); } var handle = MetadataTokens.MethodDefinitionHandle(token); var definition = metadataReader.GetMethodDefinition(handle); var parent = definition.GetDeclaringType(); MethodSignature<CilType> signature = SignatureDecoder.DecodeMethodSignature(definition.Signature, provider); var returnType = GetMethodReturnType(signature); var parameters = provider.GetParameterList(signature); var parentType = SignatureDecoder.DecodeType(parent, provider, 0); return string.Format("{0} {1}::{2}{3}{4}", returnType, parentType.ToString(false), GetString(metadataReader, definition.Name), genericParameters, parameters); } private static string GetGenericParametersSignature(MethodSpecification methodSpec, CilTypeProvider provider) { var genericParameters = SignatureDecoder.DecodeMethodSpecificationSignature(methodSpec.Signature, provider); StringBuilder sb = new StringBuilder(); int i; for(i = 0; i < genericParameters.Length; i++) { if(i == 0) { sb.Append("<"); } sb.Append(genericParameters[i]); sb.Append(","); } if(i > 0) { sb.Length--; sb.Append(">"); } return sb.ToString(); } private static string GetFieldInformation(MetadataReader metadataReader, int intOperand, CilTypeProvider provider) { if(IsMemberReference(intOperand)) { return GetMemberRef(metadataReader, intOperand, provider); } var handle = MetadataTokens.FieldDefinitionHandle(intOperand); var definition = metadataReader.GetFieldDefinition(handle); var typeHandle = definition.GetDeclaringType(); var typeSignature = SignatureDecoder.DecodeType(typeHandle, provider, 0); var signature = SignatureDecoder.DecodeFieldSignature(definition.Signature, provider); return String.Format("{0} {1}::{2}", signature.ToString(), typeSignature.ToString(false), GetString(metadataReader, definition.Name)); } private static string GetString(MetadataReader metadataReader, StringHandle handle) { return CilDecoderHelpers.Instance.NormalizeString(metadataReader.GetString(handle)); } private static CilTokenType GetTokenType(int token) { return unchecked((CilTokenType)(token >> 24)); } private static char HexadecimalNibble(byte b) { return (char)(b >= 0 && b <= 9 ? '0' + b : 'A' + (b - 10)); } internal static string DecodeOverridenMethodName(MetadataReader metadataReader, int token, CilTypeProvider provider) { var handle = MetadataTokens.MethodDefinitionHandle(token); var definition = metadataReader.GetMethodDefinition(handle); var parent = definition.GetDeclaringType(); var parentType = SignatureDecoder.DecodeType(parent, provider, 0); return string.Format("{0}::{1}", parentType.ToString(false), GetString(metadataReader, definition.Name)); } internal static string GetCachedValue(StringHandle value, CilReaders readers, ref string storage) { if (storage != null) { return storage; } storage = readers.MdReader.GetString(value); return storage; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Pathoschild.Stardew.Common; using StardewModdingAPI; using StardewValley; using StardewValley.Characters; using StardewValley.Locations; using StardewValley.Menus; using StardewValley.Monsters; namespace Pathoschild.Stardew.LookupAnything.Framework.Lookups.Characters { /// <summary>Provides lookup data for in-game characters.</summary> internal class CharacterLookupProvider : BaseLookupProvider { /********* ** Fields methods *********/ /// <summary>The mod configuration.</summary> private readonly Func<ModConfig> Config; /// <summary>Provides subject entries.</summary> private readonly ISubjectRegistry Codex; /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="reflection">Simplifies access to private game code.</param> /// <param name="gameHelper">Provides utility methods for interacting with the game code.</param> /// <param name="config">The mod configuration.</param> /// <param name="codex">Provides subject entries.</param> public CharacterLookupProvider(IReflectionHelper reflection, GameHelper gameHelper, Func<ModConfig> config, ISubjectRegistry codex) : base(reflection, gameHelper) { this.Config = config; this.Codex = codex; } /// <inheritdoc /> public override IEnumerable<ITarget> GetTargets(GameLocation location, Vector2 lookupTile) { // Gourmand NPC if (location is IslandFarmCave { gourmand: not null } islandFarmCave) { NPC gourmand = islandFarmCave.gourmand; yield return new CharacterTarget(this.GameHelper, this.GetSubjectType(gourmand), gourmand, gourmand.getTileLocation(), this.Reflection, () => this.BuildSubject(gourmand)); } // NPCs foreach (NPC npc in Game1.CurrentEvent?.actors ?? (IEnumerable<NPC>)location.characters) { Vector2 entityTile = npc.getTileLocation(); if (this.GameHelper.CouldSpriteOccludeTile(entityTile, lookupTile)) yield return new CharacterTarget(this.GameHelper, this.GetSubjectType(npc), npc, entityTile, this.Reflection, () => this.BuildSubject(npc)); } // animals if (location is IAnimalLocation animalLocation) { foreach (FarmAnimal animal in animalLocation.Animals.Values) { Vector2 entityTile = animal.getTileLocation(); if (this.GameHelper.CouldSpriteOccludeTile(entityTile, lookupTile)) yield return new FarmAnimalTarget(this.GameHelper, animal, entityTile, () => this.BuildSubject(animal)); } } // players foreach (Farmer farmer in location.farmers) { Vector2 entityTile = farmer.getTileLocation(); if (this.GameHelper.CouldSpriteOccludeTile(entityTile, lookupTile)) yield return new FarmerTarget(this.GameHelper, farmer, () => this.BuildSubject(farmer)); } } /// <inheritdoc /> public override ISubject GetSubject(IClickableMenu menu, int cursorX, int cursorY) { IClickableMenu targetMenu = (menu as GameMenu)?.GetCurrentPage() ?? menu; switch (targetMenu) { /**** ** GameMenu ****/ // skills tab case SkillsPage: return this.BuildSubject(Game1.player); // profile tab case ProfileMenu profileMenu: if (profileMenu.hoveredItem == null) { if (profileMenu.GetCharacter() is NPC npc) return this.Codex.GetByEntity(npc, npc.currentLocation); } break; // social tab case SocialPage socialPage: foreach (ClickableTextureComponent slot in socialPage.characterSlots) { if (slot.containsPoint(cursorX, cursorY)) { object socialID = this.Reflection.GetField<List<object>>(socialPage, "names").GetValue()[slot.myID]; // player slot if (socialID is long playerID) { Farmer player = Game1.getFarmerMaybeOffline(playerID); return this.BuildSubject(player); } // NPC slot if (socialID is string villagerName) { NPC npc = this.GameHelper.GetAllCharacters().FirstOrDefault(p => p.isVillager() && p.Name == villagerName); if (npc != null) return this.BuildSubject(npc); } } } break; /**** ** Calendar ****/ case Billboard { calendarDays: not null } billboard: // Billboard used for both calendar and 'help wanted' { // get target day int selectedDay = -1; for (int i = 0; i < billboard.calendarDays.Count; i++) { if (billboard.calendarDays[i].containsPoint(cursorX, cursorY)) { selectedDay = i + 1; break; } } if (selectedDay == -1) return null; // get villager with a birthday on that date NPC target = this.GameHelper .GetAllCharacters() .Where(p => p.Birthday_Season == Game1.currentSeason && p.Birthday_Day == selectedDay) .OrderByDescending(p => p.CanSocialize) // SVE duplicates the Marlon NPC, but only one of them is marked social .FirstOrDefault(); if (target != null) return this.BuildSubject(target); } break; /**** ** Load menu ****/ case TitleMenu when TitleMenu.subMenu is LoadGameMenu loadMenu: { ClickableComponent button = loadMenu.slotButtons.FirstOrDefault(p => p.containsPoint(cursorX, cursorY)); if (button != null) { int index = this.Reflection.GetField<int>(loadMenu, "currentItemIndex").GetValue() + int.Parse(button.name); var slots = this.Reflection.GetProperty<List<LoadGameMenu.MenuSlot>>(loadMenu, "MenuSlots").GetValue(); LoadGameMenu.SaveFileSlot slot = slots[index] as LoadGameMenu.SaveFileSlot; if (slot?.Farmer != null) return new FarmerSubject(this.GameHelper, slot.Farmer, isLoadMenu: true); } } break; /**** ** mod: Animal Social Menu ****/ case IClickableMenu when targetMenu.GetType().FullName == "AnimalSocialMenu.Framework.AnimalSocialPage": { int slotOffset = this.Reflection.GetField<int>(targetMenu, "SlotPosition").GetValue(); List<ClickableTextureComponent> slots = this.Reflection.GetField<List<ClickableTextureComponent>>(targetMenu, "Sprites").GetValue(); List<object> animalIds = this.Reflection.GetField<List<object>>(targetMenu, "Names").GetValue(); for (int i = slotOffset; i < slots.Count; i++) { if (slots[i].containsPoint(cursorX, cursorY)) { if (animalIds.TryGetIndex(i, out object rawId) && rawId is long id) { FarmAnimal animal = Game1 .getFarm() .getAllFarmAnimals() .FirstOrDefault(p => p.myID.Value == id); if (animal != null) return this.BuildSubject(animal); } break; } } } break; } return null; } /// <inheritdoc /> public override ISubject GetSubjectFor(object entity, GameLocation location) { return entity switch { FarmAnimal animal => this.BuildSubject(animal), Farmer player => this.BuildSubject(player), NPC npc => this.BuildSubject(npc), _ => null }; } /// <inheritdoc /> public override IEnumerable<ISubject> GetSearchSubjects() { // get all matching NPCs IEnumerable<ISubject> GetAll() { // NPCs foreach (NPC npc in Utility.getAllCharacters()) yield return this.BuildSubject(npc); // animals foreach (var location in CommonHelper.GetLocations().OfType<IAnimalLocation>()) { foreach (FarmAnimal animal in location.Animals.Values) yield return this.BuildSubject(animal); } // players foreach (Farmer player in Game1.getAllFarmers()) yield return this.BuildSubject(player); } // filter duplicates (e.g. multiple monsters) HashSet<string> seen = new HashSet<string>(); foreach (ISubject subject in GetAll()) { if (!seen.Add($"{subject.GetType().FullName}::{subject.Type}::{subject.Name}")) continue; yield return subject; } } /********* ** Private methods *********/ /// <summary>Build a subject.</summary> /// <param name="player">The entity to look up.</param> private ISubject BuildSubject(Farmer player) { return new FarmerSubject(this.GameHelper, player); } /// <summary>Build a subject.</summary> /// <param name="animal">The entity to look up.</param> private ISubject BuildSubject(FarmAnimal animal) { return new FarmAnimalSubject(this.Codex, this.GameHelper, animal); } /// <summary>Build a subject.</summary> /// <param name="npc">The entity to look up.</param> private ISubject BuildSubject(NPC npc) { ModConfig config = this.Config(); return new CharacterSubject( codex: this.Codex, gameHelper: this.GameHelper, npc: npc, type: this.GetSubjectType(npc), metadata: this.GameHelper.Metadata, reflectionHelper: this.Reflection, progressionMode: config.ProgressionMode, highlightUnrevealedGiftTastes: config.HighlightUnrevealedGiftTastes, showAllGiftTastes: config.ShowAllGiftTastes, enableTargetRedirection: config.EnableTargetRedirection ); } /// <summary>Get the subject type for an NPC.</summary> /// <param name="npc">The NPC instance.</param> private SubjectType GetSubjectType(NPC npc) { return npc switch { Horse => SubjectType.Horse, Junimo => SubjectType.Junimo, Pet => SubjectType.Pet, Monster => SubjectType.Monster, _ => SubjectType.Villager }; } } }
// // GtkBaseClient.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2007 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Runtime.InteropServices; using Mono.Addins; using Hyena; using Banshee.Base; using Banshee.Metrics; using Banshee.Database; using Banshee.ServiceStack; using Banshee.Gui.Dialogs; namespace Banshee.Gui { public abstract class GtkBaseClient : Client { static GtkBaseClient () { Application.InitializePaths (); user_css = Path.Combine (Paths.ApplicationData, "gtk.css"); } private static Type client_type; private static string user_css; private Gtk.CssProvider custom_provider; public static void Startup<T> (string [] args) where T : GtkBaseClient { Hyena.Log.InformationFormat ("Running Banshee {0}: [{1}]", Application.Version, Application.BuildDisplayInfo); // Boot the client Banshee.Gui.GtkBaseClient.Startup<T> (); } public static void Startup<T> () where T : GtkBaseClient { if (client_type != null) { throw new ApplicationException ("Only a single GtkBaseClient can be initialized through Entry<T>"); } client_type = typeof (T); Hyena.Gui.CleanRoomStartup.Startup (Startup); } private static void Startup () { ((GtkBaseClient)Activator.CreateInstance (client_type)).Run (); } private string default_icon_name; protected GtkBaseClient () : this (true, Application.IconName) { } protected GtkBaseClient (bool initializeDefault, string defaultIconName) { this.default_icon_name = defaultIconName; if (initializeDefault) { Initialize (true); } } protected virtual void PreInitializeGtk () { } [DllImport ("libdbus-glib-1-2.dll")] internal static extern void dbus_g_thread_init (); protected virtual void InitializeGtk () { Log.Debug ("Initializing GTK"); if (!GLib.Thread.Supported) { GLib.Thread.Init (); } #if HAVE_DBUS_GLIB // Using GConf from multiple threads causes crashes if multithreading is not initialized explictly in dbus // This is a workaround for bgo#692374 dbus_g_thread_init (); #endif Gtk.Application.Init (); // This could go into GtkBaseClient, but it's probably something we // should really only support at each client level if (File.Exists (user_css) && !ApplicationContext.CommandLine.Contains ("no-gtkcss")) { custom_provider = new Gtk.CssProvider (); custom_provider.LoadFromPath (user_css); Gtk.StyleContext.AddProviderForScreen (Gdk.Screen.Default, (Gtk.IStyleProvider)custom_provider, 600 /* GTK_STYLE_PROVIDER_PRIORITY_APPLICATION*/ ); } if (ApplicationContext.CommandLine.Contains ("debug-gtkcss")) { Log.Information ("Note: gtk.css file will be checked for reload every 5 seconds!"); GLib.Timeout.Add (5000, delegate { if (custom_provider != null) { custom_provider.LoadFromPath (user_css); Gtk.StyleContext.ResetWidgets (Gdk.Screen.Default); Log.Information ("gtk.css has been reloaded"); } return true; }); } } protected virtual void PostInitializeGtk () { Log.Debug ("Post-Initializing GTK"); foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes ("/Banshee/ThickClient/GtkBaseClient/PostInitializeGtk")) { try { node.CreateInstance (); } catch (Exception e) { Log.Exception ("PostInitializeGtk extension failed to run", e); } } } protected void Initialize (bool registerCommonServices) { // Set the process name so system process listings and commands are pretty ApplicationContext.TrySetProcessName (Application.InternalName); PreInitializeGtk (); InitializeGtk (); Application.Initialize (); PostInitializeGtk (); Gtk.Window.DefaultIconName = default_icon_name; ThreadAssist.InitializeMainThread (); ThreadAssist.ProxyToMainHandler = Banshee.ServiceStack.Application.Invoke; Gdk.Global.ProgramClass = Application.InternalName; GLib.Global.ApplicationName = "Banshee"; // TODO: Set this to "video" when we're playing a video. PulseAudio doesn't treat it differently // than "music" for now, but it would be more correct. Environment.SetEnvironmentVariable ("PULSE_PROP_media.role", "music"); if (ApplicationContext.Debugging) { GLib.Log.SetLogHandler ("Gtk", GLib.LogLevelFlags.Critical, GLib.Log.PrintTraceLogFunction); Gdk.Window.DebugUpdates = !String.IsNullOrEmpty (Environment.GetEnvironmentVariable ("GDK_DEBUG_UPDATES")); } ServiceManager.ServiceStarted += OnServiceStarted; // Register specific services this client will care about if (registerCommonServices) { Banshee.Gui.CommonServices.Register (); } OnRegisterServices (); Application.ShutdownPromptHandler = OnShutdownPrompt; Application.TimeoutHandler = RunTimeout; Application.IdleHandler = RunIdle; Application.IdleTimeoutRemoveHandler = IdleTimeoutRemove; BansheeMetrics.Started += OnMetricsStarted; // Start the core boot process Application.PushClient (this); Application.Run (); if (!Banshee.Configuration.DefaultApplicationHelper.NeverAsk && Banshee.Configuration.DefaultApplicationHelper.HaveHelper) { Application.ClientStarted += delegate { Banshee.Gui.Dialogs.DefaultApplicationHelperDialog.RunIfAppropriate (); }; } Log.Notify += OnLogNotify; } private void OnMetricsStarted () { var metrics = BansheeMetrics.Instance; var screen = Gdk.Screen.Default; metrics.Add ("Display/NScreens", Gdk.Display.Default.NScreens); metrics.Add ("Screen/Height", screen.Height); metrics.Add ("Screen/Width", screen.Width); metrics.Add ("Screen/IsComposited", screen.IsComposited); metrics.Add ("Screen/NMonitors", screen.NMonitors); } public virtual void Run () { RunIdle (delegate { OnStarted (); return false; }); Log.Debug ("Starting GTK main loop"); Gtk.Application.Run (); } protected virtual void OnRegisterServices () { } private void OnServiceStarted (ServiceStartedArgs args) { if (args.Service is BansheeDbConnection) { ServiceManager.ServiceStarted -= OnServiceStarted; BansheeDbFormatMigrator migrator = ((BansheeDbConnection)args.Service).Migrator; if (migrator != null) { migrator.Started += OnMigratorStarted; migrator.Finished += OnMigratorFinished; } } } private void OnMigratorStarted (object o, EventArgs args) { BansheeDbFormatMigrator migrator = (BansheeDbFormatMigrator)o; new BansheeDbFormatMigratorMonitor (migrator); } private void OnMigratorFinished (object o, EventArgs args) { BansheeDbFormatMigrator migrator = (BansheeDbFormatMigrator)o; migrator.Started -= OnMigratorStarted; migrator.Finished -= OnMigratorFinished; } private void OnLogNotify (LogNotifyArgs args) { RunIdle (delegate { ShowLogCoreEntry (args.Entry); return false; }); } private void ShowLogCoreEntry (LogEntry entry) { Gtk.Window window = null; Gtk.MessageType mtype; if (ServiceManager.Contains<GtkElementsService> ()) { window = ServiceManager.Get<GtkElementsService> ().PrimaryWindow; } switch (entry.Type) { case LogEntryType.Warning: mtype = Gtk.MessageType.Warning; break; case LogEntryType.Information: mtype = Gtk.MessageType.Info; break; case LogEntryType.Error: default: mtype = Gtk.MessageType.Error; break; } Hyena.Widgets.HigMessageDialog dialog = new Hyena.Widgets.HigMessageDialog ( window, Gtk.DialogFlags.Modal, mtype, Gtk.ButtonsType.Close, entry.Message, entry.Details); dialog.Title = String.Empty; dialog.Run (); dialog.Destroy (); } private bool OnShutdownPrompt () { ConfirmShutdownDialog dialog = new ConfirmShutdownDialog (); try { return dialog.Run () != Gtk.ResponseType.Cancel; } finally { dialog.Destroy (); } } protected uint RunTimeout (uint milliseconds, TimeoutHandler handler) { return GLib.Timeout.Add (milliseconds, delegate { return handler (); }); } protected uint RunIdle (IdleHandler handler) { return GLib.Idle.Add (delegate { return handler (); }); } protected bool IdleTimeoutRemove (uint id) { return GLib.Source.Remove (id); } } }
// MIT License // // Copyright (c) 2017 Maarten van Sambeek. // // 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 ConnectQl.DataSources.Joins { using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using ConnectQl.AsyncEnumerables; using ConnectQl.AsyncEnumerables.Policies; using ConnectQl.Expressions; using ConnectQl.Expressions.Helpers; using ConnectQl.Expressions.Visitors; using ConnectQl.Interfaces; using ConnectQl.Results; using JetBrains.Annotations; /// <summary> /// The CROSS JOIN. /// </summary> internal class CrossJoin : DataSource { /// <summary> /// Initializes a new instance of the <see cref="CrossJoin"/> class. /// </summary> /// <param name="left"> /// The left. /// </param> /// <param name="right"> /// The right. /// </param> protected CrossJoin([NotNull] DataSource left, [NotNull] DataSource right) : base(new HashSet<string>(left.Aliases.Concat(right.Aliases))) { this.Left = left; this.Right = right; } /// <summary> /// Gets the left. /// </summary> protected DataSource Left { get; } /// <summary> /// Gets the right. /// </summary> protected DataSource Right { get; } /// <summary> /// Gets the rows for the join. /// </summary> /// <param name="context"> /// The context. /// </param> /// <param name="multiPartQuery"> /// The multi part query. /// </param> /// <returns> /// The <see cref="IAsyncEnumerable{Row}"/>. /// </returns> internal override IAsyncEnumerable<Row> GetRows(IInternalExecutionContext context, [NotNull] IMultiPartQuery multiPartQuery) { var rowBuilder = new RowBuilder(); //// Build the left part by filtering by parts that contain the fields of the left side. var leftQuery = new MultiPartQuery { Fields = multiPartQuery.Fields.Where(f => this.Left.Aliases.Contains(f.SourceAlias)), FilterExpression = multiPartQuery.FilterExpression.FilterByAliases(this.Left.Aliases), WildcardAliases = multiPartQuery.WildcardAliases.Intersect(this.Left.Aliases).ToArray(), }; //// Create the enumerable. return context.CreateAsyncEnumerable( async () => { //// Retrieve the records from the left side. var leftData = await this.Left.GetRows(context, leftQuery).MaterializeAsync().ConfigureAwait(false); var rightQuery = new MultiPartQuery { Fields = multiPartQuery.Fields.Where(f => this.Right.Aliases.Contains(f.SourceAlias)), FilterExpression = CrossJoin.RangesToJoinFilter(await this.FindRangesAsync(context, multiPartQuery.FilterExpression, leftData)), WildcardAliases = multiPartQuery.WildcardAliases.Intersect(this.Right.Aliases), }; var rightData = await this.Right.GetRows(context, rightQuery).MaterializeAsync().ConfigureAwait(false); return leftData.CrossJoin(rightData, rowBuilder.CombineRows); }) .Where(multiPartQuery.FilterExpression.GetRowFilter()) .OrderBy(multiPartQuery.OrderByExpressions) .AfterLastElement(count => context.Logger.Verbose($"{this.GetType().Name} returned {count} records.")); } /// <summary> /// Gets the descriptors for this data source. /// </summary> /// <param name="context"> /// The execution context. /// </param> /// <returns> /// All data sources inside this data source. /// </returns> [ItemNotNull] protected internal override async Task<IEnumerable<IDataSourceDescriptor>> GetDataSourceDescriptorsAsync(IExecutionContext context) { return (await this.Left.GetDataSourceDescriptorsAsync(context).ConfigureAwait(false)) .Concat(await this.Right.GetDataSourceDescriptorsAsync(context).ConfigureAwait(false)); } /// <summary> /// The ranges to join filter. /// </summary> /// <param name="filter"> /// The filter. /// </param> /// <returns> /// The <see cref="Expression"/>. /// </returns> private static Expression RangesToJoinFilter(Expression filter) { return GenericVisitor.Visit( (BinaryExpression node) => { if (!node.IsComparison()) { return null; } var rightRange = node.Right as RangeExpression; if (rightRange == null) { var leftRange = node.Left as RangeExpression; if (leftRange == null) { return null; } switch (node.NodeType) { case ExpressionType.Equal: return Expression.AndAlso( OperatorHelper.GenerateExpression(ExpressionType.GreaterThanOrEqual, leftRange.MinExpression, node.Right), OperatorHelper.GenerateExpression(ExpressionType.LessThanOrEqual, leftRange.MaxExpression, node.Right)); case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: return OperatorHelper.GenerateExpression(node.NodeType, leftRange.MinExpression, node.Right); case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: return OperatorHelper.GenerateExpression(node.NodeType, leftRange.MaxExpression, node.Right); case ExpressionType.NotEqual: return Expression.Constant(true); default: return null; } } switch (node.NodeType) { case ExpressionType.Equal: return Expression.AndAlso( OperatorHelper.GenerateExpression(ExpressionType.GreaterThanOrEqual, node.Left, rightRange.MinExpression), OperatorHelper.GenerateExpression(ExpressionType.LessThanOrEqual, node.Left, rightRange.MaxExpression)); case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: return OperatorHelper.GenerateExpression(node.NodeType, node.Left, rightRange.MinExpression); case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: return OperatorHelper.GenerateExpression(node.NodeType, node.Left, rightRange.MaxExpression); case ExpressionType.NotEqual: return Expression.Constant(true); default: return null; } }, filter); } /// <summary> /// Finds the ranges in an expression using the already retrieved rows. /// </summary> /// <param name="context"> /// The context. /// </param> /// <param name="expression"> /// The expression. /// </param> /// <param name="rows"> /// The rows. /// </param> /// <returns> /// A <see cref="Task"/> returning the <see cref="Expression"/> containing ranges. /// </returns> private async Task<Expression> FindRangesAsync(IExecutionContext context, Expression expression, IAsyncReadOnlyCollection<Row> rows) { var ranges = await expression.SplitByOrExpressions().ToRangedExpressionAsync(rows, this.Right.Aliases).ConfigureAwait(false); return ranges .Select(r => r.SimplifyExpression(context)) .Where(r => !object.Equals((r as ConstantExpression)?.Value, false)) .DefaultIfEmpty().Aggregate(Expression.OrElse).SimplifyRanges(); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.Semantics { public class ValueTupleTests : CompilingTestBase { [Fact] public void TestWellKnownMembersForValueTuple() { var source = @" namespace System { struct ValueTuple<T1> { public T1 Item1; } struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; } struct ValueTuple<T1, T2, T3> { public T1 Item1; public T2 Item2; public T3 Item3; } struct ValueTuple<T1, T2, T3, T4> { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; } struct ValueTuple<T1, T2, T3, T4, T5> { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; } struct ValueTuple<T1, T2, T3, T4, T5, T6> { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; } struct ValueTuple<T1, T2, T3, T4, T5, T6, T7> { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; public T7 Item7; } struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; public T7 Item7; public TRest Rest; } }"; var comp = CreateStandardCompilation(source); Assert.Equal("T1 System.ValueTuple<T1>.Item1", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T1__Item1).ToTestDisplayString()); Assert.Equal("T1 System.ValueTuple<T1, T2>.Item1", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T2__Item1).ToTestDisplayString()); Assert.Equal("T2 System.ValueTuple<T1, T2>.Item2", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T2__Item2).ToTestDisplayString()); Assert.Equal("T1 System.ValueTuple<T1, T2, T3>.Item1", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T3__Item1).ToTestDisplayString()); Assert.Equal("T2 System.ValueTuple<T1, T2, T3>.Item2", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T3__Item2).ToTestDisplayString()); Assert.Equal("T3 System.ValueTuple<T1, T2, T3>.Item3", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T3__Item3).ToTestDisplayString()); Assert.Equal("T1 System.ValueTuple<T1, T2, T3, T4>.Item1", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T4__Item1).ToTestDisplayString()); Assert.Equal("T2 System.ValueTuple<T1, T2, T3, T4>.Item2", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T4__Item2).ToTestDisplayString()); Assert.Equal("T3 System.ValueTuple<T1, T2, T3, T4>.Item3", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T4__Item3).ToTestDisplayString()); Assert.Equal("T4 System.ValueTuple<T1, T2, T3, T4>.Item4", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T4__Item4).ToTestDisplayString()); Assert.Equal("T1 System.ValueTuple<T1, T2, T3, T4, T5>.Item1", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T5__Item1).ToTestDisplayString()); Assert.Equal("T2 System.ValueTuple<T1, T2, T3, T4, T5>.Item2", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T5__Item2).ToTestDisplayString()); Assert.Equal("T3 System.ValueTuple<T1, T2, T3, T4, T5>.Item3", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T5__Item3).ToTestDisplayString()); Assert.Equal("T4 System.ValueTuple<T1, T2, T3, T4, T5>.Item4", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T5__Item4).ToTestDisplayString()); Assert.Equal("T5 System.ValueTuple<T1, T2, T3, T4, T5>.Item5", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T5__Item5).ToTestDisplayString()); Assert.Equal("T1 System.ValueTuple<T1, T2, T3, T4, T5, T6>.Item1", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T6__Item1).ToTestDisplayString()); Assert.Equal("T2 System.ValueTuple<T1, T2, T3, T4, T5, T6>.Item2", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T6__Item2).ToTestDisplayString()); Assert.Equal("T3 System.ValueTuple<T1, T2, T3, T4, T5, T6>.Item3", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T6__Item3).ToTestDisplayString()); Assert.Equal("T4 System.ValueTuple<T1, T2, T3, T4, T5, T6>.Item4", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T6__Item4).ToTestDisplayString()); Assert.Equal("T5 System.ValueTuple<T1, T2, T3, T4, T5, T6>.Item5", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T6__Item5).ToTestDisplayString()); Assert.Equal("T6 System.ValueTuple<T1, T2, T3, T4, T5, T6>.Item6", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T6__Item6).ToTestDisplayString()); Assert.Equal("T1 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7>.Item1", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__Item1).ToTestDisplayString()); Assert.Equal("T2 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7>.Item2", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__Item2).ToTestDisplayString()); Assert.Equal("T3 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7>.Item3", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__Item3).ToTestDisplayString()); Assert.Equal("T4 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7>.Item4", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__Item4).ToTestDisplayString()); Assert.Equal("T5 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7>.Item5", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__Item5).ToTestDisplayString()); Assert.Equal("T6 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7>.Item6", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__Item6).ToTestDisplayString()); Assert.Equal("T7 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7>.Item7", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__Item7).ToTestDisplayString()); Assert.Equal("T1 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item1", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Item1).ToTestDisplayString()); Assert.Equal("T2 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item2", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Item2).ToTestDisplayString()); Assert.Equal("T3 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item3", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Item3).ToTestDisplayString()); Assert.Equal("T4 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item4", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Item4).ToTestDisplayString()); Assert.Equal("T5 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item5", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Item5).ToTestDisplayString()); Assert.Equal("T6 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item6", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Item6).ToTestDisplayString()); Assert.Equal("T7 System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Item7", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Item7).ToTestDisplayString()); Assert.Equal("TRest System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>.Rest", comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Rest).ToTestDisplayString()); } [Fact] public void TestMissingWellKnownMembersForValueTuple() { var comp = CreateStandardCompilation(""); Assert.True(comp.GetWellKnownType(WellKnownType.System_ValueTuple_T1).IsErrorType()); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T1__Item1)); Assert.True(comp.GetWellKnownType(WellKnownType.System_ValueTuple_T2).IsErrorType()); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T2__Item1)); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T2__Item2)); Assert.True(comp.GetWellKnownType(WellKnownType.System_ValueTuple_T3).IsErrorType()); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T3__Item1)); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T3__Item2)); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T3__Item3)); Assert.True(comp.GetWellKnownType(WellKnownType.System_ValueTuple_T4).IsErrorType()); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T4__Item1)); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T4__Item2)); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T4__Item3)); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T4__Item4)); Assert.True(comp.GetWellKnownType(WellKnownType.System_ValueTuple_T5).IsErrorType()); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T5__Item1)); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T5__Item2)); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T5__Item3)); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T5__Item4)); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T5__Item5)); Assert.True(comp.GetWellKnownType(WellKnownType.System_ValueTuple_T6).IsErrorType()); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T6__Item1)); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T6__Item2)); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T6__Item3)); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T6__Item4)); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T6__Item6)); Assert.True(comp.GetWellKnownType(WellKnownType.System_ValueTuple_T7).IsErrorType()); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__Item1)); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__Item2)); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__Item3)); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__Item4)); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__Item6)); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__Item7)); Assert.True(comp.GetWellKnownType(WellKnownType.System_ValueTuple_TRest).IsErrorType()); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Item1)); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Item2)); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Item3)); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Item4)); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Item6)); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Item7)); Assert.Null(comp.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__Rest)); } } }
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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.Collections.ObjectModel; using System.Linq; using RestSharp; using Infoplus.Client; using Infoplus.Model; namespace Infoplus.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IShoppingCartConnectionApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Create a shoppingCartConnection /// </summary> /// <remarks> /// Inserts a new shoppingCartConnection using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">ShoppingCartConnection to be inserted.</param> /// <returns>ShoppingCartConnection</returns> ShoppingCartConnection AddShoppingCartConnection (ShoppingCartConnection body); /// <summary> /// Create a shoppingCartConnection /// </summary> /// <remarks> /// Inserts a new shoppingCartConnection using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">ShoppingCartConnection to be inserted.</param> /// <returns>ApiResponse of ShoppingCartConnection</returns> ApiResponse<ShoppingCartConnection> AddShoppingCartConnectionWithHttpInfo (ShoppingCartConnection body); /// <summary> /// Delete a shoppingCartConnection /// </summary> /// <remarks> /// Deletes the shoppingCartConnection identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="shoppingCartConnectionId">Id of the shoppingCartConnection to be deleted.</param> /// <returns></returns> void DeleteShoppingCartConnection (int? shoppingCartConnectionId); /// <summary> /// Delete a shoppingCartConnection /// </summary> /// <remarks> /// Deletes the shoppingCartConnection identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="shoppingCartConnectionId">Id of the shoppingCartConnection to be deleted.</param> /// <returns>ApiResponse of Object(void)</returns> ApiResponse<Object> DeleteShoppingCartConnectionWithHttpInfo (int? shoppingCartConnectionId); /// <summary> /// Search shoppingCartConnections by filter /// </summary> /// <remarks> /// Returns the list of shoppingCartConnections that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>List&lt;ShoppingCartConnection&gt;</returns> List<ShoppingCartConnection> GetShoppingCartConnectionByFilter (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Search shoppingCartConnections by filter /// </summary> /// <remarks> /// Returns the list of shoppingCartConnections that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>ApiResponse of List&lt;ShoppingCartConnection&gt;</returns> ApiResponse<List<ShoppingCartConnection>> GetShoppingCartConnectionByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Get a shoppingCartConnection by id /// </summary> /// <remarks> /// Returns the shoppingCartConnection identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="shoppingCartConnectionId">Id of the shoppingCartConnection to be returned.</param> /// <returns>ShoppingCartConnection</returns> ShoppingCartConnection GetShoppingCartConnectionById (int? shoppingCartConnectionId); /// <summary> /// Get a shoppingCartConnection by id /// </summary> /// <remarks> /// Returns the shoppingCartConnection identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="shoppingCartConnectionId">Id of the shoppingCartConnection to be returned.</param> /// <returns>ApiResponse of ShoppingCartConnection</returns> ApiResponse<ShoppingCartConnection> GetShoppingCartConnectionByIdWithHttpInfo (int? shoppingCartConnectionId); /// <summary> /// Update a shoppingCartConnection /// </summary> /// <remarks> /// Updates an existing shoppingCartConnection using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">ShoppingCartConnection to be updated.</param> /// <returns></returns> void UpdateShoppingCartConnection (ShoppingCartConnection body); /// <summary> /// Update a shoppingCartConnection /// </summary> /// <remarks> /// Updates an existing shoppingCartConnection using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">ShoppingCartConnection to be updated.</param> /// <returns>ApiResponse of Object(void)</returns> ApiResponse<Object> UpdateShoppingCartConnectionWithHttpInfo (ShoppingCartConnection body); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Create a shoppingCartConnection /// </summary> /// <remarks> /// Inserts a new shoppingCartConnection using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">ShoppingCartConnection to be inserted.</param> /// <returns>Task of ShoppingCartConnection</returns> System.Threading.Tasks.Task<ShoppingCartConnection> AddShoppingCartConnectionAsync (ShoppingCartConnection body); /// <summary> /// Create a shoppingCartConnection /// </summary> /// <remarks> /// Inserts a new shoppingCartConnection using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">ShoppingCartConnection to be inserted.</param> /// <returns>Task of ApiResponse (ShoppingCartConnection)</returns> System.Threading.Tasks.Task<ApiResponse<ShoppingCartConnection>> AddShoppingCartConnectionAsyncWithHttpInfo (ShoppingCartConnection body); /// <summary> /// Delete a shoppingCartConnection /// </summary> /// <remarks> /// Deletes the shoppingCartConnection identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="shoppingCartConnectionId">Id of the shoppingCartConnection to be deleted.</param> /// <returns>Task of void</returns> System.Threading.Tasks.Task DeleteShoppingCartConnectionAsync (int? shoppingCartConnectionId); /// <summary> /// Delete a shoppingCartConnection /// </summary> /// <remarks> /// Deletes the shoppingCartConnection identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="shoppingCartConnectionId">Id of the shoppingCartConnection to be deleted.</param> /// <returns>Task of ApiResponse</returns> System.Threading.Tasks.Task<ApiResponse<Object>> DeleteShoppingCartConnectionAsyncWithHttpInfo (int? shoppingCartConnectionId); /// <summary> /// Search shoppingCartConnections by filter /// </summary> /// <remarks> /// Returns the list of shoppingCartConnections that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of List&lt;ShoppingCartConnection&gt;</returns> System.Threading.Tasks.Task<List<ShoppingCartConnection>> GetShoppingCartConnectionByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Search shoppingCartConnections by filter /// </summary> /// <remarks> /// Returns the list of shoppingCartConnections that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of ApiResponse (List&lt;ShoppingCartConnection&gt;)</returns> System.Threading.Tasks.Task<ApiResponse<List<ShoppingCartConnection>>> GetShoppingCartConnectionByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Get a shoppingCartConnection by id /// </summary> /// <remarks> /// Returns the shoppingCartConnection identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="shoppingCartConnectionId">Id of the shoppingCartConnection to be returned.</param> /// <returns>Task of ShoppingCartConnection</returns> System.Threading.Tasks.Task<ShoppingCartConnection> GetShoppingCartConnectionByIdAsync (int? shoppingCartConnectionId); /// <summary> /// Get a shoppingCartConnection by id /// </summary> /// <remarks> /// Returns the shoppingCartConnection identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="shoppingCartConnectionId">Id of the shoppingCartConnection to be returned.</param> /// <returns>Task of ApiResponse (ShoppingCartConnection)</returns> System.Threading.Tasks.Task<ApiResponse<ShoppingCartConnection>> GetShoppingCartConnectionByIdAsyncWithHttpInfo (int? shoppingCartConnectionId); /// <summary> /// Update a shoppingCartConnection /// </summary> /// <remarks> /// Updates an existing shoppingCartConnection using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">ShoppingCartConnection to be updated.</param> /// <returns>Task of void</returns> System.Threading.Tasks.Task UpdateShoppingCartConnectionAsync (ShoppingCartConnection body); /// <summary> /// Update a shoppingCartConnection /// </summary> /// <remarks> /// Updates an existing shoppingCartConnection using the specified data. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">ShoppingCartConnection to be updated.</param> /// <returns>Task of ApiResponse</returns> System.Threading.Tasks.Task<ApiResponse<Object>> UpdateShoppingCartConnectionAsyncWithHttpInfo (ShoppingCartConnection body); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class ShoppingCartConnectionApi : IShoppingCartConnectionApi { private Infoplus.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="ShoppingCartConnectionApi"/> class. /// </summary> /// <returns></returns> public ShoppingCartConnectionApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="ShoppingCartConnectionApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public ShoppingCartConnectionApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public Infoplus.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Create a shoppingCartConnection Inserts a new shoppingCartConnection using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">ShoppingCartConnection to be inserted.</param> /// <returns>ShoppingCartConnection</returns> public ShoppingCartConnection AddShoppingCartConnection (ShoppingCartConnection body) { ApiResponse<ShoppingCartConnection> localVarResponse = AddShoppingCartConnectionWithHttpInfo(body); return localVarResponse.Data; } /// <summary> /// Create a shoppingCartConnection Inserts a new shoppingCartConnection using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">ShoppingCartConnection to be inserted.</param> /// <returns>ApiResponse of ShoppingCartConnection</returns> public ApiResponse< ShoppingCartConnection > AddShoppingCartConnectionWithHttpInfo (ShoppingCartConnection body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling ShoppingCartConnectionApi->AddShoppingCartConnection"); var localVarPath = "/v1.0/shoppingCartConnection"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("AddShoppingCartConnection", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ShoppingCartConnection>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (ShoppingCartConnection) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ShoppingCartConnection))); } /// <summary> /// Create a shoppingCartConnection Inserts a new shoppingCartConnection using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">ShoppingCartConnection to be inserted.</param> /// <returns>Task of ShoppingCartConnection</returns> public async System.Threading.Tasks.Task<ShoppingCartConnection> AddShoppingCartConnectionAsync (ShoppingCartConnection body) { ApiResponse<ShoppingCartConnection> localVarResponse = await AddShoppingCartConnectionAsyncWithHttpInfo(body); return localVarResponse.Data; } /// <summary> /// Create a shoppingCartConnection Inserts a new shoppingCartConnection using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">ShoppingCartConnection to be inserted.</param> /// <returns>Task of ApiResponse (ShoppingCartConnection)</returns> public async System.Threading.Tasks.Task<ApiResponse<ShoppingCartConnection>> AddShoppingCartConnectionAsyncWithHttpInfo (ShoppingCartConnection body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling ShoppingCartConnectionApi->AddShoppingCartConnection"); var localVarPath = "/v1.0/shoppingCartConnection"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("AddShoppingCartConnection", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ShoppingCartConnection>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (ShoppingCartConnection) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ShoppingCartConnection))); } /// <summary> /// Delete a shoppingCartConnection Deletes the shoppingCartConnection identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="shoppingCartConnectionId">Id of the shoppingCartConnection to be deleted.</param> /// <returns></returns> public void DeleteShoppingCartConnection (int? shoppingCartConnectionId) { DeleteShoppingCartConnectionWithHttpInfo(shoppingCartConnectionId); } /// <summary> /// Delete a shoppingCartConnection Deletes the shoppingCartConnection identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="shoppingCartConnectionId">Id of the shoppingCartConnection to be deleted.</param> /// <returns>ApiResponse of Object(void)</returns> public ApiResponse<Object> DeleteShoppingCartConnectionWithHttpInfo (int? shoppingCartConnectionId) { // verify the required parameter 'shoppingCartConnectionId' is set if (shoppingCartConnectionId == null) throw new ApiException(400, "Missing required parameter 'shoppingCartConnectionId' when calling ShoppingCartConnectionApi->DeleteShoppingCartConnection"); var localVarPath = "/v1.0/shoppingCartConnection/{shoppingCartConnectionId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (shoppingCartConnectionId != null) localVarPathParams.Add("shoppingCartConnectionId", Configuration.ApiClient.ParameterToString(shoppingCartConnectionId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("DeleteShoppingCartConnection", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } /// <summary> /// Delete a shoppingCartConnection Deletes the shoppingCartConnection identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="shoppingCartConnectionId">Id of the shoppingCartConnection to be deleted.</param> /// <returns>Task of void</returns> public async System.Threading.Tasks.Task DeleteShoppingCartConnectionAsync (int? shoppingCartConnectionId) { await DeleteShoppingCartConnectionAsyncWithHttpInfo(shoppingCartConnectionId); } /// <summary> /// Delete a shoppingCartConnection Deletes the shoppingCartConnection identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="shoppingCartConnectionId">Id of the shoppingCartConnection to be deleted.</param> /// <returns>Task of ApiResponse</returns> public async System.Threading.Tasks.Task<ApiResponse<Object>> DeleteShoppingCartConnectionAsyncWithHttpInfo (int? shoppingCartConnectionId) { // verify the required parameter 'shoppingCartConnectionId' is set if (shoppingCartConnectionId == null) throw new ApiException(400, "Missing required parameter 'shoppingCartConnectionId' when calling ShoppingCartConnectionApi->DeleteShoppingCartConnection"); var localVarPath = "/v1.0/shoppingCartConnection/{shoppingCartConnectionId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (shoppingCartConnectionId != null) localVarPathParams.Add("shoppingCartConnectionId", Configuration.ApiClient.ParameterToString(shoppingCartConnectionId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("DeleteShoppingCartConnection", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } /// <summary> /// Search shoppingCartConnections by filter Returns the list of shoppingCartConnections that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>List&lt;ShoppingCartConnection&gt;</returns> public List<ShoppingCartConnection> GetShoppingCartConnectionByFilter (string filter = null, int? page = null, int? limit = null, string sort = null) { ApiResponse<List<ShoppingCartConnection>> localVarResponse = GetShoppingCartConnectionByFilterWithHttpInfo(filter, page, limit, sort); return localVarResponse.Data; } /// <summary> /// Search shoppingCartConnections by filter Returns the list of shoppingCartConnections that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>ApiResponse of List&lt;ShoppingCartConnection&gt;</returns> public ApiResponse< List<ShoppingCartConnection> > GetShoppingCartConnectionByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null) { var localVarPath = "/v1.0/shoppingCartConnection/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetShoppingCartConnectionByFilter", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<ShoppingCartConnection>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<ShoppingCartConnection>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<ShoppingCartConnection>))); } /// <summary> /// Search shoppingCartConnections by filter Returns the list of shoppingCartConnections that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of List&lt;ShoppingCartConnection&gt;</returns> public async System.Threading.Tasks.Task<List<ShoppingCartConnection>> GetShoppingCartConnectionByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null) { ApiResponse<List<ShoppingCartConnection>> localVarResponse = await GetShoppingCartConnectionByFilterAsyncWithHttpInfo(filter, page, limit, sort); return localVarResponse.Data; } /// <summary> /// Search shoppingCartConnections by filter Returns the list of shoppingCartConnections that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of ApiResponse (List&lt;ShoppingCartConnection&gt;)</returns> public async System.Threading.Tasks.Task<ApiResponse<List<ShoppingCartConnection>>> GetShoppingCartConnectionByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null) { var localVarPath = "/v1.0/shoppingCartConnection/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetShoppingCartConnectionByFilter", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<ShoppingCartConnection>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<ShoppingCartConnection>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<ShoppingCartConnection>))); } /// <summary> /// Get a shoppingCartConnection by id Returns the shoppingCartConnection identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="shoppingCartConnectionId">Id of the shoppingCartConnection to be returned.</param> /// <returns>ShoppingCartConnection</returns> public ShoppingCartConnection GetShoppingCartConnectionById (int? shoppingCartConnectionId) { ApiResponse<ShoppingCartConnection> localVarResponse = GetShoppingCartConnectionByIdWithHttpInfo(shoppingCartConnectionId); return localVarResponse.Data; } /// <summary> /// Get a shoppingCartConnection by id Returns the shoppingCartConnection identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="shoppingCartConnectionId">Id of the shoppingCartConnection to be returned.</param> /// <returns>ApiResponse of ShoppingCartConnection</returns> public ApiResponse< ShoppingCartConnection > GetShoppingCartConnectionByIdWithHttpInfo (int? shoppingCartConnectionId) { // verify the required parameter 'shoppingCartConnectionId' is set if (shoppingCartConnectionId == null) throw new ApiException(400, "Missing required parameter 'shoppingCartConnectionId' when calling ShoppingCartConnectionApi->GetShoppingCartConnectionById"); var localVarPath = "/v1.0/shoppingCartConnection/{shoppingCartConnectionId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (shoppingCartConnectionId != null) localVarPathParams.Add("shoppingCartConnectionId", Configuration.ApiClient.ParameterToString(shoppingCartConnectionId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetShoppingCartConnectionById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ShoppingCartConnection>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (ShoppingCartConnection) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ShoppingCartConnection))); } /// <summary> /// Get a shoppingCartConnection by id Returns the shoppingCartConnection identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="shoppingCartConnectionId">Id of the shoppingCartConnection to be returned.</param> /// <returns>Task of ShoppingCartConnection</returns> public async System.Threading.Tasks.Task<ShoppingCartConnection> GetShoppingCartConnectionByIdAsync (int? shoppingCartConnectionId) { ApiResponse<ShoppingCartConnection> localVarResponse = await GetShoppingCartConnectionByIdAsyncWithHttpInfo(shoppingCartConnectionId); return localVarResponse.Data; } /// <summary> /// Get a shoppingCartConnection by id Returns the shoppingCartConnection identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="shoppingCartConnectionId">Id of the shoppingCartConnection to be returned.</param> /// <returns>Task of ApiResponse (ShoppingCartConnection)</returns> public async System.Threading.Tasks.Task<ApiResponse<ShoppingCartConnection>> GetShoppingCartConnectionByIdAsyncWithHttpInfo (int? shoppingCartConnectionId) { // verify the required parameter 'shoppingCartConnectionId' is set if (shoppingCartConnectionId == null) throw new ApiException(400, "Missing required parameter 'shoppingCartConnectionId' when calling ShoppingCartConnectionApi->GetShoppingCartConnectionById"); var localVarPath = "/v1.0/shoppingCartConnection/{shoppingCartConnectionId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (shoppingCartConnectionId != null) localVarPathParams.Add("shoppingCartConnectionId", Configuration.ApiClient.ParameterToString(shoppingCartConnectionId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetShoppingCartConnectionById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ShoppingCartConnection>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (ShoppingCartConnection) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ShoppingCartConnection))); } /// <summary> /// Update a shoppingCartConnection Updates an existing shoppingCartConnection using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">ShoppingCartConnection to be updated.</param> /// <returns></returns> public void UpdateShoppingCartConnection (ShoppingCartConnection body) { UpdateShoppingCartConnectionWithHttpInfo(body); } /// <summary> /// Update a shoppingCartConnection Updates an existing shoppingCartConnection using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">ShoppingCartConnection to be updated.</param> /// <returns>ApiResponse of Object(void)</returns> public ApiResponse<Object> UpdateShoppingCartConnectionWithHttpInfo (ShoppingCartConnection body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling ShoppingCartConnectionApi->UpdateShoppingCartConnection"); var localVarPath = "/v1.0/shoppingCartConnection"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("UpdateShoppingCartConnection", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } /// <summary> /// Update a shoppingCartConnection Updates an existing shoppingCartConnection using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">ShoppingCartConnection to be updated.</param> /// <returns>Task of void</returns> public async System.Threading.Tasks.Task UpdateShoppingCartConnectionAsync (ShoppingCartConnection body) { await UpdateShoppingCartConnectionAsyncWithHttpInfo(body); } /// <summary> /// Update a shoppingCartConnection Updates an existing shoppingCartConnection using the specified data. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="body">ShoppingCartConnection to be updated.</param> /// <returns>Task of ApiResponse</returns> public async System.Threading.Tasks.Task<ApiResponse<Object>> UpdateShoppingCartConnectionAsyncWithHttpInfo (ShoppingCartConnection body) { // verify the required parameter 'body' is set if (body == null) throw new ApiException(400, "Missing required parameter 'body' when calling ShoppingCartConnectionApi->UpdateShoppingCartConnection"); var localVarPath = "/v1.0/shoppingCartConnection"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (body != null && body.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter } else { localVarPostBody = body; // byte array } // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("UpdateShoppingCartConnection", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), null); } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using CodeJam.PerfTests; using CodeJam.Ranges; using JetBrains.Annotations; using NUnit.Framework; using static CodeJam.PerfTests.CompetitionHelpers; namespace CodeJam.RangesAlternatives { /// <summary> /// Test to choose valid Range(of T) implementation. /// </summary> [TestFixture(Category = PerfTestCategory + ": Ranges")] [CompetitionBurstMode] [SuppressMessage("ReSharper", "PassStringInterpolation")] public class RangeAlternativesPerfTests { [Test] public void RunRangeAlternativesIntCase() => Competition.Run<RangeAlternativesIntCase>(); [PublicAPI] public class RangeAlternativesIntCase { private static readonly int Count = CompetitionRunHelpers.BurstModeLoopCount / 16; private readonly KeyValuePair<int, int>[] _data; private readonly RangeStub<int>[] _rangeData; private readonly RangeStub<int, string>[] _rangeKeyData; private readonly RangeStubCompact<int>[] _rangeCompactData; private readonly Range<int>[] _rangeDataImpl; private readonly Range<int, string>[] _rangeKeyDataImpl; public RangeAlternativesIntCase() { _data = new KeyValuePair<int, int>[Count]; _rangeData = new RangeStub<int>[Count]; _rangeKeyData = new RangeStub<int, string>[Count]; _rangeCompactData = new RangeStubCompact<int>[Count]; _rangeDataImpl = new Range<int>[Count]; _rangeKeyDataImpl = new Range<int, string>[Count]; for (var i = 0; i < _data.Length; i++) { _data[i] = new KeyValuePair<int, int>(i, i + 1); _rangeData[i] = new RangeStub<int>(i, i + 1); _rangeKeyData[i] = new RangeStub<int, string>(i, i + 1, i.ToString()); _rangeCompactData[i] = new RangeStubCompact<int>(i, i + 1); _rangeDataImpl[i] = new Range<int>(i, i + 1); _rangeKeyDataImpl[i] = new Range<int, string>(i, i + 1, i.ToString()); } } [CompetitionBaseline] [GcAllocations(0)] public KeyValuePair<int, int> Test00DirectCompare() { var result = _data[0]; for (var i = 1; i < _data.Length; i++) { result = new KeyValuePair<int, int>( result.Key < _data[i].Key ? result.Key : _data[i].Key, result.Value > _data[i].Value ? result.Value : _data[i].Value); } return result; } [CompetitionBenchmark(10.53, 29.99)] [GcAllocations(0)] public RangeStub<int> Test01Range() { var result = _rangeData[0]; for (var i = 1; i < _rangeData.Length; i++) { result = result.Union(_rangeData[i]); } return result; } [CompetitionBenchmark(10.33, 29.58)] [GcAllocations(0)] public RangeStub<int, string> Test02KeyRange() { var result = _rangeKeyData[0]; for (var i = 1; i < _rangeKeyData.Length; i++) { result = result.Union(_rangeKeyData[i]); } return result; } [CompetitionBenchmark(30.44, 87.87)] [GcAllocations(0)] public RangeStubCompact<int> Test03CompactRange() { var result = _rangeCompactData[0]; for (var i = 1; i < _rangeCompactData.Length; i++) { result = result.Union(_rangeCompactData[i]); } return result; } [CompetitionBenchmark(14.74, 42.21)] [GcAllocations(0)] public Range<int> Test04RangeImpl() { var result = _rangeDataImpl[0]; for (var i = 1; i < _rangeDataImpl.Length; i++) { result = result.Union(_rangeDataImpl[i]); } return result; } [CompetitionBenchmark(16.45, 44.15)] [GcAllocations(0)] public Range<int, string> Test05RangeKeyImpl() { var result = _rangeKeyDataImpl[0]; for (var i = 1; i < _rangeKeyDataImpl.Length; i++) { result = result.Union(_rangeKeyDataImpl[i]); } return result; } } [Test] public void RunRangeAlternativesNullableIntCase() => Competition.Run<RangeAlternativesNullableIntCase>(); [PublicAPI] public class RangeAlternativesNullableIntCase { private static readonly int Count = CompetitionRunHelpers.SmallLoopCount; private readonly KeyValuePair<int?, int?>[] _data; private readonly RangeStub<int?>[] _rangeData; private readonly RangeStub<int?, string>[] _rangeKeyData; private readonly RangeStubCompact<int?>[] _rangeCompactData; private readonly Range<int?>[] _rangeDataImpl; private readonly Range<int?, string>[] _rangeKeyDataImpl; public RangeAlternativesNullableIntCase() { _data = new KeyValuePair<int?, int?>[Count]; _rangeData = new RangeStub<int?>[Count]; _rangeKeyData = new RangeStub<int?, string>[Count]; _rangeCompactData = new RangeStubCompact<int?>[Count]; _rangeDataImpl = new Range<int?>[Count]; _rangeKeyDataImpl = new Range<int?, string>[Count]; for (var i = 0; i < _data.Length; i++) { _data[i] = new KeyValuePair<int?, int?>(i, i + 1); _rangeData[i] = new RangeStub<int?>(i, i + 1); _rangeKeyData[i] = new RangeStub<int?, string>(i, i + 1, i.ToString()); _rangeCompactData[i] = new RangeStubCompact<int?>(i, i + 1); _rangeDataImpl[i] = new Range<int?>(i, i + 1); _rangeKeyDataImpl[i] = new Range<int?, string>(i, i + 1, i.ToString()); } } [CompetitionBaseline] [GcAllocations(0)] public KeyValuePair<int?, int?> Test00DirectCompare() { var result = _data[0]; for (var i = 1; i < _data.Length; i++) { result = new KeyValuePair<int?, int?>( result.Key < _data[i].Key ? result.Key : _data[i].Key, result.Value > _data[i].Value ? result.Value : _data[i].Value); } return result; } [CompetitionBenchmark(2.93, 6.11)] [GcAllocations(0)] public RangeStub<int?> Test01Range() { var result = _rangeData[0]; for (var i = 1; i < _rangeData.Length; i++) { result = result.Union(_rangeData[i]); } return result; } [CompetitionBenchmark(3.15, 7.32)] [GcAllocations(0)] public RangeStub<int?, string> Test02KeyRange() { var result = _rangeKeyData[0]; for (var i = 1; i < _rangeKeyData.Length; i++) { result = result.Union(_rangeKeyData[i]); } return result; } [CompetitionBenchmark(10.94, 17.87)] [GcAllocations(0)] public RangeStubCompact<int?> Test03CompactRange() { var result = _rangeCompactData[0]; for (var i = 1; i < _rangeCompactData.Length; i++) { result = result.Union(_rangeCompactData[i]); } return result; } [CompetitionBenchmark(4.77, 8.67)] [GcAllocations(0)] public Range<int?> Test04RangeImpl() { var result = _rangeDataImpl[0]; for (var i = 1; i < _rangeDataImpl.Length; i++) { result = result.Union(_rangeDataImpl[i]); } return result; } [CompetitionBenchmark(5.35, 11.14)] [GcAllocations(0)] public Range<int?, string> Test05RangeKeyImpl() { var result = _rangeKeyDataImpl[0]; for (var i = 1; i < _rangeKeyDataImpl.Length; i++) { result = result.Union(_rangeKeyDataImpl[i]); } return result; } } } }
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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.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> /// FulfillmentPlan /// </summary> [DataContract] public partial class FulfillmentPlan : IEquatable<FulfillmentPlan> { /// <summary> /// Initializes a new instance of the <see cref="FulfillmentPlan" /> class. /// </summary> [JsonConstructorAttribute] protected FulfillmentPlan() { } /// <summary> /// Initializes a new instance of the <see cref="FulfillmentPlan" /> class. /// </summary> /// <param name="Name">Name (required).</param> /// <param name="Description">Description.</param> /// <param name="WarehouseId">WarehouseId (required).</param> /// <param name="OrderSmartFilterId">OrderSmartFilterId (required).</param> /// <param name="LocationSmartFilterId">LocationSmartFilterId.</param> /// <param name="MaximumNumberOfOrders">MaximumNumberOfOrders.</param> /// <param name="CreatePickWork">CreatePickWork (required) (default to false).</param> /// <param name="PickingRule">PickingRule.</param> /// <param name="LayoutRule">LayoutRule.</param> /// <param name="PickSortRule">PickSortRule.</param> /// <param name="CreatePickList">CreatePickList (default to false).</param> /// <param name="PickListFormat">PickListFormat.</param> /// <param name="PickListLayout">PickListLayout.</param> /// <param name="PickListGroup">PickListGroup.</param> /// <param name="PickListSort">PickListSort.</param> /// <param name="CreatePickSummary">CreatePickSummary (default to false).</param> /// <param name="PickSummaryFormat">PickSummaryFormat.</param> /// <param name="PickSummaryLayout">PickSummaryLayout.</param> /// <param name="PickSummarySort">PickSummarySort.</param> /// <param name="CartonizeOrders">CartonizeOrders (required) (default to false).</param> /// <param name="AutoShipCasebreakCartons">AutoShipCasebreakCartons (default to false).</param> /// <param name="PreGenerateParcelLabels">PreGenerateParcelLabels (default to false).</param> /// <param name="OverridePackingSlipTemplateId">OverridePackingSlipTemplateId.</param> /// <param name="CreatePackingSlip">CreatePackingSlip (required) (default to false).</param> /// <param name="CreateOrderAssemblyGuide">CreateOrderAssemblyGuide (default to false).</param> public FulfillmentPlan(string Name = null, string Description = null, int? WarehouseId = null, int? OrderSmartFilterId = null, int? LocationSmartFilterId = null, int? MaximumNumberOfOrders = null, bool? CreatePickWork = null, string PickingRule = null, string LayoutRule = null, string PickSortRule = null, bool? CreatePickList = null, string PickListFormat = null, string PickListLayout = null, string PickListGroup = null, string PickListSort = null, bool? CreatePickSummary = null, string PickSummaryFormat = null, string PickSummaryLayout = null, string PickSummarySort = null, bool? CartonizeOrders = null, bool? AutoShipCasebreakCartons = null, bool? PreGenerateParcelLabels = null, int? OverridePackingSlipTemplateId = null, bool? CreatePackingSlip = null, bool? CreateOrderAssemblyGuide = null) { // to ensure "Name" is required (not null) if (Name == null) { throw new InvalidDataException("Name is a required property for FulfillmentPlan and cannot be null"); } else { this.Name = Name; } // to ensure "WarehouseId" is required (not null) if (WarehouseId == null) { throw new InvalidDataException("WarehouseId is a required property for FulfillmentPlan and cannot be null"); } else { this.WarehouseId = WarehouseId; } // to ensure "OrderSmartFilterId" is required (not null) if (OrderSmartFilterId == null) { throw new InvalidDataException("OrderSmartFilterId is a required property for FulfillmentPlan and cannot be null"); } else { this.OrderSmartFilterId = OrderSmartFilterId; } // to ensure "CreatePickWork" is required (not null) if (CreatePickWork == null) { throw new InvalidDataException("CreatePickWork is a required property for FulfillmentPlan and cannot be null"); } else { this.CreatePickWork = CreatePickWork; } // to ensure "CartonizeOrders" is required (not null) if (CartonizeOrders == null) { throw new InvalidDataException("CartonizeOrders is a required property for FulfillmentPlan and cannot be null"); } else { this.CartonizeOrders = CartonizeOrders; } // to ensure "CreatePackingSlip" is required (not null) if (CreatePackingSlip == null) { throw new InvalidDataException("CreatePackingSlip is a required property for FulfillmentPlan and cannot be null"); } else { this.CreatePackingSlip = CreatePackingSlip; } this.Description = Description; this.LocationSmartFilterId = LocationSmartFilterId; this.MaximumNumberOfOrders = MaximumNumberOfOrders; this.PickingRule = PickingRule; this.LayoutRule = LayoutRule; this.PickSortRule = PickSortRule; // use default value if no "CreatePickList" provided if (CreatePickList == null) { this.CreatePickList = false; } else { this.CreatePickList = CreatePickList; } this.PickListFormat = PickListFormat; this.PickListLayout = PickListLayout; this.PickListGroup = PickListGroup; this.PickListSort = PickListSort; // use default value if no "CreatePickSummary" provided if (CreatePickSummary == null) { this.CreatePickSummary = false; } else { this.CreatePickSummary = CreatePickSummary; } this.PickSummaryFormat = PickSummaryFormat; this.PickSummaryLayout = PickSummaryLayout; this.PickSummarySort = PickSummarySort; // use default value if no "AutoShipCasebreakCartons" provided if (AutoShipCasebreakCartons == null) { this.AutoShipCasebreakCartons = false; } else { this.AutoShipCasebreakCartons = AutoShipCasebreakCartons; } // use default value if no "PreGenerateParcelLabels" provided if (PreGenerateParcelLabels == null) { this.PreGenerateParcelLabels = false; } else { this.PreGenerateParcelLabels = PreGenerateParcelLabels; } this.OverridePackingSlipTemplateId = OverridePackingSlipTemplateId; // use default value if no "CreateOrderAssemblyGuide" provided if (CreateOrderAssemblyGuide == null) { this.CreateOrderAssemblyGuide = false; } else { this.CreateOrderAssemblyGuide = CreateOrderAssemblyGuide; } } /// <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 Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Gets or Sets Description /// </summary> [DataMember(Name="description", EmitDefaultValue=false)] public string Description { get; set; } /// <summary> /// Gets or Sets WarehouseId /// </summary> [DataMember(Name="warehouseId", EmitDefaultValue=false)] public int? WarehouseId { get; set; } /// <summary> /// Gets or Sets OrderSmartFilterId /// </summary> [DataMember(Name="orderSmartFilterId", EmitDefaultValue=false)] public int? OrderSmartFilterId { get; set; } /// <summary> /// Gets or Sets LocationSmartFilterId /// </summary> [DataMember(Name="locationSmartFilterId", EmitDefaultValue=false)] public int? LocationSmartFilterId { get; set; } /// <summary> /// Gets or Sets MaximumNumberOfOrders /// </summary> [DataMember(Name="maximumNumberOfOrders", EmitDefaultValue=false)] public int? MaximumNumberOfOrders { get; set; } /// <summary> /// Gets or Sets CreatePickWork /// </summary> [DataMember(Name="createPickWork", EmitDefaultValue=false)] public bool? CreatePickWork { get; set; } /// <summary> /// Gets or Sets PickingRule /// </summary> [DataMember(Name="pickingRule", EmitDefaultValue=false)] public string PickingRule { get; set; } /// <summary> /// Gets or Sets LayoutRule /// </summary> [DataMember(Name="layoutRule", EmitDefaultValue=false)] public string LayoutRule { get; set; } /// <summary> /// Gets or Sets PickSortRule /// </summary> [DataMember(Name="pickSortRule", EmitDefaultValue=false)] public string PickSortRule { get; set; } /// <summary> /// Gets or Sets CreatePickList /// </summary> [DataMember(Name="createPickList", EmitDefaultValue=false)] public bool? CreatePickList { get; set; } /// <summary> /// Gets or Sets PickListFormat /// </summary> [DataMember(Name="pickListFormat", EmitDefaultValue=false)] public string PickListFormat { get; set; } /// <summary> /// Gets or Sets PickListLayout /// </summary> [DataMember(Name="pickListLayout", EmitDefaultValue=false)] public string PickListLayout { get; set; } /// <summary> /// Gets or Sets PickListGroup /// </summary> [DataMember(Name="pickListGroup", EmitDefaultValue=false)] public string PickListGroup { get; set; } /// <summary> /// Gets or Sets PickListSort /// </summary> [DataMember(Name="pickListSort", EmitDefaultValue=false)] public string PickListSort { get; set; } /// <summary> /// Gets or Sets CreatePickSummary /// </summary> [DataMember(Name="createPickSummary", EmitDefaultValue=false)] public bool? CreatePickSummary { get; set; } /// <summary> /// Gets or Sets PickSummaryFormat /// </summary> [DataMember(Name="pickSummaryFormat", EmitDefaultValue=false)] public string PickSummaryFormat { get; set; } /// <summary> /// Gets or Sets PickSummaryLayout /// </summary> [DataMember(Name="pickSummaryLayout", EmitDefaultValue=false)] public string PickSummaryLayout { get; set; } /// <summary> /// Gets or Sets PickSummarySort /// </summary> [DataMember(Name="pickSummarySort", EmitDefaultValue=false)] public string PickSummarySort { get; set; } /// <summary> /// Gets or Sets CartonizeOrders /// </summary> [DataMember(Name="cartonizeOrders", EmitDefaultValue=false)] public bool? CartonizeOrders { get; set; } /// <summary> /// Gets or Sets AutoShipCasebreakCartons /// </summary> [DataMember(Name="autoShipCasebreakCartons", EmitDefaultValue=false)] public bool? AutoShipCasebreakCartons { get; set; } /// <summary> /// Gets or Sets PreGenerateParcelLabels /// </summary> [DataMember(Name="preGenerateParcelLabels", EmitDefaultValue=false)] public bool? PreGenerateParcelLabels { get; set; } /// <summary> /// Gets or Sets OverridePackingSlipTemplateId /// </summary> [DataMember(Name="overridePackingSlipTemplateId", EmitDefaultValue=false)] public int? OverridePackingSlipTemplateId { get; set; } /// <summary> /// Gets or Sets CreatePackingSlip /// </summary> [DataMember(Name="createPackingSlip", EmitDefaultValue=false)] public bool? CreatePackingSlip { get; set; } /// <summary> /// Gets or Sets CreateOrderAssemblyGuide /// </summary> [DataMember(Name="createOrderAssemblyGuide", EmitDefaultValue=false)] public bool? CreateOrderAssemblyGuide { 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 FulfillmentPlan {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" CreateDate: ").Append(CreateDate).Append("\n"); sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Description: ").Append(Description).Append("\n"); sb.Append(" WarehouseId: ").Append(WarehouseId).Append("\n"); sb.Append(" OrderSmartFilterId: ").Append(OrderSmartFilterId).Append("\n"); sb.Append(" LocationSmartFilterId: ").Append(LocationSmartFilterId).Append("\n"); sb.Append(" MaximumNumberOfOrders: ").Append(MaximumNumberOfOrders).Append("\n"); sb.Append(" CreatePickWork: ").Append(CreatePickWork).Append("\n"); sb.Append(" PickingRule: ").Append(PickingRule).Append("\n"); sb.Append(" LayoutRule: ").Append(LayoutRule).Append("\n"); sb.Append(" PickSortRule: ").Append(PickSortRule).Append("\n"); sb.Append(" CreatePickList: ").Append(CreatePickList).Append("\n"); sb.Append(" PickListFormat: ").Append(PickListFormat).Append("\n"); sb.Append(" PickListLayout: ").Append(PickListLayout).Append("\n"); sb.Append(" PickListGroup: ").Append(PickListGroup).Append("\n"); sb.Append(" PickListSort: ").Append(PickListSort).Append("\n"); sb.Append(" CreatePickSummary: ").Append(CreatePickSummary).Append("\n"); sb.Append(" PickSummaryFormat: ").Append(PickSummaryFormat).Append("\n"); sb.Append(" PickSummaryLayout: ").Append(PickSummaryLayout).Append("\n"); sb.Append(" PickSummarySort: ").Append(PickSummarySort).Append("\n"); sb.Append(" CartonizeOrders: ").Append(CartonizeOrders).Append("\n"); sb.Append(" AutoShipCasebreakCartons: ").Append(AutoShipCasebreakCartons).Append("\n"); sb.Append(" PreGenerateParcelLabels: ").Append(PreGenerateParcelLabels).Append("\n"); sb.Append(" OverridePackingSlipTemplateId: ").Append(OverridePackingSlipTemplateId).Append("\n"); sb.Append(" CreatePackingSlip: ").Append(CreatePackingSlip).Append("\n"); sb.Append(" CreateOrderAssemblyGuide: ").Append(CreateOrderAssemblyGuide).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 FulfillmentPlan); } /// <summary> /// Returns true if FulfillmentPlan instances are equal /// </summary> /// <param name="other">Instance of FulfillmentPlan to be compared</param> /// <returns>Boolean</returns> public bool Equals(FulfillmentPlan 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.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.Description == other.Description || this.Description != null && this.Description.Equals(other.Description) ) && ( this.WarehouseId == other.WarehouseId || this.WarehouseId != null && this.WarehouseId.Equals(other.WarehouseId) ) && ( this.OrderSmartFilterId == other.OrderSmartFilterId || this.OrderSmartFilterId != null && this.OrderSmartFilterId.Equals(other.OrderSmartFilterId) ) && ( this.LocationSmartFilterId == other.LocationSmartFilterId || this.LocationSmartFilterId != null && this.LocationSmartFilterId.Equals(other.LocationSmartFilterId) ) && ( this.MaximumNumberOfOrders == other.MaximumNumberOfOrders || this.MaximumNumberOfOrders != null && this.MaximumNumberOfOrders.Equals(other.MaximumNumberOfOrders) ) && ( this.CreatePickWork == other.CreatePickWork || this.CreatePickWork != null && this.CreatePickWork.Equals(other.CreatePickWork) ) && ( this.PickingRule == other.PickingRule || this.PickingRule != null && this.PickingRule.Equals(other.PickingRule) ) && ( this.LayoutRule == other.LayoutRule || this.LayoutRule != null && this.LayoutRule.Equals(other.LayoutRule) ) && ( this.PickSortRule == other.PickSortRule || this.PickSortRule != null && this.PickSortRule.Equals(other.PickSortRule) ) && ( this.CreatePickList == other.CreatePickList || this.CreatePickList != null && this.CreatePickList.Equals(other.CreatePickList) ) && ( this.PickListFormat == other.PickListFormat || this.PickListFormat != null && this.PickListFormat.Equals(other.PickListFormat) ) && ( this.PickListLayout == other.PickListLayout || this.PickListLayout != null && this.PickListLayout.Equals(other.PickListLayout) ) && ( this.PickListGroup == other.PickListGroup || this.PickListGroup != null && this.PickListGroup.Equals(other.PickListGroup) ) && ( this.PickListSort == other.PickListSort || this.PickListSort != null && this.PickListSort.Equals(other.PickListSort) ) && ( this.CreatePickSummary == other.CreatePickSummary || this.CreatePickSummary != null && this.CreatePickSummary.Equals(other.CreatePickSummary) ) && ( this.PickSummaryFormat == other.PickSummaryFormat || this.PickSummaryFormat != null && this.PickSummaryFormat.Equals(other.PickSummaryFormat) ) && ( this.PickSummaryLayout == other.PickSummaryLayout || this.PickSummaryLayout != null && this.PickSummaryLayout.Equals(other.PickSummaryLayout) ) && ( this.PickSummarySort == other.PickSummarySort || this.PickSummarySort != null && this.PickSummarySort.Equals(other.PickSummarySort) ) && ( this.CartonizeOrders == other.CartonizeOrders || this.CartonizeOrders != null && this.CartonizeOrders.Equals(other.CartonizeOrders) ) && ( this.AutoShipCasebreakCartons == other.AutoShipCasebreakCartons || this.AutoShipCasebreakCartons != null && this.AutoShipCasebreakCartons.Equals(other.AutoShipCasebreakCartons) ) && ( this.PreGenerateParcelLabels == other.PreGenerateParcelLabels || this.PreGenerateParcelLabels != null && this.PreGenerateParcelLabels.Equals(other.PreGenerateParcelLabels) ) && ( this.OverridePackingSlipTemplateId == other.OverridePackingSlipTemplateId || this.OverridePackingSlipTemplateId != null && this.OverridePackingSlipTemplateId.Equals(other.OverridePackingSlipTemplateId) ) && ( this.CreatePackingSlip == other.CreatePackingSlip || this.CreatePackingSlip != null && this.CreatePackingSlip.Equals(other.CreatePackingSlip) ) && ( this.CreateOrderAssemblyGuide == other.CreateOrderAssemblyGuide || this.CreateOrderAssemblyGuide != null && this.CreateOrderAssemblyGuide.Equals(other.CreateOrderAssemblyGuide) ); } /// <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.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.Description != null) hash = hash * 59 + this.Description.GetHashCode(); if (this.WarehouseId != null) hash = hash * 59 + this.WarehouseId.GetHashCode(); if (this.OrderSmartFilterId != null) hash = hash * 59 + this.OrderSmartFilterId.GetHashCode(); if (this.LocationSmartFilterId != null) hash = hash * 59 + this.LocationSmartFilterId.GetHashCode(); if (this.MaximumNumberOfOrders != null) hash = hash * 59 + this.MaximumNumberOfOrders.GetHashCode(); if (this.CreatePickWork != null) hash = hash * 59 + this.CreatePickWork.GetHashCode(); if (this.PickingRule != null) hash = hash * 59 + this.PickingRule.GetHashCode(); if (this.LayoutRule != null) hash = hash * 59 + this.LayoutRule.GetHashCode(); if (this.PickSortRule != null) hash = hash * 59 + this.PickSortRule.GetHashCode(); if (this.CreatePickList != null) hash = hash * 59 + this.CreatePickList.GetHashCode(); if (this.PickListFormat != null) hash = hash * 59 + this.PickListFormat.GetHashCode(); if (this.PickListLayout != null) hash = hash * 59 + this.PickListLayout.GetHashCode(); if (this.PickListGroup != null) hash = hash * 59 + this.PickListGroup.GetHashCode(); if (this.PickListSort != null) hash = hash * 59 + this.PickListSort.GetHashCode(); if (this.CreatePickSummary != null) hash = hash * 59 + this.CreatePickSummary.GetHashCode(); if (this.PickSummaryFormat != null) hash = hash * 59 + this.PickSummaryFormat.GetHashCode(); if (this.PickSummaryLayout != null) hash = hash * 59 + this.PickSummaryLayout.GetHashCode(); if (this.PickSummarySort != null) hash = hash * 59 + this.PickSummarySort.GetHashCode(); if (this.CartonizeOrders != null) hash = hash * 59 + this.CartonizeOrders.GetHashCode(); if (this.AutoShipCasebreakCartons != null) hash = hash * 59 + this.AutoShipCasebreakCartons.GetHashCode(); if (this.PreGenerateParcelLabels != null) hash = hash * 59 + this.PreGenerateParcelLabels.GetHashCode(); if (this.OverridePackingSlipTemplateId != null) hash = hash * 59 + this.OverridePackingSlipTemplateId.GetHashCode(); if (this.CreatePackingSlip != null) hash = hash * 59 + this.CreatePackingSlip.GetHashCode(); if (this.CreateOrderAssemblyGuide != null) hash = hash * 59 + this.CreateOrderAssemblyGuide.GetHashCode(); return hash; } } } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace Jovian.Tools.Support { /// <summary> /// Summary description for rtfReplace. /// </summary> public class rtfReplace : System.Windows.Forms.UserControl { private System.Windows.Forms.ListBox lstSearchResults; private System.Windows.Forms.Label clkCancel; private System.Windows.Forms.ImageList imgList; private System.ComponentModel.IContainer components; private System.Windows.Forms.ComboBox cmoBox; private System.Windows.Forms.Button btnFilter; private System.Windows.Forms.Button btnRemove; private System.Windows.Forms.Button btnDelete; private System.Windows.Forms.Button btnReplace; private System.Windows.Forms.TextBox txtRepTxt; private JovianEdit Owner; public rtfReplace(JovianEdit own) { Owner = own; // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // TODO: Add any initialization after the InitializeComponent call } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(rtfReplace)); this.lstSearchResults = new System.Windows.Forms.ListBox(); this.clkCancel = new System.Windows.Forms.Label(); this.imgList = new System.Windows.Forms.ImageList(this.components); this.cmoBox = new System.Windows.Forms.ComboBox(); this.btnFilter = new System.Windows.Forms.Button(); this.btnRemove = new System.Windows.Forms.Button(); this.btnDelete = new System.Windows.Forms.Button(); this.btnReplace = new System.Windows.Forms.Button(); this.txtRepTxt = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // lstSearchResults // this.lstSearchResults.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.lstSearchResults.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.lstSearchResults.Cursor = System.Windows.Forms.Cursors.Arrow; this.lstSearchResults.Location = new System.Drawing.Point(4, 46); this.lstSearchResults.Name = "lstSearchResults"; this.lstSearchResults.Size = new System.Drawing.Size(80, 145); this.lstSearchResults.TabIndex = 0; this.lstSearchResults.SelectedIndexChanged += new System.EventHandler(this.lstSearchResults_SelectedIndexChanged); // // clkCancel // this.clkCancel.Cursor = System.Windows.Forms.Cursors.Hand; this.clkCancel.ImageIndex = 0; this.clkCancel.ImageList = this.imgList; this.clkCancel.Location = new System.Drawing.Point(68, 2); this.clkCancel.Name = "clkCancel"; this.clkCancel.Size = new System.Drawing.Size(18, 16); this.clkCancel.TabIndex = 8; this.clkCancel.Click += new System.EventHandler(this.clkCancel_Click); this.clkCancel.MouseEnter += new System.EventHandler(this.clkCancel_MouseEnter); this.clkCancel.MouseLeave += new System.EventHandler(this.clkCancel_MouseLeave); // // imgList // this.imgList.ImageSize = new System.Drawing.Size(16, 16); this.imgList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imgList.ImageStream"))); this.imgList.TransparentColor = System.Drawing.Color.Olive; // // cmoBox // this.cmoBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.cmoBox.Cursor = System.Windows.Forms.Cursors.Arrow; this.cmoBox.Items.AddRange(new object[] { "0", "1", "2", "3", "4"}); this.cmoBox.Location = new System.Drawing.Point(4, 194); this.cmoBox.Name = "cmoBox"; this.cmoBox.Size = new System.Drawing.Size(80, 21); this.cmoBox.TabIndex = 9; this.cmoBox.Text = "0"; // // btnFilter // this.btnFilter.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.btnFilter.Cursor = System.Windows.Forms.Cursors.Hand; this.btnFilter.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.btnFilter.Location = new System.Drawing.Point(4, 242); this.btnFilter.Name = "btnFilter"; this.btnFilter.Size = new System.Drawing.Size(78, 20); this.btnFilter.TabIndex = 10; this.btnFilter.Text = "Filter"; this.btnFilter.Click += new System.EventHandler(this.btnFilter_Click); // // btnRemove // this.btnRemove.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.btnRemove.Cursor = System.Windows.Forms.Cursors.Hand; this.btnRemove.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.btnRemove.Location = new System.Drawing.Point(4, 218); this.btnRemove.Name = "btnRemove"; this.btnRemove.Size = new System.Drawing.Size(78, 20); this.btnRemove.TabIndex = 11; this.btnRemove.Text = "Remove"; this.btnRemove.Click += new System.EventHandler(this.btnRemove_Click); // // btnDelete // this.btnDelete.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.btnDelete.Cursor = System.Windows.Forms.Cursors.Hand; this.btnDelete.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.btnDelete.Location = new System.Drawing.Point(4, 22); this.btnDelete.Name = "btnDelete"; this.btnDelete.Size = new System.Drawing.Size(78, 20); this.btnDelete.TabIndex = 12; this.btnDelete.Text = "Delete"; this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click); // // btnReplace // this.btnReplace.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.btnReplace.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.btnReplace.Location = new System.Drawing.Point(4, 326); this.btnReplace.Name = "btnReplace"; this.btnReplace.Size = new System.Drawing.Size(78, 20); this.btnReplace.TabIndex = 13; this.btnReplace.Text = "Replace"; this.btnReplace.Click += new System.EventHandler(this.btnReplace_Click); // // txtRepTxt // this.txtRepTxt.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtRepTxt.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.txtRepTxt.Location = new System.Drawing.Point(4, 280); this.txtRepTxt.Multiline = true; this.txtRepTxt.Name = "txtRepTxt"; this.txtRepTxt.Size = new System.Drawing.Size(78, 40); this.txtRepTxt.TabIndex = 14; this.txtRepTxt.Text = ""; // // rtfReplace // this.Controls.Add(this.txtRepTxt); this.Controls.Add(this.btnReplace); this.Controls.Add(this.btnDelete); this.Controls.Add(this.btnRemove); this.Controls.Add(this.btnFilter); this.Controls.Add(this.cmoBox); this.Controls.Add(this.clkCancel); this.Controls.Add(this.lstSearchResults); this.Cursor = System.Windows.Forms.Cursors.Arrow; this.Name = "rtfReplace"; this.Size = new System.Drawing.Size(90, 354); this.Load += new System.EventHandler(this.rtfReplace_Load); this.ResumeLayout(false); } #endregion private void clkCancel_MouseEnter(object sender, System.EventArgs e) { clkCancel.ImageIndex = 1; } private void clkCancel_MouseLeave(object sender, System.EventArgs e) { clkCancel.ImageIndex = 0; } private void clkCancel_Click(object sender, System.EventArgs e) { Owner.KillReplaceBar(); } public void ResetResults(ArrayList R) { lstSearchResults.Items.Clear(); lstSearchResults.Items.AddRange(R.ToArray()); } private void lstSearchResults_SelectedIndexChanged(object sender, System.EventArgs e) { btnDelete.Enabled = false; if(lstSearchResults.SelectedIndex >= 0) { rtfSearchRange key = lstSearchResults.Items[lstSearchResults.SelectedIndex] as rtfSearchRange; if(key != null) { btnDelete.Enabled = true; if(key.Idx >= 0) Owner.ChangeCursor(key.Idx); } } } private void btnRemove_Click(object sender, System.EventArgs e) { Owner.AlterSearchResults( Int32.Parse(cmoBox.Text), true ); } private void btnFilter_Click(object sender, System.EventArgs e) { Owner.AlterSearchResults( Int32.Parse(cmoBox.Text), false ); } private void rtfReplace_Load(object sender, System.EventArgs e) { } private void btnDelete_Click(object sender, System.EventArgs e) { if(lstSearchResults.SelectedIndex >= 0) { int sIdx = lstSearchResults.SelectedIndex; rtfSearchRange key = lstSearchResults.Items[lstSearchResults.SelectedIndex] as rtfSearchRange; if(key != null) { Owner.DeleteSearchResults(key); } if(lstSearchResults.Items.Count > 0) lstSearchResults.SelectedIndex = Math.Min(sIdx,lstSearchResults.Items.Count - 1); } } private void btnReplace_Click(object sender, System.EventArgs e) { Owner.ExecuteReplace(txtRepTxt.Text); } } }
// Copyright (c) 2013 SIL International // This software is licensed under the MIT license (http://opensource.org/licenses/MIT) using System; using System.Collections.Generic; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Globalization; namespace Icu.Collation { /// <summary> /// The RuleBasedCollator class provides the implementation of /// <see cref="Collator"/>, using data-driven tables. /// </summary> public sealed class RuleBasedCollator : Collator { internal sealed class SafeRuleBasedCollatorHandle : SafeHandle { public SafeRuleBasedCollatorHandle() : base(IntPtr.Zero, true) {} ///<summary> /// When overridden in a derived class, executes the code required to free the handle. ///</summary> ///<returns> /// true if the handle is released successfully; otherwise, in the event of a catastrophic failure, false. /// In this case, it generates a ReleaseHandleFailed Managed Debugging Assistant. ///</returns> [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] protected override bool ReleaseHandle() { if (handle != IntPtr.Zero) NativeMethods.ucol_close(handle); handle = IntPtr.Zero; return true; } ///<summary> ///When overridden in a derived class, gets a value indicating whether the handle value is invalid. ///</summary> ///<returns> ///true if the handle is valid; otherwise, false. ///</returns> public override bool IsInvalid { get { return handle == IntPtr.Zero; } } protected override void Dispose(bool disposing) { base.Dispose(disposing); ReleaseHandle(); } } private bool _disposingValue = false; // To detect redundant calls private SafeRuleBasedCollatorHandle _collatorHandle = default(SafeRuleBasedCollatorHandle); private RuleBasedCollator() {} /// <summary> /// RuleBasedCollator constructor. /// This takes the table rules and builds a collation table out of them. /// </summary> /// <param name="rules">the collation rules to build the collation table from</param> public RuleBasedCollator(string rules) : this(rules, CollationStrength.Default) {} /// <summary> /// RuleBasedCollator constructor. /// This takes the table rules and builds a collation table out of them. /// </summary> /// <param name="rules">the collation rules to build the collation table from</param> /// <param name="collationStrength">the collation strength to use</param> public RuleBasedCollator(string rules, CollationStrength collationStrength) : this(rules, NormalizationMode.Default, collationStrength) {} /// <summary> /// RuleBasedCollator constructor. /// This takes the table rules and builds a collation table out of them. /// </summary> /// <param name="rules">the collation rules to build the collation table from</param> /// <param name="normalizationMode">the normalization mode to use</param> /// <param name="collationStrength">the collation strength to use</param> public RuleBasedCollator(string rules, NormalizationMode normalizationMode, CollationStrength collationStrength) { ErrorCode status; var parseError = new ParseError(); _collatorHandle = NativeMethods.ucol_openRules(rules, rules.Length, normalizationMode, collationStrength, ref parseError, out status); try { ExceptionFromErrorCode.ThrowIfError(status, parseError.ToString(rules)); } catch { if (_collatorHandle != default(SafeRuleBasedCollatorHandle)) _collatorHandle.Dispose(); _collatorHandle = default(SafeRuleBasedCollatorHandle); throw; } } /// <summary>The collation strength. /// The usual strength for most locales (except Japanese) is tertiary. /// Quaternary strength is useful when combined with shifted setting /// for alternate handling attribute and for JIS x 4061 collation, /// when it is used to distinguish between Katakana and Hiragana /// (this is achieved by setting the HiraganaQuaternary mode to on. /// Otherwise, quaternary level is affected only by the number of /// non ignorable code points in the string. /// </summary> public override CollationStrength Strength { get { return (CollationStrength) GetAttribute(NativeMethods.CollationAttribute.Strength); } set { SetAttribute(NativeMethods.CollationAttribute.Strength, (NativeMethods.CollationAttributeValue) value); } } /// <summary> /// Controls whether the normalization check and necessary normalizations /// are performed. /// </summary> public override NormalizationMode NormalizationMode { get { return (NormalizationMode) GetAttribute(NativeMethods.CollationAttribute.NormalizationMode); } set { SetAttribute(NativeMethods.CollationAttribute.NormalizationMode, (NativeMethods.CollationAttributeValue) value); } } /// <summary> /// Direction of secondary weights - Necessary for French to make secondary weights be considered from back to front. /// </summary> public override FrenchCollation FrenchCollation { get { return (FrenchCollation) GetAttribute(NativeMethods.CollationAttribute.FrenchCollation); } set { SetAttribute(NativeMethods.CollationAttribute.FrenchCollation, (NativeMethods.CollationAttributeValue) value); } } /// <summary> /// Controls whether an extra case level (positioned before the third /// level) is generated or not. Contents of the case level are affected by /// the value of CaseFirst attribute. A simple way to ignore /// accent differences in a string is to set the strength to Primary /// and enable case level. /// </summary> public override CaseLevel CaseLevel { get { return (CaseLevel) GetAttribute(NativeMethods.CollationAttribute.CaseLevel); } set { SetAttribute(NativeMethods.CollationAttribute.CaseLevel, (NativeMethods.CollationAttributeValue) value); } } /// <summary> /// When turned on, this attribute positions Hiragana before all /// non-ignorables on quaternary level This is a sneaky way to produce JIS /// sort order /// </summary> [Obsolete("ICU 50 Implementation detail, cannot be set via API, was removed from implementation.")] public override HiraganaQuaternary HiraganaQuaternary { get { return (HiraganaQuaternary) GetAttribute(NativeMethods.CollationAttribute.HiraganaQuaternaryMode); } set { SetAttribute(NativeMethods.CollationAttribute.HiraganaQuaternaryMode, (NativeMethods.CollationAttributeValue) value); } } /// <summary> /// When turned on, this attribute generates a collation key /// for the numeric value of substrings of digits. /// This is a way to get '100' to sort AFTER '2'. /// </summary> public override NumericCollation NumericCollation { get { return (NumericCollation) GetAttribute(NativeMethods.CollationAttribute.NumericCollation); } set { SetAttribute(NativeMethods.CollationAttribute.NumericCollation, (NativeMethods.CollationAttributeValue) value); } } /// <summary> /// Controls the ordering of upper and lower case letters. /// </summary> public override CaseFirst CaseFirst { get { return (CaseFirst) GetAttribute(NativeMethods.CollationAttribute.CaseFirst); } set { SetAttribute(NativeMethods.CollationAttribute.CaseFirst, (NativeMethods.CollationAttributeValue) value); } } /// <summary> /// Attribute for handling variable elements. /// </summary> public override AlternateHandling AlternateHandling { get { return (AlternateHandling) GetAttribute(NativeMethods.CollationAttribute.AlternateHandling); } set { SetAttribute(NativeMethods.CollationAttribute.AlternateHandling, (NativeMethods.CollationAttributeValue) value); } } private byte[] keyData = new byte[1024]; /// <summary> /// Get a sort key for the argument string. /// Sort keys may be compared using SortKey.Compare /// </summary> /// <param name="source"></param> /// <returns></returns> public override SortKey GetSortKey(string source) { if(source == null) { throw new ArgumentNullException(); } int actualLength; for (;;) { actualLength = NativeMethods.ucol_getSortKey(_collatorHandle, source, source.Length, keyData, keyData.Length); if (actualLength > keyData.Length) { keyData = new byte[keyData.Length*2]; continue; } break; } return CreateSortKey(source, keyData, actualLength); } private NativeMethods.CollationAttributeValue GetAttribute(NativeMethods.CollationAttribute attr) { ErrorCode e; NativeMethods.CollationAttributeValue value = NativeMethods.ucol_getAttribute(_collatorHandle, attr, out e); ExceptionFromErrorCode.ThrowIfError(e); return value; } private void SetAttribute(NativeMethods.CollationAttribute attr, NativeMethods.CollationAttributeValue value) { ErrorCode e; NativeMethods.ucol_setAttribute(_collatorHandle, attr, value, out e); ExceptionFromErrorCode.ThrowIfError(e); } /// <summary> /// Create a string enumerator of all locales for which a valid collator /// may be opened. /// </summary> /// <returns></returns> public static IList<string> GetAvailableCollationLocales() { List<string> locales = new List<string>(); // The ucol_openAvailableLocales call failes when there are no locales available, so check first. if (NativeMethods.ucol_countAvailable() == 0) { return locales; } ErrorCode ec; SafeEnumeratorHandle en = NativeMethods.ucol_openAvailableLocales(out ec); ExceptionFromErrorCode.ThrowIfError(ec); try { string str = en.Next(); while (str != null) { locales.Add(str); str = en.Next(); } } finally { en.Close(); } return locales; } internal sealed class SafeEnumeratorHandle : SafeHandle { public SafeEnumeratorHandle() : base(IntPtr.Zero, true) { } ///<summary> ///When overridden in a derived class, executes the code required to free the handle. ///</summary> ///<returns> ///true if the handle is released successfully; otherwise, in the event of a catastrophic failure, false. In this case, it generates a ReleaseHandleFailed Managed Debugging Assistant. ///</returns> [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] protected override bool ReleaseHandle() { NativeMethods.uenum_close(handle); handle = IntPtr.Zero; return true; } ///<summary> ///When overridden in a derived class, gets a value indicating whether the handle value is invalid. ///</summary> ///<returns> ///true if the handle is valid; otherwise, false. ///</returns> public override bool IsInvalid { get { return (handle == IntPtr.Zero); } } public string Next() { ErrorCode e; int length; IntPtr str = NativeMethods.uenum_unext(this, out length, out e); if (str == IntPtr.Zero) { return null; } string result = Marshal.PtrToStringUni(str, length); ExceptionFromErrorCode.ThrowIfError(e); return result; } } #region ICloneable Members ///<summary> ///Creates a new object that is a copy of the current instance. ///</summary> /// ///<returns> ///A new object that is a copy of this instance. ///</returns> public override object Clone() { RuleBasedCollator copy = new RuleBasedCollator(); ErrorCode status; int buffersize = 512; copy._collatorHandle = NativeMethods.ucol_safeClone( _collatorHandle, IntPtr.Zero, ref buffersize, out status); try { ExceptionFromErrorCode.ThrowIfError(status); return copy; } catch { if (copy._collatorHandle != default(SafeRuleBasedCollatorHandle)) copy._collatorHandle.Dispose(); copy._collatorHandle = default(SafeRuleBasedCollatorHandle); throw; } } /// <summary> /// Opens a Collator for comparing strings using the given locale id. /// Does not allow for locale fallback. /// </summary> /// <param name="localeId">Locale to use</param> public static new Collator Create(string localeId) { return Create(localeId, Fallback.NoFallback); } /// <summary> /// Opens a Collator for comparing strings using the given locale id. /// </summary> /// <param name="localeId">Locale to use</param> /// <param name="fallback">Whether to allow locale fallback or not.</param> public new static Collator Create(string localeId, Fallback fallback) { // Culture identifiers in .NET are created using '-', while ICU // expects '_'. We want to make sure that the localeId is the // format that ICU expects. var locale = new Locale(localeId); var instance = new RuleBasedCollator(); ErrorCode status; instance._collatorHandle = NativeMethods.ucol_open(locale.Id, out status); try { if (status == ErrorCode.USING_FALLBACK_WARNING && fallback == Fallback.NoFallback) { throw new ArgumentException( $"Could only create Collator '{localeId}' by falling back to " + $"'{instance.ActualId}'. You can use the fallback option to create this."); } if (status == ErrorCode.USING_DEFAULT_WARNING && fallback == Fallback.NoFallback && !instance.ValidId.Equals(locale.Id) && locale.Id.Length > 0 && !locale.Id.Equals("root")) { throw new ArgumentException( $"Could only create Collator '{localeId}' by falling back to the default " + $"'{instance.ActualId}'. You can use the fallback option to create this."); } if (status == ErrorCode.INTERNAL_PROGRAM_ERROR && fallback == Fallback.FallbackAllowed) { instance = new RuleBasedCollator(string.Empty); // fallback to UCA } else { try { ExceptionFromErrorCode.ThrowIfError(status); } catch (Exception e) { throw new ArgumentException( $"Unable to create a collator using the given localeId '{localeId}'.\n" + "This is likely because the ICU data file was created without collation " + "rules for this locale. You can provide the rules yourself or replace " + "the data dll.", e); } } return instance; } catch { if (instance._collatorHandle != default(SafeRuleBasedCollatorHandle)) instance._collatorHandle.Dispose(); instance._collatorHandle = default(SafeRuleBasedCollatorHandle); throw; } } private string ActualId { get { ErrorCode status; if (_collatorHandle.IsInvalid) return string.Empty; // See NativeMethods.ucol_getLocaleByType for marshal information. string result = Marshal.PtrToStringAnsi(NativeMethods.ucol_getLocaleByType( _collatorHandle, NativeMethods.LocaleType.ActualLocale, out status)); if (status != ErrorCode.NoErrors) { return string.Empty; } return result; } } private string ValidId { get { ErrorCode status; if (_collatorHandle.IsInvalid) return string.Empty; // See NativeMethods.ucol_getLocaleByType for marshal information. string result = Marshal.PtrToStringAnsi(NativeMethods.ucol_getLocaleByType( _collatorHandle, NativeMethods.LocaleType.ValidLocale, out status)); if (status != ErrorCode.NoErrors) { return string.Empty; } return result; } } #endregion #region IComparer<string> Members /// <summary> /// Compares two strings based on the rules of this RuleBasedCollator /// </summary> /// <param name="string1">The first string to compare</param> /// <param name="string2">The second string to compare</param> /// <returns></returns> /// <remarks>Comparing a null reference is allowed and does not generate an exception. /// A null reference is considered to be less than any reference that is not null.</remarks> public override int Compare(string string1, string string2) { if(string1 == null) { if(string2 == null) { return 0; } return -1; } if(string2 == null) { return 1; } return (int) NativeMethods.ucol_strcoll(_collatorHandle, string1, string1.Length, string2, string2.Length); } #endregion #region IDisposable Support /// <summary> /// Implementing IDisposable pattern to properly release unmanaged resources. /// </summary> protected override void Dispose(bool disposing) { if (!_disposingValue) { if (disposing) { // Dispose managed state (managed objects), if any. // although SafeRuleBasedCollatorHandle deals with an unmanaged resource // it itself is a managed object, so we shouldn't try to dispose it // if !disposing because that could lead to a corrupt stack (as observed // in https://jenkins.lsdev.sil.org:45192/view/Icu/view/All/job/GitHub-IcuDotNet-Win-any-master-release/59) if (_collatorHandle != default(SafeRuleBasedCollatorHandle)) { _collatorHandle.Dispose(); } } _collatorHandle = default(SafeRuleBasedCollatorHandle); _disposingValue = true; } } /// <summary> /// Disposes of all unmanaged resources used by RulesBasedCollator. /// </summary> ~RuleBasedCollator() { Dispose(false); } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Security.AccessControl; using ClosedXML.Excel.CalcEngine; using DocumentFormat.OpenXml; namespace ClosedXML.Excel { using System.Linq; using System.Data; public enum XLEventTracking { Enabled, Disabled } public enum XLCalculateMode { Auto, AutoNoTable, Manual, Default }; public enum XLReferenceStyle { R1C1, A1, Default }; public enum XLCellSetValueBehavior { /// <summary> /// Analyze input string and convert value. For avoid analyzing use escape symbol ' /// </summary> Smart = 0, /// <summary> /// Direct set value. If value has unsupported type - value will be stored as string returned by <see /// cref = "object.ToString()" /> /// </summary> Simple = 1, } public partial class XLWorkbook: IDisposable { #region Static private static IXLStyle _defaultStyle; public static IXLStyle DefaultStyle { get { return _defaultStyle ?? (_defaultStyle = new XLStyle(null) { Font = new XLFont(null, null) { Bold = false, Italic = false, Underline = XLFontUnderlineValues.None, Strikethrough = false, VerticalAlignment = XLFontVerticalTextAlignmentValues. Baseline, FontSize = 11, FontColor = XLColor.FromArgb(0, 0, 0), FontName = "Calibri", FontFamilyNumbering = XLFontFamilyNumberingValues.Swiss }, Fill = new XLFill(null) { BackgroundColor = XLColor.FromIndex(64), PatternType = XLFillPatternValues.None, PatternColor = XLColor.FromIndex(64) }, Border = new XLBorder(null, null) { BottomBorder = XLBorderStyleValues.None, DiagonalBorder = XLBorderStyleValues.None, DiagonalDown = false, DiagonalUp = false, LeftBorder = XLBorderStyleValues.None, RightBorder = XLBorderStyleValues.None, TopBorder = XLBorderStyleValues.None, BottomBorderColor = XLColor.Black, DiagonalBorderColor = XLColor.Black, LeftBorderColor = XLColor.Black, RightBorderColor = XLColor.Black, TopBorderColor = XLColor.Black }, NumberFormat = new XLNumberFormat(null, null) {NumberFormatId = 0}, Alignment = new XLAlignment(null) { Indent = 0, Horizontal = XLAlignmentHorizontalValues. General, JustifyLastLine = false, ReadingOrder = XLAlignmentReadingOrderValues. ContextDependent, RelativeIndent = 0, ShrinkToFit = false, TextRotation = 0, Vertical = XLAlignmentVerticalValues. Bottom, WrapText = false }, Protection = new XLProtection(null) { Locked = true, Hidden = false } }); } } public static Double DefaultRowHeight { get; private set; } public static Double DefaultColumnWidth { get; private set; } public static IXLPageSetup DefaultPageOptions { get { var defaultPageOptions = new XLPageSetup(null, null) { PageOrientation = XLPageOrientation.Default, Scale = 100, PaperSize = XLPaperSize.LetterPaper, Margins = new XLMargins { Top = 0.75, Bottom = 0.5, Left = 0.75, Right = 0.75, Header = 0.5, Footer = 0.75 }, ScaleHFWithDocument = true, AlignHFWithMargins = true, PrintErrorValue = XLPrintErrorValues.Displayed, ShowComments = XLShowCommentsValues.None }; return defaultPageOptions; } } public static IXLOutline DefaultOutline { get { return new XLOutline(null) { SummaryHLocation = XLOutlineSummaryHLocation.Right, SummaryVLocation = XLOutlineSummaryVLocation.Bottom }; } } /// <summary> /// Behavior for <see cref = "IXLCell.set_Value" /> /// </summary> public static XLCellSetValueBehavior CellSetValueBehavior { get; set; } #endregion internal readonly List<UnsupportedSheet> UnsupportedSheets = new List<UnsupportedSheet>(); private readonly Dictionary<Int32, IXLStyle> _stylesById = new Dictionary<int, IXLStyle>(); private readonly Dictionary<IXLStyle, Int32> _stylesByStyle = new Dictionary<IXLStyle, Int32>(); public XLEventTracking EventTracking { get; set; } internal Int32 GetStyleId(IXLStyle style) { Int32 cached; if (_stylesByStyle.TryGetValue(style, out cached)) return cached; var count = _stylesByStyle.Count; var styleToUse = new XLStyle(null, style); _stylesByStyle.Add(styleToUse, count); _stylesById.Add(count, styleToUse); return count; } internal IXLStyle GetStyleById(Int32 id) { return _stylesById[id]; } #region Nested Type: XLLoadSource private enum XLLoadSource { New, File, Stream }; #endregion internal XLWorksheets WorksheetsInternal { get; private set; } /// <summary> /// Gets an object to manipulate the worksheets. /// </summary> public IXLWorksheets Worksheets { get { return WorksheetsInternal; } } /// <summary> /// Gets an object to manipulate this workbook's named ranges. /// </summary> public IXLNamedRanges NamedRanges { get; private set; } /// <summary> /// Gets an object to manipulate this workbook's theme. /// </summary> public IXLTheme Theme { get; private set; } /// <summary> /// Gets or sets the default style for the workbook. /// <para>All new worksheets will use this style.</para> /// </summary> public IXLStyle Style { get; set; } /// <summary> /// Gets or sets the default row height for the workbook. /// <para>All new worksheets will use this row height.</para> /// </summary> public Double RowHeight { get; set; } /// <summary> /// Gets or sets the default column width for the workbook. /// <para>All new worksheets will use this column width.</para> /// </summary> public Double ColumnWidth { get; set; } /// <summary> /// Gets or sets the default page options for the workbook. /// <para>All new worksheets will use these page options.</para> /// </summary> public IXLPageSetup PageOptions { get; set; } /// <summary> /// Gets or sets the default outline options for the workbook. /// <para>All new worksheets will use these outline options.</para> /// </summary> public IXLOutline Outline { get; set; } /// <summary> /// Gets or sets the workbook's properties. /// </summary> public XLWorkbookProperties Properties { get; set; } /// <summary> /// Gets or sets the workbook's calculation mode. /// </summary> public XLCalculateMode CalculateMode { get; set; } public Boolean CalculationOnSave { get; set; } public Boolean ForceFullCalculation { get; set; } public Boolean FullCalculationOnLoad { get; set; } public Boolean FullPrecision { get; set; } /// <summary> /// Gets or sets the workbook's reference style. /// </summary> public XLReferenceStyle ReferenceStyle { get; set; } public IXLCustomProperties CustomProperties { get; private set; } public Boolean ShowFormulas { get; set; } public Boolean ShowGridLines { get; set; } public Boolean ShowOutlineSymbols { get; set; } public Boolean ShowRowColHeaders { get; set; } public Boolean ShowRuler { get; set; } public Boolean ShowWhiteSpace { get; set; } public Boolean ShowZeros { get; set; } public Boolean RightToLeft { get; set; } public Boolean DefaultShowFormulas { get { return false; } } public Boolean DefaultShowGridLines { get { return true; } } public Boolean DefaultShowOutlineSymbols { get { return true; } } public Boolean DefaultShowRowColHeaders { get { return true; } } public Boolean DefaultShowRuler { get { return true; } } public Boolean DefaultShowWhiteSpace { get { return true; } } public Boolean DefaultShowZeros { get { return true; } } public Boolean DefaultRightToLeft { get { return false; } } private void InitializeTheme() { Theme = new XLTheme { Text1 = XLColor.FromHtml("#FF000000"), Background1 = XLColor.FromHtml("#FFFFFFFF"), Text2 = XLColor.FromHtml("#FF1F497D"), Background2 = XLColor.FromHtml("#FFEEECE1"), Accent1 = XLColor.FromHtml("#FF4F81BD"), Accent2 = XLColor.FromHtml("#FFC0504D"), Accent3 = XLColor.FromHtml("#FF9BBB59"), Accent4 = XLColor.FromHtml("#FF8064A2"), Accent5 = XLColor.FromHtml("#FF4BACC6"), Accent6 = XLColor.FromHtml("#FFF79646"), Hyperlink = XLColor.FromHtml("#FF0000FF"), FollowedHyperlink = XLColor.FromHtml("#FF800080") }; } internal XLColor GetXLColor(XLThemeColor themeColor) { switch (themeColor) { case XLThemeColor.Text1: return Theme.Text1; case XLThemeColor.Background1: return Theme.Background1; case XLThemeColor.Text2: return Theme.Text2; case XLThemeColor.Background2: return Theme.Background2; case XLThemeColor.Accent1: return Theme.Accent1; case XLThemeColor.Accent2: return Theme.Accent2; case XLThemeColor.Accent3: return Theme.Accent3; case XLThemeColor.Accent4: return Theme.Accent4; case XLThemeColor.Accent5: return Theme.Accent5; case XLThemeColor.Accent6: return Theme.Accent6; default: throw new ArgumentException("Invalid theme color"); } } public IXLNamedRange NamedRange(String rangeName) { if (rangeName.Contains("!")) { var split = rangeName.Split('!'); var first = split[0]; var wsName = first.StartsWith("'") ? first.Substring(1, first.Length - 2) : first; var name = split[1]; IXLWorksheet ws; if (TryGetWorksheet(wsName, out ws)) { var range = ws.NamedRange(name); return range ?? NamedRange(name); } return null; } return NamedRanges.NamedRange(rangeName); } public Boolean TryGetWorksheet(String name, out IXLWorksheet worksheet) { if (Worksheets.Any(w => string.Equals(w.Name, XLWorksheets.TrimSheetName(name), StringComparison.OrdinalIgnoreCase))) { worksheet = Worksheet(name); return true; } worksheet = null; return false; } public IXLRange RangeFromFullAddress(String rangeAddress, out IXLWorksheet ws) { ws = null; if (!rangeAddress.Contains('!')) return null; var split = rangeAddress.Split('!'); var first = split[0]; var wsName = first.StartsWith("'") ? first.Substring(1, first.Length - 2) : first; var localRange = split[1]; if (TryGetWorksheet(wsName, out ws)) { return ws.Range(localRange); } return null; } /// <summary> /// Saves the current workbook. /// </summary> public void Save() { #if DEBUG Save(true); #else Save(false); #endif } /// <summary> /// Saves the current workbook and optionally performs validation /// </summary> public void Save(bool validate) { checkForWorksheetsPresent(); if (_loadSource == XLLoadSource.New) throw new Exception("This is a new file, please use one of the SaveAs methods."); if (_loadSource == XLLoadSource.Stream) { CreatePackage(_originalStream, false, _spreadsheetDocumentType, validate); } else CreatePackage(_originalFile, _spreadsheetDocumentType, validate); } /// <summary> /// Saves the current workbook to a file. /// </summary> public void SaveAs(String file) { #if DEBUG SaveAs(file, true); #else SaveAs(file, false); #endif } /// <summary> /// Saves the current workbook to a file and optionally validates it. /// </summary> public void SaveAs(String file, Boolean validate) { checkForWorksheetsPresent(); PathHelper.CreateDirectory(Path.GetDirectoryName(file)); if (_loadSource == XLLoadSource.New) { if (File.Exists(file)) File.Delete(file); CreatePackage(file, GetSpreadsheetDocumentType(file), validate); } else if (_loadSource == XLLoadSource.File) { if (String.Compare(_originalFile.Trim(), file.Trim(), true) != 0) File.Copy(_originalFile, file, true); CreatePackage(file, GetSpreadsheetDocumentType(file), validate); } else if (_loadSource == XLLoadSource.Stream) { _originalStream.Position = 0; using (var fileStream = File.Create(file)) { CopyStream(_originalStream, fileStream); //fileStream.Position = 0; CreatePackage(fileStream, false, _spreadsheetDocumentType, validate); fileStream.Close(); } } } private static SpreadsheetDocumentType GetSpreadsheetDocumentType(string filePath) { var extension = Path.GetExtension(filePath); if (extension == null) throw new Exception("Empty extension is not supported."); extension = extension.Substring(1).ToLowerInvariant(); switch (extension) { case "xlsm": case "xltm": return SpreadsheetDocumentType.MacroEnabledWorkbook; case "xlsx": case "xltx": return SpreadsheetDocumentType.Workbook; default: throw new ArgumentException(String.Format("Extension '{0}' is not supported. Supported extensions are '.xlsx', '.xslm', '.xltx' and '.xltm'.", extension)); } } private void checkForWorksheetsPresent() { if (Worksheets.Count() == 0) throw new Exception("Workbooks need at least one worksheet."); } /// <summary> /// Saves the current workbook to a stream. /// </summary> public void SaveAs(Stream stream) { #if DEBUG SaveAs(stream, true); #else SaveAs(stream, false); #endif } /// <summary> /// Saves the current workbook to a stream and optionally validates it. /// </summary> public void SaveAs(Stream stream, Boolean validate) { checkForWorksheetsPresent(); if (_loadSource == XLLoadSource.New) { // dm 20130422, this method or better the method SpreadsheetDocument.Create which is called // inside of 'CreatePackage' need a stream which CanSeek & CanRead // and an ordinary Response stream of a webserver can't do this // so we have to ask and provide a way around this if (stream.CanRead && stream.CanSeek && stream.CanWrite) { // all is fine the package can be created in a direct way CreatePackage(stream, true, _spreadsheetDocumentType, validate); } else { // the harder way MemoryStream ms = new MemoryStream(); CreatePackage(ms, true, _spreadsheetDocumentType, validate); // not really nessesary, because I changed CopyStream too. // but for better understanding and if somebody in the future // provide an changed version of CopyStream ms.Position = 0; CopyStream(ms, stream); } } else if (_loadSource == XLLoadSource.File) { using (var fileStream = new FileStream(_originalFile, FileMode.Open, FileAccess.Read)) { CopyStream(fileStream, stream); fileStream.Close(); } CreatePackage(stream, false, _spreadsheetDocumentType, validate); } else if (_loadSource == XLLoadSource.Stream) { _originalStream.Position = 0; if (_originalStream != stream) CopyStream(_originalStream, stream); CreatePackage(stream, false, _spreadsheetDocumentType, validate); } } internal static void CopyStream(Stream input, Stream output) { var buffer = new byte[8 * 1024]; int len; // dm 20130422, it is always a good idea to rewind the input stream, or not? if (input.CanSeek) input.Seek(0, SeekOrigin.Begin); while ((len = input.Read(buffer, 0, buffer.Length)) > 0) output.Write(buffer, 0, len); // dm 20130422, and flushing the output after write output.Flush(); } public IXLWorksheet Worksheet(String name) { return WorksheetsInternal.Worksheet(name); } public IXLWorksheet Worksheet(Int32 position) { return WorksheetsInternal.Worksheet(position); } public IXLCustomProperty CustomProperty(String name) { return CustomProperties.CustomProperty(name); } public IXLCells FindCells(Func<IXLCell, Boolean> predicate) { var cells = new XLCells(false, false); foreach (XLWorksheet ws in WorksheetsInternal) { foreach (XLCell cell in ws.CellsUsed(true)) { if (predicate(cell)) cells.Add(cell); } } return cells; } public IXLRows FindRows(Func<IXLRow, Boolean> predicate) { var rows = new XLRows(null); foreach (XLWorksheet ws in WorksheetsInternal) { foreach (IXLRow row in ws.Rows().Where(predicate)) rows.Add(row as XLRow); } return rows; } public IXLColumns FindColumns(Func<IXLColumn, Boolean> predicate) { var columns = new XLColumns(null); foreach (XLWorksheet ws in WorksheetsInternal) { foreach (IXLColumn column in ws.Columns().Where(predicate)) columns.Add(column as XLColumn); } return columns; } #region Fields private readonly XLLoadSource _loadSource = XLLoadSource.New; private readonly String _originalFile; private readonly Stream _originalStream; #endregion #region Constructor /// <summary> /// Creates a new Excel workbook. /// </summary> public XLWorkbook() :this(XLEventTracking.Enabled) { } public XLWorkbook(XLEventTracking eventTracking) { EventTracking = eventTracking; DefaultRowHeight = 15; DefaultColumnWidth = 8.43; Style = new XLStyle(null, DefaultStyle); RowHeight = DefaultRowHeight; ColumnWidth = DefaultColumnWidth; PageOptions = DefaultPageOptions; Outline = DefaultOutline; Properties = new XLWorkbookProperties(); CalculateMode = XLCalculateMode.Default; ReferenceStyle = XLReferenceStyle.Default; InitializeTheme(); ShowFormulas = DefaultShowFormulas; ShowGridLines = DefaultShowGridLines; ShowOutlineSymbols = DefaultShowOutlineSymbols; ShowRowColHeaders = DefaultShowRowColHeaders; ShowRuler = DefaultShowRuler; ShowWhiteSpace = DefaultShowWhiteSpace; ShowZeros = DefaultShowZeros; RightToLeft = DefaultRightToLeft; WorksheetsInternal = new XLWorksheets(this); NamedRanges = new XLNamedRanges(this); CustomProperties = new XLCustomProperties(this); ShapeIdManager = new XLIdManager(); Author = Environment.UserName; } /// <summary> /// Opens an existing workbook from a file. /// </summary> /// <param name = "file">The file to open.</param> public XLWorkbook(String file) : this(file, XLEventTracking.Enabled) { } public XLWorkbook(String file, XLEventTracking eventTracking) : this(eventTracking) { _loadSource = XLLoadSource.File; _originalFile = file; _spreadsheetDocumentType = GetSpreadsheetDocumentType(_originalFile); Load(file); } /// <summary> /// Opens an existing workbook from a stream. /// </summary> /// <param name = "stream">The stream to open.</param> public XLWorkbook(Stream stream):this(stream, XLEventTracking.Enabled) { } public XLWorkbook(Stream stream, XLEventTracking eventTracking) : this(eventTracking) { _loadSource = XLLoadSource.Stream; _originalStream = stream; Load(stream); } #endregion #region Nested type: UnsupportedSheet internal sealed class UnsupportedSheet { public Boolean IsActive; public UInt32 SheetId; public Int32 Position; } #endregion public IXLCell Cell(String namedCell) { var namedRange = NamedRange(namedCell); if (namedRange == null) return null; var range = namedRange.Ranges.FirstOrDefault(); if (range == null) return null; return range.FirstCell(); } public IXLCells Cells(String namedCells) { return Ranges(namedCells).Cells(); } public IXLRange Range(String range) { var namedRange = NamedRange(range); if (namedRange != null) return namedRange.Ranges.FirstOrDefault(); else { IXLWorksheet ws; var r = RangeFromFullAddress(range, out ws); return r; } } public IXLRanges Ranges(String ranges) { var retVal = new XLRanges(); var rangePairs = ranges.Split(','); foreach (var range in rangePairs.Select(r => Range(r.Trim())).Where(range => range != null)) { retVal.Add(range); } return retVal; } internal XLIdManager ShapeIdManager { get; private set; } public void Dispose() { Worksheets.ForEach(w => w.Dispose()); } public Boolean Use1904DateSystem { get; set; } public XLWorkbook SetUse1904DateSystem() { return SetUse1904DateSystem(true); } public XLWorkbook SetUse1904DateSystem(Boolean value) { Use1904DateSystem = value; return this; } public IXLWorksheet AddWorksheet(String sheetName) { return Worksheets.Add(sheetName); } public IXLWorksheet AddWorksheet(String sheetName, Int32 position) { return Worksheets.Add(sheetName, position); } public IXLWorksheet AddWorksheet(DataTable dataTable) { return Worksheets.Add(dataTable); } public void AddWorksheet(DataSet dataSet) { Worksheets.Add(dataSet); } public void AddWorksheet(IXLWorksheet worksheet) { worksheet.CopyTo(this, worksheet.Name); } public IXLWorksheet AddWorksheet(DataTable dataTable, String sheetName) { return Worksheets.Add(dataTable, sheetName); } private XLCalcEngine _calcEngine; private XLCalcEngine CalcEngine { get { return _calcEngine ?? (_calcEngine = new XLCalcEngine(this)); } } public Object Evaluate(String expression) { return CalcEngine.Evaluate(expression); } private static XLCalcEngine _calcEngineExpr; private SpreadsheetDocumentType _spreadsheetDocumentType; private static XLCalcEngine CalcEngineExpr { get { return _calcEngineExpr ?? (_calcEngineExpr = new XLCalcEngine()); } } public static Object EvaluateExpr(String expression) { return CalcEngineExpr.Evaluate(expression); } public String Author { get; set; } public Boolean LockStructure { get; set; } public XLWorkbook SetLockStructure(Boolean value) { LockStructure = value; return this; } public Boolean LockWindows { get; set; } public XLWorkbook SetLockWindows(Boolean value) { LockWindows = value; return this; } public void Protect() { Protect(true); } public void Protect(Boolean lockStructure) { Protect(lockStructure, false); } public void Protect(Boolean lockStructure, Boolean lockWindows) { LockStructure = lockStructure; LockWindows = LockWindows; } } }
// ----------------------------------------------------------------------------------------- // <copyright file="CloudQueueMessageBase.cs" company="Microsoft"> // Copyright 2012 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // ----------------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Storage.Queue { using System; using System.Text; using Microsoft.WindowsAzure.Storage.Shared.Protocol; using System.Globalization; using Microsoft.WindowsAzure.Storage.Core; /// <summary> /// Represents a message in the Windows Azure Queue service. /// </summary> public sealed partial class CloudQueueMessage { /// <summary> /// The maximum message size in bytes. /// </summary> private const long MaximumMessageSize = 64 * Constants.KB; /// <summary> /// Gets the maximum message size in bytes. /// </summary> /// <value>The maximum message size in bytes.</value> public static long MaxMessageSize { get { return MaximumMessageSize; } } /// <summary> /// The maximum amount of time a message is kept in the queue. /// </summary> private static readonly TimeSpan MaximumTimeToLive = TimeSpan.FromDays(7); /// <summary> /// Gets the maximum amount of time a message is kept in the queue. /// </summary> /// <value>The maximum amount of time a message is kept in the queue.</value> public static TimeSpan MaxTimeToLive { get { return MaximumTimeToLive; } } /// <summary> /// The maximum number of messages that can be peeked at a time. /// </summary> private const int MaximumNumberOfMessagesToPeek = 32; /// <summary> /// Gets the maximum number of messages that can be peeked at a time. /// </summary> /// <value>The maximum number of messages that can be peeked at a time.</value> public static int MaxNumberOfMessagesToPeek { get { return MaximumNumberOfMessagesToPeek; } } /// <summary> /// Custom UTF8Encoder to throw exception in case of invalid bytes. /// </summary> private static UTF8Encoding utf8Encoder = new UTF8Encoding(false, true); /// <summary> /// Initializes a new instance of the <see cref="CloudQueueMessage"/> class with the given byte array. /// </summary> internal CloudQueueMessage() { } /// <summary> /// Initializes a new instance of the <see cref="CloudQueueMessage"/> class with the given string. /// </summary> /// <param name="content">The content of the message as a string of text.</param> public CloudQueueMessage(string content) { this.SetMessageContent(content); // At this point, without knowing whether or not the message will be Base64 encoded, we can't fully validate the message size. // So we leave it to CloudQueue so that we have a central place for this logic. } /// <summary> /// Initializes a new instance of the <see cref="CloudQueueMessage"/> class with the given message ID and pop receipt. /// </summary> /// <param name="messageId">The message ID.</param> /// <param name="popReceipt">The pop receipt token.</param> public CloudQueueMessage(string messageId, string popReceipt) { this.Id = messageId; this.PopReceipt = popReceipt; } /// <summary> /// Initializes a new instance of the <see cref="CloudQueueMessage"/> class with the given Base64 encoded string. /// This method is only used internally. /// </summary> /// <param name="content">The text string.</param> /// <param name="isBase64Encoded">Whether the string is Base64 encoded.</param> internal CloudQueueMessage(string content, bool isBase64Encoded) { if (content == null) { content = string.Empty; } this.RawString = content; this.MessageType = isBase64Encoded ? QueueMessageType.Base64Encoded : QueueMessageType.RawString; } /// <summary> /// Gets the content of the message as a byte array. /// </summary> /// <value>The content of the message as a byte array.</value> public byte[] AsBytes { get { if (this.MessageType == QueueMessageType.RawString) { return Encoding.UTF8.GetBytes(this.RawString); } else { return Convert.FromBase64String(this.RawString); } } } /// <summary> /// Gets the message ID. /// </summary> /// <value>The message ID.</value> public string Id { get; internal set; } /// <summary> /// Gets the message's pop receipt. /// </summary> /// <value>The pop receipt value.</value> public string PopReceipt { get; internal set; } /// <summary> /// Gets the time that the message was added to the queue. /// </summary> /// <value>The time that that message was added to the queue.</value> public DateTimeOffset? InsertionTime { get; internal set; } /// <summary> /// Gets the time that the message expires. /// </summary> /// <value>The time that the message expires.</value> public DateTimeOffset? ExpirationTime { get; internal set; } /// <summary> /// Gets the time that the message will next be visible. /// </summary> /// <value>The time that the message will next be visible.</value> public DateTimeOffset? NextVisibleTime { get; internal set; } /// <summary> /// Gets the content of the message, as a string. /// </summary> /// <value>The message content.</value> public string AsString { get { if (this.MessageType == QueueMessageType.RawString) { return this.RawString; } else { byte[] messageData = Convert.FromBase64String(this.RawString); return utf8Encoder.GetString(messageData, 0, messageData.Length); } } } /// <summary> /// Gets the number of times this message has been dequeued. /// </summary> /// <value>The number of times this message has been dequeued.</value> public int DequeueCount { get; internal set; } /// <summary> /// Gets message type that indicates if the RawString is the original message string or Base64 encoding of the original binary data. /// </summary> internal QueueMessageType MessageType { get; private set; } /// <summary> /// Gets or sets the original message string or Base64 encoding of the original binary data. /// </summary> /// <value>The original message string.</value> internal string RawString { get; set; } /// <summary> /// Gets the content of the message for transfer (internal use only). /// </summary> /// <param name="shouldEncodeMessage">Indicates if the message should be encoded.</param> /// <returns>The message content as a string.</returns> internal string GetMessageContentForTransfer(bool shouldEncodeMessage) { if (!shouldEncodeMessage && this.MessageType == QueueMessageType.Base64Encoded) { throw new ArgumentException(SR.BinaryMessageShouldUseBase64Encoding); } string outgoingMessageString = null; if (this.MessageType == QueueMessageType.RawString) { if (shouldEncodeMessage) { outgoingMessageString = Convert.ToBase64String(this.AsBytes); // the size of Base64 encoded string is the number of bytes this message will take up on server. if (outgoingMessageString.Length > CloudQueueMessage.MaxMessageSize) { throw new ArgumentException(string.Format( CultureInfo.InvariantCulture, SR.MessageTooLarge, CloudQueueMessage.MaxMessageSize)); } } else { outgoingMessageString = this.RawString; // we need to calculate the size of its UTF8 byte array, as that will be the storage usage on server. if (Encoding.UTF8.GetBytes(outgoingMessageString).Length > CloudQueueMessage.MaxMessageSize) { throw new ArgumentException(string.Format( CultureInfo.InvariantCulture, SR.MessageTooLarge, CloudQueueMessage.MaxMessageSize)); } } } else { // at this point, this.EncodeMessage must be true outgoingMessageString = this.RawString; // the size of Base64 encoded string is the number of bytes this message will take up on server. if (outgoingMessageString.Length > CloudQueueMessage.MaxMessageSize) { throw new ArgumentException(string.Format( CultureInfo.InvariantCulture, SR.MessageTooLarge, CloudQueueMessage.MaxMessageSize)); } } return outgoingMessageString; } /// <summary> /// Sets the content of this message. /// </summary> /// <param name="content">The new message content.</param> public void SetMessageContent(string content) { if (content == null) { // Protocol will return null for empty content content = string.Empty; } this.RawString = content; this.MessageType = QueueMessageType.RawString; } } }
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ using System; using System.Collections; using System.Collections.Generic; namespace Lucene.Net.Support { /// <summary>Represents a strongly typed list of objects that can be accessed by index. /// Provides methods to search, sort, and manipulate lists. Also provides functionality /// to compare lists against each other through an implementations of /// <see cref="IEquatable{T}"/>.</summary> /// <typeparam name="T">The type of elements in the list.</typeparam> //[Serializable] //Disabled for https://github.com/dotnet/standard/issues/300 public class EquatableList<T> : System.Collections.Generic.List<T>, IEquatable<System.Collections.Generic.IEnumerable<T>>, ICloneable { /// <summary>Initializes a new instance of the /// <see cref="EquatableList{T}"/> class that is empty and has the /// default initial capacity.</summary> public EquatableList() : base() { } /// <summary>Initializes a new instance of the <see cref="EquatableList{T}"/> /// class that contains elements copied from the specified collection and has /// sufficient capacity to accommodate the number of elements copied.</summary> /// <param name="collection">The collection whose elements are copied to the new list.</param> public EquatableList(System.Collections.Generic.IEnumerable<T> collection) : base(collection) { } /// <summary>Initializes a new instance of the <see cref="EquatableList{T}"/> /// class that is empty and has the specified initial capacity.</summary> /// <param name="capacity">The number of elements that the new list can initially store.</param> public EquatableList(int capacity) : base(capacity) { } /// <summary>Adds a range of objects represented by the <see cref="ICollection"/> /// implementation.</summary> /// <param name="c">The <see cref="ICollection"/> /// implementation to add to this list.</param> public void AddRange(ICollection c) { // If the collection is null, throw an exception. if (c == null) throw new ArgumentNullException("c"); // Pre-compute capacity. Capacity = Math.Max(c.Count + Count, Capacity); // Cycle through the items and add. foreach (T item in c) { // Add the item. Add(item); } } /// <summary>Compares the counts of two <see cref="System.Collections.Generic.IEnumerable{T}"/> /// implementations.</summary> /// <remarks>This uses a trick in LINQ, sniffing types for implementations /// of interfaces that might supply shortcuts when trying to make comparisons. /// In this case, that is the <see cref="System.Collections.Generic.ICollection{T}"/> and /// <see cref="ICollection"/> interfaces, either of which can provide a count /// which can be used in determining the equality of sequences (if they don't have /// the same count, then they can't be equal).</remarks> /// <param name="x">The <see cref="System.Collections.Generic.IEnumerable{T}"/> from the left hand side of the /// comparison to check the count of.</param> /// <param name="y">The <see cref="System.Collections.Generic.IEnumerable{T}"/> from the right hand side of the /// comparison to check the count of.</param> /// <returns>Null if the result is indeterminate. This occurs when either <paramref name="x"/> /// or <paramref name="y"/> doesn't implement <see cref="ICollection"/> or <see cref="System.Collections.Generic.ICollection{T}"/>. /// Otherwise, it will get the count from each and return true if they are equal, false otherwise.</returns> private static bool? EnumerableCountsEqual(System.Collections.Generic.IEnumerable<T> x, System.Collections.Generic.IEnumerable<T> y) { // Get the ICollection<T> and ICollection interfaces. System.Collections.Generic.ICollection<T> xOfTCollection = x as System.Collections.Generic.ICollection<T>; System.Collections.Generic.ICollection<T> yOfTCollection = y as System.Collections.Generic.ICollection<T>; ICollection xCollection = x as ICollection; ICollection yCollection = y as ICollection; // The count in x and y. int? xCount = xOfTCollection != null ? xOfTCollection.Count : xCollection != null ? xCollection.Count : (int?)null; int? yCount = yOfTCollection != null ? yOfTCollection.Count : yCollection != null ? yCollection.Count : (int?)null; // If either are null, return null, the result is indeterminate. if (xCount == null || yCount == null) { // Return null, indeterminate. return null; } // Both counts are non-null, compare. return xCount == yCount; } /// <summary>Compares the contents of a <see cref="System.Collections.Generic.IEnumerable{T}"/> /// implementation to another one to determine equality.</summary> /// <remarks>Thinking of the <see cref="System.Collections.Generic.IEnumerable{T}"/> implementation as /// a string with any number of characters, the algorithm checks /// each item in each list. If any item of the list is not equal (or /// one list contains all the elements of another list), then that list /// element is compared to the other list element to see which /// list is greater.</remarks> /// <param name="x">The <see cref="System.Collections.Generic.IEnumerable{T}"/> implementation /// that is considered the left hand side.</param> /// <param name="y">The <see cref="System.Collections.Generic.IEnumerable{T}"/> implementation /// that is considered the right hand side.</param> /// <returns>True if the items are equal, false otherwise.</returns> private static bool Equals(System.Collections.Generic.IEnumerable<T> x, System.Collections.Generic.IEnumerable<T> y) { // If x and y are null, then return true, they are the same. if (x == null && y == null) { // They are the same, return 0. return true; } // If one is null, then return a value based on whether or not // one is null or not. if (x == null || y == null) { // Return false, one is null, the other is not. return false; } // Check to see if the counts on the IEnumerable implementations are equal. // This is a shortcut, if they are not equal, then the lists are not equal. // If the result is indeterminate, then get out. bool? enumerableCountsEqual = EnumerableCountsEqual(x, y); // If the enumerable counts have been able to be calculated (indicated by // a non-null value) and it is false, then no need to iterate through the items. if (enumerableCountsEqual != null && !enumerableCountsEqual.Value) { // The sequences are not equal. return false; } // The counts of the items in the enumerations are equal, or indeterminate // so a full iteration needs to be made to compare each item. // Get the default comparer for T first. System.Collections.Generic.EqualityComparer<T> defaultComparer = EqualityComparer<T>.Default; // Get the enumerator for y. System.Collections.Generic.IEnumerator<T> otherEnumerator = y.GetEnumerator(); // Call Dispose on IDisposable if there is an implementation on the // IEnumerator<T> returned by a call to y.GetEnumerator(). using (otherEnumerator as IDisposable) { // Cycle through the items in this list. foreach (T item in x) { // If there isn't an item to get, then this has more // items than that, they are not equal. if (!otherEnumerator.MoveNext()) { // Return false. return false; } // Perform a comparison. Must check this on the left hand side // and that on the right hand side. bool comparison = defaultComparer.Equals(item, otherEnumerator.Current); // If the value is false, return false. if (!comparison) { // Return the value. return comparison; } } // If there are no more items, then return true, the sequences // are equal. if (!otherEnumerator.MoveNext()) { // The sequences are equal. return true; } // The other sequence has more items than this one, return // false, these are not equal. return false; } } #region IEquatable<IEnumerable<T>> Members /// <summary>Compares this sequence to another <see cref="System.Collections.Generic.IEnumerable{T}"/> /// implementation, returning true if they are equal, false otherwise.</summary> /// <param name="other">The other <see cref="System.Collections.Generic.IEnumerable{T}"/> implementation /// to compare against.</param> /// <returns>True if the sequence in <paramref name="other"/> /// is the same as this one.</returns> public bool Equals(System.Collections.Generic.IEnumerable<T> other) { // Compare to the other sequence. If 0, then equal. return Equals(this, other); } #endregion /// <summary>Compares this object for equality against other.</summary> /// <param name="obj">The other object to compare this object against.</param> /// <returns>True if this object and <paramref name="obj"/> are equal, false /// otherwise.</returns> public override bool Equals(object obj) { // Call the strongly typed version. return Equals(obj as System.Collections.Generic.IEnumerable<T>); } /// <summary>Gets the hash code for the list.</summary> /// <returns>The hash code value.</returns> public override int GetHashCode() { // Call the static method, passing this. return GetHashCode(this); } #if __MonoCS__ public static int GetHashCode<T>(System.Collections.Generic.IEnumerable<T> source) #else /// <summary>Gets the hash code for the list.</summary> /// <param name="source">The <see cref="System.Collections.Generic.IEnumerable{T}"/> /// implementation which will have all the contents hashed.</param> /// <returns>The hash code value.</returns> public static int GetHashCode(System.Collections.Generic.IEnumerable<T> source) #endif { // If source is null, then return 0. if (source == null) return 0; // Seed the hash code with the hash code of the type. // This is done so that you don't have a lot of collisions of empty // ComparableList instances when placed in dictionaries // and things that rely on hashcodes. int hashCode = typeof(T).GetHashCode(); // Iterate through the items in this implementation. foreach (T item in source) { // Adjust the hash code. hashCode = 31 * hashCode + (item == null ? 0 : item.GetHashCode()); } // Return the hash code. return hashCode; } // TODO: When diverging from Java version of Lucene, can uncomment these to adhere to best practices when overriding the Equals method and implementing IEquatable<T>. ///// <summary>Overload of the == operator, it compares a ///// <see cref="ComparableList{T}"/> to an <see cref="IEnumerable{T}"/> ///// implementation.</summary> ///// <param name="x">The <see cref="ComparableList{T}"/> to compare ///// against <paramref name="y"/>.</param> ///// <param name="y">The <see cref="IEnumerable{T}"/> to compare ///// against <paramref name="x"/>.</param> ///// <returns>True if the instances are equal, false otherwise.</returns> //public static bool operator ==(EquatableList<T> x, System.Collections.Generic.IEnumerable<T> y) //{ // // Call Equals. // return Equals(x, y); //} ///// <summary>Overload of the == operator, it compares a ///// <see cref="ComparableList{T}"/> to an <see cref="IEnumerable{T}"/> ///// implementation.</summary> ///// <param name="y">The <see cref="ComparableList{T}"/> to compare ///// against <paramref name="x"/>.</param> ///// <param name="x">The <see cref="IEnumerable{T}"/> to compare ///// against <paramref name="y"/>.</param> ///// <returns>True if the instances are equal, false otherwise.</returns> //public static bool operator ==(System.Collections.Generic.IEnumerable<T> x, EquatableList<T> y) //{ // // Call equals. // return Equals(x, y); //} ///// <summary>Overload of the != operator, it compares a ///// <see cref="ComparableList{T}"/> to an <see cref="IEnumerable{T}"/> ///// implementation.</summary> ///// <param name="x">The <see cref="ComparableList{T}"/> to compare ///// against <paramref name="y"/>.</param> ///// <param name="y">The <see cref="IEnumerable{T}"/> to compare ///// against <paramref name="x"/>.</param> ///// <returns>True if the instances are not equal, false otherwise.</returns> //public static bool operator !=(EquatableList<T> x, System.Collections.Generic.IEnumerable<T> y) //{ // // Return the negative of the equals operation. // return !(x == y); //} ///// <summary>Overload of the != operator, it compares a ///// <see cref="ComparableList{T}"/> to an <see cref="IEnumerable{T}"/> ///// implementation.</summary> ///// <param name="y">The <see cref="ComparableList{T}"/> to compare ///// against <paramref name="x"/>.</param> ///// <param name="x">The <see cref="IEnumerable{T}"/> to compare ///// against <paramref name="y"/>.</param> ///// <returns>True if the instances are not equal, false otherwise.</returns> //public static bool operator !=(System.Collections.Generic.IEnumerable<T> x, EquatableList<T> y) //{ // // Return the negative of the equals operation. // return !(x == y); //} #region ICloneable Members /// <summary>Clones the <see cref="EquatableList{T}"/>.</summary> /// <remarks>This is a shallow clone.</remarks> /// <returns>A new shallow clone of this /// <see cref="EquatableList{T}"/>.</returns> public object Clone() { // Just create a new one, passing this to the constructor. return new EquatableList<T>(this); } #endregion } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation 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 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.Data; using System.Configuration; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using Microsoft.Web.Services3.Referral; using WebsitePanel.EnterpriseServer; using WebsitePanel.EnterpriseServer.Base.HostedSolution; using WebsitePanel.Portal.UserControls; using WebsitePanel.Providers.HostedSolution; namespace WebsitePanel.Portal { public enum UserActionTypes { None = 0, Disable = 1, Enable = 2, SetServiceLevel = 3, SetVIP = 4, UnsetVIP = 5, SetMailboxPlan = 6, SendBySms = 7, SendByEmail = 8 } public partial class UserActions : ActionListControlBase<UserActionTypes> { public bool ShowSetMailboxPlan { get; set; } protected void Page_Load(object sender, EventArgs e) { // Remove Service Level item and VIP item from Action List if current Hosting plan does not allow Service Levels if (!PackagesHelper.GetCachedPackageContext(PanelSecurity.PackageId).Groups.ContainsKey(ResourceGroups.ServiceLevels)) { RemoveActionItem(UserActionTypes.SetServiceLevel); RemoveActionItem(UserActionTypes.SetVIP); RemoveActionItem(UserActionTypes.UnsetVIP); } if (!ShowSetMailboxPlan) RemoveActionItem(UserActionTypes.SetMailboxPlan); } protected override DropDownList ActionsList { get { return ddlUserActions; } } protected override int DoAction(List<int> userIds) { switch (SelectedAction) { case UserActionTypes.Disable: return ChangeUsersSettings(userIds, true, null, null); case UserActionTypes.Enable: return ChangeUsersSettings(userIds, false, null, null); case UserActionTypes.SetServiceLevel: return ChangeUsersServiceLevel(userIds); case UserActionTypes.SetVIP: return ChangeUsersSettings(userIds, null, null, true); case UserActionTypes.UnsetVIP: return ChangeUsersSettings(userIds, null, null, false); case UserActionTypes.SetMailboxPlan: return SetMailboxPlan(userIds); case UserActionTypes.SendByEmail: return SendPasswordResetEmails(userIds); case UserActionTypes.SendBySms: return SendPasswordResetSms(userIds); } return 0; } protected int ChangeUsersServiceLevel(List<int> userIds) { if (ddlServiceLevels.SelectedItem == null) return 0; string levelName = ddlServiceLevels.SelectedItem.Text; if (string.IsNullOrEmpty(levelName)) return 0; int levelId; if (string.IsNullOrEmpty(ddlServiceLevels.SelectedItem.Value)) return ChangeUsersSettings(userIds, null, 0, null); if (!int.TryParse(ddlServiceLevels.SelectedItem.Value, out levelId)) return 0; string quotaName = Quotas.SERVICE_LEVELS + levelName; PackageContext cntx = PackagesHelper.GetCachedPackageContext(PanelSecurity.PackageId); if (!cntx.Quotas.ContainsKey(quotaName)) return 0; OrganizationStatistics stats = ES.Services.Organizations.GetOrganizationStatisticsByOrganization(PanelRequest.ItemID); List<OrganizationUser> users = userIds.Select(id => ES.Services.Organizations.GetUserGeneralSettings(PanelRequest.ItemID, id)).ToList(); int usersCount = users.Count - users.Count(x => x.LevelId == levelId); if (!CheckServiceLevelQuota(levelName, stats.ServiceLevels, usersCount)) return -1; return ChangeUsersSettings(userIds, null, levelId, null); } protected void btnModalOk_Click(object sender, EventArgs e) { FireExecuteAction(); } protected void btnModalCancel_OnClick(object sender, EventArgs e) { ResetSelection(); } protected int ChangeUsersSettings(List<int> userIds, bool? disable, int? serviceLevelId, bool? isVIP) { foreach (var userId in userIds) { OrganizationUser user = ES.Services.Organizations.GetUserGeneralSettings(PanelRequest.ItemID, userId); int result = ES.Services.Organizations.SetUserGeneralSettings( PanelRequest.ItemID, userId, user.DisplayName, string.Empty, false, disable ?? user.Disabled, user.Locked, user.FirstName, user.Initials, user.LastName, user.Address, user.City, user.State, user.Zip, user.Country, user.JobTitle, user.Company, user.Department, user.Office, user.Manager != null ? user.Manager.AccountName : String.Empty, user.BusinessPhone, user.Fax, user.HomePhone, user.MobilePhone, user.Pager, user.WebPage, user.Notes, user.ExternalEmail, user.SubscriberNumber, serviceLevelId ?? user.LevelId, isVIP ?? user.IsVIP, user.UserMustChangePassword); if (result < 0) return result; } return 0; } protected int SetMailboxPlan(List<int> userIds) { int planId; if (!int.TryParse(mailboxPlanSelector.MailboxPlanId, out planId)) return 0; if (planId < 0) return 0; foreach (int userId in userIds) { ExchangeAccount account = ES.Services.ExchangeServer.GetAccount(PanelRequest.ItemID, userId); int result = ES.Services.ExchangeServer.SetExchangeMailboxPlan(PanelRequest.ItemID, userId, planId, account.ArchivingMailboxPlanId, account.EnableArchiving); if (result < 0) return result; } return 0; } protected int SendPasswordResetEmails(List<int> userIds) { foreach (int userId in userIds) { ES.Services.Organizations.SendResetUserPasswordEmail(PanelRequest.ItemID, userId, "Group action", null, true); } return 0; } protected int SendPasswordResetSms(List<int> userIds) { var accountsWithoutPhone = GetAccountsWithoutPhone(); foreach (int userId in userIds.Except(accountsWithoutPhone.Select(x => x.AccountId))) { ES.Services.Organizations.SendResetUserPasswordLinkSms(PanelRequest.ItemID, userId, "Group action", null); } return 0; } #region ServiceLevel protected void FillServiceLevelsList() { if (GridView == null || String.IsNullOrWhiteSpace(CheckboxesName)) return; List<int> ids = Utils.GetCheckboxValuesFromGrid<int>(GridView, CheckboxesName); List<OrganizationUser> users = ids.Select(id => ES.Services.Organizations.GetUserGeneralSettings(PanelRequest.ItemID, id)).ToList(); OrganizationStatistics stats = ES.Services.Organizations.GetOrganizationStatisticsByOrganization(PanelRequest.ItemID); PackageContext cntx = PackagesHelper.GetCachedPackageContext(PanelSecurity.PackageId); if (cntx.Groups.ContainsKey(ResourceGroups.ServiceLevels)) { List<ServiceLevel> enabledServiceLevels = new List<ServiceLevel>(); foreach (ServiceLevel serviceLevel in ES.Services.Organizations.GetSupportServiceLevels()) { int usersCount = users.Count - users.Count(x => (x.LevelId == serviceLevel.LevelId)); if (CheckServiceLevelQuota(serviceLevel.LevelName, stats.ServiceLevels, usersCount)) enabledServiceLevels.Add(serviceLevel); } ddlServiceLevels.DataSource = enabledServiceLevels; ddlServiceLevels.DataTextField = "LevelName"; ddlServiceLevels.DataValueField = "LevelId"; ddlServiceLevels.DataBind(); ddlServiceLevels.Items.Insert(0, new ListItem("<Select Service Level>", string.Empty)); ddlServiceLevels.Items.FindByValue(string.Empty).Selected = true; } } private bool CheckServiceLevelQuota(string serviceLevelName, List<QuotaValueInfo> quotas, int itemCount) { var quota = quotas.FirstOrDefault(q => q.QuotaName.Replace(Quotas.SERVICE_LEVELS, "") == serviceLevelName); if (quota == null) return false; if (quota.QuotaAllocatedValue == -1) return true; return quota.QuotaAllocatedValue >= quota.QuotaUsedValue + itemCount; } #endregion protected void CheckUsersHaveMobilePhone() { var accountsWithoutPhones = GetAccountsWithoutPhone(); if (accountsWithoutPhones.Any()) { repAccountsWithoutPhone.DataSource = accountsWithoutPhones; repAccountsWithoutPhone.DataBind(); Modal.PopupControlID = PasswordResetNotificationPanel.ID; Modal.Show(); } else { FireExecuteAction(); } } protected List<OrganizationUser> GetAccountsWithoutPhone() { if (GridView == null || String.IsNullOrWhiteSpace(CheckboxesName)) return new List<OrganizationUser>(); // Get checked users var ids = Utils.GetCheckboxValuesFromGrid<int>(GridView, CheckboxesName); var accountsWithoutPhones = new List<OrganizationUser>(); foreach (var id in ids) { var account = ES.Services.Organizations.GetUserGeneralSettings(PanelRequest.ItemID, id); if (string.IsNullOrEmpty(account.MobilePhone)) { accountsWithoutPhones.Add(account); } } return accountsWithoutPhones; } protected void btnApply_Click(object sender, EventArgs e) { switch (SelectedAction) { case UserActionTypes.Disable: case UserActionTypes.Enable: case UserActionTypes.SetVIP: case UserActionTypes.UnsetVIP: case UserActionTypes.SendByEmail: FireExecuteAction(); break; case UserActionTypes.SetServiceLevel: FillServiceLevelsList(); Modal.PopupControlID = ServiceLevelPanel.ID; Modal.Show(); break; case UserActionTypes.SetMailboxPlan: Modal.PopupControlID = MailboxPlanPanel.ID; Modal.Show(); break; case UserActionTypes.SendBySms: CheckUsersHaveMobilePhone(); break; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ServiceBus { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for NamespacesOperations. /// </summary> public static partial class NamespacesOperationsExtensions { /// <summary> /// Check the give namespace name availability. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='parameters'> /// Parameters to check availability of the given namespace name /// </param> public static CheckNameAvailabilityResult CheckNameAvailabilityMethod(this INamespacesOperations operations, CheckNameAvailability parameters) { return operations.CheckNameAvailabilityMethodAsync(parameters).GetAwaiter().GetResult(); } /// <summary> /// Check the give namespace name availability. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='parameters'> /// Parameters to check availability of the given namespace name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CheckNameAvailabilityResult> CheckNameAvailabilityMethodAsync(this INamespacesOperations operations, CheckNameAvailability parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CheckNameAvailabilityMethodWithHttpMessagesAsync(parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all the available namespaces within the subscription, irrespective of /// the resource groups. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<NamespaceResource> ListBySubscription(this INamespacesOperations operations) { return operations.ListBySubscriptionAsync().GetAwaiter().GetResult(); } /// <summary> /// Gets all the available namespaces within the subscription, irrespective of /// the resource groups. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NamespaceResource>> ListBySubscriptionAsync(this INamespacesOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListBySubscriptionWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the available namespaces within a resource group. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> public static IPage<NamespaceResource> ListByResourceGroup(this INamespacesOperations operations, string resourceGroupName) { return operations.ListByResourceGroupAsync(resourceGroupName).GetAwaiter().GetResult(); } /// <summary> /// Gets the available namespaces within a resource group. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NamespaceResource>> ListByResourceGroupAsync(this INamespacesOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a service namespace. Once created, this namespace's /// resource manifest is immutable. This operation is idempotent. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639408.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a namespace resource. /// </param> public static NamespaceResource CreateOrUpdate(this INamespacesOperations operations, string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, namespaceName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a service namespace. Once created, this namespace's /// resource manifest is immutable. This operation is idempotent. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639408.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a namespace resource. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<NamespaceResource> CreateOrUpdateAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes an existing namespace. This operation also removes all associated /// resources under the namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639389.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> public static void Delete(this INamespacesOperations operations, string resourceGroupName, string namespaceName) { operations.DeleteAsync(resourceGroupName, namespaceName).GetAwaiter().GetResult(); } /// <summary> /// Deletes an existing namespace. This operation also removes all associated /// resources under the namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639389.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets a description for the specified namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639379.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> public static NamespaceResource Get(this INamespacesOperations operations, string resourceGroupName, string namespaceName) { return operations.GetAsync(resourceGroupName, namespaceName).GetAwaiter().GetResult(); } /// <summary> /// Gets a description for the specified namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639379.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<NamespaceResource> GetAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates a service namespace. Once created, this namespace's resource /// manifest is immutable. This operation is idempotent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='parameters'> /// Parameters supplied to update a namespace resource. /// </param> public static NamespaceResource Update(this INamespacesOperations operations, string resourceGroupName, string namespaceName, NamespaceUpdateParameters parameters) { return operations.UpdateAsync(resourceGroupName, namespaceName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Updates a service namespace. Once created, this namespace's resource /// manifest is immutable. This operation is idempotent. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='parameters'> /// Parameters supplied to update a namespace resource. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<NamespaceResource> UpdateAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, NamespaceUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the authorization rules for a namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639376.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> public static IPage<SharedAccessAuthorizationRuleResource> ListAuthorizationRules(this INamespacesOperations operations, string resourceGroupName, string namespaceName) { return operations.ListAuthorizationRulesAsync(resourceGroupName, namespaceName).GetAwaiter().GetResult(); } /// <summary> /// Gets the authorization rules for a namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639376.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<SharedAccessAuthorizationRuleResource>> ListAuthorizationRulesAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAuthorizationRulesWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates an authorization rule for a namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639410.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='parameters'> /// The shared access authorization rule. /// </param> public static SharedAccessAuthorizationRuleResource CreateOrUpdateAuthorizationRule(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates an authorization rule for a namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639410.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='parameters'> /// The shared access authorization rule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<SharedAccessAuthorizationRuleResource> CreateOrUpdateAuthorizationRuleAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a namespace authorization rule. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639417.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> public static void DeleteAuthorizationRule(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName) { operations.DeleteAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName).GetAwaiter().GetResult(); } /// <summary> /// Deletes a namespace authorization rule. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639417.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAuthorizationRuleAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets an authorization rule for a namespace by rule name. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639392.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> public static SharedAccessAuthorizationRuleResource GetAuthorizationRule(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName) { return operations.GetAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName).GetAwaiter().GetResult(); } /// <summary> /// Gets an authorization rule for a namespace by rule name. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639392.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<SharedAccessAuthorizationRuleResource> GetAuthorizationRuleAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the primary and secondary connection strings for the namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639398.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> public static ResourceListKeys ListKeys(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName) { return operations.ListKeysAsync(resourceGroupName, namespaceName, authorizationRuleName).GetAwaiter().GetResult(); } /// <summary> /// Gets the primary and secondary connection strings for the namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639398.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ResourceListKeys> ListKeysAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Regenerates the primary or secondary connection strings for the namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt718977.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate the authorization rule. /// </param> public static ResourceListKeys RegenerateKeys(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, RegenerateKeysParameters parameters) { return operations.RegenerateKeysAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Regenerates the primary or secondary connection strings for the namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt718977.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate the authorization rule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ResourceListKeys> RegenerateKeysAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, RegenerateKeysParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.RegenerateKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a service namespace. Once created, this namespace's /// resource manifest is immutable. This operation is idempotent. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639408.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a namespace resource. /// </param> public static NamespaceResource BeginCreateOrUpdate(this INamespacesOperations operations, string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, namespaceName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a service namespace. Once created, this namespace's /// resource manifest is immutable. This operation is idempotent. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639408.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a namespace resource. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<NamespaceResource> BeginCreateOrUpdateAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes an existing namespace. This operation also removes all associated /// resources under the namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639389.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> public static void BeginDelete(this INamespacesOperations operations, string resourceGroupName, string namespaceName) { operations.BeginDeleteAsync(resourceGroupName, namespaceName).GetAwaiter().GetResult(); } /// <summary> /// Deletes an existing namespace. This operation also removes all associated /// resources under the namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639389.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all the available namespaces within the subscription, irrespective of /// the resource groups. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<NamespaceResource> ListBySubscriptionNext(this INamespacesOperations operations, string nextPageLink) { return operations.ListBySubscriptionNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets all the available namespaces within the subscription, irrespective of /// the resource groups. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NamespaceResource>> ListBySubscriptionNextAsync(this INamespacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListBySubscriptionNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the available namespaces within a resource group. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<NamespaceResource> ListByResourceGroupNext(this INamespacesOperations operations, string nextPageLink) { return operations.ListByResourceGroupNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets the available namespaces within a resource group. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639412.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<NamespaceResource>> ListByResourceGroupNextAsync(this INamespacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the authorization rules for a namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639376.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<SharedAccessAuthorizationRuleResource> ListAuthorizationRulesNext(this INamespacesOperations operations, string nextPageLink) { return operations.ListAuthorizationRulesNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets the authorization rules for a namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639376.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<SharedAccessAuthorizationRuleResource>> ListAuthorizationRulesNextAsync(this INamespacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAuthorizationRulesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
/* * 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.Net; using System.Xml; using System.Reflection; using System.Text; using System.Threading; using OpenSim.Framework; using OpenSim.Framework.Capabilities; using OpenSim.Framework.Client; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Serialization; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenMetaverse; using log4net; using Nini.Config; using Mono.Addins; using PermissionMask = OpenSim.Framework.PermissionMask; namespace OpenSim.Region.CoreModules.Framework.InventoryAccess { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "BasicInventoryAccessModule")] public class BasicInventoryAccessModule : INonSharedRegionModule, IInventoryAccessModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected bool m_Enabled = false; protected Scene m_Scene; protected IUserManagement m_UserManagement; protected IUserManagement UserManagementModule { get { if (m_UserManagement == null) m_UserManagement = m_Scene.RequestModuleInterface<IUserManagement>(); return m_UserManagement; } } public bool CoalesceMultipleObjectsToInventory { get; set; } #region INonSharedRegionModule public Type ReplaceableInterface { get { return null; } } public virtual string Name { get { return "BasicInventoryAccessModule"; } } public virtual void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("InventoryAccessModule", ""); if (name == Name) { m_Enabled = true; InitialiseCommon(source); m_log.InfoFormat("[INVENTORY ACCESS MODULE]: {0} enabled.", Name); } } } /// <summary> /// Common module config for both this and descendant classes. /// </summary> /// <param name="source"></param> protected virtual void InitialiseCommon(IConfigSource source) { IConfig inventoryConfig = source.Configs["Inventory"]; if (inventoryConfig != null) CoalesceMultipleObjectsToInventory = inventoryConfig.GetBoolean("CoalesceMultipleObjectsToInventory", true); else CoalesceMultipleObjectsToInventory = true; } public virtual void PostInitialise() { } public virtual void AddRegion(Scene scene) { if (!m_Enabled) return; m_Scene = scene; scene.RegisterModuleInterface<IInventoryAccessModule>(this); scene.EventManager.OnNewClient += OnNewClient; } protected virtual void OnNewClient(IClientAPI client) { client.OnCreateNewInventoryItem += CreateNewInventoryItem; } public virtual void Close() { if (!m_Enabled) return; } public virtual void RemoveRegion(Scene scene) { if (!m_Enabled) return; m_Scene = null; } public virtual void RegionLoaded(Scene scene) { if (!m_Enabled) return; } #endregion #region Inventory Access /// <summary> /// Create a new inventory item. Called when the client creates a new item directly within their /// inventory (e.g. by selecting a context inventory menu option). /// </summary> /// <param name="remoteClient"></param> /// <param name="transactionID"></param> /// <param name="folderID"></param> /// <param name="callbackID"></param> /// <param name="description"></param> /// <param name="name"></param> /// <param name="invType"></param> /// <param name="type"></param> /// <param name="wearableType"></param> /// <param name="nextOwnerMask"></param> public void CreateNewInventoryItem(IClientAPI remoteClient, UUID transactionID, UUID folderID, uint callbackID, string description, string name, sbyte invType, sbyte assetType, byte wearableType, uint nextOwnerMask, int creationDate) { m_log.DebugFormat("[INVENTORY ACCESS MODULE]: Received request to create inventory item {0} in folder {1}", name, folderID); if (!m_Scene.Permissions.CanCreateUserInventory(invType, remoteClient.AgentId)) return; if (transactionID == UUID.Zero) { ScenePresence presence; if (m_Scene.TryGetScenePresence(remoteClient.AgentId, out presence)) { byte[] data = null; if (invType == (sbyte)InventoryType.Landmark && presence != null) { string suffix = string.Empty, prefix = string.Empty; string strdata = GenerateLandmark(presence, out prefix, out suffix); data = Encoding.ASCII.GetBytes(strdata); name = prefix + name; description += suffix; } AssetBase asset = m_Scene.CreateAsset(name, description, assetType, data, remoteClient.AgentId); m_Scene.AssetService.Store(asset); m_Scene.CreateNewInventoryItem( remoteClient, remoteClient.AgentId.ToString(), string.Empty, folderID, name, description, 0, callbackID, asset.FullID, asset.Type, invType, nextOwnerMask, creationDate); } else { m_log.ErrorFormat( "[INVENTORY ACCESS MODULE]: ScenePresence for agent uuid {0} unexpectedly not found in CreateNewInventoryItem", remoteClient.AgentId); } } else { IAgentAssetTransactions agentTransactions = m_Scene.AgentTransactionsModule; if (agentTransactions != null) { agentTransactions.HandleItemCreationFromTransaction( remoteClient, transactionID, folderID, callbackID, description, name, invType, assetType, wearableType, nextOwnerMask); } } } protected virtual string GenerateLandmark(ScenePresence presence, out string prefix, out string suffix) { prefix = string.Empty; suffix = string.Empty; Vector3 pos = presence.AbsolutePosition; return String.Format("Landmark version 2\nregion_id {0}\nlocal_pos {1} {2} {3}\nregion_handle {4}\n", presence.Scene.RegionInfo.RegionID, pos.X, pos.Y, pos.Z, presence.RegionHandle); } /// <summary> /// Capability originating call to update the asset of an item in an agent's inventory /// </summary> /// <param name="remoteClient"></param> /// <param name="itemID"></param> /// <param name="data"></param> /// <returns></returns> public virtual UUID CapsUpdateInventoryItemAsset(IClientAPI remoteClient, UUID itemID, byte[] data) { InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId); item = m_Scene.InventoryService.GetItem(item); if (item.Owner != remoteClient.AgentId) return UUID.Zero; if (item != null) { if ((InventoryType)item.InvType == InventoryType.Notecard) { if (!m_Scene.Permissions.CanEditNotecard(itemID, UUID.Zero, remoteClient.AgentId)) { remoteClient.SendAgentAlertMessage("Insufficient permissions to edit notecard", false); return UUID.Zero; } remoteClient.SendAlertMessage("Notecard saved"); } else if ((InventoryType)item.InvType == InventoryType.LSL) { if (!m_Scene.Permissions.CanEditScript(itemID, UUID.Zero, remoteClient.AgentId)) { remoteClient.SendAgentAlertMessage("Insufficient permissions to edit script", false); return UUID.Zero; } remoteClient.SendAlertMessage("Script saved"); } AssetBase asset = CreateAsset(item.Name, item.Description, (sbyte)item.AssetType, data, remoteClient.AgentId.ToString()); item.AssetID = asset.FullID; m_Scene.AssetService.Store(asset); m_Scene.InventoryService.UpdateItem(item); // remoteClient.SendInventoryItemCreateUpdate(item); return (asset.FullID); } else { m_log.ErrorFormat( "[INVENTORY ACCESS MODULE]: Could not find item {0} for caps inventory update", itemID); } return UUID.Zero; } public virtual bool UpdateInventoryItemAsset(UUID ownerID, InventoryItemBase item, AssetBase asset) { if (item != null && item.Owner == ownerID && asset != null) { // m_log.DebugFormat( // "[INVENTORY ACCESS MODULE]: Updating item {0} {1} with new asset {2}", // item.Name, item.ID, asset.ID); item.AssetID = asset.FullID; item.Description = asset.Description; item.Name = asset.Name; item.AssetType = asset.Type; item.InvType = (int)InventoryType.Object; m_Scene.AssetService.Store(asset); m_Scene.InventoryService.UpdateItem(item); return true; } else { m_log.ErrorFormat("[INVENTORY ACCESS MODULE]: Given invalid item for inventory update: {0}", (item == null || asset == null? "null item or asset" : "wrong owner")); return false; } } public virtual List<InventoryItemBase> CopyToInventory( DeRezAction action, UUID folderID, List<SceneObjectGroup> objectGroups, IClientAPI remoteClient, bool asAttachment) { List<InventoryItemBase> copiedItems = new List<InventoryItemBase>(); Dictionary<UUID, List<SceneObjectGroup>> bundlesToCopy = new Dictionary<UUID, List<SceneObjectGroup>>(); if (CoalesceMultipleObjectsToInventory) { // The following code groups the SOG's by owner. No objects // belonging to different people can be coalesced, for obvious // reasons. foreach (SceneObjectGroup g in objectGroups) { if (!bundlesToCopy.ContainsKey(g.OwnerID)) bundlesToCopy[g.OwnerID] = new List<SceneObjectGroup>(); bundlesToCopy[g.OwnerID].Add(g); } } else { // If we don't want to coalesce then put every object in its own bundle. foreach (SceneObjectGroup g in objectGroups) { List<SceneObjectGroup> bundle = new List<SceneObjectGroup>(); bundle.Add(g); bundlesToCopy[g.UUID] = bundle; } } // m_log.DebugFormat( // "[INVENTORY ACCESS MODULE]: Copying {0} object bundles to folder {1} action {2} for {3}", // bundlesToCopy.Count, folderID, action, remoteClient.Name); // Each iteration is really a separate asset being created, // with distinct destinations as well. foreach (List<SceneObjectGroup> bundle in bundlesToCopy.Values) copiedItems.Add(CopyBundleToInventory(action, folderID, bundle, remoteClient, asAttachment)); return copiedItems; } /// <summary> /// Copy a bundle of objects to inventory. If there is only one object, then this will create an object /// item. If there are multiple objects then these will be saved as a single coalesced item. /// </summary> /// <param name="action"></param> /// <param name="folderID"></param> /// <param name="objlist"></param> /// <param name="remoteClient"></param> /// <param name="asAttachment">Should be true if the bundle is being copied as an attachment. This prevents /// attempted serialization of any script state which would abort any operating scripts.</param> /// <returns>The inventory item created by the copy</returns> protected InventoryItemBase CopyBundleToInventory( DeRezAction action, UUID folderID, List<SceneObjectGroup> objlist, IClientAPI remoteClient, bool asAttachment) { CoalescedSceneObjects coa = new CoalescedSceneObjects(UUID.Zero); // Dictionary<UUID, Vector3> originalPositions = new Dictionary<UUID, Vector3>(); Dictionary<SceneObjectGroup, KeyframeMotion> group2Keyframe = new Dictionary<SceneObjectGroup, KeyframeMotion>(); foreach (SceneObjectGroup objectGroup in objlist) { if (objectGroup.RootPart.KeyframeMotion != null) { objectGroup.RootPart.KeyframeMotion.Pause(); group2Keyframe.Add(objectGroup, objectGroup.RootPart.KeyframeMotion); objectGroup.RootPart.KeyframeMotion = null; } // Vector3 inventoryStoredPosition = new Vector3 // (((objectGroup.AbsolutePosition.X > (int)Constants.RegionSize) // ? 250 // : objectGroup.AbsolutePosition.X) // , // (objectGroup.AbsolutePosition.Y > (int)Constants.RegionSize) // ? 250 // : objectGroup.AbsolutePosition.Y, // objectGroup.AbsolutePosition.Z); // // originalPositions[objectGroup.UUID] = objectGroup.AbsolutePosition; // // objectGroup.AbsolutePosition = inventoryStoredPosition; // Make sure all bits but the ones we want are clear // on take. // This will be applied to the current perms, so // it will do what we want. objectGroup.RootPart.NextOwnerMask &= ((uint)PermissionMask.Copy | (uint)PermissionMask.Transfer | (uint)PermissionMask.Modify | (uint)PermissionMask.Export); objectGroup.RootPart.NextOwnerMask |= (uint)PermissionMask.Move; coa.Add(objectGroup); } string itemXml; // If we're being called from a script, then trying to serialize that same script's state will not complete // in any reasonable time period. Therefore, we'll avoid it. The worst that can happen is that if // the client/server crashes rather than logging out normally, the attachment's scripts will resume // without state on relog. Arguably, this is what we want anyway. if (objlist.Count > 1) itemXml = CoalescedSceneObjectsSerializer.ToXml(coa, !asAttachment); else itemXml = SceneObjectSerializer.ToOriginalXmlFormat(objlist[0], !asAttachment); // // Restore the position of each group now that it has been stored to inventory. // foreach (SceneObjectGroup objectGroup in objlist) // objectGroup.AbsolutePosition = originalPositions[objectGroup.UUID]; InventoryItemBase item = CreateItemForObject(action, remoteClient, objlist[0], folderID); // m_log.DebugFormat( // "[INVENTORY ACCESS MODULE]: Created item is {0}", // item != null ? item.ID.ToString() : "NULL"); if (item == null) return null; item.CreatorId = objlist[0].RootPart.CreatorID.ToString(); item.CreatorData = objlist[0].RootPart.CreatorData; if (objlist.Count > 1) { item.Flags = (uint)InventoryItemFlags.ObjectHasMultipleItems; // If the objects have different creators then don't specify a creator at all foreach (SceneObjectGroup objectGroup in objlist) { if ((objectGroup.RootPart.CreatorID.ToString() != item.CreatorId) || (objectGroup.RootPart.CreatorData.ToString() != item.CreatorData)) { item.CreatorId = UUID.Zero.ToString(); item.CreatorData = string.Empty; break; } } } else { item.SaleType = objlist[0].RootPart.ObjectSaleType; item.SalePrice = objlist[0].RootPart.SalePrice; } AssetBase asset = CreateAsset( objlist[0].GetPartName(objlist[0].RootPart.LocalId), objlist[0].GetPartDescription(objlist[0].RootPart.LocalId), (sbyte)AssetType.Object, Utils.StringToBytes(itemXml), objlist[0].OwnerID.ToString()); m_Scene.AssetService.Store(asset); item.AssetID = asset.FullID; if (DeRezAction.SaveToExistingUserInventoryItem == action) { m_Scene.InventoryService.UpdateItem(item); } else { item.CreationDate = Util.UnixTimeSinceEpoch(); item.Description = asset.Description; item.Name = asset.Name; item.AssetType = asset.Type; AddPermissions(item, objlist[0], objlist, remoteClient); m_Scene.AddInventoryItem(item); if (remoteClient != null && item.Owner == remoteClient.AgentId) { remoteClient.SendInventoryItemCreateUpdate(item, 0); } else { ScenePresence notifyUser = m_Scene.GetScenePresence(item.Owner); if (notifyUser != null) { notifyUser.ControllingClient.SendInventoryItemCreateUpdate(item, 0); } } } // Restore KeyframeMotion foreach (SceneObjectGroup objectGroup in group2Keyframe.Keys) { objectGroup.RootPart.KeyframeMotion = group2Keyframe[objectGroup]; objectGroup.RootPart.KeyframeMotion.Start(); } // This is a hook to do some per-asset post-processing for subclasses that need that if (remoteClient != null) ExportAsset(remoteClient.AgentId, asset.FullID); return item; } protected virtual void ExportAsset(UUID agentID, UUID assetID) { // nothing to do here } /// <summary> /// Add relevant permissions for an object to the item. /// </summary> /// <param name="item"></param> /// <param name="so"></param> /// <param name="objsForEffectivePermissions"></param> /// <param name="remoteClient"></param> /// <returns></returns> protected InventoryItemBase AddPermissions( InventoryItemBase item, SceneObjectGroup so, List<SceneObjectGroup> objsForEffectivePermissions, IClientAPI remoteClient) { uint effectivePerms = (uint)(PermissionMask.Copy | PermissionMask.Transfer | PermissionMask.Modify | PermissionMask.Move | PermissionMask.Export) | 7; uint allObjectsNextOwnerPerms = 0x7fffffff; uint allObjectsEveryOnePerms = 0x7fffffff; uint allObjectsGroupPerms = 0x7fffffff; foreach (SceneObjectGroup grp in objsForEffectivePermissions) { effectivePerms &= grp.GetEffectivePermissions(); allObjectsNextOwnerPerms &= grp.RootPart.NextOwnerMask; allObjectsEveryOnePerms &= grp.RootPart.EveryoneMask; allObjectsGroupPerms &= grp.RootPart.GroupMask; } effectivePerms |= (uint)PermissionMask.Move; //PermissionsUtil.LogPermissions(item.Name, "Before AddPermissions", item.BasePermissions, item.CurrentPermissions, item.NextPermissions); if (remoteClient != null && (remoteClient.AgentId != so.RootPart.OwnerID) && m_Scene.Permissions.PropagatePermissions()) { // Changing ownership, so apply the "Next Owner" permissions to all of the // inventory item's permissions. uint perms = effectivePerms; PermissionsUtil.ApplyFoldedPermissions(effectivePerms, ref perms); item.BasePermissions = perms & allObjectsNextOwnerPerms; item.CurrentPermissions = item.BasePermissions; item.NextPermissions = perms & allObjectsNextOwnerPerms; item.EveryOnePermissions = allObjectsEveryOnePerms & allObjectsNextOwnerPerms; item.GroupPermissions = allObjectsGroupPerms & allObjectsNextOwnerPerms; // apply next owner perms on rez item.CurrentPermissions |= SceneObjectGroup.SLAM; } else { // Not changing ownership. // In this case we apply the permissions in the object's items ONLY to the inventory // item's "Next Owner" permissions, but NOT to its "Current", "Base", etc. permissions. // E.g., if the object contains a No-Transfer item then the item's "Next Owner" // permissions are also No-Transfer. PermissionsUtil.ApplyFoldedPermissions(effectivePerms, ref allObjectsNextOwnerPerms); item.BasePermissions = effectivePerms; item.CurrentPermissions = effectivePerms; item.NextPermissions = allObjectsNextOwnerPerms & effectivePerms; item.EveryOnePermissions = allObjectsEveryOnePerms & effectivePerms; item.GroupPermissions = allObjectsGroupPerms & effectivePerms; item.CurrentPermissions &= ((uint)PermissionMask.Copy | (uint)PermissionMask.Transfer | (uint)PermissionMask.Modify | (uint)PermissionMask.Move | (uint)PermissionMask.Export | 7); // Preserve folded permissions } //PermissionsUtil.LogPermissions(item.Name, "After AddPermissions", item.BasePermissions, item.CurrentPermissions, item.NextPermissions); return item; } /// <summary> /// Create an item using details for the given scene object. /// </summary> /// <param name="action"></param> /// <param name="remoteClient"></param> /// <param name="so"></param> /// <param name="folderID"></param> /// <returns></returns> protected InventoryItemBase CreateItemForObject( DeRezAction action, IClientAPI remoteClient, SceneObjectGroup so, UUID folderID) { // m_log.DebugFormat( // "[BASIC INVENTORY ACCESS MODULE]: Creating item for object {0} {1} for folder {2}, action {3}", // so.Name, so.UUID, folderID, action); // // Get the user info of the item destination // UUID userID = UUID.Zero; if (action == DeRezAction.Take || action == DeRezAction.TakeCopy || action == DeRezAction.SaveToExistingUserInventoryItem) { // Take or take copy require a taker // Saving changes requires a local user // if (remoteClient == null) return null; userID = remoteClient.AgentId; // m_log.DebugFormat( // "[INVENTORY ACCESS MODULE]: Target of {0} in CreateItemForObject() is {1} {2}", // action, remoteClient.Name, userID); } else if (so.RootPart.OwnerID == so.RootPart.GroupID) { // Group owned objects go to the last owner before the object was transferred. userID = so.RootPart.LastOwnerID; } else { // Other returns / deletes go to the object owner // userID = so.RootPart.OwnerID; // m_log.DebugFormat( // "[INVENTORY ACCESS MODULE]: Target of {0} in CreateItemForObject() is object owner {1}", // action, userID); } if (userID == UUID.Zero) // Can't proceed { return null; } // If we're returning someone's item, it goes back to the // owner's Lost And Found folder. // Delete is treated like return in this case // Deleting your own items makes them go to trash // InventoryFolderBase folder = null; InventoryItemBase item = null; if (DeRezAction.SaveToExistingUserInventoryItem == action) { item = new InventoryItemBase(so.RootPart.FromUserInventoryItemID, userID); item = m_Scene.InventoryService.GetItem(item); //item = userInfo.RootFolder.FindItem( // objectGroup.RootPart.FromUserInventoryItemID); if (null == item) { m_log.DebugFormat( "[INVENTORY ACCESS MODULE]: Object {0} {1} scheduled for save to inventory has already been deleted.", so.Name, so.UUID); return null; } } else { // Folder magic // if (action == DeRezAction.Delete) { // Deleting someone else's item // if (remoteClient == null || so.OwnerID != remoteClient.AgentId) { folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder); } else { folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.TrashFolder); } } else if (action == DeRezAction.Return) { // Dump to lost + found unconditionally // folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder); } if (folderID == UUID.Zero && folder == null) { if (action == DeRezAction.Delete) { // Deletes go to trash by default // folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.TrashFolder); } else { if (remoteClient == null || so.RootPart.OwnerID != remoteClient.AgentId) { // Taking copy of another person's item. Take to // Objects folder. folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.Object); so.FromFolderID = UUID.Zero; } else { // Catch all. Use lost & found // folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.LostAndFoundFolder); } } } // Override and put into where it came from, if it came // from anywhere in inventory and the owner is taking it back. // if (action == DeRezAction.Take || action == DeRezAction.TakeCopy) { if (so.FromFolderID != UUID.Zero && so.RootPart.OwnerID == remoteClient.AgentId) { InventoryFolderBase f = new InventoryFolderBase(so.FromFolderID, userID); folder = m_Scene.InventoryService.GetFolder(f); if(folder.Type == 14 || folder.Type == 16) { // folder.Type = 6; folder = m_Scene.InventoryService.GetFolderForType(userID, AssetType.Object); } } } if (folder == null) // None of the above { folder = new InventoryFolderBase(folderID); if (folder == null) // Nowhere to put it { return null; } } item = new InventoryItemBase(); item.ID = UUID.Random(); item.InvType = (int)InventoryType.Object; item.Folder = folder.ID; item.Owner = userID; } return item; } public virtual SceneObjectGroup RezObject( IClientAPI remoteClient, UUID itemID, Vector3 RayEnd, Vector3 RayStart, UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection, bool RezSelected, bool RemoveItem, UUID fromTaskID, bool attachment) { // m_log.DebugFormat("[INVENTORY ACCESS MODULE]: RezObject for {0}, item {1}", remoteClient.Name, itemID); InventoryItemBase item = new InventoryItemBase(itemID, remoteClient.AgentId); item = m_Scene.InventoryService.GetItem(item); if (item == null) { m_log.WarnFormat( "[INVENTORY ACCESS MODULE]: Could not find item {0} for {1} in RezObject()", itemID, remoteClient.Name); return null; } item.Owner = remoteClient.AgentId; return RezObject( remoteClient, item, item.AssetID, RayEnd, RayStart, RayTargetID, BypassRayCast, RayEndIsIntersection, RezSelected, RemoveItem, fromTaskID, attachment); } public virtual SceneObjectGroup RezObject( IClientAPI remoteClient, InventoryItemBase item, UUID assetID, Vector3 RayEnd, Vector3 RayStart, UUID RayTargetID, byte BypassRayCast, bool RayEndIsIntersection, bool RezSelected, bool RemoveItem, UUID fromTaskID, bool attachment) { AssetBase rezAsset = m_Scene.AssetService.Get(assetID.ToString()); if (rezAsset == null) { if (item != null) { m_log.WarnFormat( "[InventoryAccessModule]: Could not find asset {0} for item {1} {2} for {3} in RezObject()", assetID, item.Name, item.ID, remoteClient.Name); remoteClient.SendAgentAlertMessage(string.Format("Unable to rez: could not find asset {0} for item {1}.", assetID, item.Name), false); } else { m_log.WarnFormat( "[INVENTORY ACCESS MODULE]: Could not find asset {0} for {1} in RezObject()", assetID, remoteClient.Name); remoteClient.SendAgentAlertMessage(string.Format("Unable to rez: could not find asset {0}.", assetID), false); } return null; } SceneObjectGroup group = null; List<SceneObjectGroup> objlist; List<Vector3> veclist; Vector3 bbox; float offsetHeight; byte bRayEndIsIntersection = (byte)(RayEndIsIntersection ? 1 : 0); Vector3 pos; bool single = m_Scene.GetObjectsToRez( rezAsset.Data, attachment, out objlist, out veclist, out bbox, out offsetHeight); if (single) { pos = m_Scene.GetNewRezLocation( RayStart, RayEnd, RayTargetID, Quaternion.Identity, BypassRayCast, bRayEndIsIntersection, true, bbox, false); pos.Z += offsetHeight; } else { pos = m_Scene.GetNewRezLocation(RayStart, RayEnd, RayTargetID, Quaternion.Identity, BypassRayCast, bRayEndIsIntersection, true, bbox, false); pos -= bbox / 2; } if (item != null && !DoPreRezWhenFromItem(remoteClient, item, objlist, pos, veclist, attachment)) return null; for (int i = 0; i < objlist.Count; i++) { group = objlist[i]; // m_log.DebugFormat( // "[INVENTORY ACCESS MODULE]: Preparing to rez {0} {1} {2} ownermask={3:X} nextownermask={4:X} groupmask={5:X} everyonemask={6:X} for {7}", // group.Name, group.LocalId, group.UUID, // group.RootPart.OwnerMask, group.RootPart.NextOwnerMask, group.RootPart.GroupMask, group.RootPart.EveryoneMask, // remoteClient.Name); // Vector3 storedPosition = group.AbsolutePosition; if (group.UUID == UUID.Zero) { m_log.Debug("[INVENTORY ACCESS MODULE]: Object has UUID.Zero! Position 3"); } // if this was previously an attachment and is now being rezzed, // save the old attachment info. if (group.IsAttachment == false && group.RootPart.Shape.State != 0) { group.RootPart.AttachedPos = group.AbsolutePosition; group.RootPart.Shape.LastAttachPoint = (byte)group.AttachmentPoint; } if (item == null) { // Change ownership. Normally this is done in DoPreRezWhenFromItem(), but in this case we must do it here. foreach (SceneObjectPart part in group.Parts) { // Make the rezzer the owner, as this is not necessarily set correctly in the serialized asset. part.LastOwnerID = part.OwnerID; part.OwnerID = remoteClient.AgentId; } } if (!attachment) { // If it's rezzed in world, select it. Much easier to // find small items. // foreach (SceneObjectPart part in group.Parts) { part.CreateSelected = true; } } group.ResetIDs(); if (attachment) { group.RootPart.Flags |= PrimFlags.Phantom; group.IsAttachment = true; } // If we're rezzing an attachment then don't ask // AddNewSceneObject() to update the client since // we'll be doing that later on. Scheduling more than // one full update during the attachment // process causes some clients to fail to display the // attachment properly. m_Scene.AddNewSceneObject(group, !attachment, false); // if attachment we set it's asset id so object updates // can reflect that, if not, we set it's position in world. if (!attachment) { group.ScheduleGroupForFullUpdate(); group.AbsolutePosition = pos + veclist[i]; } group.SetGroup(remoteClient.ActiveGroupId, remoteClient); if (!attachment) { SceneObjectPart rootPart = group.RootPart; if (rootPart.Shape.PCode == (byte)PCode.Prim) group.ClearPartAttachmentData(); // Fire on_rez group.CreateScriptInstances(0, true, m_Scene.DefaultScriptEngine, 1); rootPart.ParentGroup.ResumeScripts(); rootPart.ScheduleFullUpdate(); } // m_log.DebugFormat( // "[INVENTORY ACCESS MODULE]: Rezzed {0} {1} {2} ownermask={3:X} nextownermask={4:X} groupmask={5:X} everyonemask={6:X} for {7}", // group.Name, group.LocalId, group.UUID, // group.RootPart.OwnerMask, group.RootPart.NextOwnerMask, group.RootPart.GroupMask, group.RootPart.EveryoneMask, // remoteClient.Name); } if (item != null) DoPostRezWhenFromItem(item, attachment); return group; } /// <summary> /// Do pre-rez processing when the object comes from an item. /// </summary> /// <param name="remoteClient"></param> /// <param name="item"></param> /// <param name="objlist"></param> /// <param name="pos"></param> /// <param name="veclist"> /// List of vector position adjustments for a coalesced objects. For ordinary objects /// this list will contain just Vector3.Zero. The order of adjustments must match the order of objlist /// </param> /// <param name="isAttachment"></param> /// <returns>true if we can processed with rezzing, false if we need to abort</returns> private bool DoPreRezWhenFromItem( IClientAPI remoteClient, InventoryItemBase item, List<SceneObjectGroup> objlist, Vector3 pos, List<Vector3> veclist, bool isAttachment) { UUID fromUserInventoryItemId = UUID.Zero; // If we have permission to copy then link the rezzed object back to the user inventory // item that it came from. This allows us to enable 'save object to inventory' if (!m_Scene.Permissions.BypassPermissions()) { if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == (uint)PermissionMask.Copy && (item.Flags & (uint)InventoryItemFlags.ObjectHasMultipleItems) == 0) { fromUserInventoryItemId = item.ID; } } else { if ((item.Flags & (uint)InventoryItemFlags.ObjectHasMultipleItems) == 0) { // Brave new fullperm world fromUserInventoryItemId = item.ID; } } for (int i = 0; i < objlist.Count; i++) { SceneObjectGroup g = objlist[i]; if (!m_Scene.Permissions.CanRezObject( g.PrimCount, remoteClient.AgentId, pos + veclist[i]) && !isAttachment) { // The client operates in no fail mode. It will // have already removed the item from the folder // if it's no copy. // Put it back if it's not an attachment // if (((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0) && (!isAttachment)) remoteClient.SendBulkUpdateInventory(item); ILandObject land = m_Scene.LandChannel.GetLandObject(pos.X, pos.Y); remoteClient.SendAlertMessage(string.Format( "Can't rez object '{0}' at <{1:F3}, {2:F3}, {3:F3}> on parcel '{4}' in region {5}.", item.Name, pos.X, pos.Y, pos.Z, land != null ? land.LandData.Name : "Unknown", m_Scene.Name)); return false; } } for (int i = 0; i < objlist.Count; i++) { SceneObjectGroup so = objlist[i]; SceneObjectPart rootPart = so.RootPart; // Since renaming the item in the inventory does not // affect the name stored in the serialization, transfer // the correct name from the inventory to the // object itself before we rez. // // Only do these for the first object if we are rezzing a coalescence. if (i == 0) { rootPart.Name = item.Name; rootPart.Description = item.Description; rootPart.ObjectSaleType = item.SaleType; rootPart.SalePrice = item.SalePrice; } so.FromFolderID = item.Folder; // m_log.DebugFormat( // "[INVENTORY ACCESS MODULE]: rootPart.OwnedID {0}, item.Owner {1}, item.CurrentPermissions {2:X}", // rootPart.OwnerID, item.Owner, item.CurrentPermissions); if ((rootPart.OwnerID != item.Owner) || (item.CurrentPermissions & SceneObjectGroup.SLAM) != 0) { //Need to kill the for sale here rootPart.ObjectSaleType = 0; rootPart.SalePrice = 10; } foreach (SceneObjectPart part in so.Parts) { part.FromUserInventoryItemID = fromUserInventoryItemId; part.ApplyPermissionsOnRez(item, true, m_Scene); } rootPart.TrimPermissions(); if (isAttachment) so.FromItemID = item.ID; } return true; } /// <summary> /// Do post-rez processing when the object comes from an item. /// </summary> /// <param name="item"></param> /// <param name="isAttachment"></param> private void DoPostRezWhenFromItem(InventoryItemBase item, bool isAttachment) { if (!m_Scene.Permissions.BypassPermissions()) { if ((item.CurrentPermissions & (uint)PermissionMask.Copy) == 0) { // If this is done on attachments, no // copy ones will be lost, so avoid it // if (!isAttachment) { List<UUID> uuids = new List<UUID>(); uuids.Add(item.ID); m_Scene.InventoryService.DeleteItems(item.Owner, uuids); } } } } protected void AddUserData(SceneObjectGroup sog) { UserManagementModule.AddUser(sog.RootPart.CreatorID, sog.RootPart.CreatorData); foreach (SceneObjectPart sop in sog.Parts) UserManagementModule.AddUser(sop.CreatorID, sop.CreatorData); } public virtual void TransferInventoryAssets(InventoryItemBase item, UUID sender, UUID receiver) { } public virtual bool CanGetAgentInventoryItem(IClientAPI remoteClient, UUID itemID, UUID requestID) { InventoryItemBase assetRequestItem = GetItem(remoteClient.AgentId, itemID); if (assetRequestItem == null) { ILibraryService lib = m_Scene.RequestModuleInterface<ILibraryService>(); if (lib != null) assetRequestItem = lib.LibraryRootFolder.FindItem(itemID); if (assetRequestItem == null) return false; } // At this point, we need to apply perms // only to notecards and scripts. All // other asset types are always available // if (assetRequestItem.AssetType == (int)AssetType.LSLText) { if (!m_Scene.Permissions.CanViewScript(itemID, UUID.Zero, remoteClient.AgentId)) { remoteClient.SendAgentAlertMessage("Insufficient permissions to view script", false); return false; } } else if (assetRequestItem.AssetType == (int)AssetType.Notecard) { if (!m_Scene.Permissions.CanViewNotecard(itemID, UUID.Zero, remoteClient.AgentId)) { remoteClient.SendAgentAlertMessage("Insufficient permissions to view notecard", false); return false; } } if (assetRequestItem.AssetID != requestID) { m_log.WarnFormat( "[INVENTORY ACCESS MODULE]: {0} requested asset {1} from item {2} but this does not match item's asset {3}", Name, requestID, itemID, assetRequestItem.AssetID); return false; } return true; } public virtual bool IsForeignUser(UUID userID, out string assetServerURL) { assetServerURL = string.Empty; return false; } #endregion #region Misc /// <summary> /// Create a new asset data structure. /// </summary> /// <param name="name"></param> /// <param name="description"></param> /// <param name="invType"></param> /// <param name="assetType"></param> /// <param name="data"></param> /// <returns></returns> private AssetBase CreateAsset(string name, string description, sbyte assetType, byte[] data, string creatorID) { AssetBase asset = new AssetBase(UUID.Random(), name, assetType, creatorID); asset.Description = description; asset.Data = (data == null) ? new byte[1] : data; return asset; } protected virtual InventoryItemBase GetItem(UUID agentID, UUID itemID) { IInventoryService invService = m_Scene.RequestModuleInterface<IInventoryService>(); InventoryItemBase item = new InventoryItemBase(itemID, agentID); item = invService.GetItem(item); if (item != null && item.CreatorData != null && item.CreatorData != string.Empty) UserManagementModule.AddUser(item.CreatorIdAsUuid, item.CreatorData); return item; } #endregion } }
/* * Copyright 2004,2006 The Poderosa Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * $Id: TelnetSSHPlugin.cs,v 1.4 2011/10/27 23:21:59 kzmi Exp $ */ using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Diagnostics; using Poderosa.Plugins; using Poderosa.Commands; using Poderosa.Terminal; using Poderosa.ConnectionParam; using Poderosa.Protocols; using Poderosa.Forms; using Poderosa.MacroEngine; [assembly: PluginDeclaration(typeof(Poderosa.Sessions.TelnetSSHPlugin))] namespace Poderosa.Sessions { [PluginInfo(ID = "org.poderosa.telnet_ssh", Version = VersionInfo.PODEROSA_VERSION, Author = VersionInfo.PROJECT_NAME, Dependencies = "org.poderosa.core.window")] internal class TelnetSSHPlugin : PluginBase { private static TelnetSSHPlugin _instance; private ICommandManager _commandManager; private LoginDialogCommand _loginDialogCommand; private LoginMenuGroup _loginMenuGroup; private LoginToolBarComponent _loginToolBarComponent; private IMacroEngine _macroEngine; public static TelnetSSHPlugin Instance { get { return _instance; } } public override void InitializePlugin(IPoderosaWorld poderosa) { base.InitializePlugin(poderosa); _instance = this; IPluginManager pm = poderosa.PluginManager; _commandManager = (ICommandManager)pm.FindPlugin("org.poderosa.core.commands", typeof(ICommandManager)); _loginDialogCommand = new LoginDialogCommand(); _commandManager.Register(_loginDialogCommand); IExtensionPoint ep = pm.FindExtensionPoint("org.poderosa.menu.file"); _loginMenuGroup = new LoginMenuGroup(); ep.RegisterExtension(_loginMenuGroup); IExtensionPoint toolbar = pm.FindExtensionPoint("org.poderosa.core.window.toolbar"); _loginToolBarComponent = new LoginToolBarComponent(); toolbar.RegisterExtension(_loginToolBarComponent); } public IPoderosaMenuGroup TelnetSSHMenuGroup { get { return _loginMenuGroup; } } public IToolBarComponent TelnetSSHToolBar { get { return _loginToolBarComponent; } } public IMacroEngine MacroEngine { get { if (_macroEngine == null) { _macroEngine = _poderosaWorld.PluginManager.FindPlugin("org.poderosa.macro", typeof(IMacroEngine)) as IMacroEngine; } return _macroEngine; } } private class LoginMenuGroup : IPoderosaMenuGroup, IPositionDesignation { public IPoderosaMenu[] ChildMenus { get { return new IPoderosaMenu[] { new LoginMenuItem() }; } } public bool IsVolatileContent { get { return false; } } public bool ShowSeparator { get { return true; } } public IAdaptable GetAdapter(Type adapter) { return _instance.PoderosaWorld.AdapterManager.GetAdapter(this, adapter); } public IAdaptable DesignationTarget { get { return null; } } public PositionType DesignationPosition { get { return PositionType.First; } } } private class LoginMenuItem : IPoderosaMenuItem { public IPoderosaCommand AssociatedCommand { get { return _instance._loginDialogCommand; } } public string Text { get { return TEnv.Strings.GetString("Menu.NewConnection"); } } public bool IsEnabled(ICommandTarget target) { return true; } public bool IsChecked(ICommandTarget target) { return false; } public IAdaptable GetAdapter(Type adapter) { return _instance.PoderosaWorld.AdapterManager.GetAdapter(this, adapter); } } private class LoginToolBarComponent : IToolBarComponent, IPositionDesignation { public IAdaptable DesignationTarget { get { return null; } } public PositionType DesignationPosition { get { return PositionType.First; } } public bool ShowSeparator { get { return true; } } public IToolBarElement[] ToolBarElements { get { return new IToolBarElement[] { new ToolBarCommandButtonImpl(_instance._loginDialogCommand, Poderosa.TerminalSession.Properties.Resources.NewConnection16x16) }; } } public IAdaptable GetAdapter(Type adapter) { return _instance.PoderosaWorld.AdapterManager.GetAdapter(this, adapter); } } private class LoginDialogCommand : IGeneralCommand { public CommandResult InternalExecute(ICommandTarget target, params IAdaptable[] args) { IPoderosaMainWindow window = (IPoderosaMainWindow)target.GetAdapter(typeof(IPoderosaMainWindow)); if (window == null) return CommandResult.Ignored; TelnetSSHLoginDialog dlg = new TelnetSSHLoginDialog(window); dlg.ApplyParam(); CommandResult res = CommandResult.Cancelled; if (dlg.ShowDialog() == DialogResult.OK) { ITerminalConnection con = dlg.Result; if (con != null) { ISessionManager sm = (ISessionManager)TelnetSSHPlugin.Instance.PoderosaWorld.PluginManager.FindPlugin("org.poderosa.core.sessions", typeof(ISessionManager)); TerminalSession ts = new TerminalSession(con, dlg.TerminalSettings); sm.StartNewSession(ts, (IPoderosaView)dlg.TargetView.GetAdapter(typeof(IPoderosaView))); sm.ActivateDocument(ts.Terminal.IDocument, ActivateReason.InternalAction); IAutoExecMacroParameter autoExecParam = con.Destination.GetAdapter(typeof(IAutoExecMacroParameter)) as IAutoExecMacroParameter; if (autoExecParam != null && autoExecParam.AutoExecMacroPath != null && TelnetSSHPlugin.Instance.MacroEngine != null) { TelnetSSHPlugin.Instance.MacroEngine.RunMacro(autoExecParam.AutoExecMacroPath, ts); } return CommandResult.Succeeded; } } dlg.Dispose(); return res; } public string CommandID { get { return "org.poderosa.session.telnetSSH"; } } public Keys DefaultShortcutKey { get { return Keys.Alt | Keys.N; } } public string Description { get { return TEnv.Strings.GetString("Command.TelnetSSH"); } } public ICommandCategory CommandCategory { get { return ConnectCommandCategory._instance; } } public bool CanExecute(ICommandTarget target) { return true; } public IAdaptable GetAdapter(Type adapter) { return _instance.PoderosaWorld.AdapterManager.GetAdapter(this, adapter); } } } }
/* FluorineFx open source library Copyright (C) 2007 Zoltan Csibi, [email protected], 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.IO; using log4net; using FluorineFx.Collections; using FluorineFx.Configuration; using FluorineFx.IO; using FluorineFx.Messaging.Api; using FluorineFx.Messaging.Api.SO; using FluorineFx.Messaging.Api.Service; using FluorineFx.Messaging.Api.Stream; using FluorineFx.Messaging.Rtmp; using FluorineFx.Messaging.Rtmp.Stream; using FluorineFx.Messaging.Rtmp.IO; using FluorineFx.Messaging.Server; using FluorineFx.Exceptions; using FluorineFx.Util; using FluorineFx.Context; namespace FluorineFx.Messaging.Adapter { /// <summary> /// <para> /// ApplicationAdapter class serves as a base class for your applications. /// It provides methods to work with SharedObjects and streams, as well as /// connections and scheduling services. /// </para> /// <para> /// ApplicationAdapter is an application level IScope. To handle streaming /// processes in your application you should implement /// IStreamAwareScopeHandler interface and implement handling methods. /// </para> /// <para> /// Application adapter provides you with useful event handlers that can be used to intercept streams, /// authorize users, etc. Also, all methods added in subclasses can be called from client side with NetConnection.call /// method. /// </para> /// If you want to build a server-side framework this is a place to start and wrap it around ApplicationAdapter subclass. /// </summary> /// <example> /// <para>Calling a method added to an ApplicationAdapter subclass</para> /// <code lang="Actionscript"> /// var nc:NetConnection = new NetConnection(); /// nc.connect(...); /// nc.call("serverHelloMsg", resultObject, "my message"); /// </code> /// <code lang="CS"> /// public class HelloWorldApplication : ApplicationAdapter /// { /// public string serverHelloMsg(string helloStr) /// { /// return "Hello, " + helloStr + "!"; /// } /// } /// </code> /// </example> [CLSCompliant(false)] public class ApplicationAdapter : StatefulScopeWrappingAdapter, ISharedObjectService, ISharedObjectSecurityService, IStreamSecurityService { private static readonly ILog log = LogManager.GetLogger(typeof(ApplicationAdapter)); /// <summary> /// List of IApplication listeners. /// </summary> private ArrayList _listeners = new ArrayList(); /// <summary> /// List of handlers that protect shared objects. /// </summary> private CopyOnWriteArray _sharedObjectSecurityHandlers = new CopyOnWriteArray(); /// <summary> /// List of handlers that protect stream publishing. /// </summary> private CopyOnWriteArray _publishSecurityHandlers = new CopyOnWriteArray(); /// <summary> /// List of handlers that protect stream playback. /// </summary> private CopyOnWriteArray _playbackSecurityHandlers = new CopyOnWriteArray(); /// <summary> /// Initializes a new instance of the ApplicationAdapter class. /// </summary> public ApplicationAdapter() { } /// <summary> /// Starts scope. Scope can be both application or room level. /// </summary> /// <param name="scope">Scope object.</param> /// <returns>true if scope can be started, false otherwise.</returns> public override bool Start(IScope scope) { if(!base.Start(scope)) return false; if(ScopeUtils.IsApplication(scope)) return AppStart(scope); else if (ScopeUtils.IsRoom(scope)) return RoomStart(scope); else return false; } /// <summary> /// Stops scope handling (that is, stops application if given scope is app /// level scope and stops room handling if given scope has lower scope level). /// </summary> /// <param name="scope">Scope to stop.</param> public override void Stop(IScope scope) { if(ScopeUtils.IsApplication(scope)) AppStop(scope); else if (ScopeUtils.IsRoom(scope)) RoomStop(scope); base.Stop(scope); } /// <summary> /// Adds client to scope. Scope can be both application or room. Can be /// applied to both application scope and scopes of lower level. /// </summary> /// <param name="client">Client object.</param> /// <param name="scope">Scope object.</param> /// <returns>true to allow, false to deny join.</returns> public override bool Join(IClient client, IScope scope) { if(!base.Join(client, scope)) return false; if(ScopeUtils.IsApplication(scope)) return AppJoin(client, scope); else if (ScopeUtils.IsRoom(scope)) return RoomJoin(client, scope); else return false; } /// <summary> /// Disconnects client from scope. Can be applied to both application scope /// and scopes of lower level. /// </summary> /// <param name="client">Client object.</param> /// <param name="scope">Scope object.</param> public override void Leave(IClient client, IScope scope) { if (ScopeUtils.IsApplication(scope)) AppLeave(client, scope); else if (ScopeUtils.IsRoom(scope)) RoomLeave(client, scope); base.Leave(client, scope); } /// <summary> /// Register listener that will get notified about application events. Please /// note that return values (e.g. from IApplication.AppStart(IScope)) /// will be ignored for listeners. /// </summary> /// <param name="listener">Application listener.</param> public void AddListener(IApplication listener) { _listeners.Add(listener); } /// <summary> /// Unregister handler that will not get notified about application events /// any longer. /// </summary> /// <param name="listener">Application listener.</param> public void RemoveListener(IApplication listener) { _listeners.Remove(listener); } /// <summary> /// Rejects the currently connecting client without a special error message. /// </summary> protected void RejectClient() { throw new ClientRejectedException(null); } /// <summary> /// Rejects the currently connecting client with the specified reason. /// </summary> /// <param name="reason">Reason object.</param> protected void RejectClient(object reason) { throw new ClientRejectedException(reason); } /// <summary> /// Returns connection result for given scope and parameters. /// Whether the scope is room or application level scope, this method distinguishes it and acts accordingly. /// </summary> /// <param name="connection">Connection object.</param> /// <param name="scope">Scope object.</param> /// <param name="parameters">List of params passed to connection handler.</param> /// <returns>true if connect is successful, false otherwise.</returns> public override bool Connect(IConnection connection, IScope scope, object[] parameters) { if( !base.Connect (connection, scope, parameters) ) return false; bool success = false; if(ScopeUtils.IsApplication(scope)) { success = AppConnect(connection, parameters); } else if (ScopeUtils.IsRoom(scope)) { success = RoomConnect(connection, parameters); } return success; } /// <summary> /// Returns disconnection result for given scope and parameters. /// Whether the scope is room or application level scope, this method distinguishes it and acts accordingly. /// </summary> /// <param name="connection">Connection object.</param> /// <param name="scope">true if disconnect is successful, false otherwise.</param> public override void Disconnect(IConnection connection, IScope scope) { if (ScopeUtils.IsApplication(scope)) { AppDisconnect(connection); } else if (ScopeUtils.IsRoom(scope)) { RoomDisconnect(connection); } base.Disconnect(connection, scope); } /// <summary> /// Handler method. Called every time new client connects (that is, new IConnection object is created after call from a SWF movie) to the application. /// /// You override this method to pass additional data from client to server application using <code>NetConnection.connect</code> method. /// </summary> /// <param name="connection">Connection object.</param> /// <param name="parameters">List of parameters after connection URL passed to <code>NetConnection.connect</code> method.</param> /// <returns>true if connect is successful, false otherwise.</returns> /// <example> /// <p><strong>Client-side:</strong><br /> /// <code>NetConnection.connect("rtmp://localhost/app", "silver");</code></p> /// /// <p><strong>Server-side:</strong><br /> /// <code>if (parameters.Length > 0) Trace.WriteLine("Theme selected: " + parameters[0]);</code></p> /// </example> public virtual bool AppConnect(IConnection connection, Object[] parameters) { log.Debug(__Res.GetString(__Res.AppAdapter_AppConnect, connection.ToString())); foreach(IApplication listener in _listeners) { listener.OnAppConnect(connection, parameters); } return true; } /// <summary> /// Handler method. Called every time client disconnects from the application. /// </summary> /// <param name="connection">Disconnected connection object.</param> public virtual void AppDisconnect(IConnection connection) { log.Debug(__Res.GetString(__Res.AppAdapter_AppDisconnect, connection.ToString())); foreach(IApplication listener in _listeners) { listener.OnAppDisconnect(connection); } } /// <summary> /// Handler method. Called every time new client connects (that is, new IConnection object is created after call from a SWF movie) to the application. /// /// You override this method to pass additional data from client to server application using <c>NetConnection.connect</c> method. /// </summary> /// <param name="connection">Connection object.</param> /// <param name="parameters">List of paramaters passed to room scope.</param> /// <returns>true if connect is successful, false otherwise.</returns> public virtual bool RoomConnect(IConnection connection, Object[] parameters) { log.Debug(__Res.GetString(__Res.AppAdapter_RoomConnect, connection.ToString())); foreach(IApplication listener in _listeners) { listener.OnRoomConnect(connection, parameters); } return true; } /// <summary> /// Handler method. Called every time client disconnects from the application. /// </summary> /// <param name="connection">Disconnected connection object.</param> public virtual void RoomDisconnect(IConnection connection) { log.Debug(__Res.GetString(__Res.AppAdapter_RoomDisconnect, connection.ToString())); foreach(IApplication listener in _listeners) { listener.OnRoomDisconnect(connection); } } /// <summary> /// Handler method. Called when an application scope is started. /// </summary> /// <param name="application">Application scope.</param> /// <returns>true if started successful, false otherwise.</returns> public virtual bool AppStart(IScope application) { log.Debug(__Res.GetString(__Res.AppAdapter_AppStart, application.ToString())); foreach(IApplication listener in _listeners) { listener.OnAppStart(application); } return true; } /// <summary> /// Handler method. Called when a room scope is started. /// </summary> /// <param name="room">Room scope.</param> /// <returns>true if started successful, false otherwise.</returns> public virtual bool RoomStart(IScope room) { log.Debug(__Res.GetString(__Res.AppAdapter_RoomStart, room.ToString())); foreach(IApplication listener in _listeners) { listener.OnRoomStart(room); } return true; } /// <summary> /// Handler method. Called when an application scope is stopped. /// </summary> /// <param name="application">Application scope.</param> public virtual void AppStop(IScope application) { log.Debug(__Res.GetString(__Res.AppAdapter_AppStop, application.ToString())); foreach(IApplication listener in _listeners) { listener.OnAppStop(application); } } /// <summary> /// Handler method. Called when a room scope is stopped. /// </summary> /// <param name="room">Room scope.</param> public virtual void RoomStop(IScope room) { log.Debug(__Res.GetString(__Res.AppAdapter_RoomStop, room.ToString())); foreach(IApplication listener in _listeners) { listener.OnRoomStop(room); } } /// <summary> /// Handler method. Called every time client joins application scope. /// </summary> /// <param name="client">Client object.</param> /// <param name="application">Application scope.</param> /// <returns>true if join is successful, false otherwise.</returns> public virtual bool AppJoin(IClient client, IScope application) { log.Debug(__Res.GetString(__Res.AppAdapter_AppJoin, client.ToString(), application.ToString())); foreach(IApplication listener in _listeners) { listener.OnAppJoin(client, application); } return true; } /// <summary> /// Handler method. Called every time client leaves application scope. /// </summary> /// <param name="client">Client object that left.</param> /// <param name="application">Application scope.</param> public virtual void AppLeave(IClient client, IScope application) { log.Debug(__Res.GetString(__Res.AppAdapter_AppLeave, client.ToString(), application.ToString())); foreach(IApplication listener in _listeners) { listener.OnAppLeave(client, application); } } /// <summary> /// Handler method. Called every time client joins room scope. /// </summary> /// <param name="client">Client object.</param> /// <param name="room">Room scope.</param> /// <returns>true if join is successful, false otherwise.</returns> public virtual bool RoomJoin(IClient client, IScope room) { log.Debug(__Res.GetString(__Res.AppAdapter_RoomJoin, client.ToString(), room.ToString())); foreach(IApplication listener in _listeners) { listener.OnRoomJoin(client, room); } return true; } /// <summary> /// Handler method. Called every time client leaves room scope. /// </summary> /// <param name="client">Client object that left.</param> /// <param name="room">Room scope.</param> public virtual void RoomLeave(IClient client, IScope room) { log.Debug(__Res.GetString(__Res.AppAdapter_RoomLeave, client.ToString(), room.ToString())); foreach(IApplication listener in _listeners) { listener.OnRoomLeave(client, room); } } #region ISharedObjectService Members /// <summary> /// Returns a collection of available SharedObject names. /// </summary> /// <param name="scope">Scope that SharedObjects belong to.</param> /// <returns>Collection of available SharedObject names.</returns> public ICollection GetSharedObjectNames(IScope scope) { ISharedObjectService service = (ISharedObjectService)ScopeUtils.GetScopeService(scope, typeof(ISharedObjectService)); return service.GetSharedObjectNames(scope); } /// <summary> /// Creates a new shared object for given scope. Server-side shared objects /// (also known as Remote SO) are special kind of objects synchronized between clients. /// <para> /// To get an instance of RSO at client-side, use <c>SharedObject.getRemote()</c>. /// </para> /// SharedObjects can be persistent and transient. Persistent RSO are stateful, i.e. store their data between sessions. /// If you need to store some data on server while clients go back and forth use persistent SO, otherwise perfer usage of transient for /// extra performance. /// </summary> /// <param name="scope">Scope that shared object belongs to.</param> /// <param name="name">Name of SharedObject.</param> /// <param name="persistent">Whether SharedObject instance should be persistent or not.</param> /// <returns>true if SO was created, false otherwise.</returns> public bool CreateSharedObject(IScope scope, string name, bool persistent) { ISharedObjectService service = (ISharedObjectService)ScopeUtils.GetScopeService(scope, typeof(ISharedObjectService)); return service.CreateSharedObject(scope, name, persistent); } /// <summary> /// Returns shared object from given scope by name. /// </summary> /// <param name="scope">Scope that shared object belongs to.</param> /// <param name="name">Name of SharedObject.</param> /// <returns>Shared object instance with the specifed name.</returns> public ISharedObject GetSharedObject(IScope scope, string name) { ISharedObjectService service = (ISharedObjectService)ScopeUtils.GetScopeService(scope, typeof(ISharedObjectService)); return service.GetSharedObject(scope, name); } /// <summary> /// Returns shared object from given scope by name. /// </summary> /// <param name="scope">Scope that shared object belongs to.</param> /// <param name="name">Name of SharedObject.</param> /// <param name="persistent">Whether SharedObject instance should be persistent or not.</param> /// <returns>Shared object instance with the specifed name.</returns> public ISharedObject GetSharedObject(IScope scope, string name, bool persistent) { ISharedObjectService service = (ISharedObjectService)ScopeUtils.GetScopeService(scope, typeof(ISharedObjectService)); return service.GetSharedObject(scope, name, persistent); } /// <summary> /// Checks whether there is a SharedObject with given scope and name. /// </summary> /// <param name="scope">Scope that shared object belongs to.</param> /// <param name="name">Name of SharedObject.</param> /// <returns>true if SharedObject exists, false otherwise.</returns> public bool HasSharedObject(IScope scope, string name) { ISharedObjectService service = (ISharedObjectService)ScopeUtils.GetScopeService(scope, typeof(ISharedObjectService)); return service.HasSharedObject(scope, name); } /// <summary> /// <para> /// Deletes persistent shared objects specified by name and clears all /// properties from active shared objects (persistent and nonpersistent). The /// name parameter specifies the name of a shared object, which can include a /// slash (/) as a delimiter between directories in the path. The last /// element in the path can contain wildcard patterns (for example, a /// question mark [?] and an asterisk [*]) or a shared object name. The /// ClearSharedObjects() method traverses the shared object hierarchy along /// the specified path and clears all the shared objects. Specifying a slash /// (/) clears all the shared objects associated with an application /// instance. /// </para> /// The following values are possible for the soPath parameter: /// <list type="table"> /// <listheader> /// <term>soPath parameter</term> /// <description>action</description> /// </listheader> /// <item><term></term> /// <description>clears all local and persistent shared objects associated with the instance</description></item> /// <item><term>/foo/bar</term> /// <description>clears the shared object /foo/bar; if bar is a directory name, no shared objects are deleted</description></item> /// <item><term>/foo/bar/*</term> /// <description>clears all shared objects stored under the instance directory</description></item> /// <item><term>/foo/bar.</term> /// <description>the bar directory is also deleted if no persistent shared objects are in use within this namespace</description></item> /// <item><term>/foo/bar/XX??</term> /// <description>clears all shared objects that begin with XX, followed by any two characters</description></item> /// </list> /// If a directory name matches this specification, all the shared objects within this directory are cleared. /// /// If you call the ClearSharedObjects() method and the specified path /// matches a shared object that is currently active, all its properties are /// deleted, and a "clear" event is sent to all subscribers of the shared /// object. If it is a persistent shared object, the persistent store is also cleared. /// </summary> /// <param name="scope">Scope that shared object belongs to.</param> /// <param name="name">Name of SharedObject.</param> /// <returns>true if successful, false otherwise.</returns> public bool ClearSharedObjects(IScope scope, string name) { ISharedObjectService service = (ISharedObjectService)ScopeUtils.GetScopeService(scope, typeof(ISharedObjectService)); return service.ClearSharedObjects(scope, name); } /// <summary> /// Start service. /// </summary> /// <param name="configuration">Application configuration.</param> public void Start(ConfigurationSection configuration) { } /// <summary> /// Shutdown service. /// </summary> public void Shutdown() { } #endregion #region ISharedObjectSecurityService Members /// <summary> /// Adds handler that protects shared objects. /// </summary> /// <param name="handler">The ISharedObjectSecurity handler.</param> public void RegisterSharedObjectSecurity(ISharedObjectSecurity handler) { _sharedObjectSecurityHandlers.Add(handler); } /// <summary> /// Removes handler that protects shared objects. /// </summary> /// <param name="handler">The ISharedObjectSecurity handler.</param> public void UnregisterSharedObjectSecurity(ISharedObjectSecurity handler) { _sharedObjectSecurityHandlers.Remove(handler); } /// <summary> /// Gets the collection of security handlers that protect shared objects. /// </summary> /// <returns>Enumerator of ISharedObjectSecurity handlers.</returns> public IEnumerator GetSharedObjectSecurity() { return _sharedObjectSecurityHandlers.GetEnumerator(); } #endregion #region IStreamSecurityService Members /// <summary> /// Add handler that protects stream publishing. /// </summary> /// <param name="handler">Handler to add.</param> public void RegisterStreamPublishSecurity(IStreamPublishSecurity handler) { _publishSecurityHandlers.Add(handler); } /// <summary> /// Remove handler that protects stream publishing. /// </summary> /// <param name="handler">Handler to remove.</param> public void UnregisterStreamPublishSecurity(IStreamPublishSecurity handler) { _publishSecurityHandlers.Remove(handler); } /// <summary> /// Returns handlers that protect stream publishing. /// </summary> /// <returns>Enumerator of handlers.</returns> public IEnumerator GetStreamPublishSecurity() { return _publishSecurityHandlers.GetEnumerator(); } /// <summary> /// Add handler that protects stream playback. /// </summary> /// <param name="handler">Handler to add.</param> public void RegisterStreamPlaybackSecurity(IStreamPlaybackSecurity handler) { _playbackSecurityHandlers.Add(handler); } /// <summary> /// Remove handler that protects stream playback. /// </summary> /// <param name="handler">Handler to remove.</param> public void UnregisterStreamPlaybackSecurity(IStreamPlaybackSecurity handler) { _playbackSecurityHandlers.Remove(handler); } /// <summary> /// Returns handlers that protect stream plaback. /// </summary> /// <returns>Enumerator of handlers.</returns> public IEnumerator GetStreamPlaybackSecurity() { return _playbackSecurityHandlers.GetEnumerator(); } #endregion /// <summary> /// Returns list of stream names broadcasted in scope. Broadcast stream name is somewhat different /// from server stream name. Server stream name is just an ID assigned to every created stream. Broadcast stream name /// is the name that is being used to subscribe to the stream at client side, that is, in <c>NetStream.play</c> call. /// </summary> /// <param name="scope">Scope to retrieve broadcasted stream names.</param> /// <returns>List of broadcasted stream names.</returns> public IEnumerator GetBroadcastStreamNames(IScope scope) { IProviderService service = ScopeUtils.GetScopeService(scope, typeof(IProviderService)) as IProviderService; return service.GetBroadcastStreamNames(scope); } /// <summary> /// Invoke clients with parameters and callback. /// </summary> /// <param name="method">Method name.</param> /// <param name="arguments">Invocation parameters passed to the method.</param> /// <param name="callback">Callback used to handle return values.</param> protected void InvokeClients(string method, object[] arguments, IPendingServiceCallback callback) { InvokeClients(method, arguments, callback, false); } /// <summary> /// Invoke clients with parameters and callback. /// </summary> /// <param name="method">Method name.</param> /// <param name="arguments">Invocation parameters passed to the method.</param> /// <param name="callback">Callback used to handle return values.</param> /// <param name="ignoreSelf">Current client shoud be ignored.</param> protected void InvokeClients(string method, object[] arguments, IPendingServiceCallback callback, bool ignoreSelf) { InvokeClients(method, arguments, callback, ignoreSelf, this.Scope); } /// <summary> /// Invoke clients with parameters and callback. /// </summary> /// <param name="method">Method name.</param> /// <param name="arguments">Invocation parameters passed to the method.</param> /// <param name="callback">Callback used to handle return values.</param> /// <param name="ignoreSelf">Current client shoud be ignored.</param> /// <param name="targetScope">Invoke clients subscribed to the specified Scope.</param> protected void InvokeClients(string method, object[] arguments, IPendingServiceCallback callback, bool ignoreSelf, IScope targetScope) { try { if (log.IsDebugEnabled) log.Debug(string.Format("Invoke clients: {0}", method)); IServiceCapableConnection connection = FluorineFx.Context.FluorineContext.Current.Connection as IServiceCapableConnection; IEnumerator collections = targetScope.GetConnections(); while (collections.MoveNext()) { IConnection connectionTmp = collections.Current as IConnection; if (!connectionTmp.Scope.Name.Equals(targetScope.Name)) continue; if ((connectionTmp is IServiceCapableConnection) && (!ignoreSelf || connectionTmp != connection)) (connectionTmp as IServiceCapableConnection).Invoke(method, arguments, callback); } } catch (Exception ex) { if (log.IsErrorEnabled) log.Error("InvokeClients failed", ex); throw; } finally { if (log.IsDebugEnabled) log.Debug(string.Format("Finished invoking clients ({0})", method)); } } /// <summary> /// Begins an asynchronous operation to invoke clients with parameters and callback. /// </summary> /// <param name="asyncCallback">The AsyncCallback delegate.</param> /// <param name="method">Method name.</param> /// <param name="arguments">Invocation parameters passed to the method.</param> /// <param name="callback">Callback used to handle return values.</param> /// <returns>An IAsyncResult that references the asynchronous invocation.</returns> /// <remarks> /// <para> /// The <i>asyncCallback</i> delegate identifies the callback invoked when the messages are sent, the <i>callback</i> object identifies the callback handling client responses. /// </para> /// <para> /// You can create a callback method that implements the AsyncCallback delegate and pass its name to the BeginInvokeClients method. /// </para> /// <para> /// Your callback method should invoke the EndInvokeClients method. When your application calls BeginInvokeClients, the system will use a separate thread to execute the specified callback method, and will block on EndInvokeClients until the clients are invoked successfully or throws an exception. /// </para> /// </remarks> protected IAsyncResult BeginInvokeClients(AsyncCallback asyncCallback, string method, object[] arguments, IPendingServiceCallback callback) { return BeginInvokeClients(asyncCallback, method, arguments, callback, false); } /// <summary> /// Begins an asynchronous operation to invoke clients with parameters and callback. /// </summary> /// <param name="asyncCallback">The AsyncCallback delegate.</param> /// <param name="method">Method name.</param> /// <param name="arguments">Invocation parameters passed to the method.</param> /// <param name="callback">Callback used to handle return values.</param> /// <param name="ignoreSelf">Current client shoud be ignored.</param> /// <returns>An IAsyncResult that references the asynchronous invocation.</returns> /// <remarks> /// <para> /// The <i>asyncCallback</i> delegate identifies the callback invoked when the messages are sent, the <i>callback</i> object identifies the callback handling client responses. /// </para> /// <para> /// You can create a callback method that implements the AsyncCallback delegate and pass its name to the BeginInvokeClients method. /// </para> /// <para> /// Your callback method should invoke the EndInvokeClients method. When your application calls BeginInvokeClients, the system will use a separate thread to execute the specified callback method, and will block on EndInvokeClients until the clients are invoked successfully or throws an exception. /// </para> /// </remarks> protected IAsyncResult BeginInvokeClients(AsyncCallback asyncCallback, string method, object[] arguments, IPendingServiceCallback callback, bool ignoreSelf) { return BeginInvokeClients(asyncCallback, method, arguments, callback, ignoreSelf, this.Scope); } /// <summary> /// Begins an asynchronous operation to invoke clients with parameters and callback. /// </summary> /// <param name="asyncCallback">The AsyncCallback delegate.</param> /// <param name="method">Method name.</param> /// <param name="arguments">Invocation parameters passed to the method.</param> /// <param name="callback">Callback used to handle return values.</param> /// <param name="ignoreSelf">Current client shoud be ignored.</param> /// <param name="targetScope">Invoke clients subscribed to the specified Scope.</param> /// <returns>An IAsyncResult that references the asynchronous invocation.</returns> /// <remarks> /// <para> /// The <i>asyncCallback</i> delegate identifies the callback invoked when the messages are sent, the <i>callback</i> object identifies the callback handling client responses. /// </para> /// <para> /// You can create a callback method that implements the AsyncCallback delegate and pass its name to the BeginInvokeClients method. /// </para> /// <para> /// Your callback method should invoke the EndInvokeClients method. When your application calls BeginInvokeClients, the system will use a separate thread to execute the specified callback method, and will block on EndInvokeClients until the clients are invoked successfully or throws an exception. /// </para> /// </remarks> protected IAsyncResult BeginInvokeClients(AsyncCallback asyncCallback, string method, object[] arguments, IPendingServiceCallback callback, bool ignoreSelf, IScope targetScope) { // Create IAsyncResult object identifying the asynchronous operation AsyncResultNoResult ar = new AsyncResultNoResult(asyncCallback, new InvokeData(FluorineContext.Current, method, arguments, callback, ignoreSelf, targetScope)); // Use a thread pool thread to perform the operation FluorineFx.Threading.ThreadPoolEx.Global.QueueUserWorkItem(new System.Threading.WaitCallback(OnBeginInvokeClients), ar); // Return the IAsyncResult to the caller return ar; } private void OnBeginInvokeClients(object asyncResult) { AsyncResultNoResult ar = asyncResult as AsyncResultNoResult; try { // Perform the operation; if sucessful set the result InvokeData invokeData = ar.AsyncState as InvokeData; //Restore context FluorineWebSafeCallContext.SetData(FluorineContext.FluorineContextKey, invokeData.Context); InvokeClients(invokeData.Method, invokeData.Arguments, invokeData.Callback, invokeData.IgnoreSelf, invokeData.TargetScope); ar.SetAsCompleted(null, false); } catch (Exception ex) { // If operation fails, set the exception ar.SetAsCompleted(ex, false); } finally { FluorineWebSafeCallContext.FreeNamedDataSlot(FluorineContext.FluorineContextKey); } } /// <summary> /// Ends a pending asynchronous client invocation. /// </summary> /// <param name="asyncResult">An IAsyncResult that stores state information and any user defined data for this asynchronous operation.</param> /// <remarks> /// <para> /// EndInvokeClients is a blocking method that completes the asynchronous client invocation request started in the BeginInvokeClients method. /// </para> /// <para> /// Before calling BeginInvokeClients, you can create a callback method that implements the AsyncCallback delegate. This callback method executes in a separate thread and is called by the system after BeginInvokeClients returns. /// The callback method must accept the IAsyncResult returned by the BeginInvokeClients method as a parameter. /// </para> /// <para>Within the callback method you can call the EndInvokeClients method to successfully complete the invocation attempt.</para> /// <para>The BeginInvokeClients enables to use the fire and forget pattern too (by not implementing an AsyncCallback delegate), however if the invocation fails the EndInvokeClients method is responsible to throw an appropriate exception. /// Implementing the callback and calling EndInvokeClients also allows early garbage collection of the internal objects used in the asynchronous call.</para> /// </remarks> public void EndInvokeClients(IAsyncResult asyncResult) { AsyncResultNoResult ar = asyncResult as AsyncResultNoResult; // Wait for operation to complete, then return result or throw exception ar.EndInvoke(); } /// <summary> /// Start a bandwidth check. /// </summary> protected virtual void CalculateClientBw() { CalculateClientBw(FluorineFx.Context.FluorineContext.Current.Connection); } /// <summary> /// Start a bandwidth check. /// </summary> /// <param name="client">Connection object.</param> protected virtual void CalculateClientBw(IConnection client) { new BWCheck(client).CalculateClientBw(); } /// <summary> /// Returns stream length. Method added to get flv player to work. /// </summary> /// <param name="name">Stream name.</param> /// <returns>Returns the length of a stream, in seconds.</returns> public double getStreamLength(string name) { double duration = 0; IProviderService provider = ScopeUtils.GetScopeService(this.Scope, typeof(IProviderService)) as IProviderService; FileInfo file = provider.GetVODProviderFile(this.Scope, name); if (file != null) { IStreamableFileFactory factory = (IStreamableFileFactory)ScopeUtils.GetScopeService(this.Scope, typeof(IStreamableFileFactory)) as IStreamableFileFactory; IStreamableFileService service = factory.GetService(file); if (service != null) { ITagReader reader = null; try { IStreamableFile streamFile = service.GetStreamableFile(file); reader = streamFile.GetReader(); duration = (double)reader.Duration / 1000; } catch (IOException ex) { if (log.IsErrorEnabled) log.Error(string.Format("Error reading stream file {0}. {1}", file.FullName, ex.Message)); } finally { if (reader != null) reader.Close(); } } else { if (log.IsErrorEnabled) log.Error(string.Format("No service found for {0}", file.FullName)); } file = null; } return duration; } } }
#define __Morph using clrcore; using System.Text; namespace Morph { using tchar = System.Byte; public unsafe class String { //This waits for TICKET#27 // TODO! Chars implements only as ASCII (for now) // Use #define for all other white-space ! internal static readonly char[] WhitespaceChars = { (char) 0x9, (char) 0xA, (char) 0xB, (char) 0xC, (char) 0xD, (char) 0x20, (char) 0xA0 #if !__Morph ,(char) 0x2000, (char) 0x2001, (char) 0x2002, (char) 0x2003, (char) 0x2004, (char) 0x2005, (char) 0x2006, (char) 0x2007, (char) 0x2008, (char) 0x2009, (char) 0x200A, (char) 0x200B, (char) 0x3000, (char) 0xFEFF #endif }; internal tchar* m_buffer; internal uint m_size; internal bool m_isInHeap; public static readonly string Empty = ""; //new String('a', 0); //Constructors: public unsafe String(char c, int length) { tchar* tmp = (tchar*)Morph.Imports.allocate((uint)length); for (int i = 0; i < length; i++) tmp[i] = (tchar)c; initInternals((uint)length, tmp, true); Morph.Imports.free(tmp); } public unsafe String(char[] c, int startIndex, int length) { tchar* tmp = (tchar*)Morph.Imports.allocate((uint)length); for (int i = 0; i < length; i++) tmp[i] = (tchar) c[startIndex + i]; initInternals((uint)length, tmp, true); Morph.Imports.free(tmp); } //public String(byte[] value) //{ // fixed (tchar* p = value) // { // initInternals((uint)value.Length, p, false); // } //} private void Make(char[] value) { tchar* p = (tchar*)Morph.Imports.convert(value); initInternals((uint)value.Length, (tchar*)p, true); } public String(char[] value) { Make(value); } /** * Called by the compiler to save space. Instance a new string object from .data section * and size */ //////private static Morph.String compilerInstanceNewString(uint size, tchar* source) //////{ ////// return new String(size, source, false); //////} private static string compilerInstanceNewString(uint size, tchar* source) { return Morph.Imports.convertToString(new String(size, source, false)); } /** * Private string constructor * * Create a new string, either from .data or copy to heap */ internal String(uint size, tchar* source, bool shouldCopyToHeap) { initInternals(size, source, shouldCopyToHeap); } private void initInternals(uint size, tchar* source, bool shouldCopyToHeap) { m_size = size; if (shouldCopyToHeap) { uint bsize = size * sizeof(tchar); m_buffer = (tchar*)Morph.Imports.allocate(bsize); Memory.memcpy(m_buffer, source, bsize); m_isInHeap = true; } else { m_buffer = source; m_isInHeap = false; } } /** * Private string constructor (Multi-string) */ private String(uint size1, uint size2, tchar* s1, tchar* s2) { m_size = size1 + size2; m_buffer = (tchar*)Morph.Imports.allocate((m_size) * sizeof(tchar)); uint bsize = size1 * sizeof(tchar); Memory.memcpy(m_buffer, s1, bsize); Memory.memcpy(m_buffer + bsize, s2, size2 * sizeof(tchar)); m_isInHeap = true; } public override string ToString() { // TODO! Compiler optimization return Morph.Imports.convertToString(this); } /** * */ ~String() { if (m_isInHeap) { Morph.Imports.free(m_buffer); } } [System.Runtime.CompilerServices.IndexerName("Chars")] public char this[int index] { get { if (index < m_size) { return (char)(m_buffer[index]); } else { throw new System.IndexOutOfRangeException(); } } } //statics public unsafe static int Compare(String strA, String strB) { return Compare(strA, strB, false); } public static int Compare(String strA, String strB, bool ignoreCase) { if (strA == null && strB == null) { return 0; } if (strA == null) { return -1; } if (strB == null) { return 1; } uint len; len = (strA.m_size < strB.m_size ? strA.m_size : strB.m_size); int diff; for (int i = 0; i < len; i++) { tchar A = strA.m_buffer[i]; tchar B = strB.m_buffer[i]; if (ignoreCase) { if (B >= 'a' && B <= 'z') { B = (tchar)(B - (tchar)32); } if (A >= 'a' && A <= 'z') { A = (tchar)(A - (tchar)32); } } diff = A - B; if (diff != 0) { return diff; } } if (strA.m_size != strB.m_size) { return (int)strA.m_size - (int)strB.m_size; } return 0; } public static bool Equals(String a, String b) { if ((System.Object)a == (System.Object)b) { return true; } if ((System.Object)a == null || (System.Object)b == null) { return false; } return a.Equals(b); } //public static bool Equals(System.Object a, System.Object b) //{ // if (a == b) // return true; // if (a == null || b == null) // { // return false; // } // return ((string)a).Equals((string)b); //} public override unsafe int GetHashCode() { tchar* cc = m_buffer; tchar* end = cc + m_size - 1; int h = 0; for (; cc < end; cc += 2) { h = (h << 5) - h + *cc; h = (h << 5) - h + cc[1]; } ++end; if (cc < end) h = (h << 5) - h + *cc; return h; } public static bool IsNullOrEmpty(String value) { if (value == null) return true; if (value.m_size == 0) return true; return false; } //Propereties: public int Length { get { return (int)m_size; } } public unsafe tchar* getTCharBuffer() { return m_buffer; } public static String Concat(String a, String b) { if (a == null) return b; if (b == null) return a; return new String(a.m_size, b.m_size, a.m_buffer, b.m_buffer); } public static String Concat(String a, String b, String c) { String ab = Concat(a, b); return new String(ab.m_size, c.m_size, ab.m_buffer, c.m_buffer); } // Be carefull from recursive, use System.String instead of Morph.String public static System.String Concat(System.Object a, System.Object b) { if (a == null) return b.ToString(); if (b == null) return a.ToString(); return System.String.Concat(a.ToString(), b.ToString()); } public static System.String Concat(System.Object a, System.Object b, System.Object c) { return System.String.Concat(a.ToString(), System.String.Concat(b.ToString(), c.ToString())); } public static System.String Concat(System.Object a, System.Object b, System.Object c, System.Object d) { return System.String.Concat(System.String.Concat(a.ToString(), b.ToString()), System.String.Concat(c.ToString(), d.ToString())); } public static String Concat(String a, String b, String c, String d) { return Concat(Concat(a, b), Concat(c, d)); } public int CompareTo(System.Object value) { if (value == null) { return 1; } //if (!(value is String)) //{ // throw new ArgumentException(Environment.GetResourceString("Arg_MustBeString")); //} return String.Compare(this, (String)value); } public int CompareTo(String strB) { return Compare(this, strB); } public override bool Equals(object obj) { if (!(obj is String)) { return false; } return this.Equals((String)obj); } public bool Equals(String str) { if (str == null) { return false; } return (Compare(this, str, false) == 0); } public string ToLower() { char[] s = new char[Length]; for (int i = 0; i < Length; i++) if (this[i] >= 'A' && this[i] <= 'Z')//TICKET#53 s[i] = (char)(this[i] - 'A' + 'a'); else s[i] = (char)this[i]; return new string(s); } public string ToUpper() { char[] s = new char[Length]; for (int i = 0; i < Length; i++) if (this[i] >= 'a' && this[i] <= 'z') //TICKET#53 s[i] = (char)(this[i] + 'A' - 'a'); else s[i] = (char)this[i]; return new string(s); } public string Substring(int startIndex) { if (startIndex == 0) return Imports.convertToString(this); if (startIndex < 0 || startIndex > this.Length) throw new System.ArgumentOutOfRangeException("startIndex"); return compilerInstanceNewString((uint)(Length - startIndex), m_buffer + startIndex); } public string Substring(int startIndex, int length) { if (length < 0) throw new System.ArgumentOutOfRangeException("length", "Cannot be negative."); if (startIndex < 0) throw new System.ArgumentOutOfRangeException("startIndex", "Cannot be negative."); if (startIndex > this.Length) throw new System.ArgumentOutOfRangeException("startIndex", "Cannot exceed length of string."); if (startIndex > this.Length - length) throw new System.ArgumentOutOfRangeException("length", "startIndex + length > this.length"); if (startIndex == 0 && length == this.Length)//TICKET#53 return Imports.convertToString(this); return compilerInstanceNewString((uint)(length), m_buffer + startIndex); } public static bool operator ==(String a, String b) { return Equals(a, b); } public static bool operator !=(String a, String b) { return !Equals(a, b); } public System.Object Clone() { return this; } public static string Copy(String str) { if (str == null) throw new System.ArgumentNullException("str"); return compilerInstanceNewString((uint)str.Length, str.m_buffer); } public char[] ToCharArray() { return ToCharArray(0, Length); } public char[] ToCharArray(int startIndex, int length) { if (startIndex < 0) throw new System.ArgumentOutOfRangeException("startIndex", "< 0"); if (length < 0) throw new System.ArgumentOutOfRangeException("length", "< 0"); if (startIndex > this.Length - length) throw new System.ArgumentOutOfRangeException("startIndex", "Must be greater than the length of the string."); char[] tmp = new char[length]; unsafe { fixed (char* dest = tmp) Memory.memcpy(dest, m_buffer + startIndex, (uint)length); } return tmp; } public string Trim() { if (Length == 0) return String.Empty; int start = FindNotWhiteSpace(0, Length, 1); if (start == Length) return String.Empty; int end = FindNotWhiteSpace(Length - 1, start, -1); int newLength = end - start + 1; if (newLength == Length) return Morph.Imports.convertToString(this); return Morph.Imports.convertToString(compilerInstanceNewString((uint)newLength, m_buffer + start)); } private int FindNotWhiteSpace(int pos, int target, int change) { while (pos != target) { char c = this[pos]; if (!char.IsWhiteSpace(c)) break; pos += change; } return pos; } private int FindNotInTable(int pos, int target, int change, char[] table) { unsafe { fixed (char* tablePtr = table) { while (pos != target) { tchar c = m_buffer[pos]; int x = 0; while (x < table.Length) { if (c == tablePtr[x]) break; x++; } if (x == table.Length) return pos; pos += change; } } return pos; } } public string Trim(params char[] trimChars) { if (trimChars == null || trimChars.Length == 0) return Trim(); if (Length == 0) return String.Empty; int start = FindNotInTable(0, Length, 1, trimChars); if (start == Length) return String.Empty; int end = FindNotInTable(Length - 1, start, -1, trimChars); int newLength = end - start + 1; if (newLength == Length) return Morph.Imports.convertToString(this); return Morph.Imports.convertToString(compilerInstanceNewString((uint)newLength, m_buffer + start)); } public string TrimStart(params char[] trimChars) { if (Length == 0) return String.Empty; int start; if (trimChars == null || trimChars.Length == 0) start = FindNotWhiteSpace(0, Length, 1); else start = FindNotInTable(0, Length, 1, trimChars); if (start == 0) return Morph.Imports.convertToString(this); return Morph.Imports.convertToString(compilerInstanceNewString((uint)(Length - start), m_buffer + start)); } public string TrimEnd(params char[] trimChars) { if (Length == 0) return String.Empty; int end; if (trimChars == null || trimChars.Length == 0) end = FindNotWhiteSpace(Length - 1, -1, -1); else end = FindNotInTable(Length - 1, -1, -1, trimChars); end++; if (end == Length) return Morph.Imports.convertToString(this); return Morph.Imports.convertToString(compilerInstanceNewString((uint)(end), m_buffer)); } public bool StartsWith(String value) { if (value == null) throw new System.ArgumentNullException("value"); if (value.Length > Length) return false; for (int i = 0; i < value.Length; i++) if (value[i] != this[i]) return false; return true; } public string Remove(int startIndex) { if (startIndex < 0) throw new System.ArgumentOutOfRangeException("startIndex", "StartIndex can not be less than zero"); if (startIndex >= this.Length) throw new System.ArgumentOutOfRangeException("startIndex", "StartIndex must be less than the length of the string"); return Remove(startIndex, Length - startIndex); } public unsafe string Remove(int startIndex, int count) { if (startIndex < 0) throw new System.ArgumentOutOfRangeException("startIndex", "Cannot be negative."); if (count < 0) throw new System.ArgumentOutOfRangeException("count", "Cannot be negative."); if (startIndex > this.Length - count) throw new System.ArgumentOutOfRangeException("count", "startIndex + count > this.length"); return Morph.Imports.convertToString(Concat(compilerInstanceNewString((uint)startIndex, m_buffer), Morph.Imports.convertToString(compilerInstanceNewString((uint)(Length - count - startIndex), m_buffer + startIndex + count)))); } public string Replace(char oldChar, char newChar) { if (oldChar == newChar) return Imports.convertToString(this); char[] s = new char[Length]; for (int i = 0; i < Length; i++) if (this[i] == oldChar) s[i] = newChar; else s[i] = this[i]; return new string(s); } public string PadLeft(int totalWidth) { return PadLeft(totalWidth, ' '); } public unsafe string PadLeft(int totalWidth, char paddingChar) { //LAMESPEC: MSDN Doc says this is reversed for RtL languages, but this seems to be untrue if (totalWidth < 0) throw new System.ArgumentOutOfRangeException("totalWidth", "< 0"); if (totalWidth < Length) return Morph.Imports.convertToString(this); tchar* tmp = (tchar*)Morph.Imports.allocate((uint)totalWidth * sizeof(tchar)); tchar* padPos = tmp; tchar* padTo = tmp + (totalWidth - Length); while (padPos != padTo) { *padPos = (tchar)paddingChar; padPos++; } Memory.memcpy(padTo, m_buffer, (uint)Length); return Morph.Imports.convertToString(compilerInstanceNewString((uint)totalWidth, tmp)); } public string PadRight(int totalWidth) { return PadRight(totalWidth, ' '); } public unsafe string PadRight(int totalWidth, char paddingChar) { //LAMESPEC: MSDN Doc says this is reversed for RtL languages, but this seems to be untrue if (totalWidth < 0) throw new System.ArgumentOutOfRangeException("totalWidth", "< 0"); if (totalWidth < Length) return Morph.Imports.convertToString(this); if (totalWidth == 0) return String.Empty; tchar* tmp = (tchar*)Morph.Imports.allocate((uint)totalWidth * sizeof(tchar)); Memory.memcpy(tmp, m_buffer, (uint)Length); tchar* padPos = tmp + Length; tchar* padTo = tmp + totalWidth; while (padPos != padTo) { *padPos = (tchar)paddingChar; padPos++; } return Morph.Imports.convertToString(compilerInstanceNewString((uint)totalWidth, tmp)); } public unsafe void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) { if (destination == null) throw new System.ArgumentNullException("destination"); if (sourceIndex < 0) throw new System.ArgumentOutOfRangeException("sourceIndex", "Cannot be negative"); if (destinationIndex < 0) throw new System.ArgumentOutOfRangeException("destinationIndex", "Cannot be negative."); if (count < 0) throw new System.ArgumentOutOfRangeException("count", "Cannot be negative."); if (sourceIndex > Length - count) throw new System.ArgumentOutOfRangeException("sourceIndex", "sourceIndex + count > Length"); if (destinationIndex > destination.Length - count) throw new System.ArgumentOutOfRangeException("destinationIndex", "destinationIndex + count > destination.Length"); fixed (char* dest = destination) Memory.memcpy(dest + destinationIndex, m_buffer + sourceIndex, (uint)count); } public bool EndsWith(String value) { if (value == null) throw new System.ArgumentNullException("value"); if (Length < value.Length) return false; int len = Length - value.Length; for (int i = 0; i < value.Length; i++) if (value[i] != this[len + i]) return false; return true; } public int IndexOf(char value) { if (Length == 0) return -1; return IndexOfUnchecked(value, 0, Length); } public int IndexOf(char value, int startIndex) { if (startIndex < 0) throw new System.ArgumentOutOfRangeException("startIndex", "< 0"); if (startIndex > Length) throw new System.ArgumentOutOfRangeException("startIndex", "startIndex > this.length"); if ((startIndex == 0 && Length == 0) || (startIndex == Length))//TICKET#53 return -1; return IndexOfUnchecked(value, startIndex, Length - startIndex); } public int IndexOf(char value, int startIndex, int count) { if (startIndex < 0 || startIndex > Length) throw new System.ArgumentOutOfRangeException("startIndex", "Cannot be negative and must be< 0"); if (count < 0) throw new System.ArgumentOutOfRangeException("count", "< 0"); if (startIndex > Length - count) throw new System.ArgumentOutOfRangeException("count", "startIndex + count > this.length"); if ((startIndex == 0 && Length == 0) || (startIndex == Length) || (count == 0))//TICKET#53 return -1; return IndexOfUnchecked(value, startIndex, count); } internal unsafe int IndexOfUnchecked(char value, int startIndex, int count) { // It helps JIT compiler to optimize comparison int value_32 = (int)value; tchar* ptr = m_buffer + startIndex; tchar* end_ptr = ptr + (count >> 3 << 3); while (ptr != end_ptr) { if (*ptr == value_32) return (int)(ptr - m_buffer); if (ptr[1] == value_32) return (int)(ptr - m_buffer + 1); if (ptr[2] == value_32) return (int)(ptr - m_buffer + 2); if (ptr[3] == value_32) return (int)(ptr - m_buffer + 3); if (ptr[4] == value_32) return (int)(ptr - m_buffer + 4); if (ptr[5] == value_32) return (int)(ptr - m_buffer + 5); if (ptr[6] == value_32) return (int)(ptr - m_buffer + 6); if (ptr[7] == value_32) return (int)(ptr - m_buffer + 7); ptr += 8; } end_ptr += count & 0x07; while (ptr != end_ptr) { if (*ptr == value_32) return (int)(ptr - m_buffer); ptr++; } return -1; } public int IndexOfAny(char[] anyOf) { if (anyOf == null) throw new System.ArgumentNullException(); if (Length == 0) return -1; return IndexOfAnyUnchecked(anyOf, 0, Length); } public int IndexOfAny(char[] anyOf, int startIndex) { if (anyOf == null) throw new System.ArgumentNullException(); if (startIndex < 0 || startIndex > Length) throw new System.ArgumentOutOfRangeException(); return IndexOfAnyUnchecked(anyOf, startIndex, Length - startIndex); } public int IndexOfAny(char[] anyOf, int startIndex, int count) { if (anyOf == null) throw new System.ArgumentNullException(); if (startIndex < 0 || startIndex > Length) throw new System.ArgumentOutOfRangeException(); if (count < 0 || startIndex > Length - count) throw new System.ArgumentOutOfRangeException("count", "Count cannot be negative, and startIndex + count must be less than length of the string."); return IndexOfAnyUnchecked(anyOf, startIndex, count); } private unsafe int IndexOfAnyUnchecked(char[] anyOf, int startIndex, int count) { if (anyOf.Length == 0) return -1; if (anyOf.Length == 1) return IndexOfUnchecked(anyOf[0], startIndex, count); fixed (char* any = anyOf) { char highest = *any; char lowest = *any; char* end_any_ptr = any + anyOf.Length; char* any_ptr = any; while (++any_ptr != end_any_ptr) { if (*any_ptr > highest) { highest = *any_ptr; continue; } if (*any_ptr < lowest) lowest = *any_ptr; } tchar* ptr = m_buffer + startIndex; tchar* end_ptr = ptr + count; while (ptr != end_ptr) { if (*ptr > highest || *ptr < lowest) { ptr++; continue; } if (*ptr == (tchar)(*any)) return (int)(ptr - m_buffer); any_ptr = any; while (++any_ptr != end_any_ptr) { if (*ptr == (tchar)(*any_ptr)) return (int)(ptr - m_buffer); } ptr++; } } return -1; } public int IndexOf(String value) { if (value == null) throw new System.ArgumentNullException("value"); if (value.Length == 0) return 0; if (this.Length == 0) return -1; return IndexOf(value, 0, Length); } public int IndexOf(String value, int startIndex) { return IndexOf(value, startIndex, this.Length - startIndex); } public unsafe int IndexOf(String value, int startIndex, int count) { if (value == null) throw new System.ArgumentNullException("value"); if (startIndex < 0 || startIndex > this.Length) throw new System.ArgumentOutOfRangeException("startIndex", "Cannot be negative, and should not exceed length of string."); if (count < 0 || startIndex > this.Length - count) throw new System.ArgumentOutOfRangeException("count", "Cannot be negative, and should point to location in string."); if (value.Length == 0) return startIndex; if (startIndex == 0 && this.Length == 0)//TICKET#53 return -1; if (count == 0) return -1; tchar* st1 = m_buffer + startIndex, end1 = m_buffer + startIndex + count; tchar* st2 = value.m_buffer, end2 = value.m_buffer + value.Length; int index = -1; while (st1 != end1) { int tmp2 = *st1; if (*st1 == *st2) { int tmp = *st2; st2++; } else { st2 = value.m_buffer; } st1++; if (st2 == end2) { index = (int)(st1 - m_buffer) - value.Length; break; } } return index; } public unsafe string Insert(int startIndex, String value) { if (value == null) throw new System.ArgumentNullException("value"); if (startIndex < 0 || startIndex > Length) throw new System.ArgumentOutOfRangeException("startIndex", "Cannot be negative and must be less than or equal to length of string."); if (value.Length == 0) return Imports.convertToString(this); if (this.Length == 0) return Imports.convertToString(value); tchar* tmp = (tchar*)Imports.allocate((uint)(Length + value.Length)); tchar* dst = tmp; Memory.memcpy(dst, m_buffer, (uint)startIndex); dst += startIndex; Memory.memcpy(dst, value.m_buffer, (uint)value.Length); dst += value.Length; Memory.memcpy(dst, m_buffer + startIndex, (uint)(Length - startIndex)); return Morph.Imports.convertToString(compilerInstanceNewString((uint)(Length + value.Length), tmp)); } public static bool IsNullOrWhiteSpace (string value) { if ((value == null) || (value.Length == 0)) return true; foreach (char c in value) if (!Char.IsWhiteSpace (c)) return false; return true; } public int LastIndexOf(char value) { if (this.Length == 0) return -1; return LastIndexOfUnchecked(value, this.Length - 1, this.Length); } public int LastIndexOf(char value, int startIndex) { return LastIndexOf(value, startIndex, startIndex + 1); } public int LastIndexOf(char value, int startIndex, int count) { if (this.Length == 0) return -1; // >= for char (> for string) if ((startIndex < 0) || (startIndex >= this.Length)) throw new System.ArgumentOutOfRangeException("startIndex", "< 0 || >= this.Length"); if ((count < 0) || (count > this.Length)) throw new System.ArgumentOutOfRangeException("count", "< 0 || > this.Length"); if (startIndex - count + 1 < 0) throw new System.ArgumentOutOfRangeException("startIndex - count + 1 < 0"); return LastIndexOfUnchecked(value, startIndex, count); } internal unsafe int LastIndexOfUnchecked(char value, int startIndex, int count) { // It helps JIT compiler to optimize comparison int value_32 = (int)value; tchar* ptr = m_buffer + startIndex; tchar* end_ptr = ptr - (count >> 3 << 3); while (ptr != end_ptr) { if (*ptr == value_32) return (int)(ptr - m_buffer); if (ptr[-1] == value_32) return (int)(ptr - m_buffer) - 1; if (ptr[-2] == value_32) return (int)(ptr - m_buffer) - 2; if (ptr[-3] == value_32) return (int)(ptr - m_buffer) - 3; if (ptr[-4] == value_32) return (int)(ptr - m_buffer) - 4; if (ptr[-5] == value_32) return (int)(ptr - m_buffer) - 5; if (ptr[-6] == value_32) return (int)(ptr - m_buffer) - 6; if (ptr[-7] == value_32) return (int)(ptr - m_buffer) - 7; ptr -= 8; } end_ptr -= count & 0x07; while (ptr != end_ptr) { if (*ptr == value_32) return (int)(ptr - m_buffer); ptr--; } return -1; } public int LastIndexOf(String value) { return LastIndexOf(value, this.Length - 1, this.Length); } public int LastIndexOf(String value, int startIndex) { int max = startIndex; if (max < this.Length) max++; return LastIndexOf(value, startIndex, max); } public int LastIndexOf(String value, int startIndex, int count) { if (value == null) throw new System.ArgumentNullException("value"); if (this.Length == 0) return Imports.convertToString(value) == String.Empty ? 0 : -1; // -1 > startIndex > for string (0 > startIndex >= for char) if ((startIndex < -1) || (startIndex > this.Length)) throw new System.ArgumentOutOfRangeException("startIndex", "< 0 || > this.Length"); if ((count < 0) || (count > this.Length)) throw new System.ArgumentOutOfRangeException("count", "< 0 || > this.Length"); if (startIndex - count + 1 < 0) throw new System.ArgumentOutOfRangeException("startIndex - count + 1 < 0"); if (value.Length == 0) return Math.Min(this.Length - 1, startIndex); if (startIndex == 0 && this.Length == 0)//TICKET#53 return -1; // This check is needed to match undocumented MS behaviour if (this.Length == 0 && value.Length > 0)//TICKET#53 return -1; if (count == 0) return -1; if (startIndex == this.Length) startIndex--; tchar* end1 = m_buffer + startIndex - count - 1, st1 = m_buffer + startIndex; tchar* end2 = value.m_buffer - 1, st2 = value.m_buffer + value.Length - 1; int i = startIndex, index = -1; while (st1 != end1) { if (st2 == end2) { index = i + 1; break; } if (*st1 == *st2) { st2--; } else { st2 = value.m_buffer + value.Length - 1; } st1--; i--; } return index; } public int LastIndexOfAny(char[] anyOf) { if (anyOf == null) throw new System.ArgumentNullException(); if (this.Length == 0) return -1; return LastIndexOfAnyUnchecked(anyOf, this.Length - 1, this.Length); } public int LastIndexOfAny(char[] anyOf, int startIndex) { if (anyOf == null) throw new System.ArgumentNullException(); if (this.Length == 0) return -1; if (startIndex < 0 || startIndex >= this.Length) throw new System.ArgumentOutOfRangeException("startIndex", "Cannot be negative, and should be less than length of string."); if (this.Length == 0) return -1; return LastIndexOfAnyUnchecked(anyOf, startIndex, startIndex + 1); } public int LastIndexOfAny(char[] anyOf, int startIndex, int count) { if (anyOf == null) throw new System.ArgumentNullException(); if (this.Length == 0) return -1; if ((startIndex < 0) || (startIndex >= this.Length)) throw new System.ArgumentOutOfRangeException("startIndex", "< 0 || > this.Length"); if ((count < 0) || (count > this.Length)) throw new System.ArgumentOutOfRangeException("count", "< 0 || > this.Length"); if (startIndex - count + 1 < 0) throw new System.ArgumentOutOfRangeException("startIndex - count + 1 < 0"); if (this.Length == 0) return -1; return LastIndexOfAnyUnchecked(anyOf, startIndex, count); } private unsafe int LastIndexOfAnyUnchecked(char[] anyOf, int startIndex, int count) { if (anyOf.Length == 1) return LastIndexOfUnchecked(anyOf[0], startIndex, count); char* start = (char*)m_buffer; fixed (char* testStart = anyOf) { char* ptr = start + startIndex; char* ptrEnd = ptr - count; char* test; char* testEnd = testStart + anyOf.Length; while (ptr != ptrEnd) { test = testStart; while (test != testEnd) { if (*test == *ptr) return (int)(ptr - start); test++; } ptr--; } return -1; } } public bool Contains(char c) { return IndexOf(c) != -1; } public bool Contains(String value) { return IndexOf(value) != -1; } public static string Join(Morph.String separator, Morph.Object[] value) { Morph.String[] strArr = new Morph.String[value.Length]; for (int i = 0; i < value.Length; i++) { strArr[i] = (Morph.String)Imports.convertToObject(value[i].ToString()); } return Join( separator, strArr); } public static string Join(Morph.String separator, Morph.String[] value) { if (value == null) throw new System.ArgumentNullException("value"); if (separator == null) separator = (Morph.String)Morph.Imports.convertToObject(String.Empty); return JoinUnchecked (separator, value, 0, value.Length); } public static string Join(Morph.String separator, Morph.String[] value, int startIndex, int count) { if (value == null) throw new System.ArgumentNullException("value"); if (startIndex < 0) throw new System.ArgumentOutOfRangeException("startIndex", "< 0"); if (count < 0) throw new System.ArgumentOutOfRangeException("count", "< 0"); if (startIndex > value.Length - count) throw new System.ArgumentOutOfRangeException("startIndex", "startIndex + count > value.length"); if (startIndex >= value.Length) return String.Empty; if (separator == null) separator = (Morph.String) Morph.Imports.convertToObject(String.Empty); return JoinUnchecked (separator, value, startIndex, count); } private static unsafe string JoinUnchecked(Morph.String separator, Morph.String[] value, int startIndex, int count) { // Unchecked parameters // startIndex, count must be >= 0; startIndex + count must be <= value.length // separator and value must not be null int length = 0; int maxIndex = startIndex + count; // Precount the number of characters that the resulting string will have for (int i = startIndex; i < maxIndex; i++) { if (value[i] != null) length += value[i].Length; } length += separator.Length * (count - 1); if (length <= 0) return Morph.String.Empty; tchar* tmp = (tchar*)Imports.allocate((uint)length); maxIndex--; tchar* dest = tmp; // Copy each string from value except the last one and add a separator for each int pos = 0; for (int i = startIndex; i < maxIndex; i++) { String source = value[i]; if (source != null) { if (source.Length > 0) { tchar* src = source.m_buffer; Memory.memcpy (dest + pos, src, (uint)source.Length); pos += source.Length; } } if (separator.Length > 0) { Memory.memcpy(dest + pos, separator.m_buffer, (uint)separator.Length); pos += separator.Length; } } // Append last string that does not get an additional separator Morph.String sourceLast = value[maxIndex]; if (sourceLast != null) { if (sourceLast.Length > 0) { Memory.memcpy(dest + pos, sourceLast.m_buffer, (uint)sourceLast.Length); } } return compilerInstanceNewString((uint)length, tmp); } public static string Join(string separator, params object[] values) { string[] st = new string[values.Length]; for (int i = 0; i < values.Length; i++) st[i] = values[i].ToString(); return Join(separator, st); } public string[] Split(params char[] separator) { return Split(separator, Int32.MaxValue); } public string[] Split(char[] separator, int count) { if (separator == null || separator.Length == 0) separator = WhitespaceChars; if (count < 0) throw new System.ArgumentOutOfRangeException("count"); if (count == 0) return new string[0]; if (count == 1) return new string[1] { Imports.convertToString(this) }; string[] res = new string[count]; int indx = 0, last = 0; for (int i = 0; i < Length; i++) if (Belong(this[i], separator)) { res[indx] = this.Substring(last, i); indx++; last = i + 1; } return res; } private bool Belong(char c, char[] a) { foreach (char cc in a) if (c == cc) return true; return false; } public static string Format(string format, object arg0) { return Format(null, format, new object[] { arg0 }); } public static string Format(string format, object arg0, object arg1) { return Format(null, format, new object[] { arg0, arg1 }); } public static string Format(string format, object arg0, object arg1, object arg2) { return Format(null, format, new object[] { arg0, arg1, arg2 }); } public static string Format(string format, params object[] args) { StringBuilder b = FormatHelper(null, format, args); return b.ToString(); } internal static StringBuilder FormatHelper(StringBuilder result, string format, params object[] args) { if (format == null) throw new System.ArgumentNullException("format"); if (args == null) throw new System.ArgumentNullException("args"); if (result == null) { /* Try to approximate the size of result to avoid reallocations */ int i, len; len = 0; for (i = 0; i < args.Length; ++i) { string s = args[i] as string; if (s != null) len += s.Length; else break; } if (i == args.Length) result = new StringBuilder(len + format.Length); else result = new StringBuilder(); } int ptr = 0; int start = ptr; while (ptr < format.Length) { char c = format[ptr++]; if (c == '{') { result.Append(format, start, ptr - start - 1); // check for escaped open bracket if (format[ptr] == '{') { start = ptr++; continue; } // parse specifier int n, width; bool left_align; string arg_format; ParseFormatSpecifier(format, ref ptr, out n, out width, out left_align, out arg_format); if (n >= args.Length) throw new System.FormatException("Index (zero based) must be greater than or equal to zero and less than the size of the argument list."); // format argument object arg = args[n]; string str; str = arg.ToString(); // pad formatted string and append to result if (width > str.Length) { const char padchar = ' '; int padlen = width - str.Length; if (left_align) { result.Append(str); result.Append(padchar, padlen); } else { result.Append(padchar, padlen); result.Append(str); } } else result.Append(str); start = ptr; } else if (c == '}' && ptr < format.Length && format[ptr] == '}') { result.Append(format, start, ptr - start - 1); start = ptr++; } else if (c == '}') { throw new System.FormatException("Input string was not in a correct format."); } } if (start < format.Length) result.Append(format, start, format.Length - start); return result; } private static void ParseFormatSpecifier (string str, ref int ptr, out int n, out int width, out bool left_align, out string format) { int max = str.Length; // parses format specifier of form: // N,[\ +[-]M][:F]} // // where: // N = argument number (non-negative integer) n = ParseDecimal (str, ref ptr); if (n < 0) throw new System.FormatException ("Input string was not in a correct format."); // M = width (non-negative integer) if (ptr < max && str[ptr] == ',') { // White space between ',' and number or sign. ++ptr; while (ptr < max && Char.IsWhiteSpace (str [ptr])) ++ptr; int start = ptr; format = str.Substring (start, ptr - start); left_align = (ptr < max && str [ptr] == '-'); if (left_align) ++ ptr; width = ParseDecimal (str, ref ptr); if (width < 0) throw new System.FormatException ("Input string was not in a correct format."); } else { width = 0; left_align = false; format = String.Empty; } // F = argument format (string) if (ptr < max && str[ptr] == ':') { int start = ++ ptr; while (ptr < max && str[ptr] != '}') ++ ptr; format += str.Substring (start, ptr - start); } else format = null; if ((ptr >= max) || str[ptr ++] != '}') throw new System.FormatException ("Input string was not in a correct format."); } private static int ParseDecimal (string str, ref int ptr) { int p = ptr; int n = 0; int max = str.Length; while (p < max) { char c = str[p]; if (c < '0' || '9' < c) break; n = n * 10 + c - '0'; ++ p; } if (p == ptr || p == max) return -1; ptr = p; return n; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using Microsoft.VisualStudio.TestTools.UnitTesting; using DotVVM.Framework.Binding; using DotVVM.Framework.Configuration; using DotVVM.Framework.Controls; using DotVVM.Framework.Controls.Infrastructure; using DotVVM.Framework.Hosting; using DotVVM.Framework.Parser; using DotVVM.Framework.Runtime; using DotVVM.Framework.Runtime.Compilation; namespace DotVVM.Framework.Tests.Runtime { [TestClass] public class DefaultViewCompilerTests { private DotvvmRequestContext context; [TestInitialize] public void TestInit() { context = new DotvvmRequestContext(); context.Configuration = DotvvmConfiguration.CreateDefault(); } [TestMethod] public void DefaultViewCompiler_CodeGeneration_ElementWithAttributeProperty() { var markup = @"@viewModel System.Object, mscorlib test <dot:Literal Text='test' />"; var page = CompileMarkup(markup); Assert.IsInstanceOfType(page, typeof(DotvvmView)); Assert.AreEqual(2, page.Children.Count); Assert.IsInstanceOfType(page.Children[0], typeof(Literal)); Assert.AreEqual("test ", ((Literal)page.Children[0]).Text); Assert.IsInstanceOfType(page.Children[1], typeof(Literal)); Assert.AreEqual("test", ((Literal)page.Children[1]).Text); } [TestMethod] public void DefaultViewCompiler_CodeGeneration_ElementWithBindingProperty() { var markup = string.Format("@viewModel {0}, {1}\r\ntest <dot:Literal Text='{{{{value: FirstName}}}}' />", typeof(ViewCompilerTestViewModel).FullName, typeof(ViewCompilerTestViewModel).Assembly.GetName().Name); var page = CompileMarkup(markup); Assert.IsInstanceOfType(page, typeof(DotvvmView)); Assert.AreEqual(2, page.Children.Count); Assert.IsInstanceOfType(page.Children[0], typeof(Literal)); Assert.AreEqual("test ", ((Literal)page.Children[0]).Text); Assert.IsInstanceOfType(page.Children[1], typeof(Literal)); var binding = ((Literal)page.Children[1]).GetBinding(Literal.TextProperty) as ValueBindingExpression; Assert.IsNotNull(binding); Assert.AreEqual("FirstName", binding.OriginalString); } [TestMethod] public void DefaultViewCompiler_CodeGeneration_BindingInText() { var markup = string.Format("@viewModel {0}, {1}\r\ntest {{{{value: FirstName}}}}", typeof(ViewCompilerTestViewModel).FullName, typeof(ViewCompilerTestViewModel).Assembly.GetName().Name); var page = CompileMarkup(markup); Assert.IsInstanceOfType(page, typeof(DotvvmView)); Assert.AreEqual(2, page.Children.Count); Assert.IsInstanceOfType(page.Children[0], typeof(Literal)); Assert.AreEqual("test ", ((Literal)page.Children[0]).Text); Assert.IsInstanceOfType(page.Children[1], typeof(Literal)); var binding = ((Literal)page.Children[1]).GetBinding(Literal.TextProperty) as ValueBindingExpression; Assert.IsNotNull(binding); Assert.AreEqual("FirstName", binding.OriginalString); } [TestMethod] public void DefaultViewCompiler_CodeGeneration_NestedControls() { var markup = @"@viewModel System.Object, mscorlib <dot:Placeholder>test <dot:Literal /></dot:Placeholder>"; var page = CompileMarkup(markup); Assert.IsInstanceOfType(page, typeof(DotvvmView)); Assert.AreEqual(1, page.Children.Count); Assert.IsInstanceOfType(page.Children[0], typeof(Placeholder)); Assert.AreEqual(2, page.Children[0].Children.Count); Assert.IsTrue(page.Children[0].Children.All(c => c is Literal)); Assert.AreEqual("test ", ((Literal)page.Children[0].Children[0]).Text); Assert.AreEqual("", ((Literal)page.Children[0].Children[1]).Text); } [TestMethod] [ExpectedException(typeof(Exception))] public void DefaultViewCompiler_CodeGeneration_ElementCannotHaveContent_TextInside() { var markup = @"@viewModel System.Object, mscorlib test <dot:Literal>aaa</dot:Literal>"; var page = CompileMarkup(markup); } [TestMethod] [ExpectedException(typeof(Exception))] public void DefaultViewCompiler_CodeGeneration_ElementCannotHaveContent_BindingAndWhiteSpaceInside() { var markup = @"@viewModel System.Object, mscorlib test <dot:Literal>{{value: FirstName}} </dot:Literal>"; var page = CompileMarkup(markup); } [TestMethod] [ExpectedException(typeof(Exception))] public void DefaultViewCompiler_CodeGeneration_ElementCannotHaveContent_ElementInside() { var markup = @"@viewModel System.Object, mscorlib test <dot:Literal><a /></dot:Literal>"; var page = CompileMarkup(markup); } [TestMethod] public void DefaultViewCompiler_CodeGeneration_Template() { var markup = string.Format("@viewModel {0}, {1}\r\n", typeof(ViewCompilerTestViewModel).FullName, typeof(ViewCompilerTestViewModel).Assembly.GetName().Name) + @"<dot:Repeater DataSource=""{value: FirstName}""> <ItemTemplate> <p>This is a test</p> </ItemTemplate> </dot:Repeater>"; var page = CompileMarkup(markup); Assert.IsInstanceOfType(page, typeof(DotvvmView)); Assert.AreEqual(1, page.Children.Count); Assert.IsInstanceOfType(page.Children[0], typeof(Repeater)); DotvvmControl placeholder = new Placeholder(); ((Repeater)page.Children[0]).ItemTemplate.BuildContent(context, placeholder); placeholder = placeholder.Children[0]; Assert.AreEqual(3, placeholder.Children.Count); Assert.IsTrue(string.IsNullOrWhiteSpace(((Literal)placeholder.Children[0]).Text)); Assert.AreEqual("p", ((HtmlGenericControl)placeholder.Children[1]).TagName); Assert.AreEqual("This is a test", ((Literal)placeholder.Children[1].Children[0]).Text); Assert.IsTrue(string.IsNullOrWhiteSpace(((Literal)placeholder.Children[2]).Text)); } [TestMethod] public void DefaultViewCompiler_CodeGeneration_AttachedProperty() { var markup = @"@viewModel System.Object, mscorlib <dot:Button Validate.Enabled=""false"" /><dot:Button Validate.Enabled=""true"" /><dot:Button />"; var page = CompileMarkup(markup); Assert.IsInstanceOfType(page, typeof(DotvvmView)); var button1 = page.Children[0]; Assert.IsInstanceOfType(button1, typeof(Button)); Assert.IsFalse((bool)button1.GetValue(Validate.EnabledProperty)); var button2 = page.Children[1]; Assert.IsInstanceOfType(button2, typeof(Button)); Assert.IsTrue((bool)button2.GetValue(Validate.EnabledProperty)); var button3 = page.Children[2]; Assert.IsInstanceOfType(button3, typeof(Button)); Assert.IsTrue((bool)button3.GetValue(Validate.EnabledProperty)); } [TestMethod] public void DefaultViewCompiler_CodeGeneration_MarkupControl() { var markup = @"@viewModel System.Object, mscorlib <cc:Test1 />"; var page = CompileMarkup(markup, new Dictionary<string, string>() { { "test1.dothtml", @"@viewModel System.Object, mscorlib <dot:Literal Text='aaa' />" } }); Assert.IsInstanceOfType(page, typeof(DotvvmView)); Assert.IsInstanceOfType(page.Children[0], typeof(DotvvmView)); var literal = page.Children[0].Children[0]; Assert.IsInstanceOfType(literal, typeof(Literal)); Assert.AreEqual("aaa", ((Literal)literal).Text); } [TestMethod] public void DefaultViewCompiler_CodeGeneration_MarkupControlWithBaseType() { var markup = @"@viewModel System.Object, mscorlib <cc:Test2 />"; var page = CompileMarkup(markup, new Dictionary<string, string>() { { "test2.dothtml", string.Format("@baseType {0}, {1}\r\n@viewModel System.Object, mscorlib\r\n<dot:Literal Text='aaa' />", typeof(TestControl), typeof(TestControl).Assembly.GetName().Name) } }); Assert.IsInstanceOfType(page, typeof(DotvvmView)); Assert.IsInstanceOfType(page.Children[0], typeof(TestControl)); var literal = page.Children[0].Children[0]; Assert.IsInstanceOfType(literal, typeof(Literal)); Assert.AreEqual("aaa", ((Literal)literal).Text); } [TestMethod] public void DefaultViewCompiler_CodeGeneration_MarkupControl_InTemplate() { var markup = string.Format("@viewModel {0}, {1}\r\n", typeof(ViewCompilerTestViewModel).FullName, typeof(ViewCompilerTestViewModel).Assembly.GetName().Name) + @"<dot:Repeater DataSource=""{value: FirstName}""> <ItemTemplate> <cc:Test3 /> </ItemTemplate> </dot:Repeater>"; var page = CompileMarkup(markup, new Dictionary<string, string>() { { "test3.dothtml", "@viewModel System.Char, mscorlib\r\n<dot:Literal Text='aaa' />" } }); Assert.IsInstanceOfType(page, typeof(DotvvmView)); Assert.IsInstanceOfType(page.Children[0], typeof(Repeater)); var container = new Placeholder(); ((Repeater)page.Children[0]).ItemTemplate.BuildContent(context, container); Assert.IsInstanceOfType(container.Children[0], typeof(Placeholder)); var literal1 = container.Children[0].Children[0]; Assert.IsInstanceOfType(literal1, typeof(Literal)); Assert.IsTrue(string.IsNullOrWhiteSpace(((Literal)literal1).Text)); var markupControl = container.Children[0].Children[1]; Assert.IsInstanceOfType(markupControl, typeof(DotvvmView)); Assert.IsInstanceOfType(markupControl.Children[0], typeof(Literal)); Assert.AreEqual("aaa", ((Literal)markupControl.Children[0]).Text); var literal2 = container.Children[0].Children[2]; Assert.IsInstanceOfType(literal2, typeof(Literal)); Assert.IsTrue(string.IsNullOrWhiteSpace(((Literal)literal2).Text)); } [TestMethod] public void DefaultViewCompiler_CodeGeneration_MarkupControl_InTemplate_CacheTest() { var markup = string.Format("@viewModel {0}, {1}\r\n", typeof(ViewCompilerTestViewModel).FullName, typeof(ViewCompilerTestViewModel).Assembly.GetName().Name) + @"<dot:Repeater DataSource=""{value: FirstName}""> <ItemTemplate> <cc:Test4 /> </ItemTemplate> </dot:Repeater>"; var page = CompileMarkup(markup, new Dictionary<string, string>() { { "test4.dothtml", "@viewModel System.Char, mscorlib\r\n<dot:Literal Text='aaa' />" } }, compileTwice: true); Assert.IsInstanceOfType(page, typeof(DotvvmView)); Assert.IsInstanceOfType(page.Children[0], typeof(Repeater)); var container = new Placeholder(); ((Repeater)page.Children[0]).ItemTemplate.BuildContent(context, container); Assert.IsInstanceOfType(container.Children[0], typeof(Placeholder)); var literal1 = container.Children[0].Children[0]; Assert.IsInstanceOfType(literal1, typeof(Literal)); Assert.IsTrue(string.IsNullOrWhiteSpace(((Literal)literal1).Text)); var markupControl = container.Children[0].Children[1]; Assert.IsInstanceOfType(markupControl, typeof(DotvvmView)); Assert.IsInstanceOfType(markupControl.Children[0], typeof(Literal)); Assert.AreEqual("aaa", ((Literal)markupControl.Children[0]).Text); var literal2 = container.Children[0].Children[2]; Assert.IsInstanceOfType(literal2, typeof(Literal)); Assert.IsTrue(string.IsNullOrWhiteSpace(((Literal)literal2).Text)); } private DotvvmControl CompileMarkup(string markup, Dictionary<string, string> markupFiles = null, bool compileTwice = false, [CallerMemberName]string fileName = null) { if (markupFiles == null) { markupFiles = new Dictionary<string, string>(); } markupFiles[fileName + ".dothtml"] = markup; var dotvvmConfiguration = context.Configuration; dotvvmConfiguration.Markup.Controls.Add(new DotvvmControlConfiguration() { TagPrefix = "cc", TagName = "Test1", Src = "test1.dothtml" }); dotvvmConfiguration.Markup.Controls.Add(new DotvvmControlConfiguration() { TagPrefix = "cc", TagName = "Test2", Src = "test2.dothtml" }); dotvvmConfiguration.Markup.Controls.Add(new DotvvmControlConfiguration() { TagPrefix = "cc", TagName = "Test3", Src = "test3.dothtml" }); dotvvmConfiguration.Markup.Controls.Add(new DotvvmControlConfiguration() { TagPrefix = "cc", TagName = "Test4", Src = "test4.dothtml" }); dotvvmConfiguration.ServiceLocator.RegisterSingleton<IMarkupFileLoader>(() => new FakeMarkupFileLoader(markupFiles)); dotvvmConfiguration.Markup.AddAssembly(Assembly.GetExecutingAssembly().GetName().Name); var controlBuilderFactory = dotvvmConfiguration.ServiceLocator.GetService<IControlBuilderFactory>(); var controlBuilder = controlBuilderFactory.GetControlBuilder(fileName + ".dothtml"); var result = controlBuilder.BuildControl(controlBuilderFactory); if (compileTwice) { result = controlBuilder.BuildControl(controlBuilderFactory); } return result; } } public class ViewCompilerTestViewModel { public string FirstName { get; set; } } public class TestControl : DotvvmMarkupControl { } public class FakeMarkupFileLoader : IMarkupFileLoader { private readonly Dictionary<string, string> markupFiles; public FakeMarkupFileLoader(Dictionary<string, string> markupFiles = null) { this.markupFiles = markupFiles ?? new Dictionary<string, string>(); } public MarkupFile GetMarkup(DotvvmConfiguration configuration, string virtualPath) { return new MarkupFile(virtualPath, virtualPath, markupFiles[virtualPath]); } public string GetMarkupFileVirtualPath(DotvvmRequestContext context) { throw new NotImplementedException(); } } }
/* The MIT License * * Copyright (c) 2010 Intel Corporation. * All rights reserved. * * Based on the convexdecomposition library from * <http://codesuppository.googlecode.com> by John W. Ratcliff and Stan Melax. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace OpenSim.Region.Physics.ConvexDecompositionDotNet { public class float4x4 { public float4 x = new float4(); public float4 y = new float4(); public float4 z = new float4(); public float4 w = new float4(); public float4x4() { } public float4x4(float4 _x, float4 _y, float4 _z, float4 _w) { x = new float4(_x); y = new float4(_y); z = new float4(_z); w = new float4(_w); } public float4x4( float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13, float m20, float m21, float m22, float m23, float m30, float m31, float m32, float m33) { x = new float4(m00, m01, m02, m03); y = new float4(m10, m11, m12, m13); z = new float4(m20, m21, m22, m23); w = new float4(m30, m31, m32, m33); } public float4x4(float4x4 m) { x = new float4(m.x); y = new float4(m.y); z = new float4(m.z); w = new float4(m.w); } public float4 this[int i] { get { switch (i) { case 0: return x; case 1: return y; case 2: return z; case 3: return w; } throw new ArgumentOutOfRangeException(); } set { switch (i) { case 0: x = value; return; case 1: y = value; return; case 2: z = value; return; case 3: w = value; return; } throw new ArgumentOutOfRangeException(); } } public override int GetHashCode() { return x.GetHashCode() ^ y.GetHashCode() ^ z.GetHashCode() ^ w.GetHashCode(); } public override bool Equals(object obj) { float4x4 m = obj as float4x4; if (m == null) return false; return this == m; } public static float4x4 operator *(float4x4 a, float4x4 b) { return new float4x4(a.x * b, a.y * b, a.z * b, a.w * b); } public static bool operator ==(float4x4 a, float4x4 b) { return (a.x == b.x && a.y == b.y && a.z == b.z && a.w == b.w); } public static bool operator !=(float4x4 a, float4x4 b) { return !(a == b); } public static float4x4 Inverse(float4x4 m) { float4x4 d = new float4x4(); //float dst = d.x.x; float[] tmp = new float[12]; // temp array for pairs float[] src = new float[16]; // array of transpose source matrix float det; // determinant // transpose matrix for (int i = 0; i < 4; i++) { src[i] = m[i].x; src[i + 4] = m[i].y; src[i + 8] = m[i].z; src[i + 12] = m[i].w; } // calculate pairs for first 8 elements (cofactors) tmp[0] = src[10] * src[15]; tmp[1] = src[11] * src[14]; tmp[2] = src[9] * src[15]; tmp[3] = src[11] * src[13]; tmp[4] = src[9] * src[14]; tmp[5] = src[10] * src[13]; tmp[6] = src[8] * src[15]; tmp[7] = src[11] * src[12]; tmp[8] = src[8] * src[14]; tmp[9] = src[10] * src[12]; tmp[10] = src[8] * src[13]; tmp[11] = src[9] * src[12]; // calculate first 8 elements (cofactors) d.x.x = tmp[0]*src[5] + tmp[3]*src[6] + tmp[4]*src[7]; d.x.x -= tmp[1]*src[5] + tmp[2]*src[6] + tmp[5]*src[7]; d.x.y = tmp[1]*src[4] + tmp[6]*src[6] + tmp[9]*src[7]; d.x.y -= tmp[0]*src[4] + tmp[7]*src[6] + tmp[8]*src[7]; d.x.z = tmp[2]*src[4] + tmp[7]*src[5] + tmp[10]*src[7]; d.x.z -= tmp[3]*src[4] + tmp[6]*src[5] + tmp[11]*src[7]; d.x.w = tmp[5]*src[4] + tmp[8]*src[5] + tmp[11]*src[6]; d.x.w -= tmp[4]*src[4] + tmp[9]*src[5] + tmp[10]*src[6]; d.y.x = tmp[1]*src[1] + tmp[2]*src[2] + tmp[5]*src[3]; d.y.x -= tmp[0]*src[1] + tmp[3]*src[2] + tmp[4]*src[3]; d.y.y = tmp[0]*src[0] + tmp[7]*src[2] + tmp[8]*src[3]; d.y.y -= tmp[1]*src[0] + tmp[6]*src[2] + tmp[9]*src[3]; d.y.z = tmp[3]*src[0] + tmp[6]*src[1] + tmp[11]*src[3]; d.y.z -= tmp[2]*src[0] + tmp[7]*src[1] + tmp[10]*src[3]; d.y.w = tmp[4]*src[0] + tmp[9]*src[1] + tmp[10]*src[2]; d.y.w -= tmp[5]*src[0] + tmp[8]*src[1] + tmp[11]*src[2]; // calculate pairs for second 8 elements (cofactors) tmp[0] = src[2]*src[7]; tmp[1] = src[3]*src[6]; tmp[2] = src[1]*src[7]; tmp[3] = src[3]*src[5]; tmp[4] = src[1]*src[6]; tmp[5] = src[2]*src[5]; tmp[6] = src[0]*src[7]; tmp[7] = src[3]*src[4]; tmp[8] = src[0]*src[6]; tmp[9] = src[2]*src[4]; tmp[10] = src[0]*src[5]; tmp[11] = src[1]*src[4]; // calculate second 8 elements (cofactors) d.z.x = tmp[0]*src[13] + tmp[3]*src[14] + tmp[4]*src[15]; d.z.x -= tmp[1]*src[13] + tmp[2]*src[14] + tmp[5]*src[15]; d.z.y = tmp[1]*src[12] + tmp[6]*src[14] + tmp[9]*src[15]; d.z.y -= tmp[0]*src[12] + tmp[7]*src[14] + tmp[8]*src[15]; d.z.z = tmp[2]*src[12] + tmp[7]*src[13] + tmp[10]*src[15]; d.z.z -= tmp[3]*src[12] + tmp[6]*src[13] + tmp[11]*src[15]; d.z.w = tmp[5]*src[12] + tmp[8]*src[13] + tmp[11]*src[14]; d.z.w-= tmp[4]*src[12] + tmp[9]*src[13] + tmp[10]*src[14]; d.w.x = tmp[2]*src[10] + tmp[5]*src[11] + tmp[1]*src[9]; d.w.x-= tmp[4]*src[11] + tmp[0]*src[9] + tmp[3]*src[10]; d.w.y = tmp[8]*src[11] + tmp[0]*src[8] + tmp[7]*src[10]; d.w.y-= tmp[6]*src[10] + tmp[9]*src[11] + tmp[1]*src[8]; d.w.z = tmp[6]*src[9] + tmp[11]*src[11] + tmp[3]*src[8]; d.w.z-= tmp[10]*src[11] + tmp[2]*src[8] + tmp[7]*src[9]; d.w.w = tmp[10]*src[10] + tmp[4]*src[8] + tmp[9]*src[9]; d.w.w-= tmp[8]*src[9] + tmp[11]*src[10] + tmp[5]*src[8]; // calculate determinant det = src[0] * d.x.x + src[1] * d.x.y + src[2] * d.x.z + src[3] * d.x.w; // calculate matrix inverse det = 1/det; for (int j = 0; j < 4; j++) d[j] *= det; return d; } public static float4x4 MatrixRigidInverse(float4x4 m) { float4x4 trans_inverse = MatrixTranslation(-m.w.xyz()); float4x4 rot = new float4x4(m); rot.w = new float4(0f, 0f, 0f, 1f); return trans_inverse * MatrixTranspose(rot); } public static float4x4 MatrixTranspose(float4x4 m) { return new float4x4(m.x.x, m.y.x, m.z.x, m.w.x, m.x.y, m.y.y, m.z.y, m.w.y, m.x.z, m.y.z, m.z.z, m.w.z, m.x.w, m.y.w, m.z.w, m.w.w); } public static float4x4 MatrixPerspectiveFov(float fovy, float aspect, float zn, float zf) { float h = 1.0f / (float)Math.Tan(fovy / 2.0f); // view space height float w = h / aspect; // view space width return new float4x4(w, 0, 0, 0, 0, h, 0, 0, 0, 0, zf / (zn - zf), -1, 0, 0, zn * zf / (zn - zf), 0); } public static float4x4 MatrixTranslation(float3 t) { return new float4x4(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, t.x, t.y, t.z, 1); } public static float4x4 MatrixRotationZ(float angle_radians) { float s = (float)Math.Sin(angle_radians); float c = (float)Math.Cos(angle_radians); return new float4x4(c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); } public static float4x4 MatrixLookAt(float3 eye, float3 at, float3 up) { float4x4 m = new float4x4(); m.w.w = 1.0f; m.w.setxyz(eye); m.z.setxyz(float3.normalize(eye - at)); m.x.setxyz(float3.normalize(float3.cross(up, m.z.xyz()))); m.y.setxyz(float3.cross(m.z.xyz(), m.x.xyz())); return MatrixRigidInverse(m); } public static float4x4 MatrixFromQuatVec(Quaternion q, float3 v) { // builds a 4x4 transformation matrix based on orientation q and translation v float qx2 = q.x * q.x; float qy2 = q.y * q.y; float qz2 = q.z * q.z; float qxqy = q.x * q.y; float qxqz = q.x * q.z; float qxqw = q.x * q.w; float qyqz = q.y * q.z; float qyqw = q.y * q.w; float qzqw = q.z * q.w; return new float4x4( 1 - 2 * (qy2 + qz2), 2 * (qxqy + qzqw), 2 * (qxqz - qyqw), 0, 2 * (qxqy - qzqw), 1 - 2 * (qx2 + qz2), 2 * (qyqz + qxqw), 0, 2 * (qxqz + qyqw), 2 * (qyqz - qxqw), 1 - 2 * (qx2 + qy2), 0, v.x, v.y, v.z, 1.0f); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Packaging; using System.Linq; using System.Net.Mime; using System.Text; using System.Xml.Serialization; namespace ClosedXML.Tests { public static class PackageHelper { public static void WriteXmlPart(Package package, Uri uri, object content, XmlSerializer serializer) { if (package.PartExists(uri)) { package.DeletePart(uri); } PackagePart part = package.CreatePart(uri, MediaTypeNames.Text.Xml, CompressionOption.Fast); using (Stream stream = part.GetStream()) { serializer.Serialize(stream, content); } } public static object ReadXmlPart(Package package, Uri uri, XmlSerializer serializer) { if (!package.PartExists(uri)) { throw new ApplicationException(string.Format("Package part '{0}' doesn't exists!", uri.OriginalString)); } PackagePart part = package.GetPart(uri); using (Stream stream = part.GetStream()) { return serializer.Deserialize(stream); } } public static void WriteBinaryPart(Package package, Uri uri, Stream content) { if (package.PartExists(uri)) { package.DeletePart(uri); } PackagePart part = package.CreatePart(uri, MediaTypeNames.Application.Octet, CompressionOption.Fast); using (Stream stream = part.GetStream()) { StreamHelper.StreamToStreamAppend(content, stream); } } /// <summary> /// Returns part's stream /// </summary> /// <param name="package"></param> /// <param name="uri"></param> /// <returns></returns> public static Stream ReadBinaryPart(Package package, Uri uri) { if (!package.PartExists(uri)) { throw new ApplicationException("Package part doesn't exists!"); } PackagePart part = package.GetPart(uri); return part.GetStream(); } public static void CopyPart(Uri uri, Package source, Package dest) { CopyPart(uri, source, dest, true); } public static void CopyPart(Uri uri, Package source, Package dest, bool overwrite) { #region Check if (ReferenceEquals(uri, null)) { throw new ArgumentNullException("uri"); } if (ReferenceEquals(source, null)) { throw new ArgumentNullException("source"); } if (ReferenceEquals(dest, null)) { throw new ArgumentNullException("dest"); } #endregion Check if (dest.PartExists(uri)) { if (!overwrite) { throw new ArgumentException("Specified part already exists", "uri"); } dest.DeletePart(uri); } PackagePart sourcePart = source.GetPart(uri); PackagePart destPart = dest.CreatePart(uri, sourcePart.ContentType, sourcePart.CompressionOption); using (Stream sourceStream = sourcePart.GetStream()) { using (Stream destStream = destPart.GetStream()) { StreamHelper.StreamToStreamAppend(sourceStream, destStream); } } } public static void WritePart<T>(Package package, PackagePartDescriptor descriptor, T content, Action<Stream, T> serializeAction) { #region Check if (ReferenceEquals(package, null)) { throw new ArgumentNullException("package"); } if (ReferenceEquals(descriptor, null)) { throw new ArgumentNullException("descriptor"); } if (ReferenceEquals(serializeAction, null)) { throw new ArgumentNullException("serializeAction"); } #endregion Check if (package.PartExists(descriptor.Uri)) { package.DeletePart(descriptor.Uri); } PackagePart part = package.CreatePart(descriptor.Uri, descriptor.ContentType, descriptor.CompressOption); using (Stream stream = part.GetStream()) { serializeAction(stream, content); } } public static void WritePart(Package package, PackagePartDescriptor descriptor, Action<Stream> serializeAction) { #region Check if (ReferenceEquals(package, null)) { throw new ArgumentNullException("package"); } if (ReferenceEquals(descriptor, null)) { throw new ArgumentNullException("descriptor"); } if (ReferenceEquals(serializeAction, null)) { throw new ArgumentNullException("serializeAction"); } #endregion Check if (package.PartExists(descriptor.Uri)) { package.DeletePart(descriptor.Uri); } PackagePart part = package.CreatePart(descriptor.Uri, descriptor.ContentType, descriptor.CompressOption); using (Stream stream = part.GetStream()) { serializeAction(stream); } } public static T ReadPart<T>(Package package, Uri uri, Func<Stream, T> deserializeFunc) { #region Check if (ReferenceEquals(package, null)) { throw new ArgumentNullException("package"); } if (ReferenceEquals(uri, null)) { throw new ArgumentNullException("uri"); } if (ReferenceEquals(deserializeFunc, null)) { throw new ArgumentNullException("deserializeFunc"); } #endregion Check if (!package.PartExists(uri)) { throw new ApplicationException(string.Format("Package part '{0}' doesn't exists!", uri.OriginalString)); } PackagePart part = package.GetPart(uri); using (Stream stream = part.GetStream()) { return deserializeFunc(stream); } } public static void ReadPart(Package package, Uri uri, Action<Stream> deserializeAction) { #region Check if (ReferenceEquals(package, null)) { throw new ArgumentNullException("package"); } if (ReferenceEquals(uri, null)) { throw new ArgumentNullException("uri"); } if (ReferenceEquals(deserializeAction, null)) { throw new ArgumentNullException("deserializeAction"); } #endregion Check if (!package.PartExists(uri)) { throw new ApplicationException(string.Format("Package part '{0}' doesn't exists!", uri.OriginalString)); } PackagePart part = package.GetPart(uri); using (Stream stream = part.GetStream()) { deserializeAction(stream); } } public static bool TryReadPart(Package package, Uri uri, Action<Stream> deserializeAction) { #region Check if (ReferenceEquals(package, null)) { throw new ArgumentNullException("package"); } if (ReferenceEquals(uri, null)) { throw new ArgumentNullException("uri"); } if (ReferenceEquals(deserializeAction, null)) { throw new ArgumentNullException("deserializeAction"); } #endregion Check if (!package.PartExists(uri)) { return false; } PackagePart part = package.GetPart(uri); using (Stream stream = part.GetStream()) { deserializeAction(stream); } return true; } /// <summary> /// Compare to packages by parts like streams /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <param name="compareToFirstDifference"></param> /// <param name="excludeMethod"></param> /// <param name="message"></param> /// <returns></returns> public static bool Compare(Package left, Package right, bool compareToFirstDifference, out string message) { return Compare(left, right, compareToFirstDifference, null, out message); } /// <summary> /// Compare to packages by parts like streams /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <param name="compareToFirstDifference"></param> /// <param name="excludeMethod"></param> /// <param name="message"></param> /// <returns></returns> public static bool Compare(Package left, Package right, bool compareToFirstDifference, Func<Uri, bool> excludeMethod, out string message) { #region Check if (left == null) { throw new ArgumentNullException("left"); } if (right == null) { throw new ArgumentNullException("right"); } #endregion Check excludeMethod = excludeMethod ?? (uri => false); PackagePartCollection leftParts = left.GetParts(); PackagePartCollection rightParts = right.GetParts(); var pairs = new Dictionary<Uri, PartPair>(); foreach (PackagePart part in leftParts) { if (excludeMethod(part.Uri)) { continue; } pairs.Add(part.Uri, new PartPair(part.Uri, CompareStatus.OnlyOnLeft)); } foreach (PackagePart part in rightParts) { if (excludeMethod(part.Uri)) { continue; } if (pairs.TryGetValue(part.Uri, out PartPair pair)) { pair.Status = CompareStatus.Equal; } else { pairs.Add(part.Uri, new PartPair(part.Uri, CompareStatus.OnlyOnRight)); } } if (compareToFirstDifference && pairs.Any(pair => pair.Value.Status != CompareStatus.Equal)) { goto EXIT; } foreach (PartPair pair in pairs.Values) { if (pair.Status != CompareStatus.Equal) { continue; } var leftPart = left.GetPart(pair.Uri); var rightPart = right.GetPart(pair.Uri); using (Stream leftPackagePartStream = leftPart.GetStream(FileMode.Open, FileAccess.Read)) using (Stream rightPackagePartStream = rightPart.GetStream(FileMode.Open, FileAccess.Read)) using (var leftMemoryStream = new MemoryStream()) using (var rightMemoryStream = new MemoryStream()) { leftPackagePartStream.CopyTo(leftMemoryStream); rightPackagePartStream.CopyTo(rightMemoryStream); leftMemoryStream.Seek(0, SeekOrigin.Begin); rightMemoryStream.Seek(0, SeekOrigin.Begin); bool stripColumnWidthsFromSheet = TestHelper.StripColumnWidths && leftPart.ContentType == @"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml" && rightPart.ContentType == @"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"; var tuple1 = new Tuple<Uri, Stream>(pair.Uri, leftMemoryStream); var tuple2 = new Tuple<Uri, Stream>(pair.Uri, rightMemoryStream); if (!StreamHelper.Compare(tuple1, tuple2, stripColumnWidthsFromSheet)) { pair.Status = CompareStatus.NonEqual; if (compareToFirstDifference) { goto EXIT; } } } } EXIT: List<PartPair> sortedPairs = pairs.Values.ToList(); sortedPairs.Sort((one, other) => one.Uri.OriginalString.CompareTo(other.Uri.OriginalString)); var sbuilder = new StringBuilder(); foreach (PartPair pair in sortedPairs) { if (pair.Status == CompareStatus.Equal) { continue; } sbuilder.AppendFormat("{0} :{1}", pair.Uri, pair.Status); sbuilder.AppendLine(); } message = sbuilder.ToString(); return message.Length == 0; } #region Nested type: PackagePartDescriptor public sealed class PackagePartDescriptor { #region Private fields [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly CompressionOption _compressOption; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly string _contentType; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly Uri _uri; #endregion Private fields #region Constructor /// <summary> /// Instance constructor /// </summary> /// <param name="uri">Part uri</param> /// <param name="contentType">Content type from <see cref="MediaTypeNames" /></param> /// <param name="compressOption"></param> public PackagePartDescriptor(Uri uri, string contentType, CompressionOption compressOption) { #region Check if (ReferenceEquals(uri, null)) { throw new ArgumentNullException("uri"); } if (string.IsNullOrEmpty(contentType)) { throw new ArgumentNullException("contentType"); } #endregion Check _uri = uri; _contentType = contentType; _compressOption = compressOption; } #endregion Constructor #region Public properties public Uri Uri { [DebuggerStepThrough] get { return _uri; } } public string ContentType { [DebuggerStepThrough] get { return _contentType; } } public CompressionOption CompressOption { [DebuggerStepThrough] get { return _compressOption; } } #endregion Public properties #region Public methods public override string ToString() { return string.Format("Uri:{0} ContentType: {1}, Compression: {2}", _uri, _contentType, _compressOption); } #endregion Public methods } #endregion Nested type: PackagePartDescriptor #region Nested type: CompareStatus private enum CompareStatus { OnlyOnLeft, OnlyOnRight, Equal, NonEqual } #endregion Nested type: CompareStatus #region Nested type: PartPair private sealed class PartPair { #region Private fields [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly Uri _uri; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private CompareStatus _status; #endregion Private fields #region Constructor public PartPair(Uri uri, CompareStatus status) { _uri = uri; _status = status; } #endregion Constructor #region Public properties public Uri Uri { [DebuggerStepThrough] get { return _uri; } } public CompareStatus Status { [DebuggerStepThrough] get { return _status; } [DebuggerStepThrough] set { _status = value; } } #endregion Public properties } #endregion Nested type: PartPair //-- } }
// 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.Runtime.InteropServices; public enum TestEnum { red = 1, green = 2, blue = 4, } public class AA { public bool[][,][, ,][][][][] m_abField1; public static float m_fStatic1; public static ushort Static1(ref char[, ,] param1, ref byte[, ,] param2, ulong param3, bool[, ,] param4) { short local1 = App.m_shFwd1; while (App.m_bFwd2) { object local2 = ((object)(TestEnum.red)); byte local3 = ((byte)(88u)); long local4 = App.m_lFwd3; short local5 = App.m_shFwd1; try { byte local6 = ((byte)(37u)); local6 = (local6 += local3); } catch (InvalidOperationException) { sbyte[, ,][][][] local7 = (new sbyte[89u, 48u, 47u][][][]); ulong local8 = ((ulong)(67u)); #pragma warning disable 1717 local3 = (local3 = local3); AA.m_fStatic1 = AA.m_fStatic1; #pragma warning restore 1717 } do { AA.m_fStatic1 = (45.0f + local4); try { goto label1; } catch (NullReferenceException) { param2[109, 35, 92] = (local3 += local3); } label1: do { #pragma warning disable 1717 AA.m_fStatic1 *= (AA.m_fStatic1 = AA.m_fStatic1); #pragma warning restore 1717 do { } while (((bool)(local2))); } while (((bool)(local2))); } while (((bool)(local2))); local5 += local1; } for (App.m_sbyFwd4 = ((sbyte)(local1)); App.m_bFwd2; local1 *= (local1 -= local1) ) { } param1[74, 65, ((int)(AA.m_fStatic1))] = '\x30'; return ((ushort)(33u)); } public static uint Static2(String[,] param1, double param2, ref long param3) { for (App.m_iFwd5 -= 20; (87.0 == param2); App.m_chFwd6 /= '\x2e') { Array[,][] local9 = (new Array[36u, 24u][]); char local10 = ((char)(121)); bool local11 = false; String local12 = "120"; String local13 = "110"; try { ushort[,] local14 = (new ushort[80u, 97u]); sbyte local15 = Convert.ToSByte('\x72'); ushort local16 = Convert.ToUInt16(56.0); param1[((int)(param2)), 17] = "35"; while (local11) { AA.Static1( ref App.m_achFwd7, ref App.m_abyFwd8, App.m_ulFwd9, (new bool[20u, 47u, 26u])); if (local11) try { throw new InvalidOperationException(); } catch (NullReferenceException) { continue; } #pragma warning disable 1717 local11 = local11; #pragma warning restore 1717 } } finally { do { } while ((local11 || true)); local10 = '\x11'; do { } while (local11); } if (local11) return 93u; continue; } try { } catch (Exception) { } param1[106, ((int)('\x40'))] = "34"; return 17u; } public static byte Static3(ref byte param1, ref char param2, ref char[,][,][, ,] param3, ref ulong param4, double param5, TestEnum[, ,] param6, sbyte param7, ulong[, , ,][, ,][, ,] param8) { return param1; } public static double[, ,] Static4(Array[][, ,] param1, long param2, ushort param3 , ref Array param4, float[][] param5, ref byte[] param6, float[,] param7, ref TestEnum param8) { double[][,] local17 = (new double[101u][,]); int[,] local18 = (new int[85u, 101u]); ushort local19 = ((ushort)(77.0f)); return (new double[48u, 34u, 29u]); } public static sbyte[][,] Static5(double[] param1, ref char param2, ref object[,] param3, ushort param4, bool[][] param5, ref float param6, uint[, ,][] param7, long param8) { AA.m_fStatic1 /= AA.m_fStatic1; try { float local20 = ((float)(50)); double[,] local21 = (new double[91u, 31u]); TestEnum[, ,] local22 = (new TestEnum[69u, 7u, 94u]); for (param2 += '\x6d'; Convert.ToBoolean(AA.m_fStatic1); App.m_uFwd10 /= AA. Static2((new String[36u, 114u]), 48.0, ref param8)) { byte[][][, , ,][, ,] local23 = new byte[][][,,,][,,]{(new byte[36u][,,,][,,]), (new byte[85u][,,,][,,]), (new byte[77u][,,,][,,]), new byte[][,,,][,,]{ (new byte[122u, 118u, 41u, 13u][,,]), (new byte[20u, 126u, 99u, 44u][,,]), (new byte[18u, 96u, 14u, 125u][,,]) }, (new byte[37u][,,,][,,]) }; sbyte[,][, ,][,][, ,][][, , ,] local24 = (new sbyte[66u, 74u][, ,][,][,,][][,,,]) ; TestEnum[,] local25 = (new TestEnum[112u, 103u]); String[,] local26 = (new String[114u, 47u]); goto label2; } goto label3; } finally { ushort local27 = ((ushort)(17.0)); #pragma warning disable 1717 for (App.m_ulFwd9 *= ((ulong)(85.0)); Convert.ToBoolean(param8); param2 -= param2 ) { AA.m_fStatic1 += (param6 = param6); #pragma warning restore 1717 do { AA.Static3( ref App.m_byFwd11, ref param2, ref App.m_achFwd12, ref App.m_ulFwd9, (67.0 - param6), (new TestEnum[41u, 27u, 5u]), App.m_sbyFwd4, (new ulong[54u, 94u, 4u, 113u][, ,][,,])); try { while (App.m_bFwd2) { param7[123, 77, 111][63] -= AA.Static2((new String[113u, 113u]), 117.0, ref param8); } do { } while (App.m_bFwd2); for (param8 /= (param8 | param8); App.m_bFwd2; App.m_uFwd10 -= ((uint)(110.0)) ) { } } catch (Exception) { } param4 *= param4; } while (App.m_bFwd2); AA.m_fStatic1 /= AA.m_fStatic1; } } label3: label2: return new sbyte[][,] { (new sbyte[50u, 121u]), (new sbyte[59u, 10u]) }; } } [StructLayout(LayoutKind.Sequential)] public class App { static int Main() { try { Console.WriteLine("Testing AA::Static1"); AA.Static1( ref App.m_achFwd7, ref App.m_abyFwd8, App.m_ulFwd9, (new bool[2u, 84u, 69u])); } catch (Exception x) { Console.WriteLine("Exception handled: " + x.ToString()); } try { Console.WriteLine("Testing AA::Static2"); AA.Static2( (new String[13u, 8u]), 55.0, ref App.m_lFwd3); } catch (Exception x) { Console.WriteLine("Exception handled: " + x.ToString()); } try { Console.WriteLine("Testing AA::Static3"); AA.Static3( ref App.m_byFwd11, ref App.m_chFwd6, ref App.m_achFwd12, ref App.m_ulFwd9, 118.0, (new TestEnum[46u, 80u, 35u]), ((sbyte)(72)), (new ulong[97u, 36u, 52u, 126u][, ,][,,])); } catch (Exception x) { Console.WriteLine("Exception handled: " + x.ToString()); } try { Console.WriteLine("Testing AA::Static4"); AA.Static4( (new Array[80u][, ,]), ((long)(88)), ((ushort)(AA.m_fStatic1)), ref App.m_xFwd13, (new float[16u][]), ref App.m_abyFwd14, (new float[93u, 70u]), ref App.m_xFwd15); } catch (Exception x) { Console.WriteLine("Exception handled: " + x.ToString()); } try { Console.WriteLine("Testing AA::Static5"); AA.Static5( (new double[66u]), ref App.m_chFwd6, ref App.m_aobjFwd16, ((ushort)(119u)), new bool[][]{new bool[]{true, false, false }, new bool[]{true, true, true } , new bool[]{false, true }, (new bool[126u]), (new bool[4u]) }, ref AA.m_fStatic1, (new uint[52u, 87u, 34u][]), App.m_lFwd3); } catch (Exception x) { Console.WriteLine("Exception handled: " + x.ToString()); } Console.WriteLine("Passed."); return 100; } public static short m_shFwd1; public static bool m_bFwd2; public static long m_lFwd3; public static sbyte m_sbyFwd4; public static int m_iFwd5; public static char m_chFwd6; public static char[, ,] m_achFwd7; public static byte[, ,] m_abyFwd8; public static ulong m_ulFwd9; public static uint m_uFwd10; public static byte m_byFwd11; public static char[,][,][, ,] m_achFwd12; public static Array m_xFwd13; public static byte[] m_abyFwd14; public static TestEnum m_xFwd15; public static object[,] m_aobjFwd16; }
#if !DISABLE_PLAYFABCLIENT_API using PlayFab.ClientModels; namespace PlayFab.Events { public partial class PlayFabEvents { public event PlayFabResultEvent<LoginResult> OnLoginResultEvent; public event PlayFabRequestEvent<AcceptTradeRequest> OnAcceptTradeRequestEvent; public event PlayFabResultEvent<AcceptTradeResponse> OnAcceptTradeResultEvent; public event PlayFabRequestEvent<AddFriendRequest> OnAddFriendRequestEvent; public event PlayFabResultEvent<AddFriendResult> OnAddFriendResultEvent; public event PlayFabRequestEvent<AddGenericIDRequest> OnAddGenericIDRequestEvent; public event PlayFabResultEvent<AddGenericIDResult> OnAddGenericIDResultEvent; public event PlayFabRequestEvent<AddOrUpdateContactEmailRequest> OnAddOrUpdateContactEmailRequestEvent; public event PlayFabResultEvent<AddOrUpdateContactEmailResult> OnAddOrUpdateContactEmailResultEvent; public event PlayFabRequestEvent<AddSharedGroupMembersRequest> OnAddSharedGroupMembersRequestEvent; public event PlayFabResultEvent<AddSharedGroupMembersResult> OnAddSharedGroupMembersResultEvent; public event PlayFabRequestEvent<AddUsernamePasswordRequest> OnAddUsernamePasswordRequestEvent; public event PlayFabResultEvent<AddUsernamePasswordResult> OnAddUsernamePasswordResultEvent; public event PlayFabRequestEvent<AddUserVirtualCurrencyRequest> OnAddUserVirtualCurrencyRequestEvent; public event PlayFabResultEvent<ModifyUserVirtualCurrencyResult> OnAddUserVirtualCurrencyResultEvent; public event PlayFabRequestEvent<AndroidDevicePushNotificationRegistrationRequest> OnAndroidDevicePushNotificationRegistrationRequestEvent; public event PlayFabResultEvent<AndroidDevicePushNotificationRegistrationResult> OnAndroidDevicePushNotificationRegistrationResultEvent; public event PlayFabRequestEvent<AttributeInstallRequest> OnAttributeInstallRequestEvent; public event PlayFabResultEvent<AttributeInstallResult> OnAttributeInstallResultEvent; public event PlayFabRequestEvent<CancelTradeRequest> OnCancelTradeRequestEvent; public event PlayFabResultEvent<CancelTradeResponse> OnCancelTradeResultEvent; public event PlayFabRequestEvent<ConfirmPurchaseRequest> OnConfirmPurchaseRequestEvent; public event PlayFabResultEvent<ConfirmPurchaseResult> OnConfirmPurchaseResultEvent; public event PlayFabRequestEvent<ConsumeItemRequest> OnConsumeItemRequestEvent; public event PlayFabResultEvent<ConsumeItemResult> OnConsumeItemResultEvent; public event PlayFabRequestEvent<ConsumeXboxEntitlementsRequest> OnConsumeXboxEntitlementsRequestEvent; public event PlayFabResultEvent<ConsumeXboxEntitlementsResult> OnConsumeXboxEntitlementsResultEvent; public event PlayFabRequestEvent<CreateSharedGroupRequest> OnCreateSharedGroupRequestEvent; public event PlayFabResultEvent<CreateSharedGroupResult> OnCreateSharedGroupResultEvent; public event PlayFabRequestEvent<ExecuteCloudScriptRequest> OnExecuteCloudScriptRequestEvent; public event PlayFabResultEvent<ExecuteCloudScriptResult> OnExecuteCloudScriptResultEvent; public event PlayFabRequestEvent<GetAccountInfoRequest> OnGetAccountInfoRequestEvent; public event PlayFabResultEvent<GetAccountInfoResult> OnGetAccountInfoResultEvent; public event PlayFabRequestEvent<ListUsersCharactersRequest> OnGetAllUsersCharactersRequestEvent; public event PlayFabResultEvent<ListUsersCharactersResult> OnGetAllUsersCharactersResultEvent; public event PlayFabRequestEvent<GetCatalogItemsRequest> OnGetCatalogItemsRequestEvent; public event PlayFabResultEvent<GetCatalogItemsResult> OnGetCatalogItemsResultEvent; public event PlayFabRequestEvent<GetCharacterDataRequest> OnGetCharacterDataRequestEvent; public event PlayFabResultEvent<GetCharacterDataResult> OnGetCharacterDataResultEvent; public event PlayFabRequestEvent<GetCharacterInventoryRequest> OnGetCharacterInventoryRequestEvent; public event PlayFabResultEvent<GetCharacterInventoryResult> OnGetCharacterInventoryResultEvent; public event PlayFabRequestEvent<GetCharacterLeaderboardRequest> OnGetCharacterLeaderboardRequestEvent; public event PlayFabResultEvent<GetCharacterLeaderboardResult> OnGetCharacterLeaderboardResultEvent; public event PlayFabRequestEvent<GetCharacterDataRequest> OnGetCharacterReadOnlyDataRequestEvent; public event PlayFabResultEvent<GetCharacterDataResult> OnGetCharacterReadOnlyDataResultEvent; public event PlayFabRequestEvent<GetCharacterStatisticsRequest> OnGetCharacterStatisticsRequestEvent; public event PlayFabResultEvent<GetCharacterStatisticsResult> OnGetCharacterStatisticsResultEvent; public event PlayFabRequestEvent<GetContentDownloadUrlRequest> OnGetContentDownloadUrlRequestEvent; public event PlayFabResultEvent<GetContentDownloadUrlResult> OnGetContentDownloadUrlResultEvent; public event PlayFabRequestEvent<CurrentGamesRequest> OnGetCurrentGamesRequestEvent; public event PlayFabResultEvent<CurrentGamesResult> OnGetCurrentGamesResultEvent; public event PlayFabRequestEvent<GetFriendLeaderboardRequest> OnGetFriendLeaderboardRequestEvent; public event PlayFabResultEvent<GetLeaderboardResult> OnGetFriendLeaderboardResultEvent; public event PlayFabRequestEvent<GetFriendLeaderboardAroundPlayerRequest> OnGetFriendLeaderboardAroundPlayerRequestEvent; public event PlayFabResultEvent<GetFriendLeaderboardAroundPlayerResult> OnGetFriendLeaderboardAroundPlayerResultEvent; public event PlayFabRequestEvent<GetFriendsListRequest> OnGetFriendsListRequestEvent; public event PlayFabResultEvent<GetFriendsListResult> OnGetFriendsListResultEvent; public event PlayFabRequestEvent<GameServerRegionsRequest> OnGetGameServerRegionsRequestEvent; public event PlayFabResultEvent<GameServerRegionsResult> OnGetGameServerRegionsResultEvent; public event PlayFabRequestEvent<GetLeaderboardRequest> OnGetLeaderboardRequestEvent; public event PlayFabResultEvent<GetLeaderboardResult> OnGetLeaderboardResultEvent; public event PlayFabRequestEvent<GetLeaderboardAroundCharacterRequest> OnGetLeaderboardAroundCharacterRequestEvent; public event PlayFabResultEvent<GetLeaderboardAroundCharacterResult> OnGetLeaderboardAroundCharacterResultEvent; public event PlayFabRequestEvent<GetLeaderboardAroundPlayerRequest> OnGetLeaderboardAroundPlayerRequestEvent; public event PlayFabResultEvent<GetLeaderboardAroundPlayerResult> OnGetLeaderboardAroundPlayerResultEvent; public event PlayFabRequestEvent<GetLeaderboardForUsersCharactersRequest> OnGetLeaderboardForUserCharactersRequestEvent; public event PlayFabResultEvent<GetLeaderboardForUsersCharactersResult> OnGetLeaderboardForUserCharactersResultEvent; public event PlayFabRequestEvent<GetPaymentTokenRequest> OnGetPaymentTokenRequestEvent; public event PlayFabResultEvent<GetPaymentTokenResult> OnGetPaymentTokenResultEvent; public event PlayFabRequestEvent<GetPhotonAuthenticationTokenRequest> OnGetPhotonAuthenticationTokenRequestEvent; public event PlayFabResultEvent<GetPhotonAuthenticationTokenResult> OnGetPhotonAuthenticationTokenResultEvent; public event PlayFabRequestEvent<GetPlayerCombinedInfoRequest> OnGetPlayerCombinedInfoRequestEvent; public event PlayFabResultEvent<GetPlayerCombinedInfoResult> OnGetPlayerCombinedInfoResultEvent; public event PlayFabRequestEvent<GetPlayerProfileRequest> OnGetPlayerProfileRequestEvent; public event PlayFabResultEvent<GetPlayerProfileResult> OnGetPlayerProfileResultEvent; public event PlayFabRequestEvent<GetPlayerSegmentsRequest> OnGetPlayerSegmentsRequestEvent; public event PlayFabResultEvent<GetPlayerSegmentsResult> OnGetPlayerSegmentsResultEvent; public event PlayFabRequestEvent<GetPlayerStatisticsRequest> OnGetPlayerStatisticsRequestEvent; public event PlayFabResultEvent<GetPlayerStatisticsResult> OnGetPlayerStatisticsResultEvent; public event PlayFabRequestEvent<GetPlayerStatisticVersionsRequest> OnGetPlayerStatisticVersionsRequestEvent; public event PlayFabResultEvent<GetPlayerStatisticVersionsResult> OnGetPlayerStatisticVersionsResultEvent; public event PlayFabRequestEvent<GetPlayerTagsRequest> OnGetPlayerTagsRequestEvent; public event PlayFabResultEvent<GetPlayerTagsResult> OnGetPlayerTagsResultEvent; public event PlayFabRequestEvent<GetPlayerTradesRequest> OnGetPlayerTradesRequestEvent; public event PlayFabResultEvent<GetPlayerTradesResponse> OnGetPlayerTradesResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromFacebookIDsRequest> OnGetPlayFabIDsFromFacebookIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromFacebookIDsResult> OnGetPlayFabIDsFromFacebookIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromFacebookInstantGamesIdsRequest> OnGetPlayFabIDsFromFacebookInstantGamesIdsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromFacebookInstantGamesIdsResult> OnGetPlayFabIDsFromFacebookInstantGamesIdsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromGameCenterIDsRequest> OnGetPlayFabIDsFromGameCenterIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromGameCenterIDsResult> OnGetPlayFabIDsFromGameCenterIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromGenericIDsRequest> OnGetPlayFabIDsFromGenericIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromGenericIDsResult> OnGetPlayFabIDsFromGenericIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromGoogleIDsRequest> OnGetPlayFabIDsFromGoogleIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromGoogleIDsResult> OnGetPlayFabIDsFromGoogleIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromKongregateIDsRequest> OnGetPlayFabIDsFromKongregateIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromKongregateIDsResult> OnGetPlayFabIDsFromKongregateIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromNintendoSwitchDeviceIdsRequest> OnGetPlayFabIDsFromNintendoSwitchDeviceIdsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromNintendoSwitchDeviceIdsResult> OnGetPlayFabIDsFromNintendoSwitchDeviceIdsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromSteamIDsRequest> OnGetPlayFabIDsFromSteamIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromSteamIDsResult> OnGetPlayFabIDsFromSteamIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromTwitchIDsRequest> OnGetPlayFabIDsFromTwitchIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromTwitchIDsResult> OnGetPlayFabIDsFromTwitchIDsResultEvent; public event PlayFabRequestEvent<GetPlayFabIDsFromXboxLiveIDsRequest> OnGetPlayFabIDsFromXboxLiveIDsRequestEvent; public event PlayFabResultEvent<GetPlayFabIDsFromXboxLiveIDsResult> OnGetPlayFabIDsFromXboxLiveIDsResultEvent; public event PlayFabRequestEvent<GetPublisherDataRequest> OnGetPublisherDataRequestEvent; public event PlayFabResultEvent<GetPublisherDataResult> OnGetPublisherDataResultEvent; public event PlayFabRequestEvent<GetPurchaseRequest> OnGetPurchaseRequestEvent; public event PlayFabResultEvent<GetPurchaseResult> OnGetPurchaseResultEvent; public event PlayFabRequestEvent<GetSharedGroupDataRequest> OnGetSharedGroupDataRequestEvent; public event PlayFabResultEvent<GetSharedGroupDataResult> OnGetSharedGroupDataResultEvent; public event PlayFabRequestEvent<GetStoreItemsRequest> OnGetStoreItemsRequestEvent; public event PlayFabResultEvent<GetStoreItemsResult> OnGetStoreItemsResultEvent; public event PlayFabRequestEvent<GetTimeRequest> OnGetTimeRequestEvent; public event PlayFabResultEvent<GetTimeResult> OnGetTimeResultEvent; public event PlayFabRequestEvent<GetTitleDataRequest> OnGetTitleDataRequestEvent; public event PlayFabResultEvent<GetTitleDataResult> OnGetTitleDataResultEvent; public event PlayFabRequestEvent<GetTitleNewsRequest> OnGetTitleNewsRequestEvent; public event PlayFabResultEvent<GetTitleNewsResult> OnGetTitleNewsResultEvent; public event PlayFabRequestEvent<GetTitlePublicKeyRequest> OnGetTitlePublicKeyRequestEvent; public event PlayFabResultEvent<GetTitlePublicKeyResult> OnGetTitlePublicKeyResultEvent; public event PlayFabRequestEvent<GetTradeStatusRequest> OnGetTradeStatusRequestEvent; public event PlayFabResultEvent<GetTradeStatusResponse> OnGetTradeStatusResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnGetUserDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnGetUserDataResultEvent; public event PlayFabRequestEvent<GetUserInventoryRequest> OnGetUserInventoryRequestEvent; public event PlayFabResultEvent<GetUserInventoryResult> OnGetUserInventoryResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnGetUserPublisherDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnGetUserPublisherDataResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnGetUserPublisherReadOnlyDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnGetUserPublisherReadOnlyDataResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnGetUserReadOnlyDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnGetUserReadOnlyDataResultEvent; public event PlayFabRequestEvent<GetWindowsHelloChallengeRequest> OnGetWindowsHelloChallengeRequestEvent; public event PlayFabResultEvent<GetWindowsHelloChallengeResponse> OnGetWindowsHelloChallengeResultEvent; public event PlayFabRequestEvent<GrantCharacterToUserRequest> OnGrantCharacterToUserRequestEvent; public event PlayFabResultEvent<GrantCharacterToUserResult> OnGrantCharacterToUserResultEvent; public event PlayFabRequestEvent<LinkAndroidDeviceIDRequest> OnLinkAndroidDeviceIDRequestEvent; public event PlayFabResultEvent<LinkAndroidDeviceIDResult> OnLinkAndroidDeviceIDResultEvent; public event PlayFabRequestEvent<LinkCustomIDRequest> OnLinkCustomIDRequestEvent; public event PlayFabResultEvent<LinkCustomIDResult> OnLinkCustomIDResultEvent; public event PlayFabRequestEvent<LinkFacebookAccountRequest> OnLinkFacebookAccountRequestEvent; public event PlayFabResultEvent<LinkFacebookAccountResult> OnLinkFacebookAccountResultEvent; public event PlayFabRequestEvent<LinkFacebookInstantGamesIdRequest> OnLinkFacebookInstantGamesIdRequestEvent; public event PlayFabResultEvent<LinkFacebookInstantGamesIdResult> OnLinkFacebookInstantGamesIdResultEvent; public event PlayFabRequestEvent<LinkGameCenterAccountRequest> OnLinkGameCenterAccountRequestEvent; public event PlayFabResultEvent<LinkGameCenterAccountResult> OnLinkGameCenterAccountResultEvent; public event PlayFabRequestEvent<LinkGoogleAccountRequest> OnLinkGoogleAccountRequestEvent; public event PlayFabResultEvent<LinkGoogleAccountResult> OnLinkGoogleAccountResultEvent; public event PlayFabRequestEvent<LinkIOSDeviceIDRequest> OnLinkIOSDeviceIDRequestEvent; public event PlayFabResultEvent<LinkIOSDeviceIDResult> OnLinkIOSDeviceIDResultEvent; public event PlayFabRequestEvent<LinkKongregateAccountRequest> OnLinkKongregateRequestEvent; public event PlayFabResultEvent<LinkKongregateAccountResult> OnLinkKongregateResultEvent; public event PlayFabRequestEvent<LinkNintendoSwitchDeviceIdRequest> OnLinkNintendoSwitchDeviceIdRequestEvent; public event PlayFabResultEvent<LinkNintendoSwitchDeviceIdResult> OnLinkNintendoSwitchDeviceIdResultEvent; public event PlayFabRequestEvent<LinkOpenIdConnectRequest> OnLinkOpenIdConnectRequestEvent; public event PlayFabResultEvent<EmptyResult> OnLinkOpenIdConnectResultEvent; public event PlayFabRequestEvent<LinkSteamAccountRequest> OnLinkSteamAccountRequestEvent; public event PlayFabResultEvent<LinkSteamAccountResult> OnLinkSteamAccountResultEvent; public event PlayFabRequestEvent<LinkTwitchAccountRequest> OnLinkTwitchRequestEvent; public event PlayFabResultEvent<LinkTwitchAccountResult> OnLinkTwitchResultEvent; public event PlayFabRequestEvent<LinkWindowsHelloAccountRequest> OnLinkWindowsHelloRequestEvent; public event PlayFabResultEvent<LinkWindowsHelloAccountResponse> OnLinkWindowsHelloResultEvent; public event PlayFabRequestEvent<LinkXboxAccountRequest> OnLinkXboxAccountRequestEvent; public event PlayFabResultEvent<LinkXboxAccountResult> OnLinkXboxAccountResultEvent; public event PlayFabRequestEvent<LoginWithAndroidDeviceIDRequest> OnLoginWithAndroidDeviceIDRequestEvent; public event PlayFabRequestEvent<LoginWithCustomIDRequest> OnLoginWithCustomIDRequestEvent; public event PlayFabRequestEvent<LoginWithEmailAddressRequest> OnLoginWithEmailAddressRequestEvent; public event PlayFabRequestEvent<LoginWithFacebookRequest> OnLoginWithFacebookRequestEvent; public event PlayFabRequestEvent<LoginWithFacebookInstantGamesIdRequest> OnLoginWithFacebookInstantGamesIdRequestEvent; public event PlayFabRequestEvent<LoginWithGameCenterRequest> OnLoginWithGameCenterRequestEvent; public event PlayFabRequestEvent<LoginWithGoogleAccountRequest> OnLoginWithGoogleAccountRequestEvent; public event PlayFabRequestEvent<LoginWithIOSDeviceIDRequest> OnLoginWithIOSDeviceIDRequestEvent; public event PlayFabRequestEvent<LoginWithKongregateRequest> OnLoginWithKongregateRequestEvent; public event PlayFabRequestEvent<LoginWithNintendoSwitchDeviceIdRequest> OnLoginWithNintendoSwitchDeviceIdRequestEvent; public event PlayFabRequestEvent<LoginWithOpenIdConnectRequest> OnLoginWithOpenIdConnectRequestEvent; public event PlayFabRequestEvent<LoginWithPlayFabRequest> OnLoginWithPlayFabRequestEvent; public event PlayFabRequestEvent<LoginWithSteamRequest> OnLoginWithSteamRequestEvent; public event PlayFabRequestEvent<LoginWithTwitchRequest> OnLoginWithTwitchRequestEvent; public event PlayFabRequestEvent<LoginWithWindowsHelloRequest> OnLoginWithWindowsHelloRequestEvent; public event PlayFabRequestEvent<LoginWithXboxRequest> OnLoginWithXboxRequestEvent; public event PlayFabRequestEvent<MatchmakeRequest> OnMatchmakeRequestEvent; public event PlayFabResultEvent<MatchmakeResult> OnMatchmakeResultEvent; public event PlayFabRequestEvent<OpenTradeRequest> OnOpenTradeRequestEvent; public event PlayFabResultEvent<OpenTradeResponse> OnOpenTradeResultEvent; public event PlayFabRequestEvent<PayForPurchaseRequest> OnPayForPurchaseRequestEvent; public event PlayFabResultEvent<PayForPurchaseResult> OnPayForPurchaseResultEvent; public event PlayFabRequestEvent<PurchaseItemRequest> OnPurchaseItemRequestEvent; public event PlayFabResultEvent<PurchaseItemResult> OnPurchaseItemResultEvent; public event PlayFabRequestEvent<RedeemCouponRequest> OnRedeemCouponRequestEvent; public event PlayFabResultEvent<RedeemCouponResult> OnRedeemCouponResultEvent; public event PlayFabRequestEvent<RegisterForIOSPushNotificationRequest> OnRegisterForIOSPushNotificationRequestEvent; public event PlayFabResultEvent<RegisterForIOSPushNotificationResult> OnRegisterForIOSPushNotificationResultEvent; public event PlayFabRequestEvent<RegisterPlayFabUserRequest> OnRegisterPlayFabUserRequestEvent; public event PlayFabResultEvent<RegisterPlayFabUserResult> OnRegisterPlayFabUserResultEvent; public event PlayFabRequestEvent<RegisterWithWindowsHelloRequest> OnRegisterWithWindowsHelloRequestEvent; public event PlayFabRequestEvent<RemoveContactEmailRequest> OnRemoveContactEmailRequestEvent; public event PlayFabResultEvent<RemoveContactEmailResult> OnRemoveContactEmailResultEvent; public event PlayFabRequestEvent<RemoveFriendRequest> OnRemoveFriendRequestEvent; public event PlayFabResultEvent<RemoveFriendResult> OnRemoveFriendResultEvent; public event PlayFabRequestEvent<RemoveGenericIDRequest> OnRemoveGenericIDRequestEvent; public event PlayFabResultEvent<RemoveGenericIDResult> OnRemoveGenericIDResultEvent; public event PlayFabRequestEvent<RemoveSharedGroupMembersRequest> OnRemoveSharedGroupMembersRequestEvent; public event PlayFabResultEvent<RemoveSharedGroupMembersResult> OnRemoveSharedGroupMembersResultEvent; public event PlayFabRequestEvent<DeviceInfoRequest> OnReportDeviceInfoRequestEvent; public event PlayFabResultEvent<EmptyResponse> OnReportDeviceInfoResultEvent; public event PlayFabRequestEvent<ReportPlayerClientRequest> OnReportPlayerRequestEvent; public event PlayFabResultEvent<ReportPlayerClientResult> OnReportPlayerResultEvent; public event PlayFabRequestEvent<RestoreIOSPurchasesRequest> OnRestoreIOSPurchasesRequestEvent; public event PlayFabResultEvent<RestoreIOSPurchasesResult> OnRestoreIOSPurchasesResultEvent; public event PlayFabRequestEvent<SendAccountRecoveryEmailRequest> OnSendAccountRecoveryEmailRequestEvent; public event PlayFabResultEvent<SendAccountRecoveryEmailResult> OnSendAccountRecoveryEmailResultEvent; public event PlayFabRequestEvent<SetFriendTagsRequest> OnSetFriendTagsRequestEvent; public event PlayFabResultEvent<SetFriendTagsResult> OnSetFriendTagsResultEvent; public event PlayFabRequestEvent<SetPlayerSecretRequest> OnSetPlayerSecretRequestEvent; public event PlayFabResultEvent<SetPlayerSecretResult> OnSetPlayerSecretResultEvent; public event PlayFabRequestEvent<StartGameRequest> OnStartGameRequestEvent; public event PlayFabResultEvent<StartGameResult> OnStartGameResultEvent; public event PlayFabRequestEvent<StartPurchaseRequest> OnStartPurchaseRequestEvent; public event PlayFabResultEvent<StartPurchaseResult> OnStartPurchaseResultEvent; public event PlayFabRequestEvent<SubtractUserVirtualCurrencyRequest> OnSubtractUserVirtualCurrencyRequestEvent; public event PlayFabResultEvent<ModifyUserVirtualCurrencyResult> OnSubtractUserVirtualCurrencyResultEvent; public event PlayFabRequestEvent<UnlinkAndroidDeviceIDRequest> OnUnlinkAndroidDeviceIDRequestEvent; public event PlayFabResultEvent<UnlinkAndroidDeviceIDResult> OnUnlinkAndroidDeviceIDResultEvent; public event PlayFabRequestEvent<UnlinkCustomIDRequest> OnUnlinkCustomIDRequestEvent; public event PlayFabResultEvent<UnlinkCustomIDResult> OnUnlinkCustomIDResultEvent; public event PlayFabRequestEvent<UnlinkFacebookAccountRequest> OnUnlinkFacebookAccountRequestEvent; public event PlayFabResultEvent<UnlinkFacebookAccountResult> OnUnlinkFacebookAccountResultEvent; public event PlayFabRequestEvent<UnlinkFacebookInstantGamesIdRequest> OnUnlinkFacebookInstantGamesIdRequestEvent; public event PlayFabResultEvent<UnlinkFacebookInstantGamesIdResult> OnUnlinkFacebookInstantGamesIdResultEvent; public event PlayFabRequestEvent<UnlinkGameCenterAccountRequest> OnUnlinkGameCenterAccountRequestEvent; public event PlayFabResultEvent<UnlinkGameCenterAccountResult> OnUnlinkGameCenterAccountResultEvent; public event PlayFabRequestEvent<UnlinkGoogleAccountRequest> OnUnlinkGoogleAccountRequestEvent; public event PlayFabResultEvent<UnlinkGoogleAccountResult> OnUnlinkGoogleAccountResultEvent; public event PlayFabRequestEvent<UnlinkIOSDeviceIDRequest> OnUnlinkIOSDeviceIDRequestEvent; public event PlayFabResultEvent<UnlinkIOSDeviceIDResult> OnUnlinkIOSDeviceIDResultEvent; public event PlayFabRequestEvent<UnlinkKongregateAccountRequest> OnUnlinkKongregateRequestEvent; public event PlayFabResultEvent<UnlinkKongregateAccountResult> OnUnlinkKongregateResultEvent; public event PlayFabRequestEvent<UnlinkNintendoSwitchDeviceIdRequest> OnUnlinkNintendoSwitchDeviceIdRequestEvent; public event PlayFabResultEvent<UnlinkNintendoSwitchDeviceIdResult> OnUnlinkNintendoSwitchDeviceIdResultEvent; public event PlayFabRequestEvent<UninkOpenIdConnectRequest> OnUnlinkOpenIdConnectRequestEvent; public event PlayFabResultEvent<EmptyResponse> OnUnlinkOpenIdConnectResultEvent; public event PlayFabRequestEvent<UnlinkSteamAccountRequest> OnUnlinkSteamAccountRequestEvent; public event PlayFabResultEvent<UnlinkSteamAccountResult> OnUnlinkSteamAccountResultEvent; public event PlayFabRequestEvent<UnlinkTwitchAccountRequest> OnUnlinkTwitchRequestEvent; public event PlayFabResultEvent<UnlinkTwitchAccountResult> OnUnlinkTwitchResultEvent; public event PlayFabRequestEvent<UnlinkWindowsHelloAccountRequest> OnUnlinkWindowsHelloRequestEvent; public event PlayFabResultEvent<UnlinkWindowsHelloAccountResponse> OnUnlinkWindowsHelloResultEvent; public event PlayFabRequestEvent<UnlinkXboxAccountRequest> OnUnlinkXboxAccountRequestEvent; public event PlayFabResultEvent<UnlinkXboxAccountResult> OnUnlinkXboxAccountResultEvent; public event PlayFabRequestEvent<UnlockContainerInstanceRequest> OnUnlockContainerInstanceRequestEvent; public event PlayFabResultEvent<UnlockContainerItemResult> OnUnlockContainerInstanceResultEvent; public event PlayFabRequestEvent<UnlockContainerItemRequest> OnUnlockContainerItemRequestEvent; public event PlayFabResultEvent<UnlockContainerItemResult> OnUnlockContainerItemResultEvent; public event PlayFabRequestEvent<UpdateAvatarUrlRequest> OnUpdateAvatarUrlRequestEvent; public event PlayFabResultEvent<EmptyResponse> OnUpdateAvatarUrlResultEvent; public event PlayFabRequestEvent<UpdateCharacterDataRequest> OnUpdateCharacterDataRequestEvent; public event PlayFabResultEvent<UpdateCharacterDataResult> OnUpdateCharacterDataResultEvent; public event PlayFabRequestEvent<UpdateCharacterStatisticsRequest> OnUpdateCharacterStatisticsRequestEvent; public event PlayFabResultEvent<UpdateCharacterStatisticsResult> OnUpdateCharacterStatisticsResultEvent; public event PlayFabRequestEvent<UpdatePlayerStatisticsRequest> OnUpdatePlayerStatisticsRequestEvent; public event PlayFabResultEvent<UpdatePlayerStatisticsResult> OnUpdatePlayerStatisticsResultEvent; public event PlayFabRequestEvent<UpdateSharedGroupDataRequest> OnUpdateSharedGroupDataRequestEvent; public event PlayFabResultEvent<UpdateSharedGroupDataResult> OnUpdateSharedGroupDataResultEvent; public event PlayFabRequestEvent<UpdateUserDataRequest> OnUpdateUserDataRequestEvent; public event PlayFabResultEvent<UpdateUserDataResult> OnUpdateUserDataResultEvent; public event PlayFabRequestEvent<UpdateUserDataRequest> OnUpdateUserPublisherDataRequestEvent; public event PlayFabResultEvent<UpdateUserDataResult> OnUpdateUserPublisherDataResultEvent; public event PlayFabRequestEvent<UpdateUserTitleDisplayNameRequest> OnUpdateUserTitleDisplayNameRequestEvent; public event PlayFabResultEvent<UpdateUserTitleDisplayNameResult> OnUpdateUserTitleDisplayNameResultEvent; public event PlayFabRequestEvent<ValidateAmazonReceiptRequest> OnValidateAmazonIAPReceiptRequestEvent; public event PlayFabResultEvent<ValidateAmazonReceiptResult> OnValidateAmazonIAPReceiptResultEvent; public event PlayFabRequestEvent<ValidateGooglePlayPurchaseRequest> OnValidateGooglePlayPurchaseRequestEvent; public event PlayFabResultEvent<ValidateGooglePlayPurchaseResult> OnValidateGooglePlayPurchaseResultEvent; public event PlayFabRequestEvent<ValidateIOSReceiptRequest> OnValidateIOSReceiptRequestEvent; public event PlayFabResultEvent<ValidateIOSReceiptResult> OnValidateIOSReceiptResultEvent; public event PlayFabRequestEvent<ValidateWindowsReceiptRequest> OnValidateWindowsStoreReceiptRequestEvent; public event PlayFabResultEvent<ValidateWindowsReceiptResult> OnValidateWindowsStoreReceiptResultEvent; public event PlayFabRequestEvent<WriteClientCharacterEventRequest> OnWriteCharacterEventRequestEvent; public event PlayFabResultEvent<WriteEventResponse> OnWriteCharacterEventResultEvent; public event PlayFabRequestEvent<WriteClientPlayerEventRequest> OnWritePlayerEventRequestEvent; public event PlayFabResultEvent<WriteEventResponse> OnWritePlayerEventResultEvent; public event PlayFabRequestEvent<WriteTitleEventRequest> OnWriteTitleEventRequestEvent; public event PlayFabResultEvent<WriteEventResponse> OnWriteTitleEventResultEvent; } } #endif
namespace AutoMapper { using System; using System.ComponentModel; using System.Linq.Expressions; /// <summary> /// Mapping configuration options for non-generic maps /// </summary> public interface IMappingExpression { /// <summary> /// Customize configuration for individual constructor parameter /// </summary> /// <param name="ctorParamName">Constructor parameter name</param> /// <param name="paramOptions">Options</param> /// <returns>Itself</returns> IMappingExpression ForCtorParam(string ctorParamName, Action<ICtorParamConfigurationExpression<object>> paramOptions); /// <summary> /// Create a type mapping from the destination to the source type, using the destination members as validation. /// </summary> /// <returns>Itself</returns> IMappingExpression ReverseMap(); /// <summary> /// Replace the original runtime instance with a new source instance. Useful when ORMs return proxy types with no relationships to runtime types. /// The returned source object will be mapped instead of what was supplied in the original source object. /// </summary> /// <param name="substituteFunc">Substitution function</param> /// <returns>New source object to map.</returns> IMappingExpression Substitute(Func<object, object> substituteFunc); /// <summary> /// Construct the destination object using the service locator /// </summary> /// <returns>Itself</returns> IMappingExpression ConstructUsingServiceLocator(); /// <summary> /// For self-referential types, limit recurse depth /// </summary> /// <param name="depth">Number of levels to limit to</param> /// <returns>Itself</returns> IMappingExpression MaxDepth(int depth); /// <summary> /// Supply a custom instantiation expression for the destination type for LINQ projection /// </summary> /// <param name="ctor">Callback to create the destination type given the source object</param> /// <returns>Itself</returns> IMappingExpression ConstructProjectionUsing(LambdaExpression ctor); /// <summary> /// Supply a custom instantiation function for the destination type, based on the entire resolution context /// </summary> /// <param name="ctor">Callback to create the destination type given the current resolution context</param> /// <returns>Itself</returns> IMappingExpression ConstructUsing(Func<ResolutionContext, object> ctor); /// <summary> /// Supply a custom instantiation function for the destination type /// </summary> /// <param name="ctor">Callback to create the destination type given the source object</param> /// <returns>Itself</returns> IMappingExpression ConstructUsing(Func<object, object> ctor); /// <summary> /// Skip member mapping and use a custom expression during LINQ projection /// </summary> /// <param name="projectionExpression">Projection expression</param> void ProjectUsing(Expression<Func<object, object>> projectionExpression); /// <summary> /// Customize configuration for all members /// </summary> /// <param name="memberOptions">Callback for member options</param> void ForAllMembers(Action<IMemberConfigurationExpression> memberOptions); /// <summary> /// Customize configuration for an individual source member /// </summary> /// <param name="sourceMemberName">Source member name</param> /// <param name="memberOptions">Callback for member configuration options</param> /// <returns>Itself</returns> IMappingExpression ForSourceMember(string sourceMemberName, Action<ISourceMemberConfigurationExpression> memberOptions); /// <summary> /// Assign a profile to the current type map /// </summary> /// <param name="profileName">Profile name</param> /// <returns>Itself</returns> IMappingExpression WithProfile(string profileName); /// <summary> /// Skip normal member mapping and convert using a <see cref="ITypeConverter{TSource,TDestination}"/> instantiated during mapping /// </summary> /// <typeparam name="TTypeConverter">Type converter type</typeparam> void ConvertUsing<TTypeConverter>(); /// <summary> /// Skip normal member mapping and convert using a <see cref="ITypeConverter{TSource,TDestination}"/> instantiated during mapping /// Use this method if you need to specify the converter type at runtime /// </summary> /// <param name="typeConverterType">Type converter type</param> void ConvertUsing(Type typeConverterType); /// <summary> /// Override the destination type mapping for looking up configuration and instantiation /// </summary> /// <param name="typeOverride"></param> void As(Type typeOverride); /// <summary> /// Customize individual members /// </summary> /// <param name="name">Name of the member</param> /// <param name="memberOptions">Callback for configuring member</param> /// <returns>Itself</returns> IMappingExpression ForMember(string name, Action<IMemberConfigurationExpression> memberOptions); /// <summary> /// Include this configuration in derived types' maps /// </summary> /// <param name="derivedSourceType">Derived source type</param> /// <param name="derivedDestinationType">Derived destination type</param> /// <returns>Itself</returns> IMappingExpression Include(Type derivedSourceType, Type derivedDestinationType); /// <summary> /// Ignores all destination properties that have either a private or protected setter, forcing the mapper to respect encapsulation (note: order matters, so place this before explicit configuration of any properties with an inaccessible setter) /// </summary> /// <returns>Itself</returns> IMappingExpression IgnoreAllPropertiesWithAnInaccessibleSetter(); /// <summary> /// When using ReverseMap, ignores all source properties that have either a private or protected setter, keeping the reverse mapping consistent with the forward mapping (note: destination properties with an inaccessible setter may still be mapped unless IgnoreAllPropertiesWithAnInaccessibleSetter is also used) /// </summary> /// <returns>Itself</returns> IMappingExpression IgnoreAllSourcePropertiesWithAnInaccessibleSetter(); /// <summary> /// Include the base type map's configuration in this map /// </summary> /// <param name="sourceBase">Base source type</param> /// <param name="destinationBase">Base destination type</param> /// <returns></returns> IMappingExpression IncludeBase(Type sourceBase, Type destinationBase); /// <summary> /// Execute a custom function to the source and/or destination types before member mapping /// </summary> /// <param name="beforeFunction">Callback for the source/destination types</param> /// <returns>Itself</returns> IMappingExpression BeforeMap(Action<object, object> beforeFunction); /// <summary> /// Execute a custom mapping action before member mapping /// </summary> /// <typeparam name="TMappingAction">Mapping action type instantiated during mapping</typeparam> /// <returns>Itself</returns> IMappingExpression BeforeMap<TMappingAction>() where TMappingAction : IMappingAction<object, object>; /// <summary> /// Execute a custom function to the source and/or destination types after member mapping /// </summary> /// <param name="afterFunction">Callback for the source/destination types</param> /// <returns>Itself</returns> IMappingExpression AfterMap(Action<object, object> afterFunction); /// <summary> /// Execute a custom mapping action after member mapping /// </summary> /// <typeparam name="TMappingAction">Mapping action type instantiated during mapping</typeparam> /// <returns>Itself</returns> IMappingExpression AfterMap<TMappingAction>() where TMappingAction : IMappingAction<object, object>; /// <summary> /// The current TypeMap being configured /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] TypeMap TypeMap { get; } } /// <summary> /// Mapping configuration options /// </summary> /// <typeparam name="TSource">Source type</typeparam> /// <typeparam name="TDestination">Destination type</typeparam> public interface IMappingExpression<TSource, TDestination> { /// <summary> /// Customize configuration for individual member /// </summary> /// <param name="destinationMember">Expression to the top-level destination member. This must be a member on the <typeparamref name="TDestination"/>TDestination</param> type /// <param name="memberOptions">Callback for member options</param> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> ForMember(Expression<Func<TDestination, object>> destinationMember, Action<IMemberConfigurationExpression<TSource>> memberOptions); /// <summary> /// Customize configuration for individual member. Used when the name isn't known at compile-time /// </summary> /// <param name="name">Destination member name</param> /// <param name="memberOptions">Callback for member options</param> /// <returns></returns> IMappingExpression<TSource, TDestination> ForMember(string name, Action<IMemberConfigurationExpression<TSource>> memberOptions); /// <summary> /// Customize configuration for all members /// </summary> /// <param name="memberOptions">Callback for member options</param> void ForAllMembers(Action<IMemberConfigurationExpression<TSource>> memberOptions); /// <summary> /// Ignores all <typeparamref name="TDestination"/> properties that have either a private or protected setter, forcing the mapper to respect encapsulation (note: order matters, so place this before explicit configuration of any properties with an inaccessible setter) /// </summary> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> IgnoreAllPropertiesWithAnInaccessibleSetter(); /// <summary> /// When using ReverseMap, ignores all <typeparamref name="TSource"/> properties that have either a private or protected setter, keeping the reverse mapping consistent with the forward mapping (note: <typeparamref name="TDestination"/> properties with an inaccessible setter may still be mapped unless IgnoreAllPropertiesWithAnInaccessibleSetter is also used) /// </summary> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> IgnoreAllSourcePropertiesWithAnInaccessibleSetter(); /// <summary> /// Include this configuration in derived types' maps /// </summary> /// <typeparam name="TOtherSource">Derived source type</typeparam> /// <typeparam name="TOtherDestination">Derived destination type</typeparam> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> Include<TOtherSource, TOtherDestination>() where TOtherSource : TSource where TOtherDestination : TDestination; /// <summary> /// Include the base type map's configuration in this map /// </summary> /// <typeparam name="TSourceBase">Base source type</typeparam> /// <typeparam name="TDestinationBase">Base destination type</typeparam> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> IncludeBase<TSourceBase, TDestinationBase>(); /// <summary> /// Include this configuration in derived types' maps /// </summary> /// <param name="derivedSourceType">Derived source type</param> /// <param name="derivedDestinationType">Derived destination type</param> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> Include(Type derivedSourceType, Type derivedDestinationType); /// <summary> /// Assign a profile to the current type map /// </summary> /// <param name="profileName">Name of the profile</param> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> WithProfile(string profileName); /// <summary> /// Skip member mapping and use a custom expression during LINQ projection /// </summary> /// <param name="projectionExpression">Projection expression</param> void ProjectUsing(Expression<Func<TSource, TDestination>> projectionExpression); /// <summary> /// Skip member mapping and use a custom function to convert to the destination type /// </summary> /// <param name="mappingFunction">Callback to convert from source type to destination type</param> void ConvertUsing(Func<TSource, TDestination> mappingFunction); /// <summary> /// Skip member mapping and use a custom function to convert to the destination type /// </summary> /// <param name="mappingFunction">Callback to convert from source type to destination type</param> void ConvertUsing(Func<ResolutionContext, TDestination> mappingFunction); /// <summary> /// Skip member mapping and use a custom function to convert to the destination type /// </summary> /// <param name="mappingFunction">Callback to convert from source type to destination type</param> void ConvertUsing(Func<ResolutionContext, TSource, TDestination> mappingFunction); /// <summary> /// Skip member mapping and use a custom type converter instance to convert to the destination type /// </summary> /// <param name="converter">Type converter instance</param> void ConvertUsing(ITypeConverter<TSource, TDestination> converter); /// <summary> /// Skip member mapping and use a custom type converter instance to convert to the destination type /// </summary> /// <typeparam name="TTypeConverter">Type converter type</typeparam> void ConvertUsing<TTypeConverter>() where TTypeConverter : ITypeConverter<TSource, TDestination>; /// <summary> /// Execute a custom function to the source and/or destination types before member mapping /// </summary> /// <param name="beforeFunction">Callback for the source/destination types</param> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> BeforeMap(Action<TSource, TDestination> beforeFunction); /// <summary> /// Execute a custom mapping action before member mapping /// </summary> /// <typeparam name="TMappingAction">Mapping action type instantiated during mapping</typeparam> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> BeforeMap<TMappingAction>() where TMappingAction : IMappingAction<TSource, TDestination>; /// <summary> /// Execute a custom function to the source and/or destination types after member mapping /// </summary> /// <param name="afterFunction">Callback for the source/destination types</param> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> AfterMap(Action<TSource, TDestination> afterFunction); /// <summary> /// Execute a custom mapping action after member mapping /// </summary> /// <typeparam name="TMappingAction">Mapping action type instantiated during mapping</typeparam> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> AfterMap<TMappingAction>() where TMappingAction : IMappingAction<TSource, TDestination>; /// <summary> /// Supply a custom instantiation function for the destination type /// </summary> /// <param name="ctor">Callback to create the destination type given the source object</param> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> ConstructUsing(Func<TSource, TDestination> ctor); /// <summary> /// Supply a custom instantiation expression for the destination type for LINQ projection /// </summary> /// <param name="ctor">Callback to create the destination type given the source object</param> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> ConstructProjectionUsing(Expression<Func<TSource, TDestination>> ctor); /// <summary> /// Supply a custom instantiation function for the destination type, based on the entire resolution context /// </summary> /// <param name="ctor">Callback to create the destination type given the current resolution context</param> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> ConstructUsing(Func<ResolutionContext, TDestination> ctor); /// <summary> /// Override the destination type mapping for looking up configuration and instantiation /// </summary> /// <typeparam name="T">Destination type to use</typeparam> void As<T>(); /// <summary> /// For self-referential types, limit recurse depth /// </summary> /// <param name="depth">Number of levels to limit to</param> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> MaxDepth(int depth); /// <summary> /// Construct the destination object using the service locator /// </summary> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> ConstructUsingServiceLocator(); /// <summary> /// Create a type mapping from the destination to the source type, using the <typeparamref name="TDestination"/> members as validation /// </summary> /// <returns>Itself</returns> IMappingExpression<TDestination, TSource> ReverseMap(); /// <summary> /// Customize configuration for an individual source member /// </summary> /// <param name="sourceMember">Expression to source member. Must be a member of the <typeparamref name="TSource"/> type</param> /// <param name="memberOptions">Callback for member configuration options</param> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> ForSourceMember(Expression<Func<TSource, object>> sourceMember, Action<ISourceMemberConfigurationExpression> memberOptions); /// <summary> /// Customize configuration for an individual source member. Member name not known until runtime /// </summary> /// <param name="sourceMemberName">Expression to source member. Must be a member of the <typeparamref name="TSource"/> type</param> /// <param name="memberOptions">Callback for member configuration options</param> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> ForSourceMember(string sourceMemberName, Action<ISourceMemberConfigurationExpression> memberOptions); /// <summary> /// Replace the original runtime instance with a new source instance. Useful when ORMs return proxy types with no relationships to runtime types. /// The returned source object will be mapped instead of what was supplied in the original source object. /// </summary> /// <param name="substituteFunc">Substitution function</param> /// <returns>New source object to map.</returns> IMappingExpression<TSource, TDestination> Substitute(Func<TSource, object> substituteFunc); /// <summary> /// Customize configuration for individual constructor parameter /// </summary> /// <param name="ctorParamName">Constructor parameter name</param> /// <param name="paramOptions">Options</param> /// <returns>Itself</returns> IMappingExpression<TSource, TDestination> ForCtorParam(string ctorParamName, Action<ICtorParamConfigurationExpression<TSource>> paramOptions); /// <summary> /// The current TypeMap being configured /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] TypeMap TypeMap { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net.Security; using System.Runtime.CompilerServices; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using CURLAUTH = Interop.Http.CURLAUTH; using CURLcode = Interop.Http.CURLcode; using CURLMcode = Interop.Http.CURLMcode; using CURLoption = Interop.Http.CURLoption; namespace System.Net.Http { // Object model: // ------------- // CurlHandler provides an HttpMessageHandler implementation that wraps libcurl. The core processing for CurlHandler // is handled via a CurlHandler.MultiAgent instance, where currently a CurlHandler instance stores and uses a single // MultiAgent for the lifetime of the handler (with the MultiAgent lazily initialized on first use, so that it can // be initialized with all of the configured options on the handler). The MultiAgent is named as such because it wraps // a libcurl multi handle that's responsible for handling all requests on the instance. When a request arrives, it's // queued to the MultiAgent, which ensures that a thread is running to continually loop and process all work associated // with the multi handle until no more work is required; at that point, the thread is retired until more work arrives, // at which point another thread will be spun up. Any number of requests will have their handling multiplexed onto // this one event loop thread. Each request is represented by a CurlHandler.EasyRequest, so named because it wraps // a libcurl easy handle, libcurl's representation of a request. The EasyRequest stores all state associated with // the request, including the CurlHandler.CurlResponseMessage and CurlHandler.CurlResponseStream that are handed // back to the caller to provide access to the HTTP response information. // // Lifetime: // --------- // The MultiAgent is initialized on first use and is kept referenced by the CurlHandler for the remainder of the // handler's lifetime. Both are disposable, and disposing of the CurlHandler will dispose of the MultiAgent. // However, libcurl is not thread safe in that two threads can't be using the same multi or easy handles concurrently, // so any interaction with the multi handle must happen on the MultiAgent's thread. For this reason, the // SafeHandle storing the underlying multi handle has its ref count incremented when the MultiAgent worker is running // and decremented when it stops running, enabling any disposal requests to be delayed until the worker has quiesced. // To enable that to happen quickly when a dispose operation occurs, an "incoming request" (how all other threads // communicate with the MultiAgent worker) is queued to the worker to request a shutdown; upon receiving that request, // the worker will exit and allow the multi handle to be disposed of. // // An EasyRequest itself doesn't govern its own lifetime. Since an easy handle is added to a multi handle for // the multi handle to process, the easy handle must not be destroyed until after it's been removed from the multi handle. // As such, once the SafeHandle for an easy handle is created, although its stored in the EasyRequest instance, // it's also stored into a dictionary on the MultiAgent and has its ref count incremented to prevent it from being // disposed of while it's in use by the multi handle. // // When a request is made to the CurlHandler, callbacks are registered with libcurl, including state that will // be passed back into managed code and used to identify the associated EasyRequest. This means that the native // code needs to be able both to keep the EasyRequest alive and to refer to it using an IntPtr. For this, we // use a GCHandle to the EasyRequest. However, the native code needs to be able to refer to the EasyRequest for the // lifetime of the request, but we also need to avoid keeping the EasyRequest (and all state it references) alive artificially. // For the beginning phase of the request, the native code may be the only thing referencing the managed objects, since // when a caller invokes "Task<HttpResponseMessage> SendAsync(...)", there's nothing handed back to the caller that represents // the request until at least the HTTP response headers are received and the returned Task is completed with the response // message object. However, after that point, if the caller drops the HttpResponseMessage, we also want to cancel and // dispose of the associated state, which means something needs to be finalizable and not kept rooted while at the same // time still allowing the native code to continue using its GCHandle and lookup the associated state as long as it's alive. // Yet then when an async read is made on the response message, we want to postpone such finalization and ensure that the async // read can be appropriately completed with control and reference ownership given back to the reader. As such, we do two things: // we make the response stream finalizable, and we make the GCHandle be to a wrapper object for the EasyRequest rather than to // the EasyRequest itself. That wrapper object maintains a weak reference to the EasyRequest as well as sometimes maintaining // a strong reference. When the request starts out, the GCHandle is created to the wrapper, which has a strong reference to // the EasyRequest (which also back references to the wrapper so that the wrapper can be accessed via it). The GCHandle is // thus keeping the EasyRequest and all of the state it references alive, e.g. the CurlResponseStream, which itself has a reference // back to the EasyRequest. Once the request progresses to the point of receiving HTTP response headers and the HttpResponseMessage // is handed back to the caller, the wrapper object drops its strong reference and maintains only a weak reference. At this // point, if the caller were to drop its HttpResponseMessage object, that would also drop the only strong reference to the // CurlResponseStream; the CurlResponseStream would be available for collection and finalization, and its finalization would // request cancellation of the easy request to the multi agent. The multi agent would then in response remove the easy handle // from the multi handle and decrement the ref count on the SafeHandle for the easy handle, allowing it to be finalized and // the underlying easy handle released. If instead of dropping the HttpResponseMessage the caller makes a read request on the // response stream, the wrapper object is transitioned back to having a strong reference, so that even if the caller then drops // the HttpResponseMessage, the read Task returned from the read operation will still be completed eventually, at which point // the wrapper will transition back to being a weak reference. // // Even with that, of course, Dispose is still the recommended way of cleaning things up. Disposing the CurlResponseMessage // will Dispose the CurlResponseStream, which will Dispose of the SafeHandle for the easy handle and request that the MultiAgent // cancel the operation. Once canceled and removed, the SafeHandle will have its ref count decremented and the previous disposal // will proceed to release the underlying handle. internal partial class CurlHandler : HttpMessageHandler { #region Constants private const char SpaceChar = ' '; private const int StatusCodeLength = 3; private const string UriSchemeHttp = "http"; private const string UriSchemeHttps = "https"; private const string EncodingNameGzip = "gzip"; private const string EncodingNameDeflate = "deflate"; private const int MaxRequestBufferSize = 16384; // Default used by libcurl private const string NoTransferEncoding = HttpKnownHeaderNames.TransferEncoding + ":"; private const string NoContentType = HttpKnownHeaderNames.ContentType + ":"; private const string NoExpect = HttpKnownHeaderNames.Expect + ":"; private const int CurlAge = 5; private const int MinCurlAge = 3; #endregion #region Fields private static readonly KeyValuePair<string,CURLAUTH>[] s_orderedAuthTypes = new KeyValuePair<string, CURLAUTH>[] { new KeyValuePair<string,CURLAUTH>("Negotiate", CURLAUTH.Negotiate), new KeyValuePair<string,CURLAUTH>("NTLM", CURLAUTH.NTLM), new KeyValuePair<string,CURLAUTH>("Digest", CURLAUTH.Digest), new KeyValuePair<string,CURLAUTH>("Basic", CURLAUTH.Basic), }; // Max timeout value used by WinHttp handler, so mapping to that here. private static readonly TimeSpan s_maxTimeout = TimeSpan.FromMilliseconds(int.MaxValue); private static readonly char[] s_newLineCharArray = new char[] { HttpRuleParser.CR, HttpRuleParser.LF }; private static readonly bool s_supportsAutomaticDecompression; private static readonly bool s_supportsSSL; private static readonly bool s_supportsHttp2Multiplexing; private static string s_curlVersionDescription; private static string s_curlSslVersionDescription; private static readonly MultiAgent s_singletonSharedAgent; private readonly MultiAgent _agent; private volatile bool _anyOperationStarted; private volatile bool _disposed; private IWebProxy _proxy = null; private ICredentials _serverCredentials = null; private bool _useProxy = HttpHandlerDefaults.DefaultUseProxy; private ICredentials _defaultProxyCredentials = null; private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression; private bool _preAuthenticate = HttpHandlerDefaults.DefaultPreAuthenticate; private CredentialCache _credentialCache = null; // protected by LockObject private bool _useDefaultCredentials = HttpHandlerDefaults.DefaultUseDefaultCredentials; private CookieContainer _cookieContainer = new CookieContainer(); private bool _useCookies = HttpHandlerDefaults.DefaultUseCookies; private TimeSpan _connectTimeout = Timeout.InfiniteTimeSpan; private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection; private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections; private int _maxConnectionsPerServer = HttpHandlerDefaults.DefaultMaxConnectionsPerServer; private int _maxResponseHeadersLength = HttpHandlerDefaults.DefaultMaxResponseHeadersLength; private ClientCertificateOption _clientCertificateOption = HttpHandlerDefaults.DefaultClientCertificateOption; private X509Certificate2Collection _clientCertificates; private Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> _serverCertificateValidationCallback; private bool _checkCertificateRevocationList = HttpHandlerDefaults.DefaultCheckCertificateRevocationList; private SslProtocols _sslProtocols = SslProtocols.None; // use default private IDictionary<String, Object> _properties; // Only create dictionary when required. private object LockObject { get { return _agent; } } #endregion static CurlHandler() { // curl_global_init call handled by Interop.LibCurl's cctor Interop.Http.CurlFeatures features = Interop.Http.GetSupportedFeatures(); s_supportsSSL = (features & Interop.Http.CurlFeatures.CURL_VERSION_SSL) != 0; s_supportsAutomaticDecompression = (features & Interop.Http.CurlFeatures.CURL_VERSION_LIBZ) != 0; s_supportsHttp2Multiplexing = (features & Interop.Http.CurlFeatures.CURL_VERSION_HTTP2) != 0 && Interop.Http.GetSupportsHttp2Multiplexing(); if (NetEventSource.IsEnabled) { EventSourceTrace($"libcurl: {CurlVersionDescription} {CurlSslVersionDescription} {features}"); } // By default every CurlHandler gets its own MultiAgent. But for some backends, // we need to restrict the number of threads involved in processing libcurl work, // so we create a single MultiAgent that's used by all handlers. if (UseSingletonMultiAgent) { s_singletonSharedAgent = new MultiAgent(null); } } public CurlHandler() { // If the shared MultiAgent was initialized, use it. // Otherwise, create a new MultiAgent for this handler. _agent = s_singletonSharedAgent ?? new MultiAgent(this); } #region Properties private static string CurlVersionDescription => s_curlVersionDescription ?? (s_curlVersionDescription = Interop.Http.GetVersionDescription() ?? string.Empty); private static string CurlSslVersionDescription => s_curlSslVersionDescription ?? (s_curlSslVersionDescription = Interop.Http.GetSslVersionDescription() ?? string.Empty); private static bool UseSingletonMultiAgent { get { // Some backends other than OpenSSL need locks initialized in order to use them in a // multithreaded context, which would happen with multiple HttpClients and thus multiple // MultiAgents. Since we don't currently have the ability to do so initialization, instead we // restrict all HttpClients to use the same MultiAgent instance in this case. We know LibreSSL // is in this camp, so we currently special-case it. string curlSslVersion = Interop.Http.GetSslVersionDescription(); return !string.IsNullOrEmpty(curlSslVersion) && curlSslVersion.StartsWith(Interop.Http.LibreSslDescription, StringComparison.OrdinalIgnoreCase); } } internal bool AllowAutoRedirect { get { return _automaticRedirection; } set { CheckDisposedOrStarted(); _automaticRedirection = value; } } internal bool UseProxy { get { return _useProxy; } set { CheckDisposedOrStarted(); _useProxy = value; } } internal IWebProxy Proxy { get { return _proxy; } set { CheckDisposedOrStarted(); _proxy = value; } } internal ICredentials DefaultProxyCredentials { get { return _defaultProxyCredentials; } set { CheckDisposedOrStarted(); _defaultProxyCredentials = value; } } internal ICredentials Credentials { get { return _serverCredentials; } set { _serverCredentials = value; } } internal ClientCertificateOption ClientCertificateOptions { get { return _clientCertificateOption; } set { if (value != ClientCertificateOption.Manual && value != ClientCertificateOption.Automatic) { throw new ArgumentOutOfRangeException(nameof(value)); } CheckDisposedOrStarted(); _clientCertificateOption = value; } } internal X509Certificate2Collection ClientCertificates { get { if (_clientCertificateOption != ClientCertificateOption.Manual) { throw new InvalidOperationException(SR.Format(SR.net_http_invalid_enable_first, nameof(ClientCertificateOptions), nameof(ClientCertificateOption.Manual))); } return _clientCertificates ?? (_clientCertificates = new X509Certificate2Collection()); } } internal Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ServerCertificateCustomValidationCallback { get { return _serverCertificateValidationCallback; } set { CheckDisposedOrStarted(); _serverCertificateValidationCallback = value; } } internal bool CheckCertificateRevocationList { get { return _checkCertificateRevocationList; } set { CheckDisposedOrStarted(); _checkCertificateRevocationList = value; } } internal SslProtocols SslProtocols { get { return _sslProtocols; } set { SecurityProtocol.ThrowOnNotAllowed(value, allowNone: true); CheckDisposedOrStarted(); _sslProtocols = value; } } internal bool SupportsAutomaticDecompression => s_supportsAutomaticDecompression; internal DecompressionMethods AutomaticDecompression { get { return _automaticDecompression; } set { CheckDisposedOrStarted(); _automaticDecompression = value; } } internal bool PreAuthenticate { get { return _preAuthenticate; } set { CheckDisposedOrStarted(); _preAuthenticate = value; if (value && _credentialCache == null) { _credentialCache = new CredentialCache(); } } } internal bool UseCookies { get { return _useCookies; } set { CheckDisposedOrStarted(); _useCookies = value; } } internal CookieContainer CookieContainer { get { return _cookieContainer; } set { CheckDisposedOrStarted(); _cookieContainer = value; } } internal int MaxAutomaticRedirections { get { return _maxAutomaticRedirections; } set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxAutomaticRedirections = value; } } internal int MaxConnectionsPerServer { get { return _maxConnectionsPerServer; } set { if (value < 1) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxConnectionsPerServer = value; } } internal int MaxResponseHeadersLength { get { return _maxResponseHeadersLength; } set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxResponseHeadersLength = value; } } internal bool UseDefaultCredentials { get { return _useDefaultCredentials; } set { CheckDisposedOrStarted(); _useDefaultCredentials = value; } } public IDictionary<string, object> Properties { get { if (_properties == null) { _properties = new Dictionary<String, object>(); } return _properties; } } #endregion protected override void Dispose(bool disposing) { _disposed = true; if (disposing && _agent != s_singletonSharedAgent) { _agent.Dispose(); } base.Dispose(disposing); } protected internal override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { if (request == null) { throw new ArgumentNullException(nameof(request), SR.net_http_handler_norequest); } if (request.RequestUri.Scheme == UriSchemeHttps) { if (!s_supportsSSL) { throw new PlatformNotSupportedException(SR.Format(SR.net_http_unix_https_support_unavailable_libcurl, CurlVersionDescription)); } } else { Debug.Assert(request.RequestUri.Scheme == UriSchemeHttp, "HttpClient expected to validate scheme as http or https."); } if (request.Headers.TransferEncodingChunked.GetValueOrDefault() && (request.Content == null)) { return Task.FromException<HttpResponseMessage>( new HttpRequestException(SR.net_http_client_execution_error, new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content))); } if (_useCookies && _cookieContainer == null) { throw new InvalidOperationException(SR.net_http_invalid_cookiecontainer); } CheckDisposed(); SetOperationStarted(); // Do an initial cancellation check to avoid initiating the async operation if // cancellation has already been requested. After this, we'll rely on CancellationToken.Register // to notify us of cancellation requests and shut down the operation if possible. if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<HttpResponseMessage>(cancellationToken); } // Create the easy request. This associates the easy request with this handler and configures // it based on the settings configured for the handler. var easy = new EasyRequest(this, _agent, request, cancellationToken); try { EventSourceTrace("{0}", request, easy: easy); _agent.Queue(new MultiAgent.IncomingRequest { Easy = easy, Type = MultiAgent.IncomingRequestType.New }); } catch (Exception exc) { easy.CleanupAndFailRequest(exc); } return easy.Task; } #region Private methods private void SetOperationStarted() { if (!_anyOperationStarted) { _anyOperationStarted = true; } } private KeyValuePair<NetworkCredential, CURLAUTH> GetCredentials(Uri requestUri) { // If preauthentication is enabled, we may have populated our internal credential cache, // so first check there to see if we have any credentials for this uri. if (_preAuthenticate) { KeyValuePair<NetworkCredential, CURLAUTH> ncAndScheme; lock (LockObject) { Debug.Assert(_credentialCache != null, "Expected non-null credential cache"); ncAndScheme = GetCredentials(requestUri, _credentialCache, s_orderedAuthTypes); } if (ncAndScheme.Key != null) { return ncAndScheme; } } // We either weren't preauthenticating or we didn't have any cached credentials // available, so check the credentials on the handler. return GetCredentials(requestUri, _serverCredentials, s_orderedAuthTypes); } private void TransferCredentialsToCache(Uri serverUri, CURLAUTH serverAuthAvail) { if (_serverCredentials == null) { // No credentials, nothing to put into the cache. return; } lock (LockObject) { // For each auth type we allow, check whether it's one supported by the server. KeyValuePair<string, CURLAUTH>[] validAuthTypes = s_orderedAuthTypes; for (int i = 0; i < validAuthTypes.Length; i++) { // Is it supported by the server? if ((serverAuthAvail & validAuthTypes[i].Value) != 0) { // And do we have a credential for it? NetworkCredential nc = _serverCredentials.GetCredential(serverUri, validAuthTypes[i].Key); if (nc != null) { // We have a credential for it, so add it, and we're done. Debug.Assert(_credentialCache != null, "Expected non-null credential cache"); try { _credentialCache.Add(serverUri, validAuthTypes[i].Key, nc); } catch (ArgumentException) { // Ignore the case of key already present } break; } } } } } private void AddResponseCookies(EasyRequest state, string cookieHeader) { if (!_useCookies) { return; } try { _cookieContainer.SetCookies(state._requestMessage.RequestUri, cookieHeader); state.SetCookieOption(state._requestMessage.RequestUri); } catch (CookieException e) { EventSourceTrace( "Malformed cookie parsing failed: {0}, server: {1}, cookie: {2}", e.Message, state._requestMessage.RequestUri, cookieHeader, easy: state); } } private static KeyValuePair<NetworkCredential, CURLAUTH> GetCredentials(Uri requestUri, ICredentials credentials, KeyValuePair<string, CURLAUTH>[] validAuthTypes) { NetworkCredential nc = null; CURLAUTH curlAuthScheme = CURLAUTH.None; if (credentials != null) { // For each auth type we consider valid, try to get a credential for it. // Union together the auth types for which we could get credentials, but validate // that the found credentials are all the same, as libcurl doesn't support differentiating // by auth type. for (int i = 0; i < validAuthTypes.Length; i++) { NetworkCredential networkCredential = credentials.GetCredential(requestUri, validAuthTypes[i].Key); if (networkCredential != null) { curlAuthScheme |= validAuthTypes[i].Value; if (nc == null) { nc = networkCredential; } else if(!AreEqualNetworkCredentials(nc, networkCredential)) { throw new PlatformNotSupportedException(SR.Format(SR.net_http_unix_invalid_credential, CurlVersionDescription)); } } } } EventSourceTrace("Authentication scheme: {0}", curlAuthScheme); return new KeyValuePair<NetworkCredential, CURLAUTH>(nc, curlAuthScheme); ; } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } } private void CheckDisposedOrStarted() { CheckDisposed(); if (_anyOperationStarted) { throw new InvalidOperationException(SR.net_http_operation_started); } } private static void ThrowIfCURLEError(CURLcode error) { if (error != CURLcode.CURLE_OK) // success { string msg = CurlException.GetCurlErrorString((int)error, isMulti: false); EventSourceTrace(msg); switch (error) { case CURLcode.CURLE_OPERATION_TIMEDOUT: throw new OperationCanceledException(msg); case CURLcode.CURLE_OUT_OF_MEMORY: throw new OutOfMemoryException(msg); case CURLcode.CURLE_SEND_FAIL_REWIND: throw new InvalidOperationException(msg); default: throw new CurlException((int)error, msg); } } } private static void ThrowIfCURLMError(CURLMcode error) { if (error != CURLMcode.CURLM_OK && // success error != CURLMcode.CURLM_CALL_MULTI_PERFORM) // success + a hint to try curl_multi_perform again { string msg = CurlException.GetCurlErrorString((int)error, isMulti: true); EventSourceTrace(msg); switch (error) { case CURLMcode.CURLM_ADDED_ALREADY: case CURLMcode.CURLM_BAD_EASY_HANDLE: case CURLMcode.CURLM_BAD_HANDLE: case CURLMcode.CURLM_BAD_SOCKET: throw new ArgumentException(msg); case CURLMcode.CURLM_UNKNOWN_OPTION: throw new ArgumentOutOfRangeException(msg); case CURLMcode.CURLM_OUT_OF_MEMORY: throw new OutOfMemoryException(msg); case CURLMcode.CURLM_INTERNAL_ERROR: default: throw new CurlException((int)error, msg); } } } private static bool AreEqualNetworkCredentials(NetworkCredential credential1, NetworkCredential credential2) { Debug.Assert(credential1 != null && credential2 != null, "arguments are non-null in network equality check"); return credential1.UserName == credential2.UserName && credential1.Domain == credential2.Domain && string.Equals(credential1.Password, credential2.Password, StringComparison.Ordinal); } // PERF NOTE: // These generic overloads of EventSourceTrace (and similar wrapper methods in some of the other CurlHandler // nested types) exist to allow call sites to call EventSourceTrace without boxing and without checking // NetEventSource.IsEnabled. Do not remove these without fixing the call sites accordingly. private static void EventSourceTrace<TArg0>( string formatMessage, TArg0 arg0, MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null) { if (NetEventSource.IsEnabled) { EventSourceTraceCore(string.Format(formatMessage, arg0), agent, easy, memberName); } } private static void EventSourceTrace<TArg0, TArg1, TArg2> (string formatMessage, TArg0 arg0, TArg1 arg1, TArg2 arg2, MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null) { if (NetEventSource.IsEnabled) { EventSourceTraceCore(string.Format(formatMessage, arg0, arg1, arg2), agent, easy, memberName); } } private static void EventSourceTrace( string message, MultiAgent agent = null, EasyRequest easy = null, [CallerMemberName] string memberName = null) { if (NetEventSource.IsEnabled) { EventSourceTraceCore(message, agent, easy, memberName); } } private static void EventSourceTraceCore(string message, MultiAgent agent, EasyRequest easy, string memberName) { // If we weren't handed a multi agent, see if we can get one from the EasyRequest if (agent == null && easy != null) { agent = easy._associatedMultiAgent; } NetEventSource.Log.HandlerMessage( agent?.GetHashCode() ?? 0, (agent?.RunningWorkerId).GetValueOrDefault(), easy?.Task.Id ?? 0, memberName, message); } private static HttpRequestException CreateHttpRequestException(Exception inner) { return new HttpRequestException(SR.net_http_client_execution_error, inner); } private static IOException MapToReadWriteIOException(Exception error, bool isRead) { return new IOException( isRead ? SR.net_http_io_read : SR.net_http_io_write, error is HttpRequestException && error.InnerException != null ? error.InnerException : error); } private static void SetChunkedModeForSend(HttpRequestMessage request) { bool chunkedMode = request.Headers.TransferEncodingChunked.GetValueOrDefault(); HttpContent requestContent = request.Content; Debug.Assert(requestContent != null, "request is null"); // Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics. // libcurl adds a Transfer-Encoding header by default and the request fails if both are set. if (requestContent.Headers.ContentLength.HasValue) { if (chunkedMode) { // Same behaviour as WinHttpHandler requestContent.Headers.ContentLength = null; } else { // Prevent libcurl from adding Transfer-Encoding header request.Headers.TransferEncodingChunked = false; } } else if (!chunkedMode) { // Make sure Transfer-Encoding: chunked header is set, // as we have content to send but no known length for it. request.Headers.TransferEncodingChunked = true; } } #endregion } }
namespace System.Collections.Generic { using Bridge; using System; using System.Collections; //using System.Diagnostics.Contracts; public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue> { private struct Entry { public int hashCode; // Lower 31 bits of hash code, -1 if unused public int next; // Index of next entry, -1 if last public TKey key; // Key of entry public TValue value; // Value of entry } private int[] buckets; private object simpleBuckets; private Entry[] entries; private int count; private int version; private int freeList; private int freeCount; private IEqualityComparer<TKey> comparer; private KeyCollection keys; private ValueCollection values; private bool isSimpleKey; // constants for serialization private const String VersionName = "Version"; private const String HashSizeName = "HashSize"; // Must save buckets.Length private const String KeyValuePairsName = "KeyValuePairs"; private const String ComparerName = "Comparer"; public Dictionary() : this(0, null) { } public Dictionary(int capacity) : this(capacity, null) { } public Dictionary(IEqualityComparer<TKey> comparer) : this(0, comparer) { } public Dictionary(int capacity, IEqualityComparer<TKey> comparer) { if (capacity < 0) ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.capacity); if (capacity > 0) Initialize(capacity); this.comparer = comparer ?? EqualityComparer<TKey>.Default; this.isSimpleKey = ((typeof(TKey) == typeof(System.String)) || (Script.Get<bool>("TKey.$number") == true && typeof(TKey) != typeof(System.Int64) && typeof(TKey) != typeof(System.UInt64)) || (typeof(TKey) == typeof(System.Char))) && (this.comparer == EqualityComparer<TKey>.Default); } public Dictionary(IDictionary<TKey, TValue> dictionary) : this(dictionary, null) { } public Dictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) : this(dictionary != null ? dictionary.Count : 0, comparer) { if (dictionary == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); } foreach (KeyValuePair<TKey, TValue> pair in dictionary) { Add(pair.Key, pair.Value); } } public IEqualityComparer<TKey> Comparer { get { return comparer; } } public int Count { get { return count - freeCount; } } public KeyCollection Keys { get { if (keys == null) keys = new KeyCollection(this); return keys; } } ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { if (keys == null) keys = new KeyCollection(this); return keys; } } IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys { get { if (keys == null) keys = new KeyCollection(this); return keys; } } public ValueCollection Values { get { if (values == null) values = new ValueCollection(this); return values; } } ICollection<TValue> IDictionary<TKey, TValue>.Values { get { if (values == null) values = new ValueCollection(this); return values; } } IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values { get { if (values == null) values = new ValueCollection(this); return values; } } public TValue this[TKey key] { get { int i = FindEntry(key); if (i >= 0) return entries[i].value; throw new KeyNotFoundException(); } set { Insert(key, value, false); } } [Bridge.Template("{obj}[{key}]")] [Bridge.External] public static extern int GetBucket(object obj, TKey key); [Bridge.Template("{obj}[{key}] = {value}")] [Bridge.External] public static extern void SetBucket(object obj, TKey key, int value); public void Add(TKey key, TValue value) { Insert(key, value, true); } void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair) { Add(keyValuePair.Key, keyValuePair.Value); } bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair) { int i = FindEntry(keyValuePair.Key); if (i >= 0 && EqualityComparer<TValue>.Default.Equals(entries[i].value, keyValuePair.Value)) { return true; } return false; } bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair) { int i = FindEntry(keyValuePair.Key); if (i >= 0 && EqualityComparer<TValue>.Default.Equals(entries[i].value, keyValuePair.Value)) { Remove(keyValuePair.Key); return true; } return false; } public void Clear() { if (count > 0) { for (int i = 0; i < buckets.Length; i++) buckets[i] = -1; if (this.isSimpleKey) { this.simpleBuckets = new object(); } Array.Clear(entries, 0, count); freeList = -1; count = 0; freeCount = 0; version++; } } public bool ContainsKey(TKey key) { return FindEntry(key) >= 0; } public bool ContainsValue(TValue value) { if (value == null) { for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0 && entries[i].value == null) return true; } } else { EqualityComparer<TValue> c = EqualityComparer<TValue>.Default; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0 && c.Equals(entries[i].value, value)) return true; } } return false; } private void CopyTo(KeyValuePair<TKey, TValue>[] array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } int count = this.count; Entry[] entries = this.entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { array[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value); } } } public Enumerator GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } private int FindEntry(TKey key) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (this.isSimpleKey) { if (this.simpleBuckets != null && this.simpleBuckets.HasOwnProperty(key)) { return GetBucket(this.simpleBuckets, key); } } else if (buckets != null) { int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF; for (int i = buckets[hashCode % buckets.Length]; i >= 0; i = entries[i].next) { if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) return i; } } return -1; } private void Initialize(int capacity) { int size = HashHelpers.GetPrime(capacity); buckets = new int[size]; for (int i = 0; i < buckets.Length; i++) buckets[i] = -1; entries = new Entry[size]; freeList = -1; this.simpleBuckets = new object(); } private void Insert(TKey key, TValue value, bool add) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (buckets == null) Initialize(0); if(this.isSimpleKey) { if(this.simpleBuckets.HasOwnProperty(key)) { if (add) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate); } entries[GetBucket(this.simpleBuckets, key)].value = value; version++; return; } int simpleIndex; if (freeCount > 0) { simpleIndex = freeList; freeList = entries[simpleIndex].next; freeCount--; } else { if (count == entries.Length) { Resize(); } simpleIndex = count; count++; } entries[simpleIndex].hashCode = 1; entries[simpleIndex].next = -1; entries[simpleIndex].key = key; entries[simpleIndex].value = value; SetBucket(simpleBuckets, key, simpleIndex); version++; return; } int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF; int targetBucket = hashCode % buckets.Length; for (int i = buckets[targetBucket]; i >= 0; i = entries[i].next) { if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) { if (add) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate); } entries[i].value = value; version++; return; } } int index; if (freeCount > 0) { index = freeList; freeList = entries[index].next; freeCount--; } else { if (count == entries.Length) { Resize(); targetBucket = hashCode % buckets.Length; } index = count; count++; } entries[index].hashCode = hashCode; entries[index].next = buckets[targetBucket]; entries[index].key = key; entries[index].value = value; buckets[targetBucket] = index; version++; } private void Resize() { Resize(HashHelpers.ExpandPrime(count), false); } private void Resize(int newSize, bool forceNewHashCodes) { //Contract.Assert(newSize >= entries.Length); int[] newBuckets = new int[newSize]; for (int i = 0; i < newBuckets.Length; i++) newBuckets[i] = -1; if(this.isSimpleKey) { this.simpleBuckets = new object(); } Entry[] newEntries = new Entry[newSize]; Array.Copy(entries, 0, newEntries, 0, count); if (forceNewHashCodes) { for (int i = 0; i < count; i++) { if (newEntries[i].hashCode != -1) { newEntries[i].hashCode = (comparer.GetHashCode(newEntries[i].key) & 0x7FFFFFFF); } } } for (int i = 0; i < count; i++) { if (newEntries[i].hashCode >= 0) { if (this.isSimpleKey) { newEntries[i].next = -1; SetBucket(this.simpleBuckets, newEntries[i].key, i); } else { int bucket = newEntries[i].hashCode % newSize; newEntries[i].next = newBuckets[bucket]; newBuckets[bucket] = i; } } } buckets = newBuckets; entries = newEntries; } public bool Remove(TKey key) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if(this.isSimpleKey) { if(this.simpleBuckets != null) { if(this.simpleBuckets.HasOwnProperty(key)) { var i = GetBucket(this.simpleBuckets, key); Script.Delete(GetBucket(this.simpleBuckets, key)); entries[i].hashCode = -1; entries[i].next = freeList; entries[i].key = default(TKey); entries[i].value = default(TValue); freeList = i; freeCount++; version++; return true; } } } else if (buckets != null) { int hashCode = comparer.GetHashCode(key) & 0x7FFFFFFF; int bucket = hashCode % buckets.Length; int last = -1; for (int i = buckets[bucket]; i >= 0; last = i, i = entries[i].next) { if (entries[i].hashCode == hashCode && comparer.Equals(entries[i].key, key)) { if (last < 0) { buckets[bucket] = entries[i].next; } else { entries[last].next = entries[i].next; } entries[i].hashCode = -1; entries[i].next = freeList; entries[i].key = default(TKey); entries[i].value = default(TValue); freeList = i; freeCount++; version++; return true; } } } return false; } public bool TryGetValue(TKey key, out TValue value) { int i = FindEntry(key); if (i >= 0) { value = entries[i].value; return true; } value = default(TValue); return false; } // This is a convenience method for the internal callers that were converted from using Hashtable. // Many were combining key doesn't exist and key exists but null value (for non-value types) checks. // This allows them to continue getting that behavior with minimal code delta. This is basically // TryGetValue without the out param internal TValue GetValueOrDefault(TKey key) { int i = FindEntry(key); if (i >= 0) { return entries[i].value; } return default(TValue); } bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return false; } } void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int index) { CopyTo(array, index); } void ICollection.CopyTo(Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } KeyValuePair<TKey, TValue>[] pairs = array as KeyValuePair<TKey, TValue>[]; if (pairs != null) { CopyTo(pairs, index); } else if (array is DictionaryEntry[]) { DictionaryEntry[] dictEntryArray = array as DictionaryEntry[]; Entry[] entries = this.entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { dictEntryArray[index++] = new DictionaryEntry(entries[i].key, entries[i].value); } } } else { object[] objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType); } try { int count = this.count; Entry[] entries = this.entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) { objects[index++] = new KeyValuePair<TKey, TValue>(entries[i].key, entries[i].value); } } } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType); } } } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return null; } } bool IDictionary.IsFixedSize { get { return false; } } bool IDictionary.IsReadOnly { get { return false; } } ICollection IDictionary.Keys { get { return (ICollection)Keys; } } ICollection IDictionary.Values { get { return (ICollection)Values; } } object IDictionary.this[object key] { get { if (IsCompatibleKey(key)) { int i = FindEntry((TKey)key); if (i >= 0) { return entries[i].value; } } return null; } set { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value); try { TKey tempKey = (TKey)key; try { this[tempKey] = (TValue)value; } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue)); } } catch (InvalidCastException) { ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey)); } } } private static bool IsCompatibleKey(object key) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } return (key is TKey); } void IDictionary.Add(object key, object value) { if (key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } ThrowHelper.IfNullAndNullsAreIllegalThenThrow<TValue>(value, ExceptionArgument.value); try { TKey tempKey = (TKey)key; try { Add(tempKey, (TValue)value); } catch (InvalidCastException) { ThrowHelper.ThrowWrongValueTypeArgumentException(value, typeof(TValue)); } } catch (InvalidCastException) { ThrowHelper.ThrowWrongKeyTypeArgumentException(key, typeof(TKey)); } } bool IDictionary.Contains(object key) { if (IsCompatibleKey(key)) { return ContainsKey((TKey)key); } return false; } IDictionaryEnumerator IDictionary.GetEnumerator() { return new Enumerator(this, Enumerator.DictEntry); } void IDictionary.Remove(object key) { if (IsCompatibleKey(key)) { Remove((TKey)key); } } [Serializable] public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDictionaryEnumerator { private Dictionary<TKey, TValue> dictionary; private int version; private int index; private KeyValuePair<TKey, TValue> current; private int getEnumeratorRetType; // What should Enumerator.Current return? internal const int DictEntry = 1; internal const int KeyValuePair = 2; internal Enumerator(Dictionary<TKey, TValue> dictionary, int getEnumeratorRetType) { this.dictionary = dictionary; version = dictionary.version; index = 0; this.getEnumeratorRetType = getEnumeratorRetType; current = new KeyValuePair<TKey, TValue>(); } public bool MoveNext() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); } // Use unsigned comparison since we set index to dictionary.count+1 when the enumeration ends. // dictionary.count+1 could be negative if dictionary.count is Int32.MaxValue while ((uint)index < (uint)dictionary.count) { if (dictionary.entries[index].hashCode >= 0) { current = new KeyValuePair<TKey, TValue>(dictionary.entries[index].key, dictionary.entries[index].value); index++; return true; } index++; } index = dictionary.count + 1; current = new KeyValuePair<TKey, TValue>(); return false; } public KeyValuePair<TKey, TValue> Current { get { return current; } } public void Dispose() { } object IEnumerator.Current { get { if (index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen); } if (getEnumeratorRetType == DictEntry) { return new System.Collections.DictionaryEntry(current.Key, current.Value); } else { return new KeyValuePair<TKey, TValue>(current.Key, current.Value); } } } void IEnumerator.Reset() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); } index = 0; current = new KeyValuePair<TKey, TValue>(); } DictionaryEntry IDictionaryEnumerator.Entry { get { if (index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen); } return new DictionaryEntry(current.Key, current.Value); } } object IDictionaryEnumerator.Key { get { if (index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen); } return current.Key; } } object IDictionaryEnumerator.Value { get { if (index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen); } return current.Value; } } } [Serializable] public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey> { private Dictionary<TKey, TValue> dictionary; public KeyCollection(Dictionary<TKey, TValue> dictionary) { if (dictionary == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); } this.dictionary = dictionary; } public Enumerator GetEnumerator() { return new Enumerator(dictionary); } public void CopyTo(TKey[] array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < dictionary.Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } int count = dictionary.count; Entry[] entries = dictionary.entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) array[index++] = entries[i].key; } } public int Count { get { return dictionary.Count; } } bool ICollection<TKey>.IsReadOnly { get { return true; } } void ICollection<TKey>.Add(TKey item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); } void ICollection<TKey>.Clear() { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); } bool ICollection<TKey>.Contains(TKey item) { return dictionary.ContainsKey(item); } bool ICollection<TKey>.Remove(TKey item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_KeyCollectionSet); return false; } IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator() { return new Enumerator(dictionary); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(dictionary); } void ICollection.CopyTo(Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < dictionary.Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } TKey[] keys = array as TKey[]; if (keys != null) { CopyTo(keys, index); } else { object[] objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType); } int count = dictionary.count; Entry[] entries = dictionary.entries; try { for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) objects[index++] = entries[i].key; } } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType); } } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return ((ICollection)dictionary).SyncRoot; } } [Serializable] public struct Enumerator : IEnumerator<TKey>, System.Collections.IEnumerator { private Dictionary<TKey, TValue> dictionary; private int index; private int version; private TKey currentKey; internal Enumerator(Dictionary<TKey, TValue> dictionary) { this.dictionary = dictionary; version = dictionary.version; index = 0; currentKey = default(TKey); } public void Dispose() { } public bool MoveNext() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); } while ((uint)index < (uint)dictionary.count) { if (dictionary.entries[index].hashCode >= 0) { currentKey = dictionary.entries[index].key; index++; return true; } index++; } index = dictionary.count + 1; currentKey = default(TKey); return false; } public TKey Current { get { return currentKey; } } Object System.Collections.IEnumerator.Current { get { if (index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen); } return currentKey; } } void System.Collections.IEnumerator.Reset() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); } index = 0; currentKey = default(TKey); } } } [Serializable] public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue> { private Dictionary<TKey, TValue> dictionary; public ValueCollection(Dictionary<TKey, TValue> dictionary) { if (dictionary == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary); } this.dictionary = dictionary; } public Enumerator GetEnumerator() { return new Enumerator(dictionary); } public void CopyTo(TValue[] array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < dictionary.Count) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); } int count = dictionary.count; Entry[] entries = dictionary.entries; for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) array[index++] = entries[i].value; } } public int Count { get { return dictionary.Count; } } bool ICollection<TValue>.IsReadOnly { get { return true; } } void ICollection<TValue>.Add(TValue item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); } bool ICollection<TValue>.Remove(TValue item) { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); return false; } void ICollection<TValue>.Clear() { ThrowHelper.ThrowNotSupportedException(ExceptionResource.NotSupported_ValueCollectionSet); } bool ICollection<TValue>.Contains(TValue item) { return dictionary.ContainsValue(item); } IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator() { return new Enumerator(dictionary); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(dictionary); } void ICollection.CopyTo(Array array, int index) { if (array == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.array); } if (array.Rank != 1) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_NonZeroLowerBound); } if (index < 0 || index > array.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < dictionary.Count) ThrowHelper.ThrowArgumentException(ExceptionResource.Arg_ArrayPlusOffTooSmall); TValue[] values = array as TValue[]; if (values != null) { CopyTo(values, index); } else { object[] objects = array as object[]; if (objects == null) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType); } int count = dictionary.count; Entry[] entries = dictionary.entries; try { for (int i = 0; i < count; i++) { if (entries[i].hashCode >= 0) objects[index++] = entries[i].value; } } catch (ArrayTypeMismatchException) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_InvalidArrayType); } } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return ((ICollection)dictionary).SyncRoot; } } [Serializable] public struct Enumerator : IEnumerator<TValue>, System.Collections.IEnumerator { private Dictionary<TKey, TValue> dictionary; private int index; private int version; private TValue currentValue; internal Enumerator(Dictionary<TKey, TValue> dictionary) { this.dictionary = dictionary; version = dictionary.version; index = 0; currentValue = default(TValue); } public void Dispose() { } public bool MoveNext() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); } while ((uint)index < (uint)dictionary.count) { if (dictionary.entries[index].hashCode >= 0) { currentValue = dictionary.entries[index].value; index++; return true; } index++; } index = dictionary.count + 1; currentValue = default(TValue); return false; } public TValue Current { get { return currentValue; } } Object System.Collections.IEnumerator.Current { get { if (index == 0 || (index == dictionary.count + 1)) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen); } return currentValue; } } void System.Collections.IEnumerator.Reset() { if (version != dictionary.version) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); } index = 0; currentValue = default(TValue); } } } } public static class CollectionExtensions { public static TValue GetValueOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary, TKey key) { return dictionary.GetValueOrDefault(key, default(TValue)); } public static TValue GetValueOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary, TKey key, TValue defaultValue) { if (dictionary == null) { throw new ArgumentNullException(nameof(dictionary)); } TValue value; return dictionary.TryGetValue(key, out value) ? value : defaultValue; } public static bool TryAdd<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value) { if (dictionary == null) { throw new ArgumentNullException(nameof(dictionary)); } if (!dictionary.ContainsKey(key)) { dictionary.Add(key, value); return true; } return false; } public static bool Remove<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, out TValue value) { if (dictionary == null) { throw new ArgumentNullException(nameof(dictionary)); } if (dictionary.TryGetValue(key, out value)) { dictionary.Remove(key); return true; } value = default(TValue); return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Composition.Runtime.Util; using System.Linq; namespace System.Composition.Hosting.Core { /// <summary> /// The link between exports and imports. /// </summary> public sealed class CompositionContract { private readonly Type _contractType; private readonly string _contractName; private readonly IDictionary<string, object> _metadataConstraints; /// <summary> /// Construct a <see cref="CompositionContract"/>. /// </summary> /// <param name="contractType">The type shared between the exporter and importer.</param> public CompositionContract(Type contractType) : this(contractType, null) { } /// <summary> /// Construct a <see cref="CompositionContract"/>. /// </summary> /// <param name="contractType">The type shared between the exporter and importer.</param> /// <param name="contractName">Optionally, a name that discriminates this contract from others with the same type.</param> public CompositionContract(Type contractType, string contractName) : this(contractType, contractName, null) { } /// <summary> /// Construct a <see cref="CompositionContract"/>. /// </summary> /// <param name="contractType">The type shared between the exporter and importer.</param> /// <param name="contractName">Optionally, a name that discriminates this contract from others with the same type.</param> /// <param name="metadataConstraints">Optionally, a non-empty collection of named constraints that apply to the contract.</param> public CompositionContract(Type contractType, string contractName, IDictionary<string, object> metadataConstraints) { if (contractType == null) throw new ArgumentNullException("contractType"); if (metadataConstraints != null && metadataConstraints.Count == 0) throw new ArgumentOutOfRangeException("metadataConstraints"); _contractType = contractType; _contractName = contractName; _metadataConstraints = metadataConstraints; } /// <summary> /// The type shared between the exporter and importer. /// </summary> public Type ContractType { get { return _contractType; } } /// <summary> /// A name that discriminates this contract from others with the same type. /// </summary> public string ContractName { get { return _contractName; } } /// <summary> /// Constraints applied to the contract. Instead of using this collection /// directly it is advisable to use the <see cref="TryUnwrapMetadataConstraint"/> method. /// </summary> public IEnumerable<KeyValuePair<string, object>> MetadataConstraints { get { return _metadataConstraints; } } /// <summary> /// Determines equality between two contracts. /// </summary> /// <param name="obj">The contract to test.</param> /// <returns>True if the the contracts are equivalent; otherwise, false.</returns> public override bool Equals(object obj) { var contract = obj as CompositionContract; return contract != null && contract._contractType.Equals(_contractType) && (_contractName == null ? contract._contractName == null : _contractName.Equals(contract._contractName)) && ConstraintEqual(_metadataConstraints, contract._metadataConstraints); } /// <summary> /// Gets a hash code for the contract. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { var hc = _contractType.GetHashCode(); if (_contractName != null) hc = hc ^ _contractName.GetHashCode(); if (_metadataConstraints != null) hc = hc ^ ConstraintHashCode(_metadataConstraints); return hc; } /// <summary> /// Creates a string representaiton of the contract. /// </summary> /// <returns>A string representaiton of the contract.</returns> public override string ToString() { var result = Formatters.Format(_contractType); if (_contractName != null) result += " " + Formatters.Format(_contractName); if (_metadataConstraints != null) result += string.Format(" {{ {0} }}", string.Join(Properties.Resources.Formatter_ListSeparatorWithSpace, _metadataConstraints.Select(kv => string.Format("{0} = {1}", kv.Key, Formatters.Format(kv.Value))))); return result; } /// <summary> /// Transform the contract into a matching contract with a /// new contract type (with the same contract name and constraints). /// </summary> /// <param name="newContractType">The contract type for the new contract.</param> /// <returns>A matching contract with a /// new contract type.</returns> public CompositionContract ChangeType(Type newContractType) { if (newContractType == null) throw new ArgumentNullException("newContractType"); return new CompositionContract(newContractType, _contractName, _metadataConstraints); } /// <summary> /// Check the contract for a constraint with a particular name and value, and, if it exists, /// retrieve both the value and the remainder of the contract with the constraint /// removed. /// </summary> /// <typeparam name="T">The type of the constraint value.</typeparam> /// <param name="constraintName">The name of the constraint.</param> /// <param name="constraintValue">The value if it is present and of the correct type, otherwise null.</param> /// <param name="remainingContract">The contract with the constraint removed if present, otherwise null.</param> /// <returns>True if the constraint is present and of the correct type, otherwise false.</returns> public bool TryUnwrapMetadataConstraint<T>(string constraintName, out T constraintValue, out CompositionContract remainingContract) { if (constraintName == null) throw new ArgumentNullException("constraintName"); constraintValue = default(T); remainingContract = null; if (_metadataConstraints == null) return false; object value; if (!_metadataConstraints.TryGetValue(constraintName, out value)) return false; if (!(value is T)) return false; constraintValue = (T)value; if (_metadataConstraints.Count == 1) { remainingContract = new CompositionContract(_contractType, _contractName); } else { var remainingConstraints = new Dictionary<string, object>(_metadataConstraints); remainingConstraints.Remove(constraintName); remainingContract = new CompositionContract(_contractType, _contractName, remainingConstraints); } return true; } internal static bool ConstraintEqual(IDictionary<string, object> first, IDictionary<string, object> second) { if (first == second) return true; if (first == null || second == null) return false; if (first.Count != second.Count) return false; foreach (var firstItem in first) { object secondValue; if (!second.TryGetValue(firstItem.Key, out secondValue)) return false; if (firstItem.Value == null && secondValue != null || secondValue == null && firstItem.Value != null) { return false; } else { var firstEnumerable = firstItem.Value as IEnumerable; if (firstEnumerable != null && !(firstEnumerable is string)) { var secondEnumerable = secondValue as IEnumerable; if (secondEnumerable == null || !Enumerable.SequenceEqual(firstEnumerable.Cast<object>(), secondEnumerable.Cast<object>())) return false; } else if (!firstItem.Value.Equals(secondValue)) { return false; } } } return true; } private static int ConstraintHashCode(IDictionary<string, object> metadata) { var result = -1; foreach (var kv in metadata) { result ^= kv.Key.GetHashCode(); if (kv.Value != null) { var sval = kv.Value as string; if (sval != null) { result ^= sval.GetHashCode(); } else { var enumerableValue = kv.Value as IEnumerable; if (enumerableValue != null) { foreach (var ev in enumerableValue) if (ev != null) result ^= ev.GetHashCode(); } else { result ^= kv.Value.GetHashCode(); } } } } return result; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Linq; using System; using Xunit; using Validation; using System.Diagnostics; namespace System.Collections.Immutable.Test { public abstract class ImmutableListTestBase : SimpleElementImmutablesTestBase { internal abstract IImmutableListQueries<T> GetListQuery<T>(ImmutableList<T> list); [Fact] public void CopyToEmptyTest() { var array = new int[0]; this.GetListQuery(ImmutableList<int>.Empty).CopyTo(array); this.GetListQuery(ImmutableList<int>.Empty).CopyTo(array, 0); this.GetListQuery(ImmutableList<int>.Empty).CopyTo(0, array, 0, 0); ((ICollection)this.GetListQuery(ImmutableList<int>.Empty)).CopyTo(array, 0); } [Fact] public void CopyToTest() { var listQuery = this.GetListQuery(ImmutableList.Create(1, 2)); var list = (IEnumerable<int>)listQuery; var array = new int[2]; listQuery.CopyTo(array); Assert.Equal(list, array); array = new int[2]; listQuery.CopyTo(array, 0); Assert.Equal(list, array); array = new int[2]; listQuery.CopyTo(0, array, 0, listQuery.Count); Assert.Equal(list, array); array = new int[1]; // shorter than source length listQuery.CopyTo(0, array, 0, array.Length); Assert.Equal(list.Take(array.Length), array); array = new int[3]; listQuery.CopyTo(1, array, 2, 1); Assert.Equal(new[] { 0, 0, 2 }, array); array = new int[2]; ((ICollection)listQuery).CopyTo(array, 0); Assert.Equal(list, array); } [Fact] public void ForEachTest() { this.GetListQuery(ImmutableList<int>.Empty).ForEach(n => Assert.True(false, "Empty list should not invoke this.")); var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 3)); var hitTest = new bool[list.Max() + 1]; this.GetListQuery(list).ForEach(i => { Assert.False(hitTest[i]); hitTest[i] = true; }); for (int i = 0; i < hitTest.Length; i++) { Assert.Equal(list.Contains(i), hitTest[i]); Assert.Equal(((IList)list).Contains(i), hitTest[i]); } } [Fact] public void ExistsTest() { Assert.False(this.GetListQuery(ImmutableList<int>.Empty).Exists(n => true)); var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 5)); Assert.True(this.GetListQuery(list).Exists(n => n == 3)); Assert.False(this.GetListQuery(list).Exists(n => n == 8)); } [Fact] public void FindAllTest() { Assert.True(this.GetListQuery(ImmutableList<int>.Empty).FindAll(n => true).IsEmpty); var list = ImmutableList<int>.Empty.AddRange(new[] { 2, 3, 4, 5, 6 }); var actual = this.GetListQuery(list).FindAll(n => n % 2 == 1); var expected = list.ToList().FindAll(n => n % 2 == 1); Assert.Equal<int>(expected, actual.ToList()); } [Fact] public void FindTest() { Assert.Equal(0, this.GetListQuery(ImmutableList<int>.Empty).Find(n => true)); var list = ImmutableList<int>.Empty.AddRange(new[] { 2, 3, 4, 5, 6 }); Assert.Equal(3, this.GetListQuery(list).Find(n => (n % 2) == 1)); } [Fact] public void FindLastTest() { Assert.Equal(0, this.GetListQuery(ImmutableList<int>.Empty).FindLast(n => { Assert.True(false, "Predicate should not have been invoked."); return true; })); var list = ImmutableList<int>.Empty.AddRange(new[] { 2, 3, 4, 5, 6 }); Assert.Equal(5, this.GetListQuery(list).FindLast(n => (n % 2) == 1)); } [Fact] public void FindIndexTest() { Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindIndex(n => true)); Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindIndex(0, n => true)); Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindIndex(0, 0, n => true)); // Create a list with contents: 100,101,102,103,104,100,101,102,103,104 var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(100, 5).Concat(Enumerable.Range(100, 5))); var bclList = list.ToList(); Assert.Equal(-1, this.GetListQuery(list).FindIndex(n => n == 6)); for (int idx = 0; idx < list.Count; idx++) { for (int count = 0; count <= list.Count - idx; count++) { foreach (int c in list) { int predicateInvocationCount = 0; Predicate<int> match = n => { predicateInvocationCount++; return n == c; }; int expected = bclList.FindIndex(idx, count, match); int expectedInvocationCount = predicateInvocationCount; predicateInvocationCount = 0; int actual = this.GetListQuery(list).FindIndex(idx, count, match); int actualInvocationCount = predicateInvocationCount; Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); if (count == list.Count) { // Also test the FindIndex overload that takes no count parameter. predicateInvocationCount = 0; actual = this.GetListQuery(list).FindIndex(idx, match); Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); if (idx == 0) { // Also test the FindIndex overload that takes no index parameter. predicateInvocationCount = 0; actual = this.GetListQuery(list).FindIndex(match); Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); } } } } } } [Fact] public void FindLastIndexTest() { Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindLastIndex(n => true)); Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindLastIndex(0, n => true)); Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindLastIndex(0, 0, n => true)); // Create a list with contents: 100,101,102,103,104,100,101,102,103,104 var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(100, 5).Concat(Enumerable.Range(100, 5))); var bclList = list.ToList(); Assert.Equal(-1, this.GetListQuery(list).FindLastIndex(n => n == 6)); for (int idx = 0; idx < list.Count; idx++) { for (int count = 0; count <= idx + 1; count++) { foreach (int c in list) { int predicateInvocationCount = 0; Predicate<int> match = n => { predicateInvocationCount++; return n == c; }; int expected = bclList.FindLastIndex(idx, count, match); int expectedInvocationCount = predicateInvocationCount; predicateInvocationCount = 0; int actual = this.GetListQuery(list).FindLastIndex(idx, count, match); int actualInvocationCount = predicateInvocationCount; Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); if (count == list.Count) { // Also test the FindIndex overload that takes no count parameter. predicateInvocationCount = 0; actual = this.GetListQuery(list).FindLastIndex(idx, match); Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); if (idx == list.Count - 1) { // Also test the FindIndex overload that takes no index parameter. predicateInvocationCount = 0; actual = this.GetListQuery(list).FindLastIndex(match); Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); } } } } } } #if PORTABLE public delegate TOutput Converter<in TInput, out TOutput>(TInput input); #endif [Fact] public void ConvertAllTest() { Assert.True(this.GetListQuery(ImmutableList<int>.Empty).ConvertAll<float>(n => n).IsEmpty); var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10)); Converter<int, double> converter = n => 2.0 * n; Func<int, double> funcConverter = n => converter(n); #if PORTABLE var expected = list.ToList().Select(funcConverter).ToList(); #else var expected = list.ToList().ConvertAll(converter); #endif var actual = this.GetListQuery(list).ConvertAll(funcConverter); Assert.Equal<double>(expected.ToList(), actual.ToList()); } [Fact] public void GetRangeTest() { Assert.True(this.GetListQuery(ImmutableList<int>.Empty).GetRange(0, 0).IsEmpty); var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10)); var bclList = list.ToList(); for (int index = 0; index < list.Count; index++) { for (int count = 0; count < list.Count - index; count++) { var expected = bclList.GetRange(index, count); var actual = this.GetListQuery(list).GetRange(index, count); Assert.Equal<int>(expected.ToList(), actual.ToList()); } } } [Fact] public void TrueForAllTest() { Assert.True(this.GetListQuery(ImmutableList<int>.Empty).TrueForAll(n => false)); var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10)); this.TrueForAllTestHelper(list, n => n % 2 == 0); this.TrueForAllTestHelper(list, n => n % 2 == 1); this.TrueForAllTestHelper(list, n => true); } [Fact] public void RemoveAllTest() { var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10)); this.RemoveAllTestHelper(list, n => false); this.RemoveAllTestHelper(list, n => true); this.RemoveAllTestHelper(list, n => n < 7); this.RemoveAllTestHelper(list, n => n > 7); this.RemoveAllTestHelper(list, n => n == 7); } [Fact] public void ReverseTest() { var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10)); for (int i = 0; i < list.Count; i++) { for (int j = 0; j < list.Count - i; j++) { this.ReverseTestHelper(list, i, j); } } } [Fact] public void SortTest() { var scenarios = new[] { ImmutableList<int>.Empty, ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 50)), ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 50).Reverse()), }; foreach (var scenario in scenarios) { var expected = scenario.ToList(); expected.Sort(); var actual = this.SortTestHelper(scenario); Assert.Equal<int>(expected, actual); expected = scenario.ToList(); Comparison<int> comparison = (x, y) => x > y ? 1 : (x < y ? -1 : 0); expected.Sort(comparison); actual = this.SortTestHelper(scenario, comparison); Assert.Equal<int>(expected, actual); expected = scenario.ToList(); IComparer<int> comparer = Comparer<int>.Default; expected.Sort(comparer); actual = this.SortTestHelper(scenario, comparer); Assert.Equal<int>(expected, actual); for (int i = 0; i < scenario.Count; i++) { for (int j = 0; j < scenario.Count - i; j++) { expected = scenario.ToList(); comparer = Comparer<int>.Default; expected.Sort(i, j, comparer); actual = this.SortTestHelper(scenario, i, j, comparer); Assert.Equal<int>(expected, actual); } } } } [Fact] public void BinarySearch() { var basis = new List<int>(Enumerable.Range(1, 50).Select(n => n * 2)); var query = this.GetListQuery(basis.ToImmutableList()); for (int value = basis.First() - 1; value <= basis.Last() + 1; value++) { int expected = basis.BinarySearch(value); int actual = query.BinarySearch(value); if (expected != actual) Debugger.Break(); Assert.Equal(expected, actual); for (int index = 0; index < basis.Count - 1; index++) { for (int count = 0; count <= basis.Count - index; count++) { expected = basis.BinarySearch(index, count, value, null); actual = query.BinarySearch(index, count, value, null); if (expected != actual) Debugger.Break(); Assert.Equal(expected, actual); } } } } [Fact] public void BinarySearchPartialSortedList() { var reverseSorted = ImmutableArray.CreateRange(Enumerable.Range(1, 150).Select(n => n * 2).Reverse()); this.BinarySearchPartialSortedListHelper(reverseSorted, 0, 50); this.BinarySearchPartialSortedListHelper(reverseSorted, 50, 50); this.BinarySearchPartialSortedListHelper(reverseSorted, 100, 50); } private void BinarySearchPartialSortedListHelper(ImmutableArray<int> inputData, int sortedIndex, int sortedLength) { Requires.Range(sortedIndex >= 0, "sortedIndex"); Requires.Range(sortedLength > 0, "sortedLength"); inputData = inputData.Sort(sortedIndex, sortedLength, Comparer<int>.Default); int min = inputData[sortedIndex]; int max = inputData[sortedIndex + sortedLength - 1]; var basis = new List<int>(inputData); var query = this.GetListQuery(inputData.ToImmutableList()); for (int value = min - 1; value <= max + 1; value++) { for (int index = sortedIndex; index < sortedIndex + sortedLength; index++) // make sure the index we pass in is always within the sorted range in the list. { for (int count = 0; count <= sortedLength - index; count++) { int expected = basis.BinarySearch(index, count, value, null); int actual = query.BinarySearch(index, count, value, null); if (expected != actual) Debugger.Break(); Assert.Equal(expected, actual); } } } } [Fact] public void SyncRoot() { var collection = (ICollection)this.GetEnumerableOf<int>(); Assert.NotNull(collection.SyncRoot); Assert.Same(collection.SyncRoot, collection.SyncRoot); } [Fact] public void GetEnumeratorTest() { var enumerable = this.GetEnumerableOf(1); Assert.Equal(new[] { 1 }, enumerable.ToList()); // exercises the enumerator IEnumerable enumerableNonGeneric = enumerable; Assert.Equal(new[] { 1 }, enumerableNonGeneric.Cast<int>().ToList()); // exercises the enumerator } protected abstract void RemoveAllTestHelper<T>(ImmutableList<T> list, Predicate<T> test); protected abstract void ReverseTestHelper<T>(ImmutableList<T> list, int index, int count); protected abstract List<T> SortTestHelper<T>(ImmutableList<T> list); protected abstract List<T> SortTestHelper<T>(ImmutableList<T> list, Comparison<T> comparison); protected abstract List<T> SortTestHelper<T>(ImmutableList<T> list, IComparer<T> comparer); protected abstract List<T> SortTestHelper<T>(ImmutableList<T> list, int index, int count, IComparer<T> comparer); private void TrueForAllTestHelper<T>(ImmutableList<T> list, Predicate<T> test) { var bclList = list.ToList(); var expected = bclList.TrueForAll(test); var actual = this.GetListQuery(list).TrueForAll(test); Assert.Equal(expected, actual); } } }
/*************************************************************************** * FeedUpdateTask.cs * * Copyright (C) 2007 Michael C. Urbanski * Written by Mike Urbanski <[email protected]> ****************************************************************************/ /* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: * * 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.Threading; using System.ComponentModel; using System.Net; using Hyena; using Migo.Net; using Migo.TaskCore; namespace Migo.Syndication { public class FeedUpdateTask : Task, IDisposable { private Feed feed; private bool disposed, cancelled, completed; private ManualResetEvent mre; private AsyncWebClient wc = null; public Feed Feed { get { return feed; } } public override WaitHandle WaitHandle { get { lock (SyncRoot) { if (mre == null) { mre = new ManualResetEvent (true); } return mre; } } } #region Constructor public FeedUpdateTask (Feed feed) { if (feed == null) { throw new ArgumentNullException ("feed"); } this.feed = feed; this.Name = feed.Link; feed.DownloadStatus = FeedDownloadStatus.Pending; } #endregion #region Public Methods public override void CancelAsync () { lock (SyncRoot) { if (!completed) { cancelled = true; if (wc != null) { wc.CancelAsync (); } EmitCompletionEvents (FeedDownloadError.Canceled); } } } public void Dispose () { lock (SyncRoot) { if (!disposed) { if (mre != null) { mre.Close (); mre = null; } disposed = true; } } } public override void ExecuteAsync () { lock (SyncRoot) { SetStatus (TaskStatus.Running); if (mre != null) { mre.Reset (); } } try { wc = new AsyncWebClient (); wc.Timeout = (30 * 1000); // 30 Seconds if (feed.LastDownloadError == FeedDownloadError.None && feed.LastDownloadTime != DateTime.MinValue) { wc.IfModifiedSince = feed.LastDownloadTime.ToUniversalTime (); } wc.DownloadStringCompleted += OnDownloadDataReceived; feed.DownloadStatus = FeedDownloadStatus.Downloading; wc.DownloadStringAsync (new Uri (feed.Url)); } catch (Exception e) { if (wc != null) { wc.DownloadStringCompleted -= OnDownloadDataReceived; } EmitCompletionEvents (FeedDownloadError.DownloadFailed); Log.Error (e); } } #endregion private void OnDownloadDataReceived (object sender, Migo.Net.DownloadStringCompletedEventArgs args) { bool notify_on_save = true; lock (SyncRoot) { if (cancelled) return; wc.DownloadStringCompleted -= OnDownloadDataReceived; FeedDownloadError error; WebException we = args.Error as WebException; if (we == null) { try { DateTime last_built_at = feed.LastBuildDate; RssParser parser = new RssParser (feed.Url, args.Result); parser.UpdateFeed (feed); feed.SetItems (parser.GetFeedItems (feed)); error = FeedDownloadError.None; notify_on_save = feed.LastBuildDate > last_built_at; } catch (FormatException e) { Log.Warning (e); error = FeedDownloadError.InvalidFeedFormat; } } else { error = FeedDownloadError.DownloadFailed; HttpWebResponse resp = we.Response as HttpWebResponse; if (resp != null) { switch (resp.StatusCode) { case HttpStatusCode.NotFound: case HttpStatusCode.Gone: error = FeedDownloadError.DoesNotExist; break; case HttpStatusCode.NotModified: notify_on_save = false; error = FeedDownloadError.None; break; case HttpStatusCode.Unauthorized: error = FeedDownloadError.UnsupportedAuth; break; default: error = FeedDownloadError.DownloadFailed; break; } } } feed.LastDownloadError = error; feed.LastDownloadTime = DateTime.Now; feed.Save (notify_on_save); EmitCompletionEvents (error); completed = true; } } private void EmitCompletionEvents (FeedDownloadError err) { switch (err) { case FeedDownloadError.None: SetStatus (TaskStatus.Succeeded); feed.DownloadStatus = FeedDownloadStatus.Downloaded; break; case FeedDownloadError.Canceled: SetStatus (TaskStatus.Cancelled); feed.DownloadStatus = FeedDownloadStatus.None; break; default: SetStatus (TaskStatus.Failed); feed.DownloadStatus = FeedDownloadStatus.DownloadFailed; break; } OnTaskCompleted (null, (Status == TaskStatus.Cancelled)); if (mre != null) { mre.Set (); } } } }
//----------------------------------------------------------------------------- // // <copyright file="StreamWithDictionary.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: // The object for wrapping a data stream and its associated context // information dictionary. // // History: // 07/05/2002: RogerCh: Initial implementation. // 05/20/2003: RogerCh: Ported to WCP tree. // //----------------------------------------------------------------------------- using System; using System.Collections; using System.IO; namespace MS.Internal.IO.Packaging.CompoundFile { internal class StreamWithDictionary : Stream, IDictionary { Stream baseStream; IDictionary baseDictionary; private bool _disposed; // keep track of if we are disposed internal StreamWithDictionary( Stream wrappedStream, IDictionary wrappedDictionary ) { baseStream = wrappedStream; baseDictionary = wrappedDictionary; } /*************************************************************************/ // Stream members public override bool CanRead { get{ return !_disposed && baseStream.CanRead; }} public override bool CanSeek { get { return !_disposed && baseStream.CanSeek; } } public override bool CanWrite { get { return !_disposed && baseStream.CanWrite; } } public override long Length { get { CheckDisposed(); return baseStream.Length; } } public override long Position { get { CheckDisposed(); return baseStream.Position; } set { CheckDisposed(); baseStream.Position = value; } } public override void Flush() { CheckDisposed(); baseStream.Flush(); } public override long Seek( long offset, SeekOrigin origin ) { CheckDisposed(); return baseStream.Seek(offset, origin); } public override void SetLength( long newLength ) { CheckDisposed(); baseStream.SetLength(newLength); } public override int Read( byte[] buffer, int offset, int count ) { CheckDisposed(); return baseStream.Read(buffer, offset, count); } public override void Write( byte[] buffer, int offset, int count ) { CheckDisposed(); baseStream.Write(buffer, offset, count); } //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ /// <summary> /// Dispose(bool) /// </summary> /// <param name="disposing"></param> protected override void Dispose(bool disposing) { try { if (disposing && !_disposed) { _disposed = true; baseStream.Close(); } } finally { base.Dispose(disposing); } } /*************************************************************************/ // IDictionary members bool IDictionary.Contains( object key ) { CheckDisposed(); return baseDictionary.Contains(key); } void IDictionary.Add( object key, object val ) { CheckDisposed(); baseDictionary.Add(key, val); } void IDictionary.Clear() { CheckDisposed(); baseDictionary.Clear(); } IDictionaryEnumerator IDictionary.GetEnumerator() { CheckDisposed(); // IDictionary.GetEnumerator vs. IEnumerable.GetEnumerator? return ((IDictionary)baseDictionary).GetEnumerator(); } void IDictionary.Remove( object key ) { CheckDisposed(); baseDictionary.Remove(key); } object IDictionary.this[ object index ] { get { CheckDisposed(); return baseDictionary[index]; } set { CheckDisposed(); baseDictionary[index] = value; } } ICollection IDictionary.Keys { get { CheckDisposed(); return baseDictionary.Keys; } } ICollection IDictionary.Values { get { CheckDisposed(); return baseDictionary.Values; } } bool IDictionary.IsReadOnly { get { CheckDisposed(); return baseDictionary.IsReadOnly; } } bool IDictionary.IsFixedSize { get { CheckDisposed(); return baseDictionary.IsFixedSize; } } /*************************************************************************/ // ICollection methods void ICollection.CopyTo( Array array, int index ) { CheckDisposed(); ((ICollection)baseDictionary).CopyTo(array, index); } int ICollection.Count { get { CheckDisposed(); return ((ICollection)baseDictionary).Count; } } object ICollection.SyncRoot { get { CheckDisposed(); return ((ICollection)baseDictionary).SyncRoot; } } bool ICollection.IsSynchronized { get { CheckDisposed(); return ((ICollection)baseDictionary).IsSynchronized; } } /*************************************************************************/ // IEnumerable method IEnumerator IEnumerable.GetEnumerator() { CheckDisposed(); return ((IEnumerable)baseDictionary).GetEnumerator(); } /// <summary> /// Disposed - were we disposed? Offer this to DataSpaceManager so it can do smart flushing /// </summary> /// <returns></returns> internal bool Disposed { get { return _disposed; } } //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ private void CheckDisposed() { if (_disposed) throw new ObjectDisposedException("Stream"); } } }
using System; using System.Collections.Generic; using System.Text; using GuruComponents.Netrix.ComInterop; using System.Web.UI.Design; using GuruComponents.Netrix.Events; using GuruComponents.Netrix.WebEditing.Elements; using System.ComponentModel.Design; namespace GuruComponents.Netrix.XmlDesigner { /// <summary> /// The purpose of this class is to deal with the events a control will /// fire at design time. /// </summary> internal sealed class BogusSink : Interop.IHTMLTextContainerEvents { private Interop.IHTMLElement _element; private ConnectionPointCookie _eventSinkCookie; private Interop.IHTMLDocument2 _document; private Interop.IHTMLEventObj _eventobj; public BogusSink() { } /// <summary> /// Connects the specified control and its underlying element to the event sink. /// </summary> /// <param name="_control">Control to connect.</param> /// <param name="element">Underlying element of control.</param> public void Connect(Interop.IHTMLElement element) { try { this._element = element; this._eventSinkCookie = new ConnectionPointCookie(this._element, this, typeof(Interop.IHTMLTextContainerEvents)); } catch (Exception) { } } public void Disconnect() { if (this._eventSinkCookie != null) { this._eventSinkCookie.Disconnect(); this._eventSinkCookie = null; } this._element = null; } private Interop.IHTMLEventObj GetEventObject() { if (_element == null) return null; _document = (Interop.IHTMLDocument2)this._element.GetDocument(); Interop.IHTMLWindow2 window1 = _document.GetParentWindow(); return window1.@event; } void Invoke() { //nArgError = new int[] { Interop.S_FALSE }; _eventobj = this.GetEventObject(); if (_eventobj != null && _eventobj.srcElement != null) { System.Diagnostics.Debug.WriteLineIf(_eventobj.srcElement != null, _eventobj.type, _eventobj.srcElement.GetTagName()); _eventobj.cancelBubble = true; } } #region IHTMLTextContainerEvents Members bool Interop.IHTMLTextContainerEvents.onhelp() { Invoke(); return Convert.ToBoolean(_eventobj.returnValue); } bool Interop.IHTMLTextContainerEvents.onclick() { Invoke(); return Convert.ToBoolean(_eventobj.returnValue); } bool Interop.IHTMLTextContainerEvents.ondblclick() { Invoke(); return Convert.ToBoolean(_eventobj.returnValue); } bool Interop.IHTMLTextContainerEvents.onkeypress() { Invoke(); return Convert.ToBoolean(_eventobj.returnValue); } void Interop.IHTMLTextContainerEvents.onkeydown() { Invoke(); } void Interop.IHTMLTextContainerEvents.onkeyup() { Invoke(); } void Interop.IHTMLTextContainerEvents.onmouseout() { Invoke(); } void Interop.IHTMLTextContainerEvents.onmouseover() { Invoke(); } void Interop.IHTMLTextContainerEvents.onmousemove() { Invoke(); } void Interop.IHTMLTextContainerEvents.onmousedown() { Invoke(); } void Interop.IHTMLTextContainerEvents.onmouseup() { Invoke(); } bool Interop.IHTMLTextContainerEvents.onselectstart() { Invoke(); return Convert.ToBoolean(_eventobj.returnValue); } void Interop.IHTMLTextContainerEvents.onfilterchange() { Invoke(); } bool Interop.IHTMLTextContainerEvents.ondragstart() { Invoke(); return Convert.ToBoolean(_eventobj.returnValue); } bool Interop.IHTMLTextContainerEvents.onbeforeupdate() { Invoke(); return Convert.ToBoolean(_eventobj.returnValue); } void Interop.IHTMLTextContainerEvents.onafterupdate() { Invoke(); } bool Interop.IHTMLTextContainerEvents.onerrorupdate() { Invoke(); return Convert.ToBoolean(_eventobj.returnValue); } bool Interop.IHTMLTextContainerEvents.onrowexit() { Invoke(); return Convert.ToBoolean(_eventobj.returnValue); } void Interop.IHTMLTextContainerEvents.onrowenter() { Invoke(); } void Interop.IHTMLTextContainerEvents.ondatasetchanged() { Invoke(); } void Interop.IHTMLTextContainerEvents.ondataavailable() { Invoke(); } void Interop.IHTMLTextContainerEvents.ondatasetcomplete() { Invoke(); } void Interop.IHTMLTextContainerEvents.onlosecapture() { Invoke(); } void Interop.IHTMLTextContainerEvents.onpropertychange() { Invoke(); } void Interop.IHTMLTextContainerEvents.onscroll() { Invoke(); } void Interop.IHTMLTextContainerEvents.onfocus() { Invoke(); } void Interop.IHTMLTextContainerEvents.onblur() { Invoke(); } void Interop.IHTMLTextContainerEvents.onresize() { Invoke(); } bool Interop.IHTMLTextContainerEvents.ondrag() { Invoke(); return Convert.ToBoolean(_eventobj.returnValue); } void Interop.IHTMLTextContainerEvents.ondragend() { Invoke(); } bool Interop.IHTMLTextContainerEvents.ondragenter() { Invoke(); return Convert.ToBoolean(_eventobj.returnValue); } bool Interop.IHTMLTextContainerEvents.ondragover() { Invoke(); return Convert.ToBoolean(_eventobj.returnValue); } void Interop.IHTMLTextContainerEvents.ondragleave() { Invoke(); } bool Interop.IHTMLTextContainerEvents.ondrop() { Invoke(); return Convert.ToBoolean(_eventobj.returnValue); } bool Interop.IHTMLTextContainerEvents.onbeforecut() { Invoke(); return Convert.ToBoolean(_eventobj.returnValue); } bool Interop.IHTMLTextContainerEvents.oncut() { Invoke(); return Convert.ToBoolean(_eventobj.returnValue); } bool Interop.IHTMLTextContainerEvents.onbeforecopy() { Invoke(); return Convert.ToBoolean(_eventobj.returnValue); } bool Interop.IHTMLTextContainerEvents.oncopy() { Invoke(); return Convert.ToBoolean(_eventobj.returnValue); } bool Interop.IHTMLTextContainerEvents.onbeforepaste() { Invoke(); return Convert.ToBoolean(_eventobj.returnValue); } bool Interop.IHTMLTextContainerEvents.onpaste() { Invoke(); return Convert.ToBoolean(_eventobj.returnValue); } bool Interop.IHTMLTextContainerEvents.oncontextmenu() { Invoke(); return Convert.ToBoolean(_eventobj.returnValue); } void Interop.IHTMLTextContainerEvents.onrowsdelete() { Invoke(); } void Interop.IHTMLTextContainerEvents.onrowsinserted() { Invoke(); } void Interop.IHTMLTextContainerEvents.oncellchange() { Invoke(); } void Interop.IHTMLTextContainerEvents.onreadystatechange() { Invoke(); } void Interop.IHTMLTextContainerEvents.onbeforeeditfocus() { Invoke(); } void Interop.IHTMLTextContainerEvents.onlayoutcomplete() { Invoke(); } void Interop.IHTMLTextContainerEvents.onpage() { Invoke(); } bool Interop.IHTMLTextContainerEvents.onbeforedeactivate() { Invoke(); return Convert.ToBoolean(_eventobj.returnValue); } bool Interop.IHTMLTextContainerEvents.onbeforeactivate() { Invoke(); return Convert.ToBoolean(_eventobj.returnValue); } void Interop.IHTMLTextContainerEvents.onmove() { Invoke(); } bool Interop.IHTMLTextContainerEvents.oncontrolselect() { Invoke(); ((Interop.IHTMLElement3)_eventobj.srcElement).setActive(); return false; // Convert.ToBoolean(_eventobj.returnValue); } bool Interop.IHTMLTextContainerEvents.onmovestart() { Invoke(); return Convert.ToBoolean(_eventobj.returnValue); } void Interop.IHTMLTextContainerEvents.onmoveend() { Invoke(); } bool Interop.IHTMLTextContainerEvents.onresizestart() { Invoke(); return Convert.ToBoolean(_eventobj.returnValue); } void Interop.IHTMLTextContainerEvents.onresizeend() { Invoke(); } void Interop.IHTMLTextContainerEvents.onmouseenter() { Invoke(); } void Interop.IHTMLTextContainerEvents.onmouseleave() { Invoke(); } bool Interop.IHTMLTextContainerEvents.onmousewheel() { Invoke(); return Convert.ToBoolean(_eventobj.returnValue); } void Interop.IHTMLTextContainerEvents.onactivate() { Invoke(); } void Interop.IHTMLTextContainerEvents.ondeactivate() { Invoke(); } void Interop.IHTMLTextContainerEvents.onfocusin() { Invoke(); } void Interop.IHTMLTextContainerEvents.onfocusout() { Invoke(); } void Interop.IHTMLTextContainerEvents.onchange() { Invoke(); } void Interop.IHTMLTextContainerEvents.onselect() { Invoke(); } #endregion } }
/* * DeliveryHub * * DeliveryHub API * * OpenAPI spec version: 1.0.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace IO.Swagger.Model { /// <summary> /// The place where agetns pickup orders to delivery /// </summary> [DataContract] public partial class Shop : IEquatable<Shop>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="Shop" /> class. /// </summary> /// <param name="Id">Id.</param> /// <param name="MerchantId">MerchantId.</param> /// <param name="AreaId">AreaId.</param> /// <param name="MobileContactPhone">MobileContactPhone.</param> /// <param name="CallbackUri">CallbackUri.</param> /// <param name="RealAddress">RealAddress.</param> /// <param name="RealAddressCoordinates">RealAddressCoordinates.</param> /// <param name="RealAddressComment">A detailed route to shop description..</param> /// <param name="Name">Shop name.</param> public Shop(ObjectId Id = null, ObjectId MerchantId = null, ObjectId AreaId = null, MobilePhone MobileContactPhone = null, CallbackUri CallbackUri = null, StreetAddress RealAddress = null, Coordinates RealAddressCoordinates = null, string RealAddressComment = null, string Name = null) { this.Id = Id; this.MerchantId = MerchantId; this.AreaId = AreaId; this.MobileContactPhone = MobileContactPhone; this.CallbackUri = CallbackUri; this.RealAddress = RealAddress; this.RealAddressCoordinates = RealAddressCoordinates; this.RealAddressComment = RealAddressComment; this.Name = Name; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public ObjectId Id { get; set; } /// <summary> /// Gets or Sets MerchantId /// </summary> [DataMember(Name="merchantId", EmitDefaultValue=false)] public ObjectId MerchantId { get; set; } /// <summary> /// Gets or Sets AreaId /// </summary> [DataMember(Name="areaId", EmitDefaultValue=false)] public ObjectId AreaId { get; set; } /// <summary> /// Gets or Sets MobileContactPhone /// </summary> [DataMember(Name="mobileContactPhone", EmitDefaultValue=false)] public MobilePhone MobileContactPhone { get; set; } /// <summary> /// Gets or Sets CallbackUri /// </summary> [DataMember(Name="callbackUri", EmitDefaultValue=false)] public CallbackUri CallbackUri { get; set; } /// <summary> /// Gets or Sets RealAddress /// </summary> [DataMember(Name="realAddress", EmitDefaultValue=false)] public StreetAddress RealAddress { get; set; } /// <summary> /// Gets or Sets RealAddressCoordinates /// </summary> [DataMember(Name="realAddressCoordinates", EmitDefaultValue=false)] public Coordinates RealAddressCoordinates { get; set; } /// <summary> /// A detailed route to shop description. /// </summary> /// <value>A detailed route to shop description.</value> [DataMember(Name="realAddressComment", EmitDefaultValue=false)] public string RealAddressComment { get; set; } /// <summary> /// Shop name /// </summary> /// <value>Shop name</value> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { 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 Shop {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" MerchantId: ").Append(MerchantId).Append("\n"); sb.Append(" AreaId: ").Append(AreaId).Append("\n"); sb.Append(" MobileContactPhone: ").Append(MobileContactPhone).Append("\n"); sb.Append(" CallbackUri: ").Append(CallbackUri).Append("\n"); sb.Append(" RealAddress: ").Append(RealAddress).Append("\n"); sb.Append(" RealAddressCoordinates: ").Append(RealAddressCoordinates).Append("\n"); sb.Append(" RealAddressComment: ").Append(RealAddressComment).Append("\n"); sb.Append(" Name: ").Append(Name).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 Shop); } /// <summary> /// Returns true if Shop instances are equal /// </summary> /// <param name="other">Instance of Shop to be compared</param> /// <returns>Boolean</returns> public bool Equals(Shop 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.MerchantId == other.MerchantId || this.MerchantId != null && this.MerchantId.Equals(other.MerchantId) ) && ( this.AreaId == other.AreaId || this.AreaId != null && this.AreaId.Equals(other.AreaId) ) && ( this.MobileContactPhone == other.MobileContactPhone || this.MobileContactPhone != null && this.MobileContactPhone.Equals(other.MobileContactPhone) ) && ( this.CallbackUri == other.CallbackUri || this.CallbackUri != null && this.CallbackUri.Equals(other.CallbackUri) ) && ( this.RealAddress == other.RealAddress || this.RealAddress != null && this.RealAddress.Equals(other.RealAddress) ) && ( this.RealAddressCoordinates == other.RealAddressCoordinates || this.RealAddressCoordinates != null && this.RealAddressCoordinates.Equals(other.RealAddressCoordinates) ) && ( this.RealAddressComment == other.RealAddressComment || this.RealAddressComment != null && this.RealAddressComment.Equals(other.RealAddressComment) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ); } /// <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.MerchantId != null) hash = hash * 59 + this.MerchantId.GetHashCode(); if (this.AreaId != null) hash = hash * 59 + this.AreaId.GetHashCode(); if (this.MobileContactPhone != null) hash = hash * 59 + this.MobileContactPhone.GetHashCode(); if (this.CallbackUri != null) hash = hash * 59 + this.CallbackUri.GetHashCode(); if (this.RealAddress != null) hash = hash * 59 + this.RealAddress.GetHashCode(); if (this.RealAddressCoordinates != null) hash = hash * 59 + this.RealAddressCoordinates.GetHashCode(); if (this.RealAddressComment != null) hash = hash * 59 + this.RealAddressComment.GetHashCode(); if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
using System; using System.Globalization; using System.Linq; using GraphQL.Execution; using GraphQL.Language.AST; using GraphQL.Utilities; using GraphQL.Utilities.Federation; using Shouldly; using Xunit; namespace GraphQL.Tests.Utilities { public class AstPrinterTests { private readonly AstPrintVisitor _printer = new AstPrintVisitor(); private readonly IDocumentBuilder _builder = new GraphQLDocumentBuilder(); [Fact] public void prints_ast() { var query = @"{ complicatedArgs { intArgField(intArg: 2) } } "; var document = _builder.Build(query); var result = _printer.Visit(document); result.ShouldNotBeNull(); result.ToString().ShouldBe(MonetizeLineBreaks(query)); } [Fact] public void prints_variables() { var query = @"mutation createUser($userInput: UserInput!) { createUser(userInput: $userInput) { id gender profileImage } } "; var document = _builder.Build(query); var result = _printer.Visit(document); result.ShouldNotBeNull(); result.ToString().ShouldBe(MonetizeLineBreaks(query)); } [Fact] public void prints_inline_fragments() { var query = @"query users { users { id union { ... on UserType { username } ... on CustomerType { customername } } } } "; var document = _builder.Build(query); var result = _printer.Visit(document); result.ShouldNotBeNull(); result.ToString().ShouldBe(MonetizeLineBreaks(query)); } [Fact] public void prints_int_value() { int value = 3; var val = new IntValue(value); var result = _printer.Visit(val); result.ShouldBe("3"); } [Fact] public void prints_long_value() { long value = 3; var val = new LongValue(value); var result = _printer.Visit(val); result.ShouldBe("3"); } [Fact] public void prints_float_value_using_cultures() { CultureTestHelper.UseCultures(prints_float_value); } [Fact] public void prints_float_value() { double value = 3.33; var val = new FloatValue(value); var result = _printer.Visit(val); result.ShouldBe(value.ToString("0.0##", NumberFormatInfo.InvariantInfo)); } private static string MonetizeLineBreaks(string input) { return (input ?? string.Empty) .Replace("\r\n", "\n") .Replace("\r", "\n"); } [Fact] public void anynode_throws() { Should.Throw<InvalidOperationException>(() => AstPrinter.Print(new AnyValue(""))); } [Fact] public void string_encodes_control_characters() { var sample = new string(Enumerable.Range(0, 256).Select(x => (char)x).ToArray()); var ret = AstPrinter.Print(new StringValue(sample)); foreach (char c in ret) c.ShouldBeGreaterThanOrEqualTo(' '); var deserialized = System.Text.Json.JsonSerializer.Deserialize<string>(ret); deserialized.ShouldBe(sample); var token = GraphQLParser.Lexer.Lex(ret); token.Kind.ShouldBe(GraphQLParser.TokenKind.STRING); token.Value.ShouldBe(sample); } [Theory] [MemberData(nameof(NodeTests))] public void prints_node(INode node, string expected) { var printed = AstPrinter.Print(node); printed.ShouldBe(expected); if (node is StringValue str) { var token = GraphQLParser.Lexer.Lex(printed); token.Kind.ShouldBe(GraphQLParser.TokenKind.STRING); token.Value.ShouldBe(str.Value); } } [Theory] [MemberData(nameof(NodeTests))] public void prints_node_cultures(INode node, string expected) { CultureTestHelper.UseCultures(() => prints_node(node, expected)); } public static object[][] NodeTests = new object[][] { new object[] { new StringValue("test"), @"""test""" }, new object[] { new StringValue("ab/cd"), @"""ab/cd""" }, new object[] { new StringValue("ab\bcd"), @"""ab\bcd""" }, new object[] { new StringValue("ab\fcd"), @"""ab\fcd""" }, new object[] { new StringValue("ab\rcd"), @"""ab\rcd""" }, new object[] { new StringValue("ab\ncd"), @"""ab\ncd""" }, new object[] { new StringValue("ab\tcd"), @"""ab\tcd""" }, new object[] { new StringValue("ab\\cd"), @"""ab\\cd""" }, new object[] { new StringValue("ab\"cd"), @"""ab\""cd""" }, new object[] { new StringValue("ab\u0019cd"), @"""ab\u0019cd""" }, new object[] { new StringValue("\"abcd\""), @"""\""abcd\""""" }, new object[] { new IntValue(int.MinValue), "-2147483648" }, new object[] { new IntValue(0), "0" }, new object[] { new IntValue(int.MaxValue), "2147483647" }, new object[] { new LongValue(long.MinValue), "-9223372036854775808" }, new object[] { new LongValue(0), "0" }, new object[] { new LongValue(long.MaxValue), "9223372036854775807" }, new object[] { new BigIntValue(new System.Numerics.BigInteger(decimal.MaxValue) * 1000 + 2), "79228162514264337593543950335002" }, new object[] { new FloatValue(double.MinValue), "-1.79769313486232E+308" }, new object[] { new FloatValue(double.Epsilon), "4.94065645841247E-324" }, new object[] { new FloatValue(double.MaxValue), "1.79769313486232E+308" }, new object[] { new FloatValue(0.00000001256), "1.256E-08" }, new object[] { new FloatValue(12.56), "12.56" }, new object[] { new FloatValue(3.33), "3.33" }, new object[] { new FloatValue(1.0), "1" }, new object[] { new FloatValue(34), "34" }, new object[] { new DecimalValue(1.0000m), "1"}, new object[] { new DecimalValue(decimal.MinValue), "-79228162514264337593543950335"}, new object[] { new DecimalValue(decimal.MaxValue), "79228162514264337593543950335"}, new object[] { new DecimalValue(0.00000000000000001m), "1E-17"}, new object[] { new BooleanValue(false), "false"}, new object[] { new BooleanValue(true), "true"}, new object[] { new EnumValue("TEST"), "TEST"}, }; } }
// 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 ShiftRightLogicalUInt3232() { var test = new ImmUnaryOpTest__ShiftRightLogicalUInt3232(); 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 ImmUnaryOpTest__ShiftRightLogicalUInt3232 { private struct TestStruct { public Vector256<UInt32> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogicalUInt3232 testClass) { var result = Avx2.ShiftRightLogical(_fld, 32); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32); private static UInt32[] _data = new UInt32[Op1ElementCount]; private static Vector256<UInt32> _clsVar; private Vector256<UInt32> _fld; private SimpleUnaryOpTest__DataTable<UInt32, UInt32> _dataTable; static ImmUnaryOpTest__ShiftRightLogicalUInt3232() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); } public ImmUnaryOpTest__ShiftRightLogicalUInt3232() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new SimpleUnaryOpTest__DataTable<UInt32, UInt32>(_data, 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.ShiftRightLogical( Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr), 32 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.ShiftRightLogical( Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr)), 32 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.ShiftRightLogical( Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr)), 32 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr), (byte)32 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr)), (byte)32 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr)), (byte)32 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.ShiftRightLogical( _clsVar, 32 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr); var result = Avx2.ShiftRightLogical(firstOp, 32); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftRightLogical(firstOp, 32); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftRightLogical(firstOp, 32); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftRightLogicalUInt3232(); var result = Avx2.ShiftRightLogical(test._fld, 32); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.ShiftRightLogical(_fld, 32); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.ShiftRightLogical(test._fld, 32); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _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> firstOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray = new UInt32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray = new UInt32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (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(inArray, outArray, method); } private void ValidateResult(UInt32[] firstOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (0 != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (0!= result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightLogical)}<UInt32>(Vector256<UInt32><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Projection // Description: The basic module for MapWindow version 6.0 // ******************************************************************************************************** // // The original content was ported from the C language from the 4.6 version of Proj4 libraries. // Frank Warmerdam has released the full content of that version under the MIT license which is // recognized as being approximately equivalent to public domain. The original work was done // mostly by Gerald Evenden. The latest versions of the C libraries can be obtained here: // http://trac.osgeo.org/proj/ // // The Initial Developer of this Original Code is Ted Dunsford. Created 8/10/2009 9:25:51 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // Name | Date | Comment // --------------------|------------|------------------------------------------------------------ // Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL // Christoph Perger | 22/6/2016 | Fixed some issues with projection from LAEA to WGS84 // ******************************************************************************************************** using System; namespace DotSpatial.Projections.Transforms { /// <summary> /// LambertAzimuthalEqualArea /// </summary> public class LambertAzimuthalEqualArea : EllipticalTransform { #region Private Variables private double[] _apa; private double _cosb1; private double _dd; private Modes _mode; private double _qp; private double _rq; private double _sinb1; private double _xmf; private double _ymf; #endregion #region Constructors /// <summary> /// Creates a new instance of LambertAzimuthalEqualArea /// </summary> public LambertAzimuthalEqualArea() { Name = "Lambert_Azimuthal_Equal_Area"; Proj4Name = "laea"; } #endregion #region Methods /// <inheritdoc /> protected override void EllipticalForward(double[] lp, double[] xy, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double sinb = 0, cosb = 0, b = 0; double coslam = Math.Cos(lp[lam]); double sinlam = Math.Sin(lp[lam]); double sinphi = Math.Sin(lp[phi]); double q = Proj.Qsfn(sinphi, E, OneEs); if (_mode == Modes.Oblique || _mode == Modes.Equitorial) { sinb = q / _qp; cosb = Math.Sqrt(1 - sinb * sinb); } switch (_mode) { case Modes.Oblique: b = 1 + _sinb1 * sinb + _cosb1 * cosb * coslam; break; case Modes.Equitorial: b = 1 + cosb * coslam; break; case Modes.NorthPole: b = HALF_PI + lp[phi]; q = _qp - q; break; case Modes.SouthPole: b = lp[phi] - HALF_PI; q = _qp + q; break; } if (Math.Abs(b) < EPS10) { xy[x] = double.NaN; xy[y] = double.NaN; continue; //throw new ProjectionException(20); } switch (_mode) { case Modes.Oblique: xy[y] = _ymf * (b = Math.Sqrt(2 / b)) * (_cosb1 * sinb - _sinb1 * cosb * coslam); xy[x] = _xmf * b * cosb * sinlam; break; case Modes.Equitorial: xy[y] = (b = Math.Sqrt(2 / (1 + cosb * coslam))) * sinb * _ymf; xy[x] = _xmf * b * cosb * sinlam; break; case Modes.NorthPole: case Modes.SouthPole: if (q >= 0) { xy[x] = (b = Math.Sqrt(q)) * sinlam; xy[y] = coslam * (_mode == Modes.SouthPole ? b : -b); } else { xy[x] = xy[y] = 0; } break; } } } /// <inheritdoc /> protected override void SphericalForward(double[] lp, double[] xy, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double sinphi = Math.Sin(lp[phi]); double cosphi = Math.Cos(lp[phi]); double coslam = Math.Cos(lp[lam]); if (_mode == Modes.Equitorial || _mode == Modes.Oblique) { if (_mode == Modes.Equitorial) xy[x] = 1 + cosphi * coslam; if (_mode == Modes.Oblique) xy[y] = 1 + _sinb1 * sinphi + _cosb1 * cosphi * coslam; if (xy[y] <= EPS10) { xy[x] = double.NaN; xy[y] = double.NaN; continue; //throw new ProjectionException(20); } xy[x] = (xy[y] = Math.Sqrt(2 / xy[y])) * cosphi * Math.Sin(lp[lam]); xy[y] *= _mode == Modes.Equitorial ? sinphi : _cosb1 * sinphi - _sinb1 * cosphi * coslam; } else { if (_mode == Modes.NorthPole) coslam = -coslam; if (Math.Abs(lp[phi] + Phi0) < EPS10) { xy[x] = double.NaN; xy[y] = double.NaN; continue; //throw new ProjectionException(20); } xy[y] = FORT_PI - lp[phi] * .5; xy[y] = 2 * (_mode == Modes.SouthPole ? Math.Cos(xy[y]) : Math.Sin(xy[y])); xy[x] = xy[y] * Math.Sin(lp[lam]); xy[y] *= coslam; } } } /// <inheritdoc /> protected override void EllipticalInverse(double[] xy, double[] lp, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double ab; double cx = xy[x]; double cy = xy[y]; if (_mode == Modes.Equitorial || _mode == Modes.Oblique) { double rho = Proj.Hypot(cx /= _dd, cy *= _dd); if (rho < EPS10) { lp[lam] = 0; lp[phi] = Phi0; return; } double sCe; double cCe = Math.Cos(sCe = 2 * Math.Asin(.5 * rho / _rq)); cx *= (sCe = Math.Sin(sCe)); if (_mode == Modes.Oblique) { ab = cCe * _sinb1 + cy * sCe * _cosb1 / rho; //q = _qp*(ab); cy = rho * _cosb1 * cCe - cy * _sinb1 * sCe; } else { ab = cy * sCe / rho; //q = _qp*(ab); cy = rho * cCe; } } else { if (_mode == Modes.NorthPole) cy = -cy; double q; if ((q = (cx * cx + cy * cy)) == 0) { lp[lam] = 0; lp[phi] = Phi0; return; } ab = 1 - q / _qp; if (_mode == Modes.SouthPole) ab = -ab; } lp[lam] = Math.Atan2(cx, cy); lp[phi] = Proj.AuthLat(Math.Asin(ab), _apa); } } /// <inheritdoc /> protected override void SphericalInverse(double[] xy, double[] lp, int startIndex, int numPoints) { for (int i = startIndex; i < startIndex + numPoints; i++) { int phi = i * 2 + PHI; int lam = i * 2 + LAMBDA; int x = i * 2 + X; int y = i * 2 + Y; double cosz = 0, sinz = 0; double cx = xy[x]; double cy = xy[y]; double rh = Proj.Hypot(cx, cy); if ((lp[phi] = rh * .5) > 1) { lp[lam] = double.NaN; lp[phi] = double.NaN; continue; //throw new ProjectionException(20); } lp[phi] = 2 * Math.Asin(lp[phi]); if (_mode == Modes.Oblique || _mode == Modes.Equitorial) { sinz = Math.Sin(lp[phi]); cosz = Math.Cos(lp[phi]); } switch (_mode) { case Modes.Equitorial: lp[phi] = Math.Abs(rh) <= EPS10 ? 0 : Math.Asin(cy * sinz / rh); cx *= sinz; cy = cosz * rh; break; case Modes.Oblique: lp[phi] = Math.Abs(rh) <= EPS10 ? Phi0 : Math.Asin(cosz * _sinb1 + cy * sinz * _sinb1 / rh); cx *= sinz * _cosb1; cy = (cosz - Math.Sin(lp[phi]) * _sinb1) * rh; break; case Modes.NorthPole: cy = -cy; lp[phi] = HALF_PI - lp[phi]; break; case Modes.SouthPole: lp[phi] -= HALF_PI; break; } lp[lam] = (cy == 0 && (_mode == Modes.Equitorial || _mode == Modes.Oblique)) ? 0 : Math.Atan2(cx, cy); } } /// <summary> /// Initializes the transform using the parameters from the specified coordinate system information /// </summary> /// <param name="projInfo">A ProjectionInfo class contains all the standard and custom parameters needed to initialize this transform</param> protected override void OnInit(ProjectionInfo projInfo) { double t = Math.Abs(Phi0); if (Math.Abs(t - HALF_PI) < EPS10) { _mode = Phi0 < 0 ? Modes.SouthPole : Modes.NorthPole; } else if (Math.Abs(t) < EPS10) { _mode = Modes.Equitorial; } else { _mode = Modes.Oblique; } if (Es == 0) { IsElliptical = false; _mode = Modes.Oblique; _sinb1 = Math.Sin(Phi0); _cosb1 = Math.Cos(Phi0); return; } IsElliptical = true; _qp = Proj.Qsfn(1, E, OneEs); _apa = Proj.Authset(Es); switch (_mode) { case Modes.NorthPole: case Modes.SouthPole: _dd = 1; break; case Modes.Equitorial: _dd = 1 / (_rq = Math.Sqrt(.5 * _qp)); _xmf = 1; _ymf = .5 * _qp; break; case Modes.Oblique: _rq = Math.Sqrt(.5 * _qp); double sinphi = Math.Sin(Phi0); _sinb1 = Proj.Qsfn(sinphi, E, OneEs)/_qp; _cosb1 = Math.Sqrt(1 - _sinb1 * _sinb1); _dd = Math.Cos(Phi0) / (Math.Sqrt(1 - Es * sinphi * sinphi) * _rq * _cosb1); _ymf = (_xmf = _rq) / _dd; _xmf *= _dd; break; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // // This is a C# implementation of the Richards benchmark from: // // http://www.cl.cam.ac.uk/~mr10/Bench.html // // The benchmark was originally implemented in BCPL by Martin Richards. #define INTF_FOR_TASK using Microsoft.Xunit.Performance; using System; using System.Collections.Generic; [assembly: OptimizeForBenchmarks] // using System.Diagnostics; // using System.Text.RegularExpressions; namespace V8.Richards { /// <summary> /// Support is used for a place to generate any 'miscellaneous' methods generated as part /// of code generation, (which do not have user-visible names) /// </summary> public class Support { public static bool runRichards() { Scheduler scheduler = new Scheduler(); scheduler.addIdleTask(ID_IDLE, 0, null, COUNT); Packet queue = new Packet(null, ID_WORKER, KIND_WORK); queue = new Packet(queue, ID_WORKER, KIND_WORK); scheduler.addWorkerTask(ID_WORKER, 1000, queue); queue = new Packet(null, ID_DEVICE_A, KIND_DEVICE); queue = new Packet(queue, ID_DEVICE_A, KIND_DEVICE); queue = new Packet(queue, ID_DEVICE_A, KIND_DEVICE); scheduler.addHandlerTask(ID_HANDLER_A, 2000, queue); queue = new Packet(null, ID_DEVICE_B, KIND_DEVICE); queue = new Packet(queue, ID_DEVICE_B, KIND_DEVICE); queue = new Packet(queue, ID_DEVICE_B, KIND_DEVICE); scheduler.addHandlerTask(ID_HANDLER_B, 3000, queue); scheduler.addDeviceTask(ID_DEVICE_A, 4000, null); scheduler.addDeviceTask(ID_DEVICE_B, 5000, null); scheduler.schedule(); return ((scheduler.queueCount == EXPECTED_QUEUE_COUNT) && (scheduler.holdCount == EXPECTED_HOLD_COUNT)); } public const int COUNT = 1000; /** * These two constants specify how many times a packet is queued and * how many times a task is put on hold in a correct run of richards. * They don't have any meaning a such but are characteristic of a * correct run so if the actual queue or hold count is different from * the expected there must be a bug in the implementation. **/ public const int EXPECTED_QUEUE_COUNT = 2322; public const int EXPECTED_HOLD_COUNT = 928; public const int ID_IDLE = 0; public const int ID_WORKER = 1; public const int ID_HANDLER_A = 2; public const int ID_HANDLER_B = 3; public const int ID_DEVICE_A = 4; public const int ID_DEVICE_B = 5; public const int NUMBER_OF_IDS = 6; public const int KIND_DEVICE = 0; public const int KIND_WORK = 1; /** * The task is running and is currently scheduled. */ public const int STATE_RUNNING = 0; /** * The task has packets left to process. */ public const int STATE_RUNNABLE = 1; /** * The task is not currently running. The task is not blocked as such and may * be started by the scheduler. */ public const int STATE_SUSPENDED = 2; /** * The task is blocked and cannot be run until it is explicitly released. */ public const int STATE_HELD = 4; public const int STATE_SUSPENDED_RUNNABLE = STATE_SUSPENDED | STATE_RUNNABLE; public const int STATE_NOT_HELD = ~STATE_HELD; /* --- * * P a c k e t * --- */ public const int DATA_SIZE = 4; public static int Main(String[] args) { int n = 1; if (args.Length > 0) { n = Int32.Parse(args[0]); } bool result = Measure(n); return (result ? 100 : -1); } public static bool Measure(int n) { DateTime start = DateTime.Now; bool result = true; for (int i = 0; i < n; i++) { result &= runRichards(); } DateTime end = DateTime.Now; TimeSpan dur = end - start; Console.WriteLine("Doing {0} iters of Richards takes {1} ms; {2} us/iter.", n, dur.TotalMilliseconds, (1000.0 * dur.TotalMilliseconds) / n); return result; } [Benchmark] public static void Bench() { const int Iterations = 5000; foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Iterations; i++) { runRichards(); } } } } } internal class Scheduler { public int queueCount; public int holdCount; public TaskControlBlock[] blocks; public TaskControlBlock list; public TaskControlBlock currentTcb; public int currentId; public Scheduler() { this.queueCount = 0; this.holdCount = 0; this.blocks = new TaskControlBlock[Support.NUMBER_OF_IDS]; this.list = null; this.currentTcb = null; this.currentId = 0; } /** * Add an idle task to this scheduler. * @param {int} id the identity of the task * @param {int} priority the task's priority * @param {Packet} queue the queue of work to be processed by the task * @param {int} count the number of times to schedule the task */ public void addIdleTask(int id, int priority, Packet queue, int count) { this.addRunningTask(id, priority, queue, new IdleTask(this, 1, count)); } /** * Add a work task to this scheduler. * @param {int} id the identity of the task * @param {int} priority the task's priority * @param {Packet} queue the queue of work to be processed by the task */ public void addWorkerTask(int id, int priority, Packet queue) { this.addTask(id, priority, queue, new WorkerTask(this, Support.ID_HANDLER_A, 0)); } /** * Add a handler task to this scheduler. * @param {int} id the identity of the task * @param {int} priority the task's priority * @param {Packet} queue the queue of work to be processed by the task */ public void addHandlerTask(int id, int priority, Packet queue) { this.addTask(id, priority, queue, new HandlerTask(this)); } /** * Add a handler task to this scheduler. * @param {int} id the identity of the task * @param {int} priority the task's priority * @param {Packet} queue the queue of work to be processed by the task */ public void addDeviceTask(int id, int priority, Packet queue) { this.addTask(id, priority, queue, new DeviceTask(this)); } /** * Add the specified task and mark it as running. * @param {int} id the identity of the task * @param {int} priority the task's priority * @param {Packet} queue the queue of work to be processed by the task * @param {Task} task the task to add */ public void addRunningTask(int id, int priority, Packet queue, Task task) { this.addTask(id, priority, queue, task); this.currentTcb.setRunning(); } /** * Add the specified task to this scheduler. * @param {int} id the identity of the task * @param {int} priority the task's priority * @param {Packet} queue the queue of work to be processed by the task * @param {Task} task the task to add */ public void addTask(int id, int priority, Packet queue, Task task) { this.currentTcb = new TaskControlBlock(this.list, id, priority, queue, task); this.list = this.currentTcb; this.blocks[id] = this.currentTcb; } /** * Execute the tasks managed by this scheduler. */ public void schedule() { this.currentTcb = this.list; #if TRACEIT int kkk = 0; #endif while (this.currentTcb != null) { #if TRACEIT Console.WriteLine("kkk = {0}", kkk); kkk++; #endif if (this.currentTcb.isHeldOrSuspended()) { #if TRACEIT Console.WriteLine("held"); #endif this.currentTcb = this.currentTcb.link; } else { this.currentId = this.currentTcb.id; #if TRACEIT Console.WriteLine("currentId is now...{0}", this.currentId.ToString()); #endif this.currentTcb = this.currentTcb.run(); } } } /** * Release a task that is currently blocked and return the next block to run. * @param {int} id the id of the task to suspend */ public TaskControlBlock release(int id) { TaskControlBlock tcb = this.blocks[id]; if (tcb == null) return tcb; tcb.markAsNotHeld(); if (tcb.priority >= this.currentTcb.priority) { return tcb; } else { return this.currentTcb; } } /** * Block the currently executing task and return the next task control block * to run. The blocked task will not be made runnable until it is explicitly * released, even if new work is added to it. */ public TaskControlBlock holdCurrent() { this.holdCount++; this.currentTcb.markAsHeld(); return this.currentTcb.link; } /** * Suspend the currently executing task and return the next task control block * to run. If new work is added to the suspended task it will be made runnable. */ public TaskControlBlock suspendCurrent() { this.currentTcb.markAsSuspended(); return this.currentTcb; } /** * Add the specified packet to the end of the worklist used by the task * associated with the packet and make the task runnable if it is currently * suspended. * @param {Packet} packet the packet to add */ public TaskControlBlock queue(Packet packet) { TaskControlBlock t = this.blocks[packet.id]; if (t == null) return t; this.queueCount++; packet.link = null; packet.id = this.currentId; return t.checkPriorityAdd(this.currentTcb, packet); } } /** * A task control block manages a task and the queue of work packages associated * with it. * @param {TaskControlBlock} link the preceding block in the linked block list * @param {int} id the id of this block * @param {int} priority the priority of this block * @param {Packet} queue the queue of packages to be processed by the task * @param {Task} task the task * @constructor */ public class TaskControlBlock { public TaskControlBlock link; public int id; public int priority; public Packet queue; public Task task; public int state; public TaskControlBlock(TaskControlBlock link, int id, int priority, Packet queue, Task task) { this.link = link; this.id = id; this.priority = priority; this.queue = queue; this.task = task; if (queue == null) { this.state = Support.STATE_SUSPENDED; } else { this.state = Support.STATE_SUSPENDED_RUNNABLE; } } public void setRunning() { this.state = Support.STATE_RUNNING; } public void markAsNotHeld() { this.state = this.state & Support.STATE_NOT_HELD; } public void markAsHeld() { this.state = this.state | Support.STATE_HELD; } public bool isHeldOrSuspended() { return ((this.state & Support.STATE_HELD) != 0) || (this.state == Support.STATE_SUSPENDED); } public void markAsSuspended() { this.state = this.state | Support.STATE_SUSPENDED; } public void markAsRunnable() { this.state = this.state | Support.STATE_RUNNABLE; } /** * Runs this task, if it is ready to be run, and returns the next task to run. */ public TaskControlBlock run() { Packet packet; #if TRACEIT Console.WriteLine(" TCB::run, state = {0}", this.state); #endif if (this.state == Support.STATE_SUSPENDED_RUNNABLE) { packet = this.queue; this.queue = packet.link; if (this.queue == null) { this.state = Support.STATE_RUNNING; } else { this.state = Support.STATE_RUNNABLE; } #if TRACEIT Console.WriteLine(" State is now {0}", this.state); #endif } else { #if TRACEIT Console.WriteLine(" TCB::run, setting packet = Null."); #endif packet = null; } return this.task.run(packet); } /** * Adds a packet to the worklist of this block's task, marks this as runnable if * necessary, and returns the next runnable object to run (the one * with the highest priority). */ public TaskControlBlock checkPriorityAdd(TaskControlBlock task, Packet packet) { if (this.queue == null) { this.queue = packet; this.markAsRunnable(); if (this.priority >= task.priority) return this; } else { this.queue = packet.addTo(this.queue); } return task; } public String toString() { return "tcb { " + this.task.toString() + "@" + this.state.ToString() + " }"; } } #if INTF_FOR_TASK // I deliberately ignore the "I" prefix convention here so that we can use Task as a type in both // cases... public interface Task { TaskControlBlock run(Packet packet); String toString(); } #else public abstract class Task { public abstract TaskControlBlock run(Packet packet); public abstract String toString(); } #endif /** * An idle task doesn't do any work itself but cycles control between the two * device tasks. * @param {Scheduler} scheduler the scheduler that manages this task * @param {int} v1 a seed value that controls how the device tasks are scheduled * @param {int} count the number of times this task should be scheduled * @constructor */ internal class IdleTask : Task { public Scheduler scheduler; public int _v1; public int _count; public IdleTask(Scheduler scheduler, int v1, int count) { this.scheduler = scheduler; this._v1 = v1; this._count = count; } public #if !INTF_FOR_TASK override #endif TaskControlBlock run(Packet packet) { this._count--; if (this._count == 0) return this.scheduler.holdCurrent(); if ((this._v1 & 1) == 0) { this._v1 = this._v1 >> 1; return this.scheduler.release(Support.ID_DEVICE_A); } else { this._v1 = (this._v1 >> 1) ^ 0xD008; return this.scheduler.release(Support.ID_DEVICE_B); } } public #if !INTF_FOR_TASK override #endif String toString() { return "IdleTask"; } } /** * A task that suspends itself after each time it has been run to simulate * waiting for data from an external device. * @param {Scheduler} scheduler the scheduler that manages this task * @constructor */ internal class DeviceTask : Task { public Scheduler scheduler; private Packet _v1; public DeviceTask(Scheduler scheduler) { this.scheduler = scheduler; _v1 = null; } public #if !INTF_FOR_TASK override #endif TaskControlBlock run(Packet packet) { if (packet == null) { if (_v1 == null) return this.scheduler.suspendCurrent(); Packet v = _v1; _v1 = null; return this.scheduler.queue(v); } else { _v1 = packet; return this.scheduler.holdCurrent(); } } public #if !INTF_FOR_TASK override #endif String toString() { return "DeviceTask"; } } /** * A task that manipulates work packets. * @param {Scheduler} scheduler the scheduler that manages this task * @param {int} v1 a seed used to specify how work packets are manipulated * @param {int} v2 another seed used to specify how work packets are manipulated * @constructor */ internal class WorkerTask : Task { public Scheduler scheduler; public int v1; public int _v2; public WorkerTask(Scheduler scheduler, int v1, int v2) { this.scheduler = scheduler; this.v1 = v1; this._v2 = v2; } public #if !INTF_FOR_TASK override #endif TaskControlBlock run(Packet packet) { if (packet == null) { return this.scheduler.suspendCurrent(); } else { if (this.v1 == Support.ID_HANDLER_A) { this.v1 = Support.ID_HANDLER_B; } else { this.v1 = Support.ID_HANDLER_A; } packet.id = this.v1; packet.a1 = 0; for (int i = 0; i < Support.DATA_SIZE; i++) { this._v2++; if (this._v2 > 26) this._v2 = 1; packet.a2[i] = this._v2; } return this.scheduler.queue(packet); } } public #if !INTF_FOR_TASK override #endif String toString() { return "WorkerTask"; } } /** * A task that manipulates work packets and then suspends itself. * @param {Scheduler} scheduler the scheduler that manages this task * @constructor */ internal class HandlerTask : Task { public Scheduler scheduler; public Packet v1; public Packet v2; public HandlerTask(Scheduler scheduler) { this.scheduler = scheduler; this.v1 = null; this.v2 = null; } public #if !INTF_FOR_TASK override #endif TaskControlBlock run(Packet packet) { if (packet != null) { if (packet.kind == Support.KIND_WORK) { this.v1 = packet.addTo(this.v1); } else { this.v2 = packet.addTo(this.v2); } } if (this.v1 != null) { int count = this.v1.a1; Packet v; if (count < Support.DATA_SIZE) { if (this.v2 != null) { v = this.v2; this.v2 = this.v2.link; v.a1 = this.v1.a2[count]; this.v1.a1 = count + 1; return this.scheduler.queue(v); } } else { v = this.v1; this.v1 = this.v1.link; return this.scheduler.queue(v); } } return this.scheduler.suspendCurrent(); } public #if !INTF_FOR_TASK override #endif String toString() { return "HandlerTask"; } } /** * A simple package of data that is manipulated by the tasks. The exact layout * of the payload data carried by a packet is not importaint, and neither is the * nature of the work performed on packets by the tasks. * * Besides carrying data, packets form linked lists and are hence used both as * data and worklists. * @param {Packet} link the tail of the linked list of packets * @param {int} id an ID for this packet * @param {int} kind the type of this packet * @constructor */ public class Packet { public Packet link; public int id; public int kind; public int a1; public int[] a2; public Packet(Packet link, int id, int kind) { this.link = link; this.id = id; this.kind = kind; this.a1 = 0; this.a2 = new int[Support.DATA_SIZE]; } public Packet addTo(Packet queue) { this.link = null; if (queue == null) return this; Packet peek; Packet next = queue; while ((peek = next.link) != null) next = peek; next.link = this; return queue; } public String toString() { return "Packet"; } } }
// 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. //---------------------------------------------------------------------------------------- // // Description: // An internal class which handles compiler information cache. It can read // write the cache file, this is for incremental build support. // //--------------------------------------------------------------------------------------- using System; using System.IO; using System.Collections; using System.Diagnostics; using System.Text; using System.Globalization; using Microsoft.Build.Tasks.Windows; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using MS.Utility; namespace MS.Internal.Tasks { // // Only cache information for below types. // internal enum CompilerStateType : int { AssemblyName = 0x00, AssemblyVersion, AssemblyPublicKeyToken, OutputType, Language, LanguageSourceExtension, OutputPath, RootNamespace, LocalizationDirectivesToLocFile, HostInBrowser, DefineConstants, ApplicationFile, PageMarkup, ContentFiles, SourceCodeFiles, References, PageMarkupFileNames, SplashImage, Pass2Required, MaxCount, } // <summary> // CompilerState // </summary> internal class CompilerState { // <summary> // ctor of CompilerState // </summary> internal CompilerState(string stateFilePath, ITaskFileService taskFileService) { _cacheInfoList = new String[(int)CompilerStateType.MaxCount]; _stateFilePath = stateFilePath; _taskFileService = taskFileService; } #region internal methods // <summary> // Detect whether the state file exists or not. // </summary> // <returns></returns> internal bool StateFileExists() { return _taskFileService.Exists(_stateFilePath); } // // Clean up the state file. // internal void CleanupCache() { if (StateFileExists() ) { _taskFileService.Delete(_stateFilePath); } } internal bool SaveStateInformation(MarkupCompilePass1 mcPass1) { Debug.Assert(String.IsNullOrEmpty(_stateFilePath) != true, "StateFilePath must not be empty."); Debug.Assert(mcPass1 != null, "A valid instance of MarkupCompilePass1 must be passed to method SaveCacheInformation."); Debug.Assert(_cacheInfoList.Length == (int)CompilerStateType.MaxCount, "The Cache string array should be already allocated."); // Transfer the cache related information from mcPass1 to this instance. AssemblyName = mcPass1.AssemblyName; AssemblyVersion = mcPass1.AssemblyVersion; AssemblyPublicKeyToken = mcPass1.AssemblyPublicKeyToken; OutputType = mcPass1.OutputType; Language = mcPass1.Language; LanguageSourceExtension = mcPass1.LanguageSourceExtension; OutputPath = mcPass1.OutputPath; RootNamespace = mcPass1.RootNamespace; LocalizationDirectivesToLocFile = mcPass1.LocalizationDirectivesToLocFile; HostInBrowser = mcPass1.HostInBrowser; DefineConstants = mcPass1.DefineConstants; ApplicationFile = mcPass1.ApplicationFile; PageMarkup = mcPass1.PageMarkupCache; ContentFiles = mcPass1.ContentFilesCache; SourceCodeFiles = mcPass1.SourceCodeFilesCache; References = mcPass1.ReferencesCache; PageMarkupFileNames = GenerateStringFromFileNames(mcPass1.PageMarkup); SplashImage = mcPass1.SplashImageName; Pass2Required = (mcPass1.RequirePass2ForMainAssembly || mcPass1.RequirePass2ForSatelliteAssembly); return SaveStateInformation(); } internal bool SaveStateInformation() { bool bSuccess = false; // Save the cache information to the cache file. MemoryStream memStream = new MemoryStream(); // using Disposes the StreamWriter when it ends. Disposing the StreamWriter // also closes the underlying MemoryStream. Furthermore, don't add BOM here // since TaskFileService.WriteFile adds it. using (StreamWriter sw = new StreamWriter(memStream, new UTF8Encoding(false))) { for (int i =0; i<(int)CompilerStateType.MaxCount; i++) { sw.WriteLine(_cacheInfoList[i]); } sw.Flush(); _taskFileService.WriteFile(memStream.ToArray(), _stateFilePath); bSuccess = true; } return bSuccess; } // // Read the markupcompiler cache file, load the cached information // to the corresponding data fields in this class. // internal bool LoadStateInformation( ) { Debug.Assert(String.IsNullOrEmpty(_stateFilePath) != true, "_stateFilePath must be not be empty."); Debug.Assert(_cacheInfoList.Length == (int)CompilerStateType.MaxCount, "The Cache string array should be already allocated."); bool loadSuccess = false; Stream stream = null; if (_taskFileService.IsRealBuild) { // Pass2 writes to the cache, but Pass2 doesn't have a HostObject (because it's only // used for real builds), so it writes directly to the file system. So we need to read // directly from the file system; if we read via the HostFileManager, we'll get stale // results that don't reflect updates made in Pass2. stream = File.OpenRead(_stateFilePath); } else { stream = _taskFileService.GetContent(_stateFilePath); } // using Disposes the StreamReader when it ends. Disposing the StreamReader // also closes the underlying MemoryStream. Don't look for BOM at the beginning // of the stream, since we don't add it when writing. TaskFileService takes care // of this. using (StreamReader srCache = new StreamReader(stream, false)) { int i = 0; while (srCache.EndOfStream != true) { if (i >= (int)CompilerStateType.MaxCount) { break; } _cacheInfoList[i] = srCache.ReadLine(); i++; } loadSuccess = true; } return loadSuccess; } // // Generate cache string for item lists such as PageMarkup, References, // ContentFiles and CodeFiles etc. // internal static string GenerateCacheForFileList(ITaskItem[] fileItemList) { string cacheString = String.Empty; if (fileItemList != null && fileItemList.Length > 0) { int iHashCode = 0; int iCount = fileItemList.Length; for (int i = 0; i < iCount; i++) { iHashCode += fileItemList[i].ItemSpec.GetHashCode(); } StringBuilder sb = new StringBuilder(); sb.Append(iCount); sb.Append(iHashCode); cacheString = sb.ToString(); } return cacheString; } private static string GenerateStringFromFileNames(ITaskItem[] fileItemList) { string fileNames = String.Empty; if (fileItemList != null) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < fileItemList.Length; i++) { sb.Append(fileItemList[i].ItemSpec); sb.Append(";"); } fileNames = sb.ToString(); } return fileNames; } #endregion #region internal properties internal string CacheFilePath { get { return _stateFilePath; } } internal string AssemblyName { get { return _cacheInfoList[(int)CompilerStateType.AssemblyName]; } set { _cacheInfoList[(int)CompilerStateType.AssemblyName] = value; } } internal string AssemblyVersion { get { return _cacheInfoList[(int)CompilerStateType.AssemblyVersion]; } set { _cacheInfoList[(int)CompilerStateType.AssemblyVersion] = value; } } internal string AssemblyPublicKeyToken { get { return _cacheInfoList[(int)CompilerStateType.AssemblyPublicKeyToken]; } set { _cacheInfoList[(int)CompilerStateType.AssemblyPublicKeyToken] = value; } } internal string OutputType { get { return _cacheInfoList[(int)CompilerStateType.OutputType]; } set { _cacheInfoList[(int)CompilerStateType.OutputType] = value; } } internal string Language { get { return _cacheInfoList[(int)CompilerStateType.Language]; } set { _cacheInfoList[(int)CompilerStateType.Language] = value; } } internal string LanguageSourceExtension { get { return _cacheInfoList[(int)CompilerStateType.LanguageSourceExtension]; } set { _cacheInfoList[(int)CompilerStateType.LanguageSourceExtension] = value; } } internal string OutputPath { get { return _cacheInfoList[(int)CompilerStateType.OutputPath]; } set { _cacheInfoList[(int)CompilerStateType.OutputPath] = value; } } internal string RootNamespace { get { return _cacheInfoList[(int)CompilerStateType.RootNamespace]; } set { _cacheInfoList[(int)CompilerStateType.RootNamespace] = value; } } internal string LocalizationDirectivesToLocFile { get { return _cacheInfoList[(int)CompilerStateType.LocalizationDirectivesToLocFile]; } set { _cacheInfoList[(int)CompilerStateType.LocalizationDirectivesToLocFile] = value; } } internal string HostInBrowser { get { return _cacheInfoList[(int)CompilerStateType.HostInBrowser]; } set { _cacheInfoList[(int)CompilerStateType.HostInBrowser] = value; } } internal string DefineConstants { get { return _cacheInfoList[(int)CompilerStateType.DefineConstants]; } set { _cacheInfoList[(int)CompilerStateType.DefineConstants] = value; } } internal string ApplicationFile { get { return _cacheInfoList[(int)CompilerStateType.ApplicationFile]; } set { _cacheInfoList[(int)CompilerStateType.ApplicationFile] = value; } } internal string PageMarkup { get { return _cacheInfoList[(int)CompilerStateType.PageMarkup]; } set { _cacheInfoList[(int)CompilerStateType.PageMarkup] = value; } } internal string ContentFiles { get { return _cacheInfoList[(int)CompilerStateType.ContentFiles]; } set { _cacheInfoList[(int)CompilerStateType.ContentFiles] = value; } } internal string SourceCodeFiles { get { return _cacheInfoList[(int)CompilerStateType.SourceCodeFiles]; } set { _cacheInfoList[(int)CompilerStateType.SourceCodeFiles] = value; } } internal string References { get { return _cacheInfoList[(int)CompilerStateType.References]; } set { _cacheInfoList[(int)CompilerStateType.References] = value; } } internal string PageMarkupFileNames { get { return _cacheInfoList[(int)CompilerStateType.PageMarkupFileNames]; } set { _cacheInfoList[(int)CompilerStateType.PageMarkupFileNames] = value; } } internal string SplashImage { get { return _cacheInfoList[(int)CompilerStateType.SplashImage]; } set { _cacheInfoList[(int)CompilerStateType.SplashImage] = value; } } internal bool Pass2Required { get { return _cacheInfoList[(int)CompilerStateType.Pass2Required] == bool.TrueString; } set { _cacheInfoList[(int)CompilerStateType.Pass2Required] = value.ToString(CultureInfo.InvariantCulture); } } #endregion #region private data private String [] _cacheInfoList; private string _stateFilePath; private ITaskFileService _taskFileService = null; #endregion } }
#region File Description //----------------------------------------------------------------------------- // InputState.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using System.Collections.Generic; #endregion namespace NetworkStateManagement { /// <summary> /// Helper for reading input from keyboard, gamepad, and touch input. This class /// tracks both the current and previous state of the input devices, and implements /// query methods for high level input actions such as "move up through the menu" /// or "pause the game". /// </summary> public class InputState { #region Fields public const int MaxInputs = 4; public readonly KeyboardState[] CurrentKeyboardStates; public readonly GamePadState[] CurrentGamePadStates; public readonly KeyboardState[] LastKeyboardStates; public readonly GamePadState[] LastGamePadStates; public readonly bool[] GamePadWasConnected; #endregion #region Initialization /// <summary> /// Constructs a new input state. /// </summary> public InputState() { CurrentKeyboardStates = new KeyboardState[MaxInputs]; CurrentGamePadStates = new GamePadState[MaxInputs]; LastKeyboardStates = new KeyboardState[MaxInputs]; LastGamePadStates = new GamePadState[MaxInputs]; GamePadWasConnected = new bool[MaxInputs]; } #endregion #region Public Methods /// <summary> /// Reads the latest state of the keyboard and gamepad. /// </summary> public void Update() { for (int i = 0; i < MaxInputs; i++) { LastKeyboardStates[i] = CurrentKeyboardStates[i]; LastGamePadStates[i] = CurrentGamePadStates[i]; CurrentKeyboardStates[i] = Keyboard.GetState((PlayerIndex)i); CurrentGamePadStates[i] = GamePad.GetState((PlayerIndex)i); // Keep track of whether a gamepad has ever been // connected, so we can detect if it is unplugged. if (CurrentGamePadStates[i].IsConnected) { GamePadWasConnected[i] = true; } } } /// <summary> /// Helper for checking if a key was newly pressed during this update. The /// controllingPlayer parameter specifies which player to read input for. /// If this is null, it will accept input from any player. When a keypress /// is detected, the output playerIndex reports which player pressed it. /// </summary> public bool IsNewKeyPress(Keys key, PlayerIndex? controllingPlayer, out PlayerIndex playerIndex) { if (controllingPlayer.HasValue) { // Read input from the specified player. playerIndex = controllingPlayer.Value; int i = (int)playerIndex; return (CurrentKeyboardStates[i].IsKeyDown(key) && LastKeyboardStates[i].IsKeyUp(key)); } else { // Accept input from any player. return (IsNewKeyPress(key, PlayerIndex.One, out playerIndex) || IsNewKeyPress(key, PlayerIndex.Two, out playerIndex) || IsNewKeyPress(key, PlayerIndex.Three, out playerIndex) || IsNewKeyPress(key, PlayerIndex.Four, out playerIndex)); } } /// <summary> /// Helper for checking if a button was newly pressed during this update. /// The controllingPlayer parameter specifies which player to read input for. /// If this is null, it will accept input from any player. When a button press /// is detected, the output playerIndex reports which player pressed it. /// </summary> public bool IsNewButtonPress(Buttons button, PlayerIndex? controllingPlayer, out PlayerIndex playerIndex) { if (controllingPlayer.HasValue) { // Read input from the specified player. playerIndex = controllingPlayer.Value; int i = (int)playerIndex; return (CurrentGamePadStates[i].IsButtonDown(button) && LastGamePadStates[i].IsButtonUp(button)); } else { // Accept input from any player. return (IsNewButtonPress(button, PlayerIndex.One, out playerIndex) || IsNewButtonPress(button, PlayerIndex.Two, out playerIndex) || IsNewButtonPress(button, PlayerIndex.Three, out playerIndex) || IsNewButtonPress(button, PlayerIndex.Four, out playerIndex)); } } /// <summary> /// Checks for a "menu select" input action. /// The controllingPlayer parameter specifies which player to read input for. /// If this is null, it will accept input from any player. When the action /// is detected, the output playerIndex reports which player pressed it. /// </summary> public bool IsMenuSelect(PlayerIndex? controllingPlayer, out PlayerIndex playerIndex) { return IsNewKeyPress(Keys.Space, controllingPlayer, out playerIndex) || IsNewKeyPress(Keys.Enter, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.A, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.Start, controllingPlayer, out playerIndex); } /// <summary> /// Checks for a "menu cancel" input action. /// The controllingPlayer parameter specifies which player to read input for. /// If this is null, it will accept input from any player. When the action /// is detected, the output playerIndex reports which player pressed it. /// </summary> public bool IsMenuCancel(PlayerIndex? controllingPlayer, out PlayerIndex playerIndex) { return IsNewKeyPress(Keys.Escape, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.B, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.Back, controllingPlayer, out playerIndex); } /// <summary> /// Checks for a "menu up" input action. /// The controllingPlayer parameter specifies which player to read /// input for. If this is null, it will accept input from any player. /// </summary> public bool IsMenuUp(PlayerIndex? controllingPlayer) { PlayerIndex playerIndex; return IsNewKeyPress(Keys.Up, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.DPadUp, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.LeftThumbstickUp, controllingPlayer, out playerIndex); } /// <summary> /// Checks for a "menu down" input action. /// The controllingPlayer parameter specifies which player to read /// input for. If this is null, it will accept input from any player. /// </summary> public bool IsMenuDown(PlayerIndex? controllingPlayer) { PlayerIndex playerIndex; return IsNewKeyPress(Keys.Down, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.DPadDown, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.LeftThumbstickDown, controllingPlayer, out playerIndex); } /// <summary> /// Checks for a "pause the game" input action. /// The controllingPlayer parameter specifies which player to read /// input for. If this is null, it will accept input from any player. /// </summary> public bool IsPauseGame(PlayerIndex? controllingPlayer) { PlayerIndex playerIndex; return IsNewKeyPress(Keys.Escape, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.Back, controllingPlayer, out playerIndex) || IsNewButtonPress(Buttons.Start, controllingPlayer, out playerIndex); } #endregion } }
namespace System.Web.UI { /// <summary> /// HtmlBuilderTableTag /// </summary> public class HtmlBuilderTableTag { public class TableAttrib { public int? ColumnCount { get; set; } public string NullTdBody { get; set; } public int? RowPitch { get; set; } public int? ColumnPitch { get; set; } public string SelectedClass { get; set; } public string SelectedStyle { get; set; } public string AlternateClass { get; set; } public string AlternateStyle { get; set; } public TableTrCloseMethod? TrCloseMethod { get; set; } public TableAlternateOrientation? AlternateOrientation { get; set; } } public enum TableStage { Undefined, Colgroup, TheadTfoot, Tbody, } public enum TableTrCloseMethod { Undefined, Td, TdColspan } public enum TableAlternateOrientation { Column, Row } public HtmlBuilderTableTag(HtmlBuilder b, TableAttrib attrib) { if (attrib != null) { int? columnCount = attrib.ColumnCount; ColumnCount = (columnCount != null ? columnCount.Value : 0); NullTdBody = attrib.NullTdBody; int? rowPitch = attrib.RowPitch; RowPitch = (rowPitch != null ? rowPitch.Value : 1); int? columnPitch = attrib.ColumnPitch; ColumnPitch = (columnPitch != null ? columnPitch.Value : 1); SelectedClass = attrib.SelectedClass; SelectedStyle = attrib.SelectedStyle; AlternateClass = attrib.AlternateClass; AlternateStyle = attrib.AlternateStyle; TableTrCloseMethod? trCloseMethod = attrib.TrCloseMethod; TrCloseMethod = (trCloseMethod != null ? trCloseMethod.Value : TableTrCloseMethod.Undefined); TableAlternateOrientation? alternateOrientation = attrib.AlternateOrientation; AlternateOrientation = (alternateOrientation != null ? alternateOrientation.Value : TableAlternateOrientation.Row); } else { ColumnCount = 0; NullTdBody = string.Empty; RowPitch = 1; ColumnPitch = 1; SelectedClass = string.Empty; SelectedStyle = string.Empty; AlternateClass = string.Empty; AlternateStyle = string.Empty; TrCloseMethod = TableTrCloseMethod.Undefined; AlternateOrientation = TableAlternateOrientation.Row; } } protected internal virtual void AddAttribute(HtmlBuilder b, HtmlTextWriterEx w, HtmlTag tag, Nparams args) { bool isSelected; string appendStyle; bool isStyleDefined; string appendClass; bool isClassDefined; if (args != null) { isSelected = args.Slice<bool>("selected"); appendStyle = args.Slice<string>("appendStyle"); isStyleDefined = args.ContainsKey("style"); appendClass = args.Slice<string>("appendClass"); isClassDefined = args.ContainsKey("class"); if (tag == HtmlTag.Tr) IsTrHeader = args.Slice<bool>("header"); if (args.HasValue()) b.AddAttribute(args, null); } else { isSelected = false; appendStyle = string.Empty; isStyleDefined = false; appendClass = string.Empty; isClassDefined = false; } // only apply remaining to td/th if ((tag == HtmlTag.Td) || (tag == HtmlTag.Th)) { // style if (!isStyleDefined) { string effectiveStyle; if ((isSelected) && (!string.IsNullOrEmpty(SelectedStyle))) { effectiveStyle = (appendStyle.Length == 0 ? SelectedStyle : SelectedStyle + " " + appendStyle); w.AddAttributeIfUndefined(HtmlTextWriterAttribute.Style, effectiveStyle); } else if (!string.IsNullOrEmpty(AlternateStyle)) { effectiveStyle = (appendStyle.Length == 0 ? AlternateStyle : AlternateStyle + " " + appendStyle); switch (AlternateOrientation) { case TableAlternateOrientation.Column: if ((((ColumnIndex - ColumnOffset - 1 + ColumnPitch) / ColumnPitch) % 2) == 0) w.AddAttributeIfUndefined(HtmlTextWriterAttribute.Style, effectiveStyle); else if (appendStyle.Length > 0) w.AddAttributeIfUndefined(HtmlTextWriterAttribute.Style, appendStyle); break; case TableAlternateOrientation.Row: if ((((RowIndex - RowOffset - 1 + RowPitch) / RowPitch) % 2) == 0) w.AddAttributeIfUndefined(HtmlTextWriterAttribute.Style, effectiveStyle); else if (appendStyle.Length > 0) w.AddAttributeIfUndefined(HtmlTextWriterAttribute.Style, appendStyle); break; default: throw new InvalidOperationException(); } } else if (appendStyle.Length > 0) w.AddAttributeIfUndefined(HtmlTextWriterAttribute.Style, appendStyle); } // class if (!isClassDefined) { string effectiveClass; if ((isSelected) && (!string.IsNullOrEmpty(SelectedClass))) { effectiveClass = (appendClass.Length == 0 ? SelectedClass : SelectedClass + " " + appendClass); w.AddAttributeIfUndefined(HtmlTextWriterAttribute.Class, effectiveClass); } else if (!string.IsNullOrEmpty(AlternateClass)) { effectiveClass = (appendClass.Length == 0 ? AlternateClass : AlternateClass + " " + appendClass); switch (AlternateOrientation) { case TableAlternateOrientation.Column: if ((((ColumnIndex - ColumnOffset - 1 + ColumnPitch) / ColumnPitch) % 2) == 0) w.AddAttributeIfUndefined(HtmlTextWriterAttribute.Class, effectiveClass); else if (appendClass.Length > 0) w.AddAttributeIfUndefined(HtmlTextWriterAttribute.Class, appendClass); break; case TableAlternateOrientation.Row: if ((((RowIndex - RowOffset - 1 + RowPitch) / RowPitch) % 2) == 0) w.AddAttributeIfUndefined(HtmlTextWriterAttribute.Class, effectiveClass); else if (appendClass.Length > 0) w.AddAttributeIfUndefined(HtmlTextWriterAttribute.Class, appendClass); break; default: throw new InvalidOperationException(); } } else if (appendClass.Length > 0) w.AddAttributeIfUndefined(HtmlTextWriterAttribute.Class, appendClass); } } } public string AlternateClass { get; set; } public string AlternateStyle { get; set; } public TableAlternateOrientation AlternateOrientation { get; set; } public int ColumnCount { get; internal set; } public int ColumnIndex { get; internal set; } public int ColumnOffset { get; set; } public int ColumnPitch { get; set; } internal bool IsTrHeader { get; set; } public string NullTdBody { get; set; } public int RowIndex { get; internal set; } public int RowOffset { get; set; } public int RowPitch { get; set; } public string SelectedClass { get; set; } public string SelectedStyle { get; set; } internal TableStage Stage { get; set; } public object Tag { get; set; } public TableTrCloseMethod TrCloseMethod { get; set; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Xml; namespace Microsoft.Web.XmlTransform.Extended { internal class XmlAttributePreservationDict { #region Private data members private readonly List<string> _orderedAttributes = new List<string>(); private readonly Dictionary<string, string> _leadingSpaces = new Dictionary<string, string>(); private string _attributeNewLineString; private bool _computedOneAttributePerLine; private bool _oneAttributePerLine; #endregion private bool OneAttributePerLine { get { if (_computedOneAttributePerLine) return _oneAttributePerLine; _computedOneAttributePerLine = true; _oneAttributePerLine = ComputeOneAttributePerLine(); return _oneAttributePerLine; } } internal void ReadPreservationInfo(string elementStartTag) { Debug.Assert(elementStartTag.StartsWith("<", StringComparison.Ordinal) && elementStartTag.EndsWith(">", StringComparison.Ordinal), "Expected string containing exactly a single tag"); var whitespaceReader = new WhitespaceTrackingTextReader(new StringReader(elementStartTag)); var lastCharacter = EnumerateAttributes(elementStartTag, (line, linePosition, attributeName) => { _orderedAttributes.Add(attributeName); if (whitespaceReader.ReadToPosition(line, linePosition)) { _leadingSpaces.Add(attributeName, whitespaceReader.PrecedingWhitespace); } else { Debug.Fail("Couldn't get leading whitespace for attribute"); } } ); if (whitespaceReader.ReadToPosition(lastCharacter)) { _leadingSpaces.Add(String.Empty, whitespaceReader.PrecedingWhitespace); } else { Debug.Fail("Couldn't get trailing whitespace for tag"); } } private int EnumerateAttributes(string elementStartTag, Action<int, int, string> onAttributeSpotted) { var selfClosed = (elementStartTag.EndsWith("/>", StringComparison.Ordinal)); var xmlDocString = elementStartTag; if (!selfClosed) { xmlDocString = elementStartTag.Substring(0, elementStartTag.Length - 1) + "/>"; } var xmlReader = new XmlTextReader(new StringReader(xmlDocString)) { Namespaces = false }; xmlReader.Read(); var hasMoreAttributes = xmlReader.MoveToFirstAttribute(); while (hasMoreAttributes) { onAttributeSpotted(xmlReader.LineNumber, xmlReader.LinePosition, xmlReader.Name); hasMoreAttributes = xmlReader.MoveToNextAttribute(); } var lastCharacter = elementStartTag.Length; if (selfClosed) { lastCharacter--; } return lastCharacter; } internal void WritePreservedAttributes(XmlAttributePreservingWriter writer, XmlAttributeCollection attributes) { string oldNewLineString = null; if (_attributeNewLineString != null) { oldNewLineString = writer.SetAttributeNewLineString(_attributeNewLineString); } try { foreach (var attributeName in _orderedAttributes) { var attr = attributes[attributeName]; if (attr == null) continue; if (_leadingSpaces.ContainsKey(attributeName)) { writer.WriteAttributeWhitespace(_leadingSpaces[attributeName]); } attr.WriteTo(writer); } if (_leadingSpaces.ContainsKey(String.Empty)) { writer.WriteAttributeTrailingWhitespace(_leadingSpaces[String.Empty]); } } finally { if (oldNewLineString != null) { writer.SetAttributeNewLineString(oldNewLineString); } } } internal void UpdatePreservationInfo(XmlAttributeCollection updatedAttributes, XmlFormatter formatter) { if (updatedAttributes.Count == 0) { if (_orderedAttributes.Count > 0) { // All attributes were removed, clear preservation info _leadingSpaces.Clear(); _orderedAttributes.Clear(); } } else { var attributeExists = new Dictionary<string, bool>(); // Prepopulate the list with attributes that existed before foreach (var attributeName in _orderedAttributes) { attributeExists[attributeName] = false; } // Update the list with attributes that exist now foreach (XmlAttribute attribute in updatedAttributes) { if (!attributeExists.ContainsKey(attribute.Name)) { _orderedAttributes.Add(attribute.Name); } attributeExists[attribute.Name] = true; } var firstAttribute = true; string keepLeadingWhitespace = null; foreach (var key in _orderedAttributes) { var exists = attributeExists[key]; // Handle removal if (!exists) { // We need to figure out whether to keep the leading // or trailing whitespace. The logic is: // 1. The whitespace before the first attribute is // always kept, so remove trailing space. // 2. We want to keep newlines, so if the leading // space contains a newline then remove trailing // space. If multiple newlines are being removed, // keep the last one. // 3. Otherwise, remove leading space. // // In order to remove trailing space, we have to // remove the leading space of the next attribute, so // we store this leading space to replace the next. if (_leadingSpaces.ContainsKey(key)) { var leadingSpace = _leadingSpaces[key]; if (firstAttribute) { if (keepLeadingWhitespace == null) { keepLeadingWhitespace = leadingSpace; } } else if (ContainsNewLine(leadingSpace)) { keepLeadingWhitespace = leadingSpace; } _leadingSpaces.Remove(key); } } else if (keepLeadingWhitespace != null) { // Exception to rule #2 above: Don't replace an existing // newline with one that was removed if (firstAttribute || !_leadingSpaces.ContainsKey(key) || !ContainsNewLine(_leadingSpaces[key])) { _leadingSpaces[key] = keepLeadingWhitespace; } keepLeadingWhitespace = null; } // Handle addition else if (!_leadingSpaces.ContainsKey(key)) { if (firstAttribute) { // This will prevent the textwriter from writing a // newline before the first attribute _leadingSpaces[key] = " "; } else if (OneAttributePerLine) { // Add the indent space between each attribute _leadingSpaces[key] = GetAttributeNewLineString(formatter); } else { // Don't add any hard-coded spaces. All new attributes // should be at the end, so they'll be formatted while // writing. Make sure we have the right indent string, // though. EnsureAttributeNewLineString(formatter); } } // firstAttribute remains true until we find the first // attribute that actually exists firstAttribute = firstAttribute && !exists; } } } private bool ComputeOneAttributePerLine() { if (_leadingSpaces.Count > 1) { // If there is a newline between each pair of attributes, then // we'll continue putting newlines between all attributes. If // there's no newline between one pair, then we won't. var firstAttribute = true; foreach (var attributeName in _orderedAttributes) { // The space in front of the first attribute doesn't count, // because that space isn't between attributes. if (firstAttribute) { firstAttribute = false; } else if (_leadingSpaces.ContainsKey(attributeName) && !ContainsNewLine(_leadingSpaces[attributeName])) { // This means there are two attributes on one line return false; } } return true; } // If there aren't at least two original attributes on this // tag, then it's not possible to tell if more than one would // be on a line. Default to more than one per line. // TODO(jodavis): Should we look at sibling tags to decide? return false; } private bool ContainsNewLine(string space) { return space.IndexOf("\n", StringComparison.Ordinal) >= 0; } public string GetAttributeNewLineString(XmlFormatter formatter) { return _attributeNewLineString ?? (_attributeNewLineString = ComputeAttributeNewLineString(formatter)); } private string ComputeAttributeNewLineString(XmlFormatter formatter) { string lookAheadString = LookAheadForNewLineString(); if (lookAheadString != null) { return lookAheadString; } return formatter != null ? formatter.CurrentAttributeIndent : null; } private string LookAheadForNewLineString() { return _leadingSpaces.Values.FirstOrDefault(ContainsNewLine); } private void EnsureAttributeNewLineString(XmlFormatter formatter) { GetAttributeNewLineString(formatter); } } }
// 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! namespace Google.Apis.Libraryagent.v1 { /// <summary>The Libraryagent Service.</summary> public class LibraryagentService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public LibraryagentService() : this(new Google.Apis.Services.BaseClientService.Initializer()) { } /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public LibraryagentService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { Shelves = new ShelvesResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features => new string[0]; /// <summary>Gets the service name.</summary> public override string Name => "libraryagent"; /// <summary>Gets the service base URI.</summary> public override string BaseUri => #if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45 BaseUriOverride ?? "https://libraryagent.googleapis.com/"; #else "https://libraryagent.googleapis.com/"; #endif /// <summary>Gets the service base path.</summary> public override string BasePath => ""; #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri => "https://libraryagent.googleapis.com/batch"; /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath => "batch"; #endif /// <summary>Available OAuth 2.0 scopes for use with the Library Agent API.</summary> public class Scope { /// <summary> /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google /// Account. /// </summary> public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; } /// <summary>Available OAuth 2.0 scope constants for use with the Library Agent API.</summary> public static class ScopeConstants { /// <summary> /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google /// Account. /// </summary> public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; } /// <summary>Gets the Shelves resource.</summary> public virtual ShelvesResource Shelves { get; } } /// <summary>A base abstract class for Libraryagent requests.</summary> public abstract class LibraryagentBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { /// <summary>Constructs a new LibraryagentBaseServiceRequest instance.</summary> protected LibraryagentBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1 = 0, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2 = 1, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json = 0, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media = 1, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto = 2, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary> /// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required /// unless you provide an OAuth 2.0 token. /// </summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary> /// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a /// user, but should not exceed 40 characters. /// </summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes Libraryagent parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "shelves" collection of methods.</summary> public class ShelvesResource { private const string Resource = "shelves"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ShelvesResource(Google.Apis.Services.IClientService service) { this.service = service; Books = new BooksResource(service); } /// <summary>Gets the Books resource.</summary> public virtual BooksResource Books { get; } /// <summary>The "books" collection of methods.</summary> public class BooksResource { private const string Resource = "books"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public BooksResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary> /// Borrow a book from the library. Returns the book if it is borrowed successfully. Returns NOT_FOUND if /// the book does not exist in the library. Returns quota exceeded error if the amount of books borrowed /// exceeds allocation quota in any dimensions. /// </summary> /// <param name="name">Required. The name of the book to borrow.</param> public virtual BorrowRequest Borrow(string name) { return new BorrowRequest(service, name); } /// <summary> /// Borrow a book from the library. Returns the book if it is borrowed successfully. Returns NOT_FOUND if /// the book does not exist in the library. Returns quota exceeded error if the amount of books borrowed /// exceeds allocation quota in any dimensions. /// </summary> public class BorrowRequest : LibraryagentBaseServiceRequest<Google.Apis.Libraryagent.v1.Data.GoogleExampleLibraryagentV1Book> { /// <summary>Constructs a new Borrow request.</summary> public BorrowRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>Required. The name of the book to borrow.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "borrow"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/{+name}:borrow"; /// <summary>Initializes Borrow parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^shelves/[^/]+/books/[^/]+$", }); } } /// <summary>Gets a book. Returns NOT_FOUND if the book does not exist.</summary> /// <param name="name">Required. The name of the book to retrieve.</param> public virtual GetRequest Get(string name) { return new GetRequest(service, name); } /// <summary>Gets a book. Returns NOT_FOUND if the book does not exist.</summary> public class GetRequest : LibraryagentBaseServiceRequest<Google.Apis.Libraryagent.v1.Data.GoogleExampleLibraryagentV1Book> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>Required. The name of the book to retrieve.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "get"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/{+name}"; /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^shelves/[^/]+/books/[^/]+$", }); } } /// <summary> /// Lists books in a shelf. The order is unspecified but deterministic. Newly created books will not /// necessarily be added to the end of this list. Returns NOT_FOUND if the shelf does not exist. /// </summary> /// <param name="parent">Required. The name of the shelf whose books we'd like to list.</param> public virtual ListRequest List(string parent) { return new ListRequest(service, parent); } /// <summary> /// Lists books in a shelf. The order is unspecified but deterministic. Newly created books will not /// necessarily be added to the end of this list. Returns NOT_FOUND if the shelf does not exist. /// </summary> public class ListRequest : LibraryagentBaseServiceRequest<Google.Apis.Libraryagent.v1.Data.GoogleExampleLibraryagentV1ListBooksResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service) { Parent = parent; InitParameters(); } /// <summary>Required. The name of the shelf whose books we'd like to list.</summary> [Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)] public virtual string Parent { get; private set; } /// <summary> /// Requested page size. Server may return fewer books than requested. If unspecified, server will pick /// an appropriate default. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary> /// A token identifying a page of results the server should return. Typically, this is the value of /// ListBooksResponse.next_page_token. returned from the previous call to `ListBooks` method. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>Gets the method name.</summary> public override string MethodName => "list"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/{+parent}/books"; /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter { Name = "parent", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^shelves/[^/]+$", }); RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary> /// Return a book to the library. Returns the book if it is returned to the library successfully. Returns /// error if the book does not belong to the library or the users didn't borrow before. /// </summary> /// <param name="name">Required. The name of the book to return.</param> public virtual LibraryagentReturnRequest LibraryagentReturn(string name) { return new LibraryagentReturnRequest(service, name); } /// <summary> /// Return a book to the library. Returns the book if it is returned to the library successfully. Returns /// error if the book does not belong to the library or the users didn't borrow before. /// </summary> public class LibraryagentReturnRequest : LibraryagentBaseServiceRequest<Google.Apis.Libraryagent.v1.Data.GoogleExampleLibraryagentV1Book> { /// <summary>Constructs a new LibraryagentReturn request.</summary> public LibraryagentReturnRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>Required. The name of the book to return.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "return"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/{+name}:return"; /// <summary>Initializes LibraryagentReturn parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^shelves/[^/]+/books/[^/]+$", }); } } } /// <summary>Gets a shelf. Returns NOT_FOUND if the shelf does not exist.</summary> /// <param name="name">Required. The name of the shelf to retrieve.</param> public virtual GetRequest Get(string name) { return new GetRequest(service, name); } /// <summary>Gets a shelf. Returns NOT_FOUND if the shelf does not exist.</summary> public class GetRequest : LibraryagentBaseServiceRequest<Google.Apis.Libraryagent.v1.Data.GoogleExampleLibraryagentV1Shelf> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>Required. The name of the shelf to retrieve.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets the method name.</summary> public override string MethodName => "get"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/{+name}"; /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^shelves/[^/]+$", }); } } /// <summary> /// Lists shelves. The order is unspecified but deterministic. Newly created shelves will not necessarily be /// added to the end of this list. /// </summary> public virtual ListRequest List() { return new ListRequest(service); } /// <summary> /// Lists shelves. The order is unspecified but deterministic. Newly created shelves will not necessarily be /// added to the end of this list. /// </summary> public class ListRequest : LibraryagentBaseServiceRequest<Google.Apis.Libraryagent.v1.Data.GoogleExampleLibraryagentV1ListShelvesResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } /// <summary> /// Requested page size. Server may return fewer shelves than requested. If unspecified, server will pick an /// appropriate default. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary> /// A token identifying a page of results the server should return. Typically, this is the value of /// ListShelvesResponse.next_page_token returned from the previous call to `ListShelves` method. /// </summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>Gets the method name.</summary> public override string MethodName => "list"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "GET"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/shelves"; /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.Libraryagent.v1.Data { /// <summary>A single book in the library.</summary> public class GoogleExampleLibraryagentV1Book : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The name of the book author.</summary> [Newtonsoft.Json.JsonPropertyAttribute("author")] public virtual string Author { get; set; } /// <summary> /// The resource name of the book. Book names have the form `shelves/{shelf_id}/books/{book_id}`. The name is /// ignored when creating a book. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>Value indicating whether the book has been read.</summary> [Newtonsoft.Json.JsonPropertyAttribute("read")] public virtual System.Nullable<bool> Read { get; set; } /// <summary>The title of the book.</summary> [Newtonsoft.Json.JsonPropertyAttribute("title")] public virtual string Title { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for LibraryAgent.ListBooks.</summary> public class GoogleExampleLibraryagentV1ListBooksResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The list of books.</summary> [Newtonsoft.Json.JsonPropertyAttribute("books")] public virtual System.Collections.Generic.IList<GoogleExampleLibraryagentV1Book> Books { get; set; } /// <summary> /// A token to retrieve next page of results. Pass this value in the ListBooksRequest.page_token field in the /// subsequent call to `ListBooks` method to retrieve the next page of results. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for LibraryAgent.ListShelves.</summary> public class GoogleExampleLibraryagentV1ListShelvesResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// A token to retrieve next page of results. Pass this value in the ListShelvesRequest.page_token field in the /// subsequent call to `ListShelves` method to retrieve the next page of results. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>The list of shelves.</summary> [Newtonsoft.Json.JsonPropertyAttribute("shelves")] public virtual System.Collections.Generic.IList<GoogleExampleLibraryagentV1Shelf> Shelves { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>A Shelf contains a collection of books with a theme.</summary> public class GoogleExampleLibraryagentV1Shelf : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Output only. The resource name of the shelf. Shelf names have the form `shelves/{shelf_id}`. The name is /// ignored when creating a shelf. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>The theme of the shelf</summary> [Newtonsoft.Json.JsonPropertyAttribute("theme")] public virtual string Theme { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
//----------------------------------------------------------------------- // <copyright file="TestSubscriber.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using Akka.Actor; using Akka.Event; using Akka.Streams.Actors; using Akka.TestKit; using Reactive.Streams; namespace Akka.Streams.TestKit { public static class TestSubscriber { #region messages public interface ISubscriberEvent : INoSerializationVerificationNeeded, IDeadLetterSuppression { } public struct OnSubscribe : ISubscriberEvent { public readonly ISubscription Subscription; public OnSubscribe(ISubscription subscription) { Subscription = subscription; } public override string ToString() => $"TestSubscriber.OnSubscribe({Subscription})"; } public struct OnNext<T> : ISubscriberEvent { public readonly T Element; public OnNext(T element) { Element = element; } public override string ToString() => $"TestSubscriber.OnNext({Element})"; } public sealed class OnComplete: ISubscriberEvent { public static readonly OnComplete Instance = new OnComplete(); private OnComplete() { } public override string ToString() => "TestSubscriber.OnComplete"; } public struct OnError : ISubscriberEvent { public readonly Exception Cause; public OnError(Exception cause) { Cause = cause; } public override string ToString() => $"TestSubscriber.OnError({Cause.Message})"; } #endregion /// <summary> /// Implementation of <see cref="ISubscriber{T}"/> that allows various assertions. All timeouts are dilated automatically, /// for more details about time dilation refer to <see cref="TestKit"/>. /// </summary> public class ManualProbe<T> : ISubscriber<T> { private readonly TestProbe _probe; internal ManualProbe(TestKitBase testKit) { _probe = testKit.CreateTestProbe(); } private volatile ISubscription _subscription; public void OnSubscribe(ISubscription subscription) { _probe.Ref.Tell(new OnSubscribe(subscription)); } public void OnError(Exception cause) { _probe.Ref.Tell(new OnError(cause)); } public void OnComplete() { _probe.Ref.Tell(TestSubscriber.OnComplete.Instance); } public void OnNext(T element) { _probe.Ref.Tell(new OnNext<T>(element)); } /// <summary> /// Expects and returns <see cref="ISubscription"/>. /// </summary> public ISubscription ExpectSubscription() { _subscription = _probe.ExpectMsg<OnSubscribe>().Subscription; return _subscription; } /// <summary> /// Expect and return <see cref="ISubscriberEvent"/> (any of: <see cref="OnSubscribe"/>, <see cref="OnNext"/>, <see cref="OnError"/> or <see cref="OnComplete"/>). /// </summary> public ISubscriberEvent ExpectEvent() { return _probe.ExpectMsg<ISubscriberEvent>(); } /// <summary> /// Expect and return <see cref="ISubscriberEvent"/> (any of: <see cref="OnSubscribe"/>, <see cref="OnNext"/>, <see cref="OnError"/> or <see cref="OnComplete"/>). /// </summary> public ISubscriberEvent ExpectEvent(TimeSpan max) { return _probe.ExpectMsg<ISubscriberEvent>(max); } /// <summary> /// Fluent DSL. Expect and return <see cref="ISubscriberEvent"/> (any of: <see cref="OnSubscribe"/>, <see cref="OnNext"/>, <see cref="OnError"/> or <see cref="OnComplete"/>). /// </summary> public ManualProbe<T> ExpectEvent(ISubscriberEvent e) { _probe.ExpectMsg(e); return this; } /// <summary> /// Expect and return a stream element. /// </summary> public T ExpectNext() { var t = _probe.RemainingOrDilated(null); var message = _probe.ReceiveOne(t); if (message is OnNext<T>) return ((OnNext<T>) message).Element; else throw new Exception("expected OnNext, found " + message); } /// <summary> /// Fluent DSL. Expect a stream element. /// </summary> public ManualProbe<T> ExpectNext(T element) { _probe.ExpectMsg<OnNext<T>>(x => Equals(x.Element, element)); return this; } /// <summary> /// Fluent DSL. Expect a stream element during specified timeout. /// </summary> public ManualProbe<T> ExpectNext(T element, TimeSpan timeout) { _probe.ExpectMsg<OnNext<T>>(x => Equals(x.Element, element), timeout); return this; } /// <summary> /// Fluent DSL. Expect multiple stream elements. /// </summary> public ManualProbe<T> ExpectNext(T e1, T e2, params T[] elems) { var len = elems.Length + 2; var e = ExpectNextN(len).ToArray(); AssertEquals(e.Length, len, "expected to get {0} events, but got {1}", len, e.Length); AssertEquals(e[0], e1, "expected [0] element to be {0} but found {1}", e1, e[0]); AssertEquals(e[1], e2, "expected [1] element to be {0} but found {1}", e2, e[1]); for (var i = 0; i < elems.Length; i++) { var j = i + 2; AssertEquals(e[j], elems[i], "expected [{2}] element to be {0} but found {1}", elems[i], e[j], j); } return this; } /// <summary> /// FluentDSL. Expect multiple stream elements in arbitrary order. /// </summary> public ManualProbe<T> ExpectNextUnordered(T e1, T e2, params T[] elems) { var len = elems.Length + 2; var e = ExpectNextN(len).ToArray(); AssertEquals(e.Length, len, "expected to get {0} events, but got {1}", len, e.Length); var expectedSet = new HashSet<T>(elems) {e1, e2}; expectedSet.ExceptWith(e); Assert(expectedSet.Count == 0, "unexpected elemenents [{0}] found in the result", string.Join(", ", expectedSet)); return this; } /// <summary> /// Expect and return the next <paramref name="n"/> stream elements. /// </summary> public IEnumerable<T> ExpectNextN(long n) { var res = new List<T>((int)n); for (int i = 0; i < n; i++) { var next = _probe.ExpectMsg<OnNext<T>>(); res.Add(next.Element); } return res; } /// <summary> /// Fluent DSL. Expect the given elements to be signalled in order. /// </summary> public ManualProbe<T> ExpectNextN(IEnumerable<T> all) { foreach (var x in all) _probe.ExpectMsg<OnNext<T>>(y => Equals(y.Element, x)); return this; } /// <summary> /// Fluent DSL. Expect the given elements to be signalled in any order. /// </summary> public ManualProbe<T> ExpectNextUnorderedN(IEnumerable<T> all) { var collection = new HashSet<T>(all); while (collection.Count > 0) { var next = ExpectNext(); Assert(collection.Contains(next), $"expected one of (${string.Join(", ", collection)}), but received {next}"); collection.Remove(next); } return this; } /// <summary> /// Fluent DSL. Expect completion. /// </summary> public ManualProbe<T> ExpectComplete() { _probe.ExpectMsg<OnComplete>(); return this; } /// <summary> /// Expect and return the signalled <see cref="Exception"/>. /// </summary> public Exception ExpectError() { return _probe.ExpectMsg<OnError>().Cause; } /// <summary> /// Expect subscription to be followed immediatly by an error signal. By default single demand will be signalled in order to wake up a possibly lazy upstream. /// <seealso cref="ExpectSubscriptionAndError(bool)"/> /// </summary> public Exception ExpectSubscriptionAndError() { return ExpectSubscriptionAndError(true); } /// <summary> /// Expect subscription to be followed immediatly by an error signal. Depending on the `signalDemand` parameter demand may be signalled /// immediatly after obtaining the subscription in order to wake up a possibly lazy upstream.You can disable this by setting the `signalDemand` parameter to `false`. /// <seealso cref="ExpectSubscriptionAndError()"/> /// </summary> public Exception ExpectSubscriptionAndError(bool signalDemand) { var sub = ExpectSubscription(); if(signalDemand) sub.Request(1); return ExpectError(); } /// <summary> /// Fluent DSL. Expect subscription followed by immediate stream completion. By default single demand will be signalled in order to wake up a possibly lazy upstream /// </summary> /// <seealso cref="ExpectSubscriptionAndComplete(bool)"/> public ManualProbe<T> ExpectSubscriptionAndComplete() { return ExpectSubscriptionAndComplete(true); } /// <summary> /// Fluent DSL. Expect subscription followed by immediate stream completion. Depending on the `signalDemand` parameter /// demand may be signalled immediatly after obtaining the subscription in order to wake up a possibly lazy upstream. /// You can disable this by setting the `signalDemand` parameter to `false`. /// </summary> /// <seealso cref="ExpectSubscriptionAndComplete()"/> public ManualProbe<T> ExpectSubscriptionAndComplete(bool signalDemand) { var sub = ExpectSubscription(); if (signalDemand) sub.Request(1); ExpectComplete(); return this; } /// <summary> /// Expect given next element or error signal, returning whichever was signalled. /// </summary> public object ExpectNextOrError() { var message = _probe.FishForMessage(m => m is OnNext<T> || m is OnError, hint: "OnNext(_) or error"); if (message is OnNext<T>) return ((OnNext<T>) message).Element; return ((OnError) message).Cause; } /// <summary> /// Fluent DSL. Expect given next element or error signal. /// </summary> public ManualProbe<T> ExpectNextOrError(T element, Exception cause) { _probe.FishForMessage( m => (m is OnNext<T> && ((OnNext<T>) m).Element.Equals(element)) || (m is OnError && ((OnError) m).Cause.Equals(cause)), hint: $"OnNext({element}) or {cause.GetType().Name}"); return this; } /// <summary> /// Expect given next element or stream completion, returning whichever was signalled. /// </summary> public object ExpectNextOrComplete() { var message = _probe.FishForMessage(m => m is OnNext<T> || m is OnComplete, hint: "OnNext(_) or OnComplete"); if (message is OnNext<T>) return ((OnNext<T>) message).Element; return message; } /// <summary> /// Fluent DSL. Expect given next element or stream completion. /// </summary> public ManualProbe<T> ExpectNextOrComplete(T element) { _probe.FishForMessage( m => (m is OnNext<T> && ((OnNext<T>) m).Element.Equals(element)) || m is OnComplete, hint: $"OnNext({element}) or OnComplete"); return this; } /// <summary> /// Fluent DSL. Same as <see cref="ExpectNoMsg(TimeSpan)"/>, but correctly treating the timeFactor. /// </summary> public ManualProbe<T> ExpectNoMsg() { _probe.ExpectNoMsg(); return this; } /// <summary> /// Fluent DSL. Assert that no message is received for the specified time. /// </summary> public ManualProbe<T> ExpectNoMsg(TimeSpan remaining) { _probe.ExpectNoMsg(remaining); return this; } public TOther ExpectNext<TOther>(Predicate<TOther> predicate) { return _probe.ExpectMsg<OnNext<TOther>>(x => predicate(x.Element)).Element; } public TOther ExpectEvent<TOther>(Func<ISubscriberEvent, TOther> func) { return func(_probe.ExpectMsg<ISubscriberEvent>()); } /// <summary> /// Receive messages for a given duration or until one does not match a given partial function. /// </summary> public IEnumerable<TOther> ReceiveWhile<TOther>(TimeSpan? max = null, TimeSpan? idle = null, Func<object, TOther> filter = null, int msgs = int.MaxValue) where TOther : class { return _probe.ReceiveWhile(max, idle, filter, msgs); } /// <summary> /// Drains a given number of messages /// </summary> public IEnumerable<TOther> ReceiveWithin<TOther>(TimeSpan max, int messages = int.MaxValue) where TOther : class { return _probe.ReceiveWhile(max, max, msg => (msg as OnNext)?.Element as TOther, messages); } public TOther Within<TOther>(TimeSpan max, Func<TOther> func) { return _probe.Within(TimeSpan.Zero, max, func); } /// <summary> /// Attempt to drain the stream into a strict collection (by requesting <see cref="long.MaxValue"/> elements). /// </summary> /// <remarks> /// Use with caution: Be warned that this may not be a good idea if the stream is infinite or its elements are very large! /// </remarks> public IList<T> ToStrict(TimeSpan atMost) { var deadline = DateTime.UtcNow + atMost; // if no subscription was obtained yet, we expect it if (_subscription == null) ExpectSubscription(); _subscription.Request(long.MaxValue); var result = new List<T>(); while (true) { var e = ExpectEvent(TimeSpan.FromTicks(Math.Max(deadline.Ticks - DateTime.UtcNow.Ticks, 0))); if (e is OnError) throw new ArgumentException( $"ToStrict received OnError while draining stream! Accumulated elements: ${string.Join(", ", result)}", ((OnError) e).Cause); if (e is OnComplete) break; if (e is OnNext<T>) result.Add(((OnNext<T>) e).Element); } return result; } private void Assert(bool predicate, string format, params object[] args) { if (!predicate) throw new Exception(string.Format(format, args)); } private void AssertEquals<T1, T2>(T1 x, T2 y, string format, params object[] args) { if (!Equals(x, y)) throw new Exception(string.Format(format, args)); } } /// <summary> /// Single subscription tracking for <see cref="ManualProbe{T}"/>. /// </summary> public class Probe<T> : ManualProbe<T> { private readonly Lazy<ISubscription> _subscription; internal Probe(TestKitBase testKit) : base(testKit) { _subscription = new Lazy<ISubscription>(ExpectSubscription); } /// <summary> /// Asserts that a subscription has been received or will be received /// </summary> public Probe<T> EnsureSubscription() { var _ = _subscription.Value; // initializes lazy val return this; } public Probe<T> Request(long n) { _subscription.Value.Request(n); return this; } public Probe<T> RequestNext(T element) { _subscription.Value.Request(1); ExpectNext(element); return this; } public Probe<T> Cancel() { _subscription.Value.Cancel(); return this; } public T RequestNext() { _subscription.Value.Request(1); return ExpectNext(); } } public static ManualProbe<T> CreateManualSubscriberProbe<T>(this TestKitBase testKit) { return new ManualProbe<T>(testKit); } public static Probe<T> CreateSubscriberProbe<T>(this TestKitBase testKit) { return new Probe<T>(testKit); } } }
// // TypeReferenceCollection.cs // // Author: // Jb Evain ([email protected]) // // Generated by /CodeGen/cecil-gen.rb do not edit // Fri Mar 30 18:43:56 +0200 2007 // // (C) 2005 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 System.Collections.Specialized; using Mono.Cecil.Cil; using Hcp = Mono.Cecil.HashCodeProvider; using Cmp = System.Collections.Comparer; public sealed class TypeReferenceCollection : NameObjectCollectionBase, IList, IReflectionVisitable { ModuleDefinition m_container; public TypeReference this [int index] { get { return this.BaseGet (index) as TypeReference; } set { this.BaseSet (index, value); } } public TypeReference this [string fullName] { get { return this.BaseGet (fullName) as TypeReference; } set { this.BaseSet (fullName, value); } } public ModuleDefinition Container { get { return m_container; } } public bool IsSynchronized { get { return false; } } public object SyncRoot { get { return this; } } bool IList.IsReadOnly { get { return false; } } bool IList.IsFixedSize { get { return false; } } object IList.this [int index] { get { return BaseGet (index); } set { Check (value); BaseSet (index, value); } } public TypeReferenceCollection (ModuleDefinition container) : base (Hcp.Instance, Cmp.Default) { m_container = container; } public void Add (TypeReference value) { if (value == null) throw new ArgumentNullException ("value"); Attach (value); this.BaseAdd (value.FullName, value); } public void Clear () { foreach (TypeReference item in this) Detach (item); this.BaseClear (); } public bool Contains (TypeReference value) { return Contains (value.FullName); } public bool Contains (string fullName) { return this.BaseGet (fullName) != null; } public int IndexOf (TypeReference value) { string [] keys = this.BaseGetAllKeys (); return Array.IndexOf (keys, value.FullName, 0, keys.Length); } public void Remove (TypeReference value) { this.BaseRemove (value.FullName); Detach (value); } public void RemoveAt (int index) { TypeReference item = this [index]; Remove (item); Detach (item); } public void CopyTo (Array ary, int index) { this.BaseGetAllValues ().CopyTo (ary, index); } public new IEnumerator GetEnumerator () { return this.BaseGetAllValues ().GetEnumerator (); } public void Accept (IReflectionVisitor visitor) { visitor.VisitTypeReferenceCollection (this); } #if CF_1_0 || CF_2_0 internal object [] BaseGetAllValues () { object [] values = new object [this.Count]; for (int i=0; i < values.Length; ++i) { values [i] = this.BaseGet (i); } return values; } #endif void Check (object value) { if (!(value is TypeReference)) throw new ArgumentException (); } int IList.Add (object value) { Check (value); Add (value as TypeReference); return 0; } bool IList.Contains (object value) { Check (value); return Contains (value as TypeReference); } int IList.IndexOf (object value) { throw new NotSupportedException (); } void IList.Insert (int index, object value) { throw new NotSupportedException (); } void IList.Remove (object value) { Check (value); Remove (value as TypeReference); } void Detach (TypeReference type) { type.Module = null; } void Attach (TypeReference type) { if (type.Module != null) throw new ReflectionException ("Type is already attached, clone it instead"); type.Module = m_container; } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation 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 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.Text; using System.IO; using WebsitePanel.Setup.Web; using WebsitePanel.Setup.Windows; using Microsoft.Web.Management; using Microsoft.Web.Administration; using Ionic.Zip; using System.Xml; using System.Management; using Microsoft.Win32; using System.Linq; using System.Xml.Linq; using System.Xml.XPath; namespace WebsitePanel.Setup.Actions { public static class MyExtensions { public static XElement Element(this XElement parent, XName name, bool createIfNotFound) { var childNode = parent.Element(name); { if (childNode != null) { return childNode; } }; // if (createIfNotFound.Equals(true)) { childNode = new XElement(name); parent.Add(childNode); } // return childNode; } } #region Actions public class CheckOperatingSystemAction : Action, IPrerequisiteAction { bool IPrerequisiteAction.Run(SetupVariables vars) { throw new NotImplementedException(); } event EventHandler<ActionProgressEventArgs<bool>> IPrerequisiteAction.Complete { add { throw new NotImplementedException(); } remove { throw new NotImplementedException(); } } } public class CreateWindowsAccountAction : Action, IInstallAction, IUninstallAction { public const string UserAccountExists = "Account already exists"; public const string UserAccountDescription = "{0} account for anonymous access to Internet Information Services"; public const string LogStartMessage = "Creating Windows user account..."; public const string LogInfoMessage = "Creating Windows user account \"{0}\""; public const string LogEndMessage = "Created windows user account"; public const string InstallLogMessageLocal = "- Created a new Windows user account \"{0}\""; public const string InstallLogMessageDomain = "- Created a new Windows user account \"{0}\" in \"{1}\" domain"; public const string LogStartRollbackMessage = "Removing Windows user account..."; public const string LogInfoRollbackMessage = "Deleting user account \"{0}\""; public const string LogEndRollbackMessage = "User account has been removed"; public const string LogInfoRollbackMessageDomain = "Could not find user account '{0}' in domain '{1}', thus consider it removed"; public const string LogInfoRollbackMessageLocal = "Could not find user account '{0}', thus consider it removed"; public const string LogErrorRollbackMessage = "Could not remove Windows user account"; private void CreateUserAccount(SetupVariables vars) { //SetProgressText("Creating windows user account..."); var domain = vars.UserDomain; var userName = vars.UserAccount; // var description = String.Format(UserAccountDescription, vars.ComponentName); var memberOf = vars.UserMembership; var password = vars.UserPassword; Log.WriteStart(LogStartMessage); Log.WriteInfo(String.Format(LogInfoMessage, userName)); // create account SystemUserItem user = new SystemUserItem { Domain = domain, Name = userName, FullName = userName, Description = description, MemberOf = memberOf, Password = password, PasswordCantChange = true, PasswordNeverExpires = true, AccountDisabled = false, System = true }; // SecurityUtils.CreateUser(user); // add rollback action //RollBack.RegisterUserAccountAction(domain, userName); // update log Log.WriteEnd(LogEndMessage); // update install log if (String.IsNullOrEmpty(domain)) InstallLog.AppendLine(String.Format(InstallLogMessageLocal, userName)); else InstallLog.AppendLine(String.Format(InstallLogMessageDomain, userName, domain)); } public override bool Indeterminate { get { return true; } } void IInstallAction.Run(SetupVariables vars) { // Exit with an error if Windows account with the same name already exists if (SecurityUtils.UserExists(vars.UserDomain, vars.UserAccount)) throw new Exception(UserAccountExists); // CreateUserAccount(vars); } void IUninstallAction.Run(SetupVariables vars) { try { Log.WriteStart(LogStartRollbackMessage); Log.WriteInfo(String.Format(LogInfoRollbackMessage, vars.UserAccount)); // if (SecurityUtils.UserExists(vars.UserDomain, vars.UserAccount)) { SecurityUtils.DeleteUser(vars.UserDomain, vars.UserAccount); } else { if (!String.IsNullOrEmpty(vars.UserDomain)) { Log.WriteInfo(String.Format(LogInfoRollbackMessageDomain, vars.UserAccount, vars.UserDomain)); } else { Log.WriteInfo(String.Format(LogInfoRollbackMessageLocal, vars.UserAccount)); } } // Log.WriteEnd(LogEndRollbackMessage); } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) { return; } // Log.WriteError(LogErrorRollbackMessage, ex); throw; } } } public class ConfigureAspNetTempFolderPermissionsAction : Action, IInstallAction { void IInstallAction.Run(SetupVariables vars) { try { string path; if (vars.IISVersion.Major == 6) { // IIS_WPG -> C:\WINDOWS\Temp path = Environment.GetEnvironmentVariable("TMP", EnvironmentVariableTarget.Machine); SetFolderPermission(path, "IIS_WPG", NtfsPermission.Modify); // IIS_WPG - > C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files path = Path.Combine(System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(), "Temporary ASP.NET Files"); if (Utils.IsWin64() && Utils.IIS32Enabled()) path = path.Replace("Framework64", "Framework"); SetFolderPermission(path, "IIS_WPG", NtfsPermission.Modify); } // NETWORK_SERVICE -> C:\WINDOWS\Temp path = Environment.GetEnvironmentVariable("TMP", EnvironmentVariableTarget.Machine); // SetFolderPermissionBySid(path, SystemSID.NETWORK_SERVICE, NtfsPermission.Modify); } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) return; Log.WriteError("Security error", ex); } } private void SetFolderPermission(string path, string account, NtfsPermission permission) { try { if (!FileUtils.DirectoryExists(path)) { FileUtils.CreateDirectory(path); Log.WriteInfo(string.Format("Created {0} folder", path)); } Log.WriteStart(string.Format("Setting '{0}' permission for '{1}' folder for '{2}' account", permission, path, account)); SecurityUtils.GrantNtfsPermissions(path, null, account, permission, true, true); Log.WriteEnd("Set security permissions"); } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) return; Log.WriteError("Security error", ex); } } private void SetFolderPermissionBySid(string path, string account, NtfsPermission permission) { try { if (!FileUtils.DirectoryExists(path)) { FileUtils.CreateDirectory(path); Log.WriteInfo(string.Format("Created {0} folder", path)); } Log.WriteStart(string.Format("Setting '{0}' permission for '{1}' folder for '{2}' account", permission, path, account)); SecurityUtils.GrantNtfsPermissionsBySid(path, account, permission, true, true); Log.WriteEnd("Set security permissions"); } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) return; Log.WriteError("Security error", ex); } } } public class SetNtfsPermissionsAction : Action, IInstallAction { public const string LogStartInstallMessage = "Configuring folder permissions..."; public const string LogEndInstallMessage = "NTFS permissions has been applied to the application folder..."; public const string LogInstallErrorMessage = "Could not set content folder NTFS permissions"; public const string FqdnIdentity = "{0}\\{1}"; public override bool Indeterminate { get { return true; } } void IInstallAction.Run(SetupVariables vars) { string contentPath = vars.InstallationFolder; //creating user account string userName = vars.UserAccount; string userDomain = vars.UserDomain; string netbiosDomain = userDomain; // try { Begin(LogStartInstallMessage); // Log.WriteStart(LogStartInstallMessage); // if (!String.IsNullOrEmpty(userDomain)) { netbiosDomain = SecurityUtils.GetNETBIOSDomainName(userDomain); } // WebUtils.SetWebFolderPermissions(contentPath, netbiosDomain, userName); // Log.WriteEnd(LogEndInstallMessage); // Finish(LogStartInstallMessage); } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) return; Log.WriteError(LogInstallErrorMessage, ex); throw; } } } public class CreateWebApplicationPoolAction : Action, IInstallAction, IUninstallAction { public const string AppPoolNameFormatString = "{0} Pool"; public const string LogStartInstallMessage = "Creating application pool for the web site..."; public const string LogStartUninstallMessage = "Removing application pool..."; public const string LogUninstallAppPoolNotFoundMessage = "Application pool not found"; public static string GetWebIdentity(SetupVariables vars) { var userDomain = vars.UserDomain; var netbiosDomain = userDomain; var userName = vars.UserAccount; var iisVersion = vars.IISVersion; var iis7 = (iisVersion.Major >= 7); // if (!String.IsNullOrEmpty(userDomain)) { netbiosDomain = SecurityUtils.GetNETBIOSDomainName(userDomain); // if (iis7) { //for iis7 we use fqdn\user return String.Format(SetNtfsPermissionsAction.FqdnIdentity, userDomain, userName); } else { //for iis6 we use netbiosdomain\user return String.Format(SetNtfsPermissionsAction.FqdnIdentity, netbiosDomain, userName); } } // return userName; } public override bool Indeterminate { get { return true; } } void IInstallAction.Run(SetupVariables vars) { var appPoolName = String.Format(AppPoolNameFormatString, vars.ComponentFullName); var userDomain = vars.UserDomain; var netbiosDomain = userDomain; var userName = vars.UserAccount; var userPassword = vars.UserPassword; var identity = GetWebIdentity(vars); var componentId = vars.ComponentId; var iisVersion = vars.IISVersion; var iis7 = (iisVersion.Major >= 7); var poolExists = false; // vars.WebApplicationPoolName = appPoolName; // Maintain backward compatibility if (iis7) { poolExists = WebUtils.IIS7ApplicationPoolExists(appPoolName); } else { poolExists = WebUtils.ApplicationPoolExists(appPoolName); } // This flag is the opposite of poolExists flag vars.NewWebApplicationPool = !poolExists || vars.ComponentExists; if (poolExists) { //update app pool Log.WriteStart("Updating application pool"); Log.WriteInfo(String.Format("Updating application pool \"{0}\"", appPoolName)); // if (iis7) { WebUtils.UpdateIIS7ApplicationPool(appPoolName, userName, userPassword); } else { WebUtils.UpdateApplicationPool(appPoolName, userName, userPassword); } // //update log Log.WriteEnd("Updated application pool"); //update install log InstallLog.AppendLine(String.Format("- Updated application pool named \"{0}\"", appPoolName)); } else { // create app pool Log.WriteStart("Creating application pool"); Log.WriteInfo(String.Format("Creating application pool \"{0}\"", appPoolName)); // if (iis7) { WebUtils.CreateIIS7ApplicationPool(appPoolName, userName, userPassword); } else { WebUtils.CreateApplicationPool(appPoolName, userName, userPassword); } //update log Log.WriteEnd("Created application pool"); //update install log InstallLog.AppendLine(String.Format("- Created a new application pool named \"{0}\"", appPoolName)); } } void IUninstallAction.Run(SetupVariables vars) { try { var appPoolName = String.Format(AppPoolNameFormatString, vars.ComponentFullName); var iisVersion = vars.IISVersion; var iis7 = (iisVersion.Major >= 7); var poolExists = false; // Log.WriteStart(LogStartUninstallMessage); // vars.WebApplicationPoolName = appPoolName; // Maintain backward compatibility if (iis7) { poolExists = WebUtils.IIS7ApplicationPoolExists(appPoolName); } else { poolExists = WebUtils.ApplicationPoolExists(appPoolName); } if (!poolExists) { Log.WriteInfo(LogUninstallAppPoolNotFoundMessage); return; } // if (iis7) { WebUtils.DeleteIIS7ApplicationPool(appPoolName); } else { WebUtils.DeleteApplicationPool(appPoolName); } //update install log InstallLog.AppendLine(String.Format("- Removed application pool named \"{0}\"", appPoolName)); } finally { //update log //Log.WriteEnd(LogEndUninstallMessage); } } } public class CreateWebSiteAction : Action, IInstallAction, IUninstallAction { public const string LogStartMessage = "Creating web site..."; public const string LogEndMessage = ""; public override bool Indeterminate { get { return true; } } void IInstallAction.Run(SetupVariables vars) { var siteName = vars.ComponentFullName; var ip = vars.WebSiteIP; var port = vars.WebSitePort; var domain = vars.WebSiteDomain; var contentPath = vars.InstallationFolder; var iisVersion = vars.IISVersion; var iis7 = (iisVersion.Major >= 7); var userName = CreateWebApplicationPoolAction.GetWebIdentity(vars); var userPassword = vars.UserPassword; var appPool = vars.WebApplicationPoolName; var componentId = vars.ComponentId; var newSiteId = String.Empty; // Begin(LogStartMessage); // Log.WriteStart(LogStartMessage); // Log.WriteInfo(String.Format("Creating web site \"{0}\" ( IP: {1}, Port: {2}, Domain: {3} )", siteName, ip, port, domain)); //check for existing site var oldSiteId = iis7 ? WebUtils.GetIIS7SiteIdByBinding(ip, port, domain) : WebUtils.GetSiteIdByBinding(ip, port, domain); // if (oldSiteId != null) { // get site name string oldSiteName = iis7 ? oldSiteId : WebUtils.GetSite(oldSiteId).Name; throw new Exception( String.Format("'{0}' web site already has server binding ( IP: {1}, Port: {2}, Domain: {3} )", oldSiteName, ip, port, domain)); } // create site var site = new WebSiteItem { Name = siteName, SiteIPAddress = ip, ContentPath = contentPath, AllowExecuteAccess = false, AllowScriptAccess = true, AllowSourceAccess = false, AllowReadAccess = true, AllowWriteAccess = false, AnonymousUsername = userName, AnonymousUserPassword = userPassword, AllowDirectoryBrowsingAccess = false, AuthAnonymous = true, AuthWindows = true, DefaultDocs = null, HttpRedirect = "", InstalledDotNetFramework = AspNetVersion.AspNet20, ApplicationPool = appPool, // Bindings = new ServerBinding[] { new ServerBinding(ip, port, domain) }, }; // create site if (iis7) { newSiteId = WebUtils.CreateIIS7Site(site); } else { newSiteId = WebUtils.CreateSite(site); } try { Utils.OpenFirewallPort(vars.ComponentFullName, vars.WebSitePort, vars.IISVersion); } catch (Exception ex) { Log.WriteError("Open windows firewall port error", ex); } vars.VirtualDirectory = String.Empty; vars.NewWebSite = true; vars.NewVirtualDirectory = false; // update setup variables vars.WebSiteId = newSiteId; //update log Log.WriteEnd("Created web site"); // Finish(LogStartMessage); //update install log InstallLog.AppendLine(string.Format("- Created a new web site named \"{0}\" ({1})", siteName, newSiteId)); InstallLog.AppendLine(" You can access the application by the following URLs:"); string[] urls = Utils.GetApplicationUrls(ip, domain, port, null); foreach (string url in urls) { InstallLog.AppendLine(" http://" + url); } } void IUninstallAction.Run(SetupVariables vars) { var iisVersion = vars.IISVersion; var iis7 = (iisVersion.Major >= 7); var siteId = vars.WebSiteId; // try { Log.WriteStart("Deleting web site"); Log.WriteInfo(String.Format("Deleting web site \"{0}\"", siteId)); if (iis7) { if (WebUtils.IIS7SiteExists(siteId)) { WebUtils.DeleteIIS7Site(siteId); Log.WriteEnd("Deleted web site"); } } else { if (WebUtils.SiteIdExists(siteId)) { WebUtils.DeleteSite(siteId); Log.WriteEnd("Deleted web site"); } } } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) return; Log.WriteError("Web site delete error", ex); throw; } } } public class CopyFilesAction : Action, IInstallAction, IUninstallAction { public const string LogStartInstallMessage = "Copying files..."; public const string LogStartUninstallMessage = "Deleting files copied..."; internal void DoFilesCopyProcess(string source, string destination) { var sourceFolder = new DirectoryInfo(source); var destFolder = new DirectoryInfo(destination); // unzip long totalSize = FileUtils.CalculateFolderSize(sourceFolder.FullName); long copied = 0; int i = 0; List<DirectoryInfo> folders = new List<DirectoryInfo>(); List<FileInfo> files = new List<FileInfo>(); DirectoryInfo di = null; //FileInfo fi = null; string path = null; // Part 1: Indexing folders.Add(sourceFolder); while (i < folders.Count) { foreach (DirectoryInfo info in folders[i].GetDirectories()) { if (!folders.Contains(info)) folders.Add(info); } foreach (FileInfo info in folders[i].GetFiles()) { files.Add(info); } i++; } // Part 2: Destination Folders Creation /////////////////////////////////////////////////////// for (i = 0; i < folders.Count; i++) { if (folders[i].Exists) { path = destFolder.FullName + Path.DirectorySeparatorChar + folders[i].FullName.Remove(0, sourceFolder.FullName.Length); di = new DirectoryInfo(path); // Prevent IOException if (!di.Exists) di.Create(); } } // Part 3: Source to Destination File Copy /////////////////////////////////////////////////////// for (i = 0; i < files.Count; i++) { if (files[i].Exists) { path = destFolder.FullName + Path.DirectorySeparatorChar + files[i].FullName.Remove(0, sourceFolder.FullName.Length + 1); FileUtils.CopyFile(files[i], path); copied += files[i].Length; if (totalSize != 0) { // Update progress OnInstallProgressChanged(files[i].Name, Convert.ToInt32(copied * 100 / totalSize)); } } } } public override bool Indeterminate { get { return false; } } void IInstallAction.Run(SetupVariables vars) { try { Begin(LogStartInstallMessage); // var source = vars.InstallerFolder; var destination = vars.InstallationFolder; // string component = vars.ComponentFullName; // Log.WriteStart(LogStartInstallMessage); Log.WriteInfo(String.Format("Copying files from \"{0}\" to \"{1}\"", source, destination)); //showing copy process DoFilesCopyProcess(source, destination); // InstallLog.AppendLine(String.Format("- Copied {0} files", component)); // rollback //RollBack.RegisterDirectoryAction(destination); } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) return; Log.WriteError("Copy error", ex); throw; } } void IUninstallAction.Run(SetupVariables vars) { try { var path = vars.InstallationFolder; // Log.WriteStart(LogStartUninstallMessage); Log.WriteInfo(String.Format("Deleting directory \"{0}\"", path)); if (FileUtils.DirectoryExists(path)) { FileUtils.DeleteDirectory(path); } } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) return; Log.WriteError("Directory delete error", ex); throw; } } } public class SetServerPasswordAction : Action, IInstallAction { public const string LogStartInstallMessage = "Setting server password..."; public override bool Indeterminate { get { return true; } } void IInstallAction.Run(SetupVariables vars) { try { Begin(LogStartInstallMessage); Log.WriteStart("Updating configuration file (server password)"); Log.WriteInfo(String.Format("Server password is: '{0}'", vars.ServerPassword)); Log.WriteInfo("Single quotes are added for clarity purposes"); string file = Path.Combine(vars.InstallationFolder, vars.ConfigurationFile); string hash = Utils.ComputeSHA1(vars.ServerPassword); var XmlDoc = new XmlDocument(); XmlDoc.Load(file); var Node = XmlDoc.SelectSingleNode("configuration/websitepanel.server/security/password") as XmlElement; if (Node == null) throw new Exception("Unable to set a server access password. Check structure of configuration file."); else Node.SetAttribute("value", hash); XmlDoc.Save(file); } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) return; Log.WriteError("Configuration file update error", ex); throw; } } } public class SetCommonDistributiveParamsAction : Action, IPrepareDefaultsAction { public override bool Indeterminate { get { return true; } } void IPrepareDefaultsAction.Run(SetupVariables vars) { // if (String.IsNullOrEmpty(vars.InstallationFolder)) vars.InstallationFolder = String.Format(@"C:\WebsitePanel\{0}", vars.ComponentName); // if (String.IsNullOrEmpty(vars.WebSiteDomain)) vars.WebSiteDomain = String.Empty; // Force create new web site vars.NewWebSite = true; vars.NewVirtualDirectory = false; // if (String.IsNullOrEmpty(vars.ConfigurationFile)) vars.ConfigurationFile = "web.config"; } } public class EnsureServiceAccntSecured : Action, IPrepareDefaultsAction { public const string LogStartMessage = "Verifying setup parameters..."; public override bool Indeterminate { get { return true; } } void IPrepareDefaultsAction.Run(SetupVariables vars) { //Begin(LogStartMessage); // if (!String.IsNullOrEmpty(vars.UserPassword)) return; // vars.UserPassword = Guid.NewGuid().ToString(); // //Finish(LogEndMessage); } } public class SetServerDefaultInstallationSettingsAction : Action, IPrepareDefaultsAction { public override bool Indeterminate { get { return true; } } void IPrepareDefaultsAction.Run(SetupVariables vars) { // if (String.IsNullOrEmpty(vars.WebSiteIP)) vars.WebSiteIP = Global.Server.DefaultIP; // if (String.IsNullOrEmpty(vars.WebSitePort)) vars.WebSitePort = Global.Server.DefaultPort; // if (string.IsNullOrEmpty(vars.UserAccount)) vars.UserAccount = Global.Server.ServiceAccount; } } public class SaveComponentConfigSettingsAction : Action, IInstallAction, IUninstallAction { #region Uninstall public const string LogStartUninstallMessage = "Removing \"{0}\" component's configuration details"; public const string LogUninstallInfoMessage = "Deleting \"{0}\" component settings"; public const string LogErrorUninstallMessage = "Failed to remove the component configuration details"; public const string LogEndUninstallMessage = "Component's configuration has been removed"; #endregion public const string LogStartInstallMessage = "Updating system configuration..."; void IInstallAction.Run(SetupVariables vars) { Begin(LogStartInstallMessage); // Log.WriteStart(LogStartInstallMessage); // AppConfig.EnsureComponentConfig(vars.ComponentId); // AppConfig.SetComponentSettingStringValue(vars.ComponentId, "ApplicationName", vars.ApplicationName); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "ComponentCode", vars.ComponentCode); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "ComponentName", vars.ComponentName); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "ComponentDescription", vars.ComponentDescription); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "Release", vars.Version); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "Instance", vars.Instance); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "InstallFolder", vars.InstallationFolder); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "Installer", vars.Installer); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "InstallerType", vars.InstallerType); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "InstallerPath", vars.InstallerPath); // update config setings AppConfig.SetComponentSettingBooleanValue(vars.ComponentId, "NewApplicationPool", vars.NewWebApplicationPool); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "ApplicationPool", vars.WebApplicationPoolName); // update config setings AppConfig.SetComponentSettingStringValue(vars.ComponentId, "WebSiteId", vars.WebSiteId); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "WebSiteIP", vars.WebSiteIP); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "WebSitePort", vars.WebSitePort); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "WebSiteDomain", vars.WebSiteDomain); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "VirtualDirectory", vars.VirtualDirectory); AppConfig.SetComponentSettingBooleanValue(vars.ComponentId, "NewWebSite", vars.NewWebSite); AppConfig.SetComponentSettingBooleanValue(vars.ComponentId, "NewVirtualDirectory", vars.NewVirtualDirectory); // AppConfig.SetComponentSettingBooleanValue(vars.ComponentId, "NewUserAccount", true); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "UserAccount", vars.UserAccount); AppConfig.SetComponentSettingStringValue(vars.ComponentId, "Domain", vars.UserDomain); // AppConfig.SaveConfiguration(); } void IUninstallAction.Run(SetupVariables vars) { try { Log.WriteStart(LogStartUninstallMessage); Log.WriteInfo(String.Format(LogUninstallInfoMessage, vars.ComponentFullName)); XmlUtils.RemoveXmlNode(AppConfig.GetComponentConfig(vars.ComponentId)); AppConfig.SaveConfiguration(); Log.WriteEnd(LogEndUninstallMessage); InstallLog.AppendLine("- Updated system configuration"); } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) { return; } // Log.WriteError(LogErrorUninstallMessage, ex); throw; } } } public class SwitchAppPoolAspNetVersion : Action, IInstallAction { public const string Iis6_AspNet_v4 = "v4.0.30319"; public const string Iis7_AspNet_v4 = "v4.0"; void IInstallAction.Run(SetupVariables vars) { if (vars.IISVersion.Major >= 7) { ChangeAspNetVersionOnIis7(vars); } else { ChangeAspNetVersionOnIis6(vars); } } private void ChangeAspNetVersionOnIis7(SetupVariables vars) { using (var srvman = new ServerManager()) { var appPool = srvman.ApplicationPools[vars.WebApplicationPoolName]; // if (appPool == null) throw new ArgumentNullException("appPool"); // appPool.ManagedRuntimeVersion = Iis7_AspNet_v4; // srvman.CommitChanges(); } } private void ChangeAspNetVersionOnIis6(SetupVariables vars) { // Utils.ExecAspNetRegistrationToolCommand(vars, String.Format("-norestart -s {0}", vars.WebSiteId)); } } public class RegisterAspNet40Action : Action, IInstallAction { void IInstallAction.Run(SetupVariables vars) { if (CheckAspNet40Registered(vars) == false) { RegisterAspNet40(vars); } } private void RegisterAspNet40(Setup.SetupVariables setupVariables) { // Run ASP.NET Registration Tool command Utils.ExecAspNetRegistrationToolCommand(setupVariables, arguments: (setupVariables.IISVersion.Major == 6) ? "-ir -enable" : "-ir"); } private bool CheckAspNet40Registered(SetupVariables setupVariables) { // var aspNet40Registered = false; // Run ASP.NET Registration Tool command var psOutput = Utils.ExecAspNetRegistrationToolCommand(setupVariables, "-lv"); // Split process output per lines var strLines = psOutput.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries); // Lookup for an evidence of ASP.NET 4.0 aspNet40Registered = strLines.Any((string s) => { return s.Contains("4.0.30319.0"); }); // return aspNet40Registered; } } public class EnableAspNetWebExtensionAction : Action, IInstallAction { void IInstallAction.Run(SetupVariables vars) { if (vars.IISVersion.Major > 6) return; // Enable ASP.NET 4.0 Web Server Extension if it is prohibited if (Utils.GetAspNetWebExtensionStatus_Iis6(vars) == WebExtensionStatus.Prohibited) { Utils.EnableAspNetWebExtension_Iis6(); } } } public class MigrateServerWebConfigAction : Action, IInstallAction { void IInstallAction.Run(SetupVariables vars) { // DoMigration(vars); } private void DoMigration(SetupVariables vars) { var fileName = Path.Combine(vars.InstallationFolder, "web.config"); // var xdoc = XDocument.Load(fileName); // Modify <system.web /> node child elements var swnode = xdoc.Root.Element("system.web"); { // if (swnode.Element("compilation") != null) swnode.Element("compilation").Remove(); }; // Find/add WCF endpoints configuration section (DDTK) var serviceModelNode = xdoc.Root.Element("system.serviceModel", true); { // Find/add bindings node if does not exist var bindingsNode = serviceModelNode.Element("bindings", true); { // Find/add wsHttpBinding node if does not exist var wsHttpBindingNode = bindingsNode.Element("wsHttpBinding", true); { // Find SCVMM-DDTK endpoint binding configuration var vmmBindingNode = wsHttpBindingNode.XPathSelectElement("binding[@name='WSHttpBinding_IVirtualMachineManagementService']"); // Add SCVMM-DDTK endpoint binding configuration if (vmmBindingNode == null) wsHttpBindingNode.Add(XElement.Parse("<binding name=\"WSHttpBinding_IVirtualMachineManagementService\" closeTimeout=\"00:01:00\" openTimeout=\"00:01:00\" receiveTimeout=\"00:10:00\" sendTimeout=\"00:01:00\" bypassProxyOnLocal=\"false\" transactionFlow=\"false\" hostNameComparisonMode=\"StrongWildcard\" maxBufferPoolSize=\"524288\" maxReceivedMessageSize=\"10485760\" messageEncoding=\"Text\" textEncoding=\"utf-8\" useDefaultWebProxy=\"true\" allowCookies=\"false\"><readerQuotas maxDepth=\"32\" maxStringContentLength=\"8192\" maxArrayLength=\"16384\" maxBytesPerRead=\"4096\" maxNameTableCharCount=\"16384\" /><reliableSession ordered=\"true\" inactivityTimeout=\"00:10:00\" enabled=\"false\" /><security mode=\"Message\"><transport clientCredentialType=\"Windows\" proxyCredentialType=\"None\" realm=\"\" /><message clientCredentialType=\"Windows\" negotiateServiceCredential=\"true\" algorithmSuite=\"Default\" /></security></binding>")); // Find SCOM-DDTK endpoint binding configuration var omBindingNode = wsHttpBindingNode.XPathSelectElement("binding[@name='WSHttpBinding_IMonitoringService']"); // Add SCOM-DDTK endpoint binding configuration if (omBindingNode == null) wsHttpBindingNode.Add(XElement.Parse("<binding name=\"WSHttpBinding_IMonitoringService\" closeTimeout=\"00:01:00\" openTimeout=\"00:01:00\" receiveTimeout=\"00:10:00\" sendTimeout=\"00:01:00\" bypassProxyOnLocal=\"false\" transactionFlow=\"false\" hostNameComparisonMode=\"StrongWildcard\" maxBufferPoolSize=\"524288\" maxReceivedMessageSize=\"10485760\" messageEncoding=\"Text\" textEncoding=\"utf-8\" useDefaultWebProxy=\"true\" allowCookies=\"false\"><readerQuotas maxDepth=\"32\" maxStringContentLength=\"8192\" maxArrayLength=\"16384\" maxBytesPerRead=\"4096\" maxNameTableCharCount=\"16384\" /><reliableSession ordered=\"true\" inactivityTimeout=\"00:10:00\" enabled=\"false\" /><security mode=\"Message\"><transport clientCredentialType=\"Windows\" proxyCredentialType=\"None\" realm=\"\" /><message clientCredentialType=\"Windows\" negotiateServiceCredential=\"true\" algorithmSuite=\"Default\" /></security></binding>")); }; }; }; // Save all changes xdoc.Save(fileName); } } public class MigrateEntServerWebConfigAction : Action, IInstallAction { void IInstallAction.Run(SetupVariables vars) { // DoMigration(vars); } private void DoMigration(SetupVariables vars) { var fileName = Path.Combine(vars.InstallationFolder, "web.config"); // var xdoc = XDocument.Load(fileName); // Modify <system.web /> node child elements var swnode = xdoc.Root.Element("system.web"); { // if (swnode.Element("compilation") != null) swnode.Element("compilation").Remove(); }; // Save all changes xdoc.Save(fileName); } } public class AdjustHttpRuntimeRequestLengthAction : Action, IInstallAction { void IInstallAction.Run(SetupVariables vars) { // DoMigration(vars); } private void DoMigration(SetupVariables vars) { var fileName = Path.Combine(vars.InstallationFolder, "web.config"); // var xdoc = XDocument.Load(fileName); // Modify <system.web /> node child elements var swnode = xdoc.Root.Element("system.web"); { // Adjust httpRuntime maximum request length if (swnode.Element("httpRuntime") != null) { var htnode = swnode.Element("httpRuntime"); // htnode.SetAttributeValue("maxRequestLength", "16384"); } }; // Save all changes xdoc.Save(fileName); } } public class MigrateWebPortalWebConfigAction : Action, IInstallAction { void IInstallAction.Run(SetupVariables vars) { // if (vars.IISVersion.Major == 6) { DoMigrationOnIis6(vars); } else { DoMigrationOnIis7(vars); } } private void DoMigrationOnIis7(SetupVariables vars) { var fileName = Path.Combine(vars.InstallationFolder, "web.config"); // var xdoc = XDocument.Load(fileName); // Remove <configSections /> node if (xdoc.Root.Element("configSections") != null) xdoc.Root.Element("configSections").Remove(); // Remove <system.web.extensions /> node if (xdoc.Root.Element("system.web.extensions") != null) xdoc.Root.Element("system.web.extensions").Remove(); // Modify <appSettings /> node var apsnode = xdoc.Root.Element("appSettings"); { if (apsnode.XPathSelectElement("add[@key='ChartImageHandler']") == null) apsnode.Add(XElement.Parse("<add key=\"ChartImageHandler\" value=\"storage=file;timeout=20;\" />")); } // Modify <system.web /> node child elements var swnode = xdoc.Root.Element("system.web"); { // Modify <pages /> node var pnode = swnode.Element("pages"); { // Set rendering compatibility pnode.SetAttributeValue("controlRenderingCompatibilityVersion", "3.5"); // Select all legacy controls definitions var nodes = from node in pnode.Element("controls").Elements() where (String)node.Attribute("tagPrefix") == "asp" select node; // Remove all nodes found nodes.Remove(); }; // Set compatible request validation mode swnode.Element("httpRuntime").SetAttributeValue("requestValidationMode", "2.0"); // Modify <httpHandlers /> node var hhnode = swnode.Element("httpHandlers"); { // Remove <remove /> node if (hhnode.XPathSelectElement("remove[@path='*.asmx']") != null) hhnode.XPathSelectElement("remove[@path='*.asmx']").Remove(); // if (hhnode.XPathSelectElement("add[@path='*_AppService.axd']") != null) hhnode.XPathSelectElement("add[@path='*_AppService.axd']").Remove(); // if (hhnode.XPathSelectElement("add[@path='*.asmx']") != null) hhnode.XPathSelectElement("add[@path='*.asmx']").Remove(); // if (hhnode.XPathSelectElement("add[@path='ScriptResource.axd']") != null) hhnode.XPathSelectElement("add[@path='ScriptResource.axd']").Remove(); }; // Remove <httpModules /> node if (swnode.Element("httpModules") != null) swnode.Element("httpModules").Remove(); // if (swnode.Element("compilation") != null) swnode.Element("compilation").Remove(); }; // Remove <system.codedom /> node if (xdoc.Root.Element("system.codedom") != null) xdoc.Root.Element("system.codedom").Remove(); // var swrnode = xdoc.Root.Element("system.webServer"); { // Remove <modules /> node if (swrnode.Element("modules") != null) swrnode.Element("modules").Remove(); // Remove <handlers /> node if (swrnode.Element("handlers") != null) swrnode.Element("handlers").Remove(); // Add <handlers /> node if (swrnode.Element("handlers") == null) swrnode.Add(new XElement("handlers")); // Modify <handlers /> node var hsnode = swrnode.Element("handlers"); { // if (hsnode.XPathSelectElement("add[@path='Reserved.ReportViewerWebControl.axd']") == null) hsnode.Add(XElement.Parse("<add name=\"ReportViewerWebControl\" verb=\"*\" path=\"Reserved.ReportViewerWebControl.axd\" type=\"Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" />")); // if (hsnode.XPathSelectElement("add[@path='ChartImg.axd']") == null) hsnode.Add(XElement.Parse("<add name=\"ChartImg\" path=\"ChartImg.axd\" verb=\"GET,HEAD,POST\" type=\"System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" />")); } }; // Remove <runtime /> node if (xdoc.Root.Element("runtime") != null) xdoc.Root.Element("runtime").Remove(); // Save all changes xdoc.Save(fileName); } private void DoMigrationOnIis6(SetupVariables vars) { var fileName = Path.Combine(vars.InstallationFolder, "web.config"); // var xdoc = XDocument.Load(fileName); // Remove <configSections /> node if (xdoc.Root.Element("configSections") != null) xdoc.Root.Element("configSections").Remove(); // Remove <system.web.extensions /> node if (xdoc.Root.Element("system.web.extensions") != null) xdoc.Root.Element("system.web.extensions").Remove(); // Modify <appSettings /> node var apsnode = xdoc.Root.Element("appSettings"); { if (apsnode.XPathSelectElement("add[@key='ChartImageHandler']") == null) apsnode.Add(XElement.Parse("<add key=\"ChartImageHandler\" value=\"storage=file;timeout=20;\" />")); } // Modify <system.web /> node child elements var swnode = xdoc.Root.Element("system.web"); { // Modify <pages /> node var pnode = swnode.Element("pages"); { // Set rendering compatibility pnode.SetAttributeValue("controlRenderingCompatibilityVersion", "3.5"); // Select all legacy controls definitions var nodes = from node in pnode.Element("controls").Elements() where (String)node.Attribute("tagPrefix") == "asp" select node; // Remove all nodes found nodes.Remove(); }; // Set compatible request validation mode swnode.Element("httpRuntime").SetAttributeValue("requestValidationMode", "2.0"); // Modify <httpHandlers /> node var hhnode = swnode.Element("httpHandlers"); { // Remove <remove /> node if (hhnode.XPathSelectElement("remove[@path='*.asmx']") != null) hhnode.XPathSelectElement("remove[@path='*.asmx']").Remove(); // if (hhnode.XPathSelectElement("add[@path='*_AppService.axd']") != null) hhnode.XPathSelectElement("add[@path='*_AppService.axd']").Remove(); // if (hhnode.XPathSelectElement("add[@path='*.asmx']") != null) hhnode.XPathSelectElement("add[@path='*.asmx']").Remove(); // if (hhnode.XPathSelectElement("add[@path='ScriptResource.axd']") != null) hhnode.XPathSelectElement("add[@path='ScriptResource.axd']").Remove(); // if (hhnode.XPathSelectElement("add[@path='ChartImg.axd']") == null) hhnode.Add(XElement.Parse("<add path=\"ChartImg.axd\" verb=\"GET,HEAD,POST\" type=\"System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" validate=\"false\" />")); }; // Remove <httpModules /> node if (swnode.Element("httpModules") != null) swnode.Element("httpModules").Remove(); // Remove <compilation /> node if (swnode.Element("compilation") != null) swnode.Element("compilation").Remove(); }; // Remove <system.codedom /> node if (xdoc.Root.Element("system.codedom") != null) xdoc.Root.Element("system.codedom").Remove(); // Remove <runtime /> node if (xdoc.Root.Element("runtime") != null) xdoc.Root.Element("runtime").Remove(); // Save all changes xdoc.Save(fileName); } } public class CleanupWebsitePanelModulesListAction : Action, IInstallAction { void IInstallAction.Run(SetupVariables vars) { var filePath = Path.Combine(vars.InstallationFolder, @"App_Data\WebsitePanel_Modules.config"); // var xdoc = XDocument.Load(filePath); // if (xdoc.XPathSelectElement("//Control[@key='view_addon']") == null) { return; } // xdoc.XPathSelectElement("//Control[@key='view_addon']").Remove(); // xdoc.Save(filePath); } } #endregion public class RaiseExceptionAction : Action, IInstallAction { public override bool Indeterminate { get { return false; } } void IInstallAction.Run(SetupVariables vars) { throw new NotImplementedException(); } } public class ServerActionManager : BaseActionManager { public static readonly List<Action> InstallScenario = new List<Action> { new SetCommonDistributiveParamsAction(), new SetServerDefaultInstallationSettingsAction(), new EnsureServiceAccntSecured(), new CopyFilesAction(), new SetServerPasswordAction(), new CreateWindowsAccountAction(), new ConfigureAspNetTempFolderPermissionsAction(), new SetNtfsPermissionsAction(), new CreateWebApplicationPoolAction(), new CreateWebSiteAction(), new SwitchAppPoolAspNetVersion(), new SaveComponentConfigSettingsAction() }; public ServerActionManager(SetupVariables sessionVars) : base(sessionVars) { Initialize += new EventHandler(ServerActionManager_Initialize); } void ServerActionManager_Initialize(object sender, EventArgs e) { // switch (SessionVariables.SetupAction) { case SetupActions.Install: // Install LoadInstallationScenario(); break; default: break; } } protected virtual void LoadInstallationScenario() { CurrentScenario.AddRange(InstallScenario); } } }
/* * 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.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Security; using System.Timers; using System.Threading; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Monitoring; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using RegionFlags = OpenMetaverse.RegionFlags; using Timer = System.Timers.Timer; namespace OpenSim.Region.CoreModules.World.Estate { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "EstateManagementModule")] public class EstateManagementModule : IEstateModule, INonSharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private Timer m_regionChangeTimer = new Timer(); public Scene Scene { get; private set; } public IUserManagement UserManager { get; private set; } protected EstateManagementCommands m_commands; /// <summary> /// If false, region restart requests from the client are blocked even if they are otherwise legitimate. /// </summary> public bool AllowRegionRestartFromClient { get; set; } private bool m_ignoreEstateMinorAccessControl; private bool m_ignoreEstatePaymentAccessControl; private EstateTerrainXferHandler TerrainUploader; public TelehubManager m_Telehub; public event ChangeDelegate OnRegionInfoChange; public event ChangeDelegate OnEstateInfoChange; public event MessageDelegate OnEstateMessage; public event EstateTeleportOneUserHomeRequest OnEstateTeleportOneUserHomeRequest; public event EstateTeleportAllUsersHomeRequest OnEstateTeleportAllUsersHomeRequest; private int m_delayCount = 0; #region Region Module interface public string Name { get { return "EstateManagementModule"; } } public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource source) { AllowRegionRestartFromClient = true; IConfig config = source.Configs["EstateManagement"]; if (config != null) { AllowRegionRestartFromClient = config.GetBoolean("AllowRegionRestartFromClient", true); m_ignoreEstateMinorAccessControl = config.GetBoolean("IgnoreEstateMinorAccessControl", false); m_ignoreEstatePaymentAccessControl = config.GetBoolean("IgnoreEstatePaymentAccessControl", false); } } public void AddRegion(Scene scene) { Scene = scene; Scene.RegisterModuleInterface<IEstateModule>(this); Scene.EventManager.OnNewClient += EventManager_OnNewClient; Scene.EventManager.OnRequestChangeWaterHeight += changeWaterHeight; m_Telehub = new TelehubManager(scene); m_commands = new EstateManagementCommands(this); m_commands.Initialise(); m_regionChangeTimer.Interval = 10000; m_regionChangeTimer.Elapsed += RaiseRegionInfoChange; m_regionChangeTimer.AutoReset = false; } public void RemoveRegion(Scene scene) {} public void RegionLoaded(Scene scene) { // Sets up the sun module based no the saved Estate and Region Settings // DO NOT REMOVE or the sun will stop working scene.TriggerEstateSunUpdate(); UserManager = scene.RequestModuleInterface<IUserManagement>(); scene.RegionInfo.EstateSettings.DoDenyMinors = !m_ignoreEstateMinorAccessControl; scene.RegionInfo.EstateSettings.DoDenyAnonymous = !m_ignoreEstateMinorAccessControl; } public void Close() { m_commands.Close(); } #endregion #region IEstateModule Functions public uint GetRegionFlags() { RegionFlags flags = RegionFlags.None; // Fully implemented // if (Scene.RegionInfo.RegionSettings.AllowDamage) flags |= RegionFlags.AllowDamage; if (Scene.RegionInfo.RegionSettings.BlockTerraform) flags |= RegionFlags.BlockTerraform; if (!Scene.RegionInfo.RegionSettings.AllowLandResell) flags |= RegionFlags.BlockLandResell; if (Scene.RegionInfo.RegionSettings.DisableCollisions) flags |= RegionFlags.SkipCollisions; if (Scene.RegionInfo.RegionSettings.DisableScripts) flags |= RegionFlags.SkipScripts; if (Scene.RegionInfo.RegionSettings.DisablePhysics) flags |= RegionFlags.SkipPhysics; if (Scene.RegionInfo.RegionSettings.BlockFly) flags |= RegionFlags.NoFly; if (Scene.RegionInfo.RegionSettings.RestrictPushing) flags |= RegionFlags.RestrictPushObject; if (Scene.RegionInfo.RegionSettings.AllowLandJoinDivide) flags |= RegionFlags.AllowParcelChanges; if (Scene.RegionInfo.RegionSettings.BlockShowInSearch) flags |= RegionFlags.BlockParcelSearch; if (Scene.RegionInfo.RegionSettings.GodBlockSearch) flags |= (RegionFlags)(1 << 11); if (Scene.RegionInfo.RegionSettings.Casino) flags |= (RegionFlags)(1 << 10); if (Scene.RegionInfo.RegionSettings.FixedSun) flags |= RegionFlags.SunFixed; if (Scene.RegionInfo.RegionSettings.Sandbox) flags |= RegionFlags.Sandbox; if (Scene.RegionInfo.EstateSettings.AllowVoice) flags |= RegionFlags.AllowVoice; if (Scene.RegionInfo.EstateSettings.AllowLandmark) flags |= RegionFlags.AllowLandmark; if (Scene.RegionInfo.EstateSettings.AllowSetHome) flags |= RegionFlags.AllowSetHome; if (Scene.RegionInfo.EstateSettings.BlockDwell) flags |= RegionFlags.BlockDwell; if (Scene.RegionInfo.EstateSettings.ResetHomeOnTeleport) flags |= RegionFlags.ResetHomeOnTeleport; // TODO: SkipUpdateInterestList // Omitted // // Omitted: NullLayer (what is that?) // Omitted: SkipAgentAction (what does it do?) return (uint)flags; } public bool IsManager(UUID avatarID) { if (avatarID == Scene.RegionInfo.EstateSettings.EstateOwner) return true; List<UUID> ems = new List<UUID>(Scene.RegionInfo.EstateSettings.EstateManagers); if (ems.Contains(avatarID)) return true; return false; } public void sendRegionHandshakeToAll() { Scene.ForEachClient(sendRegionHandshake); } public void TriggerEstateInfoChange() { ChangeDelegate change = OnEstateInfoChange; if (change != null) change(Scene.RegionInfo.RegionID); } protected void RaiseRegionInfoChange(object sender, ElapsedEventArgs e) { ChangeDelegate change = OnRegionInfoChange; if (change != null) change(Scene.RegionInfo.RegionID); } public void TriggerRegionInfoChange() { m_regionChangeTimer.Stop(); m_regionChangeTimer.Start(); ChangeDelegate change = OnRegionInfoChange; if (change != null) change(Scene.RegionInfo.RegionID); } public void setEstateTerrainBaseTexture(int level, UUID texture) { setEstateTerrainBaseTexture(null, level, texture); sendRegionHandshakeToAll(); } public void setEstateTerrainTextureHeights(int corner, float lowValue, float highValue) { setEstateTerrainTextureHeights(null, corner, lowValue, highValue); } public bool IsTerrainXfer(ulong xferID) { lock (this) { if (TerrainUploader == null) return false; else return TerrainUploader.XferID == xferID; } } public string SetEstateOwner(int estateID, UserAccount account) { string response; // get the current settings from DB EstateSettings dbSettings = Scene.EstateDataService.LoadEstateSettings(estateID); if (dbSettings.EstateID == 0) { response = String.Format("No estate found with ID {0}", estateID); } else if (account.PrincipalID == dbSettings.EstateOwner) { response = String.Format("Estate already belongs to {0} ({1} {2})", account.PrincipalID, account.FirstName, account.LastName); } else { dbSettings.EstateOwner = account.PrincipalID; Scene.EstateDataService.StoreEstateSettings(dbSettings); response = String.Empty; // make sure there's a log entry to document the change m_log.InfoFormat("[ESTATE]: Estate Owner for {0} changed to {1} ({2} {3})", dbSettings.EstateName, account.PrincipalID, account.FirstName, account.LastName); // propagate the change List<UUID> regions = Scene.GetEstateRegions(estateID); UUID regionId = (regions.Count() > 0) ? regions.ElementAt(0) : UUID.Zero; if (regionId != UUID.Zero) { ChangeDelegate change = OnEstateInfoChange; if (change != null) change(regionId); } } return response; } public string SetEstateName(int estateID, string newName) { string response; // get the current settings from DB EstateSettings dbSettings = Scene.EstateDataService.LoadEstateSettings(estateID); if (dbSettings.EstateID == 0) { response = String.Format("No estate found with ID {0}", estateID); } else if (newName == dbSettings.EstateName) { response = String.Format("Estate {0} is already named \"{1}\"", estateID, newName); } else { List<int> estates = Scene.EstateDataService.GetEstates(newName); if (estates.Count() > 0) { response = String.Format("An estate named \"{0}\" already exists.", newName); } else { string oldName = dbSettings.EstateName; dbSettings.EstateName = newName; Scene.EstateDataService.StoreEstateSettings(dbSettings); response = String.Empty; // make sure there's a log entry to document the change m_log.InfoFormat("[ESTATE]: Estate {0} renamed from \"{1}\" to \"{2}\"", estateID, oldName, newName); // propagate the change List<UUID> regions = Scene.GetEstateRegions(estateID); UUID regionId = (regions.Count() > 0) ? regions.ElementAt(0) : UUID.Zero; if (regionId != UUID.Zero) { ChangeDelegate change = OnEstateInfoChange; if (change != null) change(regionId); } } } return response; } public string SetRegionEstate(RegionInfo regionInfo, int estateID) { string response; if (regionInfo.EstateSettings.EstateID == estateID) { response = String.Format("\"{0}\" is already part of estate {1}", regionInfo.RegionName, estateID); } else { // get the current settings from DB EstateSettings dbSettings = Scene.EstateDataService.LoadEstateSettings(estateID); if (dbSettings.EstateID == 0) { response = String.Format("No estate found with ID {0}", estateID); } else if (Scene.EstateDataService.LinkRegion(regionInfo.RegionID, estateID)) { // make sure there's a log entry to document the change m_log.InfoFormat("[ESTATE]: Region {0} ({1}) moved to Estate {2} ({3}).", regionInfo.RegionID, regionInfo.RegionName, estateID, dbSettings.EstateName); // propagate the change ChangeDelegate change = OnEstateInfoChange; if (change != null) change(regionInfo.RegionID); response = String.Empty; } else { response = String.Format("Could not move \"{0}\" to estate {1}", regionInfo.RegionName, estateID); } } return response; } public string CreateEstate(string estateName, UUID ownerID) { string response; if (string.IsNullOrEmpty(estateName)) { response = "No estate name specified."; } else { List<int> estates = Scene.EstateDataService.GetEstates(estateName); if (estates.Count() > 0) { response = String.Format("An estate named \"{0}\" already exists.", estateName); } else { EstateSettings settings = Scene.EstateDataService.CreateNewEstate(); if (settings == null) response = String.Format("Unable to create estate \"{0}\" at this simulator", estateName); else { settings.EstateOwner = ownerID; settings.EstateName = estateName; Scene.EstateDataService.StoreEstateSettings(settings); response = String.Empty; } } } return response; } #endregion #region Packet Data Responders private void clientSendDetailedEstateData(IClientAPI remote_client, UUID invoice) { sendDetailedEstateData(remote_client, invoice); sendEstateLists(remote_client, invoice); } private void sendDetailedEstateData(IClientAPI remote_client, UUID invoice) { uint sun = 0; if (Scene.RegionInfo.EstateSettings.FixedSun) sun = (uint)(Scene.RegionInfo.EstateSettings.SunPosition * 1024.0) + 0x1800; UUID estateOwner; estateOwner = Scene.RegionInfo.EstateSettings.EstateOwner; if (Scene.Permissions.IsGod(remote_client.AgentId)) estateOwner = remote_client.AgentId; remote_client.SendDetailedEstateData(invoice, Scene.RegionInfo.EstateSettings.EstateName, Scene.RegionInfo.EstateSettings.EstateID, Scene.RegionInfo.EstateSettings.ParentEstateID, GetEstateFlags(), sun, Scene.RegionInfo.RegionSettings.Covenant, (uint) Scene.RegionInfo.RegionSettings.CovenantChangedDateTime, Scene.RegionInfo.EstateSettings.AbuseEmail, estateOwner); } private void sendEstateLists(IClientAPI remote_client, UUID invoice) { remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.EstateManagers, Scene.RegionInfo.EstateSettings.EstateManagers, Scene.RegionInfo.EstateSettings.EstateID); remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AllowedAccess, Scene.RegionInfo.EstateSettings.EstateAccess, Scene.RegionInfo.EstateSettings.EstateID); remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AllowedGroups, Scene.RegionInfo.EstateSettings.EstateGroups, Scene.RegionInfo.EstateSettings.EstateID); remote_client.SendBannedUserList(invoice, Scene.RegionInfo.EstateSettings.EstateBans, Scene.RegionInfo.EstateSettings.EstateID); } private void estateSetRegionInfoHandler(bool blockTerraform, bool noFly, bool allowDamage, bool blockLandResell, int maxAgents, float objectBonusFactor, int matureLevel, bool restrictPushObject, bool allowParcelChanges) { if (blockTerraform) Scene.RegionInfo.RegionSettings.BlockTerraform = true; else Scene.RegionInfo.RegionSettings.BlockTerraform = false; if (noFly) Scene.RegionInfo.RegionSettings.BlockFly = true; else Scene.RegionInfo.RegionSettings.BlockFly = false; if (allowDamage) Scene.RegionInfo.RegionSettings.AllowDamage = true; else Scene.RegionInfo.RegionSettings.AllowDamage = false; if (blockLandResell) Scene.RegionInfo.RegionSettings.AllowLandResell = false; else Scene.RegionInfo.RegionSettings.AllowLandResell = true; if((byte)maxAgents <= Scene.RegionInfo.AgentCapacity) Scene.RegionInfo.RegionSettings.AgentLimit = (byte) maxAgents; else Scene.RegionInfo.RegionSettings.AgentLimit = Scene.RegionInfo.AgentCapacity; Scene.RegionInfo.RegionSettings.ObjectBonus = objectBonusFactor; if (matureLevel <= 13) Scene.RegionInfo.RegionSettings.Maturity = 0; else if (matureLevel <= 21) Scene.RegionInfo.RegionSettings.Maturity = 1; else Scene.RegionInfo.RegionSettings.Maturity = 2; if (restrictPushObject) Scene.RegionInfo.RegionSettings.RestrictPushing = true; else Scene.RegionInfo.RegionSettings.RestrictPushing = false; if (allowParcelChanges) Scene.RegionInfo.RegionSettings.AllowLandJoinDivide = true; else Scene.RegionInfo.RegionSettings.AllowLandJoinDivide = false; Scene.RegionInfo.RegionSettings.Save(); TriggerRegionInfoChange(); sendRegionInfoPacketToAll(); } public void setEstateTerrainBaseTexture(IClientAPI remoteClient, int level, UUID texture) { if (texture == UUID.Zero) return; switch (level) { case 0: Scene.RegionInfo.RegionSettings.TerrainTexture1 = texture; break; case 1: Scene.RegionInfo.RegionSettings.TerrainTexture2 = texture; break; case 2: Scene.RegionInfo.RegionSettings.TerrainTexture3 = texture; break; case 3: Scene.RegionInfo.RegionSettings.TerrainTexture4 = texture; break; } Scene.RegionInfo.RegionSettings.Save(); TriggerRegionInfoChange(); sendRegionInfoPacketToAll(); } public void setEstateTerrainTextureHeights(IClientAPI client, int corner, float lowValue, float highValue) { switch (corner) { case 0: Scene.RegionInfo.RegionSettings.Elevation1SW = lowValue; Scene.RegionInfo.RegionSettings.Elevation2SW = highValue; break; case 1: Scene.RegionInfo.RegionSettings.Elevation1NW = lowValue; Scene.RegionInfo.RegionSettings.Elevation2NW = highValue; break; case 2: Scene.RegionInfo.RegionSettings.Elevation1SE = lowValue; Scene.RegionInfo.RegionSettings.Elevation2SE = highValue; break; case 3: Scene.RegionInfo.RegionSettings.Elevation1NE = lowValue; Scene.RegionInfo.RegionSettings.Elevation2NE = highValue; break; } Scene.RegionInfo.RegionSettings.Save(); TriggerRegionInfoChange(); sendRegionHandshakeToAll(); sendRegionInfoPacketToAll(); } private void handleCommitEstateTerrainTextureRequest(IClientAPI remoteClient) { // sendRegionHandshakeToAll(); } public void setRegionTerrainSettings(float WaterHeight, float TerrainRaiseLimit, float TerrainLowerLimit, bool UseEstateSun, bool UseFixedSun, float SunHour, bool UseGlobal, bool EstateFixedSun, float EstateSunHour) { double lastwaterlevel = Scene.RegionInfo.RegionSettings.WaterHeight; // Water Height Scene.RegionInfo.RegionSettings.WaterHeight = WaterHeight; // Terraforming limits Scene.RegionInfo.RegionSettings.TerrainRaiseLimit = TerrainRaiseLimit; Scene.RegionInfo.RegionSettings.TerrainLowerLimit = TerrainLowerLimit; // Time of day / fixed sun Scene.RegionInfo.RegionSettings.UseEstateSun = UseEstateSun; Scene.RegionInfo.RegionSettings.FixedSun = UseFixedSun; Scene.RegionInfo.RegionSettings.SunPosition = SunHour; if(Scene.PhysicsEnabled && Scene.PhysicsScene != null && lastwaterlevel != WaterHeight) Scene.PhysicsScene.SetWaterLevel(WaterHeight); Scene.TriggerEstateSunUpdate(); //m_log.Debug("[ESTATE]: UFS: " + UseFixedSun.ToString()); //m_log.Debug("[ESTATE]: SunHour: " + SunHour.ToString()); sendRegionInfoPacketToAll(); Scene.RegionInfo.RegionSettings.Save(); TriggerRegionInfoChange(); } private void handleEstateRestartSimRequest(IClientAPI remoteClient, int timeInSeconds) { if (!AllowRegionRestartFromClient) { remoteClient.SendAlertMessage("Region restart has been disabled on this simulator."); return; } IRestartModule restartModule = Scene.RequestModuleInterface<IRestartModule>(); if (restartModule != null) { if (timeInSeconds == -1) { m_delayCount++; if (m_delayCount > 3) return; restartModule.DelayRestart(3600, "Restart delayed by region manager"); return; } List<int> times = new List<int>(); while (timeInSeconds > 0) { times.Add(timeInSeconds); if (timeInSeconds > 300) timeInSeconds -= 120; else if (timeInSeconds > 30) timeInSeconds -= 30; else timeInSeconds -= 15; } restartModule.ScheduleRestart(UUID.Zero, "Region will restart in {0}", times.ToArray(), false); m_log.InfoFormat( "User {0} requested restart of region {1} in {2} seconds", remoteClient.Name, Scene.Name, times.Count != 0 ? times[0] : 0); } } private void handleChangeEstateCovenantRequest(IClientAPI remoteClient, UUID estateCovenantID) { // m_log.DebugFormat( // "[ESTATE MANAGEMENT MODULE]: Handling request from {0} to change estate covenant to {1}", // remoteClient.Name, estateCovenantID); Scene.RegionInfo.RegionSettings.Covenant = estateCovenantID; Scene.RegionInfo.RegionSettings.CovenantChangedDateTime = Util.UnixTimeSinceEpoch(); Scene.RegionInfo.RegionSettings.Save(); TriggerRegionInfoChange(); } private object deltareqLock = new object(); private bool runnigDeltaExec = false; private class EstateAccessDeltaRequest { public IClientAPI remote_client; public UUID invoice; public int estateAccessType; public UUID user; } private BlockingCollection<EstateAccessDeltaRequest> deltaRequests = new BlockingCollection<EstateAccessDeltaRequest>(); private void handleEstateAccessDeltaRequest(IClientAPI _remote_client, UUID _invoice, int _estateAccessType, UUID _user) { // EstateAccessDelta handles Estate Managers, Sim Access, Sim Banlist, allowed Groups.. etc. if (_user == Scene.RegionInfo.EstateSettings.EstateOwner) return; // never process EO EstateAccessDeltaRequest newreq = new EstateAccessDeltaRequest(); newreq.remote_client = _remote_client; newreq.invoice = _invoice; newreq.estateAccessType = _estateAccessType; newreq.user = _user; deltaRequests.Add(newreq); lock(deltareqLock) { if(!runnigDeltaExec) { runnigDeltaExec = true; WorkManager.RunInThreadPool(execDeltaRequests,null,"execDeltaRequests"); } } } private void execDeltaRequests(object o) { IClientAPI remote_client; UUID invoice; int estateAccessType; UUID user; Dictionary<int,EstateSettings> changed = new Dictionary<int,EstateSettings>(); Dictionary<IClientAPI,UUID> sendAllowedOrBanList = new Dictionary<IClientAPI,UUID>(); Dictionary<IClientAPI,UUID> sendManagers = new Dictionary<IClientAPI,UUID>(); Dictionary<IClientAPI,UUID> sendGroups = new Dictionary<IClientAPI,UUID>(); List<EstateSettings> otherEstates = new List<EstateSettings>(); bool sentAllowedFull = false; bool sentBansFull = false; bool sentGroupsFull = false; bool sentManagersFull = false; EstateAccessDeltaRequest req; while(Scene.IsRunning) { req = null; deltaRequests.TryTake(out req, 500); if(!Scene.IsRunning) break; if(req == null) { if(changed.Count > 0) { foreach(EstateSettings est in changed.Values) Scene.EstateDataService.StoreEstateSettings(est); TriggerEstateInfoChange(); } EstateSettings es = Scene.RegionInfo.EstateSettings; foreach(KeyValuePair<IClientAPI,UUID> kvp in sendAllowedOrBanList) { IClientAPI cli = kvp.Key; UUID invoive = kvp.Value; cli.SendEstateList(invoive, (int)Constants.EstateAccessCodex.AllowedAccess, es.EstateAccess, es.EstateID); cli.SendBannedUserList(invoive, es.EstateBans, es.EstateID); } sendAllowedOrBanList.Clear(); foreach(KeyValuePair<IClientAPI,UUID> kvp in sendManagers) { IClientAPI cli = kvp.Key; cli.SendEstateList(kvp.Value, (int)Constants.EstateAccessCodex.EstateManagers, es.EstateManagers, es.EstateID); } foreach(KeyValuePair<IClientAPI,UUID> kvp in sendGroups) { IClientAPI cli = kvp.Key; cli.SendEstateList(kvp.Value, (int)Constants.EstateAccessCodex.AllowedGroups, es.EstateGroups, es.EstateID); } otherEstates.Clear(); sendAllowedOrBanList.Clear(); sendManagers.Clear(); sendGroups.Clear(); changed.Clear(); lock(deltareqLock) { if(deltaRequests.Count != 0) continue; runnigDeltaExec = false; return; } } remote_client = req.remote_client; if(!remote_client.IsActive) continue; invoice = req.invoice; user = req.user; estateAccessType = req.estateAccessType; bool needReply = ((estateAccessType & 1024) == 0); bool doOtherEstates = ((estateAccessType & 3) != 0); EstateSettings thisSettings = Scene.RegionInfo.EstateSettings; int thisEstateID =(int)thisSettings.EstateID; UUID agentID = remote_client.AgentId; bool isadmin = Scene.Permissions.IsAdministrator(agentID); // just i case recheck rights if (!isadmin && !Scene.Permissions.IsEstateManager(agentID)) { remote_client.SendAlertMessage("Method EstateAccess Failed, you don't have permissions"); continue; } otherEstates.Clear(); if(doOtherEstates) { UUID thisOwner = Scene.RegionInfo.EstateSettings.EstateOwner; List<int> estateIDs = Scene.EstateDataService.GetEstatesByOwner(thisOwner); foreach (int estateID in estateIDs) { if (estateID == thisEstateID) continue; EstateSettings estateSettings; if(changed.ContainsKey(estateID)) estateSettings = changed[estateID]; else estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID); if(!isadmin && !estateSettings.IsEstateManagerOrOwner(agentID)) continue; otherEstates.Add(estateSettings); } estateIDs.Clear(); } // the commands // first the ones allowed for estate managers on this region if ((estateAccessType & 4) != 0) // User add { if(thisSettings.EstateUsersCount() >= (int)Constants.EstateAccessLimits.AllowedAccess) { if(!sentAllowedFull) { sentAllowedFull = true; remote_client.SendAlertMessage("Estate Allowed users list is full"); } } else { if (doOtherEstates) { foreach (EstateSettings estateSettings in otherEstates) { if(!isadmin && !estateSettings.IsEstateManagerOrOwner(agentID)) continue; if(estateSettings.EstateUsersCount() >= (int)Constants.EstateAccessLimits.AllowedAccess) continue; estateSettings.AddEstateUser(user); estateSettings.RemoveBan(user); changed[(int)estateSettings.EstateID] = estateSettings; } } thisSettings.AddEstateUser(user); thisSettings.RemoveBan(user); changed[thisEstateID] = thisSettings;; if(needReply) sendAllowedOrBanList[remote_client] = invoice; } } if ((estateAccessType & 8) != 0) // User remove { if (doOtherEstates) // All estates { foreach (EstateSettings estateSettings in otherEstates) { if(!isadmin && !estateSettings.IsEstateManagerOrOwner(agentID)) continue; estateSettings.RemoveEstateUser(user); changed[(int)estateSettings.EstateID] = estateSettings; } } thisSettings.RemoveEstateUser(user); changed[thisEstateID] = thisSettings;; if(needReply) sendAllowedOrBanList[remote_client] = invoice; } if ((estateAccessType & 16) != 0) // Group add { if(thisSettings.EstateGroupsCount() >= (int)Constants.EstateAccessLimits.AllowedGroups) { if(!sentGroupsFull) { sentGroupsFull = true; remote_client.SendAlertMessage("Estate Allowed groups list is full"); } } else { if (doOtherEstates) // All estates { foreach (EstateSettings estateSettings in otherEstates) { if(!isadmin && !estateSettings.IsEstateManagerOrOwner(agentID)) continue; if(estateSettings.EstateGroupsCount() >= (int)Constants.EstateAccessLimits.AllowedGroups) continue; estateSettings.AddEstateGroup(user); changed[(int)estateSettings.EstateID] = estateSettings; } } thisSettings.AddEstateGroup(user); changed[thisEstateID] = thisSettings; sendGroups[remote_client] = invoice; } } if ((estateAccessType & 32) != 0) // Group remove { if (doOtherEstates) // All estates { foreach (EstateSettings estateSettings in otherEstates) { if(!isadmin && !estateSettings.IsEstateManagerOrOwner(agentID)) continue; estateSettings.RemoveEstateGroup(user); changed[(int)estateSettings.EstateID] = estateSettings; } } thisSettings.RemoveEstateGroup(user); changed[thisEstateID] = thisSettings; sendGroups[remote_client] = invoice; } if ((estateAccessType & 64) != 0) // Ban add { if(thisSettings.EstateBansCount() >= (int)Constants.EstateAccessLimits.EstateBans) { if(!sentBansFull) { sentBansFull = true; remote_client.SendAlertMessage("Estate Ban list is full"); } } else { EstateBan[] banlistcheck = Scene.RegionInfo.EstateSettings.EstateBans; bool alreadyInList = false; for (int i = 0; i < banlistcheck.Length; i++) { if (user == banlistcheck[i].BannedUserID) { alreadyInList = true; break; } } if (!alreadyInList) { if (doOtherEstates) // All estates { foreach (EstateSettings estateSettings in otherEstates) { if(!isadmin && !estateSettings.IsEstateManagerOrOwner(agentID)) continue; if(estateSettings.EstateBansCount() >= (int)Constants.EstateAccessLimits.EstateBans) continue; EstateBan bitem = new EstateBan(); bitem.BannedUserID = user; bitem.EstateID = estateSettings.EstateID; bitem.BannedHostAddress = "0.0.0.0"; bitem.BannedHostIPMask = "0.0.0.0"; estateSettings.AddBan(bitem); estateSettings.RemoveEstateUser(user); changed[(int)estateSettings.EstateID] = estateSettings; } } EstateBan item = new EstateBan(); item.BannedUserID = user; item.EstateID = Scene.RegionInfo.EstateSettings.EstateID; item.BannedHostAddress = "0.0.0.0"; item.BannedHostIPMask = "0.0.0.0"; thisSettings.AddBan(item); thisSettings.RemoveEstateUser(user); changed[thisEstateID] = thisSettings; ScenePresence s = Scene.GetScenePresence(user); if (s != null) { if (!s.IsChildAgent) { if (!Scene.TeleportClientHome(user, s.ControllingClient)) { s.ControllingClient.Kick("Your access to the region was revoked and TP home failed - you have been logged out."); Scene.CloseAgent(s.UUID, false); } } } } else { remote_client.SendAlertMessage("User is already on the region ban list"); } //Scene.RegionInfo.regionBanlist.Add(Manager(user); if(needReply) sendAllowedOrBanList[remote_client] = invoice; } } if ((estateAccessType & 128) != 0) // Ban remove { EstateBan[] banlistcheck = Scene.RegionInfo.EstateSettings.EstateBans; bool alreadyInList = false; EstateBan listitem = null; for (int i = 0; i < banlistcheck.Length; i++) { if (user == banlistcheck[i].BannedUserID) { alreadyInList = true; listitem = banlistcheck[i]; break; } } if (alreadyInList && listitem != null) { if (doOtherEstates) // All estates { foreach (EstateSettings estateSettings in otherEstates) { if(!isadmin && !estateSettings.IsEstateManagerOrOwner(agentID)) continue; estateSettings.RemoveBan(user); changed[(int)estateSettings.EstateID] = estateSettings; } } thisSettings.RemoveBan(listitem.BannedUserID); changed[thisEstateID] = thisSettings; } else { remote_client.SendAlertMessage("User is not on the region ban list"); } if(needReply) sendAllowedOrBanList[remote_client] = invoice; } // last the ones only for owners of this region if (!Scene.Permissions.CanIssueEstateCommand(agentID, true)) { remote_client.SendAlertMessage("Method EstateAccess Failed, you don't have permissions"); continue; } if ((estateAccessType & 256) != 0) // Manager add { if(thisSettings.EstateManagersCount() >= (int)Constants.EstateAccessLimits.EstateManagers) { if(!sentManagersFull) { sentManagersFull = true; remote_client.SendAlertMessage("Estate Managers list is full"); } } else { if (doOtherEstates) // All estates { foreach (EstateSettings estateSettings in otherEstates) { if(!isadmin && !estateSettings.IsEstateOwner(agentID)) // redundante check? continue; if(estateSettings.EstateManagersCount() >= (int)Constants.EstateAccessLimits.EstateManagers) continue; estateSettings.AddEstateManager(user); changed[(int)estateSettings.EstateID] = estateSettings; } } thisSettings.AddEstateManager(user); changed[thisEstateID] = thisSettings; sendManagers[remote_client] = invoice; } } if ((estateAccessType & 512) != 0) // Manager remove { if (doOtherEstates) // All estates { foreach (EstateSettings estateSettings in otherEstates) { if(!isadmin && !estateSettings.IsEstateOwner(agentID)) continue; estateSettings.RemoveEstateManager(user); changed[(int)estateSettings.EstateID] = estateSettings; } } thisSettings.RemoveEstateManager(user); changed[thisEstateID] = thisSettings; sendManagers[remote_client] = invoice; } } lock(deltareqLock) runnigDeltaExec = false; } public void HandleOnEstateManageTelehub(IClientAPI client, UUID invoice, UUID senderID, string cmd, uint param1) { SceneObjectPart part; switch (cmd) { case "info ui": break; case "connect": // Add the Telehub part = Scene.GetSceneObjectPart((uint)param1); if (part == null) return; SceneObjectGroup grp = part.ParentGroup; m_Telehub.Connect(grp); break; case "delete": // Disconnect Telehub m_Telehub.Disconnect(); break; case "spawnpoint add": // Add SpawnPoint to the Telehub part = Scene.GetSceneObjectPart((uint)param1); if (part == null) return; m_Telehub.AddSpawnPoint(part.AbsolutePosition); break; case "spawnpoint remove": // Remove SpawnPoint from Telehub m_Telehub.RemoveSpawnPoint((int)param1); break; default: break; } if (client != null) SendTelehubInfo(client); } private void SendSimulatorBlueBoxMessage( IClientAPI remote_client, UUID invoice, UUID senderID, UUID sessionID, string senderName, string message) { IDialogModule dm = Scene.RequestModuleInterface<IDialogModule>(); if (dm != null) dm.SendNotificationToUsersInRegion(senderID, senderName, message); } private void SendEstateBlueBoxMessage( IClientAPI remote_client, UUID invoice, UUID senderID, UUID sessionID, string senderName, string message) { TriggerEstateMessage(senderID, senderName, message); } private void handleEstateDebugRegionRequest( IClientAPI remote_client, UUID invoice, UUID senderID, bool disableScripts, bool disableCollisions, bool disablePhysics) { Scene.RegionInfo.RegionSettings.DisablePhysics = disablePhysics; Scene.RegionInfo.RegionSettings.DisableScripts = disableScripts; Scene.RegionInfo.RegionSettings.DisableCollisions = disableCollisions; Scene.RegionInfo.RegionSettings.Save(); TriggerRegionInfoChange(); ISceneCommandsModule scm = Scene.RequestModuleInterface<ISceneCommandsModule>(); if (scm != null) { scm.SetSceneDebugOptions( new Dictionary<string, string>() { { "scripting", (!disableScripts).ToString() }, { "collisions", (!disableCollisions).ToString() }, { "physics", (!disablePhysics).ToString() } } ); } } private void handleEstateTeleportOneUserHomeRequest(IClientAPI remover_client, UUID invoice, UUID senderID, UUID prey) { EstateTeleportOneUserHomeRequest evOverride = OnEstateTeleportOneUserHomeRequest; if(evOverride != null) { evOverride(remover_client, invoice, senderID, prey); return; } if (!Scene.Permissions.CanIssueEstateCommand(remover_client.AgentId, false)) return; if (prey != UUID.Zero) { ScenePresence s = Scene.GetScenePresence(prey); if (s != null && !s.IsDeleted && !s.IsInTransit) { if (!Scene.TeleportClientHome(prey, s.ControllingClient)) { s.ControllingClient.Kick("You were teleported home by the region owner, but the TP failed - you have been logged out."); Scene.CloseAgent(s.UUID, false); } } } } private void handleEstateTeleportAllUsersHomeRequest(IClientAPI remover_client, UUID invoice, UUID senderID) { EstateTeleportAllUsersHomeRequest evOverride = OnEstateTeleportAllUsersHomeRequest; if(evOverride != null) { evOverride(remover_client, invoice, senderID); return; } if (!Scene.Permissions.CanIssueEstateCommand(remover_client.AgentId, false)) return; Scene.ForEachRootClient(delegate(IClientAPI client) { if (client.AgentId != senderID) { // make sure they are still there, we could be working down a long list // Also make sure they are actually in the region ScenePresence p; if(Scene.TryGetScenePresence(client.AgentId, out p)) { if (!Scene.TeleportClientHome(p.UUID, p.ControllingClient)) { p.ControllingClient.Kick("You were teleported home by the region owner, but the TP failed - you have been logged out."); Scene.CloseAgent(p.UUID, false); } } } }); } private void AbortTerrainXferHandler(IClientAPI remoteClient, ulong XferID) { lock (this) { if ((TerrainUploader != null) && (XferID == TerrainUploader.XferID)) { remoteClient.OnXferReceive -= TerrainUploader.XferReceive; remoteClient.OnAbortXfer -= AbortTerrainXferHandler; TerrainUploader.TerrainUploadDone -= HandleTerrainApplication; TerrainUploader = null; remoteClient.SendAlertMessage("Terrain Upload aborted by the client"); } } } private void HandleTerrainApplication(string filename, byte[] terrainData, IClientAPI remoteClient) { lock (this) { remoteClient.OnXferReceive -= TerrainUploader.XferReceive; remoteClient.OnAbortXfer -= AbortTerrainXferHandler; TerrainUploader.TerrainUploadDone -= HandleTerrainApplication; TerrainUploader = null; } m_log.DebugFormat("[CLIENT]: Terrain upload from {0} to {1} complete.", remoteClient.Name, Scene.Name); remoteClient.SendAlertMessage("Terrain Upload Complete. Loading...."); ITerrainModule terr = Scene.RequestModuleInterface<ITerrainModule>(); if (terr != null) { try { using (MemoryStream terrainStream = new MemoryStream(terrainData)) terr.LoadFromStream(filename, terrainStream); FileInfo x = new FileInfo(filename); remoteClient.SendAlertMessage("Your terrain was loaded as a " + x.Extension + " file. It may take a few moments to appear."); } catch (IOException e) { m_log.ErrorFormat("[TERRAIN]: Error Saving a terrain file uploaded via the estate tools. It gave us the following error: {0}", e.ToString()); remoteClient.SendAlertMessage("There was an IO Exception loading your terrain. Please check free space."); return; } catch (SecurityException e) { m_log.ErrorFormat("[TERRAIN]: Error Saving a terrain file uploaded via the estate tools. It gave us the following error: {0}", e.ToString()); remoteClient.SendAlertMessage("There was a security Exception loading your terrain. Please check the security on the simulator drive"); return; } catch (UnauthorizedAccessException e) { m_log.ErrorFormat("[TERRAIN]: Error Saving a terrain file uploaded via the estate tools. It gave us the following error: {0}", e.ToString()); remoteClient.SendAlertMessage("There was a security Exception loading your terrain. Please check the security on the simulator drive"); return; } catch (Exception e) { m_log.ErrorFormat("[TERRAIN]: Error loading a terrain file uploaded via the estate tools. It gave us the following error: {0}", e.ToString()); remoteClient.SendAlertMessage("There was a general error loading your terrain. Please fix the terrain file and try again"); } } else { remoteClient.SendAlertMessage("Unable to apply terrain. Cannot get an instance of the terrain module"); } } private void handleUploadTerrain(IClientAPI remote_client, string clientFileName) { lock (this) { if (TerrainUploader == null) { m_log.DebugFormat( "[TERRAIN]: Started receiving terrain upload for region {0} from {1}", Scene.Name, remote_client.Name); TerrainUploader = new EstateTerrainXferHandler(remote_client, clientFileName); remote_client.OnXferReceive += TerrainUploader.XferReceive; remote_client.OnAbortXfer += AbortTerrainXferHandler; TerrainUploader.TerrainUploadDone += HandleTerrainApplication; TerrainUploader.RequestStartXfer(remote_client); } else { remote_client.SendAlertMessage("Another Terrain Upload is in progress. Please wait your turn!"); } } } private void handleTerrainRequest(IClientAPI remote_client, string clientFileName) { // Save terrain here ITerrainModule terr = Scene.RequestModuleInterface<ITerrainModule>(); if (terr != null) { // m_log.Warn("[CLIENT]: Got Request to Send Terrain in region " + Scene.RegionInfo.RegionName); if (File.Exists(Util.dataDir() + "/terrain.raw")) { File.Delete(Util.dataDir() + "/terrain.raw"); } terr.SaveToFile(Util.dataDir() + "/terrain.raw"); byte[] bdata; using(FileStream input = new FileStream(Util.dataDir() + "/terrain.raw",FileMode.Open)) { bdata = new byte[input.Length]; input.Read(bdata, 0, (int)input.Length); } if(bdata == null || bdata.Length == 0) { remote_client.SendAlertMessage("Terrain error"); return; } remote_client.SendAlertMessage("Terrain file written, starting download..."); string xfername = (UUID.Random()).ToString(); Scene.XferManager.AddNewFile(xfername, bdata); m_log.DebugFormat("[CLIENT]: Sending terrain for region {0} to {1}", Scene.Name, remote_client.Name); remote_client.SendInitiateDownload(xfername, clientFileName); } } private void HandleRegionInfoRequest(IClientAPI remote_client) { RegionInfoForEstateMenuArgs args = new RegionInfoForEstateMenuArgs(); args.billableFactor = Scene.RegionInfo.EstateSettings.BillableFactor; args.estateID = Scene.RegionInfo.EstateSettings.EstateID; args.maxAgents = (byte)Scene.RegionInfo.RegionSettings.AgentLimit; args.objectBonusFactor = (float)Scene.RegionInfo.RegionSettings.ObjectBonus; args.parentEstateID = Scene.RegionInfo.EstateSettings.ParentEstateID; args.pricePerMeter = Scene.RegionInfo.EstateSettings.PricePerMeter; args.redirectGridX = Scene.RegionInfo.EstateSettings.RedirectGridX; args.redirectGridY = Scene.RegionInfo.EstateSettings.RedirectGridY; args.regionFlags = GetRegionFlags(); args.simAccess = Scene.RegionInfo.AccessLevel; args.sunHour = (float)Scene.RegionInfo.RegionSettings.SunPosition; args.terrainLowerLimit = (float)Scene.RegionInfo.RegionSettings.TerrainLowerLimit; args.terrainRaiseLimit = (float)Scene.RegionInfo.RegionSettings.TerrainRaiseLimit; args.useEstateSun = Scene.RegionInfo.RegionSettings.UseEstateSun; args.waterHeight = (float)Scene.RegionInfo.RegionSettings.WaterHeight; args.simName = Scene.RegionInfo.RegionName; args.regionType = Scene.RegionInfo.RegionType; remote_client.SendRegionInfoToEstateMenu(args); } private void HandleEstateCovenantRequest(IClientAPI remote_client) { remote_client.SendEstateCovenantInformation(Scene.RegionInfo.RegionSettings.Covenant); } private void HandleLandStatRequest(int parcelID, uint reportType, uint requestFlags, string filter, IClientAPI remoteClient) { if (!Scene.Permissions.CanIssueEstateCommand(remoteClient.AgentId, false)) return; Dictionary<uint, float> sceneData = null; if (reportType == 1) { sceneData = Scene.PhysicsScene.GetTopColliders(); } else if (reportType == 0) { IScriptModule scriptModule = Scene.RequestModuleInterface<IScriptModule>(); if (scriptModule != null) sceneData = scriptModule.GetObjectScriptsExecutionTimes(); } List<LandStatReportItem> SceneReport = new List<LandStatReportItem>(); if (sceneData != null) { var sortedSceneData = sceneData.Select( item => new { Measurement = item.Value, Part = Scene.GetSceneObjectPart(item.Key) }); sortedSceneData.OrderBy(item => item.Measurement); int items = 0; foreach (var entry in sortedSceneData) { // The object may have been deleted since we received the data. if (entry.Part == null) continue; // Don't show scripts that haven't executed or where execution time is below one microsecond in // order to produce a more readable report. if (entry.Measurement < 0.001) continue; items++; SceneObjectGroup so = entry.Part.ParentGroup; LandStatReportItem lsri = new LandStatReportItem(); lsri.LocationX = so.AbsolutePosition.X; lsri.LocationY = so.AbsolutePosition.Y; lsri.LocationZ = so.AbsolutePosition.Z; lsri.Score = entry.Measurement; lsri.TaskID = so.UUID; lsri.TaskLocalID = so.LocalId; lsri.TaskName = entry.Part.Name; lsri.OwnerName = UserManager.GetUserName(so.OwnerID); if (filter.Length != 0) { if ((lsri.OwnerName.Contains(filter) || lsri.TaskName.Contains(filter))) { } else { continue; } } SceneReport.Add(lsri); if (items >= 100) break; } } remoteClient.SendLandStatReply(reportType, requestFlags, (uint)SceneReport.Count,SceneReport.ToArray()); } #endregion #region Outgoing Packets public void sendRegionInfoPacketToAll() { // Scene.ForEachRootClient(delegate(IClientAPI client) Scene.ForEachClient(delegate(IClientAPI client) { HandleRegionInfoRequest(client); }); } public void sendRegionHandshake(IClientAPI remoteClient) { RegionHandshakeArgs args = new RegionHandshakeArgs(); args.isEstateManager = Scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(remoteClient.AgentId); if (Scene.RegionInfo.EstateSettings.EstateOwner != UUID.Zero && Scene.RegionInfo.EstateSettings.EstateOwner == remoteClient.AgentId) args.isEstateManager = true; args.billableFactor = Scene.RegionInfo.EstateSettings.BillableFactor; args.terrainStartHeight0 = (float)Scene.RegionInfo.RegionSettings.Elevation1SW; args.terrainHeightRange0 = (float)Scene.RegionInfo.RegionSettings.Elevation2SW; args.terrainStartHeight1 = (float)Scene.RegionInfo.RegionSettings.Elevation1NW; args.terrainHeightRange1 = (float)Scene.RegionInfo.RegionSettings.Elevation2NW; args.terrainStartHeight2 = (float)Scene.RegionInfo.RegionSettings.Elevation1SE; args.terrainHeightRange2 = (float)Scene.RegionInfo.RegionSettings.Elevation2SE; args.terrainStartHeight3 = (float)Scene.RegionInfo.RegionSettings.Elevation1NE; args.terrainHeightRange3 = (float)Scene.RegionInfo.RegionSettings.Elevation2NE; args.simAccess = Scene.RegionInfo.AccessLevel; args.waterHeight = (float)Scene.RegionInfo.RegionSettings.WaterHeight; args.regionFlags = GetRegionFlags(); args.regionName = Scene.RegionInfo.RegionName; args.SimOwner = Scene.RegionInfo.EstateSettings.EstateOwner; args.terrainBase0 = UUID.Zero; args.terrainBase1 = UUID.Zero; args.terrainBase2 = UUID.Zero; args.terrainBase3 = UUID.Zero; args.terrainDetail0 = Scene.RegionInfo.RegionSettings.TerrainTexture1; args.terrainDetail1 = Scene.RegionInfo.RegionSettings.TerrainTexture2; args.terrainDetail2 = Scene.RegionInfo.RegionSettings.TerrainTexture3; args.terrainDetail3 = Scene.RegionInfo.RegionSettings.TerrainTexture4; // m_log.DebugFormat("[ESTATE MANAGEMENT MODULE]: Sending terrain texture 1 {0} for region {1}", args.terrainDetail0, Scene.RegionInfo.RegionName); // m_log.DebugFormat("[ESTATE MANAGEMENT MODULE]: Sending terrain texture 2 {0} for region {1}", args.terrainDetail1, Scene.RegionInfo.RegionName); // m_log.DebugFormat("[ESTATE MANAGEMENT MODULE]: Sending terrain texture 3 {0} for region {1}", args.terrainDetail2, Scene.RegionInfo.RegionName); // m_log.DebugFormat("[ESTATE MANAGEMENT MODULE]: Sending terrain texture 4 {0} for region {1}", args.terrainDetail3, Scene.RegionInfo.RegionName); remoteClient.SendRegionHandshake(Scene.RegionInfo,args); } public void handleEstateChangeInfo(IClientAPI remoteClient, UUID invoice, UUID senderID, UInt32 parms1, UInt32 parms2) { if (parms2 == 0) { Scene.RegionInfo.EstateSettings.UseGlobalTime = true; Scene.RegionInfo.EstateSettings.SunPosition = 0.0; } else { Scene.RegionInfo.EstateSettings.UseGlobalTime = false; Scene.RegionInfo.EstateSettings.SunPosition = (parms2 - 0x1800)/1024.0; // Warning: FixedSun should be set to True, otherwise this sun position won't be used. } if ((parms1 & 0x00008000) != 0) Scene.RegionInfo.EstateSettings.PublicAccess = true; else Scene.RegionInfo.EstateSettings.PublicAccess = false; if ((parms1 & 0x00000010) != 0) Scene.RegionInfo.EstateSettings.FixedSun = true; else Scene.RegionInfo.EstateSettings.FixedSun = false; // taxfree is now AllowAccessOverride if ((parms1 & 0x00000020) != 0) Scene.RegionInfo.EstateSettings.TaxFree = true; else Scene.RegionInfo.EstateSettings.TaxFree = false; if ((parms1 & 0x00100000) != 0) Scene.RegionInfo.EstateSettings.AllowDirectTeleport = true; else Scene.RegionInfo.EstateSettings.AllowDirectTeleport = false; if ((parms1 & 0x00800000) != 0) Scene.RegionInfo.EstateSettings.DenyAnonymous = true; else Scene.RegionInfo.EstateSettings.DenyAnonymous = false; // no longer in used, may be reassigned if ((parms1 & 0x01000000) != 0) Scene.RegionInfo.EstateSettings.DenyIdentified = true; else Scene.RegionInfo.EstateSettings.DenyIdentified = false; // no longer in used, may be reassigned if ((parms1 & 0x02000000) != 0) Scene.RegionInfo.EstateSettings.DenyTransacted = true; else Scene.RegionInfo.EstateSettings.DenyTransacted = false; if ((parms1 & 0x10000000) != 0) Scene.RegionInfo.EstateSettings.AllowVoice = true; else Scene.RegionInfo.EstateSettings.AllowVoice = false; if ((parms1 & 0x40000000) != 0) Scene.RegionInfo.EstateSettings.DenyMinors = true; else Scene.RegionInfo.EstateSettings.DenyMinors = false; Scene.EstateDataService.StoreEstateSettings(Scene.RegionInfo.EstateSettings); TriggerEstateInfoChange(); Scene.TriggerEstateSunUpdate(); sendDetailedEstateData(remoteClient, invoice); } #endregion #region Other Functions public void changeWaterHeight(float height) { setRegionTerrainSettings(height, (float)Scene.RegionInfo.RegionSettings.TerrainRaiseLimit, (float)Scene.RegionInfo.RegionSettings.TerrainLowerLimit, Scene.RegionInfo.RegionSettings.UseEstateSun, Scene.RegionInfo.RegionSettings.FixedSun, (float)Scene.RegionInfo.RegionSettings.SunPosition, Scene.RegionInfo.EstateSettings.UseGlobalTime, Scene.RegionInfo.EstateSettings.FixedSun, (float)Scene.RegionInfo.EstateSettings.SunPosition); // sendRegionInfoPacketToAll(); already done by setRegionTerrainSettings } #endregion private void EventManager_OnNewClient(IClientAPI client) { client.OnDetailedEstateDataRequest += clientSendDetailedEstateData; client.OnSetEstateFlagsRequest += estateSetRegionInfoHandler; // client.OnSetEstateTerrainBaseTexture += setEstateTerrainBaseTexture; client.OnSetEstateTerrainDetailTexture += setEstateTerrainBaseTexture; client.OnSetEstateTerrainTextureHeights += setEstateTerrainTextureHeights; client.OnCommitEstateTerrainTextureRequest += handleCommitEstateTerrainTextureRequest; client.OnSetRegionTerrainSettings += setRegionTerrainSettings; client.OnEstateRestartSimRequest += handleEstateRestartSimRequest; client.OnEstateChangeCovenantRequest += handleChangeEstateCovenantRequest; client.OnEstateChangeInfo += handleEstateChangeInfo; client.OnEstateManageTelehub += HandleOnEstateManageTelehub; client.OnUpdateEstateAccessDeltaRequest += handleEstateAccessDeltaRequest; client.OnSimulatorBlueBoxMessageRequest += SendSimulatorBlueBoxMessage; client.OnEstateBlueBoxMessageRequest += SendEstateBlueBoxMessage; client.OnEstateDebugRegionRequest += handleEstateDebugRegionRequest; client.OnEstateTeleportOneUserHomeRequest += handleEstateTeleportOneUserHomeRequest; client.OnEstateTeleportAllUsersHomeRequest += handleEstateTeleportAllUsersHomeRequest; client.OnRequestTerrain += handleTerrainRequest; client.OnUploadTerrain += handleUploadTerrain; client.OnRegionInfoRequest += HandleRegionInfoRequest; client.OnEstateCovenantRequest += HandleEstateCovenantRequest; client.OnLandStatRequest += HandleLandStatRequest; sendRegionHandshake(client); } public uint GetEstateFlags() { RegionFlags flags = RegionFlags.None; if (Scene.RegionInfo.EstateSettings.FixedSun) flags |= RegionFlags.SunFixed; if (Scene.RegionInfo.EstateSettings.PublicAccess) flags |= (RegionFlags.PublicAllowed | RegionFlags.ExternallyVisible); if (Scene.RegionInfo.EstateSettings.AllowVoice) flags |= RegionFlags.AllowVoice; if (Scene.RegionInfo.EstateSettings.AllowDirectTeleport) flags |= RegionFlags.AllowDirectTeleport; if (Scene.RegionInfo.EstateSettings.DenyAnonymous) flags |= RegionFlags.DenyAnonymous; if (Scene.RegionInfo.EstateSettings.DenyIdentified) flags |= RegionFlags.DenyIdentified; if (Scene.RegionInfo.EstateSettings.DenyTransacted) flags |= RegionFlags.DenyTransacted; if (Scene.RegionInfo.EstateSettings.AbuseEmailToEstateOwner) flags |= RegionFlags.AbuseEmailToEstateOwner; if (Scene.RegionInfo.EstateSettings.BlockDwell) flags |= RegionFlags.BlockDwell; if (Scene.RegionInfo.EstateSettings.EstateSkipScripts) flags |= RegionFlags.EstateSkipScripts; if (Scene.RegionInfo.EstateSettings.ResetHomeOnTeleport) flags |= RegionFlags.ResetHomeOnTeleport; if (Scene.RegionInfo.EstateSettings.TaxFree) flags |= RegionFlags.TaxFree; if (Scene.RegionInfo.EstateSettings.AllowLandmark) flags |= RegionFlags.AllowLandmark; if (Scene.RegionInfo.EstateSettings.AllowParcelChanges) flags |= RegionFlags.AllowParcelChanges; if (Scene.RegionInfo.EstateSettings.AllowSetHome) flags |= RegionFlags.AllowSetHome; if (Scene.RegionInfo.EstateSettings.DenyMinors) flags |= (RegionFlags)(1 << 30); return (uint)flags; } public void TriggerEstateMessage(UUID fromID, string fromName, string message) { MessageDelegate onmessage = OnEstateMessage; if (onmessage != null) onmessage(Scene.RegionInfo.RegionID, fromID, fromName, message); } private void SendTelehubInfo(IClientAPI client) { RegionSettings settings = this.Scene.RegionInfo.RegionSettings; SceneObjectGroup telehub = null; if (settings.TelehubObject != UUID.Zero && (telehub = Scene.GetSceneObjectGroup(settings.TelehubObject)) != null) { List<Vector3> spawnPoints = new List<Vector3>(); foreach (SpawnPoint sp in settings.SpawnPoints()) { spawnPoints.Add(sp.GetLocation(Vector3.Zero, Quaternion.Identity)); } client.SendTelehubInfo(settings.TelehubObject, telehub.Name, telehub.AbsolutePosition, telehub.GroupRotation, spawnPoints); } else { client.SendTelehubInfo(UUID.Zero, String.Empty, Vector3.Zero, Quaternion.Identity, new List<Vector3>()); } } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact [email protected]. /// /// DeploymentResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.Preview.DeployedDevices.Fleet { public class DeploymentResource : Resource { private static Request BuildFetchRequest(FetchDeploymentOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Preview, "/DeployedDevices/Fleets/" + options.PathFleetSid + "/Deployments/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Fetch information about a specific Deployment in the Fleet. /// </summary> /// <param name="options"> Fetch Deployment parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Deployment </returns> public static DeploymentResource Fetch(FetchDeploymentOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Fetch information about a specific Deployment in the Fleet. /// </summary> /// <param name="options"> Fetch Deployment parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Deployment </returns> public static async System.Threading.Tasks.Task<DeploymentResource> FetchAsync(FetchDeploymentOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Fetch information about a specific Deployment in the Fleet. /// </summary> /// <param name="pathFleetSid"> The fleet_sid </param> /// <param name="pathSid"> A string that uniquely identifies the Deployment. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Deployment </returns> public static DeploymentResource Fetch(string pathFleetSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchDeploymentOptions(pathFleetSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// Fetch information about a specific Deployment in the Fleet. /// </summary> /// <param name="pathFleetSid"> The fleet_sid </param> /// <param name="pathSid"> A string that uniquely identifies the Deployment. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Deployment </returns> public static async System.Threading.Tasks.Task<DeploymentResource> FetchAsync(string pathFleetSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchDeploymentOptions(pathFleetSid, pathSid); return await FetchAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteDeploymentOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Preview, "/DeployedDevices/Fleets/" + options.PathFleetSid + "/Deployments/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Delete a specific Deployment from the Fleet, leaving associated devices effectively undeployed. /// </summary> /// <param name="options"> Delete Deployment parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Deployment </returns> public static bool Delete(DeleteDeploymentOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// Delete a specific Deployment from the Fleet, leaving associated devices effectively undeployed. /// </summary> /// <param name="options"> Delete Deployment parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Deployment </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteDeploymentOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// Delete a specific Deployment from the Fleet, leaving associated devices effectively undeployed. /// </summary> /// <param name="pathFleetSid"> The fleet_sid </param> /// <param name="pathSid"> A string that uniquely identifies the Deployment. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Deployment </returns> public static bool Delete(string pathFleetSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteDeploymentOptions(pathFleetSid, pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// Delete a specific Deployment from the Fleet, leaving associated devices effectively undeployed. /// </summary> /// <param name="pathFleetSid"> The fleet_sid </param> /// <param name="pathSid"> A string that uniquely identifies the Deployment. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Deployment </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathFleetSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteDeploymentOptions(pathFleetSid, pathSid); return await DeleteAsync(options, client); } #endif private static Request BuildCreateRequest(CreateDeploymentOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Preview, "/DeployedDevices/Fleets/" + options.PathFleetSid + "/Deployments", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// Create a new Deployment in the Fleet, optionally giving it a friendly name and linking to a specific Twilio Sync /// service instance. /// </summary> /// <param name="options"> Create Deployment parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Deployment </returns> public static DeploymentResource Create(CreateDeploymentOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Create a new Deployment in the Fleet, optionally giving it a friendly name and linking to a specific Twilio Sync /// service instance. /// </summary> /// <param name="options"> Create Deployment parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Deployment </returns> public static async System.Threading.Tasks.Task<DeploymentResource> CreateAsync(CreateDeploymentOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Create a new Deployment in the Fleet, optionally giving it a friendly name and linking to a specific Twilio Sync /// service instance. /// </summary> /// <param name="pathFleetSid"> The fleet_sid </param> /// <param name="friendlyName"> A human readable description for this Deployment. </param> /// <param name="syncServiceSid"> The unique identifier of the Sync service instance. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Deployment </returns> public static DeploymentResource Create(string pathFleetSid, string friendlyName = null, string syncServiceSid = null, ITwilioRestClient client = null) { var options = new CreateDeploymentOptions(pathFleetSid){FriendlyName = friendlyName, SyncServiceSid = syncServiceSid}; return Create(options, client); } #if !NET35 /// <summary> /// Create a new Deployment in the Fleet, optionally giving it a friendly name and linking to a specific Twilio Sync /// service instance. /// </summary> /// <param name="pathFleetSid"> The fleet_sid </param> /// <param name="friendlyName"> A human readable description for this Deployment. </param> /// <param name="syncServiceSid"> The unique identifier of the Sync service instance. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Deployment </returns> public static async System.Threading.Tasks.Task<DeploymentResource> CreateAsync(string pathFleetSid, string friendlyName = null, string syncServiceSid = null, ITwilioRestClient client = null) { var options = new CreateDeploymentOptions(pathFleetSid){FriendlyName = friendlyName, SyncServiceSid = syncServiceSid}; return await CreateAsync(options, client); } #endif private static Request BuildReadRequest(ReadDeploymentOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Preview, "/DeployedDevices/Fleets/" + options.PathFleetSid + "/Deployments", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Retrieve a list of all Deployments belonging to the Fleet. /// </summary> /// <param name="options"> Read Deployment parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Deployment </returns> public static ResourceSet<DeploymentResource> Read(ReadDeploymentOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<DeploymentResource>.FromJson("deployments", response.Content); return new ResourceSet<DeploymentResource>(page, options, client); } #if !NET35 /// <summary> /// Retrieve a list of all Deployments belonging to the Fleet. /// </summary> /// <param name="options"> Read Deployment parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Deployment </returns> public static async System.Threading.Tasks.Task<ResourceSet<DeploymentResource>> ReadAsync(ReadDeploymentOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<DeploymentResource>.FromJson("deployments", response.Content); return new ResourceSet<DeploymentResource>(page, options, client); } #endif /// <summary> /// Retrieve a list of all Deployments belonging to the Fleet. /// </summary> /// <param name="pathFleetSid"> The fleet_sid </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Deployment </returns> public static ResourceSet<DeploymentResource> Read(string pathFleetSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadDeploymentOptions(pathFleetSid){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// Retrieve a list of all Deployments belonging to the Fleet. /// </summary> /// <param name="pathFleetSid"> The fleet_sid </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Deployment </returns> public static async System.Threading.Tasks.Task<ResourceSet<DeploymentResource>> ReadAsync(string pathFleetSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadDeploymentOptions(pathFleetSid){PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<DeploymentResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<DeploymentResource>.FromJson("deployments", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<DeploymentResource> NextPage(Page<DeploymentResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Preview) ); var response = client.Request(request); return Page<DeploymentResource>.FromJson("deployments", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<DeploymentResource> PreviousPage(Page<DeploymentResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Preview) ); var response = client.Request(request); return Page<DeploymentResource>.FromJson("deployments", response.Content); } private static Request BuildUpdateRequest(UpdateDeploymentOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Preview, "/DeployedDevices/Fleets/" + options.PathFleetSid + "/Deployments/" + options.PathSid + "", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// Update the given properties of a specific Deployment credential in the Fleet, giving it a friendly name or linking /// to a specific Twilio Sync service instance. /// </summary> /// <param name="options"> Update Deployment parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Deployment </returns> public static DeploymentResource Update(UpdateDeploymentOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Update the given properties of a specific Deployment credential in the Fleet, giving it a friendly name or linking /// to a specific Twilio Sync service instance. /// </summary> /// <param name="options"> Update Deployment parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Deployment </returns> public static async System.Threading.Tasks.Task<DeploymentResource> UpdateAsync(UpdateDeploymentOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Update the given properties of a specific Deployment credential in the Fleet, giving it a friendly name or linking /// to a specific Twilio Sync service instance. /// </summary> /// <param name="pathFleetSid"> The fleet_sid </param> /// <param name="pathSid"> A string that uniquely identifies the Deployment. </param> /// <param name="friendlyName"> A human readable description for this Deployment. </param> /// <param name="syncServiceSid"> The unique identifier of the Sync service instance. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Deployment </returns> public static DeploymentResource Update(string pathFleetSid, string pathSid, string friendlyName = null, string syncServiceSid = null, ITwilioRestClient client = null) { var options = new UpdateDeploymentOptions(pathFleetSid, pathSid){FriendlyName = friendlyName, SyncServiceSid = syncServiceSid}; return Update(options, client); } #if !NET35 /// <summary> /// Update the given properties of a specific Deployment credential in the Fleet, giving it a friendly name or linking /// to a specific Twilio Sync service instance. /// </summary> /// <param name="pathFleetSid"> The fleet_sid </param> /// <param name="pathSid"> A string that uniquely identifies the Deployment. </param> /// <param name="friendlyName"> A human readable description for this Deployment. </param> /// <param name="syncServiceSid"> The unique identifier of the Sync service instance. </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Deployment </returns> public static async System.Threading.Tasks.Task<DeploymentResource> UpdateAsync(string pathFleetSid, string pathSid, string friendlyName = null, string syncServiceSid = null, ITwilioRestClient client = null) { var options = new UpdateDeploymentOptions(pathFleetSid, pathSid){FriendlyName = friendlyName, SyncServiceSid = syncServiceSid}; return await UpdateAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a DeploymentResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> DeploymentResource object represented by the provided JSON </returns> public static DeploymentResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<DeploymentResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// A string that uniquely identifies this Deployment. /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// URL of this Deployment. /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// A human readable description for this Deployment /// </summary> [JsonProperty("friendly_name")] public string FriendlyName { get; private set; } /// <summary> /// The unique identifier of the Fleet. /// </summary> [JsonProperty("fleet_sid")] public string FleetSid { get; private set; } /// <summary> /// The unique SID that identifies this Account. /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The unique identifier of the Sync service instance. /// </summary> [JsonProperty("sync_service_sid")] public string SyncServiceSid { get; private set; } /// <summary> /// The date this Deployment was created. /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The date this Deployment was updated. /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } private DeploymentResource() { } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation 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 (c) Microsoft Corporation. All rights reserved. This code is licensed under the Visual Studio SDK license terms. THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. ***************************************************************************/ using System; using System.Collections.Generic; using System.Reflection; using System.Diagnostics; using IronPython.Compiler.Ast; using IronPython.Runtime; namespace Microsoft.Samples.VisualStudio.IronPythonInference { public abstract class Inferred { public abstract bool IsInstance { get; } public abstract bool IsType { get; } public abstract bool IsCallable { get; } public abstract bool IsBound { get; } public abstract IEnumerable<SymbolId> Names { get; } public abstract IList<Inferred> InferName(SymbolId name, Engine engine); public abstract IList<FunctionInfo> InferMethods(SymbolId name); public abstract IList<Inferred> InferResult(Engine engine); } public class InferredClass : Inferred { private ClassScope cs; public InferredClass(ClassScope cs) { this.cs = cs; } public override bool IsInstance { get { return false; } } public override bool IsType { get { return true; } } public override bool IsCallable { get { return true; } } public override bool IsBound { get { return false; } } public override IEnumerable<SymbolId> Names { get { return cs.GetNamesCurrent(); } } public override IList<Inferred> InferName(SymbolId name, Engine engine) { return cs.ResolveCurrent(name, engine); } public override IList<FunctionInfo> InferMethods(SymbolId name) { return Engine.InferMethods(cs.Module, SymbolTable.Init, cs); } public override IList<Inferred> InferResult(Engine engine) { return Engine.MakeList<Inferred>(new InferredInstance(this)); } public void Define(SymbolId name, Definition definition) { cs.Define(name, definition); } } public class InferredInstance : Inferred { Inferred type; public InferredInstance(Inferred type) { if (null == type) { throw new ArgumentNullException("type"); } Debug.Assert(!type.IsInstance); this.type = type; } public override bool IsInstance { get { return true; } } public override bool IsType { get { return false; } } public override bool IsCallable { get { return false; } } public override bool IsBound { get { return false; } } public override IEnumerable<SymbolId> Names { get { return type.Names; } } public override IList<Inferred> InferName(SymbolId name, Engine engine) { IList<Inferred> inferred = type.InferName(name, engine); foreach (Inferred inf in inferred) { FunctionInfo fi = inf as FunctionInfo; if (fi != null) { fi.Bind(); } } return inferred; } public override IList<FunctionInfo> InferMethods(SymbolId name) { return type.InferMethods(name); } public override IList<Inferred> InferResult(Engine engine) { return type.InferResult(engine); } } public abstract class ReflectedMember : Inferred { public abstract Inferred Infer(Engine engine); public override bool IsInstance { get { return false; } } public override bool IsType { get { return false; } } public override bool IsCallable { get { return false; } } public override bool IsBound { get { return false; } } public override IEnumerable<SymbolId> Names { get { return null; } } public override IList<Inferred> InferName(SymbolId name, Engine engine) { return null; } public override IList<FunctionInfo> InferMethods(SymbolId name) { return null; } public override IList<Inferred> InferResult(Engine engine) { return null; } } public class ReflectedField : ReflectedMember { private FieldInfo info; public ReflectedField(FieldInfo info) { if (null == info) { throw new ArgumentNullException("info"); } this.info = info; } public override Inferred Infer(Engine engine) { if (null == engine) { throw new ArgumentNullException("engine"); } return engine.InferType(info.FieldType); } } public class ReflectedMethod : ReflectedMember { private MethodInfo info; public ReflectedMethod(MethodInfo info) { this.info = info; } public override bool IsCallable { get { return true; } } public override Inferred Infer(Engine engine) { return this; } public override IList<FunctionInfo> InferMethods(SymbolId name) { return Engine.MakeList<FunctionInfo>(new ReflectedMethodInfo(info)); } public override IList<Inferred> InferResult(Engine engine) { Type type = info.ReturnType; if (type != typeof(void)) { return Engine.MakeList(engine.InferType(info.ReturnType)); } else return null; } } public class ReflectedProperty : ReflectedMember { private PropertyInfo info; public ReflectedProperty(PropertyInfo info) { this.info = info; } public override Inferred Infer(Engine engine) { if (null == engine) { throw new ArgumentNullException("engine"); } return engine.InferType(info.PropertyType); } } public class ReflectedConstructor : ReflectedMember { private ConstructorInfo info; public ReflectedConstructor(ConstructorInfo info) { this.info = info; } public override bool IsCallable { get { return true; } } public override Inferred Infer(Engine engine) { return this; } public override IList<FunctionInfo> InferMethods(SymbolId name) { return Engine.MakeList<FunctionInfo>(new ReflectedConstructorInfo(info)); } public override IList<Inferred> InferResult(Engine engine) { return Engine.MakeList(engine.InferType(info.DeclaringType)); } } public class ReflectedType : Inferred { // Disable "DoNotDeclareVisibleInstanceFields" warning. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051")] // Disable "DoNotNestGenericTypesInMemberSignatures" warning. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1006")] protected Dictionary<SymbolId, List<ReflectedMember>> members; // Disable "DoNotDeclareVisibleInstanceFields" warning. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051")] protected readonly Type type; public ReflectedType(Type type) { this.type = type; } public override bool IsInstance { get { return false; } } public override bool IsType { get { return true; } } public override bool IsCallable { get { return true; } } public override bool IsBound { get { return false; } } public override IEnumerable<SymbolId> Names { get { Initialize(); return members.Keys; } } public override IList<Inferred> InferName(SymbolId name, Engine engine) { Initialize(); List<ReflectedMember> list; IList<Inferred> result = null; if (members.TryGetValue(name, out list)) { foreach (ReflectedMember member in list) { result = Engine.Append<Inferred>(result, member.Infer(engine)); } } return result; } public override IList<FunctionInfo> InferMethods(SymbolId name) { Initialize(); List<ReflectedMember> list; IList<FunctionInfo> result = null; if (members.TryGetValue(name, out list)) { foreach (ReflectedMember member in list) { ReflectedMethod method = member as ReflectedMethod; if (null != method) { result = Engine.Union<FunctionInfo>(result, method.InferMethods(name)); } } } else if (type.Name == name.GetString()) { members.TryGetValue(SymbolTable.StringToId(".ctor"), out list); foreach (ReflectedMember member in list) { ReflectedConstructor constructor = member as ReflectedConstructor; if (constructor != null) { result = Engine.Union<FunctionInfo>(result, constructor.InferMethods(name)); } } } return result; } public override IList<Inferred> InferResult(Engine engine) { return Engine.MakeList<Inferred>(this); } protected virtual void Initialize() { if (members != null) return; MemberInfo[] infos = type.GetMembers(); members = new Dictionary<SymbolId, List<ReflectedMember>>(); foreach (MemberInfo info in infos) { ReflectedMember md = CreateMemberDefinition(info); if (md != null) { List<ReflectedMember> list; SymbolId name = SymbolTable.StringToId(info.Name); if (!members.TryGetValue(name, out list)) { members[name] = list = new List<ReflectedMember>(); } list.Add(md); } } } protected static ReflectedMember CreateMemberDefinition(MemberInfo info) { MethodInfo method; FieldInfo field; PropertyInfo property; ConstructorInfo constructor; ReflectedMember md; if ((method = info as MethodInfo) != null) { md = new ReflectedMethod(method); } else if ((field = info as FieldInfo) != null) { md = new ReflectedField(field); } else if ((property = info as PropertyInfo) != null) { md = new ReflectedProperty(property); } else if ((constructor = info as ConstructorInfo) != null) { md = new ReflectedConstructor(constructor); } else { md = null; } return md; } } public class ReflectedModule : Inferred { // Disable the "AvoidUnusedPrivateFields" warning. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1823")] private string full; private Dictionary<SymbolId, ReflectedType> types; private Dictionary<SymbolId, ReflectedModule> namespaces; public ReflectedModule(string full) { this.full = full; namespaces = new Dictionary<SymbolId, ReflectedModule>(); } public override bool IsInstance { get { return false; } } public override bool IsType { get { return false; } } public override bool IsCallable { get { return false; } } public override bool IsBound { get { return false; } } public override IEnumerable<SymbolId> Names { get { return Engine.Union(new List<SymbolId>(types.Keys), new List<SymbolId>(namespaces.Keys)); } } public override IList<Inferred> InferName(SymbolId name, Engine engine) { IList<Inferred> result = null; ReflectedModule rs; if (namespaces.TryGetValue(name, out rs)) { result = Engine.MakeList<Inferred>(rs); } ReflectedType rt; if (types.TryGetValue(name, out rt)) { result = Engine.Append<Inferred>(result, rt); } return result; } public override IList<FunctionInfo> InferMethods(SymbolId name) { return null; } public override IList<Inferred> InferResult(Engine engine) { return null; } // Disable the "VariableNamesShouldNotMatchFieldNames" warning. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1500", MessageId="full")] public ReflectedModule EnsureNamespace(string full, SymbolId name) { ReflectedModule nested; if (!namespaces.TryGetValue(name, out nested)) { nested = new ReflectedModule(full); namespaces[name] = nested; } return nested; } internal void AddType(string name, ReflectedType rt) { if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name"); } if (null == rt) { throw new ArgumentNullException("rt"); } if (types == null) { types = new Dictionary<SymbolId, ReflectedType>(); } types[SymbolTable.StringToId(name)] = rt; } public void AddType(Type type) { if (null == type) { throw new ArgumentNullException("type"); } AddType(type.Name, new ReflectedType(type)); } public void AddPythonType(string name, Type type) { AddType(name, new InferredPythonType(type)); } public bool TryGetNamespace(string name, out ReflectedModule scope) { return namespaces.TryGetValue(SymbolTable.StringToId(name), out scope); } // Disable the "IdentifiersShouldBeSpelledCorrectly" warning. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704")] public bool TryGetBuiltin(string name, out ReflectedType scope) { return types.TryGetValue(SymbolTable.StringToId(name), out scope); } } public class InferredPythonType : ReflectedType { public InferredPythonType(Type type) : base(type) { } protected override void Initialize() { if (members != null) return; members = new Dictionary<SymbolId, List<ReflectedMember>>(); MemberInfo[] infos = type.GetMembers(); foreach (MemberInfo info in infos) { object[] attrs = info.GetCustomAttributes(typeof(IronPython.Runtime.PythonNameAttribute), false); if (attrs == null || attrs.Length == 0) continue; IronPython.Runtime.PythonNameAttribute attr = attrs[0] as IronPython.Runtime.PythonNameAttribute; ReflectedMember md = CreateMemberDefinition(info); if (md != null) { SymbolId name = SymbolTable.StringToId(attr.name); List<ReflectedMember> list; if (!members.TryGetValue(name, out list)) { members[name] = list = new List<ReflectedMember>(); } list.Add(md); } } } } public abstract class FunctionInfo : Inferred { private bool bound; public abstract string Name { get; } public abstract string Type { get; } public abstract string Description { get; } public abstract int ParameterCount { get; } // Disable the "AvoidOutParameters" warning. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1021")] public abstract void GetParameterInfo(int parameter, out string name, out string display, out string description); public override bool IsInstance { get { return false; } } public override bool IsType { get { return false; } } public override bool IsCallable { get { return true; } } public override bool IsBound { get { return bound; } } public override IEnumerable<SymbolId> Names { get { return null; } } public void Bind() { bound = true; } public override IList<Inferred> InferName(SymbolId name, Engine engine) { return null; } public override IList<FunctionInfo> InferMethods(SymbolId name) { return Engine.MakeList<FunctionInfo>(this); } public override IList<Inferred> InferResult(Engine engine) { return null; } } public class FunctionDefinitionInfo : FunctionInfo { private IronPython.Compiler.Ast.FunctionDefinition function; public FunctionDefinitionInfo(IronPython.Compiler.Ast.FunctionDefinition function) { this.function = function; } public override string Name { get { return function.Name.GetString(); } } public override string Type { get { return string.Empty; } } public override string Description { get { string description = function.Documentation; return (description != null && description.Length > 0) ? description : "Function " + Name; } } public override int ParameterCount { get { int count = function.Parameters.Count; if (count > 0 && IsBound) { count--; } return count; } } public override void GetParameterInfo(int parameter, out string name, out string display, out string description) { if (IsBound && (parameter<int.MaxValue)) parameter++; Expression parm = function.Parameters[parameter]; NameExpression nameExpression = parm as NameExpression; if (null != nameExpression) { name = nameExpression.Name.GetString(); display = name; description = name; } else { name = display = description = String.Empty; } } } public class ReflectedMethodInfo : FunctionInfo { private System.Reflection.MethodInfo method; private System.Reflection.ParameterInfo[] parameters; public ReflectedMethodInfo(MethodInfo method) { this.method = method; } public override string Name { get { return method.Name; } } public override string Type { get { return method.ReturnType.Name; } } public override string Description { get { return method.Name; } } public override int ParameterCount { get { EnsureParameters(); return parameters.Length; } } public override void GetParameterInfo(int parameter, out string name, out string display, out string description) { EnsureParameters(); System.Reflection.ParameterInfo param = parameters[parameter]; name = param.Name; display = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0} {1}", param.ParameterType.Name, param.Name); description = param.Name; } private void EnsureParameters() { if (parameters == null) { parameters = method.GetParameters(); } } } public class ReflectedConstructorInfo : FunctionInfo { private System.Reflection.ConstructorInfo constructor; private System.Reflection.ParameterInfo[] parameters; public ReflectedConstructorInfo(ConstructorInfo constructor) { this.constructor = constructor; } public override string Name { get { return constructor.DeclaringType.Name; } } public override string Description { get { return Name; } } public override string Type { get { return constructor.DeclaringType.Name; } } public override int ParameterCount { get { EnsureParameters(); return parameters.Length; } } public override void GetParameterInfo(int parameter, out string name, out string display, out string description) { EnsureParameters(); System.Reflection.ParameterInfo param = parameters[parameter]; name = param.Name; display = string.Format(System.Globalization.CultureInfo.InstalledUICulture, "{0} {1}", param.ParameterType.Name, param.Name); description = param.Name; } private void EnsureParameters() { if (parameters == null) { parameters = constructor.GetParameters(); } } } public class InferredModule : Inferred { private ModuleScope module; public InferredModule(ModuleScope module) { this.module = module; } public override bool IsInstance { get { return false; } } public override bool IsType { get { return false; } } public override bool IsCallable { get { return false; } } public override bool IsBound { get { return false; } } public override IEnumerable<SymbolId> Names { get { return module.GetNamesCurrent(); } } public override IList<Inferred> InferName(SymbolId name, Engine engine) { return module.ResolveCurrent(name, engine); } public override IList<FunctionInfo> InferMethods(SymbolId name) { return null; } public override IList<Inferred> InferResult(Engine engine) { return null; } } }
using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Windows.Forms; using SDRSharp.Radio; namespace SDRSharp.PanView { public class SpectrumAnalyzer : UserControl { private const float TrackingFontSize = 16.0f; private const int AxisMargin = 30; private const int CarrierPenWidth = 1; private const int GradientAlpha = 180; public const float DefaultCursorHeight = 32.0f; private readonly static Color _spectrumColor = Utils.GetColorSetting("spectrumAnalyzerColor", Color.DarkGray); private readonly static bool _fillSpectrumAnalyzer = Utils.GetBooleanSetting("fillSpectrumAnalyzer"); private double _attack; private double _decay; private bool _performNeeded; private bool _drawBackgroundNeeded; private byte[] _maxSpectrum; private byte[] _spectrum; private bool[] _peaks; private byte[] _temp; private byte[] _scaledPowerSpectrum; private Bitmap _bkgBuffer; private Bitmap _buffer; private Graphics _graphics; private long _spectrumWidth; private long _centerFrequency; private long _displayCenterFrequency; private Point[] _points; private BandType _bandType; private int _filterBandwidth; private int _filterOffset; private int _stepSize = 1000; private float _xIncrement; private long _frequency; private float _lower; private float _upper; private int _zoom; private float _scale = 1f; private int _oldX; private int _trackingX; private int _trackingY; private long _trackingFrequency; private int _oldFilterBandwidth; private long _oldFrequency; private long _oldCenterFrequency; private bool _changingBandwidth; private bool _changingFrequency; private bool _changingCenterFrequency; private bool _useSmoothing; private bool _enableFilter = true; private bool _hotTrackNeeded; private bool _useSnap; private bool _markPeaks; private float _trackingPower; private string _statusText; private int _displayRange = 130; private int _displayOffset; private LinearGradientBrush _gradientBrush; private ColorBlend _gradientColorBlend = Utils.GetGradientBlend(GradientAlpha, "spectrumAnalyzerGradient"); public SpectrumAnalyzer() { _bkgBuffer = new Bitmap(ClientRectangle.Width, ClientRectangle.Height, PixelFormat.Format32bppPArgb); _buffer = new Bitmap(ClientRectangle.Width, ClientRectangle.Height, PixelFormat.Format32bppPArgb); _graphics = Graphics.FromImage(_buffer); _gradientBrush = new LinearGradientBrush(new Rectangle(AxisMargin, AxisMargin, ClientRectangle.Width - AxisMargin, ClientRectangle.Height - AxisMargin), Color.White, Color.Black, LinearGradientMode.Vertical); _gradientBrush.InterpolationColors = _gradientColorBlend; SetStyle(ControlStyles.OptimizedDoubleBuffer, true); SetStyle(ControlStyles.DoubleBuffer, true); SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); UpdateStyles(); } ~SpectrumAnalyzer() { _buffer.Dispose(); _graphics.Dispose(); _gradientBrush.Dispose(); } public event ManualFrequencyChange FrequencyChanged; public event ManualFrequencyChange CenterFrequencyChanged; public event ManualBandwidthChange BandwidthChanged; public int SpectrumWidth { get { return (int) _spectrumWidth; } set { if (_spectrumWidth != value) { _spectrumWidth = value; ApplyZoom(); } } } public int FilterBandwidth { get { return _filterBandwidth; } set { if (_filterBandwidth != value) { _filterBandwidth = value; _performNeeded = true; } } } public int FilterOffset { get { return _filterOffset; } set { if (_filterOffset != value) { _filterOffset = value; _performNeeded = true; } } } public BandType BandType { get { return _bandType; } set { if (_bandType != value) { _bandType = value; _performNeeded = true; } } } public long Frequency { get { return _frequency; } set { if (_frequency != value) { _frequency = value; _performNeeded = true; } } } public long CenterFrequency { get { return _centerFrequency; } set { if (_centerFrequency != value) { _displayCenterFrequency += value - _centerFrequency; _centerFrequency = value; _drawBackgroundNeeded = true; } } } public int DisplayRange { get { return _displayRange; } set { if (_displayRange != value) { _displayRange = value; _drawBackgroundNeeded = true; } } } public int DisplayOffset { get { return _displayOffset; } set { if (_displayOffset != value) { _displayOffset = value; _drawBackgroundNeeded = true; } } } public int Zoom { get { return _zoom; } set { if (_zoom != value) { _zoom = value; ApplyZoom(); } } } public bool UseSmoothing { get { return _useSmoothing; } set { _useSmoothing = value; } } public bool EnableFilter { get { return _enableFilter; } set { _enableFilter = value; _performNeeded = true; } } public string StatusText { get { return _statusText; } set { _statusText = value; _performNeeded = true; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public ColorBlend GradientColorBlend { get { return _gradientColorBlend; } set { _gradientColorBlend = new ColorBlend(value.Colors.Length); for (var i = 0; i < value.Colors.Length; i++) { _gradientColorBlend.Colors[i] = Color.FromArgb(GradientAlpha, value.Colors[i]); _gradientColorBlend.Positions[i] = value.Positions[i]; } _gradientBrush.Dispose(); _gradientBrush = new LinearGradientBrush(new Rectangle(AxisMargin, AxisMargin, ClientRectangle.Width - AxisMargin, ClientRectangle.Height - AxisMargin), Color.White, Color.Black, LinearGradientMode.Vertical); _gradientBrush.InterpolationColors = _gradientColorBlend; _drawBackgroundNeeded = true; } } public double Attack { get { return _attack; } set { _attack = value; } } public double Decay { get { return _decay; } set { _decay = value; } } public int StepSize { get { return _stepSize; } set { if (_stepSize != value) { _stepSize = value; _drawBackgroundNeeded = true; _performNeeded = true; } } } public bool UseSnap { get { return _useSnap; } set { _useSnap = value; } } public bool MarkPeaks { get { return _markPeaks; } set { _markPeaks = value; } } private void ApplyZoom() { _scale = (float) Math.Pow(10, _zoom * Waterfall.MaxZoom / 100.0f); if (_spectrumWidth > 0) { _displayCenterFrequency = GetDisplayCenterFrequency(); _xIncrement = _scale * (ClientRectangle.Width - 2 * AxisMargin) / _spectrumWidth; _drawBackgroundNeeded = true; } } public void CenterZoom() { _displayCenterFrequency = GetDisplayCenterFrequency(); } private long GetDisplayCenterFrequency() { var f = _frequency; switch (_bandType) { case BandType.Lower: f -= _filterBandwidth / 2 + _filterOffset; break; case BandType.Upper: f += _filterBandwidth / 2 + _filterOffset; break; } var lowerLeadingSpectrum = (long) ((_centerFrequency - _spectrumWidth / 2) - (f - _spectrumWidth / _scale / 2)); if (lowerLeadingSpectrum > 0) { f += lowerLeadingSpectrum + 10; } var upperLeadingSpectrum = (long) ((f + _spectrumWidth / _scale / 2) - (_centerFrequency + _spectrumWidth / 2)); if (upperLeadingSpectrum > 0) { f -= upperLeadingSpectrum + 10; } return f; } public void Perform() { if (_drawBackgroundNeeded) { DrawBackground(); } if (_performNeeded || _drawBackgroundNeeded) { DrawForeground(); Invalidate(); } _performNeeded = false; _drawBackgroundNeeded = false; } private void DrawCursor() { _lower = 0f; float bandpassOffset; var bandpassWidth = 0f; var cursorWidth = Math.Max((_filterBandwidth + _filterOffset) * _xIncrement, 2); var xCarrier = (float) ClientRectangle.Width / 2 + (_frequency - _displayCenterFrequency) * _xIncrement; switch (_bandType) { case BandType.Upper: bandpassOffset = _filterOffset * _xIncrement; bandpassWidth = cursorWidth - bandpassOffset; _lower = xCarrier + bandpassOffset; break; case BandType.Lower: bandpassOffset = _filterOffset * _xIncrement; bandpassWidth = cursorWidth - bandpassOffset; _lower = xCarrier - bandpassOffset - bandpassWidth; break; case BandType.Center: _lower = xCarrier - cursorWidth / 2; bandpassWidth = cursorWidth; break; } _upper = _lower + bandpassWidth; using (var transparentBackground = new SolidBrush(Color.FromArgb(80, Color.DarkGray))) using (var redPen = new Pen(Color.Red)) using (var graphics = Graphics.FromImage(_buffer)) using (var fontFamily = new FontFamily("Arial")) using (var path = new GraphicsPath()) using (var outlinePen = new Pen(Color.Black)) { if (_enableFilter && cursorWidth < ClientRectangle.Width) { var carrierPen = redPen; carrierPen.Width = CarrierPenWidth; graphics.FillRectangle(transparentBackground, (int) _lower + 1, 0, (int) bandpassWidth, ClientRectangle.Height); if (xCarrier >= AxisMargin && xCarrier <= ClientRectangle.Width - AxisMargin) { graphics.DrawLine(carrierPen, xCarrier, 0f, xCarrier, ClientRectangle.Height); } } if (_markPeaks && _spectrumWidth > 0) { var windowSize = (int) bandpassWidth; windowSize = Math.Max(windowSize, 10); windowSize = Math.Min(windowSize, _spectrum.Length); PeakDetector.GetPeaks(_spectrum, _peaks, windowSize); var yIncrement = (ClientRectangle.Height - 2 * AxisMargin) / (float) byte.MaxValue; for (var i = 0; i < _peaks.Length; i++) { if (_peaks[i]) { var y = (int) (ClientRectangle.Height - AxisMargin - _spectrum[i] * yIncrement); var x = i + AxisMargin; graphics.DrawEllipse(Pens.Yellow, x - 5, y - 5, 10, 10); } } } if (_hotTrackNeeded && _trackingX >= AxisMargin && _trackingX <= ClientRectangle.Width - AxisMargin && _trackingY >= AxisMargin && _trackingY <= ClientRectangle.Height - AxisMargin) { if (_spectrum != null && !_changingFrequency && !_changingCenterFrequency && !_changingBandwidth) { var index = _trackingX - AxisMargin; if (_useSnap) { // Todo: snap the index } if (index > 0 && index < _spectrum.Length) { graphics.DrawLine(redPen, _trackingX, 0, _trackingX, ClientRectangle.Height); } } string fstring; if (_changingFrequency) { fstring = "VFO = " + GetFrequencyDisplay(_frequency); } else if (_changingBandwidth) { fstring = "BW = " + GetFrequencyDisplay(_filterBandwidth); } else if (_changingCenterFrequency) { fstring = "Center Freq. = " + GetFrequencyDisplay(_centerFrequency); } else { fstring = string.Format("{0}\r\n{1:0.##}dB", GetFrequencyDisplay(_trackingFrequency), _trackingPower); } path.AddString(fstring, fontFamily, (int)FontStyle.Regular, TrackingFontSize, Point.Empty, StringFormat.GenericTypographic); var stringSize = path.GetBounds(); var currentCursor = Cursor.Current; var xOffset = _trackingX + 15.0f; var yOffset = _trackingY + (currentCursor == null ? DefaultCursorHeight : currentCursor.Size.Height) - 8.0f; xOffset = Math.Min(xOffset, ClientRectangle.Width - stringSize.Width - 5); yOffset = Math.Min(yOffset, ClientRectangle.Height - stringSize.Height - 5); path.Reset(); path.AddString(fstring, fontFamily, (int)FontStyle.Regular, TrackingFontSize, new Point((int)xOffset, (int)yOffset), StringFormat.GenericTypographic); var smoothingMode = graphics.SmoothingMode; var interpolationMode = graphics.InterpolationMode; graphics.SmoothingMode = SmoothingMode.AntiAlias; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; outlinePen.Width = 2; graphics.DrawPath(outlinePen, path); graphics.FillPath(Brushes.White, path); graphics.SmoothingMode = smoothingMode; graphics.InterpolationMode = interpolationMode; } } } public unsafe void Render(float* powerSpectrum, int length) { if (_scaledPowerSpectrum == null || _scaledPowerSpectrum.Length != length) { _scaledPowerSpectrum = new byte[length]; } fixed (byte* scaledPowerSpectrumPtr = _scaledPowerSpectrum) { var displayOffset = _displayOffset / 10 * 10; var displayRange = _displayRange / 10 * 10; Fourier.ScaleFFT(powerSpectrum, scaledPowerSpectrumPtr, length, displayOffset - displayRange, displayOffset); } var scaledLength = (int) (length / _scale); var offset = (int) ((length - scaledLength) / 2.0 + length * (double) (_displayCenterFrequency - _centerFrequency) / _spectrumWidth); if (_useSmoothing) { Fourier.SmoothCopy(_scaledPowerSpectrum, _temp, length, _scale, offset); for (var i = 0; i < _spectrum.Length; i++) { var ratio = _spectrum[i] < _temp[i] ? Attack : Decay; _spectrum[i] = (byte) Math.Round(_spectrum[i] * (1 - ratio) + _temp[i] * ratio); } } else { Fourier.SmoothCopy(_scaledPowerSpectrum, _spectrum, length, _scale, offset); } for (var i = 0; i < _spectrum.Length; i++) { if (_maxSpectrum[i] < _spectrum[i]) _maxSpectrum[i] = _spectrum[i]; } _performNeeded = true; } private void DrawBackground() { using (var fontBrush = new SolidBrush(Color.Silver)) using (var gridPen = new Pen(Color.FromArgb(80, 80, 80))) using (var axisPen = new Pen(Color.DarkGray)) using (var font = new Font("Arial", 8f)) using (var graphics = Graphics.FromImage(_bkgBuffer)) { ConfigureGraphics(graphics); // Background graphics.Clear(Color.Black); if (_spectrumWidth > 0) { #region Frequency markers var baseLabelLength = (int)graphics.MeasureString("1,000,000.000kHz", font).Width; var frequencyStep = (int)(_spectrumWidth / _scale * baseLabelLength / (ClientRectangle.Width - 2 * AxisMargin)); int stepSnap = _stepSize; frequencyStep = frequencyStep / stepSnap * stepSnap + stepSnap; var lineCount = (int)(_spectrumWidth / _scale / frequencyStep) + 4; var xIncrement = (ClientRectangle.Width - 2.0f * AxisMargin) * frequencyStep * _scale / _spectrumWidth; var centerShift = (int)((_displayCenterFrequency % frequencyStep) * (ClientRectangle.Width - 2.0 * AxisMargin) * _scale / _spectrumWidth); for (var i = -lineCount / 2; i < lineCount / 2; i++) { var x = (ClientRectangle.Width - 2 * AxisMargin) / 2 + AxisMargin + xIncrement * i - centerShift; if (x >= AxisMargin && x <= ClientRectangle.Width - AxisMargin) { graphics.DrawLine(gridPen, x, AxisMargin, x, ClientRectangle.Height - AxisMargin); } } for (var i = -lineCount / 2; i < lineCount / 2; i++) { var frequency = _displayCenterFrequency + i * frequencyStep - _displayCenterFrequency % frequencyStep; var fstring = GetFrequencyDisplay(frequency); var sizeF = graphics.MeasureString(fstring, font); var width = sizeF.Width; var x = (ClientRectangle.Width - 2 * AxisMargin) / 2 + AxisMargin + xIncrement * i - centerShift; if (x >= AxisMargin && x <= ClientRectangle.Width - AxisMargin) { x -= width / 2f; graphics.DrawString(fstring, font, fontBrush, x, ClientRectangle.Height - AxisMargin + 8f); } } #endregion } #region Grid gridPen.DashStyle = DashStyle.Dash; var powerMarkerCount = _displayRange / 10; // Power axis var yIncrement = (ClientRectangle.Height - 2 * AxisMargin) / (float) powerMarkerCount; for (var i = 1; i <= powerMarkerCount; i++) { graphics.DrawLine(gridPen, AxisMargin, (int)(ClientRectangle.Height - AxisMargin - i * yIncrement), ClientRectangle.Width - AxisMargin, (int)(ClientRectangle.Height - AxisMargin - i * yIncrement)); } var displayOffset = _displayOffset / 10 * 10; for (var i = 0; i <= powerMarkerCount; i++) { var db = (displayOffset - (powerMarkerCount - i) * 10).ToString(); var sizeF = graphics.MeasureString(db, font); var width = sizeF.Width; var height = sizeF.Height; graphics.DrawString(db, font, fontBrush, AxisMargin - width - 3, ClientRectangle.Height - AxisMargin - i * yIncrement - height / 2f); } // Axis graphics.DrawLine(axisPen, AxisMargin, AxisMargin, AxisMargin, ClientRectangle.Height - AxisMargin); graphics.DrawLine(axisPen, AxisMargin, ClientRectangle.Height - AxisMargin, ClientRectangle.Width - AxisMargin, ClientRectangle.Height - AxisMargin); #endregion } } public static string GetFrequencyDisplay(long frequency) { string result; if (frequency == 0) { result = "DC"; } else if (Math.Abs(frequency) > 1500000000) { result = string.Format("{0:#,0.000 000}GHz", frequency / 1000000000.0); } else if (Math.Abs(frequency) > 30000000) { result = string.Format("{0:0,0.000#}MHz", frequency / 1000000.0); } else if (Math.Abs(frequency) > 1000) { result = string.Format("{0:#,#.###}kHz", frequency / 1000.0); } else { result = string.Format("{0}Hz", frequency); } return result; } public static void ConfigureGraphics(Graphics graphics) { graphics.CompositingMode = CompositingMode.SourceOver; graphics.CompositingQuality = CompositingQuality.HighSpeed; graphics.SmoothingMode = SmoothingMode.None; graphics.PixelOffsetMode = PixelOffsetMode.HighSpeed; graphics.InterpolationMode = InterpolationMode.High; } private void DrawForeground() { if (ClientRectangle.Width <= AxisMargin || ClientRectangle.Height <= AxisMargin) { return; } CopyBackground(); DrawSpectrum(); DrawStatusText(); DrawCursor(); } private unsafe void CopyBackground() { var data1 = _buffer.LockBits(ClientRectangle, ImageLockMode.WriteOnly, _buffer.PixelFormat); var data2 = _bkgBuffer.LockBits(ClientRectangle, ImageLockMode.ReadOnly, _bkgBuffer.PixelFormat); Utils.Memcpy((void*) data1.Scan0, (void*) data2.Scan0, Math.Abs(data1.Stride) * data1.Height); _buffer.UnlockBits(data1); _bkgBuffer.UnlockBits(data2); } private void DrawSpectrum() { if (_spectrum == null || _spectrum.Length == 0) { return; } var xIncrement = (ClientRectangle.Width - 2 * AxisMargin) / (float) _spectrum.Length; var yIncrement = (ClientRectangle.Height - 2 * AxisMargin) / (float) byte.MaxValue; using (var spectrumPen = new Pen(Color.Red)) { for (var i = 0; i < _spectrum.Length; i++) { var strenght = _maxSpectrum[i]; var x = (int)(AxisMargin + i * xIncrement); var y = (int)(ClientRectangle.Height - AxisMargin - strenght * yIncrement); _points[i + 1].X = x; _points[i + 1].Y = y; } //if (_fillSpectrumAnalyzer) //{ // _points[0].X = AxisMargin; // _points[0].Y = ClientRectangle.Height - AxisMargin + 1; // _points[_points.Length - 1].X = ClientRectangle.Width - AxisMargin; // _points[_points.Length - 1].Y = ClientRectangle.Height - AxisMargin + 1; // _graphics.FillPolygon(_gradientBrush, _points); //} _points[0] = _points[1]; _points[_points.Length - 1] = _points[_points.Length - 2]; _graphics.DrawLines(spectrumPen, _points); } using (var spectrumPen = new Pen(_spectrumColor)) { for (var i = 0; i < _spectrum.Length; i++) { var strenght = _spectrum[i]; var x = (int) (AxisMargin + i * xIncrement); var y = (int) (ClientRectangle.Height - AxisMargin - strenght * yIncrement); _points[i + 1].X = x; _points[i + 1].Y = y; } if (_fillSpectrumAnalyzer) { _points[0].X = AxisMargin; _points[0].Y = ClientRectangle.Height - AxisMargin + 1; _points[_points.Length - 1].X = ClientRectangle.Width - AxisMargin; _points[_points.Length - 1].Y = ClientRectangle.Height - AxisMargin + 1; _graphics.FillPolygon(_gradientBrush, _points); } _points[0] = _points[1]; _points[_points.Length - 1] = _points[_points.Length - 2]; _graphics.DrawLines(spectrumPen, _points); } } private void DrawStatusText() { if (string.IsNullOrEmpty(_statusText)) { return; } using (var font = new Font("Lucida Console", 9)) { _graphics.DrawString(_statusText, font, Brushes.White, AxisMargin, 10); } } protected override void OnPaint(PaintEventArgs e) { ConfigureGraphics(e.Graphics); e.Graphics.DrawImageUnscaled(_buffer, 0, 0); } protected override void OnResize(EventArgs e) { base.OnResize(e); if (ClientRectangle.Width > 0 && ClientRectangle.Height > 0) { _buffer.Dispose(); _graphics.Dispose(); _bkgBuffer.Dispose(); _buffer = new Bitmap(ClientRectangle.Width, ClientRectangle.Height, PixelFormat.Format32bppPArgb); _graphics = Graphics.FromImage(_buffer); ConfigureGraphics(_graphics); _bkgBuffer = new Bitmap(ClientRectangle.Width, ClientRectangle.Height, PixelFormat.Format32bppPArgb); var length = ClientRectangle.Width - 2 * AxisMargin; var oldSpectrum = _spectrum; _maxSpectrum = new byte[length]; _spectrum = new byte[length]; _peaks = new bool[length]; if (oldSpectrum != null) { Fourier.SmoothCopy(oldSpectrum, _spectrum, oldSpectrum.Length, 1, 0); } else { for (var i = 0; i < _spectrum.Length; i++) { _spectrum[i] = 0; } } _temp = new byte[length]; _points = new Point[length + 2]; if (_spectrumWidth > 0) { _xIncrement = _scale * (ClientRectangle.Width - 2 * AxisMargin) / _spectrumWidth; } _gradientBrush.Dispose(); _gradientBrush = new LinearGradientBrush(new Rectangle(AxisMargin, AxisMargin, ClientRectangle.Width - AxisMargin, ClientRectangle.Height - AxisMargin), Color.White, Color.Black, LinearGradientMode.Vertical); _gradientBrush.InterpolationColors = _gradientColorBlend; _drawBackgroundNeeded = true; Perform(); } } protected override void OnPaintBackground(PaintEventArgs e) { // Prevent default background painting } protected virtual void OnFrequencyChanged(FrequencyEventArgs e) { if (FrequencyChanged != null) { FrequencyChanged(this, e); } } protected virtual void OnCenterFrequencyChanged(FrequencyEventArgs e) { if (CenterFrequencyChanged != null) { CenterFrequencyChanged(this, e); } } protected virtual void OnBandwidthChanged(BandwidthEventArgs e) { if (BandwidthChanged != null) { BandwidthChanged(this, e); } } private void UpdateFrequency(long f, FrequencyChangeSource source) { var min = (long) (_displayCenterFrequency - _spectrumWidth / _scale / 2); if (f < min) { f = min; } var max = (long) (_displayCenterFrequency + _spectrumWidth / _scale / 2); if (f > max) { f = max; } if (_useSnap) { f = (f + Math.Sign(f) * _stepSize / 2) / _stepSize * _stepSize; } if (f != _frequency) { var args = new FrequencyEventArgs(f, source); OnFrequencyChanged(args); if (!args.Cancel) { _frequency = args.Frequency; _performNeeded = true; } } } private void UpdateCenterFrequency(long f, FrequencyChangeSource source) { if (f < 0) { f = 0; } if (_useSnap) { f = (f + Math.Sign(f) * _stepSize / 2) / _stepSize * _stepSize; } if (f != _centerFrequency) { var args = new FrequencyEventArgs(f, source); OnCenterFrequencyChanged(args); if (!args.Cancel) { var delta = args.Frequency - _centerFrequency; _displayCenterFrequency += delta; _centerFrequency = args.Frequency; _drawBackgroundNeeded = true; } } } private void UpdateBandwidth(int bw) { bw = 10 * (bw / 10); if (bw < 10) { bw = 10; } if (bw != _filterBandwidth) { var args = new BandwidthEventArgs(bw); OnBandwidthChanged(args); if (!args.Cancel) { _filterBandwidth = args.Bandwidth; _performNeeded = true; } } } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (e.Button == MouseButtons.Left) { var cursorWidth = Math.Max((_filterBandwidth + _filterOffset) * _xIncrement, 2); if (e.X > _lower && e.X < _upper && cursorWidth < ClientRectangle.Width) { _oldX = e.X; _oldFrequency = _frequency; _changingFrequency = true; } else if (_enableFilter && ((Math.Abs(e.X - _lower + Waterfall.CursorSnapDistance) <= Waterfall.CursorSnapDistance && (_bandType == BandType.Center || _bandType == BandType.Lower)) || (Math.Abs(e.X - _upper - Waterfall.CursorSnapDistance) <= Waterfall.CursorSnapDistance && (_bandType == BandType.Center || _bandType == BandType.Upper)))) { _oldX = e.X; _oldFilterBandwidth = _filterBandwidth; _changingBandwidth = true; } else { _oldX = e.X; _oldCenterFrequency = _centerFrequency; _changingCenterFrequency = true; } } else if (e.Button == MouseButtons.Right) { UpdateFrequency(_frequency / Waterfall.RightClickSnapDistance * Waterfall.RightClickSnapDistance, FrequencyChangeSource.Click); for(int i=0;i<_maxSpectrum.Length;i++) _maxSpectrum[i] = 0; } } protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseUp(e); if (_changingCenterFrequency && e.X == _oldX) { var f = (long)((_oldX - ClientRectangle.Width / 2) * _spectrumWidth / _scale / (ClientRectangle.Width - 2 * AxisMargin) + _displayCenterFrequency); UpdateFrequency(f, FrequencyChangeSource.Click); } _changingCenterFrequency = false; _drawBackgroundNeeded = true; _changingBandwidth = false; _changingFrequency = false; } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); _trackingX = e.X; _trackingY = e.Y; _trackingFrequency = (long)((e.X - ClientRectangle.Width / 2) * _spectrumWidth / _scale / (ClientRectangle.Width - 2 * AxisMargin) + _displayCenterFrequency); if (_useSnap) { _trackingFrequency = (_trackingFrequency + Math.Sign(_trackingFrequency) * _stepSize / 2) / _stepSize * _stepSize; } var displayRange = _displayRange / 10 * 10; var displayOffset = _displayOffset / 10 * 10; var yIncrement = (ClientRectangle.Height - 2 * AxisMargin) / (float) displayRange; _trackingPower = displayOffset - displayRange - (_trackingY + AxisMargin - ClientRectangle.Height) / yIncrement; if (_changingFrequency) { var f = (long) ((e.X - _oldX) * _spectrumWidth / _scale / (ClientRectangle.Width - 2 * AxisMargin) + _oldFrequency); UpdateFrequency(f, FrequencyChangeSource.Drag); } else if (_changingCenterFrequency) { var f = (long) ((_oldX - e.X) * _spectrumWidth / _scale / (ClientRectangle.Width - 2 * AxisMargin) + _oldCenterFrequency); UpdateCenterFrequency(f, FrequencyChangeSource.Drag); } else if (_changingBandwidth) { var bw = 0; switch (_bandType) { case BandType.Upper: bw = e.X - _oldX; break; case BandType.Lower: bw = _oldX - e.X; break; case BandType.Center: bw = (_oldX > (_lower + _upper) / 2 ? e.X - _oldX : _oldX - e.X) * 2; break; } bw = (int) (bw * _spectrumWidth / _scale / (ClientRectangle.Width - 2 * AxisMargin) + _oldFilterBandwidth); UpdateBandwidth(bw); } else if (_enableFilter && ((Math.Abs(e.X - _lower + Waterfall.CursorSnapDistance) <= Waterfall.CursorSnapDistance && (_bandType == BandType.Center || _bandType == BandType.Lower)) || (Math.Abs(e.X - _upper - Waterfall.CursorSnapDistance) <= Waterfall.CursorSnapDistance && (_bandType == BandType.Center || _bandType == BandType.Upper)))) { Cursor = Cursors.SizeWE; } else { Cursor = Cursors.Default; } _performNeeded = true; } protected override void OnMouseWheel(MouseEventArgs e) { base.OnMouseWheel(e); UpdateFrequency(_frequency + _stepSize * Math.Sign(e.Delta), FrequencyChangeSource.Scroll); } protected override void OnMouseLeave(EventArgs e) { base.OnMouseLeave(e); _hotTrackNeeded = false; _performNeeded = true; } protected override void OnMouseEnter(EventArgs e) { Focus(); base.OnMouseEnter(e); _hotTrackNeeded = true; } } }
using System; using System.IO; using System.Collections.Specialized; using System.Net; using System.Text; using System.Web; using System.Security.Cryptography; using Newtonsoft.Json; using System.Security.Cryptography.X509Certificates; using System.Net.Security; using SteamKit2; namespace SteamTrade { public class SteamWeb { public static string Fetch (string url, string method, NameValueCollection data = null, CookieContainer cookies = null, bool ajax = true) { HttpWebResponse response = Request (url, method, data, cookies, ajax); StreamReader reader = new StreamReader (response.GetResponseStream ()); return reader.ReadToEnd (); } public static HttpWebResponse Request (string url, string method, NameValueCollection data = null, CookieContainer cookies = null, bool ajax = true) { HttpWebRequest request = WebRequest.Create (url) as HttpWebRequest; request.Method = method; request.Accept = "text/javascript, text/html, application/xml, text/xml, */*"; request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8"; request.Host = "steamcommunity.com"; request.UserAgent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11"; request.Referer = "http://steamcommunity.com/trade/1"; if (ajax) { request.Headers.Add ("X-Requested-With", "XMLHttpRequest"); request.Headers.Add ("X-Prototype-Version", "1.7"); } // Cookies request.CookieContainer = cookies ?? new CookieContainer (); // Request data if (data != null) { string dataString = String.Join ("&", Array.ConvertAll (data.AllKeys, key => String.Format ("{0}={1}", HttpUtility.UrlEncode (key), HttpUtility.UrlEncode (data [key])) ) ); byte[] dataBytes = Encoding.ASCII.GetBytes (dataString); request.ContentLength = dataBytes.Length; Stream requestStream = request.GetRequestStream (); requestStream.Write (dataBytes, 0, dataBytes.Length); } // Get the response return request.GetResponse () as HttpWebResponse; } /// <summary> /// Executes the login by using the Steam Website. /// </summary> public static CookieCollection DoLogin (string username, string password) { var data = new NameValueCollection (); data.Add ("username", username); string response = Fetch ("https://steamcommunity.com/login/getrsakey", "POST", data, null, false); GetRsaKey rsaJSON = JsonConvert.DeserializeObject<GetRsaKey> (response); // Validate if (rsaJSON.success != true) { return null; } //RSA Encryption RSACryptoServiceProvider rsa = new RSACryptoServiceProvider (); RSAParameters rsaParameters = new RSAParameters (); rsaParameters.Exponent = HexToByte (rsaJSON.publickey_exp); rsaParameters.Modulus = HexToByte (rsaJSON.publickey_mod); rsa.ImportParameters (rsaParameters); byte[] bytePassword = Encoding.ASCII.GetBytes (password); byte[] encodedPassword = rsa.Encrypt (bytePassword, false); string encryptedBase64Password = Convert.ToBase64String (encodedPassword); SteamResult loginJson = null; CookieCollection cookies; string steamGuardText = ""; string steamGuardId = ""; do { Console.WriteLine ("SteamWeb: Logging In..."); bool captcha = loginJson != null && loginJson.captcha_needed == true; bool steamGuard = loginJson != null && loginJson.emailauth_needed == true; string time = Uri.EscapeDataString (rsaJSON.timestamp); string capGID = loginJson == null ? null : Uri.EscapeDataString (loginJson.captcha_gid); data = new NameValueCollection (); data.Add ("password", encryptedBase64Password); data.Add ("username", username); // Captcha string capText = ""; if (captcha) { Console.WriteLine ("SteamWeb: Captcha is needed."); System.Diagnostics.Process.Start ("https://steamcommunity.com/public/captcha.php?gid=" + loginJson.captcha_gid); Console.WriteLine ("SteamWeb: Type the captcha:"); capText = Uri.EscapeDataString (Console.ReadLine ()); } data.Add ("captchagid", captcha ? capGID : ""); data.Add ("captcha_text", captcha ? capText : ""); // Captcha end // SteamGuard if (steamGuard) { Console.WriteLine ("SteamWeb: SteamGuard is needed."); Console.WriteLine ("SteamWeb: Type the code:"); steamGuardText = Uri.EscapeDataString (Console.ReadLine ()); steamGuardId = loginJson.emailsteamid; } data.Add ("emailauth", steamGuardText); data.Add ("emailsteamid", steamGuardId); // SteamGuard end data.Add ("rsatimestamp", time); HttpWebResponse webResponse = Request ("https://steamcommunity.com/login/dologin/", "POST", data, null, false); StreamReader reader = new StreamReader (webResponse.GetResponseStream ()); string json = reader.ReadToEnd (); loginJson = JsonConvert.DeserializeObject<SteamResult> (json); cookies = webResponse.Cookies; } while (loginJson.captcha_needed == true || loginJson.emailauth_needed == true); if (loginJson.success == true) { CookieContainer c = new CookieContainer (); foreach (Cookie cookie in cookies) { c.Add (cookie); } SubmitCookies (c); return cookies; } else { Console.WriteLine ("SteamWeb Error: " + loginJson.message); return null; } } ///<summary> /// Authenticate using SteamKit2 and ISteamUserAuth. /// This does the same as SteamWeb.DoLogin(), but without contacting the Steam Website. /// </summary> /// <remarks>Should this one doesnt work anymore, use <see cref="SteamWeb.DoLogin"/></remarks> public static bool Authenticate(SteamUser.LoginKeyCallback callback, SteamClient client, out string sessionId, out string token, string MyLoginKey) { sessionId = Convert.ToBase64String (Encoding.UTF8.GetBytes (callback.UniqueID.ToString ())); using (dynamic userAuth = WebAPI.GetInterface ("ISteamUserAuth")) { // generate an AES session key var sessionKey = CryptoHelper.GenerateRandomBlock (32); // rsa encrypt it with the public key for the universe we're on byte[] cryptedSessionKey = null; using (RSACrypto rsa = new RSACrypto (KeyDictionary.GetPublicKey (client.ConnectedUniverse))) { cryptedSessionKey = rsa.Encrypt (sessionKey); } byte[] loginKey = new byte[20]; Array.Copy(Encoding.ASCII.GetBytes(MyLoginKey), loginKey, MyLoginKey.Length); // aes encrypt the loginkey with our session key byte[] cryptedLoginKey = CryptoHelper.SymmetricEncrypt (loginKey, sessionKey); KeyValue authResult; try { authResult = userAuth.AuthenticateUser ( steamid: client.SteamID.ConvertToUInt64 (), sessionkey: HttpUtility.UrlEncode (cryptedSessionKey), encrypted_loginkey: HttpUtility.UrlEncode (cryptedLoginKey), method: "POST" ); } catch (Exception) { token = null; return false; } token = authResult ["token"].AsString (); return true; } } static void SubmitCookies (CookieContainer cookies) { HttpWebRequest w = WebRequest.Create ("https://steamcommunity.com/") as HttpWebRequest; w.Method = "POST"; w.ContentType = "application/x-www-form-urlencoded"; w.CookieContainer = cookies; w.GetResponse ().Close (); return; } static byte[] HexToByte (string hex) { if (hex.Length % 2 == 1) throw new Exception ("The binary key cannot have an odd number of digits"); byte[] arr = new byte[hex.Length >> 1]; int l = hex.Length; for (int i = 0; i < (l >> 1); ++i) { arr [i] = (byte)((GetHexVal (hex [i << 1]) << 4) + (GetHexVal (hex [(i << 1) + 1]))); } return arr; } static int GetHexVal (char hex) { int val = (int)hex; return val - (val < 58 ? 48 : 55); } public static bool ValidateRemoteCertificate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) { // allow all certificates return true; } } // JSON Classes public class GetRsaKey { public bool success { get; set; } public string publickey_mod { get; set; } public string publickey_exp { get; set; } public string timestamp { get; set; } } public class SteamResult { public bool success { get; set; } public string message { get; set; } public bool captcha_needed { get; set; } public string captcha_gid { get; set; } public bool emailauth_needed { get; set; } public string emailsteamid { get; set; } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos/Networking/Envelopes/RequestEnvelope.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.Networking.Envelopes { /// <summary>Holder for reflection information generated from POGOProtos/Networking/Envelopes/RequestEnvelope.proto</summary> public static partial class RequestEnvelopeReflection { #region Descriptor /// <summary>File descriptor for POGOProtos/Networking/Envelopes/RequestEnvelope.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static RequestEnvelopeReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjVQT0dPUHJvdG9zL05ldHdvcmtpbmcvRW52ZWxvcGVzL1JlcXVlc3RFbnZl", "bG9wZS5wcm90bxIfUE9HT1Byb3Rvcy5OZXR3b3JraW5nLkVudmVsb3Blcxos", "UE9HT1Byb3Rvcy9OZXR3b3JraW5nL1JlcXVlc3RzL1JlcXVlc3QucHJvdG8a", "MFBPR09Qcm90b3MvTmV0d29ya2luZy9FbnZlbG9wZXMvQXV0aFRpY2tldC5w", "cm90bxouUE9HT1Byb3Rvcy9OZXR3b3JraW5nL0VudmVsb3Blcy9Vbmtub3du", "Ni5wcm90byK0BAoPUmVxdWVzdEVudmVsb3BlEhMKC3N0YXR1c19jb2RlGAEg", "ASgFEhIKCnJlcXVlc3RfaWQYAyABKAQSOQoIcmVxdWVzdHMYBCADKAsyJy5Q", "T0dPUHJvdG9zLk5ldHdvcmtpbmcuUmVxdWVzdHMuUmVxdWVzdBI7Cgh1bmtu", "b3duNhgGIAEoCzIpLlBPR09Qcm90b3MuTmV0d29ya2luZy5FbnZlbG9wZXMu", "VW5rbm93bjYSEAoIbGF0aXR1ZGUYByABKAESEQoJbG9uZ2l0dWRlGAggASgB", "EhAKCGFjY3VyYWN5GAkgASgBEkwKCWF1dGhfaW5mbxgKIAEoCzI5LlBPR09Q", "cm90b3MuTmV0d29ya2luZy5FbnZlbG9wZXMuUmVxdWVzdEVudmVsb3BlLkF1", "dGhJbmZvEkAKC2F1dGhfdGlja2V0GAsgASgLMisuUE9HT1Byb3Rvcy5OZXR3", "b3JraW5nLkVudmVsb3Blcy5BdXRoVGlja2V0EiEKGW1zX3NpbmNlX2xhc3Rf", "bG9jYXRpb25maXgYDCABKAMalQEKCEF1dGhJbmZvEhAKCHByb3ZpZGVyGAEg", "ASgJEkwKBXRva2VuGAIgASgLMj0uUE9HT1Byb3Rvcy5OZXR3b3JraW5nLkVu", "dmVsb3Blcy5SZXF1ZXN0RW52ZWxvcGUuQXV0aEluZm8uSldUGikKA0pXVBIQ", "Cghjb250ZW50cxgBIAEoCRIQCgh1bmtub3duMhgCIAEoBWIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::POGOProtos.Networking.Requests.RequestReflection.Descriptor, global::POGOProtos.Networking.Envelopes.AuthTicketReflection.Descriptor, global::POGOProtos.Networking.Envelopes.Unknown6Reflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Networking.Envelopes.RequestEnvelope), global::POGOProtos.Networking.Envelopes.RequestEnvelope.Parser, new[]{ "StatusCode", "RequestId", "Requests", "Unknown6", "Latitude", "Longitude", "Accuracy", "AuthInfo", "AuthTicket", "MsSinceLastLocationfix" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Networking.Envelopes.RequestEnvelope.Types.AuthInfo), global::POGOProtos.Networking.Envelopes.RequestEnvelope.Types.AuthInfo.Parser, new[]{ "Provider", "Token" }, null, null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Networking.Envelopes.RequestEnvelope.Types.AuthInfo.Types.JWT), global::POGOProtos.Networking.Envelopes.RequestEnvelope.Types.AuthInfo.Types.JWT.Parser, new[]{ "Contents", "Unknown2" }, null, null, null)})}) })); } #endregion } #region Messages public sealed partial class RequestEnvelope : pb::IMessage<RequestEnvelope> { private static readonly pb::MessageParser<RequestEnvelope> _parser = new pb::MessageParser<RequestEnvelope>(() => new RequestEnvelope()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<RequestEnvelope> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Networking.Envelopes.RequestEnvelopeReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RequestEnvelope() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RequestEnvelope(RequestEnvelope other) : this() { statusCode_ = other.statusCode_; requestId_ = other.requestId_; requests_ = other.requests_.Clone(); Unknown6 = other.unknown6_ != null ? other.Unknown6.Clone() : null; latitude_ = other.latitude_; longitude_ = other.longitude_; accuracy_ = other.accuracy_; AuthInfo = other.authInfo_ != null ? other.AuthInfo.Clone() : null; AuthTicket = other.authTicket_ != null ? other.AuthTicket.Clone() : null; msSinceLastLocationfix_ = other.msSinceLastLocationfix_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RequestEnvelope Clone() { return new RequestEnvelope(this); } /// <summary>Field number for the "status_code" field.</summary> public const int StatusCodeFieldNumber = 1; private int statusCode_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int StatusCode { get { return statusCode_; } set { statusCode_ = value; } } /// <summary>Field number for the "request_id" field.</summary> public const int RequestIdFieldNumber = 3; private ulong requestId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ulong RequestId { get { return requestId_; } set { requestId_ = value; } } /// <summary>Field number for the "requests" field.</summary> public const int RequestsFieldNumber = 4; private static readonly pb::FieldCodec<global::POGOProtos.Networking.Requests.Request> _repeated_requests_codec = pb::FieldCodec.ForMessage(34, global::POGOProtos.Networking.Requests.Request.Parser); private readonly pbc::RepeatedField<global::POGOProtos.Networking.Requests.Request> requests_ = new pbc::RepeatedField<global::POGOProtos.Networking.Requests.Request>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::POGOProtos.Networking.Requests.Request> Requests { get { return requests_; } } /// <summary>Field number for the "unknown6" field.</summary> public const int Unknown6FieldNumber = 6; private global::POGOProtos.Networking.Envelopes.Unknown6 unknown6_; /// <summary> /// Unknown6 is required to get a response. /// For an example check https://github.com/keyphact/pgoapi/blob/75eba6b5b630841ee4f7c2ea983f15874fb0862d/pgoapi/rpc_api.py#L192-L212 /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Networking.Envelopes.Unknown6 Unknown6 { get { return unknown6_; } set { unknown6_ = value; } } /// <summary>Field number for the "latitude" field.</summary> public const int LatitudeFieldNumber = 7; 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 = 8; private double longitude_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double Longitude { get { return longitude_; } set { longitude_ = value; } } /// <summary>Field number for the "accuracy" field.</summary> public const int AccuracyFieldNumber = 9; private double accuracy_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double Accuracy { get { return accuracy_; } set { accuracy_ = value; } } /// <summary>Field number for the "auth_info" field.</summary> public const int AuthInfoFieldNumber = 10; private global::POGOProtos.Networking.Envelopes.RequestEnvelope.Types.AuthInfo authInfo_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Networking.Envelopes.RequestEnvelope.Types.AuthInfo AuthInfo { get { return authInfo_; } set { authInfo_ = value; } } /// <summary>Field number for the "auth_ticket" field.</summary> public const int AuthTicketFieldNumber = 11; private global::POGOProtos.Networking.Envelopes.AuthTicket authTicket_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Networking.Envelopes.AuthTicket AuthTicket { get { return authTicket_; } set { authTicket_ = value; } } /// <summary>Field number for the "ms_since_last_locationfix" field.</summary> public const int MsSinceLastLocationfixFieldNumber = 12; private long msSinceLastLocationfix_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public long MsSinceLastLocationfix { get { return msSinceLastLocationfix_; } set { msSinceLastLocationfix_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as RequestEnvelope); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(RequestEnvelope other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (StatusCode != other.StatusCode) return false; if (RequestId != other.RequestId) return false; if(!requests_.Equals(other.requests_)) return false; if (!object.Equals(Unknown6, other.Unknown6)) return false; if (Latitude != other.Latitude) return false; if (Longitude != other.Longitude) return false; if (Accuracy != other.Accuracy) return false; if (!object.Equals(AuthInfo, other.AuthInfo)) return false; if (!object.Equals(AuthTicket, other.AuthTicket)) return false; if (MsSinceLastLocationfix != other.MsSinceLastLocationfix) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (StatusCode != 0) hash ^= StatusCode.GetHashCode(); if (RequestId != 0UL) hash ^= RequestId.GetHashCode(); hash ^= requests_.GetHashCode(); if (unknown6_ != null) hash ^= Unknown6.GetHashCode(); if (Latitude != 0D) hash ^= Latitude.GetHashCode(); if (Longitude != 0D) hash ^= Longitude.GetHashCode(); if (Accuracy != 0D) hash ^= Accuracy.GetHashCode(); if (authInfo_ != null) hash ^= AuthInfo.GetHashCode(); if (authTicket_ != null) hash ^= AuthTicket.GetHashCode(); if (MsSinceLastLocationfix != 0L) hash ^= MsSinceLastLocationfix.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 (StatusCode != 0) { output.WriteRawTag(8); output.WriteInt32(StatusCode); } if (RequestId != 0UL) { output.WriteRawTag(24); output.WriteUInt64(RequestId); } requests_.WriteTo(output, _repeated_requests_codec); if (unknown6_ != null) { output.WriteRawTag(50); output.WriteMessage(Unknown6); } if (Latitude != 0D) { output.WriteRawTag(57); output.WriteDouble(Latitude); } if (Longitude != 0D) { output.WriteRawTag(65); output.WriteDouble(Longitude); } if (Accuracy != 0D) { output.WriteRawTag(73); output.WriteDouble(Accuracy); } if (authInfo_ != null) { output.WriteRawTag(82); output.WriteMessage(AuthInfo); } if (authTicket_ != null) { output.WriteRawTag(90); output.WriteMessage(AuthTicket); } if (MsSinceLastLocationfix != 0L) { output.WriteRawTag(96); output.WriteInt64(MsSinceLastLocationfix); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (StatusCode != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(StatusCode); } if (RequestId != 0UL) { size += 1 + pb::CodedOutputStream.ComputeUInt64Size(RequestId); } size += requests_.CalculateSize(_repeated_requests_codec); if (unknown6_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Unknown6); } if (Latitude != 0D) { size += 1 + 8; } if (Longitude != 0D) { size += 1 + 8; } if (Accuracy != 0D) { size += 1 + 8; } if (authInfo_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(AuthInfo); } if (authTicket_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(AuthTicket); } if (MsSinceLastLocationfix != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(MsSinceLastLocationfix); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(RequestEnvelope other) { if (other == null) { return; } if (other.StatusCode != 0) { StatusCode = other.StatusCode; } if (other.RequestId != 0UL) { RequestId = other.RequestId; } requests_.Add(other.requests_); if (other.unknown6_ != null) { if (unknown6_ == null) { unknown6_ = new global::POGOProtos.Networking.Envelopes.Unknown6(); } Unknown6.MergeFrom(other.Unknown6); } if (other.Latitude != 0D) { Latitude = other.Latitude; } if (other.Longitude != 0D) { Longitude = other.Longitude; } if (other.Accuracy != 0D) { Accuracy = other.Accuracy; } if (other.authInfo_ != null) { if (authInfo_ == null) { authInfo_ = new global::POGOProtos.Networking.Envelopes.RequestEnvelope.Types.AuthInfo(); } AuthInfo.MergeFrom(other.AuthInfo); } if (other.authTicket_ != null) { if (authTicket_ == null) { authTicket_ = new global::POGOProtos.Networking.Envelopes.AuthTicket(); } AuthTicket.MergeFrom(other.AuthTicket); } if (other.MsSinceLastLocationfix != 0L) { MsSinceLastLocationfix = other.MsSinceLastLocationfix; } } [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: { StatusCode = input.ReadInt32(); break; } case 24: { RequestId = input.ReadUInt64(); break; } case 34: { requests_.AddEntriesFrom(input, _repeated_requests_codec); break; } case 50: { if (unknown6_ == null) { unknown6_ = new global::POGOProtos.Networking.Envelopes.Unknown6(); } input.ReadMessage(unknown6_); break; } case 57: { Latitude = input.ReadDouble(); break; } case 65: { Longitude = input.ReadDouble(); break; } case 73: { Accuracy = input.ReadDouble(); break; } case 82: { if (authInfo_ == null) { authInfo_ = new global::POGOProtos.Networking.Envelopes.RequestEnvelope.Types.AuthInfo(); } input.ReadMessage(authInfo_); break; } case 90: { if (authTicket_ == null) { authTicket_ = new global::POGOProtos.Networking.Envelopes.AuthTicket(); } input.ReadMessage(authTicket_); break; } case 96: { MsSinceLastLocationfix = input.ReadInt64(); break; } } } } #region Nested types /// <summary>Container for nested types declared in the RequestEnvelope message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { public sealed partial class AuthInfo : pb::IMessage<AuthInfo> { private static readonly pb::MessageParser<AuthInfo> _parser = new pb::MessageParser<AuthInfo>(() => new AuthInfo()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<AuthInfo> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Networking.Envelopes.RequestEnvelope.Descriptor.NestedTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AuthInfo() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AuthInfo(AuthInfo other) : this() { provider_ = other.provider_; Token = other.token_ != null ? other.Token.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public AuthInfo Clone() { return new AuthInfo(this); } /// <summary>Field number for the "provider" field.</summary> public const int ProviderFieldNumber = 1; private string provider_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Provider { get { return provider_; } set { provider_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "token" field.</summary> public const int TokenFieldNumber = 2; private global::POGOProtos.Networking.Envelopes.RequestEnvelope.Types.AuthInfo.Types.JWT token_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Networking.Envelopes.RequestEnvelope.Types.AuthInfo.Types.JWT Token { get { return token_; } set { token_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as AuthInfo); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(AuthInfo other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Provider != other.Provider) return false; if (!object.Equals(Token, other.Token)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Provider.Length != 0) hash ^= Provider.GetHashCode(); if (token_ != null) hash ^= Token.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 (Provider.Length != 0) { output.WriteRawTag(10); output.WriteString(Provider); } if (token_ != null) { output.WriteRawTag(18); output.WriteMessage(Token); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Provider.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Provider); } if (token_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Token); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(AuthInfo other) { if (other == null) { return; } if (other.Provider.Length != 0) { Provider = other.Provider; } if (other.token_ != null) { if (token_ == null) { token_ = new global::POGOProtos.Networking.Envelopes.RequestEnvelope.Types.AuthInfo.Types.JWT(); } Token.MergeFrom(other.Token); } } [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: { Provider = input.ReadString(); break; } case 18: { if (token_ == null) { token_ = new global::POGOProtos.Networking.Envelopes.RequestEnvelope.Types.AuthInfo.Types.JWT(); } input.ReadMessage(token_); break; } } } } #region Nested types /// <summary>Container for nested types declared in the AuthInfo message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { public sealed partial class JWT : pb::IMessage<JWT> { private static readonly pb::MessageParser<JWT> _parser = new pb::MessageParser<JWT>(() => new JWT()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<JWT> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Networking.Envelopes.RequestEnvelope.Types.AuthInfo.Descriptor.NestedTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public JWT() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public JWT(JWT other) : this() { contents_ = other.contents_; unknown2_ = other.unknown2_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public JWT Clone() { return new JWT(this); } /// <summary>Field number for the "contents" field.</summary> public const int ContentsFieldNumber = 1; private string contents_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string Contents { get { return contents_; } set { contents_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "unknown2" field.</summary> public const int Unknown2FieldNumber = 2; private int unknown2_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int Unknown2 { get { return unknown2_; } set { unknown2_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as JWT); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(JWT other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Contents != other.Contents) return false; if (Unknown2 != other.Unknown2) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Contents.Length != 0) hash ^= Contents.GetHashCode(); if (Unknown2 != 0) hash ^= Unknown2.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 (Contents.Length != 0) { output.WriteRawTag(10); output.WriteString(Contents); } if (Unknown2 != 0) { output.WriteRawTag(16); output.WriteInt32(Unknown2); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Contents.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Contents); } if (Unknown2 != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Unknown2); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(JWT other) { if (other == null) { return; } if (other.Contents.Length != 0) { Contents = other.Contents; } if (other.Unknown2 != 0) { Unknown2 = other.Unknown2; } } [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: { Contents = input.ReadString(); break; } case 16: { Unknown2 = input.ReadInt32(); break; } } } } } } #endregion } } #endregion } #endregion } #endregion Designer generated code
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Internal.IL; using Internal.IL.Stubs; using Debug = System.Diagnostics.Debug; using System.Threading; namespace Internal.TypeSystem.Interop { /// <summary> /// This generates a class which inherits from System.Runtime.InteropServices.NativeFunctionPointerWrapper. It has a constructror and /// a second instance method which marshalls arguments in the forward direction in order to call the native function pointer. /// </summary> public partial class PInvokeDelegateWrapper : MetadataType { // The type of delegate that will be created from the native function pointer public MetadataType DelegateType { get; } public override ModuleDesc Module { get; } public override string Name { get { return "PInvokeDelegateWrapper__" + DelegateType.Name; } } public override string Namespace { get { return "Internal.CompilerGenerated"; } } public override bool IsExplicitLayout { get { return false; } } public override PInvokeStringFormat PInvokeStringFormat { get { return PInvokeStringFormat.AnsiClass; } } public override bool IsSequentialLayout { get { return false; } } public override bool IsBeforeFieldInit { get { return false; } } public override MetadataType MetadataBaseType { get { return InteropTypes.GetNativeFunctionPointerWrapper(Context); } } public override bool IsSealed { get { return true; } } public override bool IsAbstract { get { return false; } } public override DefType ContainingType { get { return null; } } public override DefType[] ExplicitlyImplementedInterfaces { get { return Array.Empty<DefType>(); } } public override TypeSystemContext Context { get { return DelegateType.Context; } } private InteropStateManager _interopStateManager; public PInvokeDelegateWrapper(ModuleDesc owningModule, MetadataType delegateType, InteropStateManager interopStateManager) { Debug.Assert(delegateType.IsDelegate); Module = owningModule; DelegateType = delegateType; _interopStateManager = interopStateManager; } public override ClassLayoutMetadata GetClassLayout() { return default(ClassLayoutMetadata); } public override bool HasCustomAttribute(string attributeNamespace, string attributeName) { return false; } public override IEnumerable<MetadataType> GetNestedTypes() { return Array.Empty<MetadataType>(); } public override MetadataType GetNestedType(string name) { return null; } protected override MethodImplRecord[] ComputeVirtualMethodImplsForType() { return Array.Empty<MethodImplRecord>(); } public override MethodImplRecord[] FindMethodsImplWithMatchingDeclName(string name) { return Array.Empty<MethodImplRecord>(); } private int _hashCode; private void InitializeHashCode() { var hashCodeBuilder = new Internal.NativeFormat.TypeHashingAlgorithms.HashCodeBuilder(Namespace); if (Namespace.Length > 0) { hashCodeBuilder.Append("."); } hashCodeBuilder.Append(Name); _hashCode = hashCodeBuilder.ToHashCode(); } public override int GetHashCode() { if (_hashCode == 0) { InitializeHashCode(); } return _hashCode; } protected override TypeFlags ComputeTypeFlags(TypeFlags mask) { TypeFlags flags = 0; if ((mask & TypeFlags.HasGenericVarianceComputed) != 0) { flags |= TypeFlags.HasGenericVarianceComputed; } if ((mask & TypeFlags.CategoryMask) != 0) { flags |= TypeFlags.Class; } flags |= TypeFlags.HasFinalizerComputed; return flags; } private MethodDesc[] _methods; private void InitializeMethods() { MethodDesc[] methods = new MethodDesc[] { new PInvokeDelegateWrapperConstructor(this), // Constructor new DelegateMarshallingMethodThunk(DelegateType, this, _interopStateManager, DelegateMarshallingMethodThunkKind.ForwardNativeFunctionWrapper) // a forward marshalling instance method }; Interlocked.CompareExchange(ref _methods, methods, null); } public override IEnumerable<MethodDesc> GetMethods() { if (_methods == null) { InitializeMethods(); } return _methods; } public MethodDesc GetPInvokeDelegateWrapperMethod(PInvokeDelegateWrapperMethodKind kind) { if (_methods == null) { InitializeMethods(); } Debug.Assert((int)kind < _methods.Length); return _methods[(int)kind]; } } public enum PInvokeDelegateWrapperMethodKind : byte { Constructor = 0, Invoke = 1 } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]> // // 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.Config { using Internal; using System; using System.Collections.Generic; using System.Globalization; using System.Xml; /// <summary> /// Represents simple XML element with case-insensitive attribute semantics. /// </summary> internal class NLogXmlElement { /// <summary> /// Initializes a new instance of the <see cref="NLogXmlElement"/> class. /// </summary> /// <param name="inputUri">The input URI.</param> public NLogXmlElement(string inputUri) : this() { using (var reader = XmlReader.Create(inputUri)) { reader.MoveToContent(); this.Parse(reader); } } /// <summary> /// Initializes a new instance of the <see cref="NLogXmlElement"/> class. /// </summary> /// <param name="reader">The reader to initialize element from.</param> public NLogXmlElement(XmlReader reader) : this() { this.Parse(reader); } /// <summary> /// Prevents a default instance of the <see cref="NLogXmlElement"/> class from being created. /// </summary> private NLogXmlElement() { this.AttributeValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); this.Children = new List<NLogXmlElement>(); } /// <summary> /// Gets the element name. /// </summary> public string LocalName { get; private set; } /// <summary> /// Gets the dictionary of attribute values. /// </summary> public Dictionary<string, string> AttributeValues { get; private set; } /// <summary> /// Gets the collection of child elements. /// </summary> public IList<NLogXmlElement> Children { get; private set; } /// <summary> /// Gets the value of the element. /// </summary> public string Value { get; private set; } /// <summary> /// Returns children elements with the specified element name. /// </summary> /// <param name="elementName">Name of the element.</param> /// <returns>Children elements with the specified element name.</returns> public IEnumerable<NLogXmlElement> Elements(string elementName) { var result = new List<NLogXmlElement>(); foreach (var ch in this.Children) { if (ch.LocalName.Equals(elementName, StringComparison.OrdinalIgnoreCase)) { result.Add(ch); } } return result; } /// <summary> /// Gets the required attribute. /// </summary> /// <param name="attributeName">Name of the attribute.</param> /// <returns>Attribute value.</returns> /// <remarks>Throws if the attribute is not specified.</remarks> public string GetRequiredAttribute(string attributeName) { string value = this.GetOptionalAttribute(attributeName, null); if (value == null) { throw new NLogConfigurationException("Expected " + attributeName + " on <" + this.LocalName + " />"); } return value; } /// <summary> /// Gets the optional boolean attribute value. /// </summary> /// <param name="attributeName">Name of the attribute.</param> /// <param name="defaultValue">Default value to return if the attribute is not found.</param> /// <returns>Boolean attribute value or default.</returns> public bool GetOptionalBooleanAttribute(string attributeName, bool defaultValue) { string value; if (!this.AttributeValues.TryGetValue(attributeName, out value)) { return defaultValue; } return Convert.ToBoolean(value, CultureInfo.InvariantCulture); } /// <summary> /// Gets the optional boolean attribute value. If whitespace, then returning <c>null</c>. /// </summary> /// <param name="attributeName">Name of the attribute.</param> /// <param name="defaultValue">Default value to return if the attribute is not found.</param> /// <returns>Boolean attribute value or default.</returns> public bool? GetOptionalBooleanAttribute(string attributeName, bool? defaultValue) { string value; if (!this.AttributeValues.TryGetValue(attributeName, out value)) { //not defined, don't override default return defaultValue; } if (StringHelpers.IsNullOrWhiteSpace(value)) { //not default otherwise no difference between not defined and empty value. return null; } return Convert.ToBoolean(value, CultureInfo.InvariantCulture); } /// <summary> /// Gets the optional attribute value. /// </summary> /// <param name="attributeName">Name of the attribute.</param> /// <param name="defaultValue">The default value.</param> /// <returns>Value of the attribute or default value.</returns> public string GetOptionalAttribute(string attributeName, string defaultValue) { string value; if (!this.AttributeValues.TryGetValue(attributeName, out value)) { value = defaultValue; } return value; } /// <summary> /// Asserts that the name of the element is among specified element names. /// </summary> /// <param name="allowedNames">The allowed names.</param> public void AssertName(params string[] allowedNames) { foreach (var en in allowedNames) { if (this.LocalName.Equals(en, StringComparison.OrdinalIgnoreCase)) { return; } } throw new InvalidOperationException("Assertion failed. Expected element name '" + string.Join("|", allowedNames) + "', actual: '" + this.LocalName + "'."); } private void Parse(XmlReader reader) { if (reader.MoveToFirstAttribute()) { do { this.AttributeValues.Add(reader.LocalName, reader.Value); } while (reader.MoveToNextAttribute()); reader.MoveToElement(); } this.LocalName = reader.LocalName; if (!reader.IsEmptyElement) { while (reader.Read()) { if (reader.NodeType == XmlNodeType.EndElement) { break; } if (reader.NodeType == XmlNodeType.CDATA || reader.NodeType == XmlNodeType.Text) { this.Value += reader.Value; continue; } if (reader.NodeType == XmlNodeType.Element) { this.Children.Add(new NLogXmlElement(reader)); } } } } } }
using System.Data; using System.Data.Common; using System.Data.Odbc; using System.Threading.Tasks; namespace appMpower.Db { public class PooledCommand : IDbCommand { private IDbCommand _dbCommand; private PooledConnection _pooledConnection; public PooledCommand(PooledConnection pooledConnection) { _dbCommand = pooledConnection.CreateCommand(); _pooledConnection = pooledConnection; } public PooledCommand(string commandText, PooledConnection pooledConnection) { pooledConnection.GetCommand(commandText, this); } internal PooledCommand(IDbCommand dbCommand, PooledConnection pooledConnection) { _dbCommand = dbCommand; _pooledConnection = pooledConnection; } internal IDbCommand DbCommand { get { return _dbCommand; } set { _dbCommand = value; } } internal PooledConnection PooledConnection { get { return _pooledConnection; } set { _pooledConnection = value; } } public string CommandText { get { return _dbCommand.CommandText; } set { _dbCommand.CommandText = value; } } public int CommandTimeout { get { return _dbCommand.CommandTimeout; } set { _dbCommand.CommandTimeout = value; } } public CommandType CommandType { get { return _dbCommand.CommandType; } set { _dbCommand.CommandType = value; } } #nullable enable public IDbConnection? Connection { get { return _dbCommand.Connection; } set { _dbCommand.Connection = (IDbConnection?)value; } } #nullable disable public IDataParameterCollection Parameters { get { return _dbCommand.Parameters; } } #nullable enable public IDbTransaction? Transaction { get { return _dbCommand.Transaction; } set { _dbCommand.Transaction = (IDbTransaction?)value; } } #nullable disable public UpdateRowSource UpdatedRowSource { get { return _dbCommand.UpdatedRowSource; } set { _dbCommand.UpdatedRowSource = value; } } public void Cancel() { _dbCommand.Cancel(); } public IDbDataParameter CreateParameter() { return _dbCommand.CreateParameter(); } public IDbDataParameter CreateParameter(string name, DbType dbType, object value) { IDbDataParameter dbDataParameter = null; if (this.Parameters.Contains(name)) { dbDataParameter = this.Parameters[name] as IDbDataParameter; dbDataParameter.Value = value; } else { dbDataParameter = _dbCommand.CreateParameter(); dbDataParameter.ParameterName = name; dbDataParameter.DbType = dbType; dbDataParameter.Value = value; this.Parameters.Add(dbDataParameter); } return dbDataParameter; } public int ExecuteNonQuery() { return _dbCommand.ExecuteNonQuery(); } public IDataReader ExecuteReader() { return _dbCommand.ExecuteReader(); } public async Task<int> ExecuteNonQueryAsync() { if (DataProvider.IsOdbcConnection) return await (_dbCommand as OdbcCommand).ExecuteNonQueryAsync(); return await (_dbCommand as DbCommand).ExecuteNonQueryAsync(); } public async Task<DbDataReader> ExecuteReaderAsync(CommandBehavior behavior) { if (DataProvider.IsOdbcConnection) return await (_dbCommand as OdbcCommand).ExecuteReaderAsync(behavior); return await (_dbCommand as DbCommand).ExecuteReaderAsync(behavior); } public IDataReader ExecuteReader(CommandBehavior behavior) { return _dbCommand.ExecuteReader(behavior); } #nullable enable public object? ExecuteScalar() { return _dbCommand.ExecuteScalar(); } #nullable disable public void Prepare() { _dbCommand.Prepare(); } public void Release() { _pooledConnection.ReleaseCommand(this); } public void Dispose() { _pooledConnection.ReleaseCommand(this); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace PacSportCamp.Web.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// 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 System.Threading; using System.Threading.Tasks; using Xunit; namespace System.IO.Tests { public class BufferedStream_StreamAsync : StreamAsync { protected override Stream CreateStream() { return new BufferedStream(new MemoryStream()); } [Fact] public async Task ConcurrentOperationsAreSerialized() { byte[] data = Enumerable.Range(0, 1000).Select(i => unchecked((byte)i)).ToArray(); var mcaos = new ManuallyReleaseAsyncOperationsStream(); var stream = new BufferedStream(mcaos, 1); var tasks = new Task[4]; for (int i = 0; i < 4; i++) { tasks[i] = stream.WriteAsync(data, 250 * i, 250); } Assert.All(tasks, t => Assert.Equal(TaskStatus.WaitingForActivation, t.Status)); mcaos.Release(); await Task.WhenAll(tasks); stream.Position = 0; for (int i = 0; i < tasks.Length; i++) { Assert.Equal(i, stream.ReadByte()); } } [Fact] public void UnderlyingStreamThrowsExceptions() { var stream = new BufferedStream(new ThrowsExceptionFromAsyncOperationsStream()); Assert.Equal(TaskStatus.Faulted, stream.ReadAsync(new byte[1], 0, 1).Status); Assert.Equal(TaskStatus.Faulted, stream.WriteAsync(new byte[10000], 0, 10000).Status); stream.WriteByte(1); Assert.Equal(TaskStatus.Faulted, stream.FlushAsync().Status); } [Theory] [InlineData(false)] [InlineData(true)] public async Task CopyToTest_RequiresFlushingOfWrites(bool copyAsynchronously) { byte[] data = Enumerable.Range(0, 1000).Select(i => (byte)(i % 256)).ToArray(); var manualReleaseStream = new ManuallyReleaseAsyncOperationsStream(); var src = new BufferedStream(manualReleaseStream); src.Write(data, 0, data.Length); src.Position = 0; var dst = new MemoryStream(); data[0] = 42; src.WriteByte(42); dst.WriteByte(42); if (copyAsynchronously) { Task copyTask = src.CopyToAsync(dst); manualReleaseStream.Release(); await copyTask; } else { manualReleaseStream.Release(); src.CopyTo(dst); } Assert.Equal(data, dst.ToArray()); } [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] [InlineData(true, true)] public async Task CopyToTest_ReadBeforeCopy_CopiesAllData(bool copyAsynchronously, bool wrappedStreamCanSeek) { byte[] data = Enumerable.Range(0, 1000).Select(i => (byte)(i % 256)).ToArray(); var wrapped = new ManuallyReleaseAsyncOperationsStream(); wrapped.Release(); wrapped.Write(data, 0, data.Length); wrapped.Position = 0; wrapped.SetCanSeek(wrappedStreamCanSeek); var src = new BufferedStream(wrapped, 100); src.ReadByte(); var dst = new MemoryStream(); if (copyAsynchronously) { await src.CopyToAsync(dst); } else { src.CopyTo(dst); } var expected = new byte[data.Length - 1]; Array.Copy(data, 1, expected, 0, expected.Length); Assert.Equal(expected, dst.ToArray()); } } public class BufferedStream_StreamMethods : StreamMethods { protected override Stream CreateStream() { return new BufferedStream(new MemoryStream()); } protected override Stream CreateStream(int bufferSize) { return new BufferedStream(new MemoryStream(), bufferSize); } [Fact] public void ReadByte_ThenRead_EndOfStreamCorrectlyFound() { using (var s = new BufferedStream(new MemoryStream(new byte[] { 1, 2 }), 2)) { Assert.Equal(1, s.ReadByte()); Assert.Equal(2, s.ReadByte()); Assert.Equal(-1, s.ReadByte()); Assert.Equal(0, s.Read(new byte[1], 0, 1)); Assert.Equal(0, s.Read(new byte[1], 0, 1)); } } } public class BufferedStream_TestLeaveOpen : TestLeaveOpen { protected override Stream CreateStream() { return new BufferedStream(new MemoryStream()); } } public class StreamWriterWithBufferedStream_CloseTests : CloseTests { protected override Stream CreateStream() { return new BufferedStream(new MemoryStream()); } } public class StreamWriterWithBufferedStream_FlushTests : FlushTests { protected override Stream CreateStream() { return new BufferedStream(new MemoryStream()); } [Fact] public void WriteAfterRead_NonSeekableStream_Throws() { var wrapped = new WrappedMemoryStream(canRead: true, canWrite: true, canSeek: false, data: new byte[] { 1, 2, 3, 4, 5 }); var s = new BufferedStream(wrapped); s.Read(new byte[3], 0, 3); Assert.Throws<NotSupportedException>(() => s.Write(new byte[10], 0, 10)); } } public class StreamWriterWithBufferedStream_WriteTests : WriteTests { protected override Stream CreateStream() { return new BufferedStream(new MemoryStream()); } } public class StreamReaderWithBufferedStream_Tests : StreamReaderTests { protected override Stream CreateStream() { return new BufferedStream(new MemoryStream()); } protected override Stream GetSmallStream() { byte[] testData = new byte[] { 72, 69, 76, 76, 79 }; return new BufferedStream(new MemoryStream(testData)); } protected override Stream GetLargeStream() { byte[] testData = new byte[] { 72, 69, 76, 76, 79 }; List<byte> data = new List<byte>(); for (int i = 0; i < 1000; i++) { data.AddRange(testData); } return new BufferedStream(new MemoryStream(data.ToArray())); } } public class BinaryWriterWithBufferedStream_Tests : BinaryWriterTests { protected override Stream CreateStream() { return new BufferedStream(new MemoryStream()); } [Fact] public override void BinaryWriter_FlushTests() { // [] Check that flush updates the underlying stream using (Stream memstr2 = CreateStream()) using (BinaryWriter bw2 = new BinaryWriter(memstr2)) { string str = "HelloWorld"; int expectedLength = str.Length + 1; // 1 for 7-bit encoded length bw2.Write(str); Assert.Equal(expectedLength, memstr2.Length); bw2.Flush(); Assert.Equal(expectedLength, memstr2.Length); } // [] Flushing a closed writer may throw an exception depending on the underlying stream using (Stream memstr2 = CreateStream()) { BinaryWriter bw2 = new BinaryWriter(memstr2); bw2.Dispose(); Assert.Throws<ObjectDisposedException>(() => bw2.Flush()); } } } public class BinaryWriterWithBufferedStream_WriteByteCharTests : BinaryWriter_WriteByteCharTests { protected override Stream CreateStream() { return new BufferedStream(new MemoryStream()); } } public class BinaryWriterWithBufferedStream_WriteTests : BinaryWriter_WriteTests { protected override Stream CreateStream() { return new BufferedStream(new MemoryStream()); } } internal sealed class ManuallyReleaseAsyncOperationsStream : Stream { private readonly MemoryStream _stream = new MemoryStream(); private readonly TaskCompletionSource<bool> _tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); private bool _canSeek = true; public override bool CanSeek => _canSeek; public override bool CanRead => _stream.CanRead; public override bool CanWrite => _stream.CanWrite; public override long Length => _stream.Length; public override long Position { get => _stream.Position; set => _stream.Position = value; } public void SetCanSeek(bool canSeek) => _canSeek = canSeek; public void Release() { _tcs.SetResult(true); } public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { await _tcs.Task; return await _stream.ReadAsync(buffer, offset, count, cancellationToken); } public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { await _tcs.Task; await _stream.WriteAsync(buffer, offset, count, cancellationToken); } public override async Task FlushAsync(CancellationToken cancellationToken) { await _tcs.Task; await _stream.FlushAsync(cancellationToken); } public override void Flush() => _stream.Flush(); public override int Read(byte[] buffer, int offset, int count) => _stream.Read(buffer, offset, count); public override long Seek(long offset, SeekOrigin origin) => _stream.Seek(offset, origin); public override void SetLength(long value) => _stream.SetLength(value); public override void Write(byte[] buffer, int offset, int count) => _stream.Write(buffer, offset, count); } internal sealed class ThrowsExceptionFromAsyncOperationsStream : MemoryStream { public override int Read(byte[] buffer, int offset, int count) => throw new InvalidOperationException("Exception from ReadAsync"); public override void Write(byte[] buffer, int offset, int count) => throw new InvalidOperationException("Exception from ReadAsync"); public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => throw new InvalidOperationException("Exception from ReadAsync"); public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => throw new InvalidOperationException("Exception from WriteAsync"); public override Task FlushAsync(CancellationToken cancellationToken) => throw new InvalidOperationException("Exception from FlushAsync"); } public class BufferedStream_NS17 { protected Stream CreateStream() { return new BufferedStream(new MemoryStream()); } public void EndCallback(IAsyncResult ar) { } [Fact] public void BeginEndReadTest() { Stream stream = CreateStream(); IAsyncResult result = stream.BeginRead(new byte[1], 0, 1, new AsyncCallback(EndCallback), new object()); stream.EndRead(result); } [Fact] public void BeginEndWriteTest() { Stream stream = CreateStream(); IAsyncResult result = stream.BeginWrite(new byte[1], 0, 1, new AsyncCallback(EndCallback), new object()); stream.EndWrite(result); } } }
// 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.Threading; using System.Threading.Tasks; namespace System.Security.Cryptography { public class CryptoStream : Stream, IDisposable { // Member variables private readonly Stream _stream; private readonly ICryptoTransform _transform; private readonly CryptoStreamMode _transformMode; private byte[] _inputBuffer; // read from _stream before _Transform private int _inputBufferIndex; private int _inputBlockSize; private byte[] _outputBuffer; // buffered output of _Transform private int _outputBufferIndex; private int _outputBlockSize; private bool _canRead; private bool _canWrite; private bool _finalBlockTransformed; private SemaphoreSlim _lazyAsyncActiveSemaphore; private readonly bool _leaveOpen; // Constructors public CryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode) : this(stream, transform, mode, false) { } public CryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode, bool leaveOpen) { _stream = stream; _transformMode = mode; _transform = transform; _leaveOpen = leaveOpen; switch (_transformMode) { case CryptoStreamMode.Read: if (!(_stream.CanRead)) throw new ArgumentException(SR.Format(SR.Argument_StreamNotReadable, nameof(stream))); _canRead = true; break; case CryptoStreamMode.Write: if (!(_stream.CanWrite)) throw new ArgumentException(SR.Format(SR.Argument_StreamNotWritable, nameof(stream))); _canWrite = true; break; default: throw new ArgumentException(SR.Argument_InvalidValue); } InitializeBuffer(); } public override bool CanRead { get { return _canRead; } } // For now, assume we can never seek into the middle of a cryptostream // and get the state right. This is too strict. public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return _canWrite; } } public override long Length { get { throw new NotSupportedException(SR.NotSupported_UnseekableStream); } } public override long Position { get { throw new NotSupportedException(SR.NotSupported_UnseekableStream); } set { throw new NotSupportedException(SR.NotSupported_UnseekableStream); } } public bool HasFlushedFinalBlock { get { return _finalBlockTransformed; } } // The flush final block functionality used to be part of close, but that meant you couldn't do something like this: // MemoryStream ms = new MemoryStream(); // CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); // cs.Write(foo, 0, foo.Length); // cs.Close(); // and get the encrypted data out of ms, because the cs.Close also closed ms and the data went away. // so now do this: // cs.Write(foo, 0, foo.Length); // cs.FlushFinalBlock() // which can only be called once // byte[] ciphertext = ms.ToArray(); // cs.Close(); public void FlushFinalBlock() { if (_finalBlockTransformed) throw new NotSupportedException(SR.Cryptography_CryptoStream_FlushFinalBlockTwice); // We have to process the last block here. First, we have the final block in _InputBuffer, so transform it byte[] finalBytes = _transform.TransformFinalBlock(_inputBuffer, 0, _inputBufferIndex); _finalBlockTransformed = true; // Now, write out anything sitting in the _OutputBuffer... if (_canWrite && _outputBufferIndex > 0) { _stream.Write(_outputBuffer, 0, _outputBufferIndex); _outputBufferIndex = 0; } // Write out finalBytes if (_canWrite) _stream.Write(finalBytes, 0, finalBytes.Length); // If the inner stream is a CryptoStream, then we want to call FlushFinalBlock on it too, otherwise just Flush. CryptoStream innerCryptoStream = _stream as CryptoStream; if (innerCryptoStream != null) { if (!innerCryptoStream.HasFlushedFinalBlock) { innerCryptoStream.FlushFinalBlock(); } } else { _stream.Flush(); } // zeroize plain text material before returning if (_inputBuffer != null) Array.Clear(_inputBuffer, 0, _inputBuffer.Length); if (_outputBuffer != null) Array.Clear(_outputBuffer, 0, _outputBuffer.Length); return; } public override void Flush() { return; } public override Task FlushAsync(CancellationToken cancellationToken) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Flush() which a subclass might have overridden. To be safe // we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Flush) when we are not sure. if (GetType() != typeof(CryptoStream)) return base.FlushAsync(cancellationToken); return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask; } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(SR.NotSupported_UnseekableStream); } public override void SetLength(long value) { throw new NotSupportedException(SR.NotSupported_UnseekableStream); } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { CheckReadArguments(buffer, offset, count); return ReadAsyncInternal(buffer, offset, count, cancellationToken); } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), callback, state); public override int EndRead(IAsyncResult asyncResult) => TaskToApm.End<int>(asyncResult); private async Task<int> ReadAsyncInternal(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { // To avoid a race with a stream's position pointer & generating race // conditions with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread if it does a second IO request until the first one completes. SemaphoreSlim semaphore = AsyncActiveSemaphore; await semaphore.WaitAsync().ForceAsync(); try { return await ReadAsyncCore(buffer, offset, count, cancellationToken, useAsync: true); } finally { semaphore.Release(); } } public override int ReadByte() { // If we have enough bytes in the buffer such that reading 1 will still leave bytes // in the buffer, then take the faster path of simply returning the first byte. // (This unfortunately still involves shifting down the bytes in the buffer, as it // does in Read. If/when that's fixed for Read, it should be fixed here, too.) if (_outputBufferIndex > 1) { byte b = _outputBuffer[0]; Buffer.BlockCopy(_outputBuffer, 1, _outputBuffer, 0, _outputBufferIndex - 1); _outputBufferIndex -= 1; return b; } // Otherwise, fall back to the more robust but expensive path of using the base // Stream.ReadByte to call Read. return base.ReadByte(); } public override void WriteByte(byte value) { // If there's room in the input buffer such that even with this byte we wouldn't // complete a block, simply add the byte to the input buffer. if (_inputBufferIndex + 1 < _inputBlockSize) { _inputBuffer[_inputBufferIndex++] = value; return; } // Otherwise, the logic is complicated, so we simply fall back to the base // implementation that'll use Write. base.WriteByte(value); } public override int Read(byte[] buffer, int offset, int count) { CheckReadArguments(buffer, offset, count); return ReadAsyncCore(buffer, offset, count, default(CancellationToken), useAsync: false).ConfigureAwait(false).GetAwaiter().GetResult(); } private void CheckReadArguments(byte[] buffer, int offset, int count) { if (!CanRead) throw new NotSupportedException(SR.NotSupported_UnreadableStream); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); } private async Task<int> ReadAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken, bool useAsync) { // read <= count bytes from the input stream, transforming as we go. // Basic idea: first we deliver any bytes we already have in the // _OutputBuffer, because we know they're good. Then, if asked to deliver // more bytes, we read & transform a block at a time until either there are // no bytes ready or we've delivered enough. int bytesToDeliver = count; int currentOutputIndex = offset; if (_outputBufferIndex != 0) { // we have some already-transformed bytes in the output buffer if (_outputBufferIndex <= count) { Buffer.BlockCopy(_outputBuffer, 0, buffer, offset, _outputBufferIndex); bytesToDeliver -= _outputBufferIndex; currentOutputIndex += _outputBufferIndex; _outputBufferIndex = 0; } else { Buffer.BlockCopy(_outputBuffer, 0, buffer, offset, count); Buffer.BlockCopy(_outputBuffer, count, _outputBuffer, 0, _outputBufferIndex - count); _outputBufferIndex -= count; return (count); } } // _finalBlockTransformed == true implies we're at the end of the input stream // if we got through the previous if block then _OutputBufferIndex = 0, meaning // we have no more transformed bytes to give // so return count-bytesToDeliver, the amount we were able to hand back // eventually, we'll just always return 0 here because there's no more to read if (_finalBlockTransformed) { return (count - bytesToDeliver); } // ok, now loop until we've delivered enough or there's nothing available int amountRead = 0; int numOutputBytes; // OK, see first if it's a multi-block transform and we can speed up things if (bytesToDeliver > _outputBlockSize) { if (_transform.CanTransformMultipleBlocks) { int BlocksToProcess = bytesToDeliver / _outputBlockSize; int numWholeBlocksInBytes = BlocksToProcess * _inputBlockSize; byte[] tempInputBuffer = new byte[numWholeBlocksInBytes]; // get first the block already read Buffer.BlockCopy(_inputBuffer, 0, tempInputBuffer, 0, _inputBufferIndex); amountRead = _inputBufferIndex; amountRead += useAsync ? await _stream.ReadAsync(tempInputBuffer, _inputBufferIndex, numWholeBlocksInBytes - _inputBufferIndex, cancellationToken) : _stream.Read(tempInputBuffer, _inputBufferIndex, numWholeBlocksInBytes - _inputBufferIndex); _inputBufferIndex = 0; if (amountRead <= _inputBlockSize) { _inputBuffer = tempInputBuffer; _inputBufferIndex = amountRead; goto slow; } // Make amountRead an integral multiple of _InputBlockSize int numWholeReadBlocksInBytes = (amountRead / _inputBlockSize) * _inputBlockSize; int numIgnoredBytes = amountRead - numWholeReadBlocksInBytes; if (numIgnoredBytes != 0) { _inputBufferIndex = numIgnoredBytes; Buffer.BlockCopy(tempInputBuffer, numWholeReadBlocksInBytes, _inputBuffer, 0, numIgnoredBytes); } byte[] tempOutputBuffer = new byte[(numWholeReadBlocksInBytes / _inputBlockSize) * _outputBlockSize]; numOutputBytes = _transform.TransformBlock(tempInputBuffer, 0, numWholeReadBlocksInBytes, tempOutputBuffer, 0); Buffer.BlockCopy(tempOutputBuffer, 0, buffer, currentOutputIndex, numOutputBytes); // Now, tempInputBuffer and tempOutputBuffer are no more needed, so zeroize them to protect plain text Array.Clear(tempInputBuffer, 0, tempInputBuffer.Length); Array.Clear(tempOutputBuffer, 0, tempOutputBuffer.Length); bytesToDeliver -= numOutputBytes; currentOutputIndex += numOutputBytes; } } slow: // try to fill _InputBuffer so we have something to transform while (bytesToDeliver > 0) { while (_inputBufferIndex < _inputBlockSize) { amountRead = useAsync ? await _stream.ReadAsync(_inputBuffer, _inputBufferIndex, _inputBlockSize - _inputBufferIndex, cancellationToken) : _stream.Read(_inputBuffer, _inputBufferIndex, _inputBlockSize - _inputBufferIndex); // first, check to see if we're at the end of the input stream if (amountRead == 0) goto ProcessFinalBlock; _inputBufferIndex += amountRead; } numOutputBytes = _transform.TransformBlock(_inputBuffer, 0, _inputBlockSize, _outputBuffer, 0); _inputBufferIndex = 0; if (bytesToDeliver >= numOutputBytes) { Buffer.BlockCopy(_outputBuffer, 0, buffer, currentOutputIndex, numOutputBytes); currentOutputIndex += numOutputBytes; bytesToDeliver -= numOutputBytes; } else { Buffer.BlockCopy(_outputBuffer, 0, buffer, currentOutputIndex, bytesToDeliver); _outputBufferIndex = numOutputBytes - bytesToDeliver; Buffer.BlockCopy(_outputBuffer, bytesToDeliver, _outputBuffer, 0, _outputBufferIndex); return count; } } return count; ProcessFinalBlock: // if so, then call TransformFinalBlock to get whatever is left byte[] finalBytes = _transform.TransformFinalBlock(_inputBuffer, 0, _inputBufferIndex); // now, since _OutputBufferIndex must be 0 if we're in the while loop at this point, // reset it to be what we just got back _outputBuffer = finalBytes; _outputBufferIndex = finalBytes.Length; // set the fact that we've transformed the final block _finalBlockTransformed = true; // now, return either everything we just got or just what's asked for, whichever is smaller if (bytesToDeliver < _outputBufferIndex) { Buffer.BlockCopy(_outputBuffer, 0, buffer, currentOutputIndex, bytesToDeliver); _outputBufferIndex -= bytesToDeliver; Buffer.BlockCopy(_outputBuffer, bytesToDeliver, _outputBuffer, 0, _outputBufferIndex); return (count); } else { Buffer.BlockCopy(_outputBuffer, 0, buffer, currentOutputIndex, _outputBufferIndex); bytesToDeliver -= _outputBufferIndex; _outputBufferIndex = 0; return (count - bytesToDeliver); } } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { CheckWriteArguments(buffer, offset, count); return WriteAsyncInternal(buffer, offset, count, cancellationToken); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), callback, state); public override void EndWrite(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); private async Task WriteAsyncInternal(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { // To avoid a race with a stream's position pointer & generating race // conditions with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread if it does a second IO request until the first one completes. SemaphoreSlim semaphore = AsyncActiveSemaphore; await semaphore.WaitAsync().ForceAsync(); try { await WriteAsyncCore(buffer, offset, count, cancellationToken, useAsync: true); } finally { semaphore.Release(); } } public override void Write(byte[] buffer, int offset, int count) { CheckWriteArguments(buffer, offset, count); WriteAsyncCore(buffer, offset, count, default(CancellationToken), useAsync: false).GetAwaiter().GetResult(); } private void CheckWriteArguments(byte[] buffer, int offset, int count) { if (!CanWrite) throw new NotSupportedException(SR.NotSupported_UnwritableStream); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen); } private async Task WriteAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken, bool useAsync) { // write <= count bytes to the output stream, transforming as we go. // Basic idea: using bytes in the _InputBuffer first, make whole blocks, // transform them, and write them out. Cache any remaining bytes in the _InputBuffer. int bytesToWrite = count; int currentInputIndex = offset; // if we have some bytes in the _InputBuffer, we have to deal with those first, // so let's try to make an entire block out of it if (_inputBufferIndex > 0) { if (count >= _inputBlockSize - _inputBufferIndex) { // we have enough to transform at least a block, so fill the input block Buffer.BlockCopy(buffer, offset, _inputBuffer, _inputBufferIndex, _inputBlockSize - _inputBufferIndex); currentInputIndex += (_inputBlockSize - _inputBufferIndex); bytesToWrite -= (_inputBlockSize - _inputBufferIndex); _inputBufferIndex = _inputBlockSize; // Transform the block and write it out } else { // not enough to transform a block, so just copy the bytes into the _InputBuffer // and return Buffer.BlockCopy(buffer, offset, _inputBuffer, _inputBufferIndex, count); _inputBufferIndex += count; return; } } // If the OutputBuffer has anything in it, write it out if (_outputBufferIndex > 0) { if (useAsync) await _stream.WriteAsync(_outputBuffer, 0, _outputBufferIndex, cancellationToken); else _stream.Write(_outputBuffer, 0, _outputBufferIndex); _outputBufferIndex = 0; } // At this point, either the _InputBuffer is full, empty, or we've already returned. // If full, let's process it -- we now know the _OutputBuffer is empty int numOutputBytes; if (_inputBufferIndex == _inputBlockSize) { numOutputBytes = _transform.TransformBlock(_inputBuffer, 0, _inputBlockSize, _outputBuffer, 0); // write out the bytes we just got if (useAsync) await _stream.WriteAsync(_outputBuffer, 0, numOutputBytes, cancellationToken); else _stream.Write(_outputBuffer, 0, numOutputBytes); // reset the _InputBuffer _inputBufferIndex = 0; } while (bytesToWrite > 0) { if (bytesToWrite >= _inputBlockSize) { // We have at least an entire block's worth to transform // If the transform will handle multiple blocks at once, do that if (_transform.CanTransformMultipleBlocks) { int numWholeBlocks = bytesToWrite / _inputBlockSize; int numWholeBlocksInBytes = numWholeBlocks * _inputBlockSize; byte[] _tempOutputBuffer = new byte[numWholeBlocks * _outputBlockSize]; numOutputBytes = _transform.TransformBlock(buffer, currentInputIndex, numWholeBlocksInBytes, _tempOutputBuffer, 0); if (useAsync) await _stream.WriteAsync(_tempOutputBuffer, 0, numOutputBytes, cancellationToken); else _stream.Write(_tempOutputBuffer, 0, numOutputBytes); currentInputIndex += numWholeBlocksInBytes; bytesToWrite -= numWholeBlocksInBytes; } else { // do it the slow way numOutputBytes = _transform.TransformBlock(buffer, currentInputIndex, _inputBlockSize, _outputBuffer, 0); if (useAsync) await _stream.WriteAsync(_outputBuffer, 0, numOutputBytes, cancellationToken); else _stream.Write(_outputBuffer, 0, numOutputBytes); currentInputIndex += _inputBlockSize; bytesToWrite -= _inputBlockSize; } } else { // In this case, we don't have an entire block's worth left, so store it up in the // input buffer, which by now must be empty. Buffer.BlockCopy(buffer, currentInputIndex, _inputBuffer, 0, bytesToWrite); _inputBufferIndex += bytesToWrite; return; } } return; } public void Clear() { Close(); } protected override void Dispose(bool disposing) { try { if (disposing) { if (!_finalBlockTransformed) { FlushFinalBlock(); } if (!_leaveOpen) { _stream.Dispose(); } } } finally { try { // Ensure we don't try to transform the final block again if we get disposed twice // since it's null after this _finalBlockTransformed = true; // we need to clear all the internal buffers if (_inputBuffer != null) Array.Clear(_inputBuffer, 0, _inputBuffer.Length); if (_outputBuffer != null) Array.Clear(_outputBuffer, 0, _outputBuffer.Length); _inputBuffer = null; _outputBuffer = null; _canRead = false; _canWrite = false; } finally { base.Dispose(disposing); } } } // Private methods private void InitializeBuffer() { if (_transform != null) { _inputBlockSize = _transform.InputBlockSize; _inputBuffer = new byte[_inputBlockSize]; _outputBlockSize = _transform.OutputBlockSize; _outputBuffer = new byte[_outputBlockSize]; } } private SemaphoreSlim AsyncActiveSemaphore { get { // Lazily-initialize _lazyAsyncActiveSemaphore. As we're never accessing the SemaphoreSlim's // WaitHandle, we don't need to worry about Disposing it. return LazyInitializer.EnsureInitialized(ref _lazyAsyncActiveSemaphore, () => new SemaphoreSlim(1, 1)); } } } }
using Microsoft.Xna.Framework.Graphics; using System; using System.Diagnostics; #if IOS using MonoTouch.ObjCRuntime; #endif namespace CocosSharp { /// <summary> /// Modified from http://stackoverflow.com/questions/10889743/cocos2d-2-0-3-numbers-on-the-bottom-left /// by Steffen Itterheim: /// /// 5623459 -- memory consumption in bytes /// 3 -- garbage collection counter (always 0 when in iOS simulator, see below) /// 082 -- number of draw calls /// 0.023 -- time it took to update the frame /// 0.016 -- time it took to draw the frame /// 60.0 -- frames per second /// /// The Draw Call number is the number of draw calls (which is fairly high). Typically each node that renders /// something on the screen (sprites, labels, particle fx, etc) increases that number by one. If you use /// a CCSpriteBatchNode and add 100 sprites to it, it will increase the draw call only by 1. /// /// 82 is a pretty high draw call number - depending on the game's complexity and assuming it is well optimized to /// reduce draw calls, the number of draw calls should be around 10 to 40. Assuming all 82 draw calls are sprites, /// then creating a texture atlas out of the sprite images (use TexturePacker, Zwoptex, SpriteHelper) in order to /// use CCSpriteBatchNode you could reduce the number of draw calls to 1. Draw calls are expensive, so it is very /// important to keep that number down. /// /// The time it took to render a frame is in milliseconds. Since you need to draw a new frame every 0.016666666 /// seconds in order to achieve 60 frames per second (1/60 = 0,0166...) this number can tell you how close your game /// is to dropping below 60 fps. Yours is pretty close, you have practically no room left for additional game logic /// or visuals before the framerate will drop below 60 fps. /// /// The last number is the number of frames per second. This value, like the previous one, is averaged over several /// frames so that it doesn't fluctuate as much (makes it hard to read). /// /// PS: one other thing to keep in mind is that the bottom two values become misleading can not be compared for /// framerates below 15 fps. For example cocos2d might show 0.0 for the time it took to render a frame at such /// a low framerate. /// /// There is a special case for Xamarin iOS monotouch on emulator where they aggresively call /// garbage collection themselves on the simulator. This should not affect the devices though. /// So we check if we are running on a Device and only update the counters if we are. /// </summary> public class CCStats { bool isInitialized, isEnabled; bool isCheckGC = true; uint totalFrames = 0; uint updateCount; uint totalDrawCount; int gcCounter; float deltaAll = 0.0f; float totalDrawTime; float totalUpdateTime; float startTime; Stopwatch stopwatch; WeakReference gcWeakRef = new WeakReference(new object()); CCLabelAtlas fpsLabel; CCLabelAtlas updateTimeLabel; CCLabelAtlas drawTimeLabel; CCLabelAtlas drawCallLabel; CCLabelAtlas memoryLabel; CCLabelAtlas gcLabel; #region Properties public bool IsInitialized { get { return isInitialized; } } public bool IsEnabled { get { return isEnabled; } set { isEnabled = value; if (value) { stopwatch.Reset(); stopwatch.Start(); } } } #endregion Properties // Initialize the stats display. public void Initialize() { if (!isInitialized) { // There is a special case for Xamarin iOS monotouch on emulator where they aggresively call // garbage collection themselves on the simulator. This should not affect the devices though. // So we check if we are running on a Device and only update the counters if we are. #if IOS if (Runtime.Arch != Arch.DEVICE) isCheckGC = false; #endif CCTexture2D texture; CCTextureCache textureCache = CCTextureCache.SharedTextureCache; stopwatch = new Stopwatch(); try { texture = !textureCache.Contains ("cc_fps_images") ? textureCache.AddImage (CCFPSImage.PngData, "cc_fps_images", CCSurfaceFormat.Bgra4444) : textureCache["cc_fps_images"]; if (texture == null || (texture.ContentSizeInPixels.Width == 0 && texture.ContentSizeInPixels.Height == 0)) { CCLog.Log ("CCStats: Failed to create stats texture"); return; } } catch (Exception ex) { // MonoGame may not allow texture.fromstream, // so catch this exception here and disable the stats CCLog.Log ("CCStats: Failed to create stats texture:"); if(ex!=null) CCLog.Log (ex.ToString ()); return; } try { texture.IsAntialiased = false; // disable antialiasing so the labels are always sharp fpsLabel = new CCLabelAtlas ("00.0", texture, 4, 8, '.'); updateTimeLabel = new CCLabelAtlas ("0.000", texture, 4, 8, '.'); drawTimeLabel = new CCLabelAtlas ("0.000", texture, 4, 8, '.'); drawCallLabel = new CCLabelAtlas ("000", texture, 4, 8, '.'); memoryLabel = new CCLabelAtlas ("0", texture, 4, 8, '.'); memoryLabel.Color = new CCColor3B (35, 185, 255); gcLabel = new CCLabelAtlas ("0", texture, 4, 8, '.'); gcLabel.Color = new CCColor3B (255, 196, 54); } catch (Exception ex) { CCLog.Log ("CCStats: Failed to create stats labels:"); if(ex !=null) CCLog.Log (ex.ToString ()); return; } } var factor = 1.0f; var pos = CCPoint.Zero; //CCApplication.SharedApplication.MainWindowDirector.VisibleOrigin; fpsLabel.Scale = factor; updateTimeLabel.Scale = factor; drawTimeLabel.Scale = factor; drawCallLabel.Scale = factor; memoryLabel.Scale = factor; gcLabel.Scale = factor; memoryLabel.Position = new CCPoint (4 * factor, 44 * factor) + pos; gcLabel.Position = new CCPoint (4 * factor, 36 * factor) + pos; drawCallLabel.Position = new CCPoint (4 * factor, 28 * factor) + pos; updateTimeLabel.Position = new CCPoint (4 * factor, 20 * factor) + pos; drawTimeLabel.Position = new CCPoint (4 * factor, 12 * factor) + pos; fpsLabel.Position = new CCPoint (4 * factor, 4 * factor) + pos; isInitialized = true; } public void UpdateStart () { if (isEnabled) startTime = (float)stopwatch.Elapsed.TotalMilliseconds; } public void UpdateEnd (float delta) { if (isEnabled) { deltaAll += delta; if (isEnabled) { updateCount++; totalUpdateTime += (float)stopwatch.Elapsed.TotalMilliseconds - startTime; } } } public void Draw (CCWindow window) { if (isEnabled) { totalFrames++; totalDrawCount++; totalDrawTime += (float)stopwatch.Elapsed.TotalMilliseconds - startTime; if (isCheckGC && !gcWeakRef.IsAlive) { gcCounter++; gcWeakRef = new WeakReference (new object ()); } if (isInitialized) { if (deltaAll > CCMacros.CCDirectorStatsUpdateIntervalInSeconds) { fpsLabel.Text = (String.Format ("{0:00.0}", totalDrawCount / deltaAll)); updateTimeLabel.Text = (String.Format ("{0:0.000}", totalUpdateTime / updateCount)); drawTimeLabel.Text = (String.Format ("{0:0.000}", totalDrawTime / totalDrawCount)); drawCallLabel.Text = (String.Format ("{0:000}", window.DrawManager.DrawCount)); deltaAll = totalDrawTime = totalUpdateTime = 0; totalDrawCount = updateCount = 0; memoryLabel.Text = String.Format ("{0}", GC.GetTotalMemory (false)); gcLabel.Text = String.Format ("{0}", gcCounter); } drawCallLabel.Visit (); fpsLabel.Visit (); updateTimeLabel.Visit (); drawTimeLabel.Visit (); memoryLabel.Visit (); gcLabel.Visit (); } } } } public static class CCFPSImage { public static byte[] PngData = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x08, 0x08, 0x04, 0x00, 0x00, 0x00, 0xE3, 0x6B, 0x31, 0x54, 0x00, 0x00, 0x00, 0xA4, 0x49, 0x44, 0x41, 0x54, 0x78, 0x01, 0xED, 0x8F, 0x31, 0xAE, 0xC6, 0x20, 0x0C, 0x83, 0x7D, 0x8F, 0xEC, 0xB9, 0xBF, 0x72, 0xA1, 0x8E, 0x9D, 0x19, 0xFF, 0xC9, 0x0F, 0x03, 0x96, 0x5A, 0x16, 0x7A, 0x80, 0x97, 0xC8, 0xF9, 0x64, 0xE3, 0x05, 0x3C, 0xE7, 0x7F, 0x48, 0x82, 0x45, 0x76, 0x61, 0x5D, 0xD1, 0xDE, 0xB4, 0xE8, 0xFE, 0xA0, 0xDF, 0x6B, 0xE3, 0x61, 0x5F, 0xE6, 0x47, 0x64, 0x57, 0x48, 0xC0, 0xB8, 0x9A, 0x91, 0x99, 0xEA, 0x58, 0x5A, 0x65, 0xA2, 0xDF, 0x77, 0xE1, 0xFB, 0x34, 0x36, 0x20, 0x1B, 0xA7, 0x80, 0x75, 0xAB, 0xE7, 0x35, 0xBD, 0xD8, 0xA8, 0x5D, 0xAC, 0x06, 0x53, 0xAB, 0xDC, 0x7D, 0x51, 0x1E, 0x5F, 0xE7, 0xE6, 0x0D, 0xA4, 0x88, 0x94, 0x00, 0x5F, 0x44, 0x67, 0xCC, 0x8E, 0xE8, 0xF7, 0xC1, 0x58, 0x7D, 0xBF, 0x3B, 0x93, 0x17, 0x13, 0xA7, 0xB9, 0x78, 0x61, 0xEC, 0x2A, 0x5F, 0xD5, 0x93, 0x42, 0xF6, 0xAB, 0xC5, 0x8B, 0x35, 0x3B, 0xEA, 0xDA, 0xBB, 0xEF, 0xDC, 0xFE, 0xD9, 0x3F, 0x4D, 0x6E, 0xF4, 0x8F, 0x53, 0xBB, 0x31, 0x1E, 0x5D, 0xFB, 0x78, 0xE5, 0xF6, 0x7E, 0x3F, 0xCC, 0x1F, 0xBE, 0x5D, 0x06, 0xEE, 0x39, 0x9F, 0xA8, 0xC7, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82 }; } }
#if !NET452 && !NET461 using System; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using FluentAssertions; using Moq; using NFluent; using RestEase; using WireMock.Admin.Mappings; using WireMock.Admin.Settings; using WireMock.Client; using WireMock.Handlers; using WireMock.Logging; using WireMock.Models; using WireMock.Server; using WireMock.Settings; using Xunit; namespace WireMock.Net.Tests { public class WireMockAdminApiTests { [Fact] public async Task IWireMockAdminApi_GetSettingsAsync() { // Arrange var server = WireMockServer.StartWithAdminInterface(); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]); // Act var settings = await api.GetSettingsAsync().ConfigureAwait(false); Check.That(settings).IsNotNull(); } [Fact] public async Task IWireMockAdminApi_PostSettingsAsync() { // Arrange var server = WireMockServer.StartWithAdminInterface(); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]); // Act var settings = new SettingsModel(); var status = await api.PostSettingsAsync(settings).ConfigureAwait(false); Check.That(status.Status).Equals("Settings updated"); } [Fact] public async Task IWireMockAdminApi_PutSettingsAsync() { // Arrange var server = WireMockServer.StartWithAdminInterface(); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]); // Act var settings = new SettingsModel(); var status = await api.PutSettingsAsync(settings).ConfigureAwait(false); Check.That(status.Status).Equals("Settings updated"); } // https://github.com/WireMock-Net/WireMock.Net/issues/325 [Fact] public async Task IWireMockAdminApi_PutMappingAsync() { // Arrange var server = WireMockServer.StartWithAdminInterface(); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]); // Act var model = new MappingModel { Request = new RequestModel { Path = "/1" }, Response = new ResponseModel { Body = "txt", StatusCode = 200 }, Priority = 500, Title = "test" }; var result = await api.PutMappingAsync(new Guid("a0000000-0000-0000-0000-000000000000"), model).ConfigureAwait(false); // Assert Check.That(result).IsNotNull(); Check.That(result.Status).Equals("Mapping added or updated"); Check.That(result.Guid).IsNotNull(); var mapping = server.Mappings.Single(m => m.Priority == 500); Check.That(mapping).IsNotNull(); Check.That(mapping.Title).Equals("test"); server.Stop(); } [Theory] [InlineData(null, null)] [InlineData(-1, -1)] [InlineData(0, 0)] [InlineData(200, 200)] [InlineData("200", "200")] public async Task IWireMockAdminApi_PostMappingAsync_WithStatusCode(object statusCode, object expectedStatusCode) { // Arrange var server = WireMockServer.StartWithAdminInterface(); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]); // Act var model = new MappingModel { Request = new RequestModel { Path = "/1" }, Response = new ResponseModel { Body = "txt", StatusCode = statusCode }, Priority = 500, Title = "test" }; var result = await api.PostMappingAsync(model).ConfigureAwait(false); // Assert Check.That(result).IsNotNull(); Check.That(result.Status).IsNotNull(); Check.That(result.Guid).IsNotNull(); var mapping = server.Mappings.Single(m => m.Priority == 500); Check.That(mapping).IsNotNull(); Check.That(mapping.Title).Equals("test"); var response = await mapping.ProvideResponseAsync(new RequestMessage(new UrlDetails("http://localhost/1"), "GET", "")).ConfigureAwait(false); Check.That(response.Message.StatusCode).Equals(expectedStatusCode); server.Stop(); } [Fact] public async Task IWireMockAdminApi_PostMappingsAsync() { // Arrange var server = WireMockServer.StartWithAdminInterface(); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]); // Act var model1 = new MappingModel { Request = new RequestModel { Path = "/1" }, Response = new ResponseModel { Body = "txt 1" }, Title = "test 1" }; var model2 = new MappingModel { Request = new RequestModel { Path = "/2" }, Response = new ResponseModel { Body = "txt 2" }, Title = "test 2" }; var result = await api.PostMappingsAsync(new[] { model1, model2 }).ConfigureAwait(false); // Assert Check.That(result).IsNotNull(); Check.That(result.Status).IsNotNull(); Check.That(result.Guid).IsNull(); Check.That(server.Mappings.Where(m => !m.IsAdminInterface)).HasSize(2); server.Stop(); } [Fact] public async Task IWireMockAdminApi_FindRequestsAsync() { // Arrange var server = WireMockServer.Start(new WireMockServerSettings { StartAdminInterface = true, Logger = new WireMockNullLogger() }); var serverUrl = "http://localhost:" + server.Ports[0]; await new HttpClient().GetAsync(serverUrl + "/foo").ConfigureAwait(false); var api = RestClient.For<IWireMockAdminApi>(serverUrl); // Act var requests = await api.FindRequestsAsync(new RequestModel { Methods = new[] { "GET" } }).ConfigureAwait(false); // Assert Check.That(requests).HasSize(1); var requestLogged = requests.First(); Check.That(requestLogged.Request.Method).IsEqualTo("GET"); Check.That(requestLogged.Request.Body).IsNull(); Check.That(requestLogged.Request.Path).IsEqualTo("/foo"); } [Fact] public async Task IWireMockAdminApi_GetRequestsAsync() { // Arrange var server = WireMockServer.Start(new WireMockServerSettings { StartAdminInterface = true, Logger = new WireMockNullLogger() }); var serverUrl = "http://localhost:" + server.Ports[0]; await new HttpClient().GetAsync(serverUrl + "/foo").ConfigureAwait(false); var api = RestClient.For<IWireMockAdminApi>(serverUrl); // Act var requests = await api.GetRequestsAsync().ConfigureAwait(false); // Assert Check.That(requests).HasSize(1); var requestLogged = requests.First(); Check.That(requestLogged.Request.Method).IsEqualTo("GET"); Check.That(requestLogged.Request.Body).IsNull(); Check.That(requestLogged.Request.Path).IsEqualTo("/foo"); } [Fact] public async Task IWireMockAdminApi_GetRequestsAsync_JsonApi() { // Arrange var server = WireMockServer.Start(new WireMockServerSettings { StartAdminInterface = true, Logger = new WireMockNullLogger() }); string serverUrl = server.Urls[0]; string data = "{\"data\":[{\"type\":\"program\",\"attributes\":{\"alias\":\"T000001\",\"title\":\"Title Group Entity\"}}]}"; string jsonApiAcceptHeader = "application/vnd.api+json"; string jsonApiContentType = "application/vnd.api+json"; var request = new HttpRequestMessage(HttpMethod.Post, serverUrl); request.Headers.Accept.Clear(); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(jsonApiAcceptHeader)); request.Content = new StringContent(data); request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(jsonApiContentType); var response = await new HttpClient().SendAsync(request); Check.That(response).IsNotNull(); var api = RestClient.For<IWireMockAdminApi>(serverUrl); // Act var requests = await api.GetRequestsAsync().ConfigureAwait(false); // Assert Check.That(requests).HasSize(1); var requestLogged = requests.First(); Check.That(requestLogged.Request.Method).IsEqualTo("POST"); Check.That(requestLogged.Request.Body).IsNotNull(); Check.That(requestLogged.Request.Body).Contains("T000001"); } [Fact] public async Task IWireMockAdminApi_GetMappingAsync_WithBodyModelMatcherModel_WithoutMethods_ShouldReturnCorrectMappingModel() { // Arrange var guid = Guid.NewGuid(); var server = WireMockServer.StartWithAdminInterface(); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]); // Act var model = new MappingModel { Guid = guid, Request = new RequestModel { Path = "/1", Body = new BodyModel { Matcher = new MatcherModel { Name = "RegexMatcher", Pattern = "hello", IgnoreCase = true } } }, Response = new ResponseModel { Body = "world" } }; var postMappingResult = await api.PostMappingAsync(model).ConfigureAwait(false); // Assert postMappingResult.Should().NotBeNull(); var mapping = server.Mappings.FirstOrDefault(m => m.Guid == guid); mapping.Should().NotBeNull(); var getMappingResult = await api.GetMappingAsync(guid).ConfigureAwait(false); getMappingResult.Should().NotBeNull(); getMappingResult.Request.Body.Should().BeEquivalentTo(model.Request.Body); server.Stop(); } [Fact] public async Task IWireMockAdminApi_GetRequestsAsync_Json() { // Arrange var server = WireMockServer.Start(new WireMockServerSettings { StartAdminInterface = true, Logger = new WireMockNullLogger() }); string serverUrl = server.Urls[0]; string data = "{\"alias\": \"T000001\"}"; string jsonAcceptHeader = "application/json"; string jsonApiContentType = "application/json"; var request = new HttpRequestMessage(HttpMethod.Post, serverUrl); request.Headers.Accept.Clear(); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(jsonAcceptHeader)); request.Content = new StringContent(data); request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(jsonApiContentType); var response = await new HttpClient().SendAsync(request); Check.That(response).IsNotNull(); var api = RestClient.For<IWireMockAdminApi>(serverUrl); // Act var requests = await api.GetRequestsAsync().ConfigureAwait(false); // Assert Check.That(requests).HasSize(1); var requestLogged = requests.First(); Check.That(requestLogged.Request.Method).IsEqualTo("POST"); Check.That(requestLogged.Request.Body).IsNotNull(); Check.That(requestLogged.Request.Body).Contains("T000001"); } [Fact] public async Task IWireMockAdminApi_PostFileAsync_Ascii() { // Arrange var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict); filesystemHandlerMock.Setup(fs => fs.GetMappingFolder()).Returns("__admin/mappings"); filesystemHandlerMock.Setup(fs => fs.FolderExists(It.IsAny<string>())).Returns(true); filesystemHandlerMock.Setup(fs => fs.WriteFile(It.IsAny<string>(), It.IsAny<byte[]>())); var server = WireMockServer.Start(new WireMockServerSettings { UseSSL = false, StartAdminInterface = true, FileSystemHandler = filesystemHandlerMock.Object }); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]); // Act var request = await api.PostFileAsync("filename.txt", "abc").ConfigureAwait(false); // Assert Check.That(request.Guid).IsNull(); Check.That(request.Status).Contains("File"); // Verify filesystemHandlerMock.Verify(fs => fs.GetMappingFolder(), Times.Once); filesystemHandlerMock.Verify(fs => fs.FolderExists(It.IsAny<string>()), Times.Once); filesystemHandlerMock.Verify(fs => fs.WriteFile(It.Is<string>(p => p == "filename.txt"), It.IsAny<byte[]>()), Times.Once); filesystemHandlerMock.VerifyNoOtherCalls(); server.Stop(); } [Fact] public async Task IWireMockAdminApi_PutFileAsync_Ascii() { // Arrange var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict); filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(true); filesystemHandlerMock.Setup(fs => fs.WriteFile(It.IsAny<string>(), It.IsAny<byte[]>())); var server = WireMockServer.Start(new WireMockServerSettings { UseSSL = false, StartAdminInterface = true, FileSystemHandler = filesystemHandlerMock.Object }); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]); // Act var request = await api.PutFileAsync("filename.txt", "abc-abc").ConfigureAwait(false); // Assert Check.That(request.Guid).IsNull(); Check.That(request.Status).Contains("File"); // Verify filesystemHandlerMock.Verify(fs => fs.WriteFile(It.Is<string>(p => p == "filename.txt"), It.IsAny<byte[]>()), Times.Once); filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once); filesystemHandlerMock.VerifyNoOtherCalls(); server.Stop(); } [Fact] public void IWireMockAdminApi_PutFileAsync_NotFound() { // Arrange var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict); filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(false); var server = WireMockServer.Start(new WireMockServerSettings { UseSSL = false, StartAdminInterface = true, FileSystemHandler = filesystemHandlerMock.Object }); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]); // Act and Assert Check.ThatAsyncCode(() => api.PutFileAsync("filename.txt", "xxx")).Throws<ApiException>(); // Verify filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once); filesystemHandlerMock.VerifyNoOtherCalls(); server.Stop(); } [Fact] public void IWireMockAdminApi_GetFileAsync_NotFound() { // Arrange var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict); filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(false); filesystemHandlerMock.Setup(fs => fs.ReadFile(It.IsAny<string>())).Returns(Encoding.ASCII.GetBytes("Here's a string.")); var server = WireMockServer.Start(new WireMockServerSettings { UseSSL = false, StartAdminInterface = true, FileSystemHandler = filesystemHandlerMock.Object }); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]); // Act and Assert Check.ThatAsyncCode(() => api.GetFileAsync("filename.txt")).Throws<ApiException>(); // Verify filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once); filesystemHandlerMock.VerifyNoOtherCalls(); server.Stop(); } [Fact] public async Task IWireMockAdminApi_GetFileAsync_Found() { // Arrange string data = "Here's a string."; var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict); filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(true); filesystemHandlerMock.Setup(fs => fs.ReadFile(It.IsAny<string>())).Returns(Encoding.ASCII.GetBytes(data)); var server = WireMockServer.Start(new WireMockServerSettings { UseSSL = false, StartAdminInterface = true, FileSystemHandler = filesystemHandlerMock.Object }); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]); // Act string file = await api.GetFileAsync("filename.txt").ConfigureAwait(false); // Assert Check.That(file).Equals(data); // Verify filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once); filesystemHandlerMock.Verify(fs => fs.ReadFile(It.Is<string>(p => p == "filename.txt")), Times.Once); filesystemHandlerMock.VerifyNoOtherCalls(); server.Stop(); } [Fact] public async Task IWireMockAdminApi_DeleteFileAsync_Ok() { // Arrange var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict); filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(true); filesystemHandlerMock.Setup(fs => fs.DeleteFile(It.IsAny<string>())); var server = WireMockServer.Start(new WireMockServerSettings { UseSSL = false, StartAdminInterface = true, FileSystemHandler = filesystemHandlerMock.Object }); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]); // Act await api.DeleteFileAsync("filename.txt").ConfigureAwait(false); // Verify filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once); filesystemHandlerMock.Verify(fs => fs.DeleteFile(It.Is<string>(p => p == "filename.txt")), Times.Once); filesystemHandlerMock.VerifyNoOtherCalls(); server.Stop(); } [Fact] public void IWireMockAdminApi_DeleteFileAsync_NotFound() { // Arrange var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict); filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(false); filesystemHandlerMock.Setup(fs => fs.DeleteFile(It.IsAny<string>())); var server = WireMockServer.Start(new WireMockServerSettings { UseSSL = false, StartAdminInterface = true, FileSystemHandler = filesystemHandlerMock.Object }); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]); // Act and Assert Check.ThatAsyncCode(() => api.DeleteFileAsync("filename.txt")).Throws<ApiException>(); // Verify filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once); filesystemHandlerMock.VerifyNoOtherCalls(); server.Stop(); } [Fact] public void IWireMockAdminApi_FileExistsAsync_NotFound() { // Arrange var filesystemHandlerMock = new Mock<IFileSystemHandler>(MockBehavior.Strict); filesystemHandlerMock.Setup(fs => fs.FileExists(It.IsAny<string>())).Returns(false); var server = WireMockServer.Start(new WireMockServerSettings { UseSSL = false, StartAdminInterface = true, FileSystemHandler = filesystemHandlerMock.Object }); var api = RestClient.For<IWireMockAdminApi>(server.Urls[0]); // Act and Assert Check.ThatAsyncCode(() => api.FileExistsAsync("filename.txt")).Throws<ApiException>(); // Verify filesystemHandlerMock.Verify(fs => fs.FileExists(It.Is<string>(p => p == "filename.txt")), Times.Once); filesystemHandlerMock.VerifyNoOtherCalls(); server.Stop(); } } } #endif
namespace Microsoft.Protocols.TestSuites.SharedAdapter { using System; using System.Collections.Generic; using System.Linq; /// <summary> /// This class is used to build data element list or parse the data element list. /// </summary> public static class DataElementUtils { /// <summary> /// The constant value of root extended GUID. /// </summary> public static readonly Guid RootExGuid = new Guid("84DEFAB9-AAA3-4A0D-A3A8-520C77AC7073"); /// <summary> /// The constant value of cell second extended GUID. /// </summary> public static readonly Guid CellSecondExGuid = new Guid("6F2A4665-42C8-46C7-BAB4-E28FDCE1E32B"); /// <summary> /// The constant value of schema GUID. /// </summary> public static readonly Guid SchemaGuid = new Guid("0EB93394-571D-41E9-AAD3-880D92D31955"); /// <summary> /// This method is used to build a list of data elements to represent a file. /// </summary> /// <param name="fileContent">Specify the file content byte array.</param> /// <param name="storageIndexExGuid">Output parameter to represent the storage index GUID.</param> /// <returns>Return the list of data elements.</returns> public static List<DataElement> BuildDataElements(byte[] fileContent, out ExGuid storageIndexExGuid) { List<DataElement> dataElementList = new List<DataElement>(); ExGuid rootNodeObjectExGuid; List<ExGuid> objectDataExGuidList = new List<ExGuid>(); dataElementList.AddRange(CreateObjectGroupDataElement(fileContent, out rootNodeObjectExGuid, ref objectDataExGuidList)); ExGuid baseRevisionID = new ExGuid(0u, Guid.Empty); Dictionary<ExGuid, ExGuid> revisionMapping = new Dictionary<ExGuid, ExGuid>(); ExGuid currentRevisionID; dataElementList.Add(CreateRevisionManifestDataElement(rootNodeObjectExGuid, baseRevisionID, objectDataExGuidList, ref revisionMapping, out currentRevisionID)); Dictionary<CellID, ExGuid> cellIDMapping = new Dictionary<CellID, ExGuid>(); dataElementList.Add(CreateCellMainifestDataElement(currentRevisionID, ref cellIDMapping)); dataElementList.Add(CreateStorageManifestDataElement(cellIDMapping)); dataElementList.Add(CreateStorageIndexDataElement(dataElementList.Last().DataElementExtendedGUID, cellIDMapping, revisionMapping)); storageIndexExGuid = dataElementList.Last().DataElementExtendedGUID; return dataElementList; } /// <summary> /// This method is used to create object group data/blob element list. /// </summary> /// <param name="fileContent">Specify the file content in byte array format.</param> /// <param name="rootNodeExGuid">Output parameter to represent the root node extended GUID.</param> /// <param name="objectDataExGuidList">Input/Output parameter to represent the list of extended GUID for the data object data.</param> /// <returns>Return the list of data element which will represent the file content.</returns> public static List<DataElement> CreateObjectGroupDataElement(byte[] fileContent, out ExGuid rootNodeExGuid, ref List<ExGuid> objectDataExGuidList) { NodeObject rootNode = new IntermediateNodeObject.RootNodeObjectBuilder().Build(fileContent); // Storage the root object node ExGuid rootNodeExGuid = new ExGuid(rootNode.ExGuid); List<DataElement> elements = new ObjectGroupDataElementData.Builder().Build(rootNode); objectDataExGuidList.AddRange( elements.Where(element => element.DataElementType == DataElementType.ObjectGroupDataElementData) .Select(element => element.DataElementExtendedGUID) .ToArray()); return elements; } /// <summary> /// This method is used to create the revision manifest data element. /// </summary> /// <param name="rootObjectExGuid">Specify the root node object extended GUID.</param> /// <param name="baseRevisionID">Specify the base revision Id.</param> /// <param name="refferenceObjectDataExGuidList">Specify the reference object data extended list.</param> /// <param name="revisionMapping">Input/output parameter to represent the mapping of revision manifest.</param> /// <param name="currentRevisionID">Output parameter to represent the revision GUID.</param> /// <returns>Return the revision manifest data element.</returns> public static DataElement CreateRevisionManifestDataElement(ExGuid rootObjectExGuid, ExGuid baseRevisionID, List<ExGuid> refferenceObjectDataExGuidList, ref Dictionary<ExGuid, ExGuid> revisionMapping, out ExGuid currentRevisionID) { RevisionManifestDataElementData data = new RevisionManifestDataElementData(); data.RevisionManifest.RevisionID = new ExGuid(1u, Guid.NewGuid()); data.RevisionManifest.BaseRevisionID = new ExGuid(baseRevisionID); // Set the root object data ExGuid data.RevisionManifestRootDeclareList.Add(new RevisionManifestRootDeclare() { RootExtendedGUID = new ExGuid(2u, RootExGuid), ObjectExtendedGUID = new ExGuid(rootObjectExGuid) }); // Set all the reference object data if (refferenceObjectDataExGuidList != null) { foreach (ExGuid dataGuid in refferenceObjectDataExGuidList) { data.RevisionManifestObjectGroupReferencesList.Add(new RevisionManifestObjectGroupReferences(dataGuid)); } } DataElement dataElement = new DataElement(DataElementType.RevisionManifestDataElementData, data); revisionMapping.Add(data.RevisionManifest.RevisionID, dataElement.DataElementExtendedGUID); currentRevisionID = data.RevisionManifest.RevisionID; return dataElement; } /// <summary> /// This method is used to create the cell manifest data element. /// </summary> /// <param name="revisionId">Specify the revision GUID.</param> /// <param name="cellIDMapping">Input/output parameter to represent the mapping of cell manifest.</param> /// <returns>Return the cell manifest data element.</returns> public static DataElement CreateCellMainifestDataElement(ExGuid revisionId, ref Dictionary<CellID, ExGuid> cellIDMapping) { CellManifestDataElementData data = new CellManifestDataElementData(); data.CellManifestCurrentRevision = new CellManifestCurrentRevision() { CellManifestCurrentRevisionExtendedGUID = new ExGuid(revisionId) }; DataElement dataElement = new DataElement(DataElementType.CellManifestDataElementData, data); CellID cellID = new CellID(new ExGuid(1u, RootExGuid), new ExGuid(1u, CellSecondExGuid)); cellIDMapping.Add(cellID, dataElement.DataElementExtendedGUID); return dataElement; } /// <summary> /// This method is used to create the storage manifest data element. /// </summary> /// <param name="cellIDMapping">Specify the mapping of cell manifest.</param> /// <returns>Return the storage manifest data element.</returns> public static DataElement CreateStorageManifestDataElement(Dictionary<CellID, ExGuid> cellIDMapping) { StorageManifestDataElementData data = new StorageManifestDataElementData(); data.StorageManifestSchemaGUID = new StorageManifestSchemaGUID() { GUID = SchemaGuid }; foreach (KeyValuePair<CellID, ExGuid> kv in cellIDMapping) { StorageManifestRootDeclare manifestRootDeclare = new StorageManifestRootDeclare(); manifestRootDeclare.RootExtendedGUID = new ExGuid(2u, RootExGuid); manifestRootDeclare.CellID = new CellID(kv.Key); data.StorageManifestRootDeclareList.Add(manifestRootDeclare); } return new DataElement(DataElementType.StorageManifestDataElementData, data); } /// <summary> /// This method is used to create the storage index data element. /// </summary> /// <param name="manifestExGuid">Specify the storage manifest data element extended GUID.</param> /// <param name="cellIDMappings">Specify the mapping of cell manifest.</param> /// <param name="revisionIDMappings">Specify the mapping of revision manifest.</param> /// <returns>Return the storage index data element.</returns> public static DataElement CreateStorageIndexDataElement(ExGuid manifestExGuid, Dictionary<CellID, ExGuid> cellIDMappings, Dictionary<ExGuid, ExGuid> revisionIDMappings) { StorageIndexDataElementData data = new StorageIndexDataElementData(); data.StorageIndexManifestMapping = new StorageIndexManifestMapping(); data.StorageIndexManifestMapping.ManifestMappingExtendedGUID = new ExGuid(manifestExGuid); data.StorageIndexManifestMapping.ManifestMappingSerialNumber = new SerialNumber(System.Guid.NewGuid(), SequenceNumberGenerator.GetCurrentSerialNumber()); foreach (KeyValuePair<CellID, ExGuid> kv in cellIDMappings) { StorageIndexCellMapping cellMapping = new StorageIndexCellMapping(); cellMapping.CellID = kv.Key; cellMapping.CellMappingExtendedGUID = kv.Value; cellMapping.CellMappingSerialNumber = new SerialNumber(System.Guid.NewGuid(), SequenceNumberGenerator.GetCurrentSerialNumber()); data.StorageIndexCellMappingList.Add(cellMapping); } foreach (KeyValuePair<ExGuid, ExGuid> kv in revisionIDMappings) { StorageIndexRevisionMapping revisionMapping = new StorageIndexRevisionMapping(); revisionMapping.RevisionExtendedGUID = kv.Key; revisionMapping.RevisionMappingExtendedGUID = kv.Value; revisionMapping.RevisionMappingSerialNumber = new SerialNumber(Guid.NewGuid(), SequenceNumberGenerator.GetCurrentSerialNumber()); data.StorageIndexRevisionMappingList.Add(revisionMapping); } return new DataElement(DataElementType.StorageIndexDataElementData, data); } /// <summary> /// This method is used to get the list of object group data element from a list of data element. /// </summary> /// <param name="dataElements">Specify the data element list.</param> /// <param name="storageIndexExGuid">Specify the storage index extended GUID.</param> /// <param name="rootExGuid">Output parameter to represent the root node object.</param> /// <returns>Return the list of object group data elements.</returns> public static List<ObjectGroupDataElementData> GetDataObjectDataElementData(List<DataElement> dataElements, ExGuid storageIndexExGuid, out ExGuid rootExGuid) { ExGuid manifestMappingGuid; Dictionary<CellID, ExGuid> cellIDMappings; Dictionary<ExGuid, ExGuid> revisionIDMappings; AnalyzeStorageIndexDataElement(dataElements, storageIndexExGuid, out manifestMappingGuid, out cellIDMappings, out revisionIDMappings); StorageManifestDataElementData manifestData = GetStorageManifestDataElementData(dataElements, manifestMappingGuid); if (manifestData == null) { throw new InvalidOperationException("Cannot find the storage manifest data element with ExGuid " + manifestMappingGuid.GUID.ToString()); } CellManifestDataElementData cellData = GetCellManifestDataElementData(dataElements, manifestData, cellIDMappings); RevisionManifestDataElementData revisionData = GetRevisionManifestDataElementData(dataElements, cellData, revisionIDMappings); return GetDataObjectDataElementData(dataElements, revisionData, out rootExGuid); } /// <summary> /// This method is used to try to analyze the returned whether data elements are complete. /// </summary> /// <param name="dataElements">Specify the data elements list.</param> /// <param name="storageIndexExGuid">Specify the storage index extended GUID.</param> /// <returns>If the data elements start with the specified storage index extended GUID are complete, return true. Otherwise return false.</returns> public static bool TryAnalyzeWhetherFullDataElementList(List<DataElement> dataElements, ExGuid storageIndexExGuid) { ExGuid manifestMappingGuid; Dictionary<CellID, ExGuid> cellIDMappings; Dictionary<ExGuid, ExGuid> revisionIDMappings; if (!AnalyzeStorageIndexDataElement(dataElements, storageIndexExGuid, out manifestMappingGuid, out cellIDMappings, out revisionIDMappings)) { return false; } if (cellIDMappings.Count == 0) { return false; } if (revisionIDMappings.Count == 0) { return false; } StorageManifestDataElementData manifestData = GetStorageManifestDataElementData(dataElements, manifestMappingGuid); if (manifestData == null) { return false; } foreach (StorageManifestRootDeclare kv in manifestData.StorageManifestRootDeclareList) { if (!cellIDMappings.ContainsKey(kv.CellID)) { throw new InvalidOperationException(string.Format("Cannot fin the Cell ID {0} in the cell id mapping", kv.CellID.ToString())); } ExGuid cellMappingID = cellIDMappings[kv.CellID]; DataElement dataElement = dataElements.Find(element => element.DataElementExtendedGUID.Equals(cellMappingID)); if (dataElement == null) { return false; } CellManifestDataElementData cellData = dataElement.GetData<CellManifestDataElementData>(); ExGuid currentRevisionExGuid = cellData.CellManifestCurrentRevision.CellManifestCurrentRevisionExtendedGUID; if (!revisionIDMappings.ContainsKey(currentRevisionExGuid)) { throw new InvalidOperationException(string.Format("Cannot find the revision id {0} in the revisionMapping", currentRevisionExGuid.ToString())); } ExGuid revisionMapping = revisionIDMappings[currentRevisionExGuid]; dataElement = dataElements.Find(element => element.DataElementExtendedGUID.Equals(revisionMapping)); if (dataElement == null) { return false; } RevisionManifestDataElementData revisionData = dataElement.GetData<RevisionManifestDataElementData>(); foreach (RevisionManifestObjectGroupReferences reference in revisionData.RevisionManifestObjectGroupReferencesList) { dataElement = dataElements.Find(element => element.DataElementExtendedGUID.Equals(reference.ObjectGroupExtendedGUID)); if (dataElement == null) { return false; } } } return true; } /// <summary> /// This method is used to analyze whether the data elements are confirmed to the schema defined in MS-FSSHTTPD. /// </summary> /// <param name="dataElements">Specify the data elements list.</param> /// <param name="storageIndexExGuid">Specify the storage index extended GUID.</param> /// <returns>If the data elements confirms to the schema defined in the MS-FSSHTTPD returns true, otherwise false.</returns> public static bool TryAnalyzeWhetherConfirmSchema(List<DataElement> dataElements, ExGuid storageIndexExGuid) { DataElement storageIndexDataElement = dataElements.Find(element => element.DataElementExtendedGUID.Equals(storageIndexExGuid)); if (storageIndexExGuid == null) { return false; } StorageIndexDataElementData storageIndexData = storageIndexDataElement.GetData<StorageIndexDataElementData>(); ExGuid manifestMappingGuid = storageIndexData.StorageIndexManifestMapping.ManifestMappingExtendedGUID; DataElement storageManifestDataElement = dataElements.Find(element => element.DataElementExtendedGUID.Equals(manifestMappingGuid)); if (storageManifestDataElement == null) { return false; } return SchemaGuid.Equals(storageManifestDataElement.GetData<StorageManifestDataElementData>().StorageManifestSchemaGUID.GUID); } /// <summary> /// This method is used to analyze the storage index data element to get all the mappings. /// </summary> /// <param name="dataElements">Specify the data element list.</param> /// <param name="storageIndexExGuid">Specify the storage index extended GUID.</param> /// <param name="manifestMappingGuid">Output parameter to represent the storage manifest mapping GUID.</param> /// <param name="cellIDMappings">Output parameter to represent the mapping of cell id.</param> /// <param name="revisionIDMappings">Output parameter to represent the revision id.</param> /// <returns>Return true if analyze the storage index succeeds, otherwise return false.</returns> public static bool AnalyzeStorageIndexDataElement( List<DataElement> dataElements, ExGuid storageIndexExGuid, out ExGuid manifestMappingGuid, out Dictionary<CellID, ExGuid> cellIDMappings, out Dictionary<ExGuid, ExGuid> revisionIDMappings) { manifestMappingGuid = null; cellIDMappings = null; revisionIDMappings = null; if (storageIndexExGuid == null) { return false; } DataElement storageIndexDataElement = dataElements.Find(element => element.DataElementExtendedGUID.Equals(storageIndexExGuid)); StorageIndexDataElementData storageIndexData = storageIndexDataElement.GetData<StorageIndexDataElementData>(); manifestMappingGuid = storageIndexData.StorageIndexManifestMapping.ManifestMappingExtendedGUID; cellIDMappings = new Dictionary<CellID, ExGuid>(); foreach (StorageIndexCellMapping kv in storageIndexData.StorageIndexCellMappingList) { cellIDMappings.Add(kv.CellID, kv.CellMappingExtendedGUID); } revisionIDMappings = new Dictionary<ExGuid, ExGuid>(); foreach (StorageIndexRevisionMapping kv in storageIndexData.StorageIndexRevisionMappingList) { revisionIDMappings.Add(kv.RevisionExtendedGUID, kv.RevisionMappingExtendedGUID); } return true; } /// <summary> /// This method is used to get storage manifest data element from a list of data element. /// </summary> /// <param name="dataElements">Specify the data element list.</param> /// <param name="manifestMapping">Specify the manifest mapping GUID.</param> /// <returns>Return the storage manifest data element.</returns> public static StorageManifestDataElementData GetStorageManifestDataElementData(List<DataElement> dataElements, ExGuid manifestMapping) { DataElement storageManifestDataElement = dataElements.Find(element => element.DataElementExtendedGUID.Equals(manifestMapping)); if (storageManifestDataElement == null) { return null; } return storageManifestDataElement.GetData<StorageManifestDataElementData>(); } /// <summary> /// This method is used to get cell manifest data element from a list of data element. /// </summary> /// <param name="dataElements">Specify the data element list.</param> /// <param name="manifestDataElementData">Specify the manifest data element.</param> /// <param name="cellIDMappings">Specify mapping of cell id.</param> /// <returns>Return the cell manifest data element.</returns> public static CellManifestDataElementData GetCellManifestDataElementData(List<DataElement> dataElements, StorageManifestDataElementData manifestDataElementData, Dictionary<CellID, ExGuid> cellIDMappings) { CellID cellID = new CellID(new ExGuid(1u, RootExGuid), new ExGuid(1u, CellSecondExGuid)); foreach (StorageManifestRootDeclare kv in manifestDataElementData.StorageManifestRootDeclareList) { if (kv.RootExtendedGUID.Equals(new ExGuid(2u, RootExGuid)) && kv.CellID.Equals(cellID)) { if (!cellIDMappings.ContainsKey(kv.CellID)) { throw new InvalidOperationException(string.Format("Cannot fin the Cell ID {0} in the cell id mapping", cellID.ToString())); } ExGuid cellMappingID = cellIDMappings[kv.CellID]; DataElement dataElement = dataElements.Find(element => element.DataElementExtendedGUID.Equals(cellMappingID)); if (dataElement == null) { throw new InvalidOperationException("Cannot find the cell data element with ExGuid " + cellMappingID.GUID.ToString()); } return dataElement.GetData<CellManifestDataElementData>(); } } throw new InvalidOperationException("Cannot find the CellManifestDataElement"); } /// <summary> /// This method is used to get revision manifest data element from a list of data element. /// </summary> /// <param name="dataElements">Specify the data element list.</param> /// <param name="cellData">Specify the cell data element.</param> /// <param name="revisionIDMappings">Specify mapping of revision id.</param> /// <returns>Return the revision manifest data element.</returns> public static RevisionManifestDataElementData GetRevisionManifestDataElementData(List<DataElement> dataElements, CellManifestDataElementData cellData, Dictionary<ExGuid, ExGuid> revisionIDMappings) { ExGuid currentRevisionExGuid = cellData.CellManifestCurrentRevision.CellManifestCurrentRevisionExtendedGUID; if (!revisionIDMappings.ContainsKey(currentRevisionExGuid)) { throw new InvalidOperationException(string.Format("Cannot find the revision id {0} in the revisionMapping", currentRevisionExGuid.ToString())); } ExGuid revisionMapping = revisionIDMappings[currentRevisionExGuid]; DataElement dataElement = dataElements.Find(element => element.DataElementExtendedGUID.Equals(revisionMapping)); if (dataElement == null) { throw new InvalidOperationException("Cannot find the revision data element with ExGuid " + revisionMapping.GUID.ToString()); } return dataElement.GetData<RevisionManifestDataElementData>(); } /// <summary> /// This method is used to get a list of object group data element from a list of data element. /// </summary> /// <param name="dataElements">Specify the data element list.</param> /// <param name="revisionData">Specify the revision data.</param> /// <param name="rootExGuid">Specify the root node object extended GUID.</param> /// <returns>Return the list of object group data element.</returns> public static List<ObjectGroupDataElementData> GetDataObjectDataElementData(List<DataElement> dataElements, RevisionManifestDataElementData revisionData, out ExGuid rootExGuid) { rootExGuid = null; foreach (RevisionManifestRootDeclare kv in revisionData.RevisionManifestRootDeclareList) { if (kv.RootExtendedGUID.Equals(new ExGuid(2u, RootExGuid))) { rootExGuid = kv.ObjectExtendedGUID; break; } } List<ObjectGroupDataElementData> dataList = new List<ObjectGroupDataElementData>(); foreach (RevisionManifestObjectGroupReferences kv in revisionData.RevisionManifestObjectGroupReferencesList) { DataElement dataElement = dataElements.Find(element => element.DataElementExtendedGUID.Equals(kv.ObjectGroupExtendedGUID)); if (dataElement == null) { throw new InvalidOperationException("Cannot find the object group data element with ExGuid " + kv.ObjectGroupExtendedGUID.GUID.ToString()); } dataList.Add(dataElement.GetData<ObjectGroupDataElementData>()); } return dataList; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Analyzer = Lucene.Net.Analysis.Analyzer; using BooleanClause = Lucene.Net.Search.BooleanClause; using BooleanQuery = Lucene.Net.Search.BooleanQuery; using MultiPhraseQuery = Lucene.Net.Search.MultiPhraseQuery; using PhraseQuery = Lucene.Net.Search.PhraseQuery; using Query = Lucene.Net.Search.Query; using Version = Lucene.Net.Util.Version; namespace Lucene.Net.QueryParsers { /// <summary> A QueryParser which constructs queries to search multiple fields. /// /// </summary> /// <version> $Revision: 829134 $ /// </version> public class MultiFieldQueryParser:QueryParser { protected internal System.String[] fields; protected internal System.Collections.IDictionary boosts; /// <summary> Creates a MultiFieldQueryParser. Allows passing of a map with term to /// Boost, and the boost to apply to each term. /// /// <p/> /// It will, when parse(String query) is called, construct a query like this /// (assuming the query consists of two terms and you specify the two fields /// <code>title</code> and <code>body</code>): /// <p/> /// /// <code> /// (title:term1 body:term1) (title:term2 body:term2) /// </code> /// /// <p/> /// When setDefaultOperator(AND_OPERATOR) is set, the result will be: /// <p/> /// /// <code> /// +(title:term1 body:term1) +(title:term2 body:term2) /// </code> /// /// <p/> /// When you pass a boost (title=>5 body=>10) you can get /// <p/> /// /// <code> /// +(title:term1^5.0 body:term1^10.0) +(title:term2^5.0 body:term2^10.0) /// </code> /// /// <p/> /// In other words, all the query's terms must appear, but it doesn't matter /// in what fields they appear. /// <p/> /// /// </summary> /// <deprecated> Please use /// {@link #MultiFieldQueryParser(Version, String[], Analyzer, Map)} /// instead /// </deprecated> [Obsolete("Please use MultiFieldQueryParser(Version, String[], Analyzer, IDictionary) instead")] public MultiFieldQueryParser(System.String[] fields, Analyzer analyzer, System.Collections.IDictionary boosts):this(Version.LUCENE_24, fields, analyzer) { this.boosts = boosts; } /// <summary> Creates a MultiFieldQueryParser. Allows passing of a map with term to /// Boost, and the boost to apply to each term. /// /// <p/> /// It will, when parse(String query) is called, construct a query like this /// (assuming the query consists of two terms and you specify the two fields /// <code>title</code> and <code>body</code>): /// <p/> /// /// <code> /// (title:term1 body:term1) (title:term2 body:term2) /// </code> /// /// <p/> /// When setDefaultOperator(AND_OPERATOR) is set, the result will be: /// <p/> /// /// <code> /// +(title:term1 body:term1) +(title:term2 body:term2) /// </code> /// /// <p/> /// When you pass a boost (title=>5 body=>10) you can get /// <p/> /// /// <code> /// +(title:term1^5.0 body:term1^10.0) +(title:term2^5.0 body:term2^10.0) /// </code> /// /// <p/> /// In other words, all the query's terms must appear, but it doesn't matter /// in what fields they appear. /// <p/> /// </summary> public MultiFieldQueryParser(Version matchVersion, System.String[] fields, Analyzer analyzer, System.Collections.IDictionary boosts):this(matchVersion, fields, analyzer) { this.boosts = boosts; } /// <summary> Creates a MultiFieldQueryParser. /// /// <p/> /// It will, when parse(String query) is called, construct a query like this /// (assuming the query consists of two terms and you specify the two fields /// <code>title</code> and <code>body</code>): /// <p/> /// /// <code> /// (title:term1 body:term1) (title:term2 body:term2) /// </code> /// /// <p/> /// When setDefaultOperator(AND_OPERATOR) is set, the result will be: /// <p/> /// /// <code> /// +(title:term1 body:term1) +(title:term2 body:term2) /// </code> /// /// <p/> /// In other words, all the query's terms must appear, but it doesn't matter /// in what fields they appear. /// <p/> /// /// </summary> /// <deprecated> Please use /// {@link #MultiFieldQueryParser(Version, String[], Analyzer)} /// instead /// </deprecated> [Obsolete("Please use MultiFieldQueryParser(Version, String[], Analyzer) instead")] public MultiFieldQueryParser(System.String[] fields, Analyzer analyzer):this(Version.LUCENE_24, fields, analyzer) { } /// <summary> Creates a MultiFieldQueryParser. /// /// <p/> /// It will, when parse(String query) is called, construct a query like this /// (assuming the query consists of two terms and you specify the two fields /// <code>title</code> and <code>body</code>): /// <p/> /// /// <code> /// (title:term1 body:term1) (title:term2 body:term2) /// </code> /// /// <p/> /// When setDefaultOperator(AND_OPERATOR) is set, the result will be: /// <p/> /// /// <code> /// +(title:term1 body:term1) +(title:term2 body:term2) /// </code> /// /// <p/> /// In other words, all the query's terms must appear, but it doesn't matter /// in what fields they appear. /// <p/> /// </summary> public MultiFieldQueryParser(Version matchVersion, System.String[] fields, Analyzer analyzer):base(matchVersion, null, analyzer) { this.fields = fields; } protected internal override Query GetFieldQuery(System.String field, System.String queryText, int slop) { if (field == null) { System.Collections.IList clauses = new System.Collections.ArrayList(); for (int i = 0; i < fields.Length; i++) { Query q = base.GetFieldQuery(fields[i], queryText); if (q != null) { //If the user passes a map of boosts if (boosts != null) { //Get the boost from the map and apply them if (boosts.Contains(fields[i])) { System.Single boost = (System.Single) boosts[fields[i]]; q.SetBoost((float) boost); } } ApplySlop(q, slop); clauses.Add(new BooleanClause(q, BooleanClause.Occur.SHOULD)); } } if (clauses.Count == 0) // happens for stopwords return null; return GetBooleanQuery(clauses, true); } Query q2 = base.GetFieldQuery(field, queryText); ApplySlop(q2, slop); return q2; } private void ApplySlop(Query q, int slop) { if (q is PhraseQuery) { ((PhraseQuery) q).SetSlop(slop); } else if (q is MultiPhraseQuery) { ((MultiPhraseQuery) q).SetSlop(slop); } } public /*protected internal*/ override Query GetFieldQuery(System.String field, System.String queryText) { return GetFieldQuery(field, queryText, 0); } public /*protected internal*/ override Query GetFuzzyQuery(System.String field, System.String termStr, float minSimilarity) { if (field == null) { System.Collections.IList clauses = new System.Collections.ArrayList(); for (int i = 0; i < fields.Length; i++) { clauses.Add(new BooleanClause(GetFuzzyQuery(fields[i], termStr, minSimilarity), BooleanClause.Occur.SHOULD)); } return GetBooleanQuery(clauses, true); } return base.GetFuzzyQuery(field, termStr, minSimilarity); } public /*protected internal*/ override Query GetPrefixQuery(System.String field, System.String termStr) { if (field == null) { System.Collections.IList clauses = new System.Collections.ArrayList(); for (int i = 0; i < fields.Length; i++) { clauses.Add(new BooleanClause(GetPrefixQuery(fields[i], termStr), BooleanClause.Occur.SHOULD)); } return GetBooleanQuery(clauses, true); } return base.GetPrefixQuery(field, termStr); } public /*protected internal*/ override Query GetWildcardQuery(System.String field, System.String termStr) { if (field == null) { System.Collections.IList clauses = new System.Collections.ArrayList(); for (int i = 0; i < fields.Length; i++) { clauses.Add(new BooleanClause(GetWildcardQuery(fields[i], termStr), BooleanClause.Occur.SHOULD)); } return GetBooleanQuery(clauses, true); } return base.GetWildcardQuery(field, termStr); } protected internal override Query GetRangeQuery(System.String field, System.String part1, System.String part2, bool inclusive) { if (field == null) { System.Collections.IList clauses = new System.Collections.ArrayList(); for (int i = 0; i < fields.Length; i++) { clauses.Add(new BooleanClause(GetRangeQuery(fields[i], part1, part2, inclusive), BooleanClause.Occur.SHOULD)); } return GetBooleanQuery(clauses, true); } return base.GetRangeQuery(field, part1, part2, inclusive); } /// <summary> Parses a query which searches on the fields specified. /// <p/> /// If x fields are specified, this effectively constructs: /// /// <pre> /// &lt;code&gt; /// (field1:query1) (field2:query2) (field3:query3)...(fieldx:queryx) /// &lt;/code&gt; /// </pre> /// /// </summary> /// <param name="queries">Queries strings to parse /// </param> /// <param name="fields">Fields to search on /// </param> /// <param name="analyzer">Analyzer to use /// </param> /// <throws> ParseException </throws> /// <summary> if query parsing fails /// </summary> /// <throws> IllegalArgumentException </throws> /// <summary> if the length of the queries array differs from the length of /// the fields array /// </summary> /// <deprecated> Use {@link #Parse(Version,String[],String[],Analyzer)} /// instead /// </deprecated> [Obsolete("Use Parse(Version,String[],String[],Analyzer) instead")] public static Query Parse(System.String[] queries, System.String[] fields, Analyzer analyzer) { return Parse(Version.LUCENE_24, queries, fields, analyzer); } /// <summary> Parses a query which searches on the fields specified. /// <p/> /// If x fields are specified, this effectively constructs: /// /// <pre> /// &lt;code&gt; /// (field1:query1) (field2:query2) (field3:query3)...(fieldx:queryx) /// &lt;/code&gt; /// </pre> /// /// </summary> /// <param name="matchVersion">Lucene version to match; this is passed through to /// QueryParser. /// </param> /// <param name="queries">Queries strings to parse /// </param> /// <param name="fields">Fields to search on /// </param> /// <param name="analyzer">Analyzer to use /// </param> /// <throws> ParseException </throws> /// <summary> if query parsing fails /// </summary> /// <throws> IllegalArgumentException </throws> /// <summary> if the length of the queries array differs from the length of /// the fields array /// </summary> public static Query Parse(Version matchVersion, System.String[] queries, System.String[] fields, Analyzer analyzer) { if (queries.Length != fields.Length) throw new System.ArgumentException("queries.length != fields.length"); BooleanQuery bQuery = new BooleanQuery(); for (int i = 0; i < fields.Length; i++) { QueryParser qp = new QueryParser(matchVersion, fields[i], analyzer); Query q = qp.Parse(queries[i]); if (q != null && (!(q is BooleanQuery) || ((BooleanQuery) q).GetClauses().Length > 0)) { bQuery.Add(q, BooleanClause.Occur.SHOULD); } } return bQuery; } /// <summary> Parses a query, searching on the fields specified. /// Use this if you need to specify certain fields as required, /// and others as prohibited. /// <p/><pre> /// Usage: /// <code> /// String[] fields = {"filename", "contents", "description"}; /// BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD, /// BooleanClause.Occur.MUST, /// BooleanClause.Occur.MUST_NOT}; /// MultiFieldQueryParser.parse("query", fields, flags, analyzer); /// </code> /// </pre> /// <p/> /// The code above would construct a query: /// <pre> /// <code> /// (filename:query) +(contents:query) -(description:query) /// </code> /// </pre> /// /// </summary> /// <param name="query">Query string to parse /// </param> /// <param name="fields">Fields to search on /// </param> /// <param name="flags">Flags describing the fields /// </param> /// <param name="analyzer">Analyzer to use /// </param> /// <throws> ParseException if query parsing fails </throws> /// <throws> IllegalArgumentException if the length of the fields array differs </throws> /// <summary> from the length of the flags array /// </summary> /// <deprecated> Use /// {@link #Parse(Version, String, String[], BooleanClause.Occur[], Analyzer)} /// instead /// </deprecated> [Obsolete("Use Parse(Version, String, String[], BooleanClause.Occur[], Analyzer) instead")] public static Query Parse(System.String query, System.String[] fields, BooleanClause.Occur[] flags, Analyzer analyzer) { return Parse(Version.LUCENE_24, query, fields, flags, analyzer); } /// <summary> Parses a query, searching on the fields specified. Use this if you need /// to specify certain fields as required, and others as prohibited. /// <p/> /// /// <pre> /// Usage: /// &lt;code&gt; /// String[] fields = {&quot;filename&quot;, &quot;contents&quot;, &quot;description&quot;}; /// BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD, /// BooleanClause.Occur.MUST, /// BooleanClause.Occur.MUST_NOT}; /// MultiFieldQueryParser.parse(&quot;query&quot;, fields, flags, analyzer); /// &lt;/code&gt; /// </pre> /// <p/> /// The code above would construct a query: /// /// <pre> /// &lt;code&gt; /// (filename:query) +(contents:query) -(description:query) /// &lt;/code&gt; /// </pre> /// /// </summary> /// <param name="matchVersion">Lucene version to match; this is passed through to /// QueryParser. /// </param> /// <param name="query">Query string to parse /// </param> /// <param name="fields">Fields to search on /// </param> /// <param name="flags">Flags describing the fields /// </param> /// <param name="analyzer">Analyzer to use /// </param> /// <throws> ParseException </throws> /// <summary> if query parsing fails /// </summary> /// <throws> IllegalArgumentException </throws> /// <summary> if the length of the fields array differs from the length of /// the flags array /// </summary> public static Query Parse(Version matchVersion, System.String query, System.String[] fields, BooleanClause.Occur[] flags, Analyzer analyzer) { if (fields.Length != flags.Length) throw new System.ArgumentException("fields.length != flags.length"); BooleanQuery bQuery = new BooleanQuery(); for (int i = 0; i < fields.Length; i++) { QueryParser qp = new QueryParser(matchVersion, fields[i], analyzer); Query q = qp.Parse(query); if (q != null && (!(q is BooleanQuery) || ((BooleanQuery) q).GetClauses().Length > 0)) { bQuery.Add(q, flags[i]); } } return bQuery; } /// <summary> Parses a query, searching on the fields specified. /// Use this if you need to specify certain fields as required, /// and others as prohibited. /// <p/><pre> /// Usage: /// <code> /// String[] query = {"query1", "query2", "query3"}; /// String[] fields = {"filename", "contents", "description"}; /// BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD, /// BooleanClause.Occur.MUST, /// BooleanClause.Occur.MUST_NOT}; /// MultiFieldQueryParser.parse(query, fields, flags, analyzer); /// </code> /// </pre> /// <p/> /// The code above would construct a query: /// <pre> /// <code> /// (filename:query1) +(contents:query2) -(description:query3) /// </code> /// </pre> /// /// </summary> /// <param name="queries">Queries string to parse /// </param> /// <param name="fields">Fields to search on /// </param> /// <param name="flags">Flags describing the fields /// </param> /// <param name="analyzer">Analyzer to use /// </param> /// <throws> ParseException if query parsing fails </throws> /// <throws> IllegalArgumentException if the length of the queries, fields, </throws> /// <summary> and flags array differ /// </summary> /// <deprecated> Used /// {@link #Parse(Version, String[], String[], BooleanClause.Occur[], Analyzer)} /// instead /// </deprecated> [Obsolete("Use Parse(Version, String[], String[], BooleanClause.Occur[], Analyzer) instead")] public static Query Parse(System.String[] queries, System.String[] fields, BooleanClause.Occur[] flags, Analyzer analyzer) { return Parse(Version.LUCENE_24, queries, fields, flags, analyzer); } /// <summary> Parses a query, searching on the fields specified. Use this if you need /// to specify certain fields as required, and others as prohibited. /// <p/> /// /// <pre> /// Usage: /// &lt;code&gt; /// String[] query = {&quot;query1&quot;, &quot;query2&quot;, &quot;query3&quot;}; /// String[] fields = {&quot;filename&quot;, &quot;contents&quot;, &quot;description&quot;}; /// BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD, /// BooleanClause.Occur.MUST, /// BooleanClause.Occur.MUST_NOT}; /// MultiFieldQueryParser.parse(query, fields, flags, analyzer); /// &lt;/code&gt; /// </pre> /// <p/> /// The code above would construct a query: /// /// <pre> /// &lt;code&gt; /// (filename:query1) +(contents:query2) -(description:query3) /// &lt;/code&gt; /// </pre> /// /// </summary> /// <param name="matchVersion">Lucene version to match; this is passed through to /// QueryParser. /// </param> /// <param name="queries">Queries string to parse /// </param> /// <param name="fields">Fields to search on /// </param> /// <param name="flags">Flags describing the fields /// </param> /// <param name="analyzer">Analyzer to use /// </param> /// <throws> ParseException </throws> /// <summary> if query parsing fails /// </summary> /// <throws> IllegalArgumentException </throws> /// <summary> if the length of the queries, fields, and flags array differ /// </summary> public static Query Parse(Version matchVersion, System.String[] queries, System.String[] fields, BooleanClause.Occur[] flags, Analyzer analyzer) { if (!(queries.Length == fields.Length && queries.Length == flags.Length)) throw new System.ArgumentException("queries, fields, and flags array have have different length"); BooleanQuery bQuery = new BooleanQuery(); for (int i = 0; i < fields.Length; i++) { QueryParser qp = new QueryParser(matchVersion, fields[i], analyzer); Query q = qp.Parse(queries[i]); if (q != null && (!(q is BooleanQuery) || ((BooleanQuery) q).GetClauses().Length > 0)) { bQuery.Add(q, flags[i]); } } return bQuery; } } }
/* * NPlot - A charting library for .NET * * Bitmap.PlotSurface2D.cs * Copyright (C) 2003-2006 Matt Howlett and others. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of NPlot 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.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; namespace NPlot { namespace Bitmap { /// <summary> /// Wrapper around NPlot.PlotSurface2D that provides extra functionality /// specific to drawing to Bitmaps. /// </summary> public class PlotSurface2D { /// <summary> /// Constructor. /// </summary> /// <param name="width">width of the bitmap.</param> /// <param name="height">height of the bitmap.</param> public PlotSurface2D(int width, int height) { b_ = new System.Drawing.Bitmap(width, height); ps_ = new NPlot.PlotSurface2D(); } /// <summary> /// Constructor. /// </summary> /// <param name="b">The Bitmap where the plot is to be rendered.</param> public PlotSurface2D(System.Drawing.Bitmap b) { b_ = b; ps_ = new NPlot.PlotSurface2D(); } /// <summary> /// Renders the plot. /// </summary> /// <param name="g">The graphics surface.</param> /// <param name="bounds">The rectangle storing the bounds for rendering.</param> public void Draw(Graphics g, Rectangle bounds) { ps_.Draw(g, bounds); } /// <summary> /// Clears the plot. /// </summary> public void Clear() { ps_.Clear(); } /// <summary> /// Adds a drawable object to the plot surface. If the object is an IPlot, /// the PlotSurface2D axes will also be updated. /// </summary> /// <param name="p">The IDrawable object to add to the plot surface.</param> public void Add(IDrawable p) { ps_.Add(p); } /// <summary> /// Adds a drawable object to the plot surface. If the object is an IPlot, /// the PlotSurface2D axes will also be updated. /// </summary> /// <param name="p">The IDrawable object to add to the plot surface.</param> /// <param name="zOrder">The z-ordering when drawing (objects with lower numbers are drawn first)</param> public void Add(IDrawable p, int zOrder) { ps_.Add(p, zOrder); } /// <summary> /// The plot surface title. /// </summary> public string Title { get => ps_.Title; set => ps_.Title = value; } /// <summary> /// The plot title font. /// </summary> public Font TitleFont { get => ps_.TitleFont; set => ps_.TitleFont = value; } /// <summary> /// The distance in pixels to leave between of the edge of the bounding rectangle /// supplied to the Draw method, and the markings that make up the plot. /// </summary> public int Padding { get => ps_.Padding; set => ps_.Padding = value; } /// <summary> /// The bottom abscissa axis. /// </summary> public DateTimeAxis XAxis1 { get => ps_.XAxis1; set => ps_.XAxis1 = value; } /// <summary> /// The left ordinate axis. /// </summary> public LinearAxis YAxis1 { get => ps_.YAxis1; set => ps_.YAxis1 = value; } /// <summary> /// The top abscissa axis. /// </summary> public DateTimeAxis XAxis2 { get => ps_.XAxis2; set => ps_.XAxis2 = value; } /// <summary> /// The right ordinate axis. /// </summary> public LinearAxis YAxis2 { get => ps_.YAxis2; set => ps_.YAxis2 = value; } /// <summary> /// A color used to paint the plot background. Mutually exclusive with PlotBackImage and PlotBackBrush /// </summary> public Color PlotBackColor { set => ps_.PlotBackColor = value; } /// <summary> /// Smoothing mode to use when drawing plots. /// </summary> public SmoothingMode SmoothingMode { get => ps_.SmoothingMode; set => ps_.SmoothingMode = value; } /// <summary> /// The bitmap width /// </summary> public int Width => b_.Width; /// <summary> /// The bitmap height /// </summary> public int Height => b_.Height; /// <summary> /// Renders the bitmap to a MemoryStream. Useful for returning the bitmap from /// an ASP.NET page. /// </summary> /// <returns>The MemoryStream object.</returns> public MemoryStream ToStream(ImageFormat imageFormat) { MemoryStream stream = new MemoryStream(); ps_.Draw(Graphics.FromImage(this.Bitmap), new Rectangle(0, 0, b_.Width, b_.Height)); this.Bitmap.Save(stream, imageFormat); return stream; } /// <summary> /// The bitmap to use as the drawing surface. /// </summary> public System.Drawing.Bitmap Bitmap { get => b_; set => b_ = value; } /// <summary> /// The bitmap background color outside the bounds of the plot surface. /// </summary> public Color BackColor { set => backColor_ = value; } private object backColor_; /// <summary> /// Refreshes (draws) the plot. /// </summary> public void Refresh() { if (this.backColor_ != null) { Graphics g = Graphics.FromImage(b_); g.FillRectangle(new Pen((Color)this.backColor_).Brush, 0, 0, b_.Width, b_.Height); } ps_.Draw(Graphics.FromImage(b_), new Rectangle(0, 0, b_.Width, b_.Height)); } private readonly NPlot.PlotSurface2D ps_; private System.Drawing.Bitmap b_; /// <summary> /// Add an axis constraint to the plot surface. Axis constraints can /// specify relative world-pixel scalings, absolute axis positions etc. /// </summary> /// <param name="c">The axis constraint to add.</param> public void AddAxesConstraint(AxesConstraint c) { ps_.AddAxesConstraint(c); } /// <summary> /// Whether or not the title will be scaled according to size of the plot /// surface. /// </summary> public bool AutoScaleTitle { get => ps_.AutoScaleTitle; set => ps_.AutoScaleTitle = value; } /// <summary> /// When plots are added to the plot surface, the axes they are attached to /// are immediately modified to reflect data of the plot. If /// AutoScaleAutoGeneratedAxes is true when a plot is added, the axes will /// be turned in to auto scaling ones if they are not already [tick marks, /// tick text and label size scaled to size of plot surface]. If false, /// axes will not be autoscaling. /// </summary> public bool AutoScaleAutoGeneratedAxes { get => ps_.AutoScaleAutoGeneratedAxes; set => ps_.AutoScaleAutoGeneratedAxes = value; } /// <summary> /// Sets the title to be drawn using a solid brush of this color. /// </summary> public Color TitleColor { set => ps_.TitleColor = value; } /// <summary> /// The brush used for drawing the title. /// </summary> public Brush TitleBrush { get => ps_.TitleBrush; set => ps_.TitleBrush = value; } /// <summary> /// Remove a drawable object from the plot surface. /// </summary> /// <param name="p">the drawable to remove</param> /// <param name="updateAxes">whether or not to update the axes after removing the idrawable.</param> public void Remove(IDrawable p, bool updateAxes) { ps_.Remove(p, updateAxes); } /// <summary> /// Gets an array list containing all drawables currently added to the PlotSurface2D. /// </summary> public List<IDrawable> Drawables => ps_.Drawables; } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using log4net; using Mail2Bug.Email; using Mail2Bug.Email.EWS; [assembly: CLSCompliant(false)] namespace Mail2Bug { class MainApp { /// <summary> /// The main entry point for the windows application. /// </summary> [STAThread] public static void Main(string[] args) // string[] args { if(args.Contains("-break")) { Logger.Info("Breaking into debugger"); Debugger.Break(); } try { string configPath = ConfigurationManager.AppSettings["ConfigPath"]; string configsFilePattern = ConfigurationManager.AppSettings["ConfigFilePattern"]; var configFiles = Directory.GetFiles(configPath, configsFilePattern); if (configFiles.Length == 0) { Logger.ErrorFormat("No configs found (path='{0}', pattern='{1}')", configPath, configsFilePattern); throw new ConfigurationErrorsException("No configs found"); } var configs = new List<Config>(); var configTimeStamps = new Dictionary<string, DateTime>(); foreach (var configFile in configFiles) { // Save the timestamp for the config so that we can detect if it changed later on configTimeStamps[configFile] = File.GetLastWriteTime(configFile); // Load the config and add it to the list. // If loading failed, print error message and continue var cfg = TryLoadConfig(configFile); if (cfg == null) { Logger.ErrorFormat("Couldn't load config file {0}. Skipping that config file.", configFile); continue; } configs.Add(cfg); } if (configs.Count == 0) { throw new ConfigurationErrorsException("None of the configs were valid"); } InitInstances(configs); var iterations = ReadIntFromAppConfig("Iterations", 200); var interval = TimeSpan.FromSeconds(ReadIntFromAppConfig("IntervalInSeconds", 1)); var useThreads = ReadBoolFromAppConfig("UseThreads", false); for (var i = 0; i < iterations; ++i ) { Logger.InfoFormat("{0} Iteration {1} {0}", new string('-', 15), i); RunInstances(useThreads); if (IsConfigsChanged(configTimeStamps)) { break; } Thread.CurrentThread.Join(interval); // Sleep between iterations } foreach (var instance in _instances) { var disposable = instance as IDisposable; if (disposable != null) { disposable.Dispose(); } } } catch (Exception exception) { Logger.ErrorFormat("Exception caught in main - aborting. {0}", exception); } } private static Config TryLoadConfig(string configFile) { try { return Config.GetConfig(configFile); } catch(Exception ex) { Logger.ErrorFormat("Exception when trying to load config from file {0}\n{1}", configFile, ex); } return null; } private static bool IsConfigsChanged(Dictionary<string, DateTime> configTimeStamps) { foreach (var timeStampEntry in configTimeStamps) { if (timeStampEntry.Value != File.GetLastWriteTime(timeStampEntry.Key)) { Logger.InfoFormat("Config '{0}' changed. Breaking.", timeStampEntry.Key); return true; } } return false; } private static void RunInstances(bool useThreads) { // At the beginning of each iteration, update the inboxes of EWS connections - specifically // for instances relying on RecipientsMailboxManagerRouter. // We cannot make the calls to process inboxes implicit in RecipientMailboxManagerRouter.GetMessages // because then it would be called by each instance, which is exactly what we want to avoid. // The alternatives are: // * Expose a function to process inboxes and call it at the beginning of each iteration (which is the // solution implemented her) // * Add logic to RecipientsMailboxManagerRouter to detect wheter a call to ProcessInbox is needed or // not based on whether new messages were received or similar logic. I initially implemented this logic // but then decided it's adding too much complexity compared to the small benefit of a somewhat cleaner // abstraction. // If we decide otherwise in the future, we can simply add it in RecipientsMailboxManagerRouter and then // get rid of the ProcessInboxes public method and the call to it here. _ewsConnectionManger.ProcessInboxes(); if (!useThreads) { RunInstancesSingleThreaded(); return; } RunInstancesMultithreaded(); } private static void RunInstancesSingleThreaded() { var task = new Task(() => _instances.ForEach(x => x.RunInstance())); task.Start(); bool done = task.Wait(_timeoutPerIteration); if (!done) { throw new TimeoutException(string.Format( "Running instances took more than {0} minutes", _timeoutPerIteration.TotalMinutes)); } } private static void RunInstancesMultithreaded() { // Multi-threaded invocation - dispatch each instance to run on a thread and wait for all threads to finish var tasks = new List<Task>(); var sw = new Stopwatch(); sw.Start(); _instances.ForEach(x => tasks.Add(new Task(x.RunInstance))); tasks.ForEach(x => x.Start()); tasks.ForEach(x => x.Wait(GetRemainigTimeout(sw, _timeoutPerIteration))); foreach (var task in tasks) { if (!task.IsCompleted) { throw new TimeoutException(string.Format( "Running instances took more than {0} minutes", _timeoutPerIteration.TotalMinutes)); } } } private static TimeSpan GetRemainigTimeout(Stopwatch sw, TimeSpan totalTimeout) { var remainigTimeout = totalTimeout - sw.Elapsed; return remainigTimeout.CompareTo(TimeSpan.Zero) > 0 ? remainigTimeout : TimeSpan.Zero; } private static void InitInstances(IEnumerable<Config> configs) { _instances = new List<IInstanceRunner>(); _ewsConnectionManger = new EWSConnectionManger(true); var mailboxManagerFactory = new MailboxManagerFactory(_ewsConnectionManger); foreach (var config in configs) { foreach (var instance in config.Instances) { try { var usePersistentInstances = ReadBoolFromAppConfig("UsePersistentInstances", true); Logger.InfoFormat("Initializing engine for instance '{0}' (Persistent? {1})", instance.Name, usePersistentInstances); if (usePersistentInstances) { _instances.Add(new PersistentInstanceRunner(instance, mailboxManagerFactory)); } else { _instances.Add(new TemporaryInstanceRunner(instance, mailboxManagerFactory)); } Logger.InfoFormat("Finished initialization of engine for instance '{0}'", instance.Name); } catch (Exception ex) { Logger.ErrorFormat("Exception while initializing instance '{0}'\n{1}", instance.Name, ex); } } } } private static int ReadIntFromAppConfig(string setting, int defaultValue) { var value = ConfigurationManager.AppSettings[setting]; return string.IsNullOrEmpty(value) ? defaultValue : int.Parse(value); } private static bool ReadBoolFromAppConfig(string setting, bool defaultValue) { var value = ConfigurationManager.AppSettings[setting]; return string.IsNullOrEmpty(value) ? defaultValue : bool.Parse(value); } private static List<IInstanceRunner> _instances; private static TimeSpan _timeoutPerIteration = TimeSpan.FromMinutes(30); private static readonly ILog Logger = LogManager.GetLogger(typeof (MainApp)); private static EWSConnectionManger _ewsConnectionManger; } }
/* * Copyright (2011) Intel Corporation and Sandia Corporation. Under the * terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the * U.S. Government retains certain rights in this software. * * 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 Intel Corporation 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 INTEL OR ITS * 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.IO; using System.Reflection; using System.Text; using HttpServer; using HttpServer.FormDecoders; using log4net; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using WaterWars; using WaterWars.Models; namespace WaterWars.WebServices { public class BuyPointServices : AbstractServices { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public const string BUY_POINT_PATH = "buypoint/"; public const string ASSETS_PATH = "assets"; public const string FIELD_PATH = "field"; public BuyPointServices(WaterWarsController controller) : base(controller) {} public Hashtable HandleRequest(string requestUri, Hashtable request) { // m_log.InfoFormat("[WATER WARS]: Handling buy point request for {0}", requestUri); requestUri = requestUri.Substring(BUY_POINT_PATH.Length); Hashtable response = null; List<string> requestComponents = new List<string>(requestUri.Split(new char[] { '/' })); string rawBpId = requestComponents[0]; if (requestComponents.Count == 1) { response = HandleBuyPointChange(rawBpId, request); } else if (requestComponents[1] == ASSETS_PATH) { string rawGameAssetId = requestComponents[2]; string method = ((string)request["_method"]).ToLower(); if ("delete" == method) response = HandleSellAsset(rawBpId, rawGameAssetId, request); else if ("put" == method) response = HandleChangeAsset(rawBpId, rawGameAssetId, request); else response = HandleGetAsset(rawBpId, rawGameAssetId, request); } else if (requestComponents[1] == FIELD_PATH) { string rawFieldId = requestComponents[2]; string method = ((string)request["_method"]).ToLower(); if ("post" == method) response = HandleBuyAsset(rawBpId, rawFieldId, request); } return response; } protected Hashtable HandleBuyPointChange(string rawBpId, Hashtable request) { JObject json = GetJsonFromPost(request); string name = (string)json.SelectToken("Name"); bool changingName = name != null; string rawDevelopmentRightsBuyerId = (string)json.SelectToken("DevelopmentRightsOwner.Uuid.Guid"); bool buyingDevelopmentRights = rawDevelopmentRightsBuyerId != null; string rawWaterRightsBuyerId = (string)json.SelectToken("WaterRightsOwner.Uuid.Guid"); bool buyingWaterRights = rawWaterRightsBuyerId != null; int? developmentRightsPrice = (int?)json.SelectToken("DevelopmentRightsPrice"); int? waterRightsPrice = (int?)json.SelectToken("WaterRightsPrice"); int? combinedRightsPrice = (int?)json.SelectToken("CombinedPrice"); // m_log.InfoFormat( // "rawBpId [{0}], buyingDevelopmentRights [{1}], buyingWaterRights [{2}]", // rawBpId, buyingDevelopmentRights, buyingWaterRights); UUID bpId = WaterWarsUtils.ParseRawId(rawBpId); BuyPoint bp = null; m_controller.Game.BuyPoints.TryGetValue(bpId, out bp); if (changingName) return HandleChangeName(bp, name); else if (buyingDevelopmentRights || buyingWaterRights) return HandleBuyRights( bp, buyingDevelopmentRights, buyingWaterRights, rawDevelopmentRightsBuyerId, rawWaterRightsBuyerId, developmentRightsPrice, waterRightsPrice, combinedRightsPrice, request); // TODO: Deal with error situations: uuid not valid, no such buy point, not enough money, etc. Hashtable reply = new Hashtable(); reply["int_response_code"] = 200; // 200 OK reply["str_response_string"] = "hoorah"; reply["content_type"] = "text/plain"; return reply; } protected Hashtable HandleChangeName(BuyPoint bp, string newName) { m_controller.State.ChangeBuyPointName(bp, newName); Hashtable reply = new Hashtable(); reply["int_response_code"] = 200; // 200 OK reply["str_response_string"] = "sausages"; reply["content_type"] = "text/plain"; return reply; } protected Hashtable HandleBuyRights( BuyPoint bp, bool buyingDevelopmentRights, bool buyingWaterRights, string rawDevelopmentRightsBuyerId, string rawWaterRightsBuyerId, int? developmentRightsPrice, int? waterRightsPrice, int? combinedRightsPrice, Hashtable request) { if (bp.DevelopmentRightsOwner == Player.None) { m_controller.Resolver.BuyLandRights(bp.Uuid.ToString(), rawDevelopmentRightsBuyerId); } else { UUID developmentRightsBuyerId = UUID.Zero; if (rawDevelopmentRightsBuyerId != null) developmentRightsBuyerId = WaterWarsUtils.ParseRawId(rawDevelopmentRightsBuyerId); UUID waterRightsBuyerId = UUID.Zero; if (rawWaterRightsBuyerId != null) waterRightsBuyerId = WaterWarsUtils.ParseRawId(rawWaterRightsBuyerId); // TODO: Do player ownership checks later when we have access to this via security if (buyingDevelopmentRights && buyingWaterRights) { if (null == combinedRightsPrice) throw new Exception( string.Format("No combined rights price specified for sale of {0} rights", bp)); m_controller.Resolver.SellRights( bp, developmentRightsBuyerId, RightsType.Combined, (int)combinedRightsPrice); } else if (buyingDevelopmentRights) { if (null == developmentRightsPrice) throw new Exception( string.Format("No development rights price specified for sale of {0} rights", bp)); m_controller.Resolver.SellRights( bp, developmentRightsBuyerId, RightsType.Development, (int)developmentRightsPrice); } else if (buyingWaterRights) { if (null == waterRightsPrice) throw new Exception( string.Format("No water rights price specified for sale of {0} rights", bp)); m_controller.Resolver.SellRights( bp, waterRightsBuyerId, RightsType.Water, (int)waterRightsPrice); } } // TODO: Deal with error situations: uuid not valid, no such buy point, not enough money, etc. Hashtable reply = new Hashtable(); reply["int_response_code"] = 200; // 200 OK reply["str_response_string"] = "hoorah"; reply["content_type"] = "text/plain"; return reply; } protected Hashtable HandleGetAsset(string rawBpId, string rawGameAssetId, Hashtable request) { Hashtable reply = new Hashtable(); UUID bpId = new UUID(rawBpId); IDictionary<UUID, BuyPoint> buyPoints = m_controller.Game.BuyPoints; BuyPoint bp; buyPoints.TryGetValue(bpId, out bp); UUID gameAssetId = new UUID(rawGameAssetId); AbstractGameAsset ga; lock (bp.GameAssets) bp.GameAssets.TryGetValue(gameAssetId, out ga); reply["int_response_code"] = 200; // 200 OK reply["str_response_string"] = BuyPointServices.Serialize(ga); reply["content_type"] = "text/plain"; return reply; } /// <summary> /// Buy an asset in a given field. /// </summary> /// <param name="rawBpId"></param> /// <param name="rawFieldId"></param> /// <param name="request"></param> /// <returns></returns> protected Hashtable HandleBuyAsset(string rawBpId, string rawFieldId, Hashtable request) { JObject json = GetJsonFromPost(request); int level = (int)json.SelectToken("Level"); // m_log.InfoFormat( // "[WATER WARS]: Processing webservices [buy game asset] request for buypoint {0}, field {1} to level {2}", // rawBpId, rawFieldId, level); // Automatically switch to the game asset from the field AbstractGameAsset ga = m_controller.Resolver.BuildGameAsset(rawBpId, rawFieldId, level); // TODO: return success condition Hashtable reply = new Hashtable(); reply["int_response_code"] = 200; // 200 OK reply["str_response_string"] = "oh yeah baby"; reply["content_type"] = "text/plain"; m_controller.ViewerWebServices.PlayerServices.SetLastSelected( ga.Field.BuyPoint.DevelopmentRightsOwner.Uuid, ga); return reply; } protected Hashtable HandleChangeAsset(string rawBpId, string rawAssetId, Hashtable request) { bool upgradeAsset = false; bool continueBuild = false; bool sellAssetToEconomy = false; bool waterAllocated = false; JObject json = GetJsonFromPost(request); int? level = (int?)json.SelectToken("Level"); if (level != null) upgradeAsset = true; int? waterAllocation = (int?)json.SelectToken("WaterAllocated"); if (waterAllocation != null) waterAllocated = true; if (json.SelectToken("OwnerUuid") != null) sellAssetToEconomy = true; if (json.SelectToken("TurnsBuilt") != null) continueBuild = true; if (upgradeAsset) { // m_log.InfoFormat( // "[WATER WARS]: Processing webservices upgrade game asset request for buypoint {0}, asset {1} to level {2}", // rawBpId, rawAssetId, level); m_controller.Resolver.UpgradeGameAsset(rawBpId, rawAssetId, (int)level); } if (waterAllocated) { if (null == waterAllocation) throw new Exception( string.Format( "No amount specified for allocation to game asset {0} on parcel {1}", rawAssetId, rawBpId)); m_controller.Resolver.UseWater( rawBpId, rawAssetId, UUID.Zero.ToString(), (int)waterAllocation); } if (sellAssetToEconomy) m_controller.Resolver.SellGameAssetToEconomy(rawBpId, rawAssetId); if (continueBuild) m_controller.Resolver.ContinueBuildingGameAsset(rawBpId, rawAssetId); // TODO: return success condition Hashtable reply = new Hashtable(); reply["int_response_code"] = 200; // 200 OK reply["str_response_string"] = "oh yeah baby"; reply["content_type"] = "text/plain"; return reply; } protected Hashtable HandleSellAsset(string rawBpId, string rawAssetId, Hashtable request) { Field f = m_controller.Resolver.RemoveGameAsset(rawBpId, rawAssetId); // TODO: properly return success condition Hashtable reply = new Hashtable(); reply["int_response_code"] = 200; // 200 OK reply["str_response_string"] = "uh huh, it's going on"; reply["content_type"] = "text/plain"; if (f != null) m_controller.ViewerWebServices.PlayerServices.SetLastSelected(f.BuyPoint.DevelopmentRightsOwner.Uuid, f); return reply; } public static string SerializeBuyPoint(BuyPoint bp) { return JsonConvert.SerializeObject(bp, Formatting.Indented); } public static string Serialize(AbstractGameAsset ga) { return JsonConvert.SerializeObject(ga, Formatting.Indented); } } /* public class WaterWarsContractResolver : DefaultContractResolver { protected override JsonProperty CreateProperty(JsonObjectContract contract, MemberInfo member) { JsonProperty p = base.CreateProperties(contract, member); if (member.GetType() == typeof(System.Enum)) { p.PropertyType = typeof(String); // JsonProperty p = base.CreateProperties(contract, member); // only serializer properties that start with the specified character properties = properties.Where(p => p.PropertyName.StartsWith(_startingWithChar.ToString())).ToList(); return properties; } } */ }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace HarmonyLib { internal class PatchSorter { List<PatchSortingWrapper> patches; HashSet<PatchSortingWrapper> handledPatches; List<PatchSortingWrapper> result; List<PatchSortingWrapper> waitingList; internal Patch[] sortedPatchArray; readonly bool debug; /// <summary>Creates a patch sorter</summary> /// <param name="patches">Array of patches that will be sorted</param> /// <param name="debug">Use debugging</param> internal PatchSorter(Patch[] patches, bool debug) { // Build the list of all patches first to be able to create dependency relationships. this.patches = patches.Select(x => new PatchSortingWrapper(x)).ToList(); this.debug = debug; // For each node find and bidirectionally register all it's dependencies. foreach (var node in this.patches) { node.AddBeforeDependency(this.patches.Where(x => node.innerPatch.before.Contains(x.innerPatch.owner))); node.AddAfterDependency(this.patches.Where(x => node.innerPatch.after.Contains(x.innerPatch.owner))); } // Sort list based on priority/index. This order will be maintain throughout the rest of the sorting process. this.patches.Sort(); } /// <summary>Sorts internal PatchSortingWrapper collection and caches the results. /// After first run the result is provided from the cache.</summary> /// <param name="original">The original method</param> /// <returns>The sorted patch methods</returns> internal List<MethodInfo> Sort(MethodBase original) { // Check if cache exists and the method was used before. if (sortedPatchArray is object) return sortedPatchArray.Select(x => x.GetMethod(original)).ToList(); // Initialize internal structures used for sorting. handledPatches = new HashSet<PatchSortingWrapper>(); waitingList = new List<PatchSortingWrapper>(); result = new List<PatchSortingWrapper>(patches.Count); var queue = new Queue<PatchSortingWrapper>(patches); // Sorting is performed by reading patches one-by-one from the queue and outputting them if // they have no unresolved dependencies. // If patch does have unresolved dependency it is put into waiting list instead that is processed later. // Patch collection is already presorted and won't loose that order throughout the rest of the process unless // required for dependency resolution. while (queue.Count != 0) { foreach (var node in queue) // Patch does not have any unresolved dependencies and can be moved to output. if (node.after.All(x => handledPatches.Contains(x))) { AddNodeToResult(node); // If patch had some before dependencies we need to check waiting list because they may have had higher priority. if (node.before.Count == 0) continue; ProcessWaitingList(); } else waitingList.Add(node); // If at this point waiting list is not empty then that means there is are cyclic dependencies and we // need to remove on of them. CullDependency(); // Try to sort the rest of the patches again. queue = new Queue<PatchSortingWrapper>(waitingList); waitingList.Clear(); } // Build cache and release all other internal structures for GC. sortedPatchArray = result.Select(x => x.innerPatch).ToArray(); handledPatches = null; waitingList = null; patches = null; return sortedPatchArray.Select(x => x.GetMethod(original)).ToList(); } /// <summary>Checks if the sorter was created with the same patch list and as a result can be reused to /// get the sorted order of the patches.</summary> /// <param name="patches">List of patches to check against</param> /// <returns>true if equal</returns> internal bool ComparePatchLists(Patch[] patches) { if (sortedPatchArray is null) _ = Sort(null); return patches is object && sortedPatchArray.Length == patches.Length && sortedPatchArray.All(x => patches.Contains(x, new PatchDetailedComparer())); } /// <summary>Removes one unresolved dependency from the least important patch.</summary> void CullDependency() { // Waiting list is already sorted on priority so start from the end. // It should always be the last element, otherwise it would not be on the waiting list because // it should have been removed by the ProcessWaitingList(). // But if for some reason it is on the list we will just find the next target. for (var i = waitingList.Count - 1; i >= 0; i--) // Find first unresolved dependency and remove it. foreach (var afterNode in waitingList[i].after) if (!handledPatches.Contains(afterNode)) { waitingList[i].RemoveAfterDependency(afterNode); if (debug) { var part1 = afterNode.innerPatch.PatchMethod.FullDescription(); var part2 = waitingList[i].innerPatch.PatchMethod.FullDescription(); FileLog.LogBuffered($"Breaking dependance between {part1} and {part2}"); } return; } } /// <summary>Outputs all unblocked patches from the waiting list to results list</summary> void ProcessWaitingList() { // Need to change loop limit as patches are removed from the waiting list. var waitingListCount = waitingList.Count; // Counter for the loop is handled internally because we want to restart after each patch that is removed. // Waiting list preserves the original sorted order so after each patch output new higher priority patches // may become unblocked and as such have to be outputted first. // Processing ends when there are no more unblocked patches in the waiting list. for (var i = 0; i < waitingListCount;) { var node = waitingList[i]; // All node dependencies are satisfied, ready for output. if (node.after.All(handledPatches.Contains)) { _ = waitingList.Remove(node); AddNodeToResult(node); // Decrement the waiting list length and reset current position counter. waitingListCount--; i = 0; } else i++; } } /// <summary>Adds patch to both results list and handled patches set</summary> /// <param name="node">Patch to add</param> void AddNodeToResult(PatchSortingWrapper node) { result.Add(node); _ = handledPatches.Add(node); } /// <summary>Wrapper used over the Patch object to allow faster dependency access and /// dependency removal in case of cyclic dependencies</summary> class PatchSortingWrapper : IComparable { internal readonly HashSet<PatchSortingWrapper> after; internal readonly HashSet<PatchSortingWrapper> before; internal readonly Patch innerPatch; /// <summary>Create patch wrapper object used for sorting</summary> /// <param name="patch">Patch to wrap</param> internal PatchSortingWrapper(Patch patch) { innerPatch = patch; before = new HashSet<PatchSortingWrapper>(); after = new HashSet<PatchSortingWrapper>(); } /// <summary>Determines how patches sort</summary> /// <param name="obj">The other patch</param> /// <returns>integer to define sort order (-1, 0, 1)</returns> public int CompareTo(object obj) { var p = obj as PatchSortingWrapper; return PatchInfoSerialization.PriorityComparer(p?.innerPatch, innerPatch.index, innerPatch.priority); } /// <summary>Determines whether patches are equal</summary> /// <param name="obj">The other patch</param> /// <returns>true if equal</returns> public override bool Equals(object obj) { return obj is PatchSortingWrapper wrapper && innerPatch.PatchMethod == wrapper.innerPatch.PatchMethod; } /// <summary>Hash function</summary> /// <returns>A hash code</returns> public override int GetHashCode() { return innerPatch.PatchMethod.GetHashCode(); } /// <summary>Bidirectionally registers Patches as after dependencies</summary> /// <param name="dependencies">List of dependencies to register</param> internal void AddBeforeDependency(IEnumerable<PatchSortingWrapper> dependencies) { foreach (var i in dependencies) { _ = before.Add(i); _ = i.after.Add(this); } } /// <summary>Bidirectionally registers Patches as before dependencies</summary> /// <param name="dependencies">List of dependencies to register</param> internal void AddAfterDependency(IEnumerable<PatchSortingWrapper> dependencies) { foreach (var i in dependencies) { _ = after.Add(i); _ = i.before.Add(this); } } /// <summary>Bidirectionally removes Patch from after dependencies</summary> /// <param name="afterNode">Patch to remove</param> internal void RemoveAfterDependency(PatchSortingWrapper afterNode) { _ = after.Remove(afterNode); _ = afterNode.before.Remove(this); } /// <summary>Bidirectionally removes Patch from before dependencies</summary> /// <param name="beforeNode">Patch to remove</param> internal void RemoveBeforeDependency(PatchSortingWrapper beforeNode) { _ = before.Remove(beforeNode); _ = beforeNode.after.Remove(this); } } internal class PatchDetailedComparer : IEqualityComparer<Patch> { public bool Equals(Patch x, Patch y) { return y is object && x is object && x.owner == y.owner && x.PatchMethod == y.PatchMethod && x.index == y.index && x.priority == y.priority && x.before.Length == y.before.Length && x.after.Length == y.after.Length && x.before.All(y.before.Contains) && x.after.All(y.after.Contains); } public int GetHashCode(Patch obj) { return obj.GetHashCode(); } } } }
// 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 Permute4x64Double85() { var test = new ImmUnaryOpTest__Permute4x64Double85(); 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 ImmUnaryOpTest__Permute4x64Double85 { private struct TestStruct { public Vector256<Double> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld), ref Unsafe.As<Double, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__Permute4x64Double85 testClass) { var result = Avx2.Permute4x64(_fld, 85); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static Double[] _data = new Double[Op1ElementCount]; private static Vector256<Double> _clsVar; private Vector256<Double> _fld; private SimpleUnaryOpTest__DataTable<Double, Double> _dataTable; static ImmUnaryOpTest__Permute4x64Double85() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar), ref Unsafe.As<Double, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); } public ImmUnaryOpTest__Permute4x64Double85() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld), ref Unsafe.As<Double, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new SimpleUnaryOpTest__DataTable<Double, Double>(_data, new Double[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.Permute4x64( Unsafe.Read<Vector256<Double>>(_dataTable.inArrayPtr), 85 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.Permute4x64( Avx.LoadVector256((Double*)(_dataTable.inArrayPtr)), 85 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.Permute4x64( Avx.LoadAlignedVector256((Double*)(_dataTable.inArrayPtr)), 85 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Permute4x64), new Type[] { typeof(Vector256<Double>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Double>>(_dataTable.inArrayPtr), (byte)85 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Permute4x64), new Type[] { typeof(Vector256<Double>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Double*)(_dataTable.inArrayPtr)), (byte)85 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.Permute4x64), new Type[] { typeof(Vector256<Double>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Double*)(_dataTable.inArrayPtr)), (byte)85 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.Permute4x64( _clsVar, 85 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector256<Double>>(_dataTable.inArrayPtr); var result = Avx2.Permute4x64(firstOp, 85); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Avx.LoadVector256((Double*)(_dataTable.inArrayPtr)); var result = Avx2.Permute4x64(firstOp, 85); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Avx.LoadAlignedVector256((Double*)(_dataTable.inArrayPtr)); var result = Avx2.Permute4x64(firstOp, 85); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__Permute4x64Double85(); var result = Avx2.Permute4x64(test._fld, 85); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.Permute4x64(_fld, 85); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.Permute4x64(test._fld, 85); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _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<Double> firstOp, void* result, [CallerMemberName] string method = "") { Double[] inArray = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Double[] inArray = new Double[Op1ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Double[] firstOp, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(firstOp[1]) != BitConverter.DoubleToInt64Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(firstOp[1]) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.Permute4x64)}<Double>(Vector256<Double><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Xunit; namespace System.Linq.Expressions.Tests { public static class NonLiftedComparisonGreaterThanNullableTests { #region Test methods [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNonLiftedComparisonGreaterThanNullableByteTest(bool useInterpreter) { byte?[] values = new byte?[] { null, 0, 1, byte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonGreaterThanNullableByte(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNonLiftedComparisonGreaterThanNullableCharTest(bool useInterpreter) { char?[] values = new char?[] { null, '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonGreaterThanNullableChar(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNonLiftedComparisonGreaterThanNullableDecimalTest(bool useInterpreter) { decimal?[] values = new decimal?[] { null, decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonGreaterThanNullableDecimal(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNonLiftedComparisonGreaterThanNullableDoubleTest(bool useInterpreter) { double?[] values = new double?[] { null, 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonGreaterThanNullableDouble(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNonLiftedComparisonGreaterThanNullableFloatTest(bool useInterpreter) { float?[] values = new float?[] { null, 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonGreaterThanNullableFloat(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNonLiftedComparisonGreaterThanNullableIntTest(bool useInterpreter) { int?[] values = new int?[] { null, 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonGreaterThanNullableInt(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNonLiftedComparisonGreaterThanNullableLongTest(bool useInterpreter) { long?[] values = new long?[] { null, 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonGreaterThanNullableLong(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNonLiftedComparisonGreaterThanNullableSByteTest(bool useInterpreter) { sbyte?[] values = new sbyte?[] { null, 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonGreaterThanNullableSByte(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNonLiftedComparisonGreaterThanNullableShortTest(bool useInterpreter) { short?[] values = new short?[] { null, 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonGreaterThanNullableShort(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNonLiftedComparisonGreaterThanNullableUIntTest(bool useInterpreter) { uint?[] values = new uint?[] { null, 0, 1, uint.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonGreaterThanNullableUInt(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNonLiftedComparisonGreaterThanNullableULongTest(bool useInterpreter) { ulong?[] values = new ulong?[] { null, 0, 1, ulong.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonGreaterThanNullableULong(values[i], values[j], useInterpreter); } } } [Theory, ClassData(typeof(CompilationTypes))] public static void CheckNonLiftedComparisonGreaterThanNullableUShortTest(bool useInterpreter) { ushort?[] values = new ushort?[] { null, 0, 1, ushort.MaxValue }; for (int i = 0; i < values.Length; i++) { for (int j = 0; j < values.Length; j++) { VerifyComparisonGreaterThanNullableUShort(values[i], values[j], useInterpreter); } } } #endregion #region Test verifiers private static void VerifyComparisonGreaterThanNullableByte(byte? a, byte? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(byte?)), Expression.Constant(b, typeof(byte?)), false, null)); Func<bool> f = e.Compile(useInterpreter); bool expected = a > b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonGreaterThanNullableChar(char? a, char? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(char?)), Expression.Constant(b, typeof(char?)), false, null)); Func<bool> f = e.Compile(useInterpreter); bool expected = a > b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonGreaterThanNullableDecimal(decimal? a, decimal? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(decimal?)), Expression.Constant(b, typeof(decimal?)), false, null)); Func<bool> f = e.Compile(useInterpreter); bool expected = a > b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonGreaterThanNullableDouble(double? a, double? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(double?)), Expression.Constant(b, typeof(double?)), false, null)); Func<bool> f = e.Compile(useInterpreter); bool expected = a > b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonGreaterThanNullableFloat(float? a, float? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(float?)), Expression.Constant(b, typeof(float?)), false, null)); Func<bool> f = e.Compile(useInterpreter); bool expected = a > b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonGreaterThanNullableInt(int? a, int? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(int?)), Expression.Constant(b, typeof(int?)), false, null)); Func<bool> f = e.Compile(useInterpreter); bool expected = a > b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonGreaterThanNullableLong(long? a, long? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(long?)), Expression.Constant(b, typeof(long?)), false, null)); Func<bool> f = e.Compile(useInterpreter); bool expected = a > b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonGreaterThanNullableSByte(sbyte? a, sbyte? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(sbyte?)), Expression.Constant(b, typeof(sbyte?)), false, null)); Func<bool> f = e.Compile(useInterpreter); bool expected = a > b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonGreaterThanNullableShort(short? a, short? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(short?)), Expression.Constant(b, typeof(short?)), false, null)); Func<bool> f = e.Compile(useInterpreter); bool expected = a > b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonGreaterThanNullableUInt(uint? a, uint? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(uint?)), Expression.Constant(b, typeof(uint?)), false, null)); Func<bool> f = e.Compile(useInterpreter); bool expected = a > b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonGreaterThanNullableULong(ulong? a, ulong? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(ulong?)), Expression.Constant(b, typeof(ulong?)), false, null)); Func<bool> f = e.Compile(useInterpreter); bool expected = a > b; bool result = f(); Assert.Equal(expected, result); } private static void VerifyComparisonGreaterThanNullableUShort(ushort? a, ushort? b, bool useInterpreter) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(ushort?)), Expression.Constant(b, typeof(ushort?)), false, null)); Func<bool> f = e.Compile(useInterpreter); bool expected = a > b; bool result = f(); Assert.Equal(expected, result); } #endregion } }
#region Apache License // // 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. // #endregion // SSCLI 1.0 has no support for ADO.NET #if !SSCLI using System; using System.Collections; using System.Configuration; using System.Data; using System.IO; using log4net.Util; using log4net.Layout; using log4net.Core; namespace log4net.Appender { /// <summary> /// Appender that logs to a database. /// </summary> /// <remarks> /// <para> /// <see cref="AdoNetAppender"/> appends logging events to a table within a /// database. The appender can be configured to specify the connection /// string by setting the <see cref="ConnectionString"/> property. /// The connection type (provider) can be specified by setting the <see cref="ConnectionType"/> /// property. For more information on database connection strings for /// your specific database see <a href="http://www.connectionstrings.com/">http://www.connectionstrings.com/</a>. /// </para> /// <para> /// Records are written into the database either using a prepared /// statement or a stored procedure. The <see cref="CommandType"/> property /// is set to <see cref="System.Data.CommandType.Text"/> (<c>System.Data.CommandType.Text</c>) to specify a prepared statement /// or to <see cref="System.Data.CommandType.StoredProcedure"/> (<c>System.Data.CommandType.StoredProcedure</c>) to specify a stored /// procedure. /// </para> /// <para> /// The prepared statement text or the name of the stored procedure /// must be set in the <see cref="CommandText"/> property. /// </para> /// <para> /// The prepared statement or stored procedure can take a number /// of parameters. Parameters are added using the <see cref="AddParameter"/> /// method. This adds a single <see cref="AdoNetAppenderParameter"/> to the /// ordered list of parameters. The <see cref="AdoNetAppenderParameter"/> /// type may be subclassed if required to provide database specific /// functionality. The <see cref="AdoNetAppenderParameter"/> specifies /// the parameter name, database type, size, and how the value should /// be generated using a <see cref="ILayout"/>. /// </para> /// </remarks> /// <example> /// An example of a SQL Server table that could be logged to: /// <code lang="SQL"> /// CREATE TABLE [dbo].[Log] ( /// [ID] [int] IDENTITY (1, 1) NOT NULL , /// [Date] [datetime] NOT NULL , /// [Thread] [varchar] (255) NOT NULL , /// [Level] [varchar] (20) NOT NULL , /// [Logger] [varchar] (255) NOT NULL , /// [Message] [varchar] (4000) NOT NULL /// ) ON [PRIMARY] /// </code> /// </example> /// <example> /// An example configuration to log to the above table: /// <code lang="XML" escaped="true"> /// <appender name="AdoNetAppender_SqlServer" type="log4net.Appender.AdoNetAppender" > /// <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> /// <connectionString value="data source=SQLSVR;initial catalog=test_log4net;integrated security=false;persist security info=True;User ID=sa;Password=sa" /> /// <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)" /> /// <parameter> /// <parameterName value="@log_date" /> /// <dbType value="DateTime" /> /// <layout type="log4net.Layout.PatternLayout" value="%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}" /> /// </parameter> /// <parameter> /// <parameterName value="@thread" /> /// <dbType value="String" /> /// <size value="255" /> /// <layout type="log4net.Layout.PatternLayout" value="%thread" /> /// </parameter> /// <parameter> /// <parameterName value="@log_level" /> /// <dbType value="String" /> /// <size value="50" /> /// <layout type="log4net.Layout.PatternLayout" value="%level" /> /// </parameter> /// <parameter> /// <parameterName value="@logger" /> /// <dbType value="String" /> /// <size value="255" /> /// <layout type="log4net.Layout.PatternLayout" value="%logger" /> /// </parameter> /// <parameter> /// <parameterName value="@message" /> /// <dbType value="String" /> /// <size value="4000" /> /// <layout type="log4net.Layout.PatternLayout" value="%message" /> /// </parameter> /// </appender> /// </code> /// </example> /// <author>Julian Biddle</author> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> /// <author>Lance Nehring</author> public class AdoNetAppender : BufferingAppenderSkeleton { #region Public Instance Constructors /// <summary> /// Initializes a new instance of the <see cref="AdoNetAppender" /> class. /// </summary> /// <remarks> /// Public default constructor to initialize a new instance of this class. /// </remarks> public AdoNetAppender() { ConnectionType = "System.Data.OleDb.OleDbConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"; UseTransactions = true; CommandType = System.Data.CommandType.Text; m_parameters = new ArrayList(); ReconnectOnError = false; } #endregion // Public Instance Constructors #region Public Instance Properties /// <summary> /// Gets or sets the database connection string that is used to connect to /// the database. /// </summary> /// <value> /// The database connection string used to connect to the database. /// </value> /// <remarks> /// <para> /// The connections string is specific to the connection type. /// See <see cref="ConnectionType"/> for more information. /// </para> /// </remarks> /// <example>Connection string for MS Access via ODBC: /// <code>"DSN=MS Access Database;UID=admin;PWD=;SystemDB=C:\data\System.mdw;SafeTransactions = 0;FIL=MS Access;DriverID = 25;DBQ=C:\data\train33.mdb"</code> /// </example> /// <example>Another connection string for MS Access via ODBC: /// <code>"Driver={Microsoft Access Driver (*.mdb)};DBQ=C:\Work\cvs_root\log4net-1.2\access.mdb;UID=;PWD=;"</code> /// </example> /// <example>Connection string for MS Access via OLE DB: /// <code>"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Work\cvs_root\log4net-1.2\access.mdb;User Id=;Password=;"</code> /// </example> public string ConnectionString { get { return m_connectionString; } set { m_connectionString = value; } } /// <summary> /// The appSettings key from App.Config that contains the connection string. /// </summary> public string AppSettingsKey { get { return m_appSettingsKey; } set { m_appSettingsKey = value; } } #if NET_2_0 /// <summary> /// The connectionStrings key from App.Config that contains the connection string. /// </summary> /// <remarks> /// This property requires at least .NET 2.0. /// </remarks> public string ConnectionStringName { get { return m_connectionStringName; } set { m_connectionStringName = value; } } #endif /// <summary> /// Gets or sets the type name of the <see cref="IDbConnection"/> connection /// that should be created. /// </summary> /// <value> /// The type name of the <see cref="IDbConnection"/> connection. /// </value> /// <remarks> /// <para> /// The type name of the ADO.NET provider to use. /// </para> /// <para> /// The default is to use the OLE DB provider. /// </para> /// </remarks> /// <example>Use the OLE DB Provider. This is the default value. /// <code>System.Data.OleDb.OleDbConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</code> /// </example> /// <example>Use the MS SQL Server Provider. /// <code>System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</code> /// </example> /// <example>Use the ODBC Provider. /// <code>Microsoft.Data.Odbc.OdbcConnection,Microsoft.Data.Odbc,version=1.0.3300.0,publicKeyToken=b77a5c561934e089,culture=neutral</code> /// This is an optional package that you can download from /// <a href="http://msdn.microsoft.com/downloads">http://msdn.microsoft.com/downloads</a> /// search for <b>ODBC .NET Data Provider</b>. /// </example> /// <example>Use the Oracle Provider. /// <code>System.Data.OracleClient.OracleConnection, System.Data.OracleClient, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</code> /// This is an optional package that you can download from /// <a href="http://msdn.microsoft.com/downloads">http://msdn.microsoft.com/downloads</a> /// search for <b>.NET Managed Provider for Oracle</b>. /// </example> public string ConnectionType { get { return m_connectionType; } set { m_connectionType = value; } } /// <summary> /// Gets or sets the command text that is used to insert logging events /// into the database. /// </summary> /// <value> /// The command text used to insert logging events into the database. /// </value> /// <remarks> /// <para> /// Either the text of the prepared statement or the /// name of the stored procedure to execute to write into /// the database. /// </para> /// <para> /// The <see cref="CommandType"/> property determines if /// this text is a prepared statement or a stored procedure. /// </para> /// <para> /// If this property is not set, the command text is retrieved by invoking /// <see cref="GetLogStatement(LoggingEvent)"/>. /// </para> /// </remarks> public string CommandText { get { return m_commandText; } set { m_commandText = value; } } /// <summary> /// Gets or sets the command type to execute. /// </summary> /// <value> /// The command type to execute. /// </value> /// <remarks> /// <para> /// This value may be either <see cref="System.Data.CommandType.Text"/> (<c>System.Data.CommandType.Text</c>) to specify /// that the <see cref="CommandText"/> is a prepared statement to execute, /// or <see cref="System.Data.CommandType.StoredProcedure"/> (<c>System.Data.CommandType.StoredProcedure</c>) to specify that the /// <see cref="CommandText"/> property is the name of a stored procedure /// to execute. /// </para> /// <para> /// The default value is <see cref="System.Data.CommandType.Text"/> (<c>System.Data.CommandType.Text</c>). /// </para> /// </remarks> public CommandType CommandType { get { return m_commandType; } set { m_commandType = value; } } /// <summary> /// Should transactions be used to insert logging events in the database. /// </summary> /// <value> /// <c>true</c> if transactions should be used to insert logging events in /// the database, otherwise <c>false</c>. The default value is <c>true</c>. /// </value> /// <remarks> /// <para> /// Gets or sets a value that indicates whether transactions should be used /// to insert logging events in the database. /// </para> /// <para> /// When set a single transaction will be used to insert the buffered events /// into the database. Otherwise each event will be inserted without using /// an explicit transaction. /// </para> /// </remarks> public bool UseTransactions { get { return m_useTransactions; } set { m_useTransactions = value; } } /// <summary> /// Gets or sets the <see cref="SecurityContext"/> used to call the NetSend method. /// </summary> /// <value> /// The <see cref="SecurityContext"/> used to call the NetSend method. /// </value> /// <remarks> /// <para> /// Unless a <see cref="SecurityContext"/> specified here for this appender /// the <see cref="SecurityContextProvider.DefaultProvider"/> is queried for the /// security context to use. The default behavior is to use the security context /// of the current thread. /// </para> /// </remarks> public SecurityContext SecurityContext { get { return m_securityContext; } set { m_securityContext = value; } } /// <summary> /// Should this appender try to reconnect to the database on error. /// </summary> /// <value> /// <c>true</c> if the appender should try to reconnect to the database after an /// error has occurred, otherwise <c>false</c>. The default value is <c>false</c>, /// i.e. not to try to reconnect. /// </value> /// <remarks> /// <para> /// The default behaviour is for the appender not to try to reconnect to the /// database if an error occurs. Subsequent logging events are discarded. /// </para> /// <para> /// To force the appender to attempt to reconnect to the database set this /// property to <c>true</c>. /// </para> /// <note> /// When the appender attempts to connect to the database there may be a /// delay of up to the connection timeout specified in the connection string. /// This delay will block the calling application's thread. /// Until the connection can be reestablished this potential delay may occur multiple times. /// </note> /// </remarks> public bool ReconnectOnError { get { return m_reconnectOnError; } set { m_reconnectOnError = value; } } #endregion // Public Instance Properties #region Protected Instance Properties /// <summary> /// Gets or sets the underlying <see cref="IDbConnection" />. /// </summary> /// <value> /// The underlying <see cref="IDbConnection" />. /// </value> /// <remarks> /// <see cref="AdoNetAppender" /> creates a <see cref="IDbConnection" /> to insert /// logging events into a database. Classes deriving from <see cref="AdoNetAppender" /> /// can use this property to get or set this <see cref="IDbConnection" />. Use the /// underlying <see cref="IDbConnection" /> returned from <see cref="Connection" /> if /// you require access beyond that which <see cref="AdoNetAppender" /> provides. /// </remarks> protected IDbConnection Connection { get { return m_dbConnection; } set { m_dbConnection = value; } } #endregion // Protected Instance Properties #region Implementation of IOptionHandler /// <summary> /// Initialize the appender based on the options set /// </summary> /// <remarks> /// <para> /// This is part of the <see cref="IOptionHandler"/> delayed object /// activation scheme. The <see cref="ActivateOptions"/> method must /// be called on this object after the configuration properties have /// been set. Until <see cref="ActivateOptions"/> is called this /// object is in an undefined state and must not be used. /// </para> /// <para> /// If any of the configuration properties are modified then /// <see cref="ActivateOptions"/> must be called again. /// </para> /// </remarks> override public void ActivateOptions() { base.ActivateOptions(); if (SecurityContext == null) { SecurityContext = SecurityContextProvider.DefaultProvider.CreateSecurityContext(this); } InitializeDatabaseConnection(); } #endregion #region Override implementation of AppenderSkeleton /// <summary> /// Override the parent method to close the database /// </summary> /// <remarks> /// <para> /// Closes the database command and database connection. /// </para> /// </remarks> override protected void OnClose() { base.OnClose(); DiposeConnection(); } #endregion #region Override implementation of BufferingAppenderSkeleton /// <summary> /// Inserts the events into the database. /// </summary> /// <param name="events">The events to insert into the database.</param> /// <remarks> /// <para> /// Insert all the events specified in the <paramref name="events"/> /// array into the database. /// </para> /// </remarks> override protected void SendBuffer(LoggingEvent[] events) { if (ReconnectOnError && (Connection == null || Connection.State != ConnectionState.Open)) { LogLog.Debug(declaringType, "Attempting to reconnect to database. Current Connection State: " + ((Connection == null) ? SystemInfo.NullText : Connection.State.ToString())); InitializeDatabaseConnection(); } // Check that the connection exists and is open if (Connection != null && Connection.State == ConnectionState.Open) { if (UseTransactions) { // Create transaction // NJC - Do this on 2 lines because it can confuse the debugger using (IDbTransaction dbTran = Connection.BeginTransaction()) { try { SendBuffer(dbTran, events); // commit transaction dbTran.Commit(); } catch (Exception ex) { // rollback the transaction try { dbTran.Rollback(); } catch (Exception) { // Ignore exception } // Can't insert into the database. That's a bad thing ErrorHandler.Error("Exception while writing to database", ex); } } } else { // Send without transaction SendBuffer(null, events); } } } #endregion // Override implementation of BufferingAppenderSkeleton #region Public Instance Methods /// <summary> /// Adds a parameter to the command. /// </summary> /// <param name="parameter">The parameter to add to the command.</param> /// <remarks> /// <para> /// Adds a parameter to the ordered list of command parameters. /// </para> /// </remarks> public void AddParameter(AdoNetAppenderParameter parameter) { m_parameters.Add(parameter); } #endregion // Public Instance Methods #region Protected Instance Methods /// <summary> /// Writes the events to the database using the transaction specified. /// </summary> /// <param name="dbTran">The transaction that the events will be executed under.</param> /// <param name="events">The array of events to insert into the database.</param> /// <remarks> /// <para> /// The transaction argument can be <c>null</c> if the appender has been /// configured not to use transactions. See <see cref="UseTransactions"/> /// property for more information. /// </para> /// </remarks> virtual protected void SendBuffer(IDbTransaction dbTran, LoggingEvent[] events) { // string.IsNotNullOrWhiteSpace() does not exist in ancient .NET frameworks if (CommandText != null && CommandText.Trim() != "") { using (IDbCommand dbCmd = Connection.CreateCommand()) { // Set the command string dbCmd.CommandText = CommandText; // Set the command type dbCmd.CommandType = CommandType; // Send buffer using the prepared command object if (dbTran != null) { dbCmd.Transaction = dbTran; } // prepare the command, which is significantly faster dbCmd.Prepare(); // run for all events foreach (LoggingEvent e in events) { // Set the parameter values foreach (AdoNetAppenderParameter param in m_parameters) { param.Prepare(dbCmd); param.FormatValue(dbCmd, e); } // Execute the query dbCmd.ExecuteNonQuery(); } } } else { // create a new command using (IDbCommand dbCmd = Connection.CreateCommand()) { if (dbTran != null) { dbCmd.Transaction = dbTran; } // run for all events foreach (LoggingEvent e in events) { // Get the command text from the Layout string logStatement = GetLogStatement(e); LogLog.Debug(declaringType, "LogStatement [" + logStatement + "]"); dbCmd.CommandText = logStatement; dbCmd.ExecuteNonQuery(); } } } } /// <summary> /// Formats the log message into database statement text. /// </summary> /// <param name="logEvent">The event being logged.</param> /// <remarks> /// This method can be overridden by subclasses to provide /// more control over the format of the database statement. /// </remarks> /// <returns> /// Text that can be passed to a <see cref="System.Data.IDbCommand"/>. /// </returns> virtual protected string GetLogStatement(LoggingEvent logEvent) { if (Layout == null) { ErrorHandler.Error("AdoNetAppender: No Layout specified."); return ""; } else { StringWriter writer = new StringWriter(System.Globalization.CultureInfo.InvariantCulture); Layout.Format(writer, logEvent); return writer.ToString(); } } /// <summary> /// Creates an <see cref="IDbConnection"/> instance used to connect to the database. /// </summary> /// <remarks> /// This method is called whenever a new IDbConnection is needed (i.e. when a reconnect is necessary). /// </remarks> /// <param name="connectionType">The <see cref="Type"/> of the <see cref="IDbConnection"/> object.</param> /// <param name="connectionString">The connectionString output from the ResolveConnectionString method.</param> /// <returns>An <see cref="IDbConnection"/> instance with a valid connection string.</returns> virtual protected IDbConnection CreateConnection(Type connectionType, string connectionString) { IDbConnection connection = (IDbConnection)Activator.CreateInstance(connectionType); connection.ConnectionString = connectionString; return connection; } /// <summary> /// Resolves the connection string from the ConnectionString, ConnectionStringName, or AppSettingsKey /// property. /// </summary> /// <remarks> /// ConnectiongStringName is only supported on .NET 2.0 and higher. /// </remarks> /// <param name="connectionStringContext">Additional information describing the connection string.</param> /// <returns>A connection string used to connect to the database.</returns> virtual protected string ResolveConnectionString(out string connectionStringContext) { if (ConnectionString != null && ConnectionString.Length > 0) { connectionStringContext = "ConnectionString"; return ConnectionString; } #if NET_2_0 if (!String.IsNullOrEmpty(ConnectionStringName)) { ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[ConnectionStringName]; if (settings != null) { connectionStringContext = "ConnectionStringName"; return settings.ConnectionString; } else { throw new LogException("Unable to find [" + ConnectionStringName + "] ConfigurationManager.ConnectionStrings item"); } } #endif if (AppSettingsKey != null && AppSettingsKey.Length > 0) { connectionStringContext = "AppSettingsKey"; string appSettingsConnectionString = SystemInfo.GetAppSetting(AppSettingsKey); if (appSettingsConnectionString == null || appSettingsConnectionString.Length == 0) { throw new LogException("Unable to find [" + AppSettingsKey + "] AppSettings key."); } return appSettingsConnectionString; } connectionStringContext = "Unable to resolve connection string from ConnectionString, ConnectionStrings, or AppSettings."; return string.Empty; } /// <summary> /// Retrieves the class type of the ADO.NET provider. /// </summary> /// <remarks> /// <para> /// Gets the Type of the ADO.NET provider to use to connect to the /// database. This method resolves the type specified in the /// <see cref="ConnectionType"/> property. /// </para> /// <para> /// Subclasses can override this method to return a different type /// if necessary. /// </para> /// </remarks> /// <returns>The <see cref="Type"/> of the ADO.NET provider</returns> virtual protected Type ResolveConnectionType() { try { return SystemInfo.GetTypeFromString(ConnectionType, true, false); } catch (Exception ex) { ErrorHandler.Error("Failed to load connection type [" + ConnectionType + "]", ex); throw; } } #endregion // Protected Instance Methods #region Private Instance Methods /// <summary> /// Connects to the database. /// </summary> private void InitializeDatabaseConnection() { string connectionStringContext = "Unable to determine connection string context."; string resolvedConnectionString = string.Empty; try { DiposeConnection(); // Set the connection string resolvedConnectionString = ResolveConnectionString(out connectionStringContext); Connection = CreateConnection(ResolveConnectionType(), resolvedConnectionString); using (SecurityContext.Impersonate(this)) { // Open the database connection Connection.Open(); } } catch (Exception e) { // Sadly, your connection string is bad. ErrorHandler.Error("Could not open database connection [" + resolvedConnectionString + "]. Connection string context [" + connectionStringContext + "].", e); Connection = null; } } /// <summary> /// Cleanup the existing connection. /// </summary> /// <remarks> /// Calls the IDbConnection's <see cref="IDbConnection.Close"/> method. /// </remarks> private void DiposeConnection() { if (Connection != null) { try { Connection.Close(); } catch (Exception ex) { LogLog.Warn(declaringType, "Exception while disposing cached connection object", ex); } Connection = null; } } #endregion // Private Instance Methods #region Protected Instance Fields /// <summary> /// The list of <see cref="AdoNetAppenderParameter"/> objects. /// </summary> /// <remarks> /// <para> /// The list of <see cref="AdoNetAppenderParameter"/> objects. /// </para> /// </remarks> protected ArrayList m_parameters; #endregion // Protected Instance Fields #region Private Instance Fields /// <summary> /// The security context to use for privileged calls /// </summary> private SecurityContext m_securityContext; /// <summary> /// The <see cref="IDbConnection" /> that will be used /// to insert logging events into a database. /// </summary> private IDbConnection m_dbConnection; /// <summary> /// Database connection string. /// </summary> private string m_connectionString; /// <summary> /// The appSettings key from App.Config that contains the connection string. /// </summary> private string m_appSettingsKey; #if NET_2_0 /// <summary> /// The connectionStrings key from App.Config that contains the connection string. /// </summary> private string m_connectionStringName; #endif /// <summary> /// String type name of the <see cref="IDbConnection"/> type name. /// </summary> private string m_connectionType; /// <summary> /// The text of the command. /// </summary> private string m_commandText; /// <summary> /// The command type. /// </summary> private CommandType m_commandType; /// <summary> /// Indicates whether to use transactions when writing to the database. /// </summary> private bool m_useTransactions; /// <summary> /// Indicates whether to reconnect when a connection is lost. /// </summary> private bool m_reconnectOnError; #endregion // Private Instance Fields #region Private Static Fields /// <summary> /// The fully qualified type of the AdoNetAppender class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(AdoNetAppender); #endregion Private Static Fields } /// <summary> /// Parameter type used by the <see cref="AdoNetAppender"/>. /// </summary> /// <remarks> /// <para> /// This class provides the basic database parameter properties /// as defined by the <see cref="System.Data.IDbDataParameter"/> interface. /// </para> /// <para>This type can be subclassed to provide database specific /// functionality. The two methods that are called externally are /// <see cref="Prepare"/> and <see cref="FormatValue"/>. /// </para> /// </remarks> public class AdoNetAppenderParameter { #region Public Instance Constructors /// <summary> /// Initializes a new instance of the <see cref="AdoNetAppenderParameter" /> class. /// </summary> /// <remarks> /// Default constructor for the AdoNetAppenderParameter class. /// </remarks> public AdoNetAppenderParameter() { Precision = 0; Scale = 0; Size = 0; } #endregion // Public Instance Constructors #region Public Instance Properties /// <summary> /// Gets or sets the name of this parameter. /// </summary> /// <value> /// The name of this parameter. /// </value> /// <remarks> /// <para> /// The name of this parameter. The parameter name /// must match up to a named parameter to the SQL stored procedure /// or prepared statement. /// </para> /// </remarks> public string ParameterName { get { return m_parameterName; } set { m_parameterName = value; } } /// <summary> /// Gets or sets the database type for this parameter. /// </summary> /// <value> /// The database type for this parameter. /// </value> /// <remarks> /// <para> /// The database type for this parameter. This property should /// be set to the database type from the <see cref="DbType"/> /// enumeration. See <see cref="IDataParameter.DbType"/>. /// </para> /// <para> /// This property is optional. If not specified the ADO.NET provider /// will attempt to infer the type from the value. /// </para> /// </remarks> /// <seealso cref="IDataParameter.DbType" /> public DbType DbType { get { return m_dbType; } set { m_dbType = value; m_inferType = false; } } /// <summary> /// Gets or sets the precision for this parameter. /// </summary> /// <value> /// The precision for this parameter. /// </value> /// <remarks> /// <para> /// The maximum number of digits used to represent the Value. /// </para> /// <para> /// This property is optional. If not specified the ADO.NET provider /// will attempt to infer the precision from the value. /// </para> /// </remarks> /// <seealso cref="IDbDataParameter.Precision" /> public byte Precision { get { return m_precision; } set { m_precision = value; } } /// <summary> /// Gets or sets the scale for this parameter. /// </summary> /// <value> /// The scale for this parameter. /// </value> /// <remarks> /// <para> /// The number of decimal places to which Value is resolved. /// </para> /// <para> /// This property is optional. If not specified the ADO.NET provider /// will attempt to infer the scale from the value. /// </para> /// </remarks> /// <seealso cref="IDbDataParameter.Scale" /> public byte Scale { get { return m_scale; } set { m_scale = value; } } /// <summary> /// Gets or sets the size for this parameter. /// </summary> /// <value> /// The size for this parameter. /// </value> /// <remarks> /// <para> /// The maximum size, in bytes, of the data within the column. /// </para> /// <para> /// This property is optional. If not specified the ADO.NET provider /// will attempt to infer the size from the value. /// </para> /// <para> /// For BLOB data types like VARCHAR(max) it may be impossible to infer the value automatically, use -1 as the size in this case. /// </para> /// </remarks> /// <seealso cref="IDbDataParameter.Size" /> public int Size { get { return m_size; } set { m_size = value; } } /// <summary> /// Gets or sets the <see cref="IRawLayout"/> to use to /// render the logging event into an object for this /// parameter. /// </summary> /// <value> /// The <see cref="IRawLayout"/> used to render the /// logging event into an object for this parameter. /// </value> /// <remarks> /// <para> /// The <see cref="IRawLayout"/> that renders the value for this /// parameter. /// </para> /// <para> /// The <see cref="RawLayoutConverter"/> can be used to adapt /// any <see cref="ILayout"/> into a <see cref="IRawLayout"/> /// for use in the property. /// </para> /// </remarks> public IRawLayout Layout { get { return m_layout; } set { m_layout = value; } } #endregion // Public Instance Properties #region Public Instance Methods /// <summary> /// Prepare the specified database command object. /// </summary> /// <param name="command">The command to prepare.</param> /// <remarks> /// <para> /// Prepares the database command object by adding /// this parameter to its collection of parameters. /// </para> /// </remarks> virtual public void Prepare(IDbCommand command) { // Create a new parameter IDbDataParameter param = command.CreateParameter(); // Set the parameter properties param.ParameterName = ParameterName; if (!m_inferType) { param.DbType = DbType; } if (Precision != 0) { param.Precision = Precision; } if (Scale != 0) { param.Scale = Scale; } if (Size != 0) { param.Size = Size; } // Add the parameter to the collection of params command.Parameters.Add(param); } /// <summary> /// Renders the logging event and set the parameter value in the command. /// </summary> /// <param name="command">The command containing the parameter.</param> /// <param name="loggingEvent">The event to be rendered.</param> /// <remarks> /// <para> /// Renders the logging event using this parameters layout /// object. Sets the value of the parameter on the command object. /// </para> /// </remarks> virtual public void FormatValue(IDbCommand command, LoggingEvent loggingEvent) { // Lookup the parameter IDbDataParameter param = (IDbDataParameter)command.Parameters[ParameterName]; // Format the value object formattedValue = Layout.Format(loggingEvent); // If the value is null then convert to a DBNull if (formattedValue == null) { formattedValue = DBNull.Value; } param.Value = formattedValue; } #endregion // Public Instance Methods #region Private Instance Fields /// <summary> /// The name of this parameter. /// </summary> private string m_parameterName; /// <summary> /// The database type for this parameter. /// </summary> private DbType m_dbType; /// <summary> /// Flag to infer type rather than use the DbType /// </summary> private bool m_inferType = true; /// <summary> /// The precision for this parameter. /// </summary> private byte m_precision; /// <summary> /// The scale for this parameter. /// </summary> private byte m_scale; /// <summary> /// The size for this parameter. /// </summary> private int m_size; /// <summary> /// The <see cref="IRawLayout"/> to use to render the /// logging event into an object for this parameter. /// </summary> private IRawLayout m_layout; #endregion // Private Instance Fields } } #endif // !SSCLI
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsUrl { using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for PathItems. /// </summary> public static partial class PathItemsExtensions { /// <summary> /// send globalStringPath='globalStringPath', /// pathItemStringPath='pathItemStringPath', localStringPath='localStringPath', /// globalStringQuery='globalStringQuery', /// pathItemStringQuery='pathItemStringQuery', /// localStringQuery='localStringQuery' /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='localStringPath'> /// should contain value 'localStringPath' /// </param> /// <param name='pathItemStringPath'> /// A string value 'pathItemStringPath' that appears in the path /// </param> /// <param name='localStringQuery'> /// should contain value 'localStringQuery' /// </param> /// <param name='pathItemStringQuery'> /// A string value 'pathItemStringQuery' that appears as a query parameter /// </param> public static void GetAllWithValues(this IPathItems operations, string localStringPath, string pathItemStringPath, string localStringQuery = default(string), string pathItemStringQuery = default(string)) { Task.Factory.StartNew(s => ((IPathItems)s).GetAllWithValuesAsync(localStringPath, pathItemStringPath, localStringQuery, pathItemStringQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// send globalStringPath='globalStringPath', /// pathItemStringPath='pathItemStringPath', localStringPath='localStringPath', /// globalStringQuery='globalStringQuery', /// pathItemStringQuery='pathItemStringQuery', /// localStringQuery='localStringQuery' /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='localStringPath'> /// should contain value 'localStringPath' /// </param> /// <param name='pathItemStringPath'> /// A string value 'pathItemStringPath' that appears in the path /// </param> /// <param name='localStringQuery'> /// should contain value 'localStringQuery' /// </param> /// <param name='pathItemStringQuery'> /// A string value 'pathItemStringQuery' that appears as a query parameter /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task GetAllWithValuesAsync(this IPathItems operations, string localStringPath, string pathItemStringPath, string localStringQuery = default(string), string pathItemStringQuery = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.GetAllWithValuesWithHttpMessagesAsync(localStringPath, pathItemStringPath, localStringQuery, pathItemStringQuery, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// send globalStringPath='globalStringPath', /// pathItemStringPath='pathItemStringPath', localStringPath='localStringPath', /// globalStringQuery=null, pathItemStringQuery='pathItemStringQuery', /// localStringQuery='localStringQuery' /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='localStringPath'> /// should contain value 'localStringPath' /// </param> /// <param name='pathItemStringPath'> /// A string value 'pathItemStringPath' that appears in the path /// </param> /// <param name='localStringQuery'> /// should contain value 'localStringQuery' /// </param> /// <param name='pathItemStringQuery'> /// A string value 'pathItemStringQuery' that appears as a query parameter /// </param> public static void GetGlobalQueryNull(this IPathItems operations, string localStringPath, string pathItemStringPath, string localStringQuery = default(string), string pathItemStringQuery = default(string)) { Task.Factory.StartNew(s => ((IPathItems)s).GetGlobalQueryNullAsync(localStringPath, pathItemStringPath, localStringQuery, pathItemStringQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// send globalStringPath='globalStringPath', /// pathItemStringPath='pathItemStringPath', localStringPath='localStringPath', /// globalStringQuery=null, pathItemStringQuery='pathItemStringQuery', /// localStringQuery='localStringQuery' /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='localStringPath'> /// should contain value 'localStringPath' /// </param> /// <param name='pathItemStringPath'> /// A string value 'pathItemStringPath' that appears in the path /// </param> /// <param name='localStringQuery'> /// should contain value 'localStringQuery' /// </param> /// <param name='pathItemStringQuery'> /// A string value 'pathItemStringQuery' that appears as a query parameter /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task GetGlobalQueryNullAsync(this IPathItems operations, string localStringPath, string pathItemStringPath, string localStringQuery = default(string), string pathItemStringQuery = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.GetGlobalQueryNullWithHttpMessagesAsync(localStringPath, pathItemStringPath, localStringQuery, pathItemStringQuery, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// send globalStringPath=globalStringPath, /// pathItemStringPath='pathItemStringPath', localStringPath='localStringPath', /// globalStringQuery=null, pathItemStringQuery='pathItemStringQuery', /// localStringQuery=null /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='localStringPath'> /// should contain value 'localStringPath' /// </param> /// <param name='pathItemStringPath'> /// A string value 'pathItemStringPath' that appears in the path /// </param> /// <param name='localStringQuery'> /// should contain null value /// </param> /// <param name='pathItemStringQuery'> /// A string value 'pathItemStringQuery' that appears as a query parameter /// </param> public static void GetGlobalAndLocalQueryNull(this IPathItems operations, string localStringPath, string pathItemStringPath, string localStringQuery = default(string), string pathItemStringQuery = default(string)) { Task.Factory.StartNew(s => ((IPathItems)s).GetGlobalAndLocalQueryNullAsync(localStringPath, pathItemStringPath, localStringQuery, pathItemStringQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// send globalStringPath=globalStringPath, /// pathItemStringPath='pathItemStringPath', localStringPath='localStringPath', /// globalStringQuery=null, pathItemStringQuery='pathItemStringQuery', /// localStringQuery=null /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='localStringPath'> /// should contain value 'localStringPath' /// </param> /// <param name='pathItemStringPath'> /// A string value 'pathItemStringPath' that appears in the path /// </param> /// <param name='localStringQuery'> /// should contain null value /// </param> /// <param name='pathItemStringQuery'> /// A string value 'pathItemStringQuery' that appears as a query parameter /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task GetGlobalAndLocalQueryNullAsync(this IPathItems operations, string localStringPath, string pathItemStringPath, string localStringQuery = default(string), string pathItemStringQuery = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.GetGlobalAndLocalQueryNullWithHttpMessagesAsync(localStringPath, pathItemStringPath, localStringQuery, pathItemStringQuery, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// send globalStringPath='globalStringPath', /// pathItemStringPath='pathItemStringPath', localStringPath='localStringPath', /// globalStringQuery='globalStringQuery', pathItemStringQuery=null, /// localStringQuery=null /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='localStringPath'> /// should contain value 'localStringPath' /// </param> /// <param name='pathItemStringPath'> /// A string value 'pathItemStringPath' that appears in the path /// </param> /// <param name='localStringQuery'> /// should contain value null /// </param> /// <param name='pathItemStringQuery'> /// should contain value null /// </param> public static void GetLocalPathItemQueryNull(this IPathItems operations, string localStringPath, string pathItemStringPath, string localStringQuery = default(string), string pathItemStringQuery = default(string)) { Task.Factory.StartNew(s => ((IPathItems)s).GetLocalPathItemQueryNullAsync(localStringPath, pathItemStringPath, localStringQuery, pathItemStringQuery), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// send globalStringPath='globalStringPath', /// pathItemStringPath='pathItemStringPath', localStringPath='localStringPath', /// globalStringQuery='globalStringQuery', pathItemStringQuery=null, /// localStringQuery=null /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='localStringPath'> /// should contain value 'localStringPath' /// </param> /// <param name='pathItemStringPath'> /// A string value 'pathItemStringPath' that appears in the path /// </param> /// <param name='localStringQuery'> /// should contain value null /// </param> /// <param name='pathItemStringQuery'> /// should contain value null /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task GetLocalPathItemQueryNullAsync(this IPathItems operations, string localStringPath, string pathItemStringPath, string localStringQuery = default(string), string pathItemStringQuery = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.GetLocalPathItemQueryNullWithHttpMessagesAsync(localStringPath, pathItemStringPath, localStringQuery, pathItemStringQuery, null, cancellationToken).ConfigureAwait(false); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; namespace Microsoft.CodeAnalysis.Editing { /// <summary> /// An editor for making changes to a syntax tree. /// </summary> public class SyntaxEditor { private readonly SyntaxGenerator _generator; private readonly SyntaxNode _root; private readonly List<Change> _changes; /// <summary> /// Creates a new <see cref="SyntaxEditor"/> instance. /// </summary> public SyntaxEditor(SyntaxNode root, Workspace workspace) { if (workspace == null) { throw new ArgumentNullException(nameof(workspace)); } _root = root ?? throw new ArgumentNullException(nameof(root)); _generator = SyntaxGenerator.GetGenerator(workspace, root.Language); _changes = new List<Change>(); } /// <summary> /// The <see cref="SyntaxNode"/> that was specified when the <see cref="SyntaxEditor"/> was constructed. /// </summary> public SyntaxNode OriginalRoot { get { return _root; } } /// <summary> /// A <see cref="SyntaxGenerator"/> to use to create and change <see cref="SyntaxNode"/>'s. /// </summary> public SyntaxGenerator Generator { get { return _generator; } } /// <summary> /// Returns the changed root node. /// </summary> public SyntaxNode GetChangedRoot() { var nodes = Enumerable.Distinct(_changes.Select(c => c.Node)); var newRoot = _root.TrackNodes(nodes); foreach (var change in _changes) { newRoot = change.Apply(newRoot, _generator); } return newRoot; } /// <summary> /// Makes sure the node is tracked, even if it is not changed. /// </summary> public void TrackNode(SyntaxNode node) { CheckNodeInTree(node); _changes.Add(new NoChange(node)); } /// <summary> /// Remove the node from the tree. /// </summary> /// <param name="node">The node to remove that currently exists as part of the tree.</param> public void RemoveNode(SyntaxNode node) { RemoveNode(node, SyntaxGenerator.DefaultRemoveOptions); } /// <summary> /// Remove the node from the tree. /// </summary> /// <param name="node">The node to remove that currently exists as part of the tree.</param> /// <param name="options">Options that affect how node removal works.</param> public void RemoveNode(SyntaxNode node, SyntaxRemoveOptions options) { CheckNodeInTree(node); _changes.Add(new RemoveChange(node, options)); } /// <summary> /// Replace the specified node with a node produced by the function. /// </summary> /// <param name="node">The node to replace that already exists in the tree.</param> /// <param name="computeReplacement">A function that computes a replacement node. /// The node passed into the compute function includes changes from prior edits. It will not appear as a descendant of the original root.</param> public void ReplaceNode(SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, SyntaxNode> computeReplacement) { CheckNodeInTree(node); _changes.Add(new ReplaceChange(node, computeReplacement)); } internal void ReplaceNode<TArgument>(SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, TArgument, SyntaxNode> computeReplacement, TArgument argument) { CheckNodeInTree(node); _changes.Add(new ReplaceChange<TArgument>(node, computeReplacement, argument)); } /// <summary> /// Replace the specified node with a different node. /// </summary> /// <param name="node">The node to replace that already exists in the tree.</param> /// <param name="newNode">The new node that will be placed into the tree in the existing node's location.</param> public void ReplaceNode(SyntaxNode node, SyntaxNode newNode) { CheckNodeInTree(node); if (node == newNode) { return; } this.ReplaceNode(node, (n, g) => newNode); } /// <summary> /// Insert the new nodes before the specified node already existing in the tree. /// </summary> /// <param name="node">The node already existing in the tree that the new nodes will be placed before. This must be a node this is contained within a syntax list.</param> /// <param name="newNodes">The nodes to place before the existing node. These nodes must be of a compatible type to be placed in the same list containing the existing node.</param> public void InsertBefore(SyntaxNode node, IEnumerable<SyntaxNode> newNodes) { CheckNodeInTree(node); _changes.Add(new InsertChange(node, newNodes, isBefore: true)); } /// <summary> /// Insert the new node before the specified node already existing in the tree. /// </summary> /// <param name="node">The node already existing in the tree that the new nodes will be placed before. This must be a node this is contained within a syntax list.</param> /// <param name="newNode">The node to place before the existing node. This node must be of a compatible type to be placed in the same list containing the existing node.</param> public void InsertBefore(SyntaxNode node, SyntaxNode newNode) { CheckNodeInTree(node); this.InsertBefore(node, new[] { newNode }); } /// <summary> /// Insert the new nodes after the specified node already existing in the tree. /// </summary> /// <param name="node">The node already existing in the tree that the new nodes will be placed after. This must be a node this is contained within a syntax list.</param> /// <param name="newNodes">The nodes to place after the existing node. These nodes must be of a compatible type to be placed in the same list containing the existing node.</param> public void InsertAfter(SyntaxNode node, IEnumerable<SyntaxNode> newNodes) { CheckNodeInTree(node); _changes.Add(new InsertChange(node, newNodes, isBefore: false)); } /// <summary> /// Insert the new node after the specified node already existing in the tree. /// </summary> /// <param name="node">The node already existing in the tree that the new nodes will be placed after. This must be a node this is contained within a syntax list.</param> /// <param name="newNode">The node to place after the existing node. This node must be of a compatible type to be placed in the same list containing the existing node.</param> public void InsertAfter(SyntaxNode node, SyntaxNode newNode) { CheckNodeInTree(node); this.InsertAfter(node, new[] { newNode }); } private void CheckNodeInTree(SyntaxNode node) { if (!_root.Contains(node)) { throw new ArgumentException(Microsoft.CodeAnalysis.WorkspacesResources.The_node_is_not_part_of_the_tree, nameof(node)); } } private abstract class Change { internal readonly SyntaxNode Node; public Change(SyntaxNode node) { this.Node = node; } public abstract SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator); } private class NoChange : Change { public NoChange(SyntaxNode node) : base(node) { } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) { return root; } } private class RemoveChange : Change { private readonly SyntaxRemoveOptions _options; public RemoveChange(SyntaxNode node, SyntaxRemoveOptions options) : base(node) { _options = options; } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) { return generator.RemoveNode(root, root.GetCurrentNode(this.Node), _options); } } private class ReplaceChange : Change { private readonly Func<SyntaxNode, SyntaxGenerator, SyntaxNode> _modifier; public ReplaceChange(SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, SyntaxNode> modifier) : base(node) { _modifier = modifier; } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) { var current = root.GetCurrentNode(this.Node); var newNode = _modifier(current, generator); return generator.ReplaceNode(root, current, newNode); } } private class ReplaceChange<TArgument> : Change { private readonly Func<SyntaxNode, SyntaxGenerator, TArgument, SyntaxNode> _modifier; private readonly TArgument _argument; public ReplaceChange( SyntaxNode node, Func<SyntaxNode, SyntaxGenerator, TArgument, SyntaxNode> modifier, TArgument argument) : base(node) { _modifier = modifier; _argument = argument; } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) { var current = root.GetCurrentNode(this.Node); var newNode = _modifier(current, generator, _argument); return generator.ReplaceNode(root, current, newNode); } } private class InsertChange : Change { private readonly List<SyntaxNode> _newNodes; private readonly bool _isBefore; public InsertChange(SyntaxNode node, IEnumerable<SyntaxNode> newNodes, bool isBefore) : base(node) { _newNodes = newNodes.ToList(); _isBefore = isBefore; } public override SyntaxNode Apply(SyntaxNode root, SyntaxGenerator generator) { if (_isBefore) { return generator.InsertNodesBefore(root, root.GetCurrentNode(this.Node), _newNodes); } else { return generator.InsertNodesAfter(root, root.GetCurrentNode(this.Node), _newNodes); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using KSP.Localization; namespace KERBALISM { public enum ScienceSituation : byte { None = byte.MaxValue, // stock situations SrfLanded = 0, SrfSplashed = 1, FlyingLow = 2, FlyingHigh = 3, InSpaceLow = 4, InSpaceHigh = 5, // Kerbalism extensions Surface = 11, Flying = 12, Space = 13, BodyGlobal = 14 } /// <summary> /// virtual biomes are fake biomes that can be used to generate subjects for specific situations. /// We use the "biome" part of the stock subjectid system because that /// doesn't currently cause any issue (as opposed to using a custom situation). /// The enum value must be less than byte.Maxvalue (255), used for "no biome" in Situation, /// but musn't collide with real CB biomes indexes that start at 0 /// </summary> // Note : if you add some virtual biomes, remember to update the related methods in ScienceSituationUtils public enum VirtualBiome : byte { None = 0, NoBiome = byte.MaxValue, // if used, will be registered as the global, biome-agnostic situation NorthernHemisphere = 254, SouthernHemisphere = 253, InnerBelt = 252, OuterBelt = 251, Magnetosphere = 250, Interstellar = 249, Reentry = 248, Storm = 247 } public static class ScienceSituationUtils { public static bool IsAvailableForExperiment(this ScienceSituation situation, ExperimentInfo experiment) { return (experiment.SituationMask & situation.BitValue()) != 0; } public static bool IsBiomesRelevantForExperiment(this ScienceSituation situation, ExperimentInfo experiment) { return (experiment.BiomeMask & situation.BitValue()) != 0 || (experiment.VirtualBiomeMask & situation.BitValue()) != 0; } public static bool IsBodyBiomesRelevantForExperiment(this ScienceSituation situation, ExperimentInfo experiment) { return (experiment.BiomeMask & situation.BitValue()) != 0; } public static bool IsVirtualBiomesRelevantForExperiment(this ScienceSituation situation, ExperimentInfo experiment) { return (experiment.VirtualBiomeMask & situation.BitValue()) != 0; } public static bool IsAvailableOnBody(this ScienceSituation situation, CelestialBody body) { switch (situation) { case ScienceSituation.SrfLanded: case ScienceSituation.Surface: if (!body.hasSolidSurface) return false; break; case ScienceSituation.SrfSplashed: if (!body.ocean || !body.hasSolidSurface) return false; break; case ScienceSituation.FlyingLow: case ScienceSituation.FlyingHigh: case ScienceSituation.Flying: if (!body.atmosphere) return false; break; case ScienceSituation.None: return false; } return true; } public static bool IsAvailableOnBody(this VirtualBiome virtualBiome, CelestialBody body) { switch (virtualBiome) { case VirtualBiome.InnerBelt: if (!Radiation.Info(body).model.has_inner) return false; break; case VirtualBiome.OuterBelt: if (!Radiation.Info(body).model.has_outer) return false; break; case VirtualBiome.Magnetosphere: if (!Radiation.Info(body).model.has_pause) return false; break; case VirtualBiome.Interstellar: if (!Lib.IsSun(body)) return false; break; case VirtualBiome.Reentry: if (!body.atmosphere) return false; break; } return true; } public static float BodyMultiplier(this ScienceSituation situation, CelestialBody body) { float result = 0f; switch (situation) { case ScienceSituation.Surface: case ScienceSituation.SrfLanded: result = body.scienceValues.LandedDataValue; break; case ScienceSituation.SrfSplashed: result = body.scienceValues.SplashedDataValue; break; case ScienceSituation.FlyingLow: result = body.scienceValues.FlyingLowDataValue; break; case ScienceSituation.Flying: case ScienceSituation.FlyingHigh: result = body.scienceValues.FlyingHighDataValue; break; case ScienceSituation.BodyGlobal: case ScienceSituation.Space: case ScienceSituation.InSpaceLow: result = body.scienceValues.InSpaceLowDataValue; break; case ScienceSituation.InSpaceHigh: result = body.scienceValues.InSpaceHighDataValue; break; } if (result == 0f) { Lib.Log("Science: invalid/unknown situation " + situation.ToString(), Lib.LogLevel.Error); return 1f; // returning 0 will result in NaN values } return result; } public static uint BitValue(this ScienceSituation situation) { switch (situation) { case ScienceSituation.None: return 0; case ScienceSituation.SrfLanded: return 1; // 1 << 0 case ScienceSituation.SrfSplashed: return 2; // 1 << 1 case ScienceSituation.FlyingLow: return 4; // 1 << 2 case ScienceSituation.FlyingHigh: return 8; // 1 << 3 case ScienceSituation.InSpaceLow: return 16; // 1 << 4 case ScienceSituation.InSpaceHigh: return 32; // 1 << 5 case ScienceSituation.Surface: return 2048; // 1 << 11 case ScienceSituation.Flying: return 4096; // 1 << 12 case ScienceSituation.Space: return 8192; // 1 << 13 case ScienceSituation.BodyGlobal: return 16384; // 1 << 14 default: return 0; } } public static uint SituationsToBitMask(List<ScienceSituation> scienceSituations) { uint bitMask = 0; foreach (ScienceSituation situation in scienceSituations) bitMask += situation.BitValue(); return bitMask; } public static List<ScienceSituation> BitMaskToSituations(uint bitMask) { List<ScienceSituation> situations = new List<ScienceSituation>(); foreach (ScienceSituation situation in validSituations) if ((bitMask & BitValue(situation)) != 0) situations.Add(situation); return situations; } public static string Title(this ScienceSituation situation) { switch (situation) { case ScienceSituation.None: return Local.Situation_None;//"none" case ScienceSituation.SrfLanded: return Local.Situation_Landed;//"landed" case ScienceSituation.SrfSplashed: return Local.Situation_Splashed;//"splashed" case ScienceSituation.FlyingLow: return Local.Situation_Flyinglow;//"flying low" case ScienceSituation.FlyingHigh: return Local.Situation_Flyinghigh;//"flying high" case ScienceSituation.InSpaceLow: return Local.Situation_Spacelow;//"space low" case ScienceSituation.InSpaceHigh: return Local.Situation_SpaceHigh;//"space high" case ScienceSituation.Surface: return Local.Situation_Surface;//"surface" case ScienceSituation.Flying: return Local.Situation_Flying;//"flying" case ScienceSituation.Space: return Local.Situation_Space;//"space" case ScienceSituation.BodyGlobal: return Local.Situation_BodyGlobal;//"global" default: return Local.Situation_None;//"none" } } public static string Title(this VirtualBiome virtualBiome) { switch (virtualBiome) { case VirtualBiome.NoBiome: return Local.Situation_NoBiome;//"global" case VirtualBiome.NorthernHemisphere: return Local.Situation_NorthernHemisphere;//"north hemisphere" case VirtualBiome.SouthernHemisphere: return Local.Situation_SouthernHemisphere;//"south hemisphere" case VirtualBiome.InnerBelt: return Local.Situation_InnerBelt;//"inner belt" case VirtualBiome.OuterBelt: return Local.Situation_OuterBelt;//"outer belt" case VirtualBiome.Magnetosphere: return Local.Situation_Magnetosphere;//"magnetosphere" case VirtualBiome.Interstellar: return Local.Situation_Interstellar;//"interstellar" case VirtualBiome.Reentry: return Local.Situation_Reentry;//"reentry" case VirtualBiome.Storm: return Local.Situation_Storm;//"solar storm" default: return Local.Situation_None;//"none" } } public static string Serialize(this ScienceSituation situation) { switch (situation) { case ScienceSituation.SrfLanded: return "SrfLanded"; case ScienceSituation.SrfSplashed: return "SrfSplashed"; case ScienceSituation.FlyingLow: return "FlyingLow"; case ScienceSituation.FlyingHigh: return "FlyingHigh"; case ScienceSituation.InSpaceLow: return "InSpaceLow"; case ScienceSituation.InSpaceHigh: return "InSpaceHigh"; case ScienceSituation.Surface: return "Surface" ; case ScienceSituation.Flying: return "Flying"; case ScienceSituation.Space: return "Space"; case ScienceSituation.BodyGlobal: return "BodyGlobal"; default: return "None"; } } public static string Serialize(this VirtualBiome virtualBiome) { switch (virtualBiome) { case VirtualBiome.NoBiome: return "NoBiome"; case VirtualBiome.NorthernHemisphere: return "NorthernHemisphere"; case VirtualBiome.SouthernHemisphere: return "SouthernHemisphere"; case VirtualBiome.InnerBelt: return "InnerBelt"; case VirtualBiome.OuterBelt: return "OuterBelt"; case VirtualBiome.Magnetosphere: return "Magnetosphere"; case VirtualBiome.Interstellar: return "Interstellar"; case VirtualBiome.Reentry: return "Reentry"; case VirtualBiome.Storm: return "Storm"; default: return "None"; } } public static ScienceSituation ScienceSituationDeserialize(string situation) { switch (situation) { case "SrfLanded": return ScienceSituation.SrfLanded; case "SrfSplashed": return ScienceSituation.SrfSplashed; case "FlyingLow": return ScienceSituation.FlyingLow; case "FlyingHigh": return ScienceSituation.FlyingHigh; case "InSpaceLow": return ScienceSituation.InSpaceLow; case "InSpaceHigh": return ScienceSituation.InSpaceHigh; case "Surface": return ScienceSituation.Surface; case "Flying": return ScienceSituation.Flying; case "Space": return ScienceSituation.Space; case "BodyGlobal": return ScienceSituation.BodyGlobal; default: return ScienceSituation.None; } } public static VirtualBiome VirtualBiomeDeserialize(string virtualBiome) { switch (virtualBiome) { case "NoBiome": return VirtualBiome.NoBiome; case "NorthernHemisphere": return VirtualBiome.NorthernHemisphere; case "SouthernHemisphere": return VirtualBiome.SouthernHemisphere; case "InnerBelt": return VirtualBiome.InnerBelt; case "OuterBelt": return VirtualBiome.OuterBelt; case "Magnetosphere": return VirtualBiome.Magnetosphere; case "Interstellar": return VirtualBiome.Interstellar; case "Reentry": return VirtualBiome.Reentry; case "Storm": return VirtualBiome.Storm; default: return VirtualBiome.None; } } /// <summary> get the stock ExperimentSituation for our ScienceSituation value </summary> // Note: any modification in this should be reflected in ValidateSituationBitMask() public static ScienceSituation ToValidStockSituation(this ScienceSituation situation) { switch (situation) { case ScienceSituation.SrfLanded: return ScienceSituation.SrfLanded; case ScienceSituation.SrfSplashed: return ScienceSituation.SrfSplashed; case ScienceSituation.FlyingLow: return ScienceSituation.FlyingLow; case ScienceSituation.FlyingHigh: return ScienceSituation.FlyingHigh; case ScienceSituation.InSpaceLow: return ScienceSituation.InSpaceLow; case ScienceSituation.InSpaceHigh: return ScienceSituation.InSpaceHigh; case ScienceSituation.Surface: return ScienceSituation.SrfLanded; case ScienceSituation.Flying: return ScienceSituation.FlyingHigh; case ScienceSituation.Space: case ScienceSituation.BodyGlobal: default: return ScienceSituation.InSpaceLow; } } /// <summary> validate and convert our bitmasks to their stock equivalent</summary> // Note: any modification in this should be reflected in ToStockSituation() public static bool ValidateSituationBitMask(ref uint situationMask, uint biomeMask, out uint stockSituationMask, out uint stockBiomeMask, out string errorMessage) { errorMessage = string.Empty; stockSituationMask = GetStockBitMask(situationMask); stockBiomeMask = GetStockBitMask(biomeMask); if (MaskHasSituation(situationMask, ScienceSituation.Surface)) { if (MaskHasSituation(situationMask, ScienceSituation.SrfSplashed) || MaskHasSituation(situationMask, ScienceSituation.SrfLanded)) { errorMessage += "Experiment situation definition error : `Surface` can't be combined with `SrfSplashed` or `SrfLanded`\n"; SetSituationBitInMask(ref situationMask, ScienceSituation.SrfSplashed, false); SetSituationBitInMask(ref situationMask, ScienceSituation.SrfLanded, false); } // make sure the stock masks don't have SrfSplashed SetSituationBitInMask(ref stockSituationMask, ScienceSituation.SrfSplashed, false); SetSituationBitInMask(ref stockBiomeMask, ScienceSituation.SrfSplashed, false); // patch Surface as SrfLanded in the stock masks SetSituationBitInMask(ref stockSituationMask, ScienceSituation.SrfLanded, true); SetSituationBitInMask(ref stockBiomeMask, ScienceSituation.SrfLanded, MaskHasSituation(biomeMask, ScienceSituation.Surface)); } if (MaskHasSituation(situationMask, ScienceSituation.Flying)) { if (MaskHasSituation(situationMask, ScienceSituation.FlyingHigh) || MaskHasSituation(situationMask, ScienceSituation.FlyingLow)) { errorMessage += "Experiment situation definition error : `Flying` can't be combined with `FlyingHigh` or `FlyingLow`\n"; SetSituationBitInMask(ref situationMask, ScienceSituation.FlyingHigh, false); SetSituationBitInMask(ref situationMask, ScienceSituation.FlyingLow, false); } // make sure the stock masks don't have FlyingLow SetSituationBitInMask(ref stockSituationMask, ScienceSituation.FlyingLow, false); SetSituationBitInMask(ref stockBiomeMask, ScienceSituation.FlyingLow, false); // patch Flying as FlyingHigh in the stock masks SetSituationBitInMask(ref stockSituationMask, ScienceSituation.FlyingHigh, true); SetSituationBitInMask(ref stockBiomeMask, ScienceSituation.FlyingHigh, MaskHasSituation(biomeMask, ScienceSituation.Flying)); } if (MaskHasSituation(situationMask, ScienceSituation.Space)) { if (MaskHasSituation(situationMask, ScienceSituation.InSpaceHigh) || MaskHasSituation(situationMask, ScienceSituation.InSpaceLow)) { errorMessage += "Experiment situation definition error : `Space` can't be combined with `InSpaceHigh` or `InSpaceLow`\n"; SetSituationBitInMask(ref situationMask, ScienceSituation.InSpaceHigh, false); SetSituationBitInMask(ref situationMask, ScienceSituation.InSpaceLow, false); } // make sure the stock masks don't have InSpaceHigh SetSituationBitInMask(ref stockSituationMask, ScienceSituation.InSpaceHigh, false); SetSituationBitInMask(ref stockBiomeMask, ScienceSituation.InSpaceHigh, false); // patch Space as InSpaceLow in the stock masks SetSituationBitInMask(ref stockSituationMask, ScienceSituation.InSpaceLow, true); SetSituationBitInMask(ref stockBiomeMask, ScienceSituation.InSpaceLow, MaskHasSituation(biomeMask, ScienceSituation.Space)); } if (MaskHasSituation(situationMask, ScienceSituation.BodyGlobal)) { if (situationMask != ScienceSituation.BodyGlobal.BitValue()) { errorMessage += "Experiment situation definition error : `BodyGlobal` can't be combined with another situation\n"; situationMask = ScienceSituation.BodyGlobal.BitValue(); } stockSituationMask = ScienceSituation.InSpaceLow.BitValue(); if (MaskHasSituation(biomeMask, ScienceSituation.BodyGlobal)) stockBiomeMask = ScienceSituation.InSpaceLow.BitValue(); else stockBiomeMask = 0; } return errorMessage == string.Empty; } public static uint GetStockBitMask(uint bitMask) { uint stockBitMask = 0; foreach (ScienceSituation situation in BitMaskToSituations(bitMask)) { switch (situation) { case ScienceSituation.SrfLanded: case ScienceSituation.SrfSplashed: case ScienceSituation.FlyingLow: case ScienceSituation.FlyingHigh: case ScienceSituation.InSpaceLow: case ScienceSituation.InSpaceHigh: stockBitMask += situation.BitValue(); break; } } return stockBitMask; } private static void SetSituationBitInMask(ref uint mask, ScienceSituation situation, bool value) { if (value) mask = (uint)((int)mask | (1 << (int)situation)); else mask = (uint)((int)mask & ~(1 << (int)situation)); } private static bool MaskHasSituation(uint mask, ScienceSituation situation) { return (mask & situation.BitValue()) != 0; } public static readonly ScienceSituation[] validSituations = new ScienceSituation[] { ScienceSituation.SrfLanded, ScienceSituation.SrfSplashed, ScienceSituation.FlyingLow, ScienceSituation.FlyingHigh, ScienceSituation.InSpaceLow, ScienceSituation.InSpaceHigh, ScienceSituation.Surface, ScienceSituation.Flying, ScienceSituation.Space, ScienceSituation.BodyGlobal }; public static readonly VirtualBiome[] validVirtualBiomes = new VirtualBiome[] { VirtualBiome.NorthernHemisphere, VirtualBiome.SouthernHemisphere, VirtualBiome.InnerBelt, VirtualBiome.OuterBelt, VirtualBiome.Magnetosphere, VirtualBiome.Interstellar, VirtualBiome.Reentry, VirtualBiome.Storm }; public const int minVirtualBiome = 247; public static readonly string[] validSituationsStrings = new string[] { "SrfLanded", "SrfSplashed", "FlyingLow", "FlyingHigh", "InSpaceLow", "InSpaceHigh", "Surface", "Flying", "Space", "BodyGlobal" }; } }
/* * Copyright (c) Contributors, http://aurora-sim.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Aurora-Sim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Security; using OpenMetaverse; using OpenMetaverse.Packets; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Physics.Manager; using PrimType = Aurora.ScriptEngine.AuroraDotNetEngine.MiniModule.PrimType; using SculptType = Aurora.ScriptEngine.AuroraDotNetEngine.MiniModule.SculptType; using Aurora.Framework; using Aurora.ScriptEngine.AuroraDotNetEngine; namespace Aurora.ScriptEngine.AuroraDotNetEngine.MiniModule { class SOPObject : MarshalByRefObject, IObject, IObjectPhysics, IObjectShape, IObjectSound { private readonly IScene m_rootScene; private readonly uint m_localID; private readonly ISecurityCredential m_security; [Obsolete("Replace with 'credential' constructor [security]")] public SOPObject(Scene rootScene, uint localID) { m_rootScene = rootScene; m_localID = localID; } public SOPObject (IScene rootScene, uint localID, ISecurityCredential credential) { m_rootScene = rootScene; m_localID = localID; m_security = credential; } /// <summary> /// This needs to run very, very quickly. /// It is utilized in nearly every property and method. /// </summary> /// <returns></returns> private ISceneChildEntity GetSOP () { return m_rootScene.GetSceneObjectPart(m_localID); } private bool CanEdit() { if (!m_security.CanEditObject(this)) { throw new SecurityException("Insufficient Permission to edit object with UUID [" + GetSOP().UUID + "]"); } return true; } #region OnTouch private event OnTouchDelegate _OnTouch; private bool _OnTouchActive = false; public event OnTouchDelegate OnTouch { add { if (CanEdit()) { if (!_OnTouchActive) { GetSOP().Flags |= PrimFlags.Touch; _OnTouchActive = true; m_rootScene.EventManager.OnObjectGrab += EventManager_OnObjectGrab; } _OnTouch += value; } } remove { _OnTouch -= value; if (_OnTouch == null) { GetSOP().Flags &= ~PrimFlags.Touch; _OnTouchActive = false; m_rootScene.EventManager.OnObjectGrab -= EventManager_OnObjectGrab; } } } void EventManager_OnObjectGrab (ISceneChildEntity part, ISceneChildEntity child, Vector3 offsetPos, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs) { if (_OnTouchActive && m_localID == part.LocalId) { TouchEventArgs e = new TouchEventArgs(); e.Avatar = new SPAvatar(m_rootScene, remoteClient.AgentId, m_security); e.TouchBiNormal = surfaceArgs.Binormal; e.TouchMaterialIndex = surfaceArgs.FaceIndex; e.TouchNormal = surfaceArgs.Normal; e.TouchPosition = surfaceArgs.Position; e.TouchST = new Vector2(surfaceArgs.STCoord.X, surfaceArgs.STCoord.Y); e.TouchUV = new Vector2(surfaceArgs.UVCoord.X, surfaceArgs.UVCoord.Y); IObject sender = this; if (_OnTouch != null) _OnTouch(sender, e); } } #endregion public bool Exists { get { return GetSOP() != null; } } public uint LocalID { get { return m_localID; } } public UUID GlobalID { get { return GetSOP().UUID; } } public string Name { get { return GetSOP().Name; } set { if (CanEdit()) GetSOP().Name = value; } } public string Description { get { return GetSOP().Description; } set { if (CanEdit()) GetSOP().Description = value; } } public UUID OwnerId { get { return GetSOP().OwnerID;} } public UUID CreatorId { get { return GetSOP().CreatorID;} } public IObject[] Children { get { ISceneChildEntity my = GetSOP (); int total = my.ParentEntity.PrimCount; IObject[] rets = new IObject[total]; int i = 0; foreach (ISceneChildEntity child in my.ParentEntity.ChildrenEntities()) { rets[i++] = new SOPObject(m_rootScene, child.LocalId, m_security); } return rets; } } public IObject Root { get { return new SOPObject(m_rootScene, GetSOP().ParentEntity.RootChild.LocalId, m_security); } } public IObjectMaterial[] Materials { get { ISceneChildEntity sop = GetSOP (); IObjectMaterial[] rets = new IObjectMaterial[getNumberOfSides(sop)]; for (int i = 0; i < rets.Length; i++) { rets[i] = new SOPObjectMaterial(i, sop); } return rets; } } public Vector3 Scale { get { return GetSOP().Scale; } set { if (CanEdit()) GetSOP().Scale = value; } } public Quaternion WorldRotation { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public Quaternion OffsetRotation { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public Vector3 WorldPosition { get { return GetSOP().AbsolutePosition; } set { if (CanEdit()) { ISceneChildEntity pos = GetSOP (); pos.UpdateOffSet(value - pos.AbsolutePosition); } } } public Vector3 OffsetPosition { get { return GetSOP().OffsetPosition; } set { if (CanEdit()) { GetSOP().FixOffsetPosition(value,false); } } } public Vector3 SitTarget { get { return GetSOP().SitTargetPosition; } set { if (CanEdit()) { GetSOP().SitTargetPosition = value; } } } public string SitTargetText { get { return GetSOP().SitName; } set { if (CanEdit()) { GetSOP().SitName = value; } } } public string TouchText { get { return GetSOP().TouchName; } set { if (CanEdit()) { GetSOP().TouchName = value; } } } public string Text { get { return GetSOP().Text; } set { if (CanEdit()) { GetSOP().SetText(value,new Vector3(1.0f,1.0f,1.0f),1.0f); } } } public bool IsRotationLockedX { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool IsRotationLockedY { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool IsRotationLockedZ { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool IsSandboxed { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool IsImmotile { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool IsAlwaysReturned { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool IsTemporary { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool IsFlexible { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public PhysicsMaterial PhysicsMaterial { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public IObjectPhysics Physics { get { return this; } } public IObjectShape Shape { get { return this; } } public IObjectInventory Inventory { get { return new SOPObjectInventory(m_rootScene, GetSOP().TaskInventory); } } #region Public Functions public void Say(string msg) { if (!CanEdit()) return; ISceneChildEntity sop = GetSOP (); IChatModule chatModule = m_rootScene.RequestModuleInterface<IChatModule>(); if (chatModule != null) chatModule.SimChat(msg, ChatTypeEnum.Say, 0, sop.AbsolutePosition, sop.Name, sop.UUID, false, m_rootScene); } public void Say(string msg,int channel) { if (!CanEdit()) return; ISceneChildEntity sop = GetSOP (); IChatModule chatModule = m_rootScene.RequestModuleInterface<IChatModule>(); if (chatModule != null) chatModule.SimChat(msg, ChatTypeEnum.Say, channel, sop.AbsolutePosition, sop.Name, sop.UUID, false, m_rootScene); } public void Dialog(UUID avatar, string message, string[] buttons, int chat_channel) { if (!CanEdit()) return; IDialogModule dm = m_rootScene.RequestModuleInterface<IDialogModule>(); if (dm == null) return; if (buttons.Length < 1) { Say("ERROR: No less than 1 button can be shown",2147483647); return; } if (buttons.Length > 12) { Say("ERROR: No more than 12 buttons can be shown",2147483647); return; } foreach (string button in buttons) { if (button == String.Empty) { Say("ERROR: button label cannot be blank",2147483647); return; } if (button.Length > 24) { Say("ERROR: button label cannot be longer than 24 characters",2147483647); return; } } dm.SendDialogToUser( avatar, GetSOP().Name, GetSOP().UUID, GetSOP().OwnerID, message, new UUID("00000000-0000-2222-3333-100000001000"), chat_channel, buttons); } #endregion #region Supporting Functions // Helper functions to understand if object has cut, hollow, dimple, and other affecting number of faces private static void hasCutHollowDimpleProfileCut(int primType, PrimitiveBaseShape shape, out bool hasCut, out bool hasHollow, out bool hasDimple, out bool hasProfileCut) { if (primType == (int)PrimType.Box || primType == (int)PrimType.Cylinder || primType == (int)PrimType.Prism) hasCut = (shape.ProfileBegin > 0) || (shape.ProfileEnd > 0); else hasCut = (shape.PathBegin > 0) || (shape.PathEnd > 0); hasHollow = shape.ProfileHollow > 0; hasDimple = (shape.ProfileBegin > 0) || (shape.ProfileEnd > 0); // taken from llSetPrimitiveParms hasProfileCut = hasDimple; // is it the same thing? } private static int getScriptPrimType(PrimitiveBaseShape primShape) { if (primShape.SculptEntry) return (int) PrimType.Sculpt; if ((primShape.ProfileCurve & 0x07) == (byte) ProfileShape.Square) { if (primShape.PathCurve == (byte) Extrusion.Straight) return (int) PrimType.Box; if (primShape.PathCurve == (byte) Extrusion.Curve1) return (int) PrimType.Tube; } else if ((primShape.ProfileCurve & 0x07) == (byte) ProfileShape.Circle) { if (primShape.PathCurve == (byte) Extrusion.Straight) return (int) PrimType.Cylinder; if (primShape.PathCurve == (byte) Extrusion.Curve1) return (int) PrimType.Torus; } else if ((primShape.ProfileCurve & 0x07) == (byte) ProfileShape.HalfCircle) { if (primShape.PathCurve == (byte) Extrusion.Curve1 || primShape.PathCurve == (byte) Extrusion.Curve2) return (int) PrimType.Sphere; } else if ((primShape.ProfileCurve & 0x07) == (byte) ProfileShape.EquilateralTriangle) { if (primShape.PathCurve == (byte) Extrusion.Straight) return (int) PrimType.Prism; if (primShape.PathCurve == (byte) Extrusion.Curve1) return (int) PrimType.Ring; } return (int) PrimType.NotPrimitive; } private static int getNumberOfSides (ISceneChildEntity part) { int ret; bool hasCut; bool hasHollow; bool hasDimple; bool hasProfileCut; int primType = getScriptPrimType(part.Shape); hasCutHollowDimpleProfileCut(primType, part.Shape, out hasCut, out hasHollow, out hasDimple, out hasProfileCut); switch (primType) { default: case (int) PrimType.Box: ret = 6; if (hasCut) ret += 2; if (hasHollow) ret += 1; break; case (int) PrimType.Cylinder: ret = 3; if (hasCut) ret += 2; if (hasHollow) ret += 1; break; case (int) PrimType.Prism: ret = 5; if (hasCut) ret += 2; if (hasHollow) ret += 1; break; case (int) PrimType.Sphere: ret = 1; if (hasCut) ret += 2; if (hasDimple) ret += 2; if (hasHollow) ret += 1; // GOTCHA: LSL shows 2 additional sides here. // This has been fixed, but may cause porting issues. break; case (int) PrimType.Torus: ret = 1; if (hasCut) ret += 2; if (hasProfileCut) ret += 2; if (hasHollow) ret += 1; break; case (int) PrimType.Tube: ret = 4; if (hasCut) ret += 2; if (hasProfileCut) ret += 2; if (hasHollow) ret += 1; break; case (int) PrimType.Ring: ret = 3; if (hasCut) ret += 2; if (hasProfileCut) ret += 2; if (hasHollow) ret += 1; break; case (int) PrimType.Sculpt: ret = 1; break; } return ret; } #endregion #region IObjectPhysics public bool Enabled { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool Phantom { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public bool PhantomCollisions { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public double Density { get { return (GetSOP().PhysActor.Mass/Scale.X*Scale.Y/Scale.Z); } set { throw new NotImplementedException(); } } public double Mass { get { return GetSOP().PhysActor.Mass; } set { throw new NotImplementedException(); } } public double Buoyancy { get { return GetSOP().PhysActor.Buoyancy; } set { GetSOP().PhysActor.Buoyancy = (float)value; } } public Vector3 GeometricCenter { get { Vector3 tmp = GetSOP().PhysActor.GeometricCenter; return tmp; } } public Vector3 CenterOfMass { get { Vector3 tmp = GetSOP().PhysActor.CenterOfMass; return tmp; } } public Vector3 RotationalVelocity { get { Vector3 tmp = GetSOP().PhysActor.RotationalVelocity; return tmp; } set { if (!CanEdit()) return; GetSOP().PhysActor.RotationalVelocity = value; } } public Vector3 Velocity { get { Vector3 tmp = GetSOP().PhysActor.Velocity; return tmp; } set { if (!CanEdit()) return; GetSOP().PhysActor.Velocity = value; } } public Vector3 Torque { get { Vector3 tmp = GetSOP().PhysActor.Torque; return tmp; } set { if (!CanEdit()) return; GetSOP().PhysActor.Torque = value; } } public Vector3 Acceleration { get { Vector3 tmp = GetSOP().PhysActor.Acceleration; return tmp; } } public Vector3 Force { get { Vector3 tmp = GetSOP().PhysActor.Force; return tmp; } set { if (!CanEdit()) return; GetSOP().PhysActor.Force = value; } } public bool FloatOnWater { set { if (!CanEdit()) return; GetSOP().PhysActor.FloatOnWater = value; } } public void AddForce(Vector3 force, bool pushforce) { if (!CanEdit()) return; GetSOP().PhysActor.AddForce(force, pushforce); } public void AddAngularForce(Vector3 force, bool pushforce) { if (!CanEdit()) return; GetSOP().PhysActor.AddAngularForce(force, pushforce); } public void SetMomentum(Vector3 momentum) { if (!CanEdit()) return; GetSOP().PhysActor.SetMomentum(momentum); } #endregion #region Implementation of IObjectShape private UUID m_sculptMap = UUID.Zero; public UUID SculptMap { get { return m_sculptMap; } set { if (!CanEdit()) return; m_sculptMap = value; SetPrimitiveSculpted(SculptMap, (byte) SculptType); } } private SculptType m_sculptType = SculptType.Default; public SculptType SculptType { get { return m_sculptType; } set { if (!CanEdit()) return; m_sculptType = value; SetPrimitiveSculpted(SculptMap, (byte) SculptType); } } public HoleShape HoleType { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public double HoleSize { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public PrimType PrimType { get { return (PrimType)getScriptPrimType(GetSOP().Shape); } set { throw new System.NotImplementedException(); } } private void SetPrimitiveSculpted(UUID map, byte type) { ObjectShapePacket.ObjectDataBlock shapeBlock = new ObjectShapePacket.ObjectDataBlock(); ISceneChildEntity part = GetSOP (); UUID sculptId = map; shapeBlock.ObjectLocalID = part.LocalId; shapeBlock.PathScaleX = 100; shapeBlock.PathScaleY = 150; // retain pathcurve shapeBlock.PathCurve = part.Shape.PathCurve; part.Shape.SetSculptData((byte)type, sculptId); part.Shape.SculptEntry = true; part.UpdateShape(shapeBlock); } #endregion #region Implementation of IObjectSound public IObjectSound Sound { get { return this; } } public void Play(UUID asset, double volume) { if (!CanEdit()) return; GetSOP().SendSound(asset.ToString(), volume, true, 0, 0, false, false); } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core { using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Runtime; using System.Threading; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache.Affinity; using Apache.Ignite.Core.Client; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Cache.Affinity; using Apache.Ignite.Core.Impl.Client; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Handle; using Apache.Ignite.Core.Impl.Log; using Apache.Ignite.Core.Impl.Memory; using Apache.Ignite.Core.Impl.Unmanaged; using Apache.Ignite.Core.Impl.Unmanaged.Jni; using Apache.Ignite.Core.Lifecycle; using Apache.Ignite.Core.Log; using Apache.Ignite.Core.Resource; using BinaryReader = Apache.Ignite.Core.Impl.Binary.BinaryReader; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; /// <summary> /// This class defines a factory for the main Ignite API. /// <p/> /// Use <see cref="Start()"/> method to start Ignite with default configuration. /// <para/> /// All members are thread-safe and may be used concurrently from multiple threads. /// </summary> public static class Ignition { /// <summary> /// Default configuration section name. /// </summary> public const string ConfigurationSectionName = "igniteConfiguration"; /// <summary> /// Default configuration section name. /// </summary> public const string ClientConfigurationSectionName = "igniteClientConfiguration"; /** */ private static readonly object SyncRoot = new object(); /** GC warning flag. */ private static int _gcWarn; /** */ private static readonly IDictionary<NodeKey, Ignite> Nodes = new Dictionary<NodeKey, Ignite>(); /** Current DLL name. */ private static readonly string IgniteDllName = Path.GetFileName(Assembly.GetExecutingAssembly().Location); /** Startup info. */ [ThreadStatic] private static Startup _startup; /** Client mode flag. */ [ThreadStatic] private static bool _clientMode; /// <summary> /// Static initializer. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")] static Ignition() { AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload; } /// <summary> /// Gets or sets a value indicating whether Ignite should be started in client mode. /// Client nodes cannot hold data in caches. /// </summary> public static bool ClientMode { get { return _clientMode; } set { _clientMode = value; } } /// <summary> /// Starts Ignite with default configuration. By default this method will /// use Ignite configuration defined in <c>{IGNITE_HOME}/config/default-config.xml</c> /// configuration file. If such file is not found, then all system defaults will be used. /// </summary> /// <returns>Started Ignite.</returns> public static IIgnite Start() { return Start(new IgniteConfiguration()); } /// <summary> /// Starts all grids specified within given Spring XML configuration file. If Ignite with given name /// is already started, then exception is thrown. In this case all instances that may /// have been started so far will be stopped too. /// </summary> /// <param name="springCfgPath">Spring XML configuration file path or URL. Note, that the path can be /// absolute or relative to IGNITE_HOME.</param> /// <returns>Started Ignite. If Spring configuration contains multiple Ignite instances, then the 1st /// found instance is returned.</returns> public static IIgnite Start(string springCfgPath) { return Start(new IgniteConfiguration {SpringConfigUrl = springCfgPath}); } /// <summary> /// Reads <see cref="IgniteConfiguration"/> from application configuration /// <see cref="IgniteConfigurationSection"/> with <see cref="ConfigurationSectionName"/> /// name and starts Ignite. /// </summary> /// <returns>Started Ignite.</returns> public static IIgnite StartFromApplicationConfiguration() { // ReSharper disable once IntroduceOptionalParameters.Global return StartFromApplicationConfiguration(ConfigurationSectionName); } /// <summary> /// Reads <see cref="IgniteConfiguration"/> from application configuration /// <see cref="IgniteConfigurationSection"/> with specified name and starts Ignite. /// </summary> /// <param name="sectionName">Name of the section.</param> /// <returns>Started Ignite.</returns> public static IIgnite StartFromApplicationConfiguration(string sectionName) { IgniteArgumentCheck.NotNullOrEmpty(sectionName, "sectionName"); var section = ConfigurationManager.GetSection(sectionName) as IgniteConfigurationSection; if (section == null) throw new ConfigurationErrorsException(string.Format("Could not find {0} with name '{1}'", typeof(IgniteConfigurationSection).Name, sectionName)); if (section.IgniteConfiguration == null) throw new ConfigurationErrorsException( string.Format("{0} with name '{1}' is defined in <configSections>, " + "but not present in configuration.", typeof(IgniteConfigurationSection).Name, sectionName)); return Start(section.IgniteConfiguration); } /// <summary> /// Reads <see cref="IgniteConfiguration" /> from application configuration /// <see cref="IgniteConfigurationSection" /> with specified name and starts Ignite. /// </summary> /// <param name="sectionName">Name of the section.</param> /// <param name="configPath">Path to the configuration file.</param> /// <returns>Started Ignite.</returns> public static IIgnite StartFromApplicationConfiguration(string sectionName, string configPath) { var section = GetConfigurationSection<IgniteConfigurationSection>(sectionName, configPath); if (section.IgniteConfiguration == null) { throw new ConfigurationErrorsException( string.Format("{0} with name '{1}' in file '{2}' is defined in <configSections>, " + "but not present in configuration.", typeof(IgniteConfigurationSection).Name, sectionName, configPath)); } return Start(section.IgniteConfiguration); } /// <summary> /// Gets the configuration section. /// </summary> private static T GetConfigurationSection<T>(string sectionName, string configPath) where T : ConfigurationSection { IgniteArgumentCheck.NotNullOrEmpty(sectionName, "sectionName"); IgniteArgumentCheck.NotNullOrEmpty(configPath, "configPath"); var fileMap = GetConfigMap(configPath); var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); var section = config.GetSection(sectionName) as T; if (section == null) { throw new ConfigurationErrorsException( string.Format("Could not find {0} with name '{1}' in file '{2}'", typeof(T).Name, sectionName, configPath)); } return section; } /// <summary> /// Gets the configuration file map. /// </summary> private static ExeConfigurationFileMap GetConfigMap(string fileName) { var fullFileName = Path.GetFullPath(fileName); if (!File.Exists(fullFileName)) throw new ConfigurationErrorsException("Specified config file does not exist: " + fileName); return new ExeConfigurationFileMap { ExeConfigFilename = fullFileName }; } /// <summary> /// Starts Ignite with given configuration. /// </summary> /// <returns>Started Ignite.</returns> public static IIgnite Start(IgniteConfiguration cfg) { IgniteArgumentCheck.NotNull(cfg, "cfg"); cfg = new IgniteConfiguration(cfg); // Create a copy so that config can be modified and reused. lock (SyncRoot) { // 0. Init logger var log = cfg.Logger ?? new JavaLogger(); log.Debug("Starting Ignite.NET " + Assembly.GetExecutingAssembly().GetName().Version); // 1. Check GC settings. CheckServerGc(cfg, log); // 2. Create context. JvmDll.Load(cfg.JvmDllPath, log); var cbs = IgniteManager.CreateJvmContext(cfg, log); var env = cbs.Jvm.AttachCurrentThread(); log.Debug("JVM started."); var gridName = cfg.IgniteInstanceName; if (cfg.AutoGenerateIgniteInstanceName) { gridName = (gridName ?? "ignite-instance-") + Guid.NewGuid(); } // 3. Create startup object which will guide us through the rest of the process. _startup = new Startup(cfg, cbs); PlatformJniTarget interopProc = null; try { // 4. Initiate Ignite start. UU.IgnitionStart(env, cfg.SpringConfigUrl, gridName, ClientMode, cfg.Logger != null, cbs.IgniteId, cfg.RedirectJavaConsoleOutput); // 5. At this point start routine is finished. We expect STARTUP object to have all necessary data. var node = _startup.Ignite; interopProc = (PlatformJniTarget)node.InteropProcessor; var javaLogger = log as JavaLogger; if (javaLogger != null) { javaLogger.SetIgnite(node); } // 6. On-start callback (notify lifecycle components). node.OnStart(); Nodes[new NodeKey(_startup.Name)] = node; return node; } catch (Exception ex) { // 1. Perform keys cleanup. string name = _startup.Name; if (name != null) { NodeKey key = new NodeKey(name); if (Nodes.ContainsKey(key)) Nodes.Remove(key); } // 2. Stop Ignite node if it was started. if (interopProc != null) UU.IgnitionStop(gridName, true); // 3. Throw error further (use startup error if exists because it is more precise). if (_startup.Error != null) { // Wrap in a new exception to preserve original stack trace. throw new IgniteException("Failed to start Ignite.NET, check inner exception for details", _startup.Error); } var jex = ex as JavaException; if (jex == null) { throw; } throw ExceptionUtils.GetException(null, jex); } finally { var ignite = _startup.Ignite; _startup = null; if (ignite != null) { ignite.ProcessorReleaseStart(); } } } } /// <summary> /// Check whether GC is set to server mode. /// </summary> /// <param name="cfg">Configuration.</param> /// <param name="log">Log.</param> private static void CheckServerGc(IgniteConfiguration cfg, ILogger log) { if (!cfg.SuppressWarnings && !GCSettings.IsServerGC && Interlocked.CompareExchange(ref _gcWarn, 1, 0) == 0) log.Warn("GC server mode is not enabled, this could lead to less " + "than optimal performance on multi-core machines (to enable see " + "http://msdn.microsoft.com/en-us/library/ms229357(v=vs.110).aspx)."); } /// <summary> /// Prepare callback invoked from Java. /// </summary> /// <param name="inStream">Input stream with data.</param> /// <param name="outStream">Output stream.</param> /// <param name="handleRegistry">Handle registry.</param> /// <param name="log">Log.</param> internal static void OnPrepare(PlatformMemoryStream inStream, PlatformMemoryStream outStream, HandleRegistry handleRegistry, ILogger log) { try { BinaryReader reader = BinaryUtils.Marshaller.StartUnmarshal(inStream); PrepareConfiguration(reader, outStream, log); PrepareLifecycleHandlers(reader, outStream, handleRegistry); PrepareAffinityFunctions(reader, outStream); outStream.SynchronizeOutput(); } catch (Exception e) { _startup.Error = e; throw; } } /// <summary> /// Prepare configuration. /// </summary> /// <param name="reader">Reader.</param> /// <param name="outStream">Response stream.</param> /// <param name="log">Log.</param> private static void PrepareConfiguration(BinaryReader reader, PlatformMemoryStream outStream, ILogger log) { // 1. Load assemblies. IgniteConfiguration cfg = _startup.Configuration; LoadAssemblies(cfg.Assemblies); ICollection<string> cfgAssembllies; BinaryConfiguration binaryCfg; BinaryUtils.ReadConfiguration(reader, out cfgAssembllies, out binaryCfg); LoadAssemblies(cfgAssembllies); // 2. Create marshaller only after assemblies are loaded. if (cfg.BinaryConfiguration == null) cfg.BinaryConfiguration = binaryCfg; _startup.Marshaller = new Marshaller(cfg.BinaryConfiguration, log); // 3. Send configuration details to Java cfg.Validate(log); cfg.Write(BinaryUtils.Marshaller.StartMarshal(outStream)); // Use system marshaller. } /// <summary> /// Prepare lifecycle handlers. /// </summary> /// <param name="reader">Reader.</param> /// <param name="outStream">Output stream.</param> /// <param name="handleRegistry">Handle registry.</param> private static void PrepareLifecycleHandlers(IBinaryRawReader reader, IBinaryStream outStream, HandleRegistry handleRegistry) { IList<LifecycleHandlerHolder> beans = new List<LifecycleHandlerHolder> { new LifecycleHandlerHolder(new InternalLifecycleHandler()) // add internal bean for events }; // 1. Read beans defined in Java. int cnt = reader.ReadInt(); for (int i = 0; i < cnt; i++) beans.Add(new LifecycleHandlerHolder(CreateObject<ILifecycleHandler>(reader))); // 2. Append beans defined in local configuration. ICollection<ILifecycleHandler> nativeBeans = _startup.Configuration.LifecycleHandlers; if (nativeBeans != null) { foreach (ILifecycleHandler nativeBean in nativeBeans) beans.Add(new LifecycleHandlerHolder(nativeBean)); } // 3. Write bean pointers to Java stream. outStream.WriteInt(beans.Count); foreach (LifecycleHandlerHolder bean in beans) outStream.WriteLong(handleRegistry.AllocateCritical(bean)); // 4. Set beans to STARTUP object. _startup.LifecycleHandlers = beans; } /// <summary> /// Prepares the affinity functions. /// </summary> private static void PrepareAffinityFunctions(BinaryReader reader, PlatformMemoryStream outStream) { var cnt = reader.ReadInt(); var writer = reader.Marshaller.StartMarshal(outStream); for (var i = 0; i < cnt; i++) { var objHolder = new ObjectInfoHolder(reader); AffinityFunctionSerializer.Write(writer, objHolder.CreateInstance<IAffinityFunction>(), objHolder); } } /// <summary> /// Creates an object and sets the properties. /// </summary> /// <param name="reader">Reader.</param> /// <returns>Resulting object.</returns> private static T CreateObject<T>(IBinaryRawReader reader) { return IgniteUtils.CreateInstance<T>(reader.ReadString(), reader.ReadDictionaryAsGeneric<string, object>()); } /// <summary> /// Kernal start callback. /// </summary> /// <param name="interopProc">Interop processor.</param> /// <param name="stream">Stream.</param> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "PlatformJniTarget is passed further")] internal static void OnStart(GlobalRef interopProc, IBinaryStream stream) { try { // 1. Read data and leave critical state ASAP. BinaryReader reader = BinaryUtils.Marshaller.StartUnmarshal(stream); // ReSharper disable once PossibleInvalidOperationException var name = reader.ReadString(); // 2. Set ID and name so that Start() method can use them later. _startup.Name = name; if (Nodes.ContainsKey(new NodeKey(name))) throw new IgniteException("Ignite with the same name already started: " + name); _startup.Ignite = new Ignite(_startup.Configuration, _startup.Name, new PlatformJniTarget(interopProc, _startup.Marshaller), _startup.Marshaller, _startup.LifecycleHandlers, _startup.Callbacks); } catch (Exception e) { // 5. Preserve exception to throw it later in the "Start" method and throw it further // to abort startup in Java. _startup.Error = e; throw; } } /// <summary> /// Load assemblies. /// </summary> /// <param name="assemblies">Assemblies.</param> private static void LoadAssemblies(IEnumerable<string> assemblies) { if (assemblies != null) { foreach (string s in assemblies) { // 1. Try loading as directory. if (Directory.Exists(s)) { string[] files = Directory.GetFiles(s, "*.dll"); #pragma warning disable 0168 foreach (string dllPath in files) { if (!SelfAssembly(dllPath)) { try { Assembly.LoadFile(dllPath); } catch (BadImageFormatException) { // No-op. } } } #pragma warning restore 0168 continue; } // 2. Try loading using full-name. try { Assembly assembly = Assembly.Load(s); if (assembly != null) continue; } catch (Exception e) { if (!(e is FileNotFoundException || e is FileLoadException)) throw new IgniteException("Failed to load assembly: " + s, e); } // 3. Try loading using file path. try { Assembly assembly = Assembly.LoadFrom(s); // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (assembly != null) continue; } catch (Exception e) { if (!(e is FileNotFoundException || e is FileLoadException)) throw new IgniteException("Failed to load assembly: " + s, e); } // 4. Not found, exception. throw new IgniteException("Failed to load assembly: " + s); } } } /// <summary> /// Whether assembly points to Ignite binary. /// </summary> /// <param name="assembly">Assembly to check..</param> /// <returns><c>True</c> if this is one of GG assemblies.</returns> private static bool SelfAssembly(string assembly) { return assembly.EndsWith(IgniteDllName, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Gets a named Ignite instance. If Ignite name is <c>null</c> or empty string, /// then default no-name Ignite will be returned. Note that caller of this method /// should not assume that it will return the same instance every time. /// <p /> /// Note that single process can run multiple Ignite instances and every Ignite instance (and its /// node) can belong to a different grid. Ignite name defines what grid a particular Ignite /// instance (and correspondingly its node) belongs to. /// </summary> /// <param name="name">Ignite name to which requested Ignite instance belongs. If <c>null</c>, /// then Ignite instance belonging to a default no-name Ignite will be returned.</param> /// <returns> /// An instance of named grid. /// </returns> /// <exception cref="IgniteException">When there is no Ignite instance with specified name.</exception> public static IIgnite GetIgnite(string name) { var ignite = TryGetIgnite(name); if (ignite == null) throw new IgniteException("Ignite instance was not properly started or was already stopped: " + name); return ignite; } /// <summary> /// Gets the default Ignite instance with null name, or an instance with any name when there is only one. /// <para /> /// Note that caller of this method should not assume that it will return the same instance every time. /// </summary> /// <returns>Default Ignite instance.</returns> /// <exception cref="IgniteException">When there is no matching Ignite instance.</exception> public static IIgnite GetIgnite() { lock (SyncRoot) { if (Nodes.Count == 0) { throw new IgniteException("Failed to get default Ignite instance: " + "there are no instances started."); } if (Nodes.Count == 1) { return Nodes.Single().Value; } Ignite result; if (Nodes.TryGetValue(new NodeKey(null), out result)) { return result; } throw new IgniteException(string.Format("Failed to get default Ignite instance: " + "there are {0} instances started, and none of them has null name.", Nodes.Count)); } } /// <summary> /// Gets all started Ignite instances. /// </summary> /// <returns>All Ignite instances.</returns> public static ICollection<IIgnite> GetAll() { lock (SyncRoot) { return Nodes.Values.ToArray(); } } /// <summary> /// Gets a named Ignite instance, or <c>null</c> if none found. If Ignite name is <c>null</c> or empty string, /// then default no-name Ignite will be returned. Note that caller of this method /// should not assume that it will return the same instance every time. /// <p/> /// Note that single process can run multiple Ignite instances and every Ignite instance (and its /// node) can belong to a different grid. Ignite name defines what grid a particular Ignite /// instance (and correspondingly its node) belongs to. /// </summary> /// <param name="name">Ignite name to which requested Ignite instance belongs. If <c>null</c>, /// then Ignite instance belonging to a default no-name Ignite will be returned. /// </param> /// <returns>An instance of named grid, or null.</returns> public static IIgnite TryGetIgnite(string name) { lock (SyncRoot) { Ignite result; return !Nodes.TryGetValue(new NodeKey(name), out result) ? null : result; } } /// <summary> /// Gets the default Ignite instance with null name, or an instance with any name when there is only one. /// Returns null when there are no Ignite instances started, or when there are more than one, /// and none of them has null name. /// </summary> /// <returns>An instance of default no-name grid, or null.</returns> public static IIgnite TryGetIgnite() { lock (SyncRoot) { if (Nodes.Count == 1) { return Nodes.Single().Value; } return TryGetIgnite(null); } } /// <summary> /// Stops named grid. If <c>cancel</c> flag is set to <c>true</c> then /// all jobs currently executing on local node will be interrupted. If /// grid name is <c>null</c>, then default no-name Ignite will be stopped. /// </summary> /// <param name="name">Grid name. If <c>null</c>, then default no-name Ignite will be stopped.</param> /// <param name="cancel">If <c>true</c> then all jobs currently executing will be cancelled /// by calling <c>ComputeJob.cancel</c>method.</param> /// <returns><c>true</c> if named Ignite instance was indeed found and stopped, <c>false</c> /// othwerwise (the instance with given <c>name</c> was not found).</returns> public static bool Stop(string name, bool cancel) { lock (SyncRoot) { NodeKey key = new NodeKey(name); Ignite node; if (!Nodes.TryGetValue(key, out node)) return false; node.Stop(cancel); Nodes.Remove(key); GC.Collect(); return true; } } /// <summary> /// Stops <b>all</b> started grids. If <c>cancel</c> flag is set to <c>true</c> then /// all jobs currently executing on local node will be interrupted. /// </summary> /// <param name="cancel">If <c>true</c> then all jobs currently executing will be cancelled /// by calling <c>ComputeJob.Cancel()</c> method.</param> public static void StopAll(bool cancel) { lock (SyncRoot) { while (Nodes.Count > 0) { var entry = Nodes.First(); entry.Value.Stop(cancel); Nodes.Remove(entry.Key); } } GC.Collect(); } /// <summary> /// Connects Ignite lightweight (thin) client to an Ignite node. /// <para /> /// Thin client connects to an existing Ignite node with a socket and does not start JVM in process. /// </summary> /// <param name="clientConfiguration">The client configuration.</param> /// <returns>Ignite client instance.</returns> public static IIgniteClient StartClient(IgniteClientConfiguration clientConfiguration) { IgniteArgumentCheck.NotNull(clientConfiguration, "clientConfiguration"); IgniteArgumentCheck.NotNull(clientConfiguration.Host, "clientConfiguration.Host"); return new IgniteClient(clientConfiguration); } /// <summary> /// Reads <see cref="IgniteClientConfiguration"/> from application configuration /// <see cref="IgniteClientConfigurationSection"/> with <see cref="ClientConfigurationSectionName"/> /// name and connects Ignite lightweight (thin) client to an Ignite node. /// <para /> /// Thin client connects to an existing Ignite node with a socket and does not start JVM in process. /// </summary> /// <returns>Ignite client instance.</returns> public static IIgniteClient StartClient() { // ReSharper disable once IntroduceOptionalParameters.Global return StartClient(ClientConfigurationSectionName); } /// <summary> /// Reads <see cref="IgniteClientConfiguration" /> from application configuration /// <see cref="IgniteClientConfigurationSection" /> with specified name and connects /// Ignite lightweight (thin) client to an Ignite node. /// <para /> /// Thin client connects to an existing Ignite node with a socket and does not start JVM in process. /// </summary> /// <param name="sectionName">Name of the configuration section.</param> /// <returns>Ignite client instance.</returns> public static IIgniteClient StartClient(string sectionName) { IgniteArgumentCheck.NotNullOrEmpty(sectionName, "sectionName"); var section = ConfigurationManager.GetSection(sectionName) as IgniteClientConfigurationSection; if (section == null) { throw new ConfigurationErrorsException(string.Format("Could not find {0} with name '{1}'.", typeof(IgniteClientConfigurationSection).Name, sectionName)); } if (section.IgniteClientConfiguration == null) { throw new ConfigurationErrorsException( string.Format("{0} with name '{1}' is defined in <configSections>, " + "but not present in configuration.", typeof(IgniteClientConfigurationSection).Name, sectionName)); } return StartClient(section.IgniteClientConfiguration); } /// <summary> /// Reads <see cref="IgniteConfiguration" /> from application configuration /// <see cref="IgniteConfigurationSection" /> with specified name and starts Ignite. /// </summary> /// <param name="sectionName">Name of the section.</param> /// <param name="configPath">Path to the configuration file.</param> /// <returns>Started Ignite.</returns> public static IIgniteClient StartClient(string sectionName, string configPath) { var section = GetConfigurationSection<IgniteClientConfigurationSection>(sectionName, configPath); if (section.IgniteClientConfiguration == null) { throw new ConfigurationErrorsException( string.Format("{0} with name '{1}' in file '{2}' is defined in <configSections>, " + "but not present in configuration.", typeof(IgniteClientConfigurationSection).Name, sectionName, configPath)); } return StartClient(section.IgniteClientConfiguration); } /// <summary> /// Handles the DomainUnload event of the CurrentDomain control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private static void CurrentDomain_DomainUnload(object sender, EventArgs e) { // If we don't stop Ignite.NET on domain unload, // we end up with broken instances in Java (invalid callbacks, etc). // IIS, in particular, is known to unload and reload domains within the same process. StopAll(true); } /// <summary> /// Grid key. Workaround for non-null key requirement in Dictionary. /// </summary> private class NodeKey { /** */ private readonly string _name; /// <summary> /// Initializes a new instance of the <see cref="NodeKey"/> class. /// </summary> /// <param name="name">The name.</param> internal NodeKey(string name) { _name = name; } /** <inheritdoc /> */ public override bool Equals(object obj) { var other = obj as NodeKey; return other != null && Equals(_name, other._name); } /** <inheritdoc /> */ public override int GetHashCode() { return _name == null ? 0 : _name.GetHashCode(); } } /// <summary> /// Value object to pass data between .Net methods during startup bypassing Java. /// </summary> private class Startup { /// <summary> /// Constructor. /// </summary> /// <param name="cfg">Configuration.</param> /// <param name="cbs"></param> internal Startup(IgniteConfiguration cfg, UnmanagedCallbacks cbs) { Configuration = cfg; Callbacks = cbs; } /// <summary> /// Configuration. /// </summary> internal IgniteConfiguration Configuration { get; private set; } /// <summary> /// Gets unmanaged callbacks. /// </summary> internal UnmanagedCallbacks Callbacks { get; private set; } /// <summary> /// Lifecycle handlers. /// </summary> internal IList<LifecycleHandlerHolder> LifecycleHandlers { get; set; } /// <summary> /// Node name. /// </summary> internal string Name { get; set; } /// <summary> /// Marshaller. /// </summary> internal Marshaller Marshaller { get; set; } /// <summary> /// Start error. /// </summary> internal Exception Error { get; set; } /// <summary> /// Gets or sets the ignite. /// </summary> internal Ignite Ignite { get; set; } } /// <summary> /// Internal handler for event notification. /// </summary> private class InternalLifecycleHandler : ILifecycleHandler { /** */ #pragma warning disable 649 // unused field [InstanceResource] private readonly IIgnite _ignite; /** <inheritdoc /> */ public void OnLifecycleEvent(LifecycleEventType evt) { if (evt == LifecycleEventType.BeforeNodeStop && _ignite != null) ((Ignite) _ignite).BeforeNodeStop(); } } } }
// Deflater.cs // // Copyright (C) 2001 Mike Krueger // Copyright (C) 2004 John Reilly // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; namespace ICSharpCode.SharpZipLib.Zip.Compression { /// <summary> /// This is the Deflater class. The deflater class compresses input /// with the deflate algorithm described in RFC 1951. It has several /// compression levels and three different strategies described below. /// /// This class is <i>not</i> thread safe. This is inherent in the API, due /// to the split of deflate and setInput. /// /// author of the original java version : Jochen Hoenicke /// </summary> public class Deflater { /// <summary> /// The best and slowest compression level. This tries to find very /// long and distant string repetitions. /// </summary> public static int BEST_COMPRESSION = 9; /// <summary> /// The worst but fastest compression level. /// </summary> public static int BEST_SPEED = 1; /// <summary> /// The default compression level. /// </summary> public static int DEFAULT_COMPRESSION = -1; /// <summary> /// This level won't compress at all but output uncompressed blocks. /// </summary> public static int NO_COMPRESSION = 0; /// <summary> /// The compression method. This is the only method supported so far. /// There is no need to use this constant at all. /// </summary> public static int DEFLATED = 8; /* * The Deflater can do the following state transitions: * * (1) -> INIT_STATE ----> INIT_FINISHING_STATE ---. * / | (2) (5) | * / v (5) | * (3)| SETDICT_STATE ---> SETDICT_FINISHING_STATE |(3) * \ | (3) | ,-------' * | | | (3) / * v v (5) v v * (1) -> BUSY_STATE ----> FINISHING_STATE * | (6) * v * FINISHED_STATE * \_____________________________________/ * | (7) * v * CLOSED_STATE * * (1) If we should produce a header we start in INIT_STATE, otherwise * we start in BUSY_STATE. * (2) A dictionary may be set only when we are in INIT_STATE, then * we change the state as indicated. * (3) Whether a dictionary is set or not, on the first call of deflate * we change to BUSY_STATE. * (4) -- intentionally left blank -- :) * (5) FINISHING_STATE is entered, when flush() is called to indicate that * there is no more INPUT. There are also states indicating, that * the header wasn't written yet. * (6) FINISHED_STATE is entered, when everything has been flushed to the * internal pending output buffer. * (7) At any time (7) * */ private static int IS_SETDICT = 0x01; private static int IS_FLUSHING = 0x04; private static int IS_FINISHING = 0x08; private static int INIT_STATE = 0x00; private static int SETDICT_STATE = 0x01; // private static int INIT_FINISHING_STATE = 0x08; // private static int SETDICT_FINISHING_STATE = 0x09; private static int BUSY_STATE = 0x10; private static int FLUSHING_STATE = 0x14; private static int FINISHING_STATE = 0x1c; private static int FINISHED_STATE = 0x1e; private static int CLOSED_STATE = 0x7f; /// <summary> /// Compression level. /// </summary> private int level; /// <summary> /// If true no Zlib/RFC1950 headers or footers are generated /// </summary> private bool noHeaderOrFooter; /// <summary> /// The current state. /// </summary> private int state; /// <summary> /// The total bytes of output written. /// </summary> private long totalOut; /// <summary> /// The pending output. /// </summary> private DeflaterPending pending; /// <summary> /// The deflater engine. /// </summary> private DeflaterEngine engine; /// <summary> /// Creates a new deflater with default compression level. /// </summary> public Deflater() : this(DEFAULT_COMPRESSION, false) { } /// <summary> /// Creates a new deflater with given compression level. /// </summary> /// <param name="lvl"> /// the compression level, a value between NO_COMPRESSION /// and BEST_COMPRESSION, or DEFAULT_COMPRESSION. /// </param> /// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception> public Deflater(int lvl) : this(lvl, false) { } /// <summary> /// Creates a new deflater with given compression level. /// </summary> /// <param name="level"> /// the compression level, a value between NO_COMPRESSION /// and BEST_COMPRESSION. /// </param> /// <param name="noHeaderOrFooter"> /// true, if we should suppress the Zlib/RFC1950 header at the /// beginning and the adler checksum at the end of the output. This is /// useful for the GZIP/PKZIP formats. /// </param> /// <exception cref="System.ArgumentOutOfRangeException">if lvl is out of range.</exception> public Deflater(int level, bool noHeaderOrFooter) { if (level == DEFAULT_COMPRESSION) { level = 6; } else if (level < NO_COMPRESSION || level > BEST_COMPRESSION) { throw new ArgumentOutOfRangeException("level"); } pending = new DeflaterPending(); engine = new DeflaterEngine(pending); this.noHeaderOrFooter = noHeaderOrFooter; SetStrategy(DeflateStrategy.Default); SetLevel(level); Reset(); } /// <summary> /// Resets the deflater. The deflater acts afterwards as if it was /// just created with the same compression level and strategy as it /// had before. /// </summary> public void Reset() { state = (noHeaderOrFooter ? BUSY_STATE : INIT_STATE); totalOut = 0; pending.Reset(); engine.Reset(); } /// <summary> /// Gets the current adler checksum of the data that was processed so far. /// </summary> public int Adler { get { return engine.Adler; } } /// <summary> /// Gets the number of input bytes processed so far. /// </summary> public int TotalIn { get { return engine.TotalIn; } } /// <summary> /// Gets the number of output bytes so far. /// </summary> public long TotalOut { get { return totalOut; } } /// <summary> /// Flushes the current input block. Further calls to deflate() will /// produce enough output to inflate everything in the current input /// block. This is not part of Sun's JDK so I have made it package /// private. It is used by DeflaterOutputStream to implement /// flush(). /// </summary> public void Flush() { state |= IS_FLUSHING; } /// <summary> /// Finishes the deflater with the current input block. It is an error /// to give more input after this method was called. This method must /// be called to force all bytes to be flushed. /// </summary> public void Finish() { state |= IS_FLUSHING | IS_FINISHING; } /// <summary> /// Returns true if the stream was finished and no more output bytes /// are available. /// </summary> public bool IsFinished { get { return state == FINISHED_STATE && pending.IsFlushed; } } /// <summary> /// Returns true, if the input buffer is empty. /// You should then call setInput(). /// NOTE: This method can also return true when the stream /// was finished. /// </summary> public bool IsNeedingInput { get { return engine.NeedsInput(); } } /// <summary> /// Sets the data which should be compressed next. This should be only /// called when needsInput indicates that more input is needed. /// If you call setInput when needsInput() returns false, the /// previous input that is still pending will be thrown away. /// The given byte array should not be changed, before needsInput() returns /// true again. /// This call is equivalent to <code>setInput(input, 0, input.length)</code>. /// </summary> /// <param name="input"> /// the buffer containing the input data. /// </param> /// <exception cref="System.InvalidOperationException"> /// if the buffer was finished() or ended(). /// </exception> public void SetInput(byte[] input) { SetInput(input, 0, input.Length); } /// <summary> /// Sets the data which should be compressed next. This should be /// only called when needsInput indicates that more input is needed. /// The given byte array should not be changed, before needsInput() returns /// true again. /// </summary> /// <param name="input"> /// the buffer containing the input data. /// </param> /// <param name="off"> /// the start of the data. /// </param> /// <param name="len"> /// the length of the data. /// </param> /// <exception cref="System.InvalidOperationException"> /// if the buffer was finished() or ended() or if previous input is still pending. /// </exception> public void SetInput(byte[] input, int off, int len) { if ((state & IS_FINISHING) != 0) { throw new InvalidOperationException("finish()/end() already called"); } engine.SetInput(input, off, len); } /// <summary> /// Sets the compression level. There is no guarantee of the exact /// position of the change, but if you call this when needsInput is /// true the change of compression level will occur somewhere near /// before the end of the so far given input. /// </summary> /// <param name="lvl"> /// the new compression level. /// </param> public void SetLevel(int lvl) { if (lvl == DEFAULT_COMPRESSION) { lvl = 6; } else if (lvl < NO_COMPRESSION || lvl > BEST_COMPRESSION) { throw new ArgumentOutOfRangeException("lvl"); } if (level != lvl) { level = lvl; engine.SetLevel(lvl); } } /// <summary> /// Get current compression level /// </summary> /// <returns>compression level</returns> public int GetLevel() { return level; } /// <summary> /// Sets the compression strategy. Strategy is one of /// DEFAULT_STRATEGY, HUFFMAN_ONLY and FILTERED. For the exact /// position where the strategy is changed, the same as for /// setLevel() applies. /// </summary> /// <param name="strategy"> /// The new compression strategy. /// </param> public void SetStrategy(DeflateStrategy strategy) { engine.Strategy = strategy; } /// <summary> /// Deflates the current input block with to the given array. /// </summary> /// <param name="output"> /// The buffer where compressed data is stored /// </param> /// <returns> /// The number of compressed bytes added to the output, or 0 if either /// needsInput() or finished() returns true or length is zero. /// </returns> public int Deflate(byte[] output) { return Deflate(output, 0, output.Length); } /// <summary> /// Deflates the current input block to the given array. /// </summary> /// <param name="output"> /// Buffer to store the compressed data. /// </param> /// <param name="offset"> /// Offset into the output array. /// </param> /// <param name="length"> /// The maximum number of bytes that may be stored. /// </param> /// <returns> /// The number of compressed bytes added to the output, or 0 if either /// needsInput() or finished() returns true or length is zero. /// </returns> /// <exception cref="System.InvalidOperationException"> /// If end() was previously called. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// If offset and/or length don't match the array length. /// </exception> public int Deflate(byte[] output, int offset, int length) { int origLength = length; if (state == CLOSED_STATE) { throw new InvalidOperationException("Deflater closed"); } if (state < BUSY_STATE) { /* output header */ int header = (DEFLATED + ((DeflaterConstants.MAX_WBITS - 8) << 4)) << 8; int level_flags = (level - 1) >> 1; if (level_flags < 0 || level_flags > 3) { level_flags = 3; } header |= level_flags << 6; if ((state & IS_SETDICT) != 0) { /* Dictionary was set */ header |= DeflaterConstants.PRESET_DICT; } header += 31 - (header % 31); pending.WriteShortMSB(header); if ((state & IS_SETDICT) != 0) { int chksum = engine.Adler; engine.ResetAdler(); pending.WriteShortMSB(chksum >> 16); pending.WriteShortMSB(chksum & 0xffff); } state = BUSY_STATE | (state & (IS_FLUSHING | IS_FINISHING)); } for (;;) { int count = pending.Flush(output, offset, length); offset += count; totalOut += count; length -= count; if (length == 0 || state == FINISHED_STATE) { break; } if (!engine.Deflate((state & IS_FLUSHING) != 0, (state & IS_FINISHING) != 0)) { if (state == BUSY_STATE) { /* We need more input now */ return origLength - length; } else if (state == FLUSHING_STATE) { if (level != NO_COMPRESSION) { /* We have to supply some lookahead. 8 bit lookahead * is needed by the zlib inflater, and we must fill * the next byte, so that all bits are flushed. */ int neededbits = 8 + ((-pending.BitCount) & 7); while (neededbits > 0) { /* write a static tree block consisting solely of * an EOF: */ pending.WriteBits(2, 10); neededbits -= 10; } } state = BUSY_STATE; } else if (state == FINISHING_STATE) { pending.AlignToByte(); // Compressed data is complete. Write footer information if required. if (!noHeaderOrFooter) { int adler = engine.Adler; pending.WriteShortMSB(adler >> 16); pending.WriteShortMSB(adler & 0xffff); } state = FINISHED_STATE; } } } return origLength - length; } /// <summary> /// Sets the dictionary which should be used in the deflate process. /// This call is equivalent to <code>setDictionary(dict, 0, dict.Length)</code>. /// </summary> /// <param name="dict"> /// the dictionary. /// </param> /// <exception cref="System.InvalidOperationException"> /// if setInput () or deflate () were already called or another dictionary was already set. /// </exception> public void SetDictionary(byte[] dict) { SetDictionary(dict, 0, dict.Length); } /// <summary> /// Sets the dictionary which should be used in the deflate process. /// The dictionary is a byte array containing strings that are /// likely to occur in the data which should be compressed. The /// dictionary is not stored in the compressed output, only a /// checksum. To decompress the output you need to supply the same /// dictionary again. /// </summary> /// <param name="dict"> /// The dictionary data /// </param> /// <param name="offset"> /// An offset into the dictionary. /// </param> /// <param name="length"> /// The length of the dictionary data to use /// </param> /// <exception cref="System.InvalidOperationException"> /// If setInput () or deflate () were already called or another dictionary was already set. /// </exception> public void SetDictionary(byte[] dict, int offset, int length) { if (state != INIT_STATE) { throw new InvalidOperationException(); } state = SETDICT_STATE; engine.SetDictionary(dict, offset, length); } } }
// DialogOptions.cs // Script#/Libraries/jQuery/UI // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Runtime.CompilerServices; namespace jQueryApi.UI.Widgets { /// <summary> /// Options used to initialize or customize Dialog. /// </summary> [ScriptImport] [ScriptIgnoreNamespace] [ScriptName("Object")] public sealed class DialogOptions { public DialogOptions() { } public DialogOptions(params object[] nameValuePairs) { } /// <summary> /// This event is triggered when a dialog attempts to close. If the beforeClose event handler (callback function) returns false, the close will be prevented. /// </summary> [ScriptField] public jQueryUIEventHandler<jQueryObject> BeforeClose { get { return null; } set { } } /// <summary> /// This event is triggered when the dialog is closed. /// </summary> [ScriptField] public jQueryUIEventHandler<jQueryObject> Close { get { return null; } set { } } /// <summary> /// This event is triggered when the dialog is created. /// </summary> [ScriptField] public jQueryEventHandler Create { get { return null; } set { } } /// <summary> /// This event is triggered when the dialog is dragged. /// </summary> [ScriptField] public jQueryUIEventHandler<DialogDragEvent> Drag { get { return null; } set { } } /// <summary> /// This event is triggered at the beginning of the dialog being dragged. /// </summary> [ScriptField] public jQueryUIEventHandler<DialogDragStartEvent> DragStart { get { return null; } set { } } /// <summary> /// This event is triggered after the dialog has been dragged. /// </summary> [ScriptField] public jQueryUIEventHandler<DialogDragStopEvent> DragStop { get { return null; } set { } } /// <summary> /// This event is triggered when the dialog gains focus. /// </summary> [ScriptField] public jQueryUIEventHandler<jQueryObject> Focus { get { return null; } set { } } /// <summary> /// This event is triggered when dialog is opened. /// </summary> [ScriptField] public jQueryUIEventHandler<jQueryObject> Open { get { return null; } set { } } /// <summary> /// This event is triggered when the dialog is resized. /// </summary> [ScriptField] public jQueryUIEventHandler<DialogResizeEvent> Resize { get { return null; } set { } } /// <summary> /// This event is triggered at the beginning of the dialog being resized. /// </summary> [ScriptField] public jQueryUIEventHandler<DialogResizeStartEvent> ResizeStart { get { return null; } set { } } /// <summary> /// This event is triggered after the dialog has been resized. /// </summary> [ScriptField] public jQueryUIEventHandler<DialogResizeStopEvent> ResizeStop { get { return null; } set { } } /// <summary> /// When ''autoOpen'' is ''true'' the dialog will open automatically when ''dialog'' is called. If ''false'' it will stay hidden until ''.dialog("open")'' is called on it. /// </summary> [ScriptField] public bool AutoOpen { get { return false; } set { } } /// <summary> /// Specifies which buttons should be displayed on the dialog. Each element of the array must be an Object defining the properties to set on the button. /// </summary> [ScriptField] public Array Buttons { get { return null; } set { } } /// <summary> /// Specifies whether the dialog should close when it has focus and the user presses the esacpe (ESC) key. /// </summary> [ScriptField] public bool CloseOnEscape { get { return false; } set { } } /// <summary> /// Specifies the text for the close button. Note that the close text is visibly hidden when using a standard theme. /// </summary> [ScriptField] public string CloseText { get { return null; } set { } } /// <summary> /// The specified class name(s) will be added to the dialog, for additional theming. /// </summary> [ScriptField] public string DialogClass { get { return null; } set { } } /// <summary> /// Disables the dialog if set to true. /// </summary> [ScriptField] public bool Disabled { get { return false; } set { } } /// <summary> /// If set to true, the dialog will be draggable by the titlebar. /// </summary> [ScriptField] public bool Draggable { get { return false; } set { } } /// <summary> /// The height of the dialog, in pixels. Specifying 'auto' is also supported to make the dialog adjust based on its content. /// </summary> [ScriptField] public int Height { get { return 0; } set { } } /// <summary> /// The effect to be used when the dialog is closed. /// </summary> [ScriptField] public object Hide { get { return null; } set { } } /// <summary> /// The maximum height to which the dialog can be resized, in pixels. /// </summary> [ScriptField] public int MaxHeight { get { return 0; } set { } } /// <summary> /// The maximum width to which the dialog can be resized, in pixels. /// </summary> [ScriptField] public int MaxWidth { get { return 0; } set { } } /// <summary> /// The minimum height to which the dialog can be resized, in pixels. /// </summary> [ScriptField] public int MinHeight { get { return 0; } set { } } /// <summary> /// The minimum width to which the dialog can be resized, in pixels. /// </summary> [ScriptField] public int MinWidth { get { return 0; } set { } } /// <summary> /// If set to true, the dialog will have modal behavior; other items on the page will be disabled (i.e. cannot be interacted with). Modal dialogs create an overlay below the dialog but above other page elements. /// </summary> [ScriptField] public bool Modal { get { return false; } set { } } /// <summary> /// Specifies where the dialog should be displayed. Possible values: <br />1) a single string representing position within viewport: 'center', 'left', 'right', 'top', 'bottom'. <br />2) an array containing an <em>x,y</em> coordinate pair in pixel offset from left, top corner of viewport (e.g. [350,100]) <br />3) an array containing <em>x,y</em> position string values (e.g. ['right','top'] for top right corner). /// </summary> [ScriptField] public object Position { get { return null; } set { } } /// <summary> /// If set to true, the dialog will be resizable. /// </summary> [ScriptField] public bool Resizable { get { return false; } set { } } /// <summary> /// The effect to be used when the dialog is opened. /// </summary> [ScriptField] public object Show { get { return null; } set { } } /// <summary> /// Specifies whether the dialog will stack on top of other dialogs. This will cause the dialog to move to the front of other dialogs when it gains focus. /// </summary> [ScriptField] public bool Stack { get { return false; } set { } } /// <summary> /// Specifies the title of the dialog. Any valid HTML may be set as the title. The title can also be specified by the title attribute on the dialog source element. /// </summary> [ScriptField] public string Title { get { return null; } set { } } /// <summary> /// The width of the dialog, in pixels. /// </summary> [ScriptField] public int Width { get { return 0; } set { } } /// <summary> /// The starting z-index for the dialog. /// </summary> [ScriptField] public int ZIndex { get { return 0; } set { } } } }
#pragma warning disable IDE1006 using System.Globalization; using Anemonis.Resources; using Microsoft.VisualStudio.TestTools.UnitTesting; using Newtonsoft.Json.Linq; namespace Anemonis.RandomOrg.UnitTests; public partial class RandomOrgClientTests { [DataTestMethod] [DataRow(00000, +0000000000, +0000000005)] [DataRow(10001, +0000000000, +0000000005)] [DataRow(00001, -1000000001, +0000000005)] [DataRow(00001, +1000000001, +0000000005)] [DataRow(00001, +0000000000, -1000000001)] [DataRow(00001, +0000000000, +1000000001)] public async Task GenerateSignedIntegersWithInvalidParameter(int count, int minimum, int maximum) { var joreq = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_int_req.json")); using (var client = new RandomOrgClient(joreq["params"]["apiKey"].ToString(), CreateEmptyHttpInvoker())) { await Assert.ThrowsExceptionAsync<ArgumentOutOfRangeException>(() => client.GenerateSignedIntegersAsync(count, minimum, maximum, false)); } } [TestMethod] public async Task GenerateSignedIntegersWithInvalidUserData() { var joreq = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_int_req.json")); var userData = CreateTestString(1001); using (var client = new RandomOrgClient(joreq["params"]["apiKey"].ToString(), CreateEmptyHttpInvoker())) { await Assert.ThrowsExceptionAsync<ArgumentException>(() => client.GenerateSignedIntegersAsync(1, 1, 1, false, userData)); } } [TestMethod] public async Task GenerateSignedIntegers() { var joreq = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_int_req.json")); var jores = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_int_res.json")); var joparams = joreq["params"]; var jorandom = jores["result"]["random"]; using (var client = new RandomOrgClient(joparams["apiKey"].ToString(), CreateHttpInvoker(joreq, jores))) { var result = await client.GenerateSignedIntegersAsync( joparams["n"].ToObject<int>(), joparams["min"].ToObject<int>(), joparams["max"].ToObject<int>(), joparams["replacement"].ToObject<bool>(), joparams["userData"].ToObject<string>()); VerifyResult(result, jores); Assert.AreEqual(jorandom["n"].ToObject<int>(), result.Random.Data.Count); CollectionAssert.AreEqual(jorandom["data"].ToObject<int[]>(), result.Random.Data?.ToArray()); Assert.AreEqual(jorandom["min"].ToObject<int>(), result.Random.Parameters.Minimum); Assert.AreEqual(jorandom["max"].ToObject<int>(), result.Random.Parameters.Maximum); Assert.AreEqual(jorandom["replacement"].ToObject<bool>(), result.Random.Parameters.Replacement); Assert.AreEqual(jorandom["userData"].ToObject<string>(), result.Random.UserData); } } [DataTestMethod] [DataRow(00000, +0000000000, +0000000005)] [DataRow(10001, +0000000000, +0000000005)] [DataRow(00001, -1000000001, +0000000005)] [DataRow(00001, +1000000001, +0000000005)] [DataRow(00001, +0000000000, -1000000001)] [DataRow(00001, +0000000000, +1000000001)] public async Task GenerateSignedIntegerSequencesWithInvalidParameter(int count, int minimum, int maximum) { var joreq = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_bas_seq_req.json")); var counts = new[] { count }; var minimums = new[] { minimum }; var maximums = new[] { maximum }; var replacements = new[] { false }; using (var client = new RandomOrgClient(joreq["params"]["apiKey"].ToString(), CreateEmptyHttpInvoker())) { await Assert.ThrowsExceptionAsync<ArgumentOutOfRangeException>(() => client.GenerateSignedIntegerSequencesAsync(counts, minimums, maximums, replacements)); } } [TestMethod] public async Task GenerateSignedIntegerSequencesWithInvalidUserData() { var joreq = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_bas_seq_req.json")); var counts = new[] { 1 }; var minimums = new[] { 1 }; var maximums = new[] { 1 }; var replacements = new[] { false }; var userData = CreateTestString(1001); using (var client = new RandomOrgClient(joreq["params"]["apiKey"].ToString(), CreateEmptyHttpInvoker())) { await Assert.ThrowsExceptionAsync<ArgumentException>(() => client.GenerateSignedIntegerSequencesAsync(counts, minimums, maximums, replacements, userData)); } } [DataTestMethod] [DataRow(0000)] [DataRow(1001)] public async Task GenerateSignedIntegerSequencesWithInvalidCount(int sequencesCount) { var joreq = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_bas_seq_req.json")); var counts = new int[sequencesCount]; var minimums = new int[sequencesCount]; var maximums = new int[sequencesCount]; var replacements = new bool[sequencesCount]; for (var i = 0; i < sequencesCount; i++) { counts[i] = 1; minimums[i] = 1; maximums[i] = 5; replacements[i] = false; } using (var client = new RandomOrgClient(joreq["params"]["apiKey"].ToString(), CreateEmptyHttpInvoker())) { await Assert.ThrowsExceptionAsync<ArgumentException>(() => client.GenerateSignedIntegerSequencesAsync(counts, minimums, maximums, replacements)); } } [TestMethod] public async Task GenerateSignedIntegerSequences() { var joreq = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_seq_req.json")); var jores = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_seq_res.json")); var joparams = joreq["params"]; var jorandom = jores["result"]["random"]; using (var client = new RandomOrgClient(joparams["apiKey"].ToString(), CreateHttpInvoker(joreq, jores))) { var result = await client.GenerateSignedIntegerSequencesAsync( joparams["length"].ToObject<int[]>(), joparams["min"].ToObject<int[]>(), joparams["max"].ToObject<int[]>(), joparams["replacement"].ToObject<bool[]>(), joparams["userData"].ToObject<string>()); VerifyResult(result, jores); Assert.AreEqual(jorandom["n"].ToObject<int>(), result.Random.Data.Count); CollectionAssert.AreEqual(jorandom["length"].ToObject<int[]>(), result.Random.Data.Select(s => s.Count).ToArray()); var jodata = (JArray)jorandom["data"]; for (var i = 0; i < result.Random.Data.Count; i++) { CollectionAssert.AreEqual(jodata[i].ToObject<int[]>(), result.Random.Data[i]?.ToArray()); } CollectionAssert.AreEqual(jorandom["min"].ToObject<int[]>(), result.Random.Parameters.Minimums?.ToArray()); CollectionAssert.AreEqual(jorandom["max"].ToObject<int[]>(), result.Random.Parameters.Maximums?.ToArray()); CollectionAssert.AreEqual(jorandom["replacement"].ToObject<bool[]>(), result.Random.Parameters.Replacements?.ToArray()); Assert.AreEqual(jorandom["userData"].ToObject<string>(), result.Random.UserData); } } [DataTestMethod] [DataRow(00000, 02)] [DataRow(10001, 02)] [DataRow(00001, 00)] [DataRow(00001, 21)] public async Task GenerateSignedDecimalFractionsWithInvalidParameter(int count, int decimalPlaces) { var joreq = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_dfr_req.json")); using (var client = new RandomOrgClient(joreq["params"]["apiKey"].ToString(), CreateEmptyHttpInvoker())) { await Assert.ThrowsExceptionAsync<ArgumentOutOfRangeException>(() => client.GenerateSignedDecimalFractionsAsync(count, decimalPlaces, false)); } } [TestMethod] public async Task GenerateSignedDecimalFractionsWithInvalidUserData() { var joreq = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_dfr_req.json")); var userData = CreateTestString(1001); using (var client = new RandomOrgClient(joreq["params"]["apiKey"].ToString(), CreateEmptyHttpInvoker())) { await Assert.ThrowsExceptionAsync<ArgumentException>(() => client.GenerateSignedDecimalFractionsAsync(1, 1, false, userData)); } } [TestMethod] public async Task GenerateSignedDecimalFractions() { var joreq = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_dfr_req.json")); var jores = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_dfr_res.json")); var joparams = joreq["params"]; var jorandom = jores["result"]["random"]; using (var client = new RandomOrgClient(joparams["apiKey"].ToString(), CreateHttpInvoker(joreq, jores))) { var result = await client.GenerateSignedDecimalFractionsAsync( joparams["n"].ToObject<int>(), joparams["decimalPlaces"].ToObject<int>(), joparams["replacement"].ToObject<bool>(), joparams["userData"].ToObject<string>()); VerifyResult(result, jores); Assert.AreEqual(jorandom["n"].ToObject<int>(), result.Random.Data.Count); CollectionAssert.AreEqual(jorandom["data"].ToObject<decimal[]>(), result.Random.Data?.ToArray()); Assert.AreEqual(jorandom["decimalPlaces"].ToObject<int>(), result.Random.Parameters.DecimalPlaces); Assert.AreEqual(jorandom["replacement"].ToObject<bool>(), result.Random.Parameters.Replacement); Assert.AreEqual(jorandom["userData"].ToObject<string>(), result.Random.UserData); } } [DataTestMethod] [DataRow(00000, "+0000000.0", "+0000000.0", 02)] [DataRow(10001, "+0000000.0", "+0000000.0", 02)] [DataRow(00001, "-1000001.0", "+0000000.0", 02)] [DataRow(00001, "+1000001.0", "+0000000.0", 02)] [DataRow(00001, "+0000000.0", "-1000001.0", 02)] [DataRow(00001, "+0000000.0", "+1000001.0", 02)] [DataRow(00001, "+0000000.0", "+0000000.0", 01)] [DataRow(00001, "+0000000.0", "+0000000.0", 21)] public async Task GenerateSignedGaussiansWithInvalidParameter(int count, string mean, string standardDeviation, int significantDigits) { var joreq = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_gss_req.json")); using (var client = new RandomOrgClient(joreq["params"]["apiKey"].ToString(), CreateEmptyHttpInvoker())) { var meanValue = decimal.Parse(mean, CultureInfo.InvariantCulture); var standardDeviationValue = decimal.Parse(standardDeviation, CultureInfo.InvariantCulture); await Assert.ThrowsExceptionAsync<ArgumentOutOfRangeException>(() => client.GenerateSignedGaussiansAsync(count, meanValue, standardDeviationValue, significantDigits)); } } [TestMethod] public async Task GenerateSignedGaussiansWithInvalidUserData() { var joreq = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_gss_req.json")); var userData = CreateTestString(1001); using (var client = new RandomOrgClient(joreq["params"]["apiKey"].ToString(), CreateEmptyHttpInvoker())) { await Assert.ThrowsExceptionAsync<ArgumentException>(() => client.GenerateSignedGaussiansAsync(1, 0M, 0M, 2, userData)); } } [TestMethod] public async Task GenerateSignedGaussians() { var joreq = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_gss_req.json")); var jores = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_gss_res.json")); var joparams = joreq["params"]; var jorandom = jores["result"]["random"]; using (var client = new RandomOrgClient(joparams["apiKey"].ToString(), CreateHttpInvoker(joreq, jores))) { var result = await client.GenerateSignedGaussiansAsync( joparams["n"].ToObject<int>(), joparams["mean"].ToObject<decimal>(), joparams["standardDeviation"].ToObject<decimal>(), joparams["significantDigits"].ToObject<int>(), joparams["userData"].ToObject<string>()); VerifyResult(result, jores); Assert.AreEqual(jorandom["n"].ToObject<int>(), result.Random.Data.Count); CollectionAssert.AreEqual(jorandom["data"].ToObject<decimal[]>(), result.Random.Data?.ToArray()); Assert.AreEqual(jorandom["mean"].ToObject<decimal>(), result.Random.Parameters.Mean); Assert.AreEqual(jorandom["standardDeviation"].ToObject<decimal>(), result.Random.Parameters.StandardDeviation); Assert.AreEqual(jorandom["significantDigits"].ToObject<int>(), result.Random.Parameters.SignificantDigits); Assert.AreEqual(jorandom["userData"].ToObject<string>(), result.Random.UserData); } } [DataTestMethod] [DataRow(00000, 01)] [DataRow(10001, 01)] [DataRow(00001, 00)] [DataRow(00001, 21)] public async Task GenerateSignedStringsWithInvalidParameter(int count, int length) { var joreq = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_str_req.json")); var characters = CreateTestString(1); using (var client = new RandomOrgClient(joreq["params"]["apiKey"].ToString(), CreateEmptyHttpInvoker())) { await Assert.ThrowsExceptionAsync<ArgumentOutOfRangeException>(() => client.GenerateSignedStringsAsync(count, length, characters, false)); } } [DataTestMethod] [DataRow(00)] [DataRow(81)] public async Task GenerateSignedStringsWithInvalidCharactersCount(int charactersCount) { var joreq = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_str_req.json")); var characters = CreateTestString(charactersCount); using (var client = new RandomOrgClient(joreq["params"]["apiKey"].ToString(), CreateEmptyHttpInvoker())) { await Assert.ThrowsExceptionAsync<ArgumentException>(() => client.GenerateSignedStringsAsync(1, 1, characters, false)); } } [TestMethod] public async Task GenerateSignedStringsWithCharactersIsNull() { var joreq = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_str_req.json")); using (var client = new RandomOrgClient(joreq["params"]["apiKey"].ToString(), CreateEmptyHttpInvoker())) { await Assert.ThrowsExceptionAsync<ArgumentNullException>(() => client.GenerateSignedStringsAsync(1, 1, null, false)); } } [TestMethod] public async Task GenerateSignedStringsWithInvalidUserData() { var joreq = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_str_req.json")); var characters = CreateTestString(1); var userData = CreateTestString(1001); using (var client = new RandomOrgClient(joreq["params"]["apiKey"].ToString(), CreateEmptyHttpInvoker())) { await Assert.ThrowsExceptionAsync<ArgumentException>(() => client.GenerateSignedStringsAsync(1, 1, characters, false, userData)); } } [TestMethod] public async Task GenerateSignedStrings() { var joreq = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_str_req.json")); var jores = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_str_res.json")); var joparams = joreq["params"]; var jorandom = jores["result"]["random"]; using (var client = new RandomOrgClient(joparams["apiKey"].ToString(), CreateHttpInvoker(joreq, jores))) { var result = await client.GenerateSignedStringsAsync( joparams["n"].ToObject<int>(), joparams["length"].ToObject<int>(), joparams["characters"].ToObject<string>(), joparams["replacement"].ToObject<bool>(), joparams["userData"].ToObject<string>()); VerifyResult(result, jores); Assert.AreEqual(jorandom["n"].ToObject<int>(), result.Random.Data.Count); CollectionAssert.AreEqual(jorandom["data"].ToObject<string[]>(), result.Random.Data?.ToArray()); Assert.AreEqual(jorandom["length"].ToObject<int>(), result.Random.Parameters.Length); Assert.AreEqual(jorandom["characters"].ToObject<string>(), result.Random.Parameters.Characters); Assert.AreEqual(jorandom["replacement"].ToObject<bool>(), result.Random.Parameters.Replacement); Assert.AreEqual(jorandom["userData"].ToObject<string>(), result.Random.UserData); } } [DataTestMethod] [DataRow(0000)] [DataRow(1001)] public async Task GenerateSignedUuidsWithInvalidParameter(int count) { var joreq = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_uid_req.json")); using (var client = new RandomOrgClient(joreq["params"]["apiKey"].ToString(), CreateEmptyHttpInvoker())) { await Assert.ThrowsExceptionAsync<ArgumentOutOfRangeException>(() => client.GenerateSignedUuidsAsync(count)); } } [TestMethod] public async Task GenerateSignedUuidsWithInvalidUserData() { var joreq = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_uid_req.json")); var userData = CreateTestString(1001); using (var client = new RandomOrgClient(joreq["params"]["apiKey"].ToString(), CreateEmptyHttpInvoker())) { await Assert.ThrowsExceptionAsync<ArgumentException>(() => client.GenerateSignedUuidsAsync(1, userData)); } } [TestMethod] public async Task GenerateSignedUuids() { var joreq = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_uid_req.json")); var jores = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_uid_res.json")); var joparams = joreq["params"]; var jorandom = jores["result"]["random"]; using (var client = new RandomOrgClient(joparams["apiKey"].ToString(), CreateHttpInvoker(joreq, jores))) { var result = await client.GenerateSignedUuidsAsync( joparams["n"].ToObject<int>(), joparams["userData"].ToObject<string>()); VerifyResult(result, jores); Assert.AreEqual(jorandom["n"].ToObject<int>(), result.Random.Data.Count); CollectionAssert.AreEqual(jorandom["data"].ToObject<Guid[]>(), result.Random.Data?.ToArray()); Assert.AreEqual(jorandom["userData"].ToObject<string>(), result.Random.UserData); } } [DataTestMethod] [DataRow(000, 000001)] [DataRow(101, 000001)] [DataRow(001, 000000)] [DataRow(001, 131073)] [DataRow(002, 131072)] public async Task GenerateSignedBlobsWithInvalidParameter(int count, int size) { var joreq = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_blb_req.json")); using (var client = new RandomOrgClient(joreq["params"]["apiKey"].ToString(), CreateEmptyHttpInvoker())) { await Assert.ThrowsExceptionAsync<ArgumentOutOfRangeException>(() => client.GenerateSignedBlobsAsync(count, size)); } } [TestMethod] public async Task GenerateSignedBlobsWithInvalidUserData() { var joreq = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_blb_req.json")); var userData = CreateTestString(1001); using (var client = new RandomOrgClient(joreq["params"]["apiKey"].ToString(), CreateEmptyHttpInvoker())) { await Assert.ThrowsExceptionAsync<ArgumentException>(() => client.GenerateSignedBlobsAsync(1, 1, userData)); } } [TestMethod] public async Task GenerateSignedBlobs() { var joreq = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_blb_req.json")); var jores = JObject.Parse(EmbeddedResourceManager.GetString("Assets.gen_sig_blb_res.json")); var joparams = joreq["params"]; var jorandom = jores["result"]["random"]; using (var client = new RandomOrgClient(joparams["apiKey"].ToString(), CreateHttpInvoker(joreq, jores))) { var result = await client.GenerateSignedBlobsAsync( joparams["n"].ToObject<int>(), joparams["size"].ToObject<int>() / 8, joparams["userData"].ToObject<string>()); VerifyResult(result, jores); Assert.AreEqual(jorandom["n"].ToObject<int>(), result.Random.Data.Count); var jodata = (JArray)jorandom["data"]; for (var i = 0; i < jodata.Count; i++) { CollectionAssert.AreEqual(Convert.FromBase64String(jodata[i].ToObject<string>()), result.Random.Data[i]); } Assert.AreEqual(jorandom["size"].ToObject<int>(), result.Random.Parameters.Size * 8); Assert.AreEqual(jorandom["userData"].ToObject<string>(), result.Random.UserData); } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion [assembly: Elmah.Scc("$Id$")] namespace Elmah { #region Imports using System; using System.Globalization; using System.IO; using System.Xml; #endregion /// <summary> /// Represents a writer that provides a fast, non-cached, forward-only /// way of generating streams or files containing JSON Text according /// to the grammar rules laid out in /// <a href="http://www.ietf.org/rfc/rfc4627.txt">RFC 4627</a>. /// </summary> /// <remarks> /// This class supports ELMAH and is not intended to be used directly /// from your code. It may be modified or removed in the future without /// notice. It has public accessibility for testing purposes. If you /// need a general-purpose JSON Text encoder, consult /// <a href="http://www.json.org/">JSON.org</a> for implementations /// or use classes available from the Microsoft .NET Framework. /// </remarks> public sealed class JsonTextWriter { private readonly TextWriter _writer; private readonly int[] _counters; private readonly char[] _terminators; private int _depth; private string _memberName; public JsonTextWriter(TextWriter writer) { Debug.Assert(writer != null); _writer = writer; const int levels = 10 + /* root */ 1; _counters = new int[levels]; _terminators = new char[levels]; } public int Depth { get { return _depth; } } private int ItemCount { get { return _counters[Depth]; } set { _counters[Depth] = value; } } private char Terminator { get { return _terminators[Depth]; } set { _terminators[Depth] = value; } } public JsonTextWriter Object() { return StartStructured("{", "}"); } public JsonTextWriter EndObject() { return Pop(); } public JsonTextWriter Array() { return StartStructured("[", "]"); } public JsonTextWriter EndArray() { return Pop(); } public JsonTextWriter Pop() { return EndStructured(); } public JsonTextWriter Member(string name) { if (name == null) throw new ArgumentNullException("name"); if (name.Length == 0) throw new ArgumentException(null, "name"); if (_memberName != null) throw new InvalidOperationException("Missing member value."); _memberName = name; return this; } private JsonTextWriter Write(string text) { return WriteImpl(text, /* raw */ false); } private JsonTextWriter WriteEnquoted(string text) { return WriteImpl(text, /* raw */ true); } private JsonTextWriter WriteImpl(string text, bool raw) { Debug.Assert(raw || (text != null && text.Length > 0)); if (Depth == 0 && (text.Length > 1 || (text[0] != '{' && text[0] != '['))) throw new InvalidOperationException(); TextWriter writer = _writer; if (ItemCount > 0) writer.Write(','); string name = _memberName; _memberName = null; if (name != null) { writer.Write(' '); Enquote(name, writer); writer.Write(':'); } if (Depth > 0) writer.Write(' '); if (raw) Enquote(text, writer); else writer.Write(text); ItemCount = ItemCount + 1; return this; } public JsonTextWriter Number(int value) { return Write(value.ToString(CultureInfo.InvariantCulture)); } public JsonTextWriter String(string str) { return str == null ? Null() : WriteEnquoted(str); } public JsonTextWriter Null() { return Write("null"); } public JsonTextWriter Boolean(bool value) { return Write(value ? "true" : "false"); } private static readonly DateTime _epoch = /* ... */ #if NET_1_0 || NET_1_1 /* ... */ new DateTime(1970, 1, 1, 0, 0, 0); #else /* ... */ new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); #endif public JsonTextWriter Number(DateTime time) { double seconds = time.ToUniversalTime().Subtract(_epoch).TotalSeconds; return Write(seconds.ToString(CultureInfo.InvariantCulture)); } public JsonTextWriter String(DateTime time) { string xmlTime; #if NET_1_0 || NET_1_1 xmlTime = XmlConvert.ToString(time); #else xmlTime = XmlConvert.ToString(time, XmlDateTimeSerializationMode.Utc); #endif return String(xmlTime); } private JsonTextWriter StartStructured(string start, string end) { if (Depth + 1 == _counters.Length) throw new Exception(); Write(start); _depth++; Terminator = end[0]; return this; } private JsonTextWriter EndStructured() { if (Depth - 1 < 0) throw new Exception(); _writer.Write(' '); _writer.Write(Terminator); ItemCount = 0; _depth--; return this; } private static void Enquote(string s, TextWriter writer) { Debug.Assert(writer != null); int length = Mask.NullString(s).Length; writer.Write('"'); char last; char ch = '\0'; for (int index = 0; index < length; index++) { last = ch; ch = s[index]; switch (ch) { case '\\': case '"': { writer.Write('\\'); writer.Write(ch); break; } case '/': { if (last == '<') writer.Write('\\'); writer.Write(ch); break; } case '\b': writer.Write("\\b"); break; case '\t': writer.Write("\\t"); break; case '\n': writer.Write("\\n"); break; case '\f': writer.Write("\\f"); break; case '\r': writer.Write("\\r"); break; default: { if (ch < ' ') { writer.Write("\\u"); writer.Write(((int)ch).ToString("x4", CultureInfo.InvariantCulture)); } else { writer.Write(ch); } break; } } } writer.Write('"'); } } }
// 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.Reflection; using System.Collections.Generic; namespace Microsoft.Build.BuildEngine.Shared { /// <summary> /// This class is used to load types from their assemblies. /// </summary> /// <owner>SumedhK</owner> internal class TypeLoader { private Dictionary<AssemblyLoadInfo, List<Type>> cacheOfAllDesiredTypesInAnAssembly = new Dictionary<AssemblyLoadInfo, List<Type>>(); private TypeFilter isDesiredType; /// <summary> /// Constructor. /// </summary> /// <param name="isDesiredType"></param> /// <owner>RGoel</owner> internal TypeLoader(TypeFilter isDesiredType) { ErrorUtilities.VerifyThrow(isDesiredType != null, "need a type filter"); this.isDesiredType = isDesiredType; } /// <summary> /// Loads the specified type if it exists in the given assembly. If the type name is fully qualified, then a match (if /// any) is unambiguous; otherwise, if there are multiple types with the same name in different namespaces, the first type /// found will be returned. /// </summary> /// <remarks>This method throws exceptions -- it is the responsibility of the caller to handle them.</remarks> /// <owner>SumedhK</owner> /// <param name="typeName">Can be empty string.</param> /// <param name="assembly"></param> /// <returns>The loaded type, or null if the type was not found.</returns> internal LoadedType Load ( string typeName, AssemblyLoadInfo assembly ) { Type type = null; // Maybe we've already cracked open this assembly before. If so, just grab the list // of public desired types that we found last time. List<Type> desiredTypesInAssembly; cacheOfAllDesiredTypesInAnAssembly.TryGetValue(assembly, out desiredTypesInAssembly); // If we have the assembly name (strong or weak), and we haven't cracked this assembly open // before to discover all the public desired types. if ((assembly.AssemblyName != null) && (typeName.Length > 0) && (desiredTypesInAssembly == null)) { try { // try to load the type using its assembly qualified name type = Type.GetType(typeName + "," + assembly.AssemblyName, false /* don't throw on error */, true /* case-insensitive */); } catch (ArgumentException) { // Type.GetType() will throw this exception if the type name is invalid -- but we have no idea if it's the // type or the assembly name that's the problem -- so just ignore the exception, because we're going to // check the existence/validity of the assembly and type respectively, below anyway } } // if we found the type, it means its assembly qualified name was also its fully qualified name if (type != null) { // if it's not the right type, bail out -- there's no point searching further since we already matched on the // fully qualified name if (!isDesiredType(type, null)) { return null; } } // if the type name was not fully qualified, or if we only have the assembly file/path else { if (desiredTypesInAssembly == null) { // we need to search the assembly for the type... Assembly loadedAssembly; try { if (assembly.AssemblyName != null) { loadedAssembly = Assembly.Load(assembly.AssemblyName); } else { loadedAssembly = Assembly.UnsafeLoadFrom(assembly.AssemblyFile); } } // Assembly.Load() and Assembly.LoadFrom() will throw an ArgumentException if the assembly name is invalid catch (ArgumentException e) { // convert to a FileNotFoundException because it's more meaningful // NOTE: don't use ErrorUtilities.VerifyThrowFileExists() here because that will hit the disk again throw new FileNotFoundException(null, assembly.ToString(), e); } // only look at public types Type[] allPublicTypesInAssembly = loadedAssembly.GetExportedTypes(); desiredTypesInAssembly = new List<Type>(); foreach (Type publicType in allPublicTypesInAssembly) { if (isDesiredType(publicType, null)) { desiredTypesInAssembly.Add(publicType); } } // Save the list of desired types into our cache, so that we don't have to crack it // open again. cacheOfAllDesiredTypesInAnAssembly[assembly] = desiredTypesInAssembly; } foreach (Type desiredTypeInAssembly in desiredTypesInAssembly) { // if type matches partially on its name if ((typeName.Length == 0) || IsPartialTypeNameMatch(desiredTypeInAssembly.FullName, typeName)) { type = desiredTypeInAssembly; break; } } } if (type != null) { return new LoadedType(type, assembly); } return null; } /// <summary> /// Given two type names, looks for a partial match between them. A partial match is considered valid only if it occurs on /// the right side (tail end) of the name strings, and at the start of a class or namespace name. /// </summary> /// <remarks> /// 1) Matches are case-insensitive. /// 2) .NET conventions regarding namespaces and nested classes are respected, including escaping of reserved characters. /// </remarks> /// <example> /// "Csc" and "csc" ==> exact match /// "Microsoft.Build.Tasks.Csc" and "Microsoft.Build.Tasks.Csc" ==> exact match /// "Microsoft.Build.Tasks.Csc" and "Csc" ==> partial match /// "Microsoft.Build.Tasks.Csc" and "Tasks.Csc" ==> partial match /// "MyTasks.ATask+NestedTask" and "NestedTask" ==> partial match /// "MyTasks.ATask\\+NestedTask" and "NestedTask" ==> partial match /// "MyTasks.CscTask" and "Csc" ==> no match /// "MyTasks.MyCsc" and "Csc" ==> no match /// "MyTasks.ATask\.Csc" and "Csc" ==> no match /// "MyTasks.ATask\\\.Csc" and "Csc" ==> no match /// </example> /// <owner>SumedhK</owner> /// <param name="typeName1"></param> /// <param name="typeName2"></param> /// <returns>true, if the type names match exactly or partially; false, if there is no match at all</returns> internal static bool IsPartialTypeNameMatch(string typeName1, string typeName2) { bool isPartialMatch = false; // if the type names are the same length, a partial match is impossible if (typeName1.Length != typeName2.Length) { string longerTypeName; string shorterTypeName; // figure out which type name is longer if (typeName1.Length > typeName2.Length) { longerTypeName = typeName1; shorterTypeName = typeName2; } else { longerTypeName = typeName2; shorterTypeName = typeName1; } // if the shorter type name matches the end of the longer one if (longerTypeName.EndsWith(shorterTypeName, StringComparison.OrdinalIgnoreCase)) { int matchIndex = longerTypeName.Length - shorterTypeName.Length; // if the matched sub-string looks like the start of a namespace or class name if ((longerTypeName[matchIndex - 1] == '.') || (longerTypeName[matchIndex - 1] == '+')) { int precedingBackslashes = 0; // confirm there are zero, or an even number of \'s preceding it... for (int i = matchIndex - 2; i >= 0; i--) { if (longerTypeName[i] == '\\') { precedingBackslashes++; } else { break; } } if ((precedingBackslashes % 2) == 0) { isPartialMatch = true; } } } } // check if the type names match exactly else { isPartialMatch = (String.Equals(typeName1, typeName2, StringComparison.OrdinalIgnoreCase)); } return isPartialMatch; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Places.API.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Net; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.Rest.Azure; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Xunit; using ResourceIdentityType = Microsoft.Azure.Management.ResourceManager.Models.ResourceIdentityType; using NM = Microsoft.Azure.Management.Network.Models; namespace Compute.Tests.DiskRPTests { public class DiskRPTestsBase : VMTestBase { protected const string DiskNamePrefix = "diskrp"; private string DiskRPLocation = ComputeManagementTestUtilities.DefaultLocation.ToLower(); #region Execution protected void Disk_CRUD_Execute(string diskCreateOption, string methodName, int? diskSizeGB = null, string location = null, IList<string> zones = null) { using (MockContext context = MockContext.Start(this.GetType(), methodName)) { EnsureClientsInitialized(context); DiskRPLocation = location ?? DiskRPLocation; // Data var rgName = TestUtilities.GenerateName(TestPrefix); var diskName = TestUtilities.GenerateName(DiskNamePrefix); Disk disk = GenerateDefaultDisk(diskCreateOption, rgName, diskSizeGB, zones, location); try { // ********** // SETUP // ********** // Create resource group, unless create option is import in which case resource group will be created with vm, // or copy in which casethe resource group will be created with the original disk. if (diskCreateOption != DiskCreateOption.Import && diskCreateOption != DiskCreateOption.Copy) { m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = DiskRPLocation }); } // ********** // TEST // ********** // Put Disk diskOut = m_CrpClient.Disks.CreateOrUpdate(rgName, diskName, disk); Validate(disk, diskOut, DiskRPLocation); // Get diskOut = m_CrpClient.Disks.Get(rgName, diskName); Validate(disk, diskOut, DiskRPLocation); // Get disk access AccessUri accessUri = m_CrpClient.Disks.GrantAccess(rgName, diskName, AccessDataDefault); Assert.NotNull(accessUri.AccessSAS); // Get diskOut = m_CrpClient.Disks.Get(rgName, diskName); Validate(disk, diskOut, DiskRPLocation); // Patch // TODO: Bug 9865640 - DiskRP doesn't follow patch semantics for zones: skip this for zones if (zones == null) { const string tagKey = "tageKey"; var updatedisk = new DiskUpdate(); updatedisk.Tags = new Dictionary<string, string>() { { tagKey, "tagvalue" } }; diskOut = m_CrpClient.Disks.Update(rgName, diskName, updatedisk); Validate(disk, diskOut, DiskRPLocation); } // Get diskOut = m_CrpClient.Disks.Get(rgName, diskName); Validate(disk, diskOut, DiskRPLocation); // End disk access m_CrpClient.Disks.RevokeAccess(rgName, diskName); // Delete m_CrpClient.Disks.Delete(rgName, diskName); try { // Ensure it was really deleted m_CrpClient.Disks.Get(rgName, diskName); Assert.False(true); } catch(CloudException ex) { Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode); } } finally { // Delete resource group m_ResourcesClient.ResourceGroups.Delete(rgName); } } } protected void PremiumDisk_CRUD_Execute(string diskCreateOption, string methodName, int? diskSizeGB = null, string tier = null, string location = null, IList<string> zones = null) { using (MockContext context = MockContext.Start(this.GetType(), methodName)) { EnsureClientsInitialized(context); DiskRPLocation = location ?? DiskRPLocation; // Data var rgName = TestUtilities.GenerateName(TestPrefix); var diskName = TestUtilities.GenerateName(DiskNamePrefix); Disk disk = GenerateDefaultDisk(diskCreateOption, rgName, diskSizeGB, zones, location); disk.Sku = new DiskSku() { Name = StorageAccountTypes.PremiumLRS }; disk.Tier = tier; try { // ********** // SETUP // ********** // Create resource group, unless create option is import in which case resource group will be created with vm, // or copy in which case the resource group will be created with the original disk. if (diskCreateOption != DiskCreateOption.Import && diskCreateOption != DiskCreateOption.Copy) { m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = DiskRPLocation }); } // ********** // TEST // ********** // Put Disk diskOut = m_CrpClient.Disks.CreateOrUpdate(rgName, diskName, disk); Validate(disk, diskOut, DiskRPLocation); Assert.Equal(tier, diskOut.Tier); // Get diskOut = m_CrpClient.Disks.Get(rgName, diskName); Validate(disk, diskOut, DiskRPLocation); Assert.Equal(tier, diskOut.Tier); // Get disk access AccessUri accessUri = m_CrpClient.Disks.GrantAccess(rgName, diskName, AccessDataDefault); Assert.NotNull(accessUri.AccessSAS); // Get diskOut = m_CrpClient.Disks.Get(rgName, diskName); Validate(disk, diskOut, DiskRPLocation); // Patch // TODO: Bug 9865640 - DiskRP doesn't follow patch semantics for zones: skip this for zones if (zones == null) { const string tagKey = "tageKey"; var updatedisk = new DiskUpdate(); updatedisk.Tags = new Dictionary<string, string>() { { tagKey, "tagvalue" } }; diskOut = m_CrpClient.Disks.Update(rgName, diskName, updatedisk); Validate(disk, diskOut, DiskRPLocation); Assert.Equal(tier, disk.Tier); } // Get diskOut = m_CrpClient.Disks.Get(rgName, diskName); Validate(disk, diskOut, DiskRPLocation); // End disk access m_CrpClient.Disks.RevokeAccess(rgName, diskName); // Delete m_CrpClient.Disks.Delete(rgName, diskName); try { // Ensure it was really deleted m_CrpClient.Disks.Get(rgName, diskName); Assert.False(true); } catch (CloudException ex) { Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode); } } finally { // Delete resource group m_ResourcesClient.ResourceGroups.Delete(rgName); } } } protected void Snapshot_CRUD_Execute(string diskCreateOption, string methodName, int? diskSizeGB = null, string location = null, bool incremental = false) { using (MockContext context = MockContext.Start(this.GetType(), methodName)) { EnsureClientsInitialized(context); DiskRPLocation = location ?? DiskRPLocation; // Data var rgName = TestUtilities.GenerateName(TestPrefix); var diskName = TestUtilities.GenerateName(DiskNamePrefix); var snapshotName = TestUtilities.GenerateName(DiskNamePrefix); Disk sourceDisk = GenerateDefaultDisk(diskCreateOption, rgName, diskSizeGB); try { // ********** // SETUP // ********** // Create resource group m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = DiskRPLocation }); // Put disk Disk diskOut = m_CrpClient.Disks.CreateOrUpdate(rgName, diskName, sourceDisk); Validate(sourceDisk, diskOut, DiskRPLocation); // Generate snapshot using disk info Snapshot snapshot = GenerateDefaultSnapshot(diskOut.Id, incremental: incremental); // ********** // TEST // ********** // Put Snapshot snapshotOut = m_CrpClient.Snapshots.CreateOrUpdate(rgName, snapshotName, snapshot); Validate(snapshot, snapshotOut, incremental: incremental); // Get snapshotOut = m_CrpClient.Snapshots.Get(rgName, snapshotName); Validate(snapshot, snapshotOut, incremental: incremental); // Get access AccessUri accessUri = m_CrpClient.Snapshots.GrantAccess(rgName, snapshotName, AccessDataDefault); Assert.NotNull(accessUri.AccessSAS); // Get snapshotOut = m_CrpClient.Snapshots.Get(rgName, snapshotName); Validate(snapshot, snapshotOut, incremental: incremental); // Patch var updatesnapshot = new SnapshotUpdate(); const string tagKey = "tageKey"; updatesnapshot.Tags = new Dictionary<string, string>() { { tagKey, "tagvalue" } }; snapshotOut = m_CrpClient.Snapshots.Update(rgName, snapshotName, updatesnapshot); Validate(snapshot, snapshotOut, incremental: incremental); // Get snapshotOut = m_CrpClient.Snapshots.Get(rgName, snapshotName); Validate(snapshot, snapshotOut, incremental: incremental); // End access m_CrpClient.Snapshots.RevokeAccess(rgName, snapshotName); // Delete m_CrpClient.Snapshots.Delete(rgName, snapshotName); try { // Ensure it was really deleted m_CrpClient.Snapshots.Get(rgName, snapshotName); Assert.False(true); } catch (CloudException ex) { Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode); } } finally { // Delete resource group m_ResourcesClient.ResourceGroups.Delete(rgName); } } } protected void DiskEncryptionSet_CRUD_Execute(string methodName, string encryptionType, string location = null) { using (MockContext context = MockContext.Start(this.GetType(), methodName)) { EnsureClientsInitialized(context); DiskRPLocation = location ?? DiskRPLocation; // Data var rgName = TestUtilities.GenerateName(TestPrefix); var desName = TestUtilities.GenerateName(DiskNamePrefix); DiskEncryptionSet des = GenerateDefaultDiskEncryptionSet(DiskRPLocation, encryptionType); try { m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = DiskRPLocation }); // Put DiskEncryptionSet DiskEncryptionSet desOut = m_CrpClient.DiskEncryptionSets.CreateOrUpdate(rgName, desName, des); Validate(des, desOut, desName, encryptionType); // Get DiskEncryptionSet desOut = m_CrpClient.DiskEncryptionSets.Get(rgName, desName); Validate(des, desOut, desName, encryptionType); // Patch DiskEncryptionSet const string tagKey = "tageKey"; var updateDes = new DiskEncryptionSetUpdate(); updateDes.Tags = new Dictionary<string, string>() { { tagKey, "tagvalue" } }; desOut = m_CrpClient.DiskEncryptionSets.Update(rgName, desName, updateDes); Validate(des, desOut, desName, encryptionType); Assert.Equal(1, desOut.Tags.Count); // Delete DiskEncryptionSet m_CrpClient.DiskEncryptionSets.Delete(rgName, desName); try { // Ensure it was really deleted m_CrpClient.DiskEncryptionSets.Get(rgName, desName); Assert.False(true); } catch (CloudException ex) { Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode); } } finally { // Delete resource group m_ResourcesClient.ResourceGroups.Delete(rgName); } } } protected void DiskAccess_CRUD_Execute(string methodName, string location = null) { using (MockContext context = MockContext.Start(this.GetType(), methodName)) { EnsureClientsInitialized(context); DiskRPLocation = location ?? DiskRPLocation; // Data var rgName = TestUtilities.GenerateName(TestPrefix); var diskAccessName = TestUtilities.GenerateName(DiskNamePrefix); DiskAccess diskAccess = GenerateDefaultDiskAccess(DiskRPLocation); try { m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = DiskRPLocation }); // Put DiskAccess DiskAccess diskAccessOut = m_CrpClient.DiskAccesses.CreateOrUpdate(rgName, diskAccessName, diskAccess); Validate(diskAccess, diskAccessOut, diskAccessName); // Get DiskAccess diskAccessOut = m_CrpClient.DiskAccesses.Get(rgName, diskAccessName); Validate(diskAccess, diskAccessOut, diskAccessName); // Patch DiskAccess const string tagKey = "tagKey"; Dictionary<string, string> tags = new Dictionary<string, string>() { { tagKey, "tagvalue" } }; diskAccessOut = m_CrpClient.DiskAccesses.Update(rgName, diskAccessName, tags); Validate(diskAccess, diskAccessOut, diskAccessName); Assert.Equal(1, diskAccessOut.Tags.Count); PrivateLinkResourceListResult privateLinkResources = m_CrpClient.DiskAccesses.GetPrivateLinkResources(rgName, diskAccessName); Validate(privateLinkResources); // Delete DiskAccess m_CrpClient.DiskAccesses.Delete(rgName, diskAccessName); try { // Ensure it was really deleted m_CrpClient.DiskAccesses.Get(rgName, diskAccessName); Assert.False(true); } catch (CloudException ex) { Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode); } } finally { // Delete resource group m_ResourcesClient.ResourceGroups.Delete(rgName); } } } protected void DiskAccess_WithPrivateEndpoint_CRUD_Execute(string methodName, string location = null) { using (MockContext context = MockContext.Start(this.GetType(), methodName)) { EnsureClientsInitialized(context); DiskRPLocation = location ?? DiskRPLocation; // Data var rgName = TestUtilities.GenerateName(TestPrefix); var diskAccessName = TestUtilities.GenerateName(DiskNamePrefix); var privateEndpointName = TestUtilities.GenerateName(DiskNamePrefix); DiskAccess diskAccess = GenerateDefaultDiskAccess(DiskRPLocation); m_location = location; try { m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = DiskRPLocation }); // Put DiskAccess DiskAccess diskAccessOut = m_CrpClient.DiskAccesses.CreateOrUpdate(rgName, diskAccessName, diskAccess); Validate(diskAccess, diskAccessOut, diskAccessName); // Get DiskAccess diskAccessOut = m_CrpClient.DiskAccesses.Get(rgName, diskAccessName); Validate(diskAccess, diskAccessOut, diskAccessName); // Create VNet with Subnet NM.Subnet subnet = CreateVNET(rgName, disablePEPolicies: true); // Put Private Endpoint associating it with disk access NM.PrivateEndpoint privateEndpoint = CreatePrivateEndpoint(rgName, privateEndpointName, diskAccessOut.Id, subnet.Id); diskAccessOut = m_CrpClient.DiskAccesses.Get(rgName, diskAccessName); Validate(diskAccess, diskAccessOut, diskAccessName, privateEndpoint.Id); // Patch DiskAccess const string tagKey = "tagKey"; Dictionary<string, string> tags = new Dictionary<string, string>() { { tagKey, "tagvalue" } }; diskAccessOut = m_CrpClient.DiskAccesses.Update(rgName, diskAccessName, tags); Validate(diskAccess, diskAccessOut, diskAccessName); Assert.Equal(1, diskAccessOut.Tags.Count); PrivateLinkResourceListResult privateLinkResources = m_CrpClient.DiskAccesses.GetPrivateLinkResources(rgName, diskAccessName); Validate(privateLinkResources); m_NrpClient.PrivateEndpoints.DeleteWithHttpMessagesAsync(rgName, privateEndpointName).GetAwaiter().GetResult(); // Delete DiskAccess m_CrpClient.DiskAccesses.Delete(rgName, diskAccessName); try { // Ensure it was really deleted m_CrpClient.DiskAccesses.Get(rgName, diskAccessName); Assert.False(true); } catch (CloudException ex) { Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode); } } finally { // Delete resource group m_ResourcesClient.ResourceGroups.Delete(rgName); } } } protected void Disk_List_Execute(string diskCreateOption, string methodName, int? diskSizeGB = null, string location = null) { using (MockContext context = MockContext.Start(this.GetType(), methodName)) { EnsureClientsInitialized(context); DiskRPLocation = location ?? DiskRPLocation; // Data var rgName1 = TestUtilities.GenerateName(TestPrefix); var rgName2 = TestUtilities.GenerateName(TestPrefix); var diskName1 = TestUtilities.GenerateName(DiskNamePrefix); var diskName2 = TestUtilities.GenerateName(DiskNamePrefix); Disk disk1 = GenerateDefaultDisk(diskCreateOption, rgName1, diskSizeGB, location: location); Disk disk2 = GenerateDefaultDisk(diskCreateOption, rgName2, diskSizeGB, location: location); try { // ********** // SETUP // ********** // Create resource groups, unless create option is import in which case resource group will be created with vm if (diskCreateOption != DiskCreateOption.Import) { m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName1, new ResourceGroup { Location = DiskRPLocation }); m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName2, new ResourceGroup { Location = DiskRPLocation }); } // Put 4 disks, 2 in each resource group m_CrpClient.Disks.CreateOrUpdate(rgName1, diskName1, disk1); m_CrpClient.Disks.CreateOrUpdate(rgName1, diskName2, disk2); m_CrpClient.Disks.CreateOrUpdate(rgName2, diskName1, disk1); m_CrpClient.Disks.CreateOrUpdate(rgName2, diskName2, disk2); // ********** // TEST // ********** // List disks under resource group IPage<Disk> disksOut = m_CrpClient.Disks.ListByResourceGroup(rgName1); Assert.Equal(2, disksOut.Count()); Assert.Null(disksOut.NextPageLink); disksOut = m_CrpClient.Disks.ListByResourceGroup(rgName2); Assert.Equal(2, disksOut.Count()); Assert.Null(disksOut.NextPageLink); // List disks under subscription disksOut = m_CrpClient.Disks.List(); Assert.True(disksOut.Count() >= 4); if (disksOut.NextPageLink != null) { disksOut = m_CrpClient.Disks.ListNext(disksOut.NextPageLink); Assert.True(disksOut.Any()); } } finally { // Delete resource group m_ResourcesClient.ResourceGroups.Delete(rgName1); m_ResourcesClient.ResourceGroups.Delete(rgName2); } } } protected void Snapshot_List_Execute(string diskCreateOption, string methodName, int? diskSizeGB = null) { using (MockContext context = MockContext.Start(this.GetType(), methodName)) { EnsureClientsInitialized(context); // Data var rgName1 = TestUtilities.GenerateName(TestPrefix); var rgName2 = TestUtilities.GenerateName(TestPrefix); var diskName1 = TestUtilities.GenerateName(DiskNamePrefix); var diskName2 = TestUtilities.GenerateName(DiskNamePrefix); var snapshotName1 = TestUtilities.GenerateName(DiskNamePrefix); var snapshotName2 = TestUtilities.GenerateName(DiskNamePrefix); Disk disk1 = GenerateDefaultDisk(diskCreateOption, rgName1, diskSizeGB); Disk disk2 = GenerateDefaultDisk(diskCreateOption, rgName2, diskSizeGB); try { // ********** // SETUP // ********** // Create resource groups m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName1, new ResourceGroup { Location = DiskRPLocation }); m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName2, new ResourceGroup { Location = DiskRPLocation }); // Put 4 disks, 2 in each resource group Disk diskOut11 = m_CrpClient.Disks.CreateOrUpdate(rgName1, diskName1, disk1); Disk diskOut12 = m_CrpClient.Disks.CreateOrUpdate(rgName1, diskName2, disk2); Disk diskOut21 = m_CrpClient.Disks.CreateOrUpdate(rgName2, diskName1, disk1); Disk diskOut22 = m_CrpClient.Disks.CreateOrUpdate(rgName2, diskName2, disk2); // Generate 4 snapshots using disks info Snapshot snapshot11 = GenerateDefaultSnapshot(diskOut11.Id); Snapshot snapshot12 = GenerateDefaultSnapshot(diskOut12.Id, SnapshotStorageAccountTypes.StandardZRS); Snapshot snapshot21 = GenerateDefaultSnapshot(diskOut21.Id); Snapshot snapshot22 = GenerateDefaultSnapshot(diskOut22.Id); // Put 4 snapshots, 2 in each resource group m_CrpClient.Snapshots.CreateOrUpdate(rgName1, snapshotName1, snapshot11); m_CrpClient.Snapshots.CreateOrUpdate(rgName1, snapshotName2, snapshot12); m_CrpClient.Snapshots.CreateOrUpdate(rgName2, snapshotName1, snapshot21); m_CrpClient.Snapshots.CreateOrUpdate(rgName2, snapshotName2, snapshot22); // ********** // TEST // ********** // List snapshots under resource group IPage<Snapshot> snapshotsOut = m_CrpClient.Snapshots.ListByResourceGroup(rgName1); Assert.Equal(2, snapshotsOut.Count()); Assert.Null(snapshotsOut.NextPageLink); snapshotsOut = m_CrpClient.Snapshots.ListByResourceGroup(rgName2); Assert.Equal(2, snapshotsOut.Count()); Assert.Null(snapshotsOut.NextPageLink); // List snapshots under subscription snapshotsOut = m_CrpClient.Snapshots.List(); Assert.True(snapshotsOut.Count() >= 4); if (snapshotsOut.NextPageLink != null) { snapshotsOut = m_CrpClient.Snapshots.ListNext(snapshotsOut.NextPageLink); Assert.True(snapshotsOut.Any()); } } finally { // Delete resource group m_ResourcesClient.ResourceGroups.Delete(rgName1); m_ResourcesClient.ResourceGroups.Delete(rgName2); } } } protected void DiskEncryptionSet_List_Execute(string methodName, string location = null) { using (MockContext context = MockContext.Start(this.GetType(), methodName)) { EnsureClientsInitialized(context); DiskRPLocation = location ?? DiskRPLocation; // Data var rgName1 = TestUtilities.GenerateName(TestPrefix); var rgName2 = TestUtilities.GenerateName(TestPrefix); var desName1 = TestUtilities.GenerateName(DiskNamePrefix); var desName2 = TestUtilities.GenerateName(DiskNamePrefix); DiskEncryptionSet des1 = GenerateDefaultDiskEncryptionSet(DiskRPLocation); DiskEncryptionSet des2 = GenerateDefaultDiskEncryptionSet(DiskRPLocation); try { // ********** // SETUP // ********** // Create resource groups m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName1, new ResourceGroup { Location = DiskRPLocation }); m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName2, new ResourceGroup { Location = DiskRPLocation }); // Put 4 diskEncryptionSets, 2 in each resource group m_CrpClient.DiskEncryptionSets.CreateOrUpdate(rgName1, desName1, des1); m_CrpClient.DiskEncryptionSets.CreateOrUpdate(rgName1, desName2, des2); m_CrpClient.DiskEncryptionSets.CreateOrUpdate(rgName2, desName1, des1); m_CrpClient.DiskEncryptionSets.CreateOrUpdate(rgName2, desName2, des2); // ********** // TEST // ********** // List diskEncryptionSets under resource group IPage<DiskEncryptionSet> dessOut = m_CrpClient.DiskEncryptionSets.ListByResourceGroup(rgName1); Assert.Equal(2, dessOut.Count()); Assert.Null(dessOut.NextPageLink); dessOut = m_CrpClient.DiskEncryptionSets.ListByResourceGroup(rgName2); Assert.Equal(2, dessOut.Count()); Assert.Null(dessOut.NextPageLink); // List diskEncryptionSets under subscription dessOut = m_CrpClient.DiskEncryptionSets.List(); Assert.True(dessOut.Count() >= 4); if (dessOut.NextPageLink != null) { dessOut = m_CrpClient.DiskEncryptionSets.ListNext(dessOut.NextPageLink); Assert.True(dessOut.Any()); } // Delete diskEncryptionSets m_CrpClient.DiskEncryptionSets.Delete(rgName1, desName1); m_CrpClient.DiskEncryptionSets.Delete(rgName1, desName2); m_CrpClient.DiskEncryptionSets.Delete(rgName2, desName1); m_CrpClient.DiskEncryptionSets.Delete(rgName2, desName2); } finally { // Delete resource group m_ResourcesClient.ResourceGroups.Delete(rgName1); m_ResourcesClient.ResourceGroups.Delete(rgName2); } } } protected void DiskAccess_List_Execute(string methodName, string location = null) { using (MockContext context = MockContext.Start(this.GetType(), methodName)) { EnsureClientsInitialized(context); DiskRPLocation = location ?? DiskRPLocation; // Data var rgName1 = TestUtilities.GenerateName(TestPrefix); var rgName2 = TestUtilities.GenerateName(TestPrefix); var diskAccessName1 = TestUtilities.GenerateName(DiskNamePrefix); var diskAccessName2 = TestUtilities.GenerateName(DiskNamePrefix); DiskAccess diskAccess1 = GenerateDefaultDiskAccess(DiskRPLocation); DiskAccess diskAccess2 = GenerateDefaultDiskAccess(DiskRPLocation); try { // ********** // SETUP // ********** // Create resource groups m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName1, new ResourceGroup { Location = DiskRPLocation }); m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName2, new ResourceGroup { Location = DiskRPLocation }); // Put 4 diskAccesses, 2 in each resource group m_CrpClient.DiskAccesses.CreateOrUpdate(rgName1, diskAccessName1, diskAccess1); m_CrpClient.DiskAccesses.CreateOrUpdate(rgName1, diskAccessName2, diskAccess2); m_CrpClient.DiskAccesses.CreateOrUpdate(rgName2, diskAccessName1, diskAccess1); m_CrpClient.DiskAccesses.CreateOrUpdate(rgName2, diskAccessName2, diskAccess2); // ********** // TEST // ********** // List diskAccesses under resource group IPage<DiskAccess> diskAccessesOut = m_CrpClient.DiskAccesses.ListByResourceGroup(rgName1); Assert.Equal(2, diskAccessesOut.Count()); Assert.Null(diskAccessesOut.NextPageLink); diskAccessesOut = m_CrpClient.DiskAccesses.ListByResourceGroup(rgName2); Assert.Equal(2, diskAccessesOut.Count()); Assert.Null(diskAccessesOut.NextPageLink); // List diskAccesses under subscription diskAccessesOut = m_CrpClient.DiskAccesses.List(); Assert.True(diskAccessesOut.Count() >= 4); if (diskAccessesOut.NextPageLink != null) { diskAccessesOut = m_CrpClient.DiskAccesses.ListNext(diskAccessesOut.NextPageLink); Assert.True(diskAccessesOut.Any()); } // Delete diskAccesses m_CrpClient.DiskAccesses.Delete(rgName1, diskAccessName1); m_CrpClient.DiskAccesses.Delete(rgName1, diskAccessName2); m_CrpClient.DiskAccesses.Delete(rgName2, diskAccessName1); m_CrpClient.DiskAccesses.Delete(rgName2, diskAccessName2); } finally { // Delete resource group m_ResourcesClient.ResourceGroups.Delete(rgName1); m_ResourcesClient.ResourceGroups.Delete(rgName2); } } } protected void DiskEncryptionSet_CreateDisk_Execute(string methodName, string location = null) { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); var rgName = TestUtilities.GenerateName(TestPrefix); var diskName = TestUtilities.GenerateName(DiskNamePrefix); var desName = "longlivedSwaggerDES"; Disk disk = GenerateDefaultDisk(DiskCreateOption.Empty, rgName, 10); disk.Location = location; try { m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = location }); // Get DiskEncryptionSet DiskEncryptionSet desOut = m_CrpClient.DiskEncryptionSets.Get("longrunningrg-centraluseuap", desName); Assert.NotNull(desOut); disk.Encryption = new Encryption { Type = EncryptionType.EncryptionAtRestWithCustomerKey.ToString(), DiskEncryptionSetId = desOut.Id }; //Put Disk m_CrpClient.Disks.CreateOrUpdate(rgName, diskName, disk); Disk diskOut = m_CrpClient.Disks.Get(rgName, diskName); Validate(disk, diskOut, disk.Location); Assert.Equal(desOut.Id.ToLower(), diskOut.Encryption.DiskEncryptionSetId.ToLower()); Assert.Equal(EncryptionType.EncryptionAtRestWithCustomerKey, diskOut.Encryption.Type); IPage<string> diskUri = m_CrpClient.DiskEncryptionSets.ListAssociatedResources("longrunningrg-centraluseuap", desName); List<string>diskUriString = diskUri.ToList().ConvertAll(r => r.ToString().ToLower()); Assert.Contains(diskOut.Id.ToLower().ToString(), diskUriString); m_CrpClient.Disks.Delete(rgName, diskName); } finally { m_ResourcesClient.ResourceGroups.Delete(rgName); } } } protected void DiskAccess_CreateDisk_Execute(string methodName, string location = null) { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); var rgName = TestUtilities.GenerateName(TestPrefix); var diskName = TestUtilities.GenerateName(DiskNamePrefix); var diskAccessName = TestUtilities.GenerateName(DiskNamePrefix); Disk disk = GenerateDefaultDisk(DiskCreateOption.Empty, rgName, 10); DiskAccess diskAccess = GenerateDefaultDiskAccess(location); disk.Location = location; try { m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = location }); DiskAccess diskAccessOut = m_CrpClient.DiskAccesses.CreateOrUpdate(rgName, diskAccessName, diskAccess); //Get DiskAccess diskAccessOut = m_CrpClient.DiskAccesses.Get(rgName, diskAccessName); disk.DiskAccessId = diskAccessOut.Id; //Put Disk m_CrpClient.Disks.CreateOrUpdate(rgName, diskName, disk); Disk diskOut = m_CrpClient.Disks.Get(rgName, diskName); Validate(disk, diskOut, disk.Location); Assert.Equal(diskAccessOut.Id.ToLower(), diskOut.DiskAccessId.ToLower()); m_CrpClient.Disks.Delete(rgName, diskName); m_CrpClient.DiskAccesses.Delete(rgName, diskAccessName); } finally { m_ResourcesClient.ResourceGroups.Delete(rgName); } } } protected void DiskEncryptionSet_UpdateDisk_Execute(string methodName, string location = null) { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); var rgName = TestUtilities.GenerateName(TestPrefix); var diskName = TestUtilities.GenerateName(DiskNamePrefix); var desName = "longlivedSwaggerDES"; Disk disk = GenerateDefaultDisk(DiskCreateOption.Empty, rgName, 10); disk.Location = location; try { m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = location }); // Put Disk with PlatformManagedKey m_CrpClient.Disks.CreateOrUpdate(rgName, diskName, disk); Disk diskOut = m_CrpClient.Disks.Get(rgName, diskName); Validate(disk, diskOut, disk.Location); Assert.Null(diskOut.Encryption.DiskEncryptionSetId); Assert.Equal(EncryptionType.EncryptionAtRestWithPlatformKey, diskOut.Encryption.Type); // Update Disk with CustomerManagedKey DiskEncryptionSet desOut = m_CrpClient.DiskEncryptionSets.Get("longrunningrg-centraluseuap", desName); Assert.NotNull(desOut); disk.Encryption = new Encryption { Type = EncryptionType.EncryptionAtRestWithCustomerKey.ToString(), DiskEncryptionSetId = desOut.Id }; m_CrpClient.Disks.CreateOrUpdate(rgName, diskName, disk); diskOut = m_CrpClient.Disks.Get(rgName, diskName); Assert.Equal(desOut.Id.ToLower(), diskOut.Encryption.DiskEncryptionSetId.ToLower()); Assert.Equal(EncryptionType.EncryptionAtRestWithCustomerKey, diskOut.Encryption.Type); m_CrpClient.Disks.Delete(rgName, diskName); } finally { m_ResourcesClient.ResourceGroups.Delete(rgName); } } } protected void DiskAccess_UpdateDisk_Execute(string methodName, string location = null) { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); var rgName = TestUtilities.GenerateName(TestPrefix); var diskName = TestUtilities.GenerateName(DiskNamePrefix); var diskAccessName = TestUtilities.GenerateName(DiskNamePrefix); Disk disk = GenerateDefaultDisk(DiskCreateOption.Empty, rgName, 10); DiskAccess diskAccess = GenerateDefaultDiskAccess(location); disk.Location = location; try { m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = location }); // Put Disk m_CrpClient.Disks.CreateOrUpdate(rgName, diskName, disk); Disk diskOut = m_CrpClient.Disks.Get(rgName, diskName); Validate(disk, diskOut, disk.Location); Assert.Null(diskOut.DiskAccessId); m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = location }); DiskAccess diskAccessOut = m_CrpClient.DiskAccesses.CreateOrUpdate(rgName, diskAccessName, diskAccess); //Get DiskAccess diskAccessOut = m_CrpClient.DiskAccesses.Get(rgName, diskAccessName); //Update Disk with DiskAccess DiskUpdate diskUpdate = new DiskUpdate { DiskAccessId = diskAccessOut.Id }; m_CrpClient.Disks.Update(rgName, diskName, diskUpdate); diskOut = m_CrpClient.Disks.Get(rgName, diskName); Assert.Equal(diskAccessOut.Id.ToLower(), diskOut.DiskAccessId.ToLower()); Assert.Equal(NetworkAccessPolicy.AllowPrivate, diskOut.NetworkAccessPolicy); m_CrpClient.Disks.Delete(rgName, diskName); m_CrpClient.DiskAccesses.Delete(rgName, diskAccessName); } finally { m_ResourcesClient.ResourceGroups.Delete(rgName); } } } protected void DiskAccess_UpdateDisk_RemoveDiskAccess_Execute(string methodName, string location = null) { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); var rgName = TestUtilities.GenerateName(TestPrefix); var diskName = TestUtilities.GenerateName(DiskNamePrefix); var diskAccessName = TestUtilities.GenerateName(DiskNamePrefix); Disk disk = GenerateDefaultDisk(DiskCreateOption.Empty, rgName, 10); DiskAccess diskAccess = GenerateDefaultDiskAccess(location); disk.Location = location; try { m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = location }); // Put Disk m_CrpClient.Disks.CreateOrUpdate(rgName, diskName, disk); Disk diskOut = m_CrpClient.Disks.Get(rgName, diskName); Validate(disk, diskOut, disk.Location); Assert.Null(diskOut.DiskAccessId); m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = location }); DiskAccess diskAccessOut = m_CrpClient.DiskAccesses.CreateOrUpdate(rgName, diskAccessName, diskAccess); //Get DiskAccess diskAccessOut = m_CrpClient.DiskAccesses.Get(rgName, diskAccessName); //Update Disk with DiskAccess DiskUpdate diskUpdate = new DiskUpdate { DiskAccessId = diskAccessOut.Id }; m_CrpClient.Disks.Update(rgName, diskName, diskUpdate); diskOut = m_CrpClient.Disks.Get(rgName, diskName); Assert.Equal(diskAccessOut.Id.ToLower(), diskOut.DiskAccessId.ToLower()); //Set network access policy to AllowAll to remove diskAccess from Disk diskUpdate.DiskAccessId = null; diskUpdate.NetworkAccessPolicy = NetworkAccessPolicy.AllowAll; m_CrpClient.Disks.Update(rgName, diskName, diskUpdate); diskOut = m_CrpClient.Disks.Get(rgName, diskName); Assert.Null(diskOut.DiskAccessId); Assert.Equal(NetworkAccessPolicy.AllowAll, diskOut.NetworkAccessPolicy); m_CrpClient.Disks.Delete(rgName, diskName); m_CrpClient.DiskAccesses.Delete(rgName, diskAccessName); } finally { m_ResourcesClient.ResourceGroups.Delete(rgName); } } } #endregion #region Generation public static readonly GrantAccessData AccessDataDefault = new GrantAccessData { Access = AccessLevel.Read, DurationInSeconds = 1000 }; protected Disk GenerateDefaultDisk(string diskCreateOption, string rgName, int? diskSizeGB = null, IList<string> zones = null, string location = null) { Disk disk; switch (diskCreateOption) { case "Upload": disk = GenerateBaseDisk(diskCreateOption); disk.CreationData.UploadSizeBytes = (long) (diskSizeGB ?? 10) * 1024 * 1024 * 1024 + 512; break; case "Empty": disk = GenerateBaseDisk(diskCreateOption); disk.DiskSizeGB = diskSizeGB; disk.Zones = zones; break; case "Import": disk = GenerateImportDisk(diskCreateOption, rgName, location); disk.DiskSizeGB = diskSizeGB; disk.Zones = zones; break; case "Copy": disk = GenerateCopyDisk(rgName, diskSizeGB ?? 10, location); disk.Zones = zones; break; default: throw new ArgumentOutOfRangeException("diskCreateOption", diskCreateOption, "Unsupported option provided."); } return disk; } /// <summary> /// Generates a disk used when the DiskCreateOption is Import /// </summary> /// <returns></returns> private Disk GenerateImportDisk(string diskCreateOption, string rgName, string location) { // Create a VM, so we can use its OS disk for creating the image string storageAccountName = ComputeManagementTestUtilities.GenerateName(DiskNamePrefix); string asName = ComputeManagementTestUtilities.GenerateName("as"); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); VirtualMachine inputVM = null; m_location = location; // Create Storage Account var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); // Create the VM, whose OS disk will be used in creating the image var createdVM = CreateVM(rgName, asName, storageAccountOutput, imageRef, out inputVM); var listResponse = m_CrpClient.VirtualMachines.ListAll(); Assert.True(listResponse.Count() >= 1); string[] id = createdVM.Id.Split('/'); string subscription = id[2]; var uri = createdVM.StorageProfile.OsDisk.Vhd.Uri; m_CrpClient.VirtualMachines.Delete(rgName, inputVM.Name); m_CrpClient.VirtualMachines.Delete(rgName, createdVM.Name); Disk disk = GenerateBaseDisk(diskCreateOption); disk.CreationData.SourceUri = uri; disk.CreationData.StorageAccountId = "/subscriptions/" + subscription + "/resourceGroups/" + rgName + "/providers/Microsoft.Storage/storageAccounts/" + storageAccountName; return disk; } /// <summary> /// Generates a disk used when the DiskCreateOption is Copy /// </summary> /// <returns></returns> private Disk GenerateCopyDisk(string rgName, int diskSizeGB, string location) { // Create an empty disk Disk originalDisk = GenerateDefaultDisk("Empty", rgName, diskSizeGB: diskSizeGB); m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = location }); Disk diskOut = m_CrpClient.Disks.CreateOrUpdate(rgName, TestUtilities.GenerateName(DiskNamePrefix + "_original"), originalDisk); Snapshot snapshot = GenerateDefaultSnapshot(diskOut.Id); Snapshot snapshotOut = m_CrpClient.Snapshots.CreateOrUpdate(rgName, "snapshotswaaggertest", snapshot); Disk copyDisk = GenerateBaseDisk("Import"); copyDisk.CreationData.SourceResourceId = snapshotOut.Id; return copyDisk; } protected DiskEncryptionSet GenerateDefaultDiskEncryptionSet(string location, string encryptionType = EncryptionType.EncryptionAtRestWithCustomerKey) { string testVaultId = @"/subscriptions/0296790d-427c-48ca-b204-8b729bbd8670/resourcegroups/swagger/providers/Microsoft.KeyVault/vaults/swaggervault"; string encryptionKeyUri = @"https://swaggervault.vault.azure.net/keys/diskRPSSEKey/4780bcaf12384596b75cf63731f2046c"; var des = new DiskEncryptionSet { Identity = new EncryptionSetIdentity { Type = ResourceIdentityType.SystemAssigned.ToString() }, Location = location, ActiveKey = new KeyForDiskEncryptionSet { SourceVault = new SourceVault { Id = testVaultId }, KeyUrl = encryptionKeyUri }, EncryptionType = encryptionType }; return des; } protected DiskAccess GenerateDefaultDiskAccess(string location) { var diskAccess = new DiskAccess { Location = location }; return diskAccess; } public Disk GenerateBaseDisk(string diskCreateOption) { var disk = new Disk { Location = DiskRPLocation, }; disk.Sku = new DiskSku() { Name = StorageAccountTypes.StandardLRS }; disk.CreationData = new CreationData() { CreateOption = diskCreateOption, }; disk.OsType = OperatingSystemTypes.Linux; return disk; } protected Snapshot GenerateDefaultSnapshot(string sourceDiskId, string snapshotStorageAccountTypes = "Standard_LRS", bool incremental = false) { Snapshot snapshot = GenerateBaseSnapshot(sourceDiskId, snapshotStorageAccountTypes, incremental); return snapshot; } private Snapshot GenerateBaseSnapshot(string sourceDiskId, string snapshotStorageAccountTypes, bool incremental = false) { var snapshot = new Snapshot() { Location = DiskRPLocation, Incremental = incremental }; snapshot.Sku = new SnapshotSku() { Name = snapshotStorageAccountTypes ?? SnapshotStorageAccountTypes.StandardLRS }; snapshot.CreationData = new CreationData() { CreateOption = DiskCreateOption.Copy, SourceResourceId = sourceDiskId, }; return snapshot; } #endregion #region Helpers protected NM.PrivateEndpoint CreatePrivateEndpoint(string rgName, string peName, string diskAccessId, string subnetId) { string plsConnectionName = TestUtilities.GenerateName("pls"); NM.PrivateEndpoint privateEndpoint = new NM.PrivateEndpoint { Subnet = new NM.Subnet { Id = subnetId }, Location = m_location, PrivateLinkServiceConnections = new List<NM.PrivateLinkServiceConnection> { new NM.PrivateLinkServiceConnection { GroupIds = new List<string> { "disks" }, Name = plsConnectionName, PrivateLinkServiceId = diskAccessId } } }; NM.PrivateEndpoint privateEndpointOut = m_NrpClient.PrivateEndpoints.CreateOrUpdateWithHttpMessagesAsync(rgName, peName, privateEndpoint).GetAwaiter().GetResult().Body; return privateEndpointOut; } #endregion #region Validation private void Validate(DiskEncryptionSet diskEncryptionSetExpected, DiskEncryptionSet diskEncryptionSetActual, string expectedDESName, string expectedEncryptionType) { Assert.Equal(expectedDESName, diskEncryptionSetActual.Name); Assert.Equal(diskEncryptionSetExpected.Location, diskEncryptionSetActual.Location); Assert.Equal(diskEncryptionSetExpected.ActiveKey.SourceVault.Id, diskEncryptionSetActual.ActiveKey.SourceVault.Id); Assert.Equal(diskEncryptionSetExpected.ActiveKey.KeyUrl, diskEncryptionSetActual.ActiveKey.KeyUrl); Assert.NotNull(diskEncryptionSetActual.Identity); Assert.Equal(ResourceIdentityType.SystemAssigned.ToString(), diskEncryptionSetActual.Identity.Type); Assert.Equal(expectedEncryptionType, diskEncryptionSetActual.EncryptionType); } private void Validate(DiskAccess diskAccessExpected, DiskAccess diskAccessActual, string expectedDiskAccessName, string privateEndpointId = null) { Assert.Equal(expectedDiskAccessName, diskAccessActual.Name); Assert.Equal(diskAccessExpected.Location, diskAccessActual.Location); Assert.Equal(string.Format("{0}/{1}", ApiConstants.ResourceProviderNamespace, "diskAccesses"), diskAccessActual.Type); Assert.Equal("Succeeded", diskAccessActual.ProvisioningState); if (privateEndpointId != null) { // since private endpoint is specified we expect there to be private endpoint connections Assert.NotNull(diskAccessActual.PrivateEndpointConnections); Assert.Equal(string.Format("{0}/{1}/{2}", ApiConstants.ResourceProviderNamespace, "diskAccesses", "PrivateEndpointConnections"), diskAccessActual.PrivateEndpointConnections[0].Type); Assert.Equal(privateEndpointId, diskAccessActual.PrivateEndpointConnections[0].PrivateEndpoint.Id); Assert.Equal("Approved", diskAccessActual.PrivateEndpointConnections[0].PrivateLinkServiceConnectionState.Status); Assert.Equal("None", diskAccessActual.PrivateEndpointConnections[0].PrivateLinkServiceConnectionState.ActionsRequired); Assert.Equal(PrivateEndpointConnectionProvisioningState.Succeeded, diskAccessActual.PrivateEndpointConnections[0].ProvisioningState); } } private void Validate(PrivateLinkResourceListResult privateLinkResources) { Assert.Equal(1, privateLinkResources.Value.Count); Assert.Equal(string.Format("{0}/{1}/{2}", ApiConstants.ResourceProviderNamespace, "diskAccesses", "privateLinkResources"), privateLinkResources.Value[0].Type); Assert.Equal("disks", privateLinkResources.Value[0].GroupId); Assert.Equal(1, privateLinkResources.Value[0].RequiredMembers.Count); Assert.Equal("diskAccess_1", privateLinkResources.Value[0].RequiredMembers[0]); Assert.Equal("privatelink.blob.core.windows.net", privateLinkResources.Value[0].RequiredZoneNames[0]); } private void Validate(Snapshot snapshotExpected, Snapshot snapshotActual, bool diskHydrated = false, bool incremental = false) { // snapshot resource Assert.Equal(string.Format("{0}/{1}", ApiConstants.ResourceProviderNamespace, "snapshots"), snapshotActual.Type); Assert.NotNull(snapshotActual.Name); Assert.Equal(DiskRPLocation, snapshotActual.Location); // snapshot properties Assert.Equal(snapshotExpected.Sku.Name, snapshotActual.Sku.Name); Assert.True(snapshotActual.ManagedBy == null); Assert.NotNull(snapshotActual.ProvisioningState); Assert.Equal(incremental, snapshotActual.Incremental); Assert.NotNull(snapshotActual.CreationData.SourceUniqueId); if (snapshotExpected.OsType != null) //these properties are not mandatory for the client { Assert.Equal(snapshotExpected.OsType, snapshotActual.OsType); } if (snapshotExpected.DiskSizeGB != null) { // Disk resizing Assert.Equal(snapshotExpected.DiskSizeGB, snapshotActual.DiskSizeGB); } // Creation data CreationData creationDataExp = snapshotExpected.CreationData; CreationData creationDataAct = snapshotActual.CreationData; Assert.Equal(creationDataExp.CreateOption, creationDataAct.CreateOption); Assert.Equal(creationDataExp.SourceUri, creationDataAct.SourceUri); Assert.Equal(creationDataExp.SourceResourceId, creationDataAct.SourceResourceId); Assert.Equal(creationDataExp.StorageAccountId, creationDataAct.StorageAccountId); // Image reference ImageDiskReference imgRefExp = creationDataExp.GalleryImageReference ?? creationDataExp.ImageReference; ImageDiskReference imgRefAct = creationDataAct.GalleryImageReference ?? creationDataAct.ImageReference; if (imgRefExp != null) { Assert.Equal(imgRefExp.Id, imgRefAct.Id); Assert.Equal(imgRefExp.Lun, imgRefAct.Lun); } else { Assert.Null(imgRefAct); } } protected void Validate(Disk diskExpected, Disk diskActual, string location, bool diskHydrated = false, bool update = false) { // disk resource Assert.Equal(string.Format("{0}/{1}", ApiConstants.ResourceProviderNamespace, "disks"), diskActual.Type); Assert.NotNull(diskActual.Name); Assert.Equal(location, diskActual.Location); // disk properties Assert.Equal(diskExpected.Sku.Name, diskActual.Sku.Name); Assert.NotNull(diskActual.ProvisioningState); Assert.Equal(diskExpected.OsType, diskActual.OsType); Assert.NotNull(diskActual.UniqueId); if (diskExpected.DiskSizeGB != null) { // Disk resizing Assert.Equal(diskExpected.DiskSizeGB, diskActual.DiskSizeGB); Assert.NotNull(diskActual.DiskSizeBytes); } if (!update) { if (diskExpected.DiskIOPSReadWrite != null) { Assert.Equal(diskExpected.DiskIOPSReadWrite, diskActual.DiskIOPSReadWrite); } if (diskExpected.DiskMBpsReadWrite != null) { Assert.Equal(diskExpected.DiskMBpsReadWrite, diskActual.DiskMBpsReadWrite); } if (diskExpected.DiskIOPSReadOnly != null) { Assert.Equal(diskExpected.DiskIOPSReadOnly, diskActual.DiskIOPSReadOnly); } if (diskExpected.DiskMBpsReadOnly != null) { Assert.Equal(diskExpected.DiskMBpsReadOnly, diskActual.DiskMBpsReadOnly); } if (diskExpected.MaxShares != null) { Assert.Equal(diskExpected.MaxShares, diskActual.MaxShares); } } // Creation data CreationData creationDataExp = diskExpected.CreationData; CreationData creationDataAct = diskActual.CreationData; Assert.Equal(creationDataExp.CreateOption, creationDataAct.CreateOption); Assert.Equal(creationDataExp.SourceUri, creationDataAct.SourceUri); Assert.Equal(creationDataExp.SourceResourceId, creationDataAct.SourceResourceId); Assert.Equal(creationDataExp.StorageAccountId, creationDataAct.StorageAccountId); // Image reference ImageDiskReference imgRefExp = creationDataExp.GalleryImageReference ?? creationDataExp.ImageReference; ImageDiskReference imgRefAct = creationDataAct.GalleryImageReference ?? creationDataAct.ImageReference; if (imgRefExp != null) { Assert.Equal(imgRefExp.Id, imgRefAct.Id); Assert.Equal(imgRefExp.Lun, imgRefAct.Lun); } else { Assert.Null(imgRefAct); } // Zones IList<string> zonesExp = diskExpected.Zones; IList<string> zonesAct = diskActual.Zones; if (zonesExp != null) { Assert.Equal(zonesExp.Count, zonesAct.Count); foreach (string zone in zonesExp) { Assert.Contains(zone, zonesAct, StringComparer.OrdinalIgnoreCase); } } else { Assert.Null(zonesAct); } } #endregion } }
// // PackedByteArray.cs // // Author: Jeffrey Stedfast <[email protected]> // // Copyright (c) 2012 Jeffrey Stedfast // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; namespace MimeKit.Utils { class PackedByteArray : IList<byte> { const int InitialBufferSize = 64; ushort[] buffer; int length; int cursor; public PackedByteArray () { buffer = new ushort[InitialBufferSize]; Clear (); } #region ICollection implementation public int Count { get { return length; } } public bool IsReadOnly { get { return false; } } void EnsureBufferSize (int size) { if (buffer.Length > size) return; int ideal = (size + 63) & ~63; Array.Resize<ushort> (ref buffer, ideal); } public void Add (byte item) { if (cursor < 0 || item != (byte) (buffer[cursor] & 0xFF) || (buffer[cursor] & 0xFF00) == 0xFF00) { EnsureBufferSize (cursor + 2); buffer[++cursor] = (ushort) ((1 << 8) | item); } else { buffer[cursor] += (1 << 8); } length++; } public void Clear () { cursor = -1; length = 0; } public bool Contains (byte item) { for (int i = 0; i <= cursor; i++) { if (item == (byte) (buffer[i] & 0xFF)) return true; } return false; } public void CopyTo (byte[] array, int arrayIndex) { if (array == null) throw new ArgumentNullException ("array"); if (arrayIndex < 0 || arrayIndex + length > array.Length) throw new ArgumentOutOfRangeException ("arrayIndex"); int index = arrayIndex; int count; byte c; for (int i = 0; i <= cursor; i++) { count = (buffer[i] >> 8) & 0xFF; c = (byte) (buffer[i] & 0xFF); for (int n = 0; n < count; n++) array[index++] = c; } } public bool Remove (byte item) { int count = 0; int i; // find the index of the element we need to remove for (i = 0; i <= cursor; i++) { if (item == (byte) (buffer[i] & 0xFF)) { count = ((buffer[i] >> 8) & 0xFF); break; } } if (i > cursor) return false; if (count > 1) { // this byte was repeated more than once, so just decrement the count buffer[i] = (ushort) (((count - 1) << 8) | item); } else if (i < cursor) { // to remove the element at position i, we need to shift the // remaining data one item to the left Array.Copy (buffer, i + 1, buffer, i, cursor - i); cursor--; } else { // removing the last byte added cursor--; } length--; return true; } #endregion #region IList implementation public int IndexOf (byte item) { int offset = 0; for (int i = 0; i <= cursor; i++) { if (item == (byte) (buffer[i] & 0xFF)) return offset; offset += ((buffer[i] >> 8) & 0xFF); } return -1; } public void Insert (int index, byte item) { throw new NotSupportedException (); } public void RemoveAt (int index) { if (index < 0 || index > length) throw new ArgumentOutOfRangeException ("index"); int offset = 0; int count = 0; int i; // find the index of the element we need to remove for (i = 0; i <= cursor; i++) { count = ((buffer[i] >> 8) & 0xFF); if (offset + count > index) break; offset += count; } if (count > 1) { // this byte was repeated more than once, so just decrement the count byte c = (byte) (buffer[i] & 0xFF); buffer[i] = (ushort) (((count - 1) << 8) | c); } else if (i < cursor) { // to remove the element at position i, we need to shift the // remaining data one item to the left Array.Copy (buffer, i + 1, buffer, i, cursor - i); cursor--; } else { // removing the last byte added cursor--; } length--; } public byte this [int index] { get { if (index < 0 || index > length) throw new ArgumentOutOfRangeException ("index"); int offset = 0; int count, i; for (i = 0; i <= cursor; i++) { count = ((buffer[i] >> 8) & 0xFF); if (offset + count > index) break; offset += count; } return (byte) (buffer[i] & 0xFF); } set { throw new NotSupportedException (); } } #endregion #region IEnumerable implementation public IEnumerator<byte> GetEnumerator () { int count; byte c; for (int i = 0; i <= cursor; i++) { count = (buffer[i] >> 8) & 0xFF; c = (byte) (buffer[i] & 0xFF); for (int n = 0; n < count; n++) yield return c; } yield break; } #endregion #region IEnumerable implementation IEnumerator IEnumerable.GetEnumerator () { return GetEnumerator (); } #endregion } }
// 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.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using DotSpatial.Data; using DotSpatial.Serialization; namespace DotSpatial.Symbology { /// <summary> /// Symbolizer for polygon features. /// </summary> public class PolygonSymbolizer : FeatureSymbolizer, IPolygonSymbolizer { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="PolygonSymbolizer"/> class. /// </summary> public PolygonSymbolizer() { Patterns = new CopyList<IPattern> { new SimplePattern() }; } /// <summary> /// Initializes a new instance of the <see cref="PolygonSymbolizer"/> class. /// </summary> /// <param name="fillColor">The color to use as a fill color.</param> public PolygonSymbolizer(Color fillColor) { Patterns = new CopyList<IPattern> { new SimplePattern(fillColor) }; } /// <summary> /// Initializes a new instance of the <see cref="PolygonSymbolizer"/> class. /// </summary> /// <param name="fillColor">The fill color to use for the polygons</param> /// <param name="outlineColor">The border color to use for the polygons</param> public PolygonSymbolizer(Color fillColor, Color outlineColor) : this(fillColor, outlineColor, 1) { } /// <summary> /// Initializes a new instance of the <see cref="PolygonSymbolizer"/> class using a solid fill pattern. /// </summary> /// <param name="fillColor">The fill color to use for the polygons</param> /// <param name="outlineColor">The border color to use for the polygons</param> /// <param name="outlineWidth">The width of the outline to use fo</param> public PolygonSymbolizer(Color fillColor, Color outlineColor, double outlineWidth) { Patterns = new CopyList<IPattern> { new SimplePattern(fillColor) }; OutlineSymbolizer = new LineSymbolizer(outlineColor, outlineWidth); } /// <summary> /// Initializes a new instance of the <see cref="PolygonSymbolizer"/> class using a Gradient Pattern with the specified colors and angle. /// </summary> /// <param name="startColor">The start color</param> /// <param name="endColor">The end color</param> /// <param name="angle">The direction of the gradient, measured in degrees clockwise from the x-axis</param> /// <param name="style">Controls how the gradient is drawn</param> public PolygonSymbolizer(Color startColor, Color endColor, double angle, GradientType style) { Patterns = new CopyList<IPattern> { new GradientPattern(startColor, endColor, angle, style) }; } /// <summary> /// Initializes a new instance of the <see cref="PolygonSymbolizer"/> class using a Gradient Pattern with the specified colors and angle. /// </summary> /// <param name="startColor">The start color</param> /// <param name="endColor">The end color</param> /// <param name="angle">The direction of the gradient, measured in degrees clockwise from the x-axis</param> /// <param name="style">The type of gradient to use</param> /// <param name="outlineColor">The color to use for the border symbolizer</param> /// <param name="outlineWidth">The width of the line to use for the border symbolizer</param> public PolygonSymbolizer(Color startColor, Color endColor, double angle, GradientType style, Color outlineColor, double outlineWidth) : this(startColor, endColor, angle, style) { OutlineSymbolizer = new LineSymbolizer(outlineColor, outlineWidth); } /// <summary> /// Initializes a new instance of the <see cref="PolygonSymbolizer"/> class using PicturePattern with the specified image. /// </summary> /// <param name="picture">The picture to draw</param> /// <param name="wrap">The way to wrap the picture</param> /// <param name="angle">The angle to rotate the image</param> public PolygonSymbolizer(Image picture, WrapMode wrap, double angle) { Patterns = new CopyList<IPattern> { new PicturePattern(picture, wrap, angle) }; } /// <summary> /// Initializes a new instance of the <see cref="PolygonSymbolizer"/> class using PicturePattern with the specified image. /// </summary> /// <param name="picture">The picture to draw</param> /// <param name="wrap">The way to wrap the picture</param> /// <param name="angle">The angle to rotate the image</param> /// <param name="outlineColor">The color to use for the border symbolizer</param> /// <param name="outlineWidth">The width of the line to use for the border symbolizer</param> public PolygonSymbolizer(Image picture, WrapMode wrap, double angle, Color outlineColor, double outlineWidth) : this(picture, wrap, angle) { OutlineSymbolizer = new LineSymbolizer(outlineColor, outlineWidth); } /// <summary> /// Initializes a new instance of the <see cref="PolygonSymbolizer"/> class using the patterns specified by the list or array of patterns. /// </summary> /// <param name="patterns">The patterns to add to this symbolizer.</param> public PolygonSymbolizer(IEnumerable<IPattern> patterns) { Patterns = new CopyList<IPattern>(); foreach (IPattern pattern in patterns) { Patterns.Add(pattern); } } /// <summary> /// Initializes a new instance of the <see cref="PolygonSymbolizer"/> class. /// </summary> /// <param name="selected">Boolean, true if this should use selection symbology</param> public PolygonSymbolizer(bool selected) { Patterns = new CopyList<IPattern>(); if (selected) { Patterns.Add(new SimplePattern(Color.Transparent)); OutlineSymbolizer = new LineSymbolizer(Color.Cyan, 2); } else { Patterns.Add(new SimplePattern()); } } #endregion #region Properties /// <summary> /// Gets or sets the Symbolizer for the borders of this polygon as they appear on the top-most pattern. /// </summary> [ShallowCopy] [Serialize("OutlineSymbolizer")] public ILineSymbolizer OutlineSymbolizer { get { if (Patterns == null) return null; if (Patterns.Count == 0) return null; return Patterns[Patterns.Count - 1].Outline; } set { if (Patterns == null) return; if (Patterns.Count == 0) return; Patterns[Patterns.Count - 1].Outline = value; } } /// <summary> /// gets or sets the list of patterns to use for filling polygons. /// </summary> [Serialize("Patterns")] public IList<IPattern> Patterns { get; set; } #endregion #region Methods /// <summary> /// Draws the polygon symbology /// </summary> /// <param name="g">The graphics device to draw to</param> /// <param name="target">The target rectangle to draw symbology content to</param> public override void Draw(Graphics g, Rectangle target) { GraphicsPath gp = new GraphicsPath(); gp.AddRectangle(target); foreach (IPattern pattern in Patterns) { pattern.Bounds = new RectangleF(target.X, target.Y, target.Width, target.Height); pattern.FillPath(g, gp); } foreach (IPattern pattern in Patterns) { pattern.Outline?.DrawPath(g, gp, 1); } gp.Dispose(); } /// <summary> /// Gets the fill color of the top-most pattern. /// </summary> /// <returns>The fill color.</returns> public Color GetFillColor() { if (Patterns == null) return Color.Empty; if (Patterns.Count == 0) return Color.Empty; return Patterns[Patterns.Count - 1].GetFillColor(); } /// <summary> /// This gets the largest width of all the strokes of the outlines of all the patterns. Setting this will /// forceably adjust the width of all the strokes of the outlines of all the patterns. /// </summary> /// <returns>The outline width.</returns> public double GetOutlineWidth() { if (Patterns == null) return 0; if (Patterns.Count == 0) return 0; double w = 0; foreach (IPattern pattern in Patterns) { double tempWidth = pattern.Outline.GetWidth(); if (tempWidth > w) w = tempWidth; } return w; } /// <summary> /// Sets the fill color of the top-most pattern. /// If the pattern is not a simple pattern, a simple pattern will be forced. /// </summary> /// <param name="color">The Color structure</param> public void SetFillColor(Color color) { if (Patterns == null) return; if (Patterns.Count == 0) return; ISimplePattern sp = Patterns[Patterns.Count - 1] as ISimplePattern; if (sp == null) { sp = new SimplePattern(); Patterns[Patterns.Count - 1] = sp; } sp.FillColor = color; } /// <summary> /// Sets the outline, assuming that the symbolizer either supports outlines, or else by using a second symbol layer. /// </summary> /// <param name="outlineColor">The color of the outline</param> /// <param name="width">The width of the outline in pixels</param> public override void SetOutline(Color outlineColor, double width) { if (Patterns == null) return; if (Patterns.Count == 0) return; foreach (IPattern pattern in Patterns) { pattern.Outline.SetFillColor(outlineColor); pattern.Outline.SetWidth(width); pattern.UseOutline = true; } base.SetOutline(outlineColor, width); } /// <summary> /// Forces the specified width to be the width of every stroke outlining every pattern. /// </summary> /// <param name="width">The width to force as the outline width</param> public void SetOutlineWidth(double width) { if (Patterns == null || Patterns.Count == 0) return; foreach (IPattern pattern in Patterns) { pattern.Outline.SetWidth(width); } } /// <summary> /// Occurs after the pattern list is set so that we can listen for when /// the outline symbolizer gets updated. /// </summary> protected virtual void OnHandlePatternEvents() { IChangeEventList<IPattern> patterns = Patterns as IChangeEventList<IPattern>; if (patterns != null) { patterns.ItemChanged += PatternsItemChanged; } } /// <summary> /// Occurs before the pattern list is set so that we can stop listening /// for messages from the old outline. /// </summary> protected virtual void OnIgnorePatternEvents() { IChangeEventList<IPattern> patterns = Patterns as IChangeEventList<IPattern>; if (patterns != null) { patterns.ItemChanged -= PatternsItemChanged; } } private void PatternsItemChanged(object sender, EventArgs e) { OnItemChanged(); } #endregion } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="AssemblyExtensions.cs" company="Catel development team"> // Copyright (c) 2008 - 2015 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Catel.Reflection { using Catel; using System; using System.Reflection; /// <summary> /// Assembly info helper class. /// </summary> public static class AssemblyExtensions { #if NET /// <summary> /// Gets the build date time of the assembly. /// </summary> /// <param name="assembly">The assembly.</param> /// <returns>DateTime.</returns> public static DateTime GetBuildDateTime(this Assembly assembly) { Argument.IsNotNull(() => assembly); return AssemblyHelper.GetLinkerTimestamp(assembly.Location); } #endif /// <summary> /// Gets the title of a specific assembly. /// </summary> /// <param name="assembly">The assembly.</param> /// <returns>The title of the assembly.</returns> public static string Title(this Assembly assembly) { string title = GetAssemblyAttributeValue(assembly, typeof(AssemblyTitleAttribute), "Title"); if (!string.IsNullOrEmpty(title)) { return title; } #if NET return System.IO.Path.GetFileNameWithoutExtension(assembly.CodeBase); #else throw new NotSupportedInPlatformException(); #endif } /// <summary> /// Gets the version of a specific assembly with a separator count. /// </summary> /// <param name="assembly">The assembly.</param> /// <param name="separatorCount">Number that determines how many version numbers should be returned.</param> /// <returns>The version of the assembly.</returns> public static string Version(this Assembly assembly, int separatorCount = 3) { separatorCount++; // Get full name, which is in [name], Version=[version], Culture=[culture], PublicKeyToken=[publickeytoken] format string assemblyFullName = assembly.FullName; string[] splittedAssemblyFullName = assemblyFullName.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (splittedAssemblyFullName.Length < 2) { return "unknown"; } string version = splittedAssemblyFullName[1].Replace("Version=", string.Empty).Trim(); string[] versionSplit = version.Split('.'); version = versionSplit[0]; for (int i = 1; i < separatorCount; i++) { if (i >= versionSplit.Length) { break; } version += string.Format(".{0}", versionSplit[i]); } return version; } /// <summary> /// Gets the informational version. /// </summary> /// <param name="assembly">The assembly.</param> /// <returns>The informational version.</returns> public static string InformationalVersion(this Assembly assembly) { var version = GetAssemblyAttribute<AssemblyInformationalVersionAttribute>(assembly); return version == null ? null : version.InformationalVersion; } /// <summary> /// Gets the description of a specific assembly. /// </summary> /// <param name="assembly">The assembly.</param> /// <returns>The description of the assembly.</returns> public static string Description(this Assembly assembly) { return GetAssemblyAttributeValue(assembly, typeof(AssemblyDescriptionAttribute), "Description"); } /// <summary> /// Gets the product of a specific assembly. /// </summary> /// <param name="assembly">The assembly.</param> /// <returns>The product of the assembly.</returns> public static string Product(this Assembly assembly) { return GetAssemblyAttributeValue(assembly, typeof(AssemblyProductAttribute), "Product"); } /// <summary> /// Gets the copyright of a specific assembly. /// </summary> /// <param name="assembly">The assembly.</param> /// <returns>The copyright of the assembly.</returns> public static string Copyright(this Assembly assembly) { return GetAssemblyAttributeValue(assembly, typeof(AssemblyCopyrightAttribute), "Copyright"); } /// <summary> /// Gets the company of a specific assembly. /// </summary> /// <param name="assembly">The assembly.</param> /// <returns>The company of the assembly.</returns> public static string Company(this Assembly assembly) { return GetAssemblyAttributeValue(assembly, typeof(AssemblyCompanyAttribute), "Company"); } /// <summary> /// Gets the directory of a specific assembly. /// </summary> /// <param name="assembly">The assembly.</param> /// <returns>The directory of the assembly.</returns> /// <exception cref="ArgumentNullException">The <paramref name="assembly"/> is <c>null</c>.</exception> public static string GetDirectory(this Assembly assembly) { Argument.IsNotNull("assembly", assembly); #if NET string location = assembly.Location; return location.Substring(0, location.LastIndexOf('\\')); #else throw new NotSupportedInPlatformException("Directories are protected"); #endif } /// <summary> /// Gets the assembly attribute. /// </summary> /// <typeparam name="TAttibute">The type of the attribute.</typeparam> /// <param name="assembly">The assembly.</param> /// <returns>The attribute that the assembly is decorated with or <c>null</c> if the assembly is not decorated with the attribute.</returns> private static TAttibute GetAssemblyAttribute<TAttibute>(Assembly assembly) where TAttibute : Attribute { var attibutes = assembly.GetCustomAttributesEx(typeof(TAttibute)); return attibutes.Length > 0 ? attibutes[0] as TAttibute : null; } /// <summary> /// Gets the specific <see cref="Attribute"/> value of the attribute type in the specified assembly. /// </summary> /// <param name="assembly">Assembly to read the information from.</param> /// <param name="attribute">Attribute to read.</param> /// <param name="property">Property to read from the attribute.</param> /// <returns>Value of the attribute or empty if the attribute is not found.</returns> private static string GetAssemblyAttributeValue(Assembly assembly, Type attribute, string property) { var attributes = assembly.GetCustomAttributesEx(attribute); if (attributes.Length == 0) { return string.Empty; } object attributeValue = attributes[0]; if (attributeValue == null) { return string.Empty; } var attributeType = attributeValue.GetType(); var propertyInfo = attributeType.GetPropertyEx(property); if (propertyInfo == null) { return string.Empty; } object propertyValue = propertyInfo.GetValue(attributeValue, null); if (propertyValue == null) { return string.Empty; } return propertyValue.ToString(); } } }
// 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.Text { using System.Runtime.Serialization; using System.Text; using System; using System.Diagnostics.Contracts; // A Decoder is used to decode a sequence of blocks of bytes into a // sequence of blocks of characters. Following instantiation of a decoder, // sequential blocks of bytes are converted into blocks of characters through // calls to the GetChars method. The decoder maintains state between the // conversions, allowing it to correctly decode byte sequences that span // adjacent blocks. // // Instances of specific implementations of the Decoder abstract base // class are typically obtained through calls to the GetDecoder method // of Encoding objects. // [System.Runtime.InteropServices.ComVisible(true)] [Serializable] public abstract class Decoder { internal DecoderFallback m_fallback = null; [NonSerialized] internal DecoderFallbackBuffer m_fallbackBuffer = null; internal void SerializeDecoder(SerializationInfo info) { info.AddValue("m_fallback", this.m_fallback); } protected Decoder( ) { // We don't call default reset because default reset probably isn't good if we aren't initialized. } [System.Runtime.InteropServices.ComVisible(false)] public DecoderFallback Fallback { get { return m_fallback; } set { if (value == null) throw new ArgumentNullException("value"); Contract.EndContractBlock(); // Can't change fallback if buffer is wrong if (m_fallbackBuffer != null && m_fallbackBuffer.Remaining > 0) throw new ArgumentException( Environment.GetResourceString("Argument_FallbackBufferNotEmpty"), "value"); m_fallback = value; m_fallbackBuffer = null; } } // Note: we don't test for threading here because async access to Encoders and Decoders // doesn't work anyway. [System.Runtime.InteropServices.ComVisible(false)] public DecoderFallbackBuffer FallbackBuffer { get { if (m_fallbackBuffer == null) { if (m_fallback != null) m_fallbackBuffer = m_fallback.CreateFallbackBuffer(); else m_fallbackBuffer = DecoderFallback.ReplacementFallback.CreateFallbackBuffer(); } return m_fallbackBuffer; } } internal bool InternalHasFallbackBuffer { get { return m_fallbackBuffer != null; } } // Reset the Decoder // // Normally if we call GetChars() and an error is thrown we don't change the state of the Decoder. This // would allow the caller to correct the error condition and try again (such as if they need a bigger buffer.) // // If the caller doesn't want to try again after GetChars() throws an error, then they need to call Reset(). // // Virtual implimentation has to call GetChars with flush and a big enough buffer to clear a 0 byte string // We avoid GetMaxCharCount() because a) we can't call the base encoder and b) it might be really big. [System.Runtime.InteropServices.ComVisible(false)] public virtual void Reset() { byte[] byteTemp = {}; char[] charTemp = new char[GetCharCount(byteTemp, 0, 0, true)]; GetChars(byteTemp, 0, 0, charTemp, 0, true); if (m_fallbackBuffer != null) m_fallbackBuffer.Reset(); } // Returns the number of characters the next call to GetChars will // produce if presented with the given range of bytes. The returned value // takes into account the state in which the decoder was left following the // last call to GetChars. The state of the decoder is not affected // by a call to this method. // public abstract int GetCharCount(byte[] bytes, int index, int count); [System.Runtime.InteropServices.ComVisible(false)] public virtual int GetCharCount(byte[] bytes, int index, int count, bool flush) { return GetCharCount(bytes, index, count); } // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implimentation) [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public virtual unsafe int GetCharCount(byte* bytes, int count, bool flush) { // Validate input parameters if (bytes == null) throw new ArgumentNullException("bytes", Environment.GetResourceString("ArgumentNull_Array")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); byte[] arrbyte = new byte[count]; int index; for (index = 0; index < count; index++) arrbyte[index] = bytes[index]; return GetCharCount(arrbyte, 0, count); } // Decodes a range of bytes in a byte array into a range of characters // in a character array. The method decodes byteCount bytes from // bytes starting at index byteIndex, storing the resulting // characters in chars starting at index charIndex. The // decoding takes into account the state in which the decoder was left // following the last call to this method. // // An exception occurs if the character array is not large enough to // hold the complete decoding of the bytes. The GetCharCount method // can be used to determine the exact number of characters that will be // produced for a given range of bytes. Alternatively, the // GetMaxCharCount method of the Encoding that produced this // decoder can be used to determine the maximum number of characters that // will be produced for a given number of bytes, regardless of the actual // byte values. // public abstract int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex); public virtual int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { return GetChars(bytes, byteIndex, byteCount, chars, charIndex); } // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implimentation) // // WARNING WARNING WARNING // // WARNING: If this breaks it could be a security threat. Obviously we // call this internally, so you need to make sure that your pointers, counts // and indexes are correct when you call this method. // // In addition, we have internal code, which will be marked as "safe" calling // this code. However this code is dependent upon the implimentation of an // external GetChars() method, which could be overridden by a third party and // the results of which cannot be guaranteed. We use that result to copy // the char[] to our char* output buffer. If the result count was wrong, we // could easily overflow our output buffer. Therefore we do an extra test // when we copy the buffer so that we don't overflow charCount either. [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public virtual unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { // Validate input parameters if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? "chars" : "bytes", Environment.GetResourceString("ArgumentNull_Array")); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount<0 ? "byteCount" : "charCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); // Get the byte array to convert byte[] arrByte = new byte[byteCount]; int index; for (index = 0; index < byteCount; index++) arrByte[index] = bytes[index]; // Get the char array to fill char[] arrChar = new char[charCount]; // Do the work int result = GetChars(arrByte, 0, byteCount, arrChar, 0, flush); Contract.Assert(result <= charCount, "Returned more chars than we have space for"); // Copy the char array // WARNING: We MUST make sure that we don't copy too many chars. We can't // rely on result because it could be a 3rd party implimentation. We need // to make sure we never copy more than charCount chars no matter the value // of result if (result < charCount) charCount = result; // We check both result and charCount so that we don't accidentally overrun // our pointer buffer just because of an issue in GetChars for (index = 0; index < charCount; index++) chars[index] = arrChar[index]; return charCount; } // This method is used when the output buffer might not be large enough. // It will decode until it runs out of bytes, and then it will return // true if it the entire input was converted. In either case it // will also return the number of converted bytes and output characters used. // It will only throw a buffer overflow exception if the entire lenght of chars[] is // too small to store the next char. (like 0 or maybe 1 or 4 for some encodings) // We're done processing this buffer only if completed returns true. // // Might consider checking Max...Count to avoid the extra counting step. // // Note that if all of the input bytes are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many bytes as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) [System.Runtime.InteropServices.ComVisible(false)] public virtual void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate parameters if (bytes == null || chars == null) throw new ArgumentNullException((bytes == null ? "bytes" : "chars"), Environment.GetResourceString("ArgumentNull_Array")); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex<0 ? "byteIndex" : "byteCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex<0 ? "charIndex" : "charCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException("bytes", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException("chars", Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); Contract.EndContractBlock(); bytesUsed = byteCount; // Its easy to do if it won't overrun our buffer. while (bytesUsed > 0) { if (GetCharCount(bytes, byteIndex, bytesUsed, flush) <= charCount) { charsUsed = GetChars(bytes, byteIndex, bytesUsed, chars, charIndex, flush); completed = (bytesUsed == byteCount && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0)); return; } // Try again with 1/2 the count, won't flush then 'cause won't read it all flush = false; bytesUsed /= 2; } // Oops, we didn't have anything, we'll have to throw an overflow throw new ArgumentException(Environment.GetResourceString("Argument_ConversionOverflow")); } // This is the version that uses *. // We're done processing this buffer only if completed returns true. // // Might consider checking Max...Count to avoid the extra counting step. // // Note that if all of the input bytes are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many bytes as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) [System.Security.SecurityCritical] // auto-generated [CLSCompliant(false)] [System.Runtime.InteropServices.ComVisible(false)] public virtual unsafe void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate input parameters if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? "chars" : "bytes", Environment.GetResourceString("ArgumentNull_Array")); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount<0 ? "byteCount" : "charCount"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); // Get ready to do it bytesUsed = byteCount; // Its easy to do if it won't overrun our buffer. while (bytesUsed > 0) { if (GetCharCount(bytes, bytesUsed, flush) <= charCount) { charsUsed = GetChars(bytes, bytesUsed, chars, charCount, flush); completed = (bytesUsed == byteCount && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0)); return; } // Try again with 1/2 the count, won't flush then 'cause won't read it all flush = false; bytesUsed /= 2; } // Oops, we didn't have anything, we'll have to throw an overflow throw new ArgumentException(Environment.GetResourceString("Argument_ConversionOverflow")); } } }
using AOT; using System; using System.Collections; using System.IO; using System.Runtime.InteropServices; using System.Collections.Generic; using UnityEngine; namespace NativeScript { /// <summary> /// Internals of the bindings between native and .NET code. /// Game code shouldn't go here. /// </summary> /// <author> /// Jackson Dunstan, 2017, http://JacksonDunstan.com /// </author> /// <license> /// MIT /// </license> public static class Bindings { // Holds objects and provides handles to them in the form of ints public static class ObjectStore { // Lookup handles by object. static Dictionary<object, int> objectHandleCache; // Stored objects. The first is never used so 0 can be "null". static object[] objects; // Stack of available handles. static int[] handles; // Index of the next available handle static int nextHandleIndex; // The maximum number of objects to store. Must be positive. static int maxObjects; public static void Init(int maxObjects) { ObjectStore.maxObjects = maxObjects; objectHandleCache = new Dictionary<object, int>(maxObjects); // Initialize the objects as all null plus room for the // first to always be null. objects = new object[maxObjects + 1]; // Initialize the handles stack as 1, 2, 3, ... handles = new int[maxObjects]; for ( int i = 0, handle = maxObjects; i < maxObjects; ++i, --handle) { handles[i] = handle; } nextHandleIndex = maxObjects - 1; } public static int Store(object obj) { // Null is always zero if (object.ReferenceEquals(obj, null)) { return 0; } lock (objects) { // Pop a handle off the stack int handle = handles[nextHandleIndex]; nextHandleIndex--; // Store the object objects[handle] = obj; objectHandleCache.Add(obj, handle); return handle; } } public static object Get(int handle) { return objects[handle]; } public static int GetHandle(object obj) { // Null is always zero if (object.ReferenceEquals(obj, null)) { return 0; } lock (objects) { int handle; // Get handle from object cache if (objectHandleCache.TryGetValue(obj, out handle)) { return handle; } } // Object not found return Store(obj); } public static object Remove(int handle) { // Null is never stored, so there's nothing to remove if (handle == 0) { return null; } lock (objects) { // Forget the object object obj = objects[handle]; objects[handle] = null; // Push the handle onto the stack nextHandleIndex++; handles[nextHandleIndex] = handle; // Remove the object from the cache objectHandleCache.Remove(obj); return obj; } } } // Holds structs and provides handles to them in the form of ints public static class StructStore<T> where T : struct { // Stored structs. The first is never used so 0 can be "null". static T[] structs; // Stack of available handles static int[] handles; // Index of the next available handle static int nextHandleIndex; public static void Init(int maxStructs) { // Initialize the objects as all default plus room for the // first to always be unused. structs = new T[maxStructs + 1]; // Initialize the handles stack as 1, 2, 3, ... handles = new int[maxStructs]; for ( int i = 0, handle = maxStructs; i < maxStructs; ++i, --handle) { handles[i] = handle; } nextHandleIndex = maxStructs - 1; } public static int Store(T structToStore) { lock (structs) { // Pop a handle off the stack int handle = handles[nextHandleIndex]; nextHandleIndex--; // Store the struct structs[handle] = structToStore; return handle; } } public static void Replace(int handle, ref T structToStore) { structs[handle] = structToStore; } public static T Get(int handle) { return structs[handle]; } public static void Remove(int handle) { if (handle != 0) { lock (structs) { // Forget the struct structs[handle] = default(T); // Push the handle onto the stack nextHandleIndex++; handles[nextHandleIndex] = handle; } } } } /// <summary> /// A reusable version of UnityEngine.WaitForSecondsRealtime to avoid /// GC allocs /// </summary> class ReusableWaitForSecondsRealtime : CustomYieldInstruction { private float waitTime; public float WaitTime { set { waitTime = Time.realtimeSinceStartup + value; } } public override bool keepWaiting { get { return Time.realtimeSinceStartup < waitTime; } } public ReusableWaitForSecondsRealtime(float time) { WaitTime = time; } } public enum DestroyFunction { /*BEGIN DESTROY FUNCTION ENUMERATORS*/ BaseBallScript /*END DESTROY FUNCTION ENUMERATORS*/ } struct DestroyEntry { public DestroyFunction Function; public int CppHandle; public DestroyEntry(DestroyFunction function, int cppHandle) { Function = function; CppHandle = cppHandle; } } // Name of the plugin when using [DllImport] #if !UNITY_EDITOR && UNITY_IOS const string PLUGIN_NAME = "__Internal"; #else const string PLUGIN_NAME = "NativeScript"; #endif // Path to load the plugin from when running inside the editor #if UNITY_EDITOR_OSX const string PLUGIN_PATH = "/Plugins/Editor/NativeScript.bundle/Contents/MacOS/NativeScript"; #elif UNITY_EDITOR_LINUX const string PLUGIN_PATH = "/Plugins/Editor/libNativeScript.so"; #elif UNITY_EDITOR_WIN const string PLUGIN_PATH = "/Plugins/Editor/NativeScript.dll"; const string PLUGIN_TEMP_PATH = "/Plugins/Editor/NativeScript_temp.dll"; #endif enum InitMode : byte { FirstBoot, Reload } #if UNITY_EDITOR // Handle to the C++ DLL static IntPtr libraryHandle; [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void InitDelegate( IntPtr memory, int memorySize, InitMode initMode); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void SetCsharpExceptionDelegate(int handle); /*BEGIN CPP DELEGATES*/ [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate int NewBaseBallScriptDelegateType(int param0); public static NewBaseBallScriptDelegateType NewBaseBallScript; [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void DestroyBaseBallScriptDelegateType(int param0); public static DestroyBaseBallScriptDelegateType DestroyBaseBallScript; [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void MyGameAbstractBaseBallScriptUpdateDelegateType(int thisHandle); public static MyGameAbstractBaseBallScriptUpdateDelegateType MyGameAbstractBaseBallScriptUpdate; [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void SetCsharpExceptionSystemNullReferenceExceptionDelegateType(int param0); public static SetCsharpExceptionSystemNullReferenceExceptionDelegateType SetCsharpExceptionSystemNullReferenceException; /*END CPP DELEGATES*/ #endif #if UNITY_EDITOR_OSX || UNITY_EDITOR_LINUX [DllImport("__Internal", CallingConvention = CallingConvention.Cdecl)] static extern IntPtr dlopen( string path, int flag); [DllImport("__Internal", CallingConvention = CallingConvention.Cdecl)] static extern IntPtr dlsym( IntPtr handle, string symbolName); [DllImport("__Internal", CallingConvention = CallingConvention.Cdecl)] static extern int dlclose( IntPtr handle); static IntPtr OpenLibrary( string path) { IntPtr handle = dlopen(path, 1); // 1 = lazy, 2 = now if (handle == IntPtr.Zero) { throw new Exception("Couldn't open native library: " + path); } return handle; } static void CloseLibrary( IntPtr libraryHandle) { dlclose(libraryHandle); } static T GetDelegate<T>( IntPtr libraryHandle, string functionName) where T : class { IntPtr symbol = dlsym(libraryHandle, functionName); if (symbol == IntPtr.Zero) { throw new Exception("Couldn't get function: " + functionName); } return Marshal.GetDelegateForFunctionPointer( symbol, typeof(T)) as T; } #elif UNITY_EDITOR_WIN [DllImport("kernel32", SetLastError=true, CharSet = CharSet.Ansi)] static extern IntPtr LoadLibrary( string path); [DllImport("kernel32", CharSet=CharSet.Ansi, ExactSpelling=true, SetLastError=true)] static extern IntPtr GetProcAddress( IntPtr libraryHandle, string symbolName); [DllImport("kernel32.dll", SetLastError=true)] static extern bool FreeLibrary( IntPtr libraryHandle); static IntPtr OpenLibrary(string path) { IntPtr handle = LoadLibrary(path); if (handle == IntPtr.Zero) { throw new Exception("Couldn't open native library: " + path); } return handle; } static void CloseLibrary(IntPtr libraryHandle) { FreeLibrary(libraryHandle); } static T GetDelegate<T>( IntPtr libraryHandle, string functionName) where T : class { IntPtr symbol = GetProcAddress(libraryHandle, functionName); if (symbol == IntPtr.Zero) { throw new Exception("Couldn't get function: " + functionName); } return Marshal.GetDelegateForFunctionPointer( symbol, typeof(T)) as T; } #else [DllImport(PLUGIN_NAME, CallingConvention = CallingConvention.Cdecl)] static extern void Init( IntPtr memory, int memorySize, InitMode initMode); [DllImport(PLUGIN_NAME, CallingConvention = CallingConvention.Cdecl)] static extern void SetCsharpException(int handle); /*BEGIN IMPORTS*/ [DllImport(PLUGIN_NAME, CallingConvention = CallingConvention.Cdecl)] public static extern int NewBaseBallScript(int thisHandle); [DllImport(PLUGIN_NAME, CallingConvention = CallingConvention.Cdecl)] public static extern void DestroyBaseBallScript(int thisHandle); [DllImport(PLUGIN_NAME, CallingConvention = CallingConvention.Cdecl)] public static extern void MyGameAbstractBaseBallScriptUpdate(int thisHandle); [DllImport(PLUGIN_NAME, CallingConvention = CallingConvention.Cdecl)] public static extern void SetCsharpExceptionSystemNullReferenceException(int thisHandle); /*END IMPORTS*/ #endif [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void ReleaseObjectDelegateType(int handle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int StringNewDelegateType(string chars); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void SetExceptionDelegateType(int handle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int ArrayGetLengthDelegateType(int handle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int EnumerableGetEnumeratorDelegateType(int handle); /*BEGIN DELEGATE TYPES*/ [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void ReleaseSystemDecimalDelegateType(int handle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int SystemDecimalConstructorSystemDoubleDelegateType(double value); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int SystemDecimalConstructorSystemUInt64DelegateType(ulong value); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int BoxDecimalDelegateType(int valHandle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int UnboxDecimalDelegateType(int valHandle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate UnityEngine.Vector3 UnityEngineVector3ConstructorSystemSingle_SystemSingle_SystemSingleDelegateType(float x, float y, float z); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate UnityEngine.Vector3 UnityEngineVector3Methodop_AdditionUnityEngineVector3_UnityEngineVector3DelegateType(ref UnityEngine.Vector3 a, ref UnityEngine.Vector3 b); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int BoxVector3DelegateType(ref UnityEngine.Vector3 val); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate UnityEngine.Vector3 UnboxVector3DelegateType(int valHandle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int UnityEngineObjectPropertyGetNameDelegateType(int thisHandle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void UnityEngineObjectPropertySetNameDelegateType(int thisHandle, int valueHandle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int UnityEngineComponentPropertyGetTransformDelegateType(int thisHandle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate UnityEngine.Vector3 UnityEngineTransformPropertyGetPositionDelegateType(int thisHandle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void UnityEngineTransformPropertySetPositionDelegateType(int thisHandle, ref UnityEngine.Vector3 value); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int SystemCollectionsIEnumeratorPropertyGetCurrentDelegateType(int thisHandle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate bool SystemCollectionsIEnumeratorMethodMoveNextDelegateType(int thisHandle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int UnityEngineGameObjectMethodAddComponentMyGameBaseBallScriptDelegateType(int thisHandle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int UnityEngineGameObjectMethodCreatePrimitiveUnityEnginePrimitiveTypeDelegateType(UnityEngine.PrimitiveType type); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void UnityEngineDebugMethodLogSystemObjectDelegateType(int messageHandle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int UnityEngineMonoBehaviourPropertyGetTransformDelegateType(int thisHandle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int SystemExceptionConstructorSystemStringDelegateType(int messageHandle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int BoxPrimitiveTypeDelegateType(UnityEngine.PrimitiveType val); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate UnityEngine.PrimitiveType UnboxPrimitiveTypeDelegateType(int valHandle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate float UnityEngineTimePropertyGetDeltaTimeDelegateType(); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void BaseBallScriptConstructorDelegateType(int cppHandle, ref int handle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void ReleaseBaseBallScriptDelegateType(int handle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int BoxBooleanDelegateType(bool val); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate bool UnboxBooleanDelegateType(int valHandle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int BoxSByteDelegateType(sbyte val); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate sbyte UnboxSByteDelegateType(int valHandle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int BoxByteDelegateType(byte val); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate byte UnboxByteDelegateType(int valHandle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int BoxInt16DelegateType(short val); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate short UnboxInt16DelegateType(int valHandle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int BoxUInt16DelegateType(ushort val); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate ushort UnboxUInt16DelegateType(int valHandle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int BoxInt32DelegateType(int val); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int UnboxInt32DelegateType(int valHandle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int BoxUInt32DelegateType(uint val); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate uint UnboxUInt32DelegateType(int valHandle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int BoxInt64DelegateType(long val); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate long UnboxInt64DelegateType(int valHandle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int BoxUInt64DelegateType(ulong val); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate ulong UnboxUInt64DelegateType(int valHandle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int BoxCharDelegateType(char val); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate char UnboxCharDelegateType(int valHandle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int BoxSingleDelegateType(float val); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate float UnboxSingleDelegateType(int valHandle); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate int BoxDoubleDelegateType(double val); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate double UnboxDoubleDelegateType(int valHandle); /*END DELEGATE TYPES*/ #if UNITY_EDITOR_WIN private static readonly string pluginTempPath = Application.dataPath + PLUGIN_TEMP_PATH; #endif public static Exception UnhandledCppException; #if UNITY_EDITOR private static readonly string pluginPath = Application.dataPath + PLUGIN_PATH; public static SetCsharpExceptionDelegate SetCsharpException; #endif static IntPtr memory; static int memorySize; static DestroyEntry[] destroyQueue; static int destroyQueueCount; static int destroyQueueCapacity; static object destroyQueueLockObj; // Fixed delegates static readonly ReleaseObjectDelegateType ReleaseObjectDelegate = new ReleaseObjectDelegateType(ReleaseObject); static readonly StringNewDelegateType StringNewDelegate = new StringNewDelegateType(StringNew); static readonly SetExceptionDelegateType SetExceptionDelegate = new SetExceptionDelegateType(SetException); static readonly ArrayGetLengthDelegateType ArrayGetLengthDelegate = new ArrayGetLengthDelegateType(ArrayGetLength); static readonly EnumerableGetEnumeratorDelegateType EnumerableGetEnumeratorDelegate = new EnumerableGetEnumeratorDelegateType(EnumerableGetEnumerator); // Generated delegates /*BEGIN CSHARP DELEGATES*/ static readonly ReleaseSystemDecimalDelegateType ReleaseSystemDecimalDelegate = new ReleaseSystemDecimalDelegateType(ReleaseSystemDecimal); static readonly SystemDecimalConstructorSystemDoubleDelegateType SystemDecimalConstructorSystemDoubleDelegate = new SystemDecimalConstructorSystemDoubleDelegateType(SystemDecimalConstructorSystemDouble); static readonly SystemDecimalConstructorSystemUInt64DelegateType SystemDecimalConstructorSystemUInt64Delegate = new SystemDecimalConstructorSystemUInt64DelegateType(SystemDecimalConstructorSystemUInt64); static readonly BoxDecimalDelegateType BoxDecimalDelegate = new BoxDecimalDelegateType(BoxDecimal); static readonly UnboxDecimalDelegateType UnboxDecimalDelegate = new UnboxDecimalDelegateType(UnboxDecimal); static readonly UnityEngineVector3ConstructorSystemSingle_SystemSingle_SystemSingleDelegateType UnityEngineVector3ConstructorSystemSingle_SystemSingle_SystemSingleDelegate = new UnityEngineVector3ConstructorSystemSingle_SystemSingle_SystemSingleDelegateType(UnityEngineVector3ConstructorSystemSingle_SystemSingle_SystemSingle); static readonly UnityEngineVector3Methodop_AdditionUnityEngineVector3_UnityEngineVector3DelegateType UnityEngineVector3Methodop_AdditionUnityEngineVector3_UnityEngineVector3Delegate = new UnityEngineVector3Methodop_AdditionUnityEngineVector3_UnityEngineVector3DelegateType(UnityEngineVector3Methodop_AdditionUnityEngineVector3_UnityEngineVector3); static readonly BoxVector3DelegateType BoxVector3Delegate = new BoxVector3DelegateType(BoxVector3); static readonly UnboxVector3DelegateType UnboxVector3Delegate = new UnboxVector3DelegateType(UnboxVector3); static readonly UnityEngineObjectPropertyGetNameDelegateType UnityEngineObjectPropertyGetNameDelegate = new UnityEngineObjectPropertyGetNameDelegateType(UnityEngineObjectPropertyGetName); static readonly UnityEngineObjectPropertySetNameDelegateType UnityEngineObjectPropertySetNameDelegate = new UnityEngineObjectPropertySetNameDelegateType(UnityEngineObjectPropertySetName); static readonly UnityEngineComponentPropertyGetTransformDelegateType UnityEngineComponentPropertyGetTransformDelegate = new UnityEngineComponentPropertyGetTransformDelegateType(UnityEngineComponentPropertyGetTransform); static readonly UnityEngineTransformPropertyGetPositionDelegateType UnityEngineTransformPropertyGetPositionDelegate = new UnityEngineTransformPropertyGetPositionDelegateType(UnityEngineTransformPropertyGetPosition); static readonly UnityEngineTransformPropertySetPositionDelegateType UnityEngineTransformPropertySetPositionDelegate = new UnityEngineTransformPropertySetPositionDelegateType(UnityEngineTransformPropertySetPosition); static readonly SystemCollectionsIEnumeratorPropertyGetCurrentDelegateType SystemCollectionsIEnumeratorPropertyGetCurrentDelegate = new SystemCollectionsIEnumeratorPropertyGetCurrentDelegateType(SystemCollectionsIEnumeratorPropertyGetCurrent); static readonly SystemCollectionsIEnumeratorMethodMoveNextDelegateType SystemCollectionsIEnumeratorMethodMoveNextDelegate = new SystemCollectionsIEnumeratorMethodMoveNextDelegateType(SystemCollectionsIEnumeratorMethodMoveNext); static readonly UnityEngineGameObjectMethodAddComponentMyGameBaseBallScriptDelegateType UnityEngineGameObjectMethodAddComponentMyGameBaseBallScriptDelegate = new UnityEngineGameObjectMethodAddComponentMyGameBaseBallScriptDelegateType(UnityEngineGameObjectMethodAddComponentMyGameBaseBallScript); static readonly UnityEngineGameObjectMethodCreatePrimitiveUnityEnginePrimitiveTypeDelegateType UnityEngineGameObjectMethodCreatePrimitiveUnityEnginePrimitiveTypeDelegate = new UnityEngineGameObjectMethodCreatePrimitiveUnityEnginePrimitiveTypeDelegateType(UnityEngineGameObjectMethodCreatePrimitiveUnityEnginePrimitiveType); static readonly UnityEngineDebugMethodLogSystemObjectDelegateType UnityEngineDebugMethodLogSystemObjectDelegate = new UnityEngineDebugMethodLogSystemObjectDelegateType(UnityEngineDebugMethodLogSystemObject); static readonly UnityEngineMonoBehaviourPropertyGetTransformDelegateType UnityEngineMonoBehaviourPropertyGetTransformDelegate = new UnityEngineMonoBehaviourPropertyGetTransformDelegateType(UnityEngineMonoBehaviourPropertyGetTransform); static readonly SystemExceptionConstructorSystemStringDelegateType SystemExceptionConstructorSystemStringDelegate = new SystemExceptionConstructorSystemStringDelegateType(SystemExceptionConstructorSystemString); static readonly BoxPrimitiveTypeDelegateType BoxPrimitiveTypeDelegate = new BoxPrimitiveTypeDelegateType(BoxPrimitiveType); static readonly UnboxPrimitiveTypeDelegateType UnboxPrimitiveTypeDelegate = new UnboxPrimitiveTypeDelegateType(UnboxPrimitiveType); static readonly UnityEngineTimePropertyGetDeltaTimeDelegateType UnityEngineTimePropertyGetDeltaTimeDelegate = new UnityEngineTimePropertyGetDeltaTimeDelegateType(UnityEngineTimePropertyGetDeltaTime); static readonly ReleaseBaseBallScriptDelegateType ReleaseBaseBallScriptDelegate = new ReleaseBaseBallScriptDelegateType(ReleaseBaseBallScript); static readonly BaseBallScriptConstructorDelegateType BaseBallScriptConstructorDelegate = new BaseBallScriptConstructorDelegateType(BaseBallScriptConstructor); static readonly BoxBooleanDelegateType BoxBooleanDelegate = new BoxBooleanDelegateType(BoxBoolean); static readonly UnboxBooleanDelegateType UnboxBooleanDelegate = new UnboxBooleanDelegateType(UnboxBoolean); static readonly BoxSByteDelegateType BoxSByteDelegate = new BoxSByteDelegateType(BoxSByte); static readonly UnboxSByteDelegateType UnboxSByteDelegate = new UnboxSByteDelegateType(UnboxSByte); static readonly BoxByteDelegateType BoxByteDelegate = new BoxByteDelegateType(BoxByte); static readonly UnboxByteDelegateType UnboxByteDelegate = new UnboxByteDelegateType(UnboxByte); static readonly BoxInt16DelegateType BoxInt16Delegate = new BoxInt16DelegateType(BoxInt16); static readonly UnboxInt16DelegateType UnboxInt16Delegate = new UnboxInt16DelegateType(UnboxInt16); static readonly BoxUInt16DelegateType BoxUInt16Delegate = new BoxUInt16DelegateType(BoxUInt16); static readonly UnboxUInt16DelegateType UnboxUInt16Delegate = new UnboxUInt16DelegateType(UnboxUInt16); static readonly BoxInt32DelegateType BoxInt32Delegate = new BoxInt32DelegateType(BoxInt32); static readonly UnboxInt32DelegateType UnboxInt32Delegate = new UnboxInt32DelegateType(UnboxInt32); static readonly BoxUInt32DelegateType BoxUInt32Delegate = new BoxUInt32DelegateType(BoxUInt32); static readonly UnboxUInt32DelegateType UnboxUInt32Delegate = new UnboxUInt32DelegateType(UnboxUInt32); static readonly BoxInt64DelegateType BoxInt64Delegate = new BoxInt64DelegateType(BoxInt64); static readonly UnboxInt64DelegateType UnboxInt64Delegate = new UnboxInt64DelegateType(UnboxInt64); static readonly BoxUInt64DelegateType BoxUInt64Delegate = new BoxUInt64DelegateType(BoxUInt64); static readonly UnboxUInt64DelegateType UnboxUInt64Delegate = new UnboxUInt64DelegateType(UnboxUInt64); static readonly BoxCharDelegateType BoxCharDelegate = new BoxCharDelegateType(BoxChar); static readonly UnboxCharDelegateType UnboxCharDelegate = new UnboxCharDelegateType(UnboxChar); static readonly BoxSingleDelegateType BoxSingleDelegate = new BoxSingleDelegateType(BoxSingle); static readonly UnboxSingleDelegateType UnboxSingleDelegate = new UnboxSingleDelegateType(UnboxSingle); static readonly BoxDoubleDelegateType BoxDoubleDelegate = new BoxDoubleDelegateType(BoxDouble); static readonly UnboxDoubleDelegateType UnboxDoubleDelegate = new UnboxDoubleDelegateType(UnboxDouble); /*END CSHARP DELEGATES*/ /// <summary> /// Open the C++ plugin and call its PluginMain() /// </summary> /// /// <param name="memorySize"> /// Number of bytes of memory to make available to the C++ plugin /// </param> public static void Open(int memorySize) { /*BEGIN STORE INIT CALLS*/ NativeScript.Bindings.ObjectStore.Init(1000); NativeScript.Bindings.StructStore<System.Decimal>.Init(1000); /*END STORE INIT CALLS*/ // Allocate unmanaged memory Bindings.memorySize = memorySize; memory = Marshal.AllocHGlobal(memorySize); // Allocate destroy queue destroyQueueCapacity = 128; destroyQueue = new DestroyEntry[destroyQueueCapacity]; destroyQueueLockObj = new object(); OpenPlugin(InitMode.FirstBoot); } // Reloading requires dynamic loading of the C++ plugin, which is only // available in the editor #if UNITY_EDITOR /// <summary> /// Reload the C++ plugin. Its memory is intact and false is passed for /// the isFirstBoot parameter of PluginMain(). /// </summary> public static void Reload() { DestroyAll(); ClosePlugin(); OpenPlugin(InitMode.Reload); } /// <summary> /// Poll the plugin for changes and reload if any are found. /// </summary> /// /// <param name="pollTime"> /// Number of seconds between polls. /// </param> /// /// <returns> /// Enumerator for this iterator function. Can be passed to /// MonoBehaviour.StartCoroutine for easy usage. /// </returns> public static IEnumerator AutoReload(float pollTime) { // Get the original time long lastWriteTime = File.GetLastWriteTime(pluginPath).Ticks; ReusableWaitForSecondsRealtime poll = new ReusableWaitForSecondsRealtime(pollTime); do { // Poll. Reload if the last write time changed. long cur = File.GetLastWriteTime(pluginPath).Ticks; if (cur != lastWriteTime) { lastWriteTime = cur; Reload(); } // Wait to poll again poll.WaitTime = pollTime; yield return poll; } while (true); } #endif private static void OpenPlugin(InitMode initMode) { #if UNITY_EDITOR string loadPath; #if UNITY_EDITOR_WIN // Copy native library to temporary file File.Copy(pluginPath, pluginTempPath, true); loadPath = pluginTempPath; #else loadPath = pluginPath; #endif // Open native library libraryHandle = OpenLibrary(loadPath); InitDelegate Init = GetDelegate<InitDelegate>( libraryHandle, "Init"); SetCsharpException = GetDelegate<SetCsharpExceptionDelegate>( libraryHandle, "SetCsharpException"); /*BEGIN GETDELEGATE CALLS*/ NewBaseBallScript = GetDelegate<NewBaseBallScriptDelegateType>(libraryHandle, "NewBaseBallScript"); DestroyBaseBallScript = GetDelegate<DestroyBaseBallScriptDelegateType>(libraryHandle, "DestroyBaseBallScript"); MyGameAbstractBaseBallScriptUpdate = GetDelegate<MyGameAbstractBaseBallScriptUpdateDelegateType>(libraryHandle, "MyGameAbstractBaseBallScriptUpdate"); SetCsharpExceptionSystemNullReferenceException = GetDelegate<SetCsharpExceptionSystemNullReferenceExceptionDelegateType>(libraryHandle, "SetCsharpExceptionSystemNullReferenceException"); /*END GETDELEGATE CALLS*/ #endif // Pass parameters through 'memory' int curMemory = 0; Marshal.WriteIntPtr( memory, curMemory, Marshal.GetFunctionPointerForDelegate(ReleaseObjectDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr( memory, curMemory, Marshal.GetFunctionPointerForDelegate(StringNewDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr( memory, curMemory, Marshal.GetFunctionPointerForDelegate(SetExceptionDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr( memory, curMemory, Marshal.GetFunctionPointerForDelegate(ArrayGetLengthDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr( memory, curMemory, Marshal.GetFunctionPointerForDelegate(EnumerableGetEnumeratorDelegate)); curMemory += IntPtr.Size; /*BEGIN INIT CALL*/ Marshal.WriteInt32(memory, curMemory, 1000); // max managed objects curMemory += sizeof(int); Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(ReleaseSystemDecimalDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(SystemDecimalConstructorSystemDoubleDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(SystemDecimalConstructorSystemUInt64Delegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(BoxDecimalDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnboxDecimalDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnityEngineVector3ConstructorSystemSingle_SystemSingle_SystemSingleDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnityEngineVector3Methodop_AdditionUnityEngineVector3_UnityEngineVector3Delegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(BoxVector3Delegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnboxVector3Delegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnityEngineObjectPropertyGetNameDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnityEngineObjectPropertySetNameDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnityEngineComponentPropertyGetTransformDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnityEngineTransformPropertyGetPositionDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnityEngineTransformPropertySetPositionDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(SystemCollectionsIEnumeratorPropertyGetCurrentDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(SystemCollectionsIEnumeratorMethodMoveNextDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnityEngineGameObjectMethodAddComponentMyGameBaseBallScriptDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnityEngineGameObjectMethodCreatePrimitiveUnityEnginePrimitiveTypeDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnityEngineDebugMethodLogSystemObjectDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnityEngineMonoBehaviourPropertyGetTransformDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(SystemExceptionConstructorSystemStringDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(BoxPrimitiveTypeDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnboxPrimitiveTypeDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnityEngineTimePropertyGetDeltaTimeDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(ReleaseBaseBallScriptDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(BaseBallScriptConstructorDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(BoxBooleanDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnboxBooleanDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(BoxSByteDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnboxSByteDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(BoxByteDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnboxByteDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(BoxInt16Delegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnboxInt16Delegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(BoxUInt16Delegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnboxUInt16Delegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(BoxInt32Delegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnboxInt32Delegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(BoxUInt32Delegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnboxUInt32Delegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(BoxInt64Delegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnboxInt64Delegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(BoxUInt64Delegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnboxUInt64Delegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(BoxCharDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnboxCharDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(BoxSingleDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnboxSingleDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(BoxDoubleDelegate)); curMemory += IntPtr.Size; Marshal.WriteIntPtr(memory, curMemory, Marshal.GetFunctionPointerForDelegate(UnboxDoubleDelegate)); curMemory += IntPtr.Size; /*END INIT CALL*/ // Init C++ library Init(memory, memorySize, initMode); if (UnhandledCppException != null) { Exception ex = UnhandledCppException; UnhandledCppException = null; throw new Exception("Unhandled C++ exception in Init", ex); } } /// <summary> /// Close the C++ plugin /// </summary> public static void Close() { ClosePlugin(); Marshal.FreeHGlobal(memory); memory = IntPtr.Zero; } /// <summary> /// Perform updates over time /// </summary> public static void Update() { DestroyAll(); } private static void ClosePlugin() { #if UNITY_EDITOR CloseLibrary(libraryHandle); libraryHandle = IntPtr.Zero; #endif #if UNITY_EDITOR_WIN File.Delete(pluginTempPath); #endif } public static void QueueDestroy(DestroyFunction function, int cppHandle) { lock (destroyQueueLockObj) { // Grow capacity if necessary int count = destroyQueueCount; int capacity = destroyQueueCapacity; DestroyEntry[] queue = destroyQueue; if (count == capacity) { int newCapacity = capacity * 2; DestroyEntry[] newQueue = new DestroyEntry[newCapacity]; for (int i = 0; i < capacity; ++i) { newQueue[i] = queue[i]; } destroyQueueCapacity = newCapacity; destroyQueue = newQueue; queue = newQueue; } // Add to the end queue[count] = new DestroyEntry(function, cppHandle); destroyQueueCount = count + 1; } } static void DestroyAll() { lock (destroyQueueLockObj) { int count = destroyQueueCount; DestroyEntry[] queue = destroyQueue; for (int i = 0; i < count; ++i) { DestroyEntry entry = queue[i]; switch (entry.Function) { /*BEGIN DESTROY QUEUE CASES*/ case DestroyFunction.BaseBallScript: DestroyBaseBallScript(entry.CppHandle); break; /*END DESTROY QUEUE CASES*/ } } destroyQueueCount = 0; } } //////////////////////////////////////////////////////////////// // C# functions for C++ to call //////////////////////////////////////////////////////////////// [MonoPInvokeCallback(typeof(ReleaseObjectDelegateType))] static void ReleaseObject( int handle) { if (handle != 0) { ObjectStore.Remove(handle); } } [MonoPInvokeCallback(typeof(StringNewDelegateType))] static int StringNew( string chars) { int handle = ObjectStore.Store(chars); return handle; } [MonoPInvokeCallback(typeof(SetExceptionDelegateType))] static void SetException(int handle) { UnhandledCppException = ObjectStore.Get(handle) as Exception; } [MonoPInvokeCallback(typeof(ArrayGetLengthDelegateType))] static int ArrayGetLength(int handle) { return ((Array)ObjectStore.Get(handle)).Length; } [MonoPInvokeCallback(typeof(EnumerableGetEnumeratorDelegateType))] static int EnumerableGetEnumerator(int handle) { return ObjectStore.Store(((IEnumerable)ObjectStore.Get(handle)).GetEnumerator()); } /*BEGIN FUNCTIONS*/ [MonoPInvokeCallback(typeof(ReleaseSystemDecimalDelegateType))] static void ReleaseSystemDecimal(int handle) { try { if (handle != 0) { NativeScript.Bindings.StructStore<System.Decimal>.Remove(handle); } } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); } } [MonoPInvokeCallback(typeof(SystemDecimalConstructorSystemDoubleDelegateType))] static int SystemDecimalConstructorSystemDouble(double value) { try { var returnValue = NativeScript.Bindings.StructStore<System.Decimal>.Store(new System.Decimal(value)); return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } } [MonoPInvokeCallback(typeof(SystemDecimalConstructorSystemUInt64DelegateType))] static int SystemDecimalConstructorSystemUInt64(ulong value) { try { var returnValue = NativeScript.Bindings.StructStore<System.Decimal>.Store(new System.Decimal(value)); return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } } [MonoPInvokeCallback(typeof(BoxDecimalDelegateType))] static int BoxDecimal(int valHandle) { try { var val = (System.Decimal)NativeScript.Bindings.StructStore<System.Decimal>.Get(valHandle); var returnValue = NativeScript.Bindings.ObjectStore.Store((object)val); return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } } [MonoPInvokeCallback(typeof(UnboxDecimalDelegateType))] static int UnboxDecimal(int valHandle) { try { var val = NativeScript.Bindings.ObjectStore.Get(valHandle); var returnValue = NativeScript.Bindings.StructStore<System.Decimal>.Store((System.Decimal)val); return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } } [MonoPInvokeCallback(typeof(UnityEngineVector3ConstructorSystemSingle_SystemSingle_SystemSingleDelegateType))] static UnityEngine.Vector3 UnityEngineVector3ConstructorSystemSingle_SystemSingle_SystemSingle(float x, float y, float z) { try { var returnValue = new UnityEngine.Vector3(x, y, z); return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(UnityEngine.Vector3); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(UnityEngine.Vector3); } } [MonoPInvokeCallback(typeof(UnityEngineVector3Methodop_AdditionUnityEngineVector3_UnityEngineVector3DelegateType))] static UnityEngine.Vector3 UnityEngineVector3Methodop_AdditionUnityEngineVector3_UnityEngineVector3(ref UnityEngine.Vector3 a, ref UnityEngine.Vector3 b) { try { var returnValue = a + b; return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(UnityEngine.Vector3); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(UnityEngine.Vector3); } } [MonoPInvokeCallback(typeof(BoxVector3DelegateType))] static int BoxVector3(ref UnityEngine.Vector3 val) { try { var returnValue = NativeScript.Bindings.ObjectStore.Store((object)val); return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } } [MonoPInvokeCallback(typeof(UnboxVector3DelegateType))] static UnityEngine.Vector3 UnboxVector3(int valHandle) { try { var val = NativeScript.Bindings.ObjectStore.Get(valHandle); var returnValue = (UnityEngine.Vector3)val; return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(UnityEngine.Vector3); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(UnityEngine.Vector3); } } [MonoPInvokeCallback(typeof(UnityEngineObjectPropertyGetNameDelegateType))] static int UnityEngineObjectPropertyGetName(int thisHandle) { try { var thiz = (UnityEngine.Object)NativeScript.Bindings.ObjectStore.Get(thisHandle); var returnValue = thiz.name; return NativeScript.Bindings.ObjectStore.GetHandle(returnValue); } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } } [MonoPInvokeCallback(typeof(UnityEngineObjectPropertySetNameDelegateType))] static void UnityEngineObjectPropertySetName(int thisHandle, int valueHandle) { try { var thiz = (UnityEngine.Object)NativeScript.Bindings.ObjectStore.Get(thisHandle); var value = (string)NativeScript.Bindings.ObjectStore.Get(valueHandle); thiz.name = value; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); } } [MonoPInvokeCallback(typeof(UnityEngineComponentPropertyGetTransformDelegateType))] static int UnityEngineComponentPropertyGetTransform(int thisHandle) { try { var thiz = (UnityEngine.Component)NativeScript.Bindings.ObjectStore.Get(thisHandle); var returnValue = thiz.transform; return NativeScript.Bindings.ObjectStore.GetHandle(returnValue); } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } } [MonoPInvokeCallback(typeof(UnityEngineTransformPropertyGetPositionDelegateType))] static UnityEngine.Vector3 UnityEngineTransformPropertyGetPosition(int thisHandle) { try { var thiz = (UnityEngine.Transform)NativeScript.Bindings.ObjectStore.Get(thisHandle); var returnValue = thiz.position; return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(UnityEngine.Vector3); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(UnityEngine.Vector3); } } [MonoPInvokeCallback(typeof(UnityEngineTransformPropertySetPositionDelegateType))] static void UnityEngineTransformPropertySetPosition(int thisHandle, ref UnityEngine.Vector3 value) { try { var thiz = (UnityEngine.Transform)NativeScript.Bindings.ObjectStore.Get(thisHandle); thiz.position = value; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); } } [MonoPInvokeCallback(typeof(SystemCollectionsIEnumeratorPropertyGetCurrentDelegateType))] static int SystemCollectionsIEnumeratorPropertyGetCurrent(int thisHandle) { try { var thiz = (System.Collections.IEnumerator)NativeScript.Bindings.ObjectStore.Get(thisHandle); var returnValue = thiz.Current; return NativeScript.Bindings.ObjectStore.GetHandle(returnValue); } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } } [MonoPInvokeCallback(typeof(SystemCollectionsIEnumeratorMethodMoveNextDelegateType))] static bool SystemCollectionsIEnumeratorMethodMoveNext(int thisHandle) { try { var thiz = (System.Collections.IEnumerator)NativeScript.Bindings.ObjectStore.Get(thisHandle); var returnValue = thiz.MoveNext(); return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(bool); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(bool); } } [MonoPInvokeCallback(typeof(UnityEngineGameObjectMethodAddComponentMyGameBaseBallScriptDelegateType))] static int UnityEngineGameObjectMethodAddComponentMyGameBaseBallScript(int thisHandle) { try { var thiz = (UnityEngine.GameObject)NativeScript.Bindings.ObjectStore.Get(thisHandle); var returnValue = thiz.AddComponent<MyGame.BaseBallScript>(); return NativeScript.Bindings.ObjectStore.GetHandle(returnValue); } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } } [MonoPInvokeCallback(typeof(UnityEngineGameObjectMethodCreatePrimitiveUnityEnginePrimitiveTypeDelegateType))] static int UnityEngineGameObjectMethodCreatePrimitiveUnityEnginePrimitiveType(UnityEngine.PrimitiveType type) { try { var returnValue = UnityEngine.GameObject.CreatePrimitive(type); return NativeScript.Bindings.ObjectStore.GetHandle(returnValue); } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } } [MonoPInvokeCallback(typeof(UnityEngineDebugMethodLogSystemObjectDelegateType))] static void UnityEngineDebugMethodLogSystemObject(int messageHandle) { try { var message = NativeScript.Bindings.ObjectStore.Get(messageHandle); UnityEngine.Debug.Log(message); } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); } } [MonoPInvokeCallback(typeof(UnityEngineMonoBehaviourPropertyGetTransformDelegateType))] static int UnityEngineMonoBehaviourPropertyGetTransform(int thisHandle) { try { var thiz = (UnityEngine.MonoBehaviour)NativeScript.Bindings.ObjectStore.Get(thisHandle); var returnValue = thiz.transform; return NativeScript.Bindings.ObjectStore.GetHandle(returnValue); } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } } [MonoPInvokeCallback(typeof(SystemExceptionConstructorSystemStringDelegateType))] static int SystemExceptionConstructorSystemString(int messageHandle) { try { var message = (string)NativeScript.Bindings.ObjectStore.Get(messageHandle); var returnValue = NativeScript.Bindings.ObjectStore.Store(new System.Exception(message)); return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } } [MonoPInvokeCallback(typeof(BoxPrimitiveTypeDelegateType))] static int BoxPrimitiveType(UnityEngine.PrimitiveType val) { try { var returnValue = NativeScript.Bindings.ObjectStore.Store((object)val); return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } } [MonoPInvokeCallback(typeof(UnboxPrimitiveTypeDelegateType))] static UnityEngine.PrimitiveType UnboxPrimitiveType(int valHandle) { try { var val = NativeScript.Bindings.ObjectStore.Get(valHandle); var returnValue = (UnityEngine.PrimitiveType)val; return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(UnityEngine.PrimitiveType); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(UnityEngine.PrimitiveType); } } [MonoPInvokeCallback(typeof(UnityEngineTimePropertyGetDeltaTimeDelegateType))] static float UnityEngineTimePropertyGetDeltaTime() { try { var returnValue = UnityEngine.Time.deltaTime; return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(float); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(float); } } [MonoPInvokeCallback(typeof(BaseBallScriptConstructorDelegateType))] static void BaseBallScriptConstructor(int cppHandle, ref int handle) { try { var thiz = new MyGame.BaseBallScript(cppHandle); handle = NativeScript.Bindings.ObjectStore.Store(thiz); } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); handle = default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); handle = default(int); } } [MonoPInvokeCallback(typeof(ReleaseBaseBallScriptDelegateType))] static void ReleaseBaseBallScript(int handle) { try { MyGame.BaseBallScript thiz; thiz = (MyGame.BaseBallScript)ObjectStore.Get(handle); int cppHandle = thiz.CppHandle; thiz.CppHandle = 0; QueueDestroy(DestroyFunction.BaseBallScript, cppHandle); ObjectStore.Remove(handle); } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); } } [MonoPInvokeCallback(typeof(BoxBooleanDelegateType))] static int BoxBoolean(bool val) { try { var returnValue = NativeScript.Bindings.ObjectStore.Store((object)val); return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } } [MonoPInvokeCallback(typeof(UnboxBooleanDelegateType))] static bool UnboxBoolean(int valHandle) { try { var val = NativeScript.Bindings.ObjectStore.Get(valHandle); var returnValue = (bool)val; return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(bool); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(bool); } } [MonoPInvokeCallback(typeof(BoxSByteDelegateType))] static int BoxSByte(sbyte val) { try { var returnValue = NativeScript.Bindings.ObjectStore.Store((object)val); return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } } [MonoPInvokeCallback(typeof(UnboxSByteDelegateType))] static sbyte UnboxSByte(int valHandle) { try { var val = NativeScript.Bindings.ObjectStore.Get(valHandle); var returnValue = (sbyte)val; return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(sbyte); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(sbyte); } } [MonoPInvokeCallback(typeof(BoxByteDelegateType))] static int BoxByte(byte val) { try { var returnValue = NativeScript.Bindings.ObjectStore.Store((object)val); return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } } [MonoPInvokeCallback(typeof(UnboxByteDelegateType))] static byte UnboxByte(int valHandle) { try { var val = NativeScript.Bindings.ObjectStore.Get(valHandle); var returnValue = (byte)val; return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(byte); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(byte); } } [MonoPInvokeCallback(typeof(BoxInt16DelegateType))] static int BoxInt16(short val) { try { var returnValue = NativeScript.Bindings.ObjectStore.Store((object)val); return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } } [MonoPInvokeCallback(typeof(UnboxInt16DelegateType))] static short UnboxInt16(int valHandle) { try { var val = NativeScript.Bindings.ObjectStore.Get(valHandle); var returnValue = (short)val; return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(short); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(short); } } [MonoPInvokeCallback(typeof(BoxUInt16DelegateType))] static int BoxUInt16(ushort val) { try { var returnValue = NativeScript.Bindings.ObjectStore.Store((object)val); return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } } [MonoPInvokeCallback(typeof(UnboxUInt16DelegateType))] static ushort UnboxUInt16(int valHandle) { try { var val = NativeScript.Bindings.ObjectStore.Get(valHandle); var returnValue = (ushort)val; return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(ushort); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(ushort); } } [MonoPInvokeCallback(typeof(BoxInt32DelegateType))] static int BoxInt32(int val) { try { var returnValue = NativeScript.Bindings.ObjectStore.Store((object)val); return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } } [MonoPInvokeCallback(typeof(UnboxInt32DelegateType))] static int UnboxInt32(int valHandle) { try { var val = NativeScript.Bindings.ObjectStore.Get(valHandle); var returnValue = (int)val; return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } } [MonoPInvokeCallback(typeof(BoxUInt32DelegateType))] static int BoxUInt32(uint val) { try { var returnValue = NativeScript.Bindings.ObjectStore.Store((object)val); return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } } [MonoPInvokeCallback(typeof(UnboxUInt32DelegateType))] static uint UnboxUInt32(int valHandle) { try { var val = NativeScript.Bindings.ObjectStore.Get(valHandle); var returnValue = (uint)val; return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(uint); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(uint); } } [MonoPInvokeCallback(typeof(BoxInt64DelegateType))] static int BoxInt64(long val) { try { var returnValue = NativeScript.Bindings.ObjectStore.Store((object)val); return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } } [MonoPInvokeCallback(typeof(UnboxInt64DelegateType))] static long UnboxInt64(int valHandle) { try { var val = NativeScript.Bindings.ObjectStore.Get(valHandle); var returnValue = (long)val; return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(long); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(long); } } [MonoPInvokeCallback(typeof(BoxUInt64DelegateType))] static int BoxUInt64(ulong val) { try { var returnValue = NativeScript.Bindings.ObjectStore.Store((object)val); return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } } [MonoPInvokeCallback(typeof(UnboxUInt64DelegateType))] static ulong UnboxUInt64(int valHandle) { try { var val = NativeScript.Bindings.ObjectStore.Get(valHandle); var returnValue = (ulong)val; return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(ulong); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(ulong); } } [MonoPInvokeCallback(typeof(BoxCharDelegateType))] static int BoxChar(char val) { try { var returnValue = NativeScript.Bindings.ObjectStore.Store((object)val); return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } } [MonoPInvokeCallback(typeof(UnboxCharDelegateType))] static char UnboxChar(int valHandle) { try { var val = NativeScript.Bindings.ObjectStore.Get(valHandle); var returnValue = (char)val; return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(char); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(char); } } [MonoPInvokeCallback(typeof(BoxSingleDelegateType))] static int BoxSingle(float val) { try { var returnValue = NativeScript.Bindings.ObjectStore.Store((object)val); return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } } [MonoPInvokeCallback(typeof(UnboxSingleDelegateType))] static float UnboxSingle(int valHandle) { try { var val = NativeScript.Bindings.ObjectStore.Get(valHandle); var returnValue = (float)val; return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(float); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(float); } } [MonoPInvokeCallback(typeof(BoxDoubleDelegateType))] static int BoxDouble(double val) { try { var returnValue = NativeScript.Bindings.ObjectStore.Store((object)val); return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(int); } } [MonoPInvokeCallback(typeof(UnboxDoubleDelegateType))] static double UnboxDouble(int valHandle) { try { var val = NativeScript.Bindings.ObjectStore.Get(valHandle); var returnValue = (double)val; return returnValue; } catch (System.NullReferenceException ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpExceptionSystemNullReferenceException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(double); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); NativeScript.Bindings.SetCsharpException(NativeScript.Bindings.ObjectStore.Store(ex)); return default(double); } } /*END FUNCTIONS*/ } } /*BEGIN BASE TYPES*/ namespace MyGame { class BaseBallScript : MyGame.AbstractBaseBallScript { public int CppHandle; public BaseBallScript() { int handle = NativeScript.Bindings.ObjectStore.Store(this); CppHandle = NativeScript.Bindings.NewBaseBallScript(handle); } ~BaseBallScript() { if (CppHandle != 0) { NativeScript.Bindings.QueueDestroy(NativeScript.Bindings.DestroyFunction.BaseBallScript, CppHandle); CppHandle = 0; } } public BaseBallScript(int cppHandle) : base() { CppHandle = cppHandle; } public override void Update() { if (CppHandle != 0) { int thisHandle = CppHandle; NativeScript.Bindings.MyGameAbstractBaseBallScriptUpdate(thisHandle); if (NativeScript.Bindings.UnhandledCppException != null) { Exception ex = NativeScript.Bindings.UnhandledCppException; NativeScript.Bindings.UnhandledCppException = null; throw ex; } } } } } /*END BASE TYPES*/
// Copyright (c) <2015> <Playdead> // This file is subject to the MIT License as seen in the root of this folder structure (LICENSE.TXT) // AUTHOR: Lasse Jon Fuglsang Pedersen <[email protected]> using System; using UnityEngine; [ExecuteInEditMode] [RequireComponent(typeof(Camera))] [AddComponentMenu("Playdead/FrustumJitter")] public class FrustumJitter : MonoBehaviour { #region Point distributions private static float[] points_Still = new float[] { 0.5f, 0.5f, }; private static float[] points_Uniform2 = new float[] { -0.25f, -0.25f,//ll 0.25f, 0.25f,//ur }; private static float[] points_Uniform4 = new float[] { -0.25f, -0.25f,//ll 0.25f, -0.25f,//lr 0.25f, 0.25f,//ur -0.25f, 0.25f,//ul }; private static float[] points_Uniform4_Helix = new float[] { -0.25f, -0.25f,//ll 3 1 0.25f, 0.25f,//ur \/| 0.25f, -0.25f,//lr /\| -0.25f, 0.25f,//ul 0 2 }; private static float[] points_Uniform4_DoubleHelix = new float[] { -0.25f, -0.25f,//ll 3 1 0.25f, 0.25f,//ur \/| 0.25f, -0.25f,//lr /\| -0.25f, 0.25f,//ul 0 2 -0.25f, -0.25f,//ll 6--7 0.25f, -0.25f,//lr \ -0.25f, 0.25f,//ul \ 0.25f, 0.25f,//ur 4--5 }; private static float[] points_SkewButterfly = new float[] { -0.250f, -0.250f, 0.250f, 0.250f, 0.125f, -0.125f, -0.125f, 0.125f, }; private static float[] points_Rotated4 = new float[] { -0.125f, -0.375f,//ll 0.375f, -0.125f,//lr 0.125f, 0.375f,//ur -0.375f, 0.125f,//ul }; private static float[] points_Rotated4_Helix = new float[] { -0.125f, -0.375f,//ll 3 1 0.125f, 0.375f,//ur \/| 0.375f, -0.125f,//lr /\| -0.375f, 0.125f,//ul 0 2 }; private static float[] points_Rotated4_Helix2 = new float[] { -0.125f, -0.375f,//ll 2--1 0.125f, 0.375f,//ur \/ -0.375f, 0.125f,//ul /\ 0.375f, -0.125f,//lr 0 3 }; private static float[] points_Poisson10 = new float[] { -0.16795960f*0.25f, 0.65544910f*0.25f, -0.69096030f*0.25f, 0.59015970f*0.25f, 0.49843820f*0.25f, 0.83099720f*0.25f, 0.17230150f*0.25f, -0.03882703f*0.25f, -0.60772670f*0.25f, -0.06013587f*0.25f, 0.65606390f*0.25f, 0.24007600f*0.25f, 0.80348370f*0.25f, -0.48096900f*0.25f, 0.33436540f*0.25f, -0.73007030f*0.25f, -0.47839520f*0.25f, -0.56005300f*0.25f, -0.12388120f*0.25f, -0.96633990f*0.25f, }; private static float[] points_Pentagram = new float[] { 0.000000f*0.5f, 0.525731f*0.5f,// head -0.309017f*0.5f, -0.425325f*0.5f,// lleg 0.500000f*0.5f, 0.162460f*0.5f,// rarm -0.500000f*0.5f, 0.162460f*0.5f,// larm 0.309017f*0.5f, -0.425325f*0.5f,// rleg }; private static float[] points_Halton_2_3_x8 = new float[8 * 2]; private static float[] points_Halton_2_3_x16 = new float[16 * 2]; private static float[] points_Halton_2_3_x32 = new float[32 * 2]; private static float[] points_Halton_2_3_x256 = new float[256 * 2]; private static float[] points_MotionPerp2 = new float[] { 0.00f, -0.25f, 0.00f, 0.25f, }; private static void TransformPattern(float[] seq, float theta, float scale) { float cs = Mathf.Cos(theta); float sn = Mathf.Sin(theta); for (int i = 0, j = 1, n = seq.Length; i != n; i += 2, j += 2) { float x = scale * seq[i]; float y = scale * seq[j]; seq[i] = x * cs - y * sn; seq[j] = x * sn + y * cs; } } // http://en.wikipedia.org/wiki/Halton_sequence private static float HaltonSeq(int prime, int index = 1/* NOT! zero-based */) { float r = 0f; float f = 1f; int i = index; while (i > 0) { f /= prime; r += f * (i % prime); i = (int)Mathf.Floor(i / (float)prime); } return r; } private static void InitializeHalton_2_3(float[] seq) { for (int i = 0, n = seq.Length / 2; i != n; i++) { float u = HaltonSeq(2, i + 1) - 0.5f; float v = HaltonSeq(3, i + 1) - 0.5f; seq[2 * i + 0] = u; seq[2 * i + 1] = v; } } static bool _initialized = false; static FrustumJitter() { if (_initialized == false) { _initialized = true; // points_Pentagram Vector2 vh = new Vector2(points_Pentagram[0] - points_Pentagram[2], points_Pentagram[1] - points_Pentagram[3]); Vector2 vu = new Vector2(0.0f, 1.0f); TransformPattern(points_Pentagram, Mathf.Deg2Rad * (0.5f * Vector2.Angle(vu, vh)), 1.0f); // points_Halton_2_3_xN InitializeHalton_2_3(points_Halton_2_3_x8); InitializeHalton_2_3(points_Halton_2_3_x16); InitializeHalton_2_3(points_Halton_2_3_x32); InitializeHalton_2_3(points_Halton_2_3_x256); } } public enum Pattern { Still, Uniform2, Uniform4, Uniform4_Helix, Uniform4_DoubleHelix, SkewButterfly, Rotated4, Rotated4_Helix, Rotated4_Helix2, Poisson10, Pentagram, Halton_2_3_X8, Halton_2_3_X16, Halton_2_3_X32, Halton_2_3_X256, MotionPerp2, }; private static float[] AccessPointData(Pattern pattern) { switch (pattern) { case Pattern.Still: return points_Still; case Pattern.Uniform2: return points_Uniform2; case Pattern.Uniform4: return points_Uniform4; case Pattern.Uniform4_Helix: return points_Uniform4_Helix; case Pattern.Uniform4_DoubleHelix: return points_Uniform4_DoubleHelix; case Pattern.SkewButterfly: return points_SkewButterfly; case Pattern.Rotated4: return points_Rotated4; case Pattern.Rotated4_Helix: return points_Rotated4_Helix; case Pattern.Rotated4_Helix2: return points_Rotated4_Helix2; case Pattern.Poisson10: return points_Poisson10; case Pattern.Pentagram: return points_Pentagram; case Pattern.Halton_2_3_X8: return points_Halton_2_3_x8; case Pattern.Halton_2_3_X16: return points_Halton_2_3_x16; case Pattern.Halton_2_3_X32: return points_Halton_2_3_x32; case Pattern.Halton_2_3_X256: return points_Halton_2_3_x256; case Pattern.MotionPerp2: return points_MotionPerp2; default: Debug.LogError("missing point distribution"); return points_Halton_2_3_x16; } } public static int AccessLength(Pattern pattern) { return AccessPointData(pattern).Length / 2; } #endregion private Vector3 focalMotionPos = Vector3.zero; private Vector3 focalMotionDir = Vector3.right; public Pattern pattern = Pattern.Halton_2_3_X16; public float patternScale = 1f; public Vector4 activeSample = Vector4.zero;// xy = current sample, zw = previous sample public int activeIndex = -1; public Vector2 Sample(Pattern pattern, int index) { float[] points = AccessPointData(pattern); int n = points.Length / 2; int i = index % n; float x = patternScale * points[2 * i + 0]; float y = patternScale * points[2 * i + 1]; if (pattern != Pattern.MotionPerp2) return new Vector2(x, y); else return new Vector2(x, y).Rotate(Vector2.right.SignedAngle(focalMotionDir)); } void OnPreCull() { var camera = GetComponent<Camera>(); if (camera != null && camera.orthographic == false) { // update motion dir { Vector3 oldWorld = focalMotionPos; Vector3 newWorld = camera.transform.TransformVector(camera.nearClipPlane * Vector3.forward); Vector3 oldPoint = (camera.worldToCameraMatrix * oldWorld); Vector3 newPoint = (camera.worldToCameraMatrix * newWorld); Vector3 newDelta = (newPoint - oldPoint).WithZ(0f); var mag = newDelta.magnitude; if (mag != 0f) { var dir = newDelta / mag;// yes, apparently this is necessary instead of newDelta.normalized... because facepalm if (dir.sqrMagnitude != 0f) { focalMotionPos = newWorld; focalMotionDir = Vector3.Slerp(focalMotionDir, dir, 0.2f); //Debug.Log("CHANGE focalMotionDir " + focalMotionDir.ToString("G4") + " delta was " + newDelta.ToString("G4") + " delta.mag " + newDelta.magnitude); } } } // update jitter { activeIndex += 1; activeIndex %= AccessLength(pattern); Vector2 sample = Sample(pattern, activeIndex); activeSample.z = activeSample.x; activeSample.w = activeSample.y; activeSample.x = sample.x; activeSample.y = sample.y; camera.projectionMatrix = camera.GetPerspectiveProjection(sample.x, sample.y); } } else { activeSample = Vector4.zero; activeIndex = -1; } } void OnDisable() { var camera = GetComponent<Camera>(); if (camera != null) { camera.ResetProjectionMatrix(); } activeSample = Vector4.zero; activeIndex = -1; } }
// Copyright 2011 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Microsoft.Data.OData.Query { #region Namespaces using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using Microsoft.Data.Edm; using Microsoft.Data.Edm.Library; using Microsoft.Data.OData.Metadata; using Microsoft.Data.OData.Query.Metadata; #endregion Namespaces /// <summary> /// Binder which applies metadata to a lexical QueryToken tree and produces a bound semantic QueryNode tree. /// </summary> [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Keeping the visitor in one place makes sense.")] #if INTERNAL_DROP internal class MetadataBinder #else public class MetadataBinder #endif { /// <summary> /// The model used for binding. /// </summary> private readonly IEdmModel model; /// <summary> /// Collection of query option tokens associated with the currect query being processed. /// If a given query option is bound it should be removed from this collection. /// </summary> private List<QueryOptionQueryToken> queryOptions; /// <summary> /// If the binder is binding an expression, like $filter or $orderby, this member holds /// the reference to the parameter node for the expression. /// </summary> private ParameterQueryNode parameter; /// <summary> /// Constructor. /// </summary> /// <param name="model">The model to use for binding.</param> public MetadataBinder(IEdmModel model) { ExceptionUtils.CheckArgumentNotNull(model, "model"); this.model = model; } /// <summary> /// Gets the EDM model. /// </summary> protected IEdmModel Model { get { return this.model; } } /// <summary> /// Binds the specified <paramref name="queryDescriptorQueryToken"/> to the metadata and returns a bound query. /// </summary> /// <param name="queryDescriptorQueryToken">The lexical query descriptor for the query to process.</param> /// <returns>Metadata bound semantic query descriptor for the query.</returns> public QueryDescriptorQueryNode BindQuery(QueryDescriptorQueryToken queryDescriptorQueryToken) { ExceptionUtils.CheckArgumentNotNull(queryDescriptorQueryToken, "queryDescriptorQueryToken"); return this.BindQueryDescriptor(queryDescriptorQueryToken); } /// <summary> /// Visits a <see cref="QueryToken"/> in the lexical tree and binds it to metadata producing a semantic <see cref="QueryNode"/>. /// </summary> /// <param name="token">The query token on the input.</param> /// <returns>The bound query node output.</returns> protected QueryNode Bind(QueryToken token) { ExceptionUtils.CheckArgumentNotNull(token, "token"); QueryNode result; switch (token.Kind) { case QueryTokenKind.Extension: result = this.BindExtension(token); break; case QueryTokenKind.Any: result = this.BindAny((AnyQueryToken)token); break; case QueryTokenKind.All: result = this.BindAll((AllQueryToken)token); break; case QueryTokenKind.Segment: result = this.BindSegment((SegmentQueryToken)token); break; case QueryTokenKind.NonRootSegment: result = this.BindNavigationProperty((NavigationPropertyToken)token); break; case QueryTokenKind.Literal: result = this.BindLiteral((LiteralQueryToken)token); break; case QueryTokenKind.BinaryOperator: result = this.BindBinaryOperator((BinaryOperatorQueryToken)token); break; case QueryTokenKind.UnaryOperator: result = this.BindUnaryOperator((UnaryOperatorQueryToken)token); break; case QueryTokenKind.PropertyAccess: result = this.BindPropertyAccess((PropertyAccessQueryToken)token); break; case QueryTokenKind.FunctionCall: result = this.BindFunctionCall((FunctionCallQueryToken)token); break; case QueryTokenKind.QueryOption: result = this.BindQueryOption((QueryOptionQueryToken)token); break; case QueryTokenKind.Cast: result = this.BindCast((CastToken)token); break; case QueryTokenKind.Parameter: result = this.BindParameter((ParameterQueryToken)token); break; default: throw new ODataException(Strings.MetadataBinder_UnsupportedQueryTokenKind(token.Kind)); } if (result == null) { throw new ODataException(Strings.MetadataBinder_BoundNodeCannotBeNull(token.Kind)); } return result; } /// <summary> /// Binds a parameter token. /// </summary> /// <param name="parameterQueryToken">The parameter token to bind.</param> /// <returns>The bound query node.</returns> protected virtual QueryNode BindParameter(ParameterQueryToken parameterQueryToken) { ExceptionUtils.CheckArgumentNotNull(parameterQueryToken, "extensionToken"); QueryNode source = this.Bind(parameterQueryToken.Parent); IEdmType type = GetType(source); return new ParameterQueryNode { ParameterType = type.ToTypeReference() }; } /// <summary> /// Binds an extension token. /// </summary> /// <param name="extensionToken">The extension token to bind.</param> /// <returns>The bound query node.</returns> protected virtual QueryNode BindExtension(QueryToken extensionToken) { ExceptionUtils.CheckArgumentNotNull(extensionToken, "extensionToken"); throw new ODataException(Strings.MetadataBinder_UnsupportedExtensionToken); } /// <summary> /// Need to revert this. /// </summary> /// <param name="segmentToken">Need to revert this.</param> /// <returns>Need to revert this.</returns> protected virtual QueryNode BindSegment(SegmentQueryToken segmentToken) { ExceptionUtils.CheckArgumentNotNull(segmentToken, "segmentToken"); ExceptionUtils.CheckArgumentNotNull(segmentToken.Name, "segmentToken.Name"); if (segmentToken.Parent == null) { return this.BindRootSegment(segmentToken); } else { // TODO: return this.BindNonRootSegment(segmentToken); throw new NotImplementedException(); } } /// <summary> /// Binds a <see cref="QueryDescriptorQueryToken"/>. /// </summary> /// <param name="queryDescriptorToken">The query descriptor token to bind.</param> /// <returns>The bound query descriptor.</returns> protected virtual QueryDescriptorQueryNode BindQueryDescriptor(QueryDescriptorQueryToken queryDescriptorToken) { ExceptionUtils.CheckArgumentNotNull(queryDescriptorToken, "queryDescriptorToken"); ExceptionUtils.CheckArgumentNotNull(queryDescriptorToken.Path, "queryDescriptorToken.Path"); // Make a copy of query options since we may consume some of them as we bind the query this.queryOptions = new List<QueryOptionQueryToken>(queryDescriptorToken.QueryOptions); //// TODO: check whether there is a $count segment at the top; if so strip it and first process everything else and //// then add it to the bound query tree at the end // First bind the path QueryNode query = this.Bind(queryDescriptorToken.Path); // Apply filter first, then order-by, skip, top, select and expand query = this.ProcessFilter(query, queryDescriptorToken.Filter); query = this.ProcessOrderBy(query, queryDescriptorToken.OrderByTokens); query = ProcessSkip(query, queryDescriptorToken.Skip); query = ProcessTop(query, queryDescriptorToken.Top); //// TODO: if we found a $count segment process it now and add it to the query QueryDescriptorQueryNode queryDescriptorNode = new QueryDescriptorQueryNode(); queryDescriptorNode.Query = query; // Add the remaining query options to the query descriptor. List<QueryNode> boundQueryOptions = this.ProcessQueryOptions(); queryDescriptorNode.CustomQueryOptions = new ReadOnlyCollection<QueryNode>(boundQueryOptions); Debug.Assert(this.queryOptions == null, "this.queryOptions == null"); return queryDescriptorNode; } /// <summary> /// Binds a literal token. /// </summary> /// <param name="literalToken">The literal token to bind.</param> /// <returns>The bound literal token.</returns> protected virtual QueryNode BindLiteral(LiteralQueryToken literalToken) { ExceptionUtils.CheckArgumentNotNull(literalToken, "literalToken"); return new ConstantQueryNode() { Value = literalToken.Value }; } /// <summary> /// Binds a binary operator token. /// </summary> /// <param name="binaryOperatorToken">The binary operator token to bind.</param> /// <returns>The bound binary operator token.</returns> protected virtual QueryNode BindBinaryOperator(BinaryOperatorQueryToken binaryOperatorToken) { ExceptionUtils.CheckArgumentNotNull(binaryOperatorToken, "binaryOperatorToken"); SingleValueQueryNode left = this.Bind(binaryOperatorToken.Left) as SingleValueQueryNode; if (left == null) { throw new ODataException(Strings.MetadataBinder_BinaryOperatorOperandNotSingleValue(binaryOperatorToken.OperatorKind.ToString())); } SingleValueQueryNode right = this.Bind(binaryOperatorToken.Right) as SingleValueQueryNode; if (right == null) { throw new ODataException(Strings.MetadataBinder_BinaryOperatorOperandNotSingleValue(binaryOperatorToken.OperatorKind.ToString())); } IEdmTypeReference leftType = left.TypeReference; IEdmTypeReference rightType = right.TypeReference; if (!TypePromotionUtils.PromoteOperandTypes(binaryOperatorToken.OperatorKind, ref leftType, ref rightType)) { string leftTypeName = left.TypeReference == null ? "<null>" : left.TypeReference.ODataFullName(); string rightTypeName = right.TypeReference == null ? "<null>" : right.TypeReference.ODataFullName(); throw new ODataException(Strings.MetadataBinder_IncompatibleOperandsError(leftTypeName, rightTypeName, binaryOperatorToken.OperatorKind)); } if (leftType != null) { left = ConvertToType(left, leftType); } if (rightType != null) { right = ConvertToType(right, rightType); } return new BinaryOperatorQueryNode() { OperatorKind = binaryOperatorToken.OperatorKind, Left = left, Right = right }; } /// <summary> /// Binds a unary operator token. /// </summary> /// <param name="unaryOperatorToken">The unary operator token to bind.</param> /// <returns>The bound unary operator token.</returns> protected virtual QueryNode BindUnaryOperator(UnaryOperatorQueryToken unaryOperatorToken) { ExceptionUtils.CheckArgumentNotNull(unaryOperatorToken, "unaryOperatorToken"); SingleValueQueryNode operand = this.Bind(unaryOperatorToken.Operand) as SingleValueQueryNode; if (operand == null) { throw new ODataException(Strings.MetadataBinder_UnaryOperatorOperandNotSingleValue(unaryOperatorToken.OperatorKind.ToString())); } IEdmTypeReference typeReference = operand.TypeReference; if (!TypePromotionUtils.PromoteOperandType(unaryOperatorToken.OperatorKind, ref typeReference)) { string typeName = operand.TypeReference == null ? "<null>" : operand.TypeReference.ODataFullName(); throw new ODataException(Strings.MetadataBinder_IncompatibleOperandError(typeName, unaryOperatorToken.OperatorKind)); } if (typeReference != null) { operand = ConvertToType(operand, typeReference); } return new UnaryOperatorQueryNode() { OperatorKind = unaryOperatorToken.OperatorKind, Operand = operand }; } /// <summary> /// Binds a type segment token. /// </summary> /// <param name="castToken">The type segment token to bind.</param> /// <returns>The bound type segment token.</returns> protected virtual QueryNode BindCast(CastToken castToken) { ExceptionUtils.CheckArgumentNotNull(castToken, "typeSegmentToken"); var childType = this.model.FindType(castToken.SegmentSpace + "." + castToken.SegmentName); // Check whether childType is a derived type of the type of its parent node QueryNode parent; IEdmType parentType; if (castToken.Source == null) { parent = null; parentType = this.parameter.ParameterType.Definition; } else { parent = this.Bind(castToken.Source); parentType = GetType(parent); } if (!childType.IsOrInheritsFrom(parentType)) { throw new ODataException(Strings.MetadataBinder_HierarchyNotFollowed(childType.FullName(), parentType.ODataFullName())); } return new CastNode() { EdmType = childType, Source = (SingleValueQueryNode)parent }; } /// <summary> /// Binds Any token. /// </summary> /// <param name="anyQueryToken">The Any token to bind.</param> /// <returns>The bound Any node.</returns> protected virtual QueryNode BindAny(AnyQueryToken anyQueryToken) { ExceptionUtils.CheckArgumentNotNull(anyQueryToken, "anyQueryToken"); QueryNode property = this.Bind(anyQueryToken.Parent); QueryNode expr = this.Bind(anyQueryToken.Expression); return new AnyQueryNode() { Body = expr, Source = property }; } /// <summary> /// Binds All token. /// </summary> /// <param name="allQueryToken">The All token to bind.</param> /// <returns>The bound All node.</returns> protected virtual QueryNode BindAll(AllQueryToken allQueryToken) { ExceptionUtils.CheckArgumentNotNull(allQueryToken, "allQueryToken"); QueryNode property = this.Bind(allQueryToken.Parent); QueryNode expr = this.Bind(allQueryToken.Expression); return new AllQueryNode() { Body = expr, Source = property }; } /// <summary> /// Binds a property access token. /// </summary> /// <param name="propertyAccessToken">The property access token to bind.</param> /// <returns>The bound property access token.</returns> protected virtual QueryNode BindPropertyAccess(PropertyAccessQueryToken propertyAccessToken) { ExceptionUtils.CheckArgumentNotNull(propertyAccessToken, "propertyAccessToken"); ExceptionUtils.CheckArgumentStringNotNullOrEmpty(propertyAccessToken.Name, "propertyAccessToken.Name"); SingleValueQueryNode parentNode; SingleValueQueryNode navigationPath = null; // Set the parentNode (get the parent type, so you can check whether the Name inside propertyAccessToken really is legit offshoot of the parent type) QueryNode parent = null; if (propertyAccessToken.Parent == null) { if (this.parameter == null) { throw new ODataException(Strings.MetadataBinder_PropertyAccessWithoutParentParameter); } parentNode = this.parameter; parent = this.parameter; } else { parent = this.Bind(propertyAccessToken.Parent) as SingleValueQueryNode; if (parent == null) { throw new ODataException(Strings.MetadataBinder_PropertyAccessSourceNotSingleValue(propertyAccessToken.Name)); } NavigationPropertyNode parentNav = parent as NavigationPropertyNode; CastNode parentCast = parent as CastNode; PropertyAccessQueryNode parentProperty = parent as PropertyAccessQueryNode; if (parentProperty != null) { navigationPath = parentProperty; var propertyPath = (IEdmStructuralProperty)parentProperty.Property; parentNode = new ParameterQueryNode() { ParameterType = propertyPath.Type }; } else if (parentCast != null) { IEdmType entityType = parentCast.EdmType; parentNode = new ParameterQueryNode() { ParameterType = entityType.ToTypeReference() }; } else if (parentNav != null) { navigationPath = parentNav; IEdmEntityType entityType = parentNav.NavigationProperty.ToEntityType(); parentNode = new ParameterQueryNode() { ParameterType = new EdmEntityTypeReference(entityType, true) }; } else { parentNode = this.Bind(propertyAccessToken.Parent) as SingleValueQueryNode; } } // Now that we have the parent type, can find its corresponding EDM type IEdmStructuredTypeReference structuredParentType = parentNode.TypeReference == null ? null : parentNode.TypeReference.AsStructuredOrNull(); IEdmProperty property = structuredParentType == null ? null : structuredParentType.FindProperty(propertyAccessToken.Name); if (property != null) { // TODO: Check that we have entity set once we add the entity set propagation into the bound tree // See RequestQueryParser.ExpressionParser.ParseMemberAccess if (property.Type.IsNonEntityODataCollectionTypeKind()) { throw new ODataException(Strings.MetadataBinder_MultiValuePropertyNotSupportedInExpression(property.Name)); } if (property.PropertyKind == EdmPropertyKind.Navigation) { // TODO: Implement navigations throw new NotImplementedException(); } if (navigationPath != null) { parentNode = navigationPath; } return new PropertyAccessQueryNode() { Source = (SingleValueQueryNode)parent, Property = property }; } else { if (parentNode.TypeReference != null && !parentNode.TypeReference.Definition.IsOpenType()) { throw new ODataException(Strings.MetadataBinder_PropertyNotDeclared(parentNode.TypeReference.ODataFullName(), propertyAccessToken.Name)); } // TODO: Implement open property support throw new NotImplementedException(); } } /// <summary> /// Binds a function call token. /// </summary> /// <param name="functionCallToken">The function call token to bind.</param> /// <returns>The bound function call token.</returns> protected virtual QueryNode BindFunctionCall(FunctionCallQueryToken functionCallToken) { ExceptionUtils.CheckArgumentNotNull(functionCallToken, "functionCallToken"); ExceptionUtils.CheckArgumentNotNull(functionCallToken.Name, "functionCallToken.Name"); // Bind all arguments List<QueryNode> argumentNodes = new List<QueryNode>(functionCallToken.Arguments.Select(ar => this.Bind(ar))); // Special case the operators which look like function calls if (functionCallToken.Name == "cast") { // TODO: Implement cast operators throw new NotImplementedException(); } else if (functionCallToken.Name == "isof") { // TODO: Implement cast operators throw new NotImplementedException(); } else { // Try to find the function in our built-in functions BuiltInFunctionSignature[] signatures; if (!BuiltInFunctions.TryGetBuiltInFunction(functionCallToken.Name, out signatures)) { throw new ODataException(Strings.MetadataBinder_UnknownFunction(functionCallToken.Name)); } // Right now all functions take a single value for all arguments IEdmTypeReference[] argumentTypes = new IEdmTypeReference[argumentNodes.Count]; for (int i = 0; i < argumentNodes.Count; i++) { SingleValueQueryNode argumentNode = argumentNodes[i] as SingleValueQueryNode; if (argumentNode == null) { throw new ODataException(Strings.MetadataBinder_FunctionArgumentNotSingleValue(functionCallToken.Name)); } argumentTypes[i] = argumentNode.TypeReference; } BuiltInFunctionSignature signature = (BuiltInFunctionSignature) TypePromotionUtils.FindBestFunctionSignature(signatures, argumentTypes); if (signature == null) { throw new ODataException(Strings.MetadataBinder_NoApplicableFunctionFound( functionCallToken.Name, BuiltInFunctions.BuildFunctionSignatureListDescription(functionCallToken.Name, signatures))); } // Convert all argument nodes to the best signature argument type Debug.Assert(signature.ArgumentTypes.Length == argumentNodes.Count, "The best signature match doesn't have the same number of arguments."); for (int i = 0; i < argumentNodes.Count; i++) { Debug.Assert(argumentNodes[i] is SingleValueQueryNode, "We should have already verified that all arguments are single values."); SingleValueQueryNode argumentNode = (SingleValueQueryNode)argumentNodes[i]; IEdmTypeReference signatureArgumentType = signature.ArgumentTypes[i]; if (signatureArgumentType != argumentNode.TypeReference) { argumentNodes[i] = ConvertToType(argumentNode, signatureArgumentType); } } return new SingleValueFunctionCallQueryNode { Name = functionCallToken.Name, Arguments = new ReadOnlyCollection<QueryNode>(argumentNodes), ReturnType = signature.ReturnType }; } } /// <summary> /// Binds a query option token. /// </summary> /// <param name="queryOptionToken">The query option token to bind.</param> /// <returns>The bound query option token.</returns> /// <remarks>The default implementation of this method will not allow any system query options /// (query options starting with '$') that were not previously processed.</remarks> protected virtual QueryNode BindQueryOption(QueryOptionQueryToken queryOptionToken) { ExceptionUtils.CheckArgumentNotNull(queryOptionToken, "queryOptionToken"); // If we find a system query option here we will throw string name = queryOptionToken.Name; if (!string.IsNullOrEmpty(name) && name[0] == '$') { throw new ODataException(Strings.MetadataBinder_UnsupportedSystemQueryOption(name)); } return new CustomQueryOptionQueryNode { Name = name, Value = queryOptionToken.Value }; } /// <summary> /// Binds a string to its associated type. /// </summary> /// <param name="parentReference">The parent type to be used to find binding options.</param> /// <param name="propertyName">The string designated the property name to be bound.</param> /// <returns>The property associated with string and parent type.</returns> private static IEdmProperty BindProperty(IEdmTypeReference parentReference, string propertyName) { IEdmStructuredTypeReference structuredParentType = parentReference == null ? null : parentReference.AsStructuredOrNull(); return structuredParentType == null ? null : structuredParentType.FindProperty(propertyName); } /// <summary> /// Retrieves type associated to a segment. /// </summary> /// <param name="segment">The segment to be bound.</param> /// <returns>The bound node.</returns> private static IEdmType GetType(QueryNode segment) { NavigationPropertyNode segmentNav = segment as NavigationPropertyNode; CastNode segmentCast = segment as CastNode; PropertyAccessQueryNode segmentProperty = segment as PropertyAccessQueryNode; ParameterQueryNode segmentParam = segment as ParameterQueryNode; if (segmentCast != null) { return segmentCast.EdmType; } else if (segmentNav != null) { return segmentNav.NavigationProperty.ToEntityType(); } else if (segmentProperty != null) { return segmentProperty.TypeReference.Definition; } else if (segmentParam != null) { return segmentParam.TypeReference.Definition; } else { throw new ODataException(Strings.MetadataBinder_NoTypeSupported); } } /// <summary> /// Processes the skip operator (if any) and returns the combined query. /// </summary> /// <param name="query">The query tree constructed so far.</param> /// <param name="skip">The skip amount or null if none was specified.</param> /// <returns> /// The unmodified <paramref name="query"/> if no skip is specified or the combined /// query tree including the skip operator if it was specified. /// </returns> private static QueryNode ProcessSkip(QueryNode query, int? skip) { ExceptionUtils.CheckArgumentNotNull(query, "query"); if (skip.HasValue) { CollectionQueryNode entityCollection = query.AsEntityCollectionNode(); if (entityCollection == null) { throw new ODataException(Strings.MetadataBinder_SkipNotApplicable); } int skipValue = skip.Value; if (skipValue < 0) { throw new ODataException(Strings.MetadataBinder_SkipRequiresNonNegativeInteger(skipValue.ToString(CultureInfo.CurrentCulture))); } query = new SkipQueryNode() { Collection = entityCollection, Amount = new ConstantQueryNode { Value = skipValue } }; } return query; } /// <summary> /// Processes the top operator (if any) and returns the combined query. /// </summary> /// <param name="query">The query tree constructed so far.</param> /// <param name="top">The top amount or null if none was specified.</param> /// <returns> /// The unmodified <paramref name="query"/> if no top is specified or the combined /// query tree including the top operator if it was specified. /// </returns> private static QueryNode ProcessTop(QueryNode query, int? top) { ExceptionUtils.CheckArgumentNotNull(query, "query"); if (top.HasValue) { CollectionQueryNode entityCollection = query.AsEntityCollectionNode(); if (entityCollection == null) { throw new ODataException(Strings.MetadataBinder_TopNotApplicable); } int topValue = top.Value; if (topValue < 0) { throw new ODataException(Strings.MetadataBinder_TopRequiresNonNegativeInteger(topValue.ToString(CultureInfo.CurrentCulture))); } query = new TopQueryNode() { Collection = entityCollection, Amount = new ConstantQueryNode { Value = topValue } }; } return query; } /// <summary> /// Determines if a segment is a complex type. /// </summary> /// <param name="instance">Segment to be checked.</param> /// <param name="parentType">The type of the parent segment.</param> /// <returns>True if segment represents a complex type and false otherwise.</returns> private static Boolean IsDerivedComplexType(NavigationPropertyToken instance, IEdmType parentType) { IEdmProperty property = BindProperty(parentType.ToTypeReference(), instance.Name); return property.Type.IsODataComplexTypeKind(); } /// <summary> /// Checks if the source is of the specified type and if not tries to inject a convert. /// </summary> /// <param name="source">The source node to apply the convertion to.</param> /// <param name="targetTypeReference">The target primitive type.</param> /// <returns>The converted query node.</returns> private static SingleValueQueryNode ConvertToType(SingleValueQueryNode source, IEdmTypeReference targetTypeReference) { Debug.Assert(source != null, "source != null"); Debug.Assert(targetTypeReference != null, "targetType != null"); Debug.Assert(targetTypeReference.IsODataPrimitiveTypeKind(), "Can only convert primitive types."); if (source.TypeReference != null) { // TODO: Do we check this here or in the caller? Debug.Assert(source.TypeReference.IsODataPrimitiveTypeKind(), "Can only work on primitive types."); if (source.TypeReference.IsEquivalentTo(targetTypeReference)) { return source; } else { if (!TypePromotionUtils.CanConvertTo(source.TypeReference, targetTypeReference)) { throw new ODataException(Strings.MetadataBinder_CannotConvertToType(source.TypeReference.ODataFullName(), targetTypeReference.ODataFullName())); } } } // If the source doesn't have a type (possibly an open property), then it's possible to convert it // cause we don't know for sure. return new ConvertQueryNode() { Source = source, TargetType = targetTypeReference }; } /// <summary> /// Binds a <see cref="NavigationPropertyToken"/>. /// </summary> /// <param name="segmentToken">The segment token to bind.</param> /// <returns>The bound node.</returns> private SingleValueQueryNode BindNavigationProperty(NavigationPropertyToken segmentToken) { QueryNode source = null; IEdmNavigationProperty property; if (segmentToken.Parent != null) { source = this.Bind(segmentToken.Parent); IEdmType entityType = null; if (IsDerivedComplexType(segmentToken, GetType(source))) { IEdmProperty returnProperty = BindProperty(GetType(source).ToTypeReference(), segmentToken.Name); return new PropertyAccessQueryNode() { Source = (SingleValueQueryNode)source, Property = returnProperty }; } else { entityType = GetType(source); } ParameterQueryNode parentNode = new ParameterQueryNode { ParameterType = entityType.ToTypeReference() }; property = (IEdmNavigationProperty)BindProperty(parentNode.TypeReference, segmentToken.Name); } else { if (IsDerivedComplexType(segmentToken, this.parameter.TypeReference.Definition)) { IEdmProperty returnProperty = BindProperty(new EdmEntityTypeReference((IEdmEntityType)this.parameter.TypeReference.Definition, true), segmentToken.Name); return new PropertyAccessQueryNode { Source = this.parameter, Property = returnProperty }; } property = (IEdmNavigationProperty)BindProperty(this.parameter.TypeReference, segmentToken.Name); } // Ensure that only collections head Any queries and nothing else if (property.OwnMultiplicity() == EdmMultiplicity.Many && segmentToken.AnyAllParent == false) { throw new ODataException(Strings.MetadataBinder_PropertyAccessSourceNotSingleValue(segmentToken.Name)); } else if (property.OwnMultiplicity() != EdmMultiplicity.Many && segmentToken.AnyAllParent == true) { throw new ODataException(Strings.MetadataBinder_InvalidAnyAllHead); } return new NavigationPropertyNode() { Source = source, NavigationProperty = property }; } /// <summary> /// Processes the filter of the query (if any). /// </summary> /// <param name="query">The query tree constructed so far.</param> /// <param name="filter">The filter to bind.</param> /// <returns>If no filter is specified, returns the <paramref name="query"/> unchanged. If a filter is specified it returns the combined query including the filter.</returns> private QueryNode ProcessFilter(QueryNode query, QueryToken filter) { ExceptionUtils.CheckArgumentNotNull(query, "query"); if (filter != null) { CollectionQueryNode entityCollection = query.AsEntityCollectionNode(); if (entityCollection == null) { throw new ODataException(Strings.MetadataBinder_FilterNotApplicable); } this.parameter = new ParameterQueryNode() { ParameterType = entityCollection.ItemType }; QueryNode expressionNode = this.Bind(filter); SingleValueQueryNode expressionResultNode = expressionNode as SingleValueQueryNode; if (expressionResultNode == null || (expressionResultNode.TypeReference != null && !expressionResultNode.TypeReference.IsODataPrimitiveTypeKind())) { throw new ODataException(Strings.MetadataBinder_FilterExpressionNotSingleValue); } // The type may be null here if the query statically represents the null literal // TODO: once we support open types/properties a 'null' type will mean 'we don't know the type'. Review. IEdmTypeReference expressionResultType = expressionResultNode.TypeReference; if (expressionResultType != null) { IEdmPrimitiveTypeReference primitiveExpressionResultType = expressionResultType.AsPrimitiveOrNull(); if (primitiveExpressionResultType == null || primitiveExpressionResultType.PrimitiveKind() != EdmPrimitiveTypeKind.Boolean) { throw new ODataException(Strings.MetadataBinder_FilterExpressionNotSingleValue); } } query = new FilterQueryNode() { Collection = entityCollection, Parameter = this.parameter, Expression = expressionResultNode }; this.parameter = null; } return query; } /// <summary> /// Processes the order-by tokens of a query (if any). /// </summary> /// <param name="query">The query tree constructed so far.</param> /// <param name="orderByTokens">The order-by tokens to bind.</param> /// <returns>If no order-by tokens are specified, returns the <paramref name="query"/> unchanged. If order-by tokens are specified it returns the combined query including the ordering.</returns> private QueryNode ProcessOrderBy(QueryNode query, IEnumerable<OrderByQueryToken> orderByTokens) { ExceptionUtils.CheckArgumentNotNull(query, "query"); foreach (OrderByQueryToken orderByToken in orderByTokens) { query = this.ProcessSingleOrderBy(query, orderByToken); } return query; } /// <summary> /// Process the remaining query options (represent the set of custom query options after /// service operation parameters and system query options have been removed). /// </summary> /// <returns>The list of <see cref="QueryNode"/> instances after binding.</returns> private List<QueryNode> ProcessQueryOptions() { List<QueryNode> customQueryOptionNodes = new List<QueryNode>(); foreach (QueryOptionQueryToken queryToken in this.queryOptions) { QueryNode customQueryOptionNode = this.Bind(queryToken); if (customQueryOptionNode != null) { customQueryOptionNodes.Add(customQueryOptionNode); } } this.queryOptions = null; return customQueryOptionNodes; } /// <summary> /// Processes the specified order-by token. /// </summary> /// <param name="query">The query tree constructed so far.</param> /// <param name="orderByToken">The order-by token to bind.</param> /// <returns>Returns the combined query including the ordering.</returns> private QueryNode ProcessSingleOrderBy(QueryNode query, OrderByQueryToken orderByToken) { Debug.Assert(query != null, "query != null"); ExceptionUtils.CheckArgumentNotNull(orderByToken, "orderByToken"); CollectionQueryNode entityCollection = query.AsEntityCollectionNode(); if (entityCollection == null) { throw new ODataException(Strings.MetadataBinder_OrderByNotApplicable); } this.parameter = new ParameterQueryNode() { ParameterType = entityCollection.ItemType }; QueryNode expressionNode = this.Bind(orderByToken.Expression); // TODO: shall we really restrict order-by expressions to primitive types? SingleValueQueryNode expressionResultNode = expressionNode as SingleValueQueryNode; if (expressionResultNode == null || (expressionResultNode.TypeReference != null && !expressionResultNode.TypeReference.IsODataPrimitiveTypeKind())) { throw new ODataException(Strings.MetadataBinder_OrderByExpressionNotSingleValue); } query = new OrderByQueryNode() { Collection = entityCollection, Direction = orderByToken.Direction, Parameter = this.parameter, Expression = expressionResultNode }; this.parameter = null; return query; } /// <summary> /// Binds a root path segment. /// </summary> /// <param name="segmentToken">The segment to bind.</param> /// <returns>The bound node.</returns> private QueryNode BindRootSegment(SegmentQueryToken segmentToken) { Debug.Assert(segmentToken != null, "segmentToken != null"); Debug.Assert(segmentToken.Parent == null, "Only root segments should be allowed here."); Debug.Assert(!string.IsNullOrEmpty(segmentToken.Name), "!string.IsNullOrEmpty(segmentToken.Name)"); //// This is a metadata-only version of the RequestUriProcessor.CreateFirstSegment. if (segmentToken.Name == UriQueryConstants.MetadataSegment) { // TODO: $metadata segment parsing - no key values are allowed. throw new NotImplementedException(); } if (segmentToken.Name == UriQueryConstants.BatchSegment) { // TODO: $batch segment parsing - no key values are allowed. throw new NotImplementedException(); } // TODO: WCF DS checks for $count here first and fails. But not for the other $ segments. // which means other $segments get to SO resolution. On the other hand the WCF DS would eventually fail if an SO started with $. // Look for a service operation IEdmFunctionImport serviceOperation = this.model.TryResolveServiceOperation(segmentToken.Name); if (serviceOperation != null) { return this.BindServiceOperation(segmentToken, serviceOperation); } // TODO: Content-ID reference resolution. Do we actually do anything here or do we perform this through extending the metadata binder? // Look for an entity set. IEdmEntitySet entitySet = this.model.TryResolveEntitySet(segmentToken.Name); if (entitySet == null) { throw new ODataException(Strings.MetadataBinder_RootSegmentResourceNotFound(segmentToken.Name)); } EntitySetQueryNode entitySetQueryNode = new EntitySetQueryNode() { EntitySet = entitySet }; if (segmentToken.NamedValues != null) { return this.BindKeyValues(entitySetQueryNode, segmentToken.NamedValues); } return entitySetQueryNode; } /// <summary> /// Binds a service operation segment. /// </summary> /// <param name="segmentToken">The segment which represents a service operation.</param> /// <param name="serviceOperation">The service operation to bind.</param> /// <returns>The bound node.</returns> private QueryNode BindServiceOperation(SegmentQueryToken segmentToken, IEdmFunctionImport serviceOperation) { Debug.Assert(segmentToken != null, "segmentToken != null"); Debug.Assert(serviceOperation != null, "serviceOperation != null"); Debug.Assert(segmentToken.Name == serviceOperation.Name, "The segment represents a different service operation."); //// This is a metadata copy of the RequestUriProcessor.CreateSegmentForServiceOperation //// The WCF DS checks the verb in this place, we can't do that here // All service operations other than those returning IQueryable MUST NOT have () appended to the URI // V1/V2 behavior: if it's IEnumerable<T>, we do not allow () either, because it's not further composable. ODataServiceOperationResultKind? resultKind = serviceOperation.GetServiceOperationResultKind(this.model); if (resultKind != ODataServiceOperationResultKind.QueryWithMultipleResults && segmentToken.NamedValues != null) { throw new ODataException(Strings.MetadataBinder_NonQueryableServiceOperationWithKeyLookup(segmentToken.Name)); } if (!resultKind.HasValue) { throw new ODataException(Strings.MetadataBinder_ServiceOperationWithoutResultKind(serviceOperation.Name)); } IEnumerable<QueryNode> serviceOperationParameters = this.BindServiceOperationParameters(serviceOperation); switch (resultKind.Value) { case ODataServiceOperationResultKind.QueryWithMultipleResults: if (serviceOperation.ReturnType.TypeKind() != EdmTypeKind.Entity) { throw new ODataException(Strings.MetadataBinder_QueryServiceOperationOfNonEntityType(serviceOperation.Name, resultKind.Value.ToString(), serviceOperation.ReturnType.ODataFullName())); } CollectionServiceOperationQueryNode collectionServiceOperationQueryNode = new CollectionServiceOperationQueryNode() { ServiceOperation = serviceOperation, Parameters = serviceOperationParameters }; if (segmentToken.NamedValues != null) { return this.BindKeyValues(collectionServiceOperationQueryNode, segmentToken.NamedValues); } else { return collectionServiceOperationQueryNode; } case ODataServiceOperationResultKind.QueryWithSingleResult: if (!serviceOperation.ReturnType.IsODataEntityTypeKind()) { throw new ODataException(Strings.MetadataBinder_QueryServiceOperationOfNonEntityType(serviceOperation.Name, resultKind.Value.ToString(), serviceOperation.ReturnType.ODataFullName())); } return new SingleValueServiceOperationQueryNode() { ServiceOperation = serviceOperation, Parameters = serviceOperationParameters }; case ODataServiceOperationResultKind.DirectValue: if (serviceOperation.ReturnType.IsODataPrimitiveTypeKind()) { // Direct primitive values are composable, $value is allowed on them. return new SingleValueServiceOperationQueryNode() { ServiceOperation = serviceOperation, Parameters = serviceOperationParameters }; } else { // Direct non-primitive values are not composable at all return new UncomposableServiceOperationQueryNode() { ServiceOperation = serviceOperation, Parameters = serviceOperationParameters }; } case ODataServiceOperationResultKind.Enumeration: case ODataServiceOperationResultKind.Void: // Enumeration and void service operations are not composable return new UncomposableServiceOperationQueryNode() { ServiceOperation = serviceOperation, Parameters = serviceOperationParameters }; default: throw new ODataException(Strings.General_InternalError(InternalErrorCodes.MetadataBinder_BindServiceOperation)); } } /// <summary> /// Binds the service operation parameters from query options. /// </summary> /// <param name="serviceOperation">The service operation to bind the parameters for.</param> /// <returns>Enumeration of parameter values for the service operation.</returns> private IEnumerable<QueryNode> BindServiceOperationParameters(IEdmFunctionImport serviceOperation) { Debug.Assert(serviceOperation != null, "serviceOperation != null"); //// This is a copy of RequestUriProcessor.ReadOperationParameters List<QueryNode> parameters = new List<QueryNode>(); foreach (IEdmFunctionParameter serviceOperationParameter in serviceOperation.Parameters) { IEdmTypeReference parameterType = serviceOperationParameter.Type; string parameterTextValue = this.ConsumeQueryOption(serviceOperationParameter.Name); object parameterValue; if (string.IsNullOrEmpty(parameterTextValue)) { if (!parameterType.IsNullable) { // The target parameter type is non-nullable, but we found null value, this usually means that the parameter is missing throw new ODataException(Strings.MetadataBinder_ServiceOperationParameterMissing(serviceOperation.Name, serviceOperationParameter.Name)); } parameterValue = null; } else { // We choose to be a little more flexible than with keys and // allow surrounding whitespace (which is never significant). parameterTextValue = parameterTextValue.Trim(); if (!UriPrimitiveTypeParser.TryUriStringToPrimitive(parameterTextValue, parameterType, out parameterValue)) { throw new ODataException(Strings.MetadataBinder_ServiceOperationParameterInvalidType(serviceOperationParameter.Name, parameterTextValue, serviceOperation.Name, serviceOperationParameter.Type.ODataFullName())); } } parameters.Add(new ConstantQueryNode() { Value = parameterValue }); } if (parameters.Count == 0) { return null; } return new ReadOnlyCollection<QueryNode>(parameters); } /// <summary> /// Binds key values to a key lookup on a collection. /// </summary> /// <param name="collectionQueryNode">Already bound collection node.</param> /// <param name="namedValues">The named value tokens to bind.</param> /// <returns>The bound key lookup.</returns> private QueryNode BindKeyValues(CollectionQueryNode collectionQueryNode, IEnumerable<NamedValue> namedValues) { Debug.Assert(namedValues != null, "namedValues != null"); Debug.Assert(collectionQueryNode != null, "collectionQueryNode != null"); Debug.Assert(collectionQueryNode.ItemType != null, "collectionQueryNode.ItemType != null"); IEdmTypeReference collectionItemType = collectionQueryNode.ItemType; List<KeyPropertyValue> keyPropertyValues = new List<KeyPropertyValue>(); if (!collectionItemType.IsODataEntityTypeKind()) { throw new ODataException(Strings.MetadataBinder_KeyValueApplicableOnlyToEntityType(collectionItemType.ODataFullName())); } IEdmEntityTypeReference collectionItemEntityTypeReference = collectionItemType.AsEntityOrNull(); Debug.Assert(collectionItemEntityTypeReference != null, "collectionItemEntityTypeReference != null"); IEdmEntityType collectionItemEntityType = collectionItemEntityTypeReference.EntityDefinition(); HashSet<string> keyPropertyNames = new HashSet<string>(StringComparer.Ordinal); foreach (NamedValue namedValue in namedValues) { KeyPropertyValue keyPropertyValue = this.BindKeyPropertyValue(namedValue, collectionItemEntityType); Debug.Assert(keyPropertyValue != null, "keyPropertyValue != null"); Debug.Assert(keyPropertyValue.KeyProperty != null, "keyPropertyValue.KeyProperty != null"); if (!keyPropertyNames.Add(keyPropertyValue.KeyProperty.Name)) { throw new ODataException(Strings.MetadataBinder_DuplicitKeyPropertyInKeyValues(keyPropertyValue.KeyProperty.Name)); } keyPropertyValues.Add(keyPropertyValue); } if (keyPropertyValues.Count == 0) { // No key values specified, for example '/Customers()', do not include the key lookup at all return collectionQueryNode; } else if (keyPropertyValues.Count != collectionItemEntityType.Key().Count()) { throw new ODataException(Strings.MetadataBinder_NotAllKeyPropertiesSpecifiedInKeyValues(collectionQueryNode.ItemType.ODataFullName())); } else { return new KeyLookupQueryNode() { Collection = collectionQueryNode, KeyPropertyValues = new ReadOnlyCollection<KeyPropertyValue>(keyPropertyValues) }; } } /// <summary> /// Binds a key property value. /// </summary> /// <param name="namedValue">The named value to bind.</param> /// <param name="collectionItemEntityType">The type of a single item in a collection to apply the key value to.</param> /// <returns>The bound key property value node.</returns> private KeyPropertyValue BindKeyPropertyValue(NamedValue namedValue, IEdmEntityType collectionItemEntityType) { // These are exception checks because the data comes directly from the potentially user specified tree. ExceptionUtils.CheckArgumentNotNull(namedValue, "namedValue"); ExceptionUtils.CheckArgumentNotNull(namedValue.Value, "namedValue.Value"); Debug.Assert(collectionItemEntityType != null, "collectionItemType != null"); IEdmProperty keyProperty = null; if (namedValue.Name == null) { foreach (IEdmProperty p in collectionItemEntityType.Key()) { if (keyProperty == null) { keyProperty = p; } else { throw new ODataException(Strings.MetadataBinder_UnnamedKeyValueOnTypeWithMultipleKeyProperties(collectionItemEntityType.ODataFullName())); } } } else { keyProperty = collectionItemEntityType.Key().Where(k => string.CompareOrdinal(k.Name, namedValue.Name) == 0).SingleOrDefault(); if (keyProperty == null) { throw new ODataException(Strings.MetadataBinder_PropertyNotDeclaredOrNotKeyInKeyValue(namedValue.Name, collectionItemEntityType.ODataFullName())); } } IEdmTypeReference keyPropertyType = keyProperty.Type; SingleValueQueryNode value = (SingleValueQueryNode)this.Bind(namedValue.Value); // TODO: Check that the value is of primitive type value = ConvertToType(value, keyPropertyType); Debug.Assert(keyProperty != null, "keyProperty != null"); return new KeyPropertyValue() { KeyProperty = keyProperty, KeyValue = value }; } /// <summary> /// Finds a query option by its name and consumes it (removes it from still available query options). /// </summary> /// <param name="queryOptionName">The query option name to get.</param> /// <returns>The value of the query option or null if it was not found.</returns> private string ConsumeQueryOption(string queryOptionName) { if (this.queryOptions != null) { return this.queryOptions.GetQueryOptionValueAndRemove(queryOptionName); } else { return null; } } } }
using System; using Box2D; using Box2D.Collision; using Box2D.Collision.Shapes; using Box2D.Common; using Box2D.Dynamics; using Box2D.Dynamics.Contacts; using Box2D.Dynamics.Joints; using Cocos2D; namespace AngryNinjas { public class Enemy : BodyNode { b2World theWorld; string baseImageName; string spriteImageName; CCPoint initialLocation; int breaksAfterHowMuchContact; //0 will break the enemy after first contact int damageLevel; //tracks how much damage has been done public bool BreaksOnNextDamage { get; set; } bool isRotationFixed; //enemy wont rotate if set to YES float theDensity; CreationMethod shapeCreationMethod; //same as all stack objects, check shape definitions in Constants.h public bool DamagesFromGroundContact { get; set; } public bool DamagesFromDamageEnabledStackObjects { get; set; } //stack objects must be enabled to damageEnemy bool differentSpritesForDamage; //whether or not you've included different images for damage progression (recommended) public int PointValue { get; set; } public BreakEffect SimpleScoreVisualFX { get; set; } //defined in constants, which visual effect occurs when the enemy breaks int currentFrame; int framesToAnimateOnBreak; //if 0 won't show any break frames bool enemyCantBeDamagedForShortInterval; // after damage occurs the enemy gets a moment of un-damage-abilty, which should play better ( I think) public Enemy (b2World world, CCPoint location, string spriteFileName, bool isTheRotationFixed, bool getsDamageFromGround, bool doesGetDamageFromDamageEnabledStackObjects, int breaksFromHowMuchContact, bool hasDifferentSpritesForDamage, int numberOfFramesToAnimateOnBreak, float density, CreationMethod createHow, int points, BreakEffect simpleScoreVisualFXType ) { InitWithWorld( world, location, spriteFileName, isTheRotationFixed, getsDamageFromGround, doesGetDamageFromDamageEnabledStackObjects, breaksFromHowMuchContact, hasDifferentSpritesForDamage, numberOfFramesToAnimateOnBreak, density, createHow, points, simpleScoreVisualFXType ); } void InitWithWorld(b2World world, CCPoint location, string spriteFileName, bool isTheRotationFixed, bool getsDamageFromGround, bool doesGetDamageFromDamageEnabledStackObjects, int breaksFromHowMuchContact, bool hasDifferentSpritesForDamage, int numberOfFramesToAnimateOnBreak, float density, CreationMethod createHow, int points, BreakEffect simpleScoreVisualFXType ) { this.theWorld = world; this.initialLocation = location; this.baseImageName = spriteFileName; this.spriteImageName = String.Format("{0}.png", baseImageName); this.DamagesFromGroundContact = getsDamageFromGround; // does the ground break / damage the enemy this.damageLevel = 0; //starts at 0, if breaksAfterHowMuchContact also equals 0 then the enemy will break on first/next contact this.breaksAfterHowMuchContact = breaksFromHowMuchContact; //contact must be made this many times before breaking, or if set to 0, the enemy will break on first/next contact this.differentSpritesForDamage = hasDifferentSpritesForDamage; //will progress through damage frames if this is YES, for example, enemy_damage1.png, enemy_damage2.png this.currentFrame = 0; this.framesToAnimateOnBreak = numberOfFramesToAnimateOnBreak; //will animate through breaks frames if this is more than 0, for example, enemy_break0001.png, enemy_break0002.png this.theDensity = density; this.shapeCreationMethod = createHow; this.isRotationFixed = isTheRotationFixed; this.PointValue = points ; this.SimpleScoreVisualFX = simpleScoreVisualFXType; this.DamagesFromDamageEnabledStackObjects = doesGetDamageFromDamageEnabledStackObjects; if ( damageLevel == breaksAfterHowMuchContact) { BreaksOnNextDamage = true; } else { BreaksOnNextDamage = false; //duh } CreateEnemy(); } void CreateEnemy () { // Define the dynamic body. var bodyDef = new b2BodyDef(); bodyDef.type = b2BodyType.b2_dynamicBody; //or you could use b2_staticBody bodyDef.fixedRotation = isRotationFixed; bodyDef.position.Set(initialLocation.X/Constants.PTM_RATIO, initialLocation.Y/Constants.PTM_RATIO); b2PolygonShape shape = new b2PolygonShape(); b2CircleShape shapeCircle = new b2CircleShape(); if (shapeCreationMethod == CreationMethod.DiameterOfImageForCircle) { var tempSprite = new CCSprite(spriteImageName); float radiusInMeters = (tempSprite.ContentSize.Width / Constants.PTM_RATIO) * 0.5f; shapeCircle.Radius = radiusInMeters; } else if ( shapeCreationMethod == CreationMethod.ShapeOfSourceImage) { var tempSprite = new CCSprite(spriteImageName); var num = 4; b2Vec2[] vertices = { new b2Vec2( (tempSprite.ContentSize.Width / -2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 ) / Constants.PTM_RATIO), //top left corner new b2Vec2( (tempSprite.ContentSize.Width / -2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 ) / Constants.PTM_RATIO), //bottom left corner new b2Vec2( (tempSprite.ContentSize.Width / 2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 )/ Constants.PTM_RATIO), //bottom right corner new b2Vec2( (tempSprite.ContentSize.Width / 2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 ) / Constants.PTM_RATIO) //top right corner }; shape.Set(vertices, num); } else if ( shapeCreationMethod == CreationMethod.ShapeOfSourceImageButSlightlySmaller ) { var tempSprite = new CCSprite(spriteImageName); var num = 4; b2Vec2[] vertices = { new b2Vec2( (tempSprite.ContentSize.Width / -2 ) *.8f / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 )*.8f / Constants.PTM_RATIO), //top left corner new b2Vec2( (tempSprite.ContentSize.Width / -2 )*.8f / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 )*.8f / Constants.PTM_RATIO), //bottom left corner new b2Vec2( (tempSprite.ContentSize.Width / 2 )*.8f / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 )*.8f / Constants.PTM_RATIO), //bottom right corner new b2Vec2( (tempSprite.ContentSize.Width / 2 )*.8f / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 )*.8f / Constants.PTM_RATIO) //top right corner }; shape.Set(vertices, num); } else if ( shapeCreationMethod == CreationMethod.Triangle) { var tempSprite = new CCSprite(spriteImageName); var num = 3; b2Vec2[] vertices = { new b2Vec2( (tempSprite.ContentSize.Width / -2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 ) / Constants.PTM_RATIO), //bottom left corner new b2Vec2( (tempSprite.ContentSize.Width / 2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 ) / Constants.PTM_RATIO), //bottom right corner new b2Vec2( 0.0f / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 )/ Constants.PTM_RATIO) // top center of image }; shape.Set(vertices, num); } else if ( shapeCreationMethod == CreationMethod.TriangleRightAngle) { var tempSprite = new CCSprite(spriteImageName); var num = 3; b2Vec2[] vertices = { new b2Vec2( (tempSprite.ContentSize.Width / 2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 ) / Constants.PTM_RATIO), //top right corner new b2Vec2( (tempSprite.ContentSize.Width / -2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 ) / Constants.PTM_RATIO), //top left corner new b2Vec2( (tempSprite.ContentSize.Width / -2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 )/ Constants.PTM_RATIO) //bottom left corner }; shape.Set(vertices, num); } else if ( shapeCreationMethod == CreationMethod.Trapezoid) { var tempSprite = new CCSprite(spriteImageName); var num = 4; b2Vec2[] vertices = { new b2Vec2( (tempSprite.ContentSize.Width / 4 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 ) / Constants.PTM_RATIO), //top of image, 3/4's across new b2Vec2( (tempSprite.ContentSize.Width / -4 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 ) / Constants.PTM_RATIO), //top of image, 1/4's across new b2Vec2( (tempSprite.ContentSize.Width / -2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 ) / Constants.PTM_RATIO), //bottom left corner new b2Vec2( (tempSprite.ContentSize.Width / 2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 ) / Constants.PTM_RATIO), //bottom right corner }; shape.Set(vertices, num); } else if ( shapeCreationMethod == CreationMethod.Hexagon) { var tempSprite = new CCSprite(spriteImageName); var num = 6; b2Vec2[] vertices = { new b2Vec2( (tempSprite.ContentSize.Width / -4 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 ) / Constants.PTM_RATIO), //top of image, 1/4 across new b2Vec2( (tempSprite.ContentSize.Width / -2 ) / Constants.PTM_RATIO, 0.0f / Constants.PTM_RATIO), // left, center new b2Vec2( (tempSprite.ContentSize.Width / -4 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 ) / Constants.PTM_RATIO), //bottom of image, 1/4 across new b2Vec2( (tempSprite.ContentSize.Width / 4 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 ) / Constants.PTM_RATIO), //bottom of image, 3/4's across new b2Vec2( (tempSprite.ContentSize.Width / 2 ) / Constants.PTM_RATIO, 0.0f / Constants.PTM_RATIO), // right, center new b2Vec2( (tempSprite.ContentSize.Width / 4 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 ) / Constants.PTM_RATIO) //top of image, 3/4's across }; shape.Set(vertices, num); } else if ( shapeCreationMethod == CreationMethod.Pentagon) { var tempSprite = new CCSprite(spriteImageName); var num = 5; b2Vec2[] vertices = { new b2Vec2( 0 / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 ) / Constants.PTM_RATIO), //top of image, center new b2Vec2( (tempSprite.ContentSize.Width / -2 ) / Constants.PTM_RATIO, 0.0f / Constants.PTM_RATIO), // left, center new b2Vec2( (tempSprite.ContentSize.Width / -4 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 ) / Constants.PTM_RATIO), //bottom of image, 1/4 across new b2Vec2( (tempSprite.ContentSize.Width / 4 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 ) / Constants.PTM_RATIO), //bottom of image, 3/4's across new b2Vec2( (tempSprite.ContentSize.Width / 2 ) / Constants.PTM_RATIO, 0.0f / Constants.PTM_RATIO), // right, center }; shape.Set(vertices, num); } else if ( shapeCreationMethod == CreationMethod.Octagon) { var tempSprite = new CCSprite(spriteImageName); var num = 8; b2Vec2[] vertices = { new b2Vec2( (tempSprite.ContentSize.Width / -6 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 ) / Constants.PTM_RATIO), //use the source image octogonShape.png for reference new b2Vec2( (tempSprite.ContentSize.Width / -2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 6 ) / Constants.PTM_RATIO), new b2Vec2( (tempSprite.ContentSize.Width / -2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -6 ) / Constants.PTM_RATIO), new b2Vec2( (tempSprite.ContentSize.Width / -6 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 ) / Constants.PTM_RATIO), new b2Vec2( (tempSprite.ContentSize.Width / 6 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 ) / Constants.PTM_RATIO), new b2Vec2( (tempSprite.ContentSize.Width / 2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -6 ) / Constants.PTM_RATIO), new b2Vec2( (tempSprite.ContentSize.Width / 2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 6 ) / Constants.PTM_RATIO), new b2Vec2( (tempSprite.ContentSize.Width / 6 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 ) / Constants.PTM_RATIO) }; shape.Set(vertices, num); } else if ( shapeCreationMethod == CreationMethod.Parallelogram) { var tempSprite = new CCSprite(spriteImageName); var num = 4; b2Vec2[] vertices = { new b2Vec2( (tempSprite.ContentSize.Width / -4 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 ) / Constants.PTM_RATIO), //top of image, 1/4 across new b2Vec2( (tempSprite.ContentSize.Width / -2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 ) / Constants.PTM_RATIO), //bottom left corner new b2Vec2( (tempSprite.ContentSize.Width / 4 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / -2 ) / Constants.PTM_RATIO), //bottom of image, 3/4's across new b2Vec2( (tempSprite.ContentSize.Width / 2 ) / Constants.PTM_RATIO, (tempSprite.ContentSize.Height / 2 ) / Constants.PTM_RATIO) //top right corner }; shape.Set(vertices, num); } else if ( shapeCreationMethod == CreationMethod.CustomCoordinates1) { //use your own custom coordinates from a program like Vertex Helper Pro var num = 4; b2Vec2[] vertices = { new b2Vec2(-64.0f / Constants.PTM_RATIO, 16.0f / Constants.PTM_RATIO), new b2Vec2(-64.0f / Constants.PTM_RATIO, -16.0f / Constants.PTM_RATIO), new b2Vec2(64.0f / Constants.PTM_RATIO, -16.0f / Constants.PTM_RATIO), new b2Vec2(64.0f / Constants.PTM_RATIO, 16.0f / Constants.PTM_RATIO) }; shape.Set(vertices, num); } // Define the dynamic body fixture. var fixtureDef = new b2FixtureDef(); if ( shapeCreationMethod == CreationMethod.DiameterOfImageForCircle) { fixtureDef.shape = shapeCircle; } else { fixtureDef.shape = shape; } fixtureDef.density = theDensity; fixtureDef.friction = 0.3f; fixtureDef.restitution = 0.1f; //how bouncy basically CreateBodyWithSpriteAndFixture(theWorld, bodyDef, fixtureDef, spriteImageName); var blinkInterval = Cocos2D.CCRandom.Next(3,8); // range 3 to 8 Schedule(Blink, blinkInterval); //comment this out if you never want to show the blink } public void DamageEnemy() { Unschedule(Blink); Unschedule(OpenEyes); if ( !enemyCantBeDamagedForShortInterval ) { damageLevel ++; enemyCantBeDamagedForShortInterval = true; ScheduleOnce(EnemyCanBeDamagedAgain, 1.0f); if ( differentSpritesForDamage ) { //GameSounds.SharedGameSounds.PlayVoiceSoundFX("enemyGrunt.mp3"); //that sound file doesn't exist sprite.Texture = new CCSprite(String.Format("{0}_damage{1}.png", baseImageName, damageLevel)).Texture; } if ( damageLevel == breaksAfterHowMuchContact ) { BreaksOnNextDamage = true; } } } void EnemyCanBeDamagedAgain(float delta) { enemyCantBeDamagedForShortInterval = false; } public void BreakEnemy () { Unschedule(Blink); Unschedule(OpenEyes); Schedule(StartBreakAnimation, 1.0f/30.0f); } void StartBreakAnimation(float delta) { if ( currentFrame == 0) { RemoveBody(); } currentFrame ++; //adds 1 every frame if (currentFrame <= framesToAnimateOnBreak ) { //if we included frames to show for breaking and the current frame is less than the max number of frames to play if (currentFrame < 10) { sprite.Texture = new CCSprite(String.Format("{0}_break000{1}.png", baseImageName, currentFrame)).Texture; } else if (currentFrame < 100) { sprite.Texture = new CCSprite(String.Format("{0}_break00{1}.png", baseImageName, currentFrame)).Texture; } } if (currentFrame > framesToAnimateOnBreak ) { //if the currentFrame equals the number of frames to animate, we remove the sprite OR if // the stackObject didn't include animated images for breaking RemoveSprite(); Unschedule(StartBreakAnimation); } } void Blink(float delta) { sprite.Texture = new CCSprite(String.Format("{0}_blink.png", baseImageName)).Texture; Unschedule(Blink); Schedule(OpenEyes, 0.5f); } void OpenEyes(float delta) { sprite.Texture = new CCSprite(String.Format("{0}.png", baseImageName)).Texture; Unschedule(OpenEyes); var blinkInterval = Cocos2D.CCRandom.Next(3,8);// random.Next(3,8); // range 3 to 8 Schedule(Blink,blinkInterval); } public void MakeUnScoreable() { PointValue = 0; CCLog.Log("points have been accumulated for this object"); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsHttp { using Microsoft.Rest; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// HttpServerFailure operations. /// </summary> public partial class HttpServerFailure : IServiceOperations<AutoRestHttpInfrastructureTestService>, IHttpServerFailure { /// <summary> /// Initializes a new instance of the HttpServerFailure class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public HttpServerFailure(AutoRestHttpInfrastructureTestService client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AutoRestHttpInfrastructureTestService /// </summary> public AutoRestHttpInfrastructureTestService Client { get; private set; } /// <summary> /// Return 501 status code - should be represented in the client as an error /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<Error>> Head501WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Head501", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/server/501").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("HEAD"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if (!_httpResponse.IsSuccessStatusCode) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Error>(); _result.Request = _httpRequest; _result.Response = _httpResponse; string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Return 501 status code - should be represented in the client as an error /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<Error>> Get501WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get501", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/server/501").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if (!_httpResponse.IsSuccessStatusCode) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Error>(); _result.Request = _httpRequest; _result.Response = _httpResponse; string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Return 505 status code - should be represented in the client as an error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<Error>> Post505WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("booleanValue", booleanValue); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Post505", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/server/505").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(booleanValue != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(booleanValue, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if (!_httpResponse.IsSuccessStatusCode) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Error>(); _result.Request = _httpRequest; _result.Response = _httpResponse; string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Return 505 status code - should be represented in the client as an error /// </summary> /// <param name='booleanValue'> /// Simple boolean value true /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<Error>> Delete505WithHttpMessagesAsync(bool? booleanValue = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("booleanValue", booleanValue); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete505", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "http/failure/server/505").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(booleanValue != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(booleanValue, Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if (!_httpResponse.IsSuccessStatusCode) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Error>(); _result.Request = _httpRequest; _result.Response = _httpResponse; string _defaultResponseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_defaultResponseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _defaultResponseContent, ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
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; namespace DalSic { /// <summary> /// Strongly-typed collection for the PnFamilium class. /// </summary> [Serializable] public partial class PnFamiliumCollection : ActiveList<PnFamilium, PnFamiliumCollection> { public PnFamiliumCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnFamiliumCollection</returns> public PnFamiliumCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnFamilium 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 PN_familia table. /// </summary> [Serializable] public partial class PnFamilium : ActiveRecord<PnFamilium>, IActiveRecord { #region .ctors and Default Settings public PnFamilium() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnFamilium(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnFamilium(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnFamilium(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } 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("PN_familia", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdFamilia = new TableSchema.TableColumn(schema); colvarIdFamilia.ColumnName = "id_familia"; colvarIdFamilia.DataType = DbType.Int32; colvarIdFamilia.MaxLength = 0; colvarIdFamilia.AutoIncrement = true; colvarIdFamilia.IsNullable = false; colvarIdFamilia.IsPrimaryKey = true; colvarIdFamilia.IsForeignKey = false; colvarIdFamilia.IsReadOnly = false; colvarIdFamilia.DefaultSetting = @""; colvarIdFamilia.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdFamilia); TableSchema.TableColumn colvarIdLegajo = new TableSchema.TableColumn(schema); colvarIdLegajo.ColumnName = "id_legajo"; colvarIdLegajo.DataType = DbType.Int32; colvarIdLegajo.MaxLength = 0; colvarIdLegajo.AutoIncrement = false; colvarIdLegajo.IsNullable = false; colvarIdLegajo.IsPrimaryKey = false; colvarIdLegajo.IsForeignKey = false; colvarIdLegajo.IsReadOnly = false; colvarIdLegajo.DefaultSetting = @""; colvarIdLegajo.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdLegajo); TableSchema.TableColumn colvarRelacion = new TableSchema.TableColumn(schema); colvarRelacion.ColumnName = "relacion"; colvarRelacion.DataType = DbType.AnsiString; colvarRelacion.MaxLength = -1; colvarRelacion.AutoIncrement = false; colvarRelacion.IsNullable = false; colvarRelacion.IsPrimaryKey = false; colvarRelacion.IsForeignKey = false; colvarRelacion.IsReadOnly = false; colvarRelacion.DefaultSetting = @""; colvarRelacion.ForeignKeyTableName = ""; schema.Columns.Add(colvarRelacion); TableSchema.TableColumn colvarNombreApellido = new TableSchema.TableColumn(schema); colvarNombreApellido.ColumnName = "nombre_apellido"; colvarNombreApellido.DataType = DbType.AnsiString; colvarNombreApellido.MaxLength = -1; colvarNombreApellido.AutoIncrement = false; colvarNombreApellido.IsNullable = false; colvarNombreApellido.IsPrimaryKey = false; colvarNombreApellido.IsForeignKey = false; colvarNombreApellido.IsReadOnly = false; colvarNombreApellido.DefaultSetting = @""; colvarNombreApellido.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombreApellido); TableSchema.TableColumn colvarFechaNacimiento = new TableSchema.TableColumn(schema); colvarFechaNacimiento.ColumnName = "fecha_nacimiento"; colvarFechaNacimiento.DataType = DbType.DateTime; colvarFechaNacimiento.MaxLength = 0; colvarFechaNacimiento.AutoIncrement = false; colvarFechaNacimiento.IsNullable = true; colvarFechaNacimiento.IsPrimaryKey = false; colvarFechaNacimiento.IsForeignKey = false; colvarFechaNacimiento.IsReadOnly = false; colvarFechaNacimiento.DefaultSetting = @""; colvarFechaNacimiento.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaNacimiento); TableSchema.TableColumn colvarDomicilio = new TableSchema.TableColumn(schema); colvarDomicilio.ColumnName = "domicilio"; colvarDomicilio.DataType = DbType.AnsiString; colvarDomicilio.MaxLength = -1; colvarDomicilio.AutoIncrement = false; colvarDomicilio.IsNullable = true; colvarDomicilio.IsPrimaryKey = false; colvarDomicilio.IsForeignKey = false; colvarDomicilio.IsReadOnly = false; colvarDomicilio.DefaultSetting = @""; colvarDomicilio.ForeignKeyTableName = ""; schema.Columns.Add(colvarDomicilio); TableSchema.TableColumn colvarDni = new TableSchema.TableColumn(schema); colvarDni.ColumnName = "dni"; colvarDni.DataType = DbType.AnsiString; colvarDni.MaxLength = -1; colvarDni.AutoIncrement = false; colvarDni.IsNullable = true; colvarDni.IsPrimaryKey = false; colvarDni.IsForeignKey = false; colvarDni.IsReadOnly = false; colvarDni.DefaultSetting = @""; colvarDni.ForeignKeyTableName = ""; schema.Columns.Add(colvarDni); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("PN_familia",schema); } } #endregion #region Props [XmlAttribute("IdFamilia")] [Bindable(true)] public int IdFamilia { get { return GetColumnValue<int>(Columns.IdFamilia); } set { SetColumnValue(Columns.IdFamilia, value); } } [XmlAttribute("IdLegajo")] [Bindable(true)] public int IdLegajo { get { return GetColumnValue<int>(Columns.IdLegajo); } set { SetColumnValue(Columns.IdLegajo, value); } } [XmlAttribute("Relacion")] [Bindable(true)] public string Relacion { get { return GetColumnValue<string>(Columns.Relacion); } set { SetColumnValue(Columns.Relacion, value); } } [XmlAttribute("NombreApellido")] [Bindable(true)] public string NombreApellido { get { return GetColumnValue<string>(Columns.NombreApellido); } set { SetColumnValue(Columns.NombreApellido, value); } } [XmlAttribute("FechaNacimiento")] [Bindable(true)] public DateTime? FechaNacimiento { get { return GetColumnValue<DateTime?>(Columns.FechaNacimiento); } set { SetColumnValue(Columns.FechaNacimiento, value); } } [XmlAttribute("Domicilio")] [Bindable(true)] public string Domicilio { get { return GetColumnValue<string>(Columns.Domicilio); } set { SetColumnValue(Columns.Domicilio, value); } } [XmlAttribute("Dni")] [Bindable(true)] public string Dni { get { return GetColumnValue<string>(Columns.Dni); } set { SetColumnValue(Columns.Dni, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdLegajo,string varRelacion,string varNombreApellido,DateTime? varFechaNacimiento,string varDomicilio,string varDni) { PnFamilium item = new PnFamilium(); item.IdLegajo = varIdLegajo; item.Relacion = varRelacion; item.NombreApellido = varNombreApellido; item.FechaNacimiento = varFechaNacimiento; item.Domicilio = varDomicilio; item.Dni = varDni; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdFamilia,int varIdLegajo,string varRelacion,string varNombreApellido,DateTime? varFechaNacimiento,string varDomicilio,string varDni) { PnFamilium item = new PnFamilium(); item.IdFamilia = varIdFamilia; item.IdLegajo = varIdLegajo; item.Relacion = varRelacion; item.NombreApellido = varNombreApellido; item.FechaNacimiento = varFechaNacimiento; item.Domicilio = varDomicilio; item.Dni = varDni; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdFamiliaColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdLegajoColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn RelacionColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn NombreApellidoColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn FechaNacimientoColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn DomicilioColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn DniColumn { get { return Schema.Columns[6]; } } #endregion #region Columns Struct public struct Columns { public static string IdFamilia = @"id_familia"; public static string IdLegajo = @"id_legajo"; public static string Relacion = @"relacion"; public static string NombreApellido = @"nombre_apellido"; public static string FechaNacimiento = @"fecha_nacimiento"; public static string Domicilio = @"domicilio"; public static string Dni = @"dni"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Gaming.V1.Snippets { using Google.Api.Gax; using Google.Api.Gax.ResourceNames; using Google.LongRunning; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedGameServerDeploymentsServiceClientSnippets { /// <summary>Snippet for ListGameServerDeployments</summary> public void ListGameServerDeploymentsRequestObject() { // Snippet: ListGameServerDeployments(ListGameServerDeploymentsRequest, CallSettings) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create(); // Initialize request argument(s) ListGameServerDeploymentsRequest request = new ListGameServerDeploymentsRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Filter = "", OrderBy = "", }; // Make the request PagedEnumerable<ListGameServerDeploymentsResponse, GameServerDeployment> response = gameServerDeploymentsServiceClient.ListGameServerDeployments(request); // Iterate over all response items, lazily performing RPCs as required foreach (GameServerDeployment item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListGameServerDeploymentsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (GameServerDeployment item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<GameServerDeployment> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (GameServerDeployment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListGameServerDeploymentsAsync</summary> public async Task ListGameServerDeploymentsRequestObjectAsync() { // Snippet: ListGameServerDeploymentsAsync(ListGameServerDeploymentsRequest, CallSettings) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync(); // Initialize request argument(s) ListGameServerDeploymentsRequest request = new ListGameServerDeploymentsRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Filter = "", OrderBy = "", }; // Make the request PagedAsyncEnumerable<ListGameServerDeploymentsResponse, GameServerDeployment> response = gameServerDeploymentsServiceClient.ListGameServerDeploymentsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((GameServerDeployment item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListGameServerDeploymentsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (GameServerDeployment item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<GameServerDeployment> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (GameServerDeployment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListGameServerDeployments</summary> public void ListGameServerDeployments() { // Snippet: ListGameServerDeployments(string, string, int?, CallSettings) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; // Make the request PagedEnumerable<ListGameServerDeploymentsResponse, GameServerDeployment> response = gameServerDeploymentsServiceClient.ListGameServerDeployments(parent); // Iterate over all response items, lazily performing RPCs as required foreach (GameServerDeployment item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListGameServerDeploymentsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (GameServerDeployment item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<GameServerDeployment> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (GameServerDeployment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListGameServerDeploymentsAsync</summary> public async Task ListGameServerDeploymentsAsync() { // Snippet: ListGameServerDeploymentsAsync(string, string, int?, CallSettings) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; // Make the request PagedAsyncEnumerable<ListGameServerDeploymentsResponse, GameServerDeployment> response = gameServerDeploymentsServiceClient.ListGameServerDeploymentsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((GameServerDeployment item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListGameServerDeploymentsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (GameServerDeployment item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<GameServerDeployment> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (GameServerDeployment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListGameServerDeployments</summary> public void ListGameServerDeploymentsResourceNames() { // Snippet: ListGameServerDeployments(LocationName, string, int?, CallSettings) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); // Make the request PagedEnumerable<ListGameServerDeploymentsResponse, GameServerDeployment> response = gameServerDeploymentsServiceClient.ListGameServerDeployments(parent); // Iterate over all response items, lazily performing RPCs as required foreach (GameServerDeployment item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListGameServerDeploymentsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (GameServerDeployment item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<GameServerDeployment> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (GameServerDeployment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListGameServerDeploymentsAsync</summary> public async Task ListGameServerDeploymentsResourceNamesAsync() { // Snippet: ListGameServerDeploymentsAsync(LocationName, string, int?, CallSettings) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); // Make the request PagedAsyncEnumerable<ListGameServerDeploymentsResponse, GameServerDeployment> response = gameServerDeploymentsServiceClient.ListGameServerDeploymentsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((GameServerDeployment item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListGameServerDeploymentsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (GameServerDeployment item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<GameServerDeployment> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (GameServerDeployment item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetGameServerDeployment</summary> public void GetGameServerDeploymentRequestObject() { // Snippet: GetGameServerDeployment(GetGameServerDeploymentRequest, CallSettings) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create(); // Initialize request argument(s) GetGameServerDeploymentRequest request = new GetGameServerDeploymentRequest { GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), }; // Make the request GameServerDeployment response = gameServerDeploymentsServiceClient.GetGameServerDeployment(request); // End snippet } /// <summary>Snippet for GetGameServerDeploymentAsync</summary> public async Task GetGameServerDeploymentRequestObjectAsync() { // Snippet: GetGameServerDeploymentAsync(GetGameServerDeploymentRequest, CallSettings) // Additional: GetGameServerDeploymentAsync(GetGameServerDeploymentRequest, CancellationToken) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync(); // Initialize request argument(s) GetGameServerDeploymentRequest request = new GetGameServerDeploymentRequest { GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), }; // Make the request GameServerDeployment response = await gameServerDeploymentsServiceClient.GetGameServerDeploymentAsync(request); // End snippet } /// <summary>Snippet for GetGameServerDeployment</summary> public void GetGameServerDeployment() { // Snippet: GetGameServerDeployment(string, CallSettings) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/gameServerDeployments/[DEPLOYMENT]"; // Make the request GameServerDeployment response = gameServerDeploymentsServiceClient.GetGameServerDeployment(name); // End snippet } /// <summary>Snippet for GetGameServerDeploymentAsync</summary> public async Task GetGameServerDeploymentAsync() { // Snippet: GetGameServerDeploymentAsync(string, CallSettings) // Additional: GetGameServerDeploymentAsync(string, CancellationToken) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/gameServerDeployments/[DEPLOYMENT]"; // Make the request GameServerDeployment response = await gameServerDeploymentsServiceClient.GetGameServerDeploymentAsync(name); // End snippet } /// <summary>Snippet for GetGameServerDeployment</summary> public void GetGameServerDeploymentResourceNames() { // Snippet: GetGameServerDeployment(GameServerDeploymentName, CallSettings) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create(); // Initialize request argument(s) GameServerDeploymentName name = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"); // Make the request GameServerDeployment response = gameServerDeploymentsServiceClient.GetGameServerDeployment(name); // End snippet } /// <summary>Snippet for GetGameServerDeploymentAsync</summary> public async Task GetGameServerDeploymentResourceNamesAsync() { // Snippet: GetGameServerDeploymentAsync(GameServerDeploymentName, CallSettings) // Additional: GetGameServerDeploymentAsync(GameServerDeploymentName, CancellationToken) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync(); // Initialize request argument(s) GameServerDeploymentName name = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"); // Make the request GameServerDeployment response = await gameServerDeploymentsServiceClient.GetGameServerDeploymentAsync(name); // End snippet } /// <summary>Snippet for CreateGameServerDeployment</summary> public void CreateGameServerDeploymentRequestObject() { // Snippet: CreateGameServerDeployment(CreateGameServerDeploymentRequest, CallSettings) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create(); // Initialize request argument(s) CreateGameServerDeploymentRequest request = new CreateGameServerDeploymentRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), DeploymentId = "", GameServerDeployment = new GameServerDeployment(), }; // Make the request Operation<GameServerDeployment, OperationMetadata> response = gameServerDeploymentsServiceClient.CreateGameServerDeployment(request); // Poll until the returned long-running operation is complete Operation<GameServerDeployment, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result GameServerDeployment result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<GameServerDeployment, OperationMetadata> retrievedResponse = gameServerDeploymentsServiceClient.PollOnceCreateGameServerDeployment(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result GameServerDeployment retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateGameServerDeploymentAsync</summary> public async Task CreateGameServerDeploymentRequestObjectAsync() { // Snippet: CreateGameServerDeploymentAsync(CreateGameServerDeploymentRequest, CallSettings) // Additional: CreateGameServerDeploymentAsync(CreateGameServerDeploymentRequest, CancellationToken) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync(); // Initialize request argument(s) CreateGameServerDeploymentRequest request = new CreateGameServerDeploymentRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), DeploymentId = "", GameServerDeployment = new GameServerDeployment(), }; // Make the request Operation<GameServerDeployment, OperationMetadata> response = await gameServerDeploymentsServiceClient.CreateGameServerDeploymentAsync(request); // Poll until the returned long-running operation is complete Operation<GameServerDeployment, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result GameServerDeployment result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<GameServerDeployment, OperationMetadata> retrievedResponse = await gameServerDeploymentsServiceClient.PollOnceCreateGameServerDeploymentAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result GameServerDeployment retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateGameServerDeployment</summary> public void CreateGameServerDeployment() { // Snippet: CreateGameServerDeployment(string, GameServerDeployment, CallSettings) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; GameServerDeployment gameServerDeployment = new GameServerDeployment(); // Make the request Operation<GameServerDeployment, OperationMetadata> response = gameServerDeploymentsServiceClient.CreateGameServerDeployment(parent, gameServerDeployment); // Poll until the returned long-running operation is complete Operation<GameServerDeployment, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result GameServerDeployment result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<GameServerDeployment, OperationMetadata> retrievedResponse = gameServerDeploymentsServiceClient.PollOnceCreateGameServerDeployment(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result GameServerDeployment retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateGameServerDeploymentAsync</summary> public async Task CreateGameServerDeploymentAsync() { // Snippet: CreateGameServerDeploymentAsync(string, GameServerDeployment, CallSettings) // Additional: CreateGameServerDeploymentAsync(string, GameServerDeployment, CancellationToken) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; GameServerDeployment gameServerDeployment = new GameServerDeployment(); // Make the request Operation<GameServerDeployment, OperationMetadata> response = await gameServerDeploymentsServiceClient.CreateGameServerDeploymentAsync(parent, gameServerDeployment); // Poll until the returned long-running operation is complete Operation<GameServerDeployment, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result GameServerDeployment result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<GameServerDeployment, OperationMetadata> retrievedResponse = await gameServerDeploymentsServiceClient.PollOnceCreateGameServerDeploymentAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result GameServerDeployment retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateGameServerDeployment</summary> public void CreateGameServerDeploymentResourceNames() { // Snippet: CreateGameServerDeployment(LocationName, GameServerDeployment, CallSettings) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); GameServerDeployment gameServerDeployment = new GameServerDeployment(); // Make the request Operation<GameServerDeployment, OperationMetadata> response = gameServerDeploymentsServiceClient.CreateGameServerDeployment(parent, gameServerDeployment); // Poll until the returned long-running operation is complete Operation<GameServerDeployment, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result GameServerDeployment result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<GameServerDeployment, OperationMetadata> retrievedResponse = gameServerDeploymentsServiceClient.PollOnceCreateGameServerDeployment(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result GameServerDeployment retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateGameServerDeploymentAsync</summary> public async Task CreateGameServerDeploymentResourceNamesAsync() { // Snippet: CreateGameServerDeploymentAsync(LocationName, GameServerDeployment, CallSettings) // Additional: CreateGameServerDeploymentAsync(LocationName, GameServerDeployment, CancellationToken) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); GameServerDeployment gameServerDeployment = new GameServerDeployment(); // Make the request Operation<GameServerDeployment, OperationMetadata> response = await gameServerDeploymentsServiceClient.CreateGameServerDeploymentAsync(parent, gameServerDeployment); // Poll until the returned long-running operation is complete Operation<GameServerDeployment, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result GameServerDeployment result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<GameServerDeployment, OperationMetadata> retrievedResponse = await gameServerDeploymentsServiceClient.PollOnceCreateGameServerDeploymentAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result GameServerDeployment retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteGameServerDeployment</summary> public void DeleteGameServerDeploymentRequestObject() { // Snippet: DeleteGameServerDeployment(DeleteGameServerDeploymentRequest, CallSettings) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create(); // Initialize request argument(s) DeleteGameServerDeploymentRequest request = new DeleteGameServerDeploymentRequest { GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), }; // Make the request Operation<Empty, OperationMetadata> response = gameServerDeploymentsServiceClient.DeleteGameServerDeployment(request); // Poll until the returned long-running operation is complete Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, OperationMetadata> retrievedResponse = gameServerDeploymentsServiceClient.PollOnceDeleteGameServerDeployment(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteGameServerDeploymentAsync</summary> public async Task DeleteGameServerDeploymentRequestObjectAsync() { // Snippet: DeleteGameServerDeploymentAsync(DeleteGameServerDeploymentRequest, CallSettings) // Additional: DeleteGameServerDeploymentAsync(DeleteGameServerDeploymentRequest, CancellationToken) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync(); // Initialize request argument(s) DeleteGameServerDeploymentRequest request = new DeleteGameServerDeploymentRequest { GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), }; // Make the request Operation<Empty, OperationMetadata> response = await gameServerDeploymentsServiceClient.DeleteGameServerDeploymentAsync(request); // Poll until the returned long-running operation is complete Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, OperationMetadata> retrievedResponse = await gameServerDeploymentsServiceClient.PollOnceDeleteGameServerDeploymentAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteGameServerDeployment</summary> public void DeleteGameServerDeployment() { // Snippet: DeleteGameServerDeployment(string, CallSettings) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/gameServerDeployments/[DEPLOYMENT]"; // Make the request Operation<Empty, OperationMetadata> response = gameServerDeploymentsServiceClient.DeleteGameServerDeployment(name); // Poll until the returned long-running operation is complete Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, OperationMetadata> retrievedResponse = gameServerDeploymentsServiceClient.PollOnceDeleteGameServerDeployment(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteGameServerDeploymentAsync</summary> public async Task DeleteGameServerDeploymentAsync() { // Snippet: DeleteGameServerDeploymentAsync(string, CallSettings) // Additional: DeleteGameServerDeploymentAsync(string, CancellationToken) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/gameServerDeployments/[DEPLOYMENT]"; // Make the request Operation<Empty, OperationMetadata> response = await gameServerDeploymentsServiceClient.DeleteGameServerDeploymentAsync(name); // Poll until the returned long-running operation is complete Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, OperationMetadata> retrievedResponse = await gameServerDeploymentsServiceClient.PollOnceDeleteGameServerDeploymentAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteGameServerDeployment</summary> public void DeleteGameServerDeploymentResourceNames() { // Snippet: DeleteGameServerDeployment(GameServerDeploymentName, CallSettings) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create(); // Initialize request argument(s) GameServerDeploymentName name = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"); // Make the request Operation<Empty, OperationMetadata> response = gameServerDeploymentsServiceClient.DeleteGameServerDeployment(name); // Poll until the returned long-running operation is complete Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, OperationMetadata> retrievedResponse = gameServerDeploymentsServiceClient.PollOnceDeleteGameServerDeployment(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteGameServerDeploymentAsync</summary> public async Task DeleteGameServerDeploymentResourceNamesAsync() { // Snippet: DeleteGameServerDeploymentAsync(GameServerDeploymentName, CallSettings) // Additional: DeleteGameServerDeploymentAsync(GameServerDeploymentName, CancellationToken) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync(); // Initialize request argument(s) GameServerDeploymentName name = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"); // Make the request Operation<Empty, OperationMetadata> response = await gameServerDeploymentsServiceClient.DeleteGameServerDeploymentAsync(name); // Poll until the returned long-running operation is complete Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, OperationMetadata> retrievedResponse = await gameServerDeploymentsServiceClient.PollOnceDeleteGameServerDeploymentAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateGameServerDeployment</summary> public void UpdateGameServerDeploymentRequestObject() { // Snippet: UpdateGameServerDeployment(UpdateGameServerDeploymentRequest, CallSettings) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create(); // Initialize request argument(s) UpdateGameServerDeploymentRequest request = new UpdateGameServerDeploymentRequest { GameServerDeployment = new GameServerDeployment(), UpdateMask = new FieldMask(), }; // Make the request Operation<GameServerDeployment, OperationMetadata> response = gameServerDeploymentsServiceClient.UpdateGameServerDeployment(request); // Poll until the returned long-running operation is complete Operation<GameServerDeployment, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result GameServerDeployment result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<GameServerDeployment, OperationMetadata> retrievedResponse = gameServerDeploymentsServiceClient.PollOnceUpdateGameServerDeployment(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result GameServerDeployment retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateGameServerDeploymentAsync</summary> public async Task UpdateGameServerDeploymentRequestObjectAsync() { // Snippet: UpdateGameServerDeploymentAsync(UpdateGameServerDeploymentRequest, CallSettings) // Additional: UpdateGameServerDeploymentAsync(UpdateGameServerDeploymentRequest, CancellationToken) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync(); // Initialize request argument(s) UpdateGameServerDeploymentRequest request = new UpdateGameServerDeploymentRequest { GameServerDeployment = new GameServerDeployment(), UpdateMask = new FieldMask(), }; // Make the request Operation<GameServerDeployment, OperationMetadata> response = await gameServerDeploymentsServiceClient.UpdateGameServerDeploymentAsync(request); // Poll until the returned long-running operation is complete Operation<GameServerDeployment, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result GameServerDeployment result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<GameServerDeployment, OperationMetadata> retrievedResponse = await gameServerDeploymentsServiceClient.PollOnceUpdateGameServerDeploymentAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result GameServerDeployment retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateGameServerDeployment</summary> public void UpdateGameServerDeployment() { // Snippet: UpdateGameServerDeployment(GameServerDeployment, FieldMask, CallSettings) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create(); // Initialize request argument(s) GameServerDeployment gameServerDeployment = new GameServerDeployment(); FieldMask updateMask = new FieldMask(); // Make the request Operation<GameServerDeployment, OperationMetadata> response = gameServerDeploymentsServiceClient.UpdateGameServerDeployment(gameServerDeployment, updateMask); // Poll until the returned long-running operation is complete Operation<GameServerDeployment, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result GameServerDeployment result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<GameServerDeployment, OperationMetadata> retrievedResponse = gameServerDeploymentsServiceClient.PollOnceUpdateGameServerDeployment(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result GameServerDeployment retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateGameServerDeploymentAsync</summary> public async Task UpdateGameServerDeploymentAsync() { // Snippet: UpdateGameServerDeploymentAsync(GameServerDeployment, FieldMask, CallSettings) // Additional: UpdateGameServerDeploymentAsync(GameServerDeployment, FieldMask, CancellationToken) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync(); // Initialize request argument(s) GameServerDeployment gameServerDeployment = new GameServerDeployment(); FieldMask updateMask = new FieldMask(); // Make the request Operation<GameServerDeployment, OperationMetadata> response = await gameServerDeploymentsServiceClient.UpdateGameServerDeploymentAsync(gameServerDeployment, updateMask); // Poll until the returned long-running operation is complete Operation<GameServerDeployment, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result GameServerDeployment result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<GameServerDeployment, OperationMetadata> retrievedResponse = await gameServerDeploymentsServiceClient.PollOnceUpdateGameServerDeploymentAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result GameServerDeployment retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for GetGameServerDeploymentRollout</summary> public void GetGameServerDeploymentRolloutRequestObject() { // Snippet: GetGameServerDeploymentRollout(GetGameServerDeploymentRolloutRequest, CallSettings) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create(); // Initialize request argument(s) GetGameServerDeploymentRolloutRequest request = new GetGameServerDeploymentRolloutRequest { GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), }; // Make the request GameServerDeploymentRollout response = gameServerDeploymentsServiceClient.GetGameServerDeploymentRollout(request); // End snippet } /// <summary>Snippet for GetGameServerDeploymentRolloutAsync</summary> public async Task GetGameServerDeploymentRolloutRequestObjectAsync() { // Snippet: GetGameServerDeploymentRolloutAsync(GetGameServerDeploymentRolloutRequest, CallSettings) // Additional: GetGameServerDeploymentRolloutAsync(GetGameServerDeploymentRolloutRequest, CancellationToken) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync(); // Initialize request argument(s) GetGameServerDeploymentRolloutRequest request = new GetGameServerDeploymentRolloutRequest { GameServerDeploymentName = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"), }; // Make the request GameServerDeploymentRollout response = await gameServerDeploymentsServiceClient.GetGameServerDeploymentRolloutAsync(request); // End snippet } /// <summary>Snippet for GetGameServerDeploymentRollout</summary> public void GetGameServerDeploymentRollout() { // Snippet: GetGameServerDeploymentRollout(string, CallSettings) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/gameServerDeployments/[DEPLOYMENT]"; // Make the request GameServerDeploymentRollout response = gameServerDeploymentsServiceClient.GetGameServerDeploymentRollout(name); // End snippet } /// <summary>Snippet for GetGameServerDeploymentRolloutAsync</summary> public async Task GetGameServerDeploymentRolloutAsync() { // Snippet: GetGameServerDeploymentRolloutAsync(string, CallSettings) // Additional: GetGameServerDeploymentRolloutAsync(string, CancellationToken) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/gameServerDeployments/[DEPLOYMENT]"; // Make the request GameServerDeploymentRollout response = await gameServerDeploymentsServiceClient.GetGameServerDeploymentRolloutAsync(name); // End snippet } /// <summary>Snippet for GetGameServerDeploymentRollout</summary> public void GetGameServerDeploymentRolloutResourceNames() { // Snippet: GetGameServerDeploymentRollout(GameServerDeploymentName, CallSettings) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create(); // Initialize request argument(s) GameServerDeploymentName name = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"); // Make the request GameServerDeploymentRollout response = gameServerDeploymentsServiceClient.GetGameServerDeploymentRollout(name); // End snippet } /// <summary>Snippet for GetGameServerDeploymentRolloutAsync</summary> public async Task GetGameServerDeploymentRolloutResourceNamesAsync() { // Snippet: GetGameServerDeploymentRolloutAsync(GameServerDeploymentName, CallSettings) // Additional: GetGameServerDeploymentRolloutAsync(GameServerDeploymentName, CancellationToken) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync(); // Initialize request argument(s) GameServerDeploymentName name = GameServerDeploymentName.FromProjectLocationDeployment("[PROJECT]", "[LOCATION]", "[DEPLOYMENT]"); // Make the request GameServerDeploymentRollout response = await gameServerDeploymentsServiceClient.GetGameServerDeploymentRolloutAsync(name); // End snippet } /// <summary>Snippet for UpdateGameServerDeploymentRollout</summary> public void UpdateGameServerDeploymentRolloutRequestObject() { // Snippet: UpdateGameServerDeploymentRollout(UpdateGameServerDeploymentRolloutRequest, CallSettings) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create(); // Initialize request argument(s) UpdateGameServerDeploymentRolloutRequest request = new UpdateGameServerDeploymentRolloutRequest { Rollout = new GameServerDeploymentRollout(), UpdateMask = new FieldMask(), }; // Make the request Operation<GameServerDeployment, OperationMetadata> response = gameServerDeploymentsServiceClient.UpdateGameServerDeploymentRollout(request); // Poll until the returned long-running operation is complete Operation<GameServerDeployment, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result GameServerDeployment result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<GameServerDeployment, OperationMetadata> retrievedResponse = gameServerDeploymentsServiceClient.PollOnceUpdateGameServerDeploymentRollout(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result GameServerDeployment retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateGameServerDeploymentRolloutAsync</summary> public async Task UpdateGameServerDeploymentRolloutRequestObjectAsync() { // Snippet: UpdateGameServerDeploymentRolloutAsync(UpdateGameServerDeploymentRolloutRequest, CallSettings) // Additional: UpdateGameServerDeploymentRolloutAsync(UpdateGameServerDeploymentRolloutRequest, CancellationToken) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync(); // Initialize request argument(s) UpdateGameServerDeploymentRolloutRequest request = new UpdateGameServerDeploymentRolloutRequest { Rollout = new GameServerDeploymentRollout(), UpdateMask = new FieldMask(), }; // Make the request Operation<GameServerDeployment, OperationMetadata> response = await gameServerDeploymentsServiceClient.UpdateGameServerDeploymentRolloutAsync(request); // Poll until the returned long-running operation is complete Operation<GameServerDeployment, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result GameServerDeployment result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<GameServerDeployment, OperationMetadata> retrievedResponse = await gameServerDeploymentsServiceClient.PollOnceUpdateGameServerDeploymentRolloutAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result GameServerDeployment retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateGameServerDeploymentRollout</summary> public void UpdateGameServerDeploymentRollout() { // Snippet: UpdateGameServerDeploymentRollout(GameServerDeploymentRollout, FieldMask, CallSettings) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create(); // Initialize request argument(s) GameServerDeploymentRollout rollout = new GameServerDeploymentRollout(); FieldMask updateMask = new FieldMask(); // Make the request Operation<GameServerDeployment, OperationMetadata> response = gameServerDeploymentsServiceClient.UpdateGameServerDeploymentRollout(rollout, updateMask); // Poll until the returned long-running operation is complete Operation<GameServerDeployment, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result GameServerDeployment result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<GameServerDeployment, OperationMetadata> retrievedResponse = gameServerDeploymentsServiceClient.PollOnceUpdateGameServerDeploymentRollout(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result GameServerDeployment retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateGameServerDeploymentRolloutAsync</summary> public async Task UpdateGameServerDeploymentRolloutAsync() { // Snippet: UpdateGameServerDeploymentRolloutAsync(GameServerDeploymentRollout, FieldMask, CallSettings) // Additional: UpdateGameServerDeploymentRolloutAsync(GameServerDeploymentRollout, FieldMask, CancellationToken) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync(); // Initialize request argument(s) GameServerDeploymentRollout rollout = new GameServerDeploymentRollout(); FieldMask updateMask = new FieldMask(); // Make the request Operation<GameServerDeployment, OperationMetadata> response = await gameServerDeploymentsServiceClient.UpdateGameServerDeploymentRolloutAsync(rollout, updateMask); // Poll until the returned long-running operation is complete Operation<GameServerDeployment, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result GameServerDeployment result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<GameServerDeployment, OperationMetadata> retrievedResponse = await gameServerDeploymentsServiceClient.PollOnceUpdateGameServerDeploymentRolloutAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result GameServerDeployment retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for PreviewGameServerDeploymentRollout</summary> public void PreviewGameServerDeploymentRolloutRequestObject() { // Snippet: PreviewGameServerDeploymentRollout(PreviewGameServerDeploymentRolloutRequest, CallSettings) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create(); // Initialize request argument(s) PreviewGameServerDeploymentRolloutRequest request = new PreviewGameServerDeploymentRolloutRequest { Rollout = new GameServerDeploymentRollout(), UpdateMask = new FieldMask(), PreviewTime = new Timestamp(), }; // Make the request PreviewGameServerDeploymentRolloutResponse response = gameServerDeploymentsServiceClient.PreviewGameServerDeploymentRollout(request); // End snippet } /// <summary>Snippet for PreviewGameServerDeploymentRolloutAsync</summary> public async Task PreviewGameServerDeploymentRolloutRequestObjectAsync() { // Snippet: PreviewGameServerDeploymentRolloutAsync(PreviewGameServerDeploymentRolloutRequest, CallSettings) // Additional: PreviewGameServerDeploymentRolloutAsync(PreviewGameServerDeploymentRolloutRequest, CancellationToken) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync(); // Initialize request argument(s) PreviewGameServerDeploymentRolloutRequest request = new PreviewGameServerDeploymentRolloutRequest { Rollout = new GameServerDeploymentRollout(), UpdateMask = new FieldMask(), PreviewTime = new Timestamp(), }; // Make the request PreviewGameServerDeploymentRolloutResponse response = await gameServerDeploymentsServiceClient.PreviewGameServerDeploymentRolloutAsync(request); // End snippet } /// <summary>Snippet for FetchDeploymentState</summary> public void FetchDeploymentStateRequestObject() { // Snippet: FetchDeploymentState(FetchDeploymentStateRequest, CallSettings) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = GameServerDeploymentsServiceClient.Create(); // Initialize request argument(s) FetchDeploymentStateRequest request = new FetchDeploymentStateRequest { Name = "", }; // Make the request FetchDeploymentStateResponse response = gameServerDeploymentsServiceClient.FetchDeploymentState(request); // End snippet } /// <summary>Snippet for FetchDeploymentStateAsync</summary> public async Task FetchDeploymentStateRequestObjectAsync() { // Snippet: FetchDeploymentStateAsync(FetchDeploymentStateRequest, CallSettings) // Additional: FetchDeploymentStateAsync(FetchDeploymentStateRequest, CancellationToken) // Create client GameServerDeploymentsServiceClient gameServerDeploymentsServiceClient = await GameServerDeploymentsServiceClient.CreateAsync(); // Initialize request argument(s) FetchDeploymentStateRequest request = new FetchDeploymentStateRequest { Name = "", }; // Make the request FetchDeploymentStateResponse response = await gameServerDeploymentsServiceClient.FetchDeploymentStateAsync(request); // End snippet } } }
/* ************************************************************************* ** Custom classes used by C# ************************************************************************* */ using System; using System.Diagnostics; using System.IO; #if !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE) using System.Management; #endif using System.Text; using System.Text.RegularExpressions; using System.Threading; using i64 = System.Int64; using u32 = System.UInt32; using time_t = System.Int64; namespace Community.CsharpSqlite { using sqlite3_value = Sqlite3.Mem; public partial class Sqlite3 { static int atoi( byte[] inStr ) { return atoi( Encoding.UTF8.GetString( inStr, 0, inStr.Length ) ); } static int atoi( string inStr ) { int i; for ( i = 0; i < inStr.Length; i++ ) { if ( !sqlite3Isdigit( inStr[i] ) && inStr[i] != '-' ) break; } int result = 0; #if WINDOWS_MOBILE try { result = Int32.Parse(inStr.Substring(0, i)); } catch { } return result; #else return ( Int32.TryParse( inStr.Substring( 0, i ), out result ) ? result : 0 ); #endif } static void fprintf( TextWriter tw, string zFormat, params object[] ap ) { tw.Write( String.Format( zFormat, ap ) ); } static void printf( string zFormat, params object[] ap ) { Console.Out.Write( String.Format( zFormat, ap ) ); } //Byte Buffer Testing static int memcmp( byte[] bA, byte[] bB, int Limit ) { if ( bA.Length < Limit ) return ( bA.Length < bB.Length ) ? -1 : +1; if ( bB.Length < Limit ) return +1; for ( int i = 0; i < Limit; i++ ) { if ( bA[i] != bB[i] ) return ( bA[i] < bB[i] ) ? -1 : 1; } return 0; } //Byte Buffer & String Testing static int memcmp( string A, byte[] bB, int Limit ) { if ( A.Length < Limit ) return ( A.Length < bB.Length ) ? -1 : +1; if ( bB.Length < Limit ) return +1; char[] cA = A.ToCharArray(); for ( int i = 0; i < Limit; i++ ) { if ( cA[i] != bB[i] ) return ( cA[i] < bB[i] ) ? -1 : 1; } return 0; } //byte with Offset & String Testing static int memcmp( byte[] a, int Offset, byte[] b, int Limit ) { if ( a.Length < Offset + Limit ) return ( a.Length - Offset < b.Length ) ? -1 : +1; if ( b.Length < Limit ) return +1; for ( int i = 0; i < Limit; i++ ) { if ( a[i + Offset] != b[i] ) return ( a[i + Offset] < b[i] ) ? -1 : 1; } return 0; } //byte with Offset & String Testing static int memcmp( byte[] a, int Aoffset, byte[] b, int Boffset, int Limit ) { if ( a.Length < Aoffset + Limit ) return ( a.Length - Aoffset < b.Length - Boffset ) ? -1 : +1; if ( b.Length < Boffset + Limit ) return +1; for ( int i = 0; i < Limit; i++ ) { if ( a[i + Aoffset] != b[i + Boffset] ) return ( a[i + Aoffset] < b[i + Boffset] ) ? -1 : 1; } return 0; } static int memcmp( byte[] a, int Offset, string b, int Limit ) { if ( a.Length < Offset + Limit ) return ( a.Length - Offset < b.Length ) ? -1 : +1; if ( b.Length < Limit ) return +1; for ( int i = 0; i < Limit; i++ ) { if ( a[i + Offset] != b[i] ) return ( a[i + Offset] < b[i] ) ? -1 : 1; } return 0; } //String Testing static int memcmp( string A, string B, int Limit ) { if ( A.Length < Limit ) return ( A.Length < B.Length ) ? -1 : +1; if ( B.Length < Limit ) return +1; int rc; if ( (rc = String.Compare( A, 0, B, 0, Limit, StringComparison.Ordinal )) == 0 ) return 0; return rc < 0 ? -1 : +1; } // ---------------------------- // ** Builtin Functions // ---------------------------- static Regex oRegex = null; /* ** The regexp() function. two arguments are both strings ** Collating sequences are not used. */ static void regexpFunc( sqlite3_context context, int argc, sqlite3_value[] argv ) { string zTest; /* The input string A */ string zRegex; /* The regex string B */ Debug.Assert( argc == 2 ); UNUSED_PARAMETER( argc ); zRegex = sqlite3_value_text( argv[0] ); zTest = sqlite3_value_text( argv[1] ); if ( zTest == null || String.IsNullOrEmpty( zRegex ) ) { sqlite3_result_int( context, 0 ); return; } if ( oRegex == null || oRegex.ToString() == zRegex ) { oRegex = new Regex( zRegex, RegexOptions.IgnoreCase ); } sqlite3_result_int( context, oRegex.IsMatch( zTest ) ? 1 : 0 ); } // ---------------------------- // ** Convertion routines // ---------------------------- static Object lock_va_list= new Object(); static string vaFORMAT; static int vaNEXT; static void va_start( object[] ap, string zFormat ) { vaFORMAT = zFormat; vaNEXT = 0; } static object va_arg( object[] ap, string sysType ) { vaNEXT += 1; if ( ap == null || ap.Length == 0 ) return ""; switch ( sysType ) { case "double": return Convert.ToDouble( ap[vaNEXT - 1] ); case "long": case "long int": case "longlong int": case "i64": if ( ap[vaNEXT - 1].GetType().BaseType.Name == "Object" ) return (i64)( ap[vaNEXT - 1].GetHashCode() ); ; return Convert.ToInt64( ap[vaNEXT - 1] ); case "int": if ( Convert.ToInt64( ap[vaNEXT - 1] ) > 0 && ( Convert.ToUInt32( ap[vaNEXT - 1] ) > Int32.MaxValue ) ) return (Int32)( Convert.ToUInt32( ap[vaNEXT - 1] ) - System.UInt32.MaxValue - 1 ); else return (Int32)Convert.ToInt32( ap[vaNEXT - 1] ); case "SrcList": return (SrcList)ap[vaNEXT - 1]; case "char": if ( ap[vaNEXT - 1].GetType().Name == "Int32" && (int)ap[vaNEXT - 1] == 0 ) { return (char)'0'; } else { if ( ap[vaNEXT - 1].GetType().Name == "Int64" ) if ( (i64)ap[vaNEXT - 1] == 0 ) { return (char)'0'; } else return (char)( (i64)ap[vaNEXT - 1] ); else return (char)ap[vaNEXT - 1]; } case "char*": case "string": if ( ap.Length<vaNEXT || ap[vaNEXT - 1] == null ) { return "NULL"; } else { if ( ap[vaNEXT - 1].GetType().Name == "Byte[]" ) if ( Encoding.UTF8.GetString( (byte[])ap[vaNEXT - 1], 0, ( (byte[])ap[vaNEXT - 1] ).Length ) == "\0" ) return ""; else return Encoding.UTF8.GetString( (byte[])ap[vaNEXT - 1], 0, ( (byte[])ap[vaNEXT - 1] ).Length ); else if ( ap[vaNEXT - 1].GetType().Name == "Int32" ) return null; else if ( ap[vaNEXT - 1].GetType().Name == "StringBuilder" ) return (string)ap[vaNEXT - 1].ToString(); else return (string)ap[vaNEXT - 1]; } case "byte[]": if ( ap[vaNEXT - 1] == null ) { return null; } else { return (byte[])ap[vaNEXT - 1]; } case "byte[][]": if ( ap[vaNEXT - 1] == null ) { return null; } else { return (byte[][])ap[vaNEXT - 1]; } case "int[]": if ( ap[vaNEXT - 1] == null ) { return "NULL"; } else { return (int[])ap[vaNEXT - 1]; } case "Token": return (Token)ap[vaNEXT - 1]; case "u3216": return Convert.ToUInt16( ap[vaNEXT - 1] ); case "u32": case "unsigned int": if ( ap[vaNEXT - 1].GetType().IsClass ) { return ap[vaNEXT - 1].GetHashCode(); } else { return Convert.ToUInt32( ap[vaNEXT - 1] ); } case "u64": case "unsigned long": case "unsigned long int": if ( ap[vaNEXT - 1].GetType().IsClass ) return Convert.ToUInt64( ap[vaNEXT - 1].GetHashCode() ); else return Convert.ToUInt64( ap[vaNEXT - 1] ); case "sqlite3_mem_methods": return (sqlite3_mem_methods)ap[vaNEXT - 1]; case "void_function": return (void_function)ap[vaNEXT - 1]; case "MemPage": return (MemPage)ap[vaNEXT - 1]; case "sqlite3": return (sqlite3)ap[vaNEXT - 1]; default: Debugger.Break(); return ap[vaNEXT - 1]; } } static void va_end( ref string[] ap ) { ap = null; vaFORMAT = ""; } static void va_end( ref object[] ap ) { ap = null; vaFORMAT = ""; } public static tm localtime( time_t baseTime ) { System.DateTime RefTime = new System.DateTime( 1970, 1, 1, 0, 0, 0, 0 ); RefTime = RefTime.AddSeconds( Convert.ToDouble( baseTime ) ).ToLocalTime(); tm tm = new tm(); tm.tm_sec = RefTime.Second; tm.tm_min = RefTime.Minute; tm.tm_hour = RefTime.Hour; tm.tm_mday = RefTime.Day; tm.tm_mon = RefTime.Month; tm.tm_year = RefTime.Year; tm.tm_wday = (int)RefTime.DayOfWeek; tm.tm_yday = RefTime.DayOfYear; tm.tm_isdst = RefTime.IsDaylightSavingTime() ? 1 : 0; return tm; } public static long ToUnixtime( System.DateTime date ) { System.DateTime unixStartTime = new System.DateTime( 1970, 1, 1, 0, 0, 0, 0 ); System.TimeSpan timeSpan = date - unixStartTime; return Convert.ToInt64( timeSpan.TotalSeconds ); } public static System.DateTime ToCSharpTime( long unixTime ) { System.DateTime unixStartTime = new System.DateTime( 1970, 1, 1, 0, 0, 0, 0 ); return unixStartTime.AddSeconds( Convert.ToDouble( unixTime ) ); } public struct tm { public int tm_sec; /* seconds after the minute - [0,59] */ public int tm_min; /* minutes after the hour - [0,59] */ public int tm_hour; /* hours since midnight - [0,23] */ public int tm_mday; /* day of the month - [1,31] */ public int tm_mon; /* months since January - [0,11] */ public int tm_year; /* years since 1900 */ public int tm_wday; /* days since Sunday - [0,6] */ public int tm_yday; /* days since January 1 - [0,365] */ public int tm_isdst; /* daylight savings time flag */ }; public struct FILETIME { public u32 dwLowDateTime; public u32 dwHighDateTime; } // Example (C#) public static int GetbytesPerSector( StringBuilder diskPath ) { #if !(SQLITE_SILVERLIGHT || WINDOWS_MOBILE) ManagementObjectSearcher mosLogicalDisks = new ManagementObjectSearcher( "select * from Win32_LogicalDisk where DeviceID = '" + diskPath.ToString().Remove( diskPath.Length - 1, 1 ) + "'" ); try { foreach ( ManagementObject moLogDisk in mosLogicalDisks.Get() ) { ManagementObjectSearcher mosDiskDrives = new ManagementObjectSearcher( "select * from Win32_DiskDrive where SystemName = '" + moLogDisk["SystemName"] + "'" ); foreach ( ManagementObject moPDisk in mosDiskDrives.Get() ) { return int.Parse( moPDisk["BytesPerSector"].ToString() ); } } } catch { } return 4096; #else return 4096; #endif } static void SWAP<T>( ref T A, ref T B ) { T t = A; A = B; B = t; } static void x_CountStep( sqlite3_context context, int argc, sqlite3_value[] argv ) { SumCtx p; int type; Debug.Assert( argc <= 1 ); Mem pMem = sqlite3_aggregate_context( context, 1 );//sizeof(*p)); if ( pMem._SumCtx == null ) pMem._SumCtx = new SumCtx(); p = pMem._SumCtx; if ( p.Context == null ) p.Context = pMem; if ( argc == 0 || SQLITE_NULL == sqlite3_value_type( argv[0] ) ) { p.cnt++; p.iSum += 1; } else { type = sqlite3_value_numeric_type( argv[0] ); if ( p != null && type != SQLITE_NULL ) { p.cnt++; if ( type == SQLITE_INTEGER ) { i64 v = sqlite3_value_int64( argv[0] ); if ( v == 40 || v == 41 ) { sqlite3_result_error( context, "value of " + v + " handed to x_count", -1 ); return; } else { p.iSum += v; if ( !( p.approx | p.overflow != 0 ) ) { i64 iNewSum = p.iSum + v; int s1 = (int)( p.iSum >> ( sizeof( i64 ) * 8 - 1 ) ); int s2 = (int)( v >> ( sizeof( i64 ) * 8 - 1 ) ); int s3 = (int)( iNewSum >> ( sizeof( i64 ) * 8 - 1 ) ); p.overflow = ( ( s1 & s2 & ~s3 ) | ( ~s1 & ~s2 & s3 ) ) != 0 ? 1 : 0; p.iSum = iNewSum; } } } else { p.rSum += sqlite3_value_double( argv[0] ); p.approx = true; } } } } static void x_CountFinalize( sqlite3_context context ) { SumCtx p; Mem pMem = sqlite3_aggregate_context( context, 0 ); p = pMem._SumCtx; if ( p != null && p.cnt > 0 ) { if ( p.overflow != 0 ) { sqlite3_result_error( context, "integer overflow", -1 ); } else if ( p.approx ) { sqlite3_result_double( context, p.rSum ); } else if ( p.iSum == 42 ) { sqlite3_result_error( context, "x_count totals to 42", -1 ); } else { sqlite3_result_int64( context, p.iSum ); } } } #if SQLITE_MUTEX_W32 //---------------------WIN32 Definitions static int GetCurrentThreadId() { return Thread.CurrentThread.ManagedThreadId; } static long InterlockedIncrement(long location) { Interlocked.Increment(ref location); return location; } static void EnterCriticalSection( Object mtx ) { //long mid = mtx.GetHashCode(); //int tid = Thread.CurrentThread.ManagedThreadId; //long ticks = cnt++; //Debug.WriteLine(String.Format( "{2}: +EnterCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, ticks) ); Monitor.Enter( mtx ); } static void InitializeCriticalSection( Object mtx ) { //Debug.WriteLine(String.Format( "{2}: +InitializeCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks )); Monitor.Enter( mtx ); } static void DeleteCriticalSection( Object mtx ) { //Debug.WriteLine(String.Format( "{2}: +DeleteCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks) ); Monitor.Exit( mtx ); } static void LeaveCriticalSection( Object mtx ) { //Debug.WriteLine(String.Format("{2}: +LeaveCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks )); Monitor.Exit( mtx ); } #endif // Miscellaneous Windows Constants //#define ERROR_HANDLE_DISK_FULL 39L const long ERROR_HANDLE_DISK_FULL = 39L; private class SQLite3UpperToLower { static int[] sqlite3UpperToLower = new int[] { #if SQLITE_ASCII 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103, 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121, 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107, 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125, 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161, 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179, 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197, 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215, 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233, 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251, 252,253,254,255 #endif }; public int this[int index] { get { if ( index < sqlite3UpperToLower.Length ) return sqlite3UpperToLower[index]; else return index; } } } static SQLite3UpperToLower sqlite3UpperToLower = new SQLite3UpperToLower(); static SQLite3UpperToLower UpperToLower = sqlite3UpperToLower; } }
/* * (c) Copyright Marek Ledvina, Foriero Studo */ using UnityEngine; using System.Collections; namespace ForieroEngine.MIDIUnified { public enum TheorySystemEnum { EnglishNames, FixedSolfege, MovableSolfege, Undefined = int.MaxValue } public static class MidiConversion { //FORMAT : C2 or C2# or C2## the same for flats// public static byte NoteToMidiIndex (string aMidiString) { byte result = 0; switch (aMidiString.Length) { case 2: result = (byte)(BaseMidiIndex (aMidiString [0]) + OctaveMidiIndex (byte.Parse (aMidiString [1].ToString ()))); break; case 3: result = (byte)(BaseMidiIndex (aMidiString [0]) + OctaveMidiIndex (byte.Parse (aMidiString [1].ToString ())) + AccidentalShift (aMidiString [2].ToString ())); break; case 4: result = (byte)(BaseMidiIndex (aMidiString [0]) + OctaveMidiIndex (byte.Parse (aMidiString [1].ToString ())) + AccidentalShift (aMidiString.Substring (2))); break; } return result; } public static int GetByteVolume (float aVolume) { return (int)(Mathf.Clamp01 (aVolume) * 127); } public static int ToByteVolume (this float volume) { return (int)(Mathf.Clamp01 (volume) * 127); } public static int GetMidiVolume (float aVolume) { int result = 0; if (aVolume > 0) { if (aVolume < 1) { result = Mathf.RoundToInt (127f * aVolume); } else result = 127; } else result = 0; return result; } public static int GetByteVolume (float aVolume, int aStreamVolume) { return (int)(Mathf.Clamp01 (aVolume) * aStreamVolume); } public static byte OctaveMidiIndex (byte anOctaveIndex) { return (byte)(anOctaveIndex * 12); } public static int AccidentalShift (string anAccidental) { int result = 0; switch (anAccidental) { case "#": result = 1; break; case "##": result = 2; break; case "b": result = -1; break; case "bb": result = -2; break; } return result; } public static byte BaseMidiIndex (char aNoteName) { byte result = 0; switch (aNoteName) { case 'C': result = 0; break; case 'D': result = 2; break; case 'E': result = 4; break; case 'F': result = 5; break; case 'G': result = 7; break; case 'A': result = 9; break; case 'B': result = 11; break; default : result = 0; break; } return result; } public static int BaseMidiIndex (int aMidiIdx) { while (aMidiIdx > 11) { aMidiIdx -= 12; } return aMidiIdx; } public static bool IsBlackKey (int aMidiIdx) { int baseIndex = BaseMidiIndex (aMidiIdx); bool result = false; switch (baseIndex) { case 1: result = true; break; case 3: result = true; break; case 6: result = true; break; case 8: result = true; break; case 10: result = true; break; } return result; } public static bool IsWhiteKey (int aMidiIdx) { int baseIndex = BaseMidiIndex (aMidiIdx); bool result = true; switch (baseIndex) { case 1: result = false; break; case 3: result = false; break; case 6: result = false; break; case 8: result = false; break; case 10: result = false; break; } return result; } public static int ToIntervalBaseIndex (this string anIntervalName) { int result = 0; switch (anIntervalName) { case "P1": result = 0; break; case "m2": result = 1; break; case "M2": result = 2; break; case "m3": result = 3; break; case "M3": result = 4; break; case "P4": result = 5; break; case "TT": result = 6; break; case "P5": result = 7; break; case "m6": result = 8; break; case "M6": result = 9; break; case "m7": result = 10; break; case "M7": result = 11; break; case "P8": result = 12; break; } return result; } public static IntervalEnum ToIntervalBaseEnum (this string anIntervalName) { IntervalEnum result = IntervalEnum.P1; switch (anIntervalName) { case "P1": result = IntervalEnum.P1; break; case "m2": result = IntervalEnum.m2; break; case "M2": result = IntervalEnum.M2; break; case "m3": result = IntervalEnum.m3; break; case "M3": result = IntervalEnum.M3; break; case "P4": result = IntervalEnum.P4; break; case "TT": result = IntervalEnum.TT; break; case "P5": result = IntervalEnum.P5; break; case "m6": result = IntervalEnum.m6; break; case "M6": result = IntervalEnum.M6; break; case "m7": result = IntervalEnum.m7; break; case "M7": result = IntervalEnum.M7; break; case "P8": result = IntervalEnum.P8; break; } return result; } public static ToneEnum GetBaseToneFromMidiIndex (int aMidiIdx) { while (aMidiIdx > 11) { aMidiIdx -= 12; } ToneEnum result = ToneEnum.A; switch (aMidiIdx) { case 0: result = ToneEnum.C; break; case 1: result = ToneEnum.CSharpDFlat; break; case 2: result = ToneEnum.D; break; case 3: result = ToneEnum.DSharpEFlat; break; case 4: result = ToneEnum.E; break; case 5: result = ToneEnum.F; break; case 6: result = ToneEnum.FSharpGFlat; break; case 7: result = ToneEnum.G; break; case 8: result = ToneEnum.GSharpAFlat; break; case 9: result = ToneEnum.A; break; case 10: result = ToneEnum.ASharpBFlat; break; case 11: result = ToneEnum.B; break; } return result; } public static Color GetToneColor (ToneEnum aTone) { Color result = Color.black; switch (aTone) { case ToneEnum.A: result = HexToRGB (74, 1, 200); break; case ToneEnum.ASharpBFlat: result = HexToRGB (49, 49, 236); break; case ToneEnum.B: result = HexToRGB (3, 146, 206); break; case ToneEnum.C: result = HexToRGB (74, 176, 2); break; case ToneEnum.CSharpDFlat: result = HexToRGB (188, 217, 2); break; case ToneEnum.D: result = HexToRGB (247, 233, 0); break; case ToneEnum.DSharpEFlat: result = HexToRGB (242, 185, 12); break; case ToneEnum.E: result = HexToRGB (251, 153, 2); break; case ToneEnum.F: result = HexToRGB (253, 91, 19); break; case ToneEnum.FSharpGFlat: result = HexToRGB (238, 0, 0); break; case ToneEnum.G: result = HexToRGB (202, 0, 69); break; case ToneEnum.GSharpAFlat: result = HexToRGB (141, 29, 175); break; } return result; } public static TheorySystemEnum theorySystem = TheorySystemEnum.EnglishNames; public static string ToToneEnglishName (this int midiIndex, char separator = '/') { return GetToneEnglishNameFromMidiIndex (midiIndex, separator); } public static string GetToneNameFromMidiIndex (int aMidiIdx, char separator = '/', TheorySystemEnum aTheorySystem = TheorySystemEnum.EnglishNames, KeySignatureEnum aKeySignature = KeySignatureEnum.CMaj_AMin) { string result = ""; switch (aTheorySystem) { case TheorySystemEnum.EnglishNames: result = GetToneEnglishNameFromMidiIndex (aMidiIdx, separator); break; case TheorySystemEnum.FixedSolfege: result = GetToneSolfageNameFromMidiIndex (aMidiIdx, KeySignatureEnum.CMaj_AMin, separator); break; case TheorySystemEnum.MovableSolfege: result = GetToneSolfageNameFromMidiIndex (aMidiIdx, aKeySignature, separator); break; } return result; } public static string GetToneEnglishNameFromMidiIndex (int aMidiIdx, char separator = '/') { while (aMidiIdx > 11) { aMidiIdx -= 12; } string result = ""; switch (aMidiIdx) { case 0: result = "C"; break; case 1: result = "C#" + separator + "Db"; break; case 2: result = "D"; break; case 3: result = "D#" + separator + "Eb"; break; case 4: result = "E"; break; case 5: result = "F"; break; case 6: result = "F#" + separator + "Gb"; break; case 7: result = "G"; break; case 8: result = "G#" + separator + "Ab"; break; case 9: result = "A"; break; case 10: result = "A#" + separator + "Hb"; break; case 11: result = "H"; break; } return result; } public static string GetToneSolfageNameFromMidiIndex (int aMidiIdx, KeySignatureEnum aKeySignature = KeySignatureEnum.CMaj_AMin, char separator = '/') { aMidiIdx += (int)aKeySignature * 7; while (aMidiIdx > 11) { aMidiIdx -= 12; } string result = ""; switch (aMidiIdx) { case 0: result = "Do"; break; case 1: result = "Di" + separator + "Ra"; break; case 2: result = "Re"; break; case 3: result = "Ri" + separator + "Me"; break; case 4: result = "Mi"; break; case 5: result = "Fa"; break; case 6: result = "Fi" + separator + "Se"; break; case 7: result = "Sol"; break; case 8: result = "Si" + separator + "Le"; break; case 9: result = "La"; break; case 10: result = "Li" + separator + "Te"; break; case 11: result = "Ti"; break; } return result; } public static Color GetToneColorFromMidiIndex (int aMidiIdx) { while (aMidiIdx > 11) { aMidiIdx -= 12; } Color result = Color.black; switch (aMidiIdx) { case 0: result = GetToneColor (ToneEnum.C); break; case 1: result = GetToneColor (ToneEnum.CSharpDFlat); break; case 2: result = GetToneColor (ToneEnum.D); break; case 3: result = GetToneColor (ToneEnum.DSharpEFlat); break; case 4: result = GetToneColor (ToneEnum.E); break; case 5: result = GetToneColor (ToneEnum.F); break; case 6: result = GetToneColor (ToneEnum.FSharpGFlat); break; case 7: result = GetToneColor (ToneEnum.G); break; case 8: result = GetToneColor (ToneEnum.GSharpAFlat); break; case 9: result = GetToneColor (ToneEnum.A); break; case 10: result = GetToneColor (ToneEnum.ASharpBFlat); break; case 11: result = GetToneColor (ToneEnum.B); break; } return result; } public static char GetHex (int anInt) { string alpha = "0123456789ABCDEF"; char result = alpha [anInt]; return result; } public static int HexToInt (char hexChar) { int result = -1; string hex = hexChar.ToString (); switch (hex) { case "0": result = 0; break; case "1": result = 1; break; case "2": result = 2; break; case "3": result = 3; break; case "4": result = 4; break; case "5": result = 5; break; case "6": result = 6; break; case "7": result = 7; break; case "8": result = 8; break; case "9": result = 9; break; case "A": result = 10; break; case "B": result = 11; break; case "C": result = 12; break; case "D": result = 13; break; case "E": result = 14; break; case "F": result = 15; break; } return result; } public static string RGBToHex (Color aColor) { float red = aColor.r * 255f; float green = aColor.g * 255f; float blue = aColor.b * 255f; char a = GetHex (Mathf.FloorToInt (red / 16f)); char b = GetHex (Mathf.RoundToInt (red % 16f)); char c = GetHex (Mathf.FloorToInt (green / 16f)); char d = GetHex (Mathf.RoundToInt (green % 16f)); char e = GetHex (Mathf.FloorToInt (blue / 16f)); char f = GetHex (Mathf.RoundToInt (blue % 16f)); string z = a.ToString () + b.ToString () + c.ToString () + d.ToString () + e.ToString () + f.ToString (); return z; } public static Color HexToRGB (int r, int g, int b) { float red = (r) / 255f; float green = (g) / 255f; float blue = (b) / 255f; var finalColor = new Color (); finalColor.r = red; finalColor.g = green; finalColor.b = blue; finalColor.a = 1; return finalColor; } public static Color HexToRGB (string aColorHex) { float red = (HexToInt (aColorHex [0]) + HexToInt (aColorHex [1]) * 16f) / 255f; float green = (HexToInt (aColorHex [2]) + HexToInt (aColorHex [3]) * 16f) / 255f; float blue = (HexToInt (aColorHex [4]) + HexToInt (aColorHex [5]) * 16f) / 255f; var finalColor = new Color (); finalColor.r = red; finalColor.g = green; finalColor.b = blue; finalColor.a = 1; return finalColor; } /// <summary>"C2", "C#3", "Cb4" /// number = octave index /// # | b = accidentals /// A,B,C,D,E,F,G = note names public static int MidiStringToMidiIndex (string s) { int midiShift = 0; int octaveIndex = 0; int noteIndex = BaseMidiIndex (s [0]); if (s.Contains ("#")) { midiShift++; octaveIndex = int.Parse (s [2].ToString ()); } else if (s.Contains ("b")) { midiShift--; octaveIndex = int.Parse (s [2].ToString ()); } else { octaveIndex = int.Parse (s [1].ToString ()); } return octaveIndex * 12 + noteIndex + midiShift; } } }
namespace Rs317.Sharp { public sealed class CollisionMap { private int insetX; private int insetY; private int width; private int height; public int[,] clippingData; public CollisionMap() { insetX = 0; insetY = 0; width = 104; height = 104; clippingData = new int[width, height]; reset(); } public void markBlocked(int x, int y) { x -= insetX; y -= insetY; clippingData[x, y] |= 0x200000; } public void markSolidOccupant(int x, int y, int width, int height, int orientation, bool impenetrable) { int occupied = 256; if (impenetrable) occupied += 0x20000; x -= insetX; y -= insetY; if (orientation == 1 || orientation == 3) { int temp = width; width = height; height = temp; } for (int _x = x; _x < x + width; _x++) if (_x >= 0 && _x < this.width) { for (int _y = y; _y < y + height; _y++) if (_y >= 0 && _y < this.height) set(_x, _y, occupied); } } public void markWall(int y, int orientation, int x, int position, bool impenetrable) { x -= insetX; y -= insetY; if (position == 0) { if (orientation == 0) { set(x, y, 128); set(x - 1, y, 8); } if (orientation == 1) { set(x, y, 2); set(x, y + 1, 32); } if (orientation == 2) { set(x, y, 8); set(x + 1, y, 128); } if (orientation == 3) { set(x, y, 32); set(x, y - 1, 2); } } if (position == 1 || position == 3) { if (orientation == 0) { set(x, y, 1); set(x - 1, y + 1, 16); } if (orientation == 1) { set(x, y, 4); set(x + 1, y + 1, 64); } if (orientation == 2) { set(x, y, 16); set(x + 1, y - 1, 1); } if (orientation == 3) { set(x, y, 64); set(x - 1, y - 1, 4); } } if (position == 2) { if (orientation == 0) { set(x, y, 130); set(x - 1, y, 8); set(x, y + 1, 32); } if (orientation == 1) { set(x, y, 10); set(x, y + 1, 32); set(x + 1, y, 128); } if (orientation == 2) { set(x, y, 40); set(x + 1, y, 128); set(x, y - 1, 2); } if (orientation == 3) { set(x, y, 160); set(x, y - 1, 2); set(x - 1, y, 8); } } if (impenetrable) { if (position == 0) { if (orientation == 0) { set(x, y, 0x10000); set(x - 1, y, 4096); } if (orientation == 1) { set(x, y, 1024); set(x, y + 1, 16384); } if (orientation == 2) { set(x, y, 4096); set(x + 1, y, 0x10000); } if (orientation == 3) { set(x, y, 16384); set(x, y - 1, 1024); } } if (position == 1 || position == 3) { if (orientation == 0) { set(x, y, 512); set(x - 1, y + 1, 8192); } if (orientation == 1) { set(x, y, 2048); set(x + 1, y + 1, 32768); } if (orientation == 2) { set(x, y, 8192); set(x + 1, y - 1, 512); } if (orientation == 3) { set(x, y, 32768); set(x - 1, y - 1, 2048); } } if (position == 2) { if (orientation == 0) { set(x, y, 0x10400); set(x - 1, y, 4096); set(x, y + 1, 16384); } if (orientation == 1) { set(x, y, 5120); set(x, y + 1, 16384); set(x + 1, y, 0x10000); } if (orientation == 2) { set(x, y, 20480); set(x + 1, y, 0x10000); set(x, y - 1, 1024); } if (orientation == 3) { set(x, y, 0x14000); set(x, y - 1, 1024); set(x - 1, y, 4096); } } } } public bool reachedFacingObject(int startX, int startY, int endX, int endY, int endDistanceX, int endDistanceY, int surroundings) { int endX2 = (endX + endDistanceX) - 1; int endY2 = (endY + endDistanceY) - 1; if (startX >= endX && startX <= endX2 && startY >= endY && startY <= endY2) return true; if (startX == endX - 1 && startY >= endY && startY <= endY2 && (clippingData[startX - insetX, startY - insetY] & 8) == 0 && (surroundings & 8) == 0) return true; if (startX == endX2 + 1 && startY >= endY && startY <= endY2 && (clippingData[startX - insetX, startY - insetY] & 0x80) == 0 && (surroundings & 2) == 0) return true; return startY == endY - 1 && startX >= endX && startX <= endX2 && (clippingData[startX - insetX, startY - insetY] & 2) == 0 && (surroundings & 4) == 0 || startY == endY2 + 1 && startX >= endX && startX <= endX2 && (clippingData[startX - insetX, startY - insetY] & 0x20) == 0 && (surroundings & 1) == 0; } public bool reachedWall(int startX, int startY, int endX, int endY, int endPosition, int endOrientation) { if (startX == endX && startY == endY) return true; startX -= insetX; startY -= insetY; endX -= insetX; endY -= insetY; if (endPosition == 0) if (endOrientation == 0) { if (startX == endX - 1 && startY == endY) return true; if (startX == endX && startY == endY + 1 && (clippingData[startX, startY] & 0x1280120) == 0) return true; if (startX == endX && startY == endY - 1 && (clippingData[startX, startY] & 0x1280102) == 0) return true; } else if (endOrientation == 1) { if (startX == endX && startY == endY + 1) return true; if (startX == endX - 1 && startY == endY && (clippingData[startX, startY] & 0x1280108) == 0) return true; if (startX == endX + 1 && startY == endY && (clippingData[startX, startY] & 0x1280180) == 0) return true; } else if (endOrientation == 2) { if (startX == endX + 1 && startY == endY) return true; if (startX == endX && startY == endY + 1 && (clippingData[startX, startY] & 0x1280120) == 0) return true; if (startX == endX && startY == endY - 1 && (clippingData[startX, startY] & 0x1280102) == 0) return true; } else if (endOrientation == 3) { if (startX == endX && startY == endY - 1) return true; if (startX == endX - 1 && startY == endY && (clippingData[startX, startY] & 0x1280108) == 0) return true; if (startX == endX + 1 && startY == endY && (clippingData[startX, startY] & 0x1280180) == 0) return true; } if (endPosition == 2) if (endOrientation == 0) { if (startX == endX - 1 && startY == endY) return true; if (startX == endX && startY == endY + 1) return true; if (startX == endX + 1 && startY == endY && (clippingData[startX, startY] & 0x1280180) == 0) return true; if (startX == endX && startY == endY - 1 && (clippingData[startX, startY] & 0x1280102) == 0) return true; } else if (endOrientation == 1) { if (startX == endX - 1 && startY == endY && (clippingData[startX, startY] & 0x1280108) == 0) return true; if (startX == endX && startY == endY + 1) return true; if (startX == endX + 1 && startY == endY) return true; if (startX == endX && startY == endY - 1 && (clippingData[startX, startY] & 0x1280102) == 0) return true; } else if (endOrientation == 2) { if (startX == endX - 1 && startY == endY && (clippingData[startX, startY] & 0x1280108) == 0) return true; if (startX == endX && startY == endY + 1 && (clippingData[startX, startY] & 0x1280120) == 0) return true; if (startX == endX + 1 && startY == endY) return true; if (startX == endX && startY == endY - 1) return true; } else if (endOrientation == 3) { if (startX == endX - 1 && startY == endY) return true; if (startX == endX && startY == endY + 1 && (clippingData[startX, startY] & 0x1280120) == 0) return true; if (startX == endX + 1 && startY == endY && (clippingData[startX, startY] & 0x1280180) == 0) return true; if (startX == endX && startY == endY - 1) return true; } if (endPosition == 9) { if (startX == endX && startY == endY + 1 && (clippingData[startX, startY] & 0x20) == 0) return true; if (startX == endX && startY == endY - 1 && (clippingData[startX, startY] & 2) == 0) return true; if (startX == endX - 1 && startY == endY && (clippingData[startX, startY] & 8) == 0) return true; if (startX == endX + 1 && startY == endY && (clippingData[startX, startY] & 0x80) == 0) return true; } return false; } public bool reachedWallDecoration(int startX, int startY, int endX, int endY, int endPosition, int endOrientation) { if (startX == endX && startY == endY) return true; startX -= insetX; startY -= insetY; endX -= insetX; endY -= insetY; if (endPosition == 6 || endPosition == 7) { if (endPosition == 7) endOrientation = endOrientation + 2 & 3; if (endOrientation == 0) { if (startX == endX + 1 && startY == endY && (clippingData[startX, startY] & 0x80) == 0) return true; if (startX == endX && startY == endY - 1 && (clippingData[startX, startY] & 2) == 0) return true; } else if (endOrientation == 1) { if (startX == endX - 1 && startY == endY && (clippingData[startX, startY] & 8) == 0) return true; if (startX == endX && startY == endY - 1 && (clippingData[startX, startY] & 2) == 0) return true; } else if (endOrientation == 2) { if (startX == endX - 1 && startY == endY && (clippingData[startX, startY] & 8) == 0) return true; if (startX == endX && startY == endY + 1 && (clippingData[startX, startY] & 0x20) == 0) return true; } else if (endOrientation == 3) { if (startX == endX + 1 && startY == endY && (clippingData[startX, startY] & 0x80) == 0) return true; if (startX == endX && startY == endY + 1 && (clippingData[startX, startY] & 0x20) == 0) return true; } } if (endPosition == 8) { if (startX == endX && startY == endY + 1 && (clippingData[startX, startY] & 0x20) == 0) return true; if (startX == endX && startY == endY - 1 && (clippingData[startX, startY] & 2) == 0) return true; if (startX == endX - 1 && startY == endY && (clippingData[startX, startY] & 8) == 0) return true; if (startX == endX + 1 && startY == endY && (clippingData[startX, startY] & 0x80) == 0) return true; } return false; } public void reset() { for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) if (x == 0 || y == 0 || x == width - 1 || y == height - 1) clippingData[x, y] = 0xffffff; else clippingData[x, y] = 0x1000000; } } private void set(int x, int y, int flag) { clippingData[x, y] |= flag; } public void unmarkConcealed(int x, int y) { x -= insetX; y -= insetY; clippingData[x, y] &= 0xdfffff; } public void unmarkSolidOccupant(int x, int y, int width, int height, int orientation, bool impenetrable) { int occupied = 256; if (impenetrable) occupied += 0x20000; x -= insetX; y -= insetY; if (orientation == 1 || orientation == 3) { int temp = width; width = height; height = temp; } for (int _x = x; _x < x + width; _x++) if (_x >= 0 && _x < this.width) { for (int _y = y; _y < y + height; _y++) if (_y >= 0 && _y < this.height) unset(_x, _y, occupied); } } public void unmarkWall(int x, int y, int position, int orientation, bool impenetrable) { x -= insetX; y -= insetY; if (position == 0) { if (orientation == 0) { unset(x, y, 128); unset(x - 1, y, 8); } if (orientation == 1) { unset(x, y, 2); unset(x, y + 1, 32); } if (orientation == 2) { unset(x, y, 8); unset(x + 1, y, 128); } if (orientation == 3) { unset(x, y, 32); unset(x, y - 1, 2); } } if (position == 1 || position == 3) { if (orientation == 0) { unset(x, y, 1); unset(x - 1, y + 1, 16); } if (orientation == 1) { unset(x, y, 4); unset(x + 1, y + 1, 64); } if (orientation == 2) { unset(x, y, 16); unset(x + 1, y - 1, 1); } if (orientation == 3) { unset(x, y, 64); unset(x - 1, y - 1, 4); } } if (position == 2) { if (orientation == 0) { unset(x, y, 130); unset(x - 1, y, 8); unset(x, y + 1, 32); } if (orientation == 1) { unset(x, y, 10); unset(x, y + 1, 32); unset(x + 1, y, 128); } if (orientation == 2) { unset(x, y, 40); unset(x + 1, y, 128); unset(x, y - 1, 2); } if (orientation == 3) { unset(x, y, 160); unset(x, y - 1, 2); unset(x - 1, y, 8); } } if (impenetrable) { if (position == 0) { if (orientation == 0) { unset(x, y, 0x10000); unset(x - 1, y, 4096); } if (orientation == 1) { unset(x, y, 1024); unset(x, y + 1, 16384); } if (orientation == 2) { unset(x, y, 4096); unset(x + 1, y, 0x10000); } if (orientation == 3) { unset(x, y, 16384); unset(x, y - 1, 1024); } } if (position == 1 || position == 3) { if (orientation == 0) { unset(x, y, 512); unset(x - 1, y + 1, 8192); } if (orientation == 1) { unset(x, y, 2048); unset(x + 1, y + 1, 32768); } if (orientation == 2) { unset(x, y, 8192); unset(x + 1, y - 1, 512); } if (orientation == 3) { unset(x, y, 32768); unset(x - 1, y - 1, 2048); } } if (position == 2) { if (orientation == 0) { unset(x, y, 0x10400); unset(x - 1, y, 4096); unset(x, y + 1, 16384); } if (orientation == 1) { unset(x, y, 5120); unset(x, y + 1, 16384); unset(x + 1, y, 0x10000); } if (orientation == 2) { unset(x, y, 20480); unset(x + 1, y, 0x10000); unset(x, y - 1, 1024); } if (orientation == 3) { unset(x, y, 0x14000); unset(x, y - 1, 1024); unset(x - 1, y, 4096); } } } } private void unset(int x, int y, int flag) { clippingData[x, y] &= 0xffffff - flag; } } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Drawing; using System.IO; using System.Runtime.InteropServices; using Microsoft.Win32; using ESRI.ArcGIS.ADF.BaseClasses; using ESRI.ArcGIS.ADF.CATIDs; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.DataSourcesFile; using ESRI.ArcGIS.Display; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.Geometry; using ESRI.ArcGIS.SystemUI; using ESRI.ArcGIS.GlobeCore; using ESRI.ArcGIS.Controls; using ESRI.ArcGIS.Analyst3D; namespace GlobeDynamicObjectTracking { /// <summary> /// This command demonstrates tracking dynamic object in ArcGlobe/GlobeControl with the camera /// </summary> [Guid("DCB871A1-390A-456f-8A0D-9FDB6A20F721")] [ClassInterface(ClassInterfaceType.None)] [ProgId("GlobeControlApp.TrackDynamicObject")] public sealed class TrackDynamicObject : BaseCommand, IDisposable { #region COM Registration Function(s) [ComRegisterFunction()] [ComVisible(false)] static void RegisterFunction(Type registerType) { // Required for ArcGIS Component Category Registrar support ArcGISCategoryRegistration(registerType); // // TODO: Add any COM registration code here // } [ComUnregisterFunction()] [ComVisible(false)] static void UnregisterFunction(Type registerType) { // Required for ArcGIS Component Category Registrar support ArcGISCategoryUnregistration(registerType); // // TODO: Add any COM unregistration code here // } #region ArcGIS Component Category Registrar generated code /// <summary> /// Required method for ArcGIS Component Category registration - /// Do not modify the contents of this method with the code editor. /// </summary> private static void ArcGISCategoryRegistration(Type registerType) { string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID); GMxCommands.Register(regKey); ControlsCommands.Register(regKey); } /// <summary> /// Required method for ArcGIS Component Category unregistration - /// Do not modify the contents of this method with the code editor. /// </summary> private static void ArcGISCategoryUnregistration(Type registerType) { string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID); GMxCommands.Unregister(regKey); ControlsCommands.Unregister(regKey); } #endregion #endregion //class members private IGlobeHookHelper m_globeHookHelper = null; private IGlobeDisplay m_globeDisplay = null; private ISceneViewer m_sceneViwer = null; private IGlobeGraphicsLayer m_globeGraphicsLayer = null; private IRealTimeFeedManager m_realTimeFeedManager = null; private IRealTimeFeed m_realTimeFeed = null; private bool m_bConnected = false; private bool m_bTrackAboveTarget = true; private bool m_once = true; private int m_trackObjectIndex = -1; private string m_shapefileName = string.Empty; #region Ctor /// <summary> /// Class Ctor /// </summary> public TrackDynamicObject() { base.m_category = ".NET Samples"; base.m_caption = "Track Dynamic Object"; base.m_message = "Tracking a dynamic object"; base.m_toolTip = "Track Dynamic Object"; base.m_name = base.m_category + "_" + base.m_caption; try { string bitmapResourceName = GetType().Name + ".bmp"; base.m_bitmap = new Bitmap(GetType(), bitmapResourceName); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message, "Invalid Bitmap"); } } #endregion #region Overriden Class Methods /// <summary> /// Occurs when this command is created /// </summary> /// <param name="hook">Instance of the application</param> public override void OnCreate(object hook) { //initialize the hook-helper if (m_globeHookHelper == null) m_globeHookHelper = new GlobeHookHelper(); //set the hook m_globeHookHelper.Hook = hook; //set the path to the featureclass used by the GPS simulator string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); m_shapefileName = System.IO.Path.Combine(path, @"ArcGIS\data\USAMajorHighways\usa_major_highways.shp"); System.Diagnostics.Debug.WriteLine(string.Format("File path for data root: {0}", m_shapefileName)); if (! File.Exists(m_shapefileName)) throw new Exception(string.Format("Fix code to point to your sample data: {0} was not found", m_shapefileName)); //get the GlobeDisplsy from the hook helper m_globeDisplay = m_globeHookHelper.GlobeDisplay; //initialize the real-time manager if (null == m_realTimeFeedManager) m_realTimeFeedManager = new RealTimeFeedManagerClass(); //use the built in simulator of the real-time manager m_realTimeFeedManager.RealTimeFeed = m_realTimeFeedManager.RealTimeFeedSimulator as IRealTimeFeed; m_realTimeFeed = m_realTimeFeedManager.RealTimeFeed; } /// <summary> /// Occurs when this command is clicked /// </summary> public override void OnClick() { try { if (!m_bConnected) { //show the tracking type selection dialog (whether to track the element from above or follow it from behind) TrackSelectionDlg dlg = new TrackSelectionDlg(); if (System.Windows.Forms.DialogResult.OK != dlg.ShowDialog()) return; //get the required tracking mode m_bTrackAboveTarget = dlg.UseOrthoTrackingMode; //do only once initializations if (m_once) { //create the graphics layer to manage the dynamic object m_globeGraphicsLayer = new GlobeGraphicsLayerClass(); ((ILayer)m_globeGraphicsLayer).Name = "DynamicObjects"; IScene scene = (IScene)m_globeDisplay.Globe; //add the new graphic layer to the globe scene.AddLayer((ILayer)m_globeGraphicsLayer, false); //activate the graphics layer scene.ActiveGraphicsLayer = (ILayer)m_globeGraphicsLayer; //redraw the GlobeDisplay m_globeDisplay.RefreshViewers(); //open a polyline featurelayer that would serve the real-time feed GPS simulator IFeatureLayer featureLayer = GetFeatureLayer(); if (featureLayer == null) return; //assign the featurelayer to the GPS simulator m_realTimeFeedManager.RealTimeFeedSimulator.FeatureLayer = featureLayer; m_once = false; } //get the GlobeViewUtil which is needed for coordinate transformations m_sceneViwer = m_globeDisplay.ActiveViewer; //Set the globe mode to terrain mode, since otherwise it will not be possible to set the target position ((IGlobeCamera)m_sceneViwer.Camera).OrientationMode = esriGlobeCameraOrientationMode.esriGlobeCameraOrientationLocal; //set the simulator elapsed time m_realTimeFeedManager.RealTimeFeedSimulator.TimeIncrement = 0.1; //sec //wire the real-time feed PositionUpdate event ((IRealTimeFeedEvents_Event)m_realTimeFeed).PositionUpdated += new IRealTimeFeedEvents_PositionUpdatedEventHandler(OnPositionUpdated); //start the real-time listener m_realTimeFeed.Start(); } else { //stop the real-time listener m_realTimeFeed.Stop(); //un-wire the PositionUpdated event handler ((IRealTimeFeedEvents_Event)m_realTimeFeed).PositionUpdated -= new IRealTimeFeedEvents_PositionUpdatedEventHandler(OnPositionUpdated); } //switch the connection flag m_bConnected = !m_bConnected; } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); } } /// <summary> /// The Checked property indicates the state of this Command. /// </summary> /// <remarks>If a command item appears depressed on a commandbar, the command is checked.</remarks> public override bool Checked { get { return m_bConnected; } } #endregion #region helper methods /// <summary> /// get a featurelayer that would be used by the real-time simulator /// </summary> /// <returns></returns> private IFeatureLayer GetFeatureLayer() { //instantiate a new featurelayer IFeatureLayer featureLayer = new FeatureLayerClass(); //set the layer's name featureLayer.Name = "GPS Data"; //open the featureclass IFeatureClass featureClass = OpenFeatureClass(); if (featureClass == null) return null; //set the featurelayer featureclass featureLayer.FeatureClass = featureClass; //return the featurelayer return featureLayer; } /// <summary> /// Opens a shapefile polyline featureclass /// </summary> /// <returns></returns> private IFeatureClass OpenFeatureClass() { string fileName = System.IO.Path.GetFileNameWithoutExtension(m_shapefileName); //instantiate a new workspace factory IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass(); //get the workspace directory string path = System.IO.Path.GetDirectoryName(m_shapefileName); //open the workspace containing the featureclass IFeatureWorkspace featureWorkspace = workspaceFactory.OpenFromFile(path, 0) as IFeatureWorkspace; //open the featureclass IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(fileName); //make sure that the featureclass type is polyline if (featureClass.ShapeType != esriGeometryType.esriGeometryPolyline) { featureClass = null; } //return the featureclass return featureClass; } /// <summary> /// Adds a sphere element to the given graphics layer at the specified position /// </summary> /// <param name="globeGraphicsLayer"></param> /// <param name="position"></param> /// <returns></returns> private int AddTrackElement(IGlobeGraphicsLayer globeGraphicsLayer, esriGpsPositionInfo position) { if (null == globeGraphicsLayer) return -1; //create a new point at the given position IPoint point = new PointClass(); ((IZAware)point).ZAware = true; point.X = position.longitude; point.Y = position.latitude; point.Z = 0.0; //set the color for the element (red) IRgbColor color = new RgbColorClass(); color.Red = 255; color.Green = 0; color.Blue = 0; //create a new 3D marker symbol IMarkerSymbol markerSymbol = new SimpleMarker3DSymbolClass(); //set the marker symbol's style and resolution ((ISimpleMarker3DSymbol)markerSymbol).Style = esriSimple3DMarkerStyle.esriS3DMSSphere; ((ISimpleMarker3DSymbol)markerSymbol).ResolutionQuality = 1.0; //set the symbol's size and color markerSymbol.Size = 700; markerSymbol.Color = color as IColor; //crate the graphic element IElement trackElement = new MarkerElementClass(); //set the element's symbol and geometry (location and shape) ((IMarkerElement)trackElement).Symbol = markerSymbol; trackElement.Geometry = point as IPoint; //add the element to the graphics layer int elemIndex = 0; ((IGraphicsContainer)globeGraphicsLayer).AddElement(trackElement, 0); //get the element's index globeGraphicsLayer.FindElementIndex(trackElement, out elemIndex); return elemIndex; } /// <summary> /// The real-time feed position updated event handler /// </summary> /// <param name="position">a GPS position information</param> /// <param name="estimate">indicates whether this is an estimated time or real time</param> void OnPositionUpdated(ref esriGpsPositionInfo position, bool estimate) { try { //add the tracking element to the tracking graphics layer (should happen only once) if (-1 == m_trackObjectIndex) { int index = AddTrackElement(m_globeGraphicsLayer, position); if (-1 == index) throw new Exception("could not add tracking object"); //cache the element's index m_trackObjectIndex = index; return; } //get the element by its index IElement elem = ((IGraphicsContainer3D)m_globeGraphicsLayer).get_Element(m_trackObjectIndex); //keep the previous location double lat, lon, alt; ((IPoint)elem.Geometry).QueryCoords(out lon, out lat); alt = ((IPoint)elem.Geometry).Z; //update the element's position IPoint point = elem.Geometry as IPoint; point.X = position.longitude; point.Y = position.latitude; point.Z = alt; elem.Geometry = (IGeometry)point; //update the element in the graphics layer. lock (m_globeGraphicsLayer) { m_globeGraphicsLayer.UpdateElementByIndex(m_trackObjectIndex); } IGlobeCamera globeCamera = m_sceneViwer.Camera as IGlobeCamera; //set the camera position in order to track the element if (m_bTrackAboveTarget) TrackAboveTarget(globeCamera, point); else TrackFollowTarget(globeCamera, point.X, point.Y, point.Z, lon, lat, alt); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); } } void TrackDynamicObject_PositionUpdated(ref esriGpsPositionInfo position, bool estimate) { } /// <summary> /// If the user chose to track the element from behind, set the camera behind the element /// so that the camera will be placed on the line connecting the previous and the current element's position. /// </summary> /// <param name="globeCamera"></param> /// <param name="newLon"></param> /// <param name="newLat"></param> /// <param name="newAlt"></param> /// <param name="oldLon"></param> /// <param name="oldLat"></param> /// <param name="oldAlt"></param> private void TrackFollowTarget(IGlobeCamera globeCamera, double newLon, double newLat, double newAlt, double oldLon, double oldLat, double oldAlt) { //make sure that the camera position is not directly above the element. Otherwise it can lead to //an ill condition if (newLon == oldLon && newLat == oldLat) { newLon += 0.00001; newLat += 0.00001; } //calculate the azimuth from the previous position to the current position double azimuth = Math.Atan2(newLat - oldLat, newLon - oldLon) * (Math.PI / 180.0); //the camera new position, right behind the element double obsX = newLon - 0.04 * Math.Cos(azimuth * (Math.PI / 180)); double obsY = newLat - 0.04 * Math.Sin(azimuth * (Math.PI / 180)); //set the camera position. The camera must be locked in order to prevent a dead-lock caused by the cache manager lock (globeCamera) { globeCamera.SetTargetLatLonAlt(newLat, newLon, newAlt / 1000.0); globeCamera.SetObserverLatLonAlt(obsY, obsX, newAlt / 1000.0 + 0.7); m_sceneViwer.Camera.Apply(); } //refresh the globe display m_globeDisplay.RefreshViewers(); } /// <summary> /// should the user choose to track the element from above, set the camera above the element /// </summary> /// <param name="globeCamera"></param> /// <param name="objectLocation"></param> private void TrackAboveTarget(IGlobeCamera globeCamera, IPoint objectLocation) { //Update the observer as well as the camera position //The camera must be locked in order to prevent a dead-lock caused by the cache manager lock (globeCamera) { globeCamera.SetTargetLatLonAlt(objectLocation.Y, objectLocation.X, objectLocation.Z / 1000.0); //The camera must nut be located exactly above the target, since it results in poor orientation computation //and therefore the camera gets jumpy. globeCamera.SetObserverLatLonAlt(objectLocation.Y - 0.000001, objectLocation.X - 0.000001, objectLocation.Z / 1000.0 + 30.0); m_sceneViwer.Camera.Apply(); } m_globeDisplay.RefreshViewers(); } #endregion #region IDisposable Members public void Dispose() { } #endregion } }
//---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: [email protected] // [email protected] // http://www.antigrain.com //---------------------------------------------------------------------------- // // Perspective 2D transformations // //---------------------------------------------------------------------------- using System; namespace MatterHackers.Agg.Transform { //=======================================================trans_perspective public sealed class Perspective : ITransform { static public readonly double affine_epsilon = 1e-14; public double sx, shy, w0, shx, sy, w1, tx, ty, w2; //-------------------------------------------------------ruction // Identity matrix public Perspective() { sx = (1); shy = (0); w0 = (0); shx = (0); sy = (1); w1 = (0); tx = (0); ty = (0); w2 = (1); } // Custom matrix public Perspective(double v0, double v1, double v2, double v3, double v4, double v5, double v6, double v7, double v8) { sx = (v0); shy = (v1); w0 = (v2); shx = (v3); sy = (v4); w1 = (v5); tx = (v6); ty = (v7); w2 = (v8); } // Custom matrix from m[9] public Perspective(double[] m) { sx = (m[0]); shy = (m[1]); w0 = (m[2]); shx = (m[3]); sy = (m[4]); w1 = (m[5]); tx = (m[6]); ty = (m[7]); w2 = (m[8]); } // From affine public Perspective(Affine a) { sx = (a.sx); shy = (a.shy); w0 = (0); shx = (a.shx); sy = (a.sy); w1 = (0); tx = (a.tx); ty = (a.ty); w2 = (1); } // From trans_perspective public Perspective(Perspective a) { sx = (a.sx); shy = (a.shy); w0 = a.w0; shx = (a.shx); sy = (a.sy); w1 = a.w1; tx = (a.tx); ty = (a.ty); w2 = a.w2; } // Rectangle to quadrilateral public Perspective(double x1, double y1, double x2, double y2, double[] quad) { rect_to_quad(x1, y1, x2, y2, quad); } // Quadrilateral to rectangle public Perspective(double[] quad, double x1, double y1, double x2, double y2) { quad_to_rect(quad, x1, y1, x2, y2); } // Arbitrary quadrilateral transformations public Perspective(double[] src, double[] dst) { quad_to_quad(src, dst); } public void Set(Perspective Other) { sx = Other.sx; shy = Other.shy; w0 = Other.w0; shx = Other.shx; sy = Other.sy; w1 = Other.w1; tx = Other.tx; ty = Other.ty; w2 = Other.w2; } //-------------------------------------- Quadrilateral transformations // The arguments are double[8] that are mapped to quadrilaterals: // x1,y1, x2,y2, x3,y3, x4,y4 public bool quad_to_quad(double[] qs, double[] qd) { Perspective p = new Perspective(); if (!quad_to_square(qs)) return false; if (!p.square_to_quad(qd)) return false; multiply(p); return true; } public bool rect_to_quad(double x1, double y1, double x2, double y2, double[] q) { double[] r = new double[8]; r[0] = r[6] = x1; r[2] = r[4] = x2; r[1] = r[3] = y1; r[5] = r[7] = y2; return quad_to_quad(r, q); } public bool quad_to_rect(double[] q, double x1, double y1, double x2, double y2) { double[] r = new double[8]; r[0] = r[6] = x1; r[2] = r[4] = x2; r[1] = r[3] = y1; r[5] = r[7] = y2; return quad_to_quad(q, r); } // Map square (0,0,1,1) to the quadrilateral and vice versa public bool square_to_quad(double[] q) { double dx = q[0] - q[2] + q[4] - q[6]; double dy = q[1] - q[3] + q[5] - q[7]; if (dx == 0.0 && dy == 0.0) { // Affine case (parallelogram) //--------------- sx = q[2] - q[0]; shy = q[3] - q[1]; w0 = 0.0; shx = q[4] - q[2]; sy = q[5] - q[3]; w1 = 0.0; tx = q[0]; ty = q[1]; w2 = 1.0; } else { double dx1 = q[2] - q[4]; double dy1 = q[3] - q[5]; double dx2 = q[6] - q[4]; double dy2 = q[7] - q[5]; double den = dx1 * dy2 - dx2 * dy1; if (den == 0.0) { // Singular case //--------------- sx = shy = w0 = shx = sy = w1 = tx = ty = w2 = 0.0; return false; } // General case //--------------- double u = (dx * dy2 - dy * dx2) / den; double v = (dy * dx1 - dx * dy1) / den; sx = q[2] - q[0] + u * q[2]; shy = q[3] - q[1] + u * q[3]; w0 = u; shx = q[6] - q[0] + v * q[6]; sy = q[7] - q[1] + v * q[7]; w1 = v; tx = q[0]; ty = q[1]; w2 = 1.0; } return true; } public bool quad_to_square(double[] q) { if (!square_to_quad(q)) return false; invert(); return true; } //--------------------------------------------------------- Operations public Perspective from_affine(Affine a) { sx = a.sx; shy = a.shy; w0 = 0; shx = a.shx; sy = a.sy; w1 = 0; tx = a.tx; ty = a.ty; w2 = 1; return this; } // Reset - load an identity matrix public Perspective reset() { sx = 1; shy = 0; w0 = 0; shx = 0; sy = 1; w1 = 0; tx = 0; ty = 0; w2 = 1; return this; } // Invert matrix. Returns false in degenerate case public bool invert() { double d0 = sy * w2 - w1 * ty; double d1 = w0 * ty - shy * w2; double d2 = shy * w1 - w0 * sy; double d = sx * d0 + shx * d1 + tx * d2; if (d == 0.0) { sx = shy = w0 = shx = sy = w1 = tx = ty = w2 = 0.0; return false; } d = 1.0 / d; Perspective a = new Perspective(this); sx = d * d0; shy = d * d1; w0 = d * d2; shx = d * (a.w1 * a.tx - a.shx * a.w2); sy = d * (a.sx * a.w2 - a.w0 * a.tx); w1 = d * (a.w0 * a.shx - a.sx * a.w1); tx = d * (a.shx * a.ty - a.sy * a.tx); ty = d * (a.shy * a.tx - a.sx * a.ty); w2 = d * (a.sx * a.sy - a.shy * a.shx); return true; } // Direct transformations operations public Perspective translate(double x, double y) { tx += x; ty += y; return this; } public Perspective rotate(double a) { multiply(Affine.NewRotation(a)); return this; } public Perspective scale(double s) { multiply(Affine.NewScaling(s)); return this; } public Perspective scale(double x, double y) { multiply(Affine.NewScaling(x, y)); return this; } public Perspective multiply(Perspective a) { Perspective b = new Perspective(this); sx = a.sx * b.sx + a.shx * b.shy + a.tx * b.w0; shx = a.sx * b.shx + a.shx * b.sy + a.tx * b.w1; tx = a.sx * b.tx + a.shx * b.ty + a.tx * b.w2; shy = a.shy * b.sx + a.sy * b.shy + a.ty * b.w0; sy = a.shy * b.shx + a.sy * b.sy + a.ty * b.w1; ty = a.shy * b.tx + a.sy * b.ty + a.ty * b.w2; w0 = a.w0 * b.sx + a.w1 * b.shy + a.w2 * b.w0; w1 = a.w0 * b.shx + a.w1 * b.sy + a.w2 * b.w1; w2 = a.w0 * b.tx + a.w1 * b.ty + a.w2 * b.w2; return this; } //------------------------------------------------------------------------ public Perspective multiply(Affine a) { Perspective b = new Perspective(this); sx = a.sx * b.sx + a.shx * b.shy + a.tx * b.w0; shx = a.sx * b.shx + a.shx * b.sy + a.tx * b.w1; tx = a.sx * b.tx + a.shx * b.ty + a.tx * b.w2; shy = a.shy * b.sx + a.sy * b.shy + a.ty * b.w0; sy = a.shy * b.shx + a.sy * b.sy + a.ty * b.w1; ty = a.shy * b.tx + a.sy * b.ty + a.ty * b.w2; return this; } //------------------------------------------------------------------------ public Perspective premultiply(Perspective b) { Perspective a = new Perspective(this); sx = a.sx * b.sx + a.shx * b.shy + a.tx * b.w0; shx = a.sx * b.shx + a.shx * b.sy + a.tx * b.w1; tx = a.sx * b.tx + a.shx * b.ty + a.tx * b.w2; shy = a.shy * b.sx + a.sy * b.shy + a.ty * b.w0; sy = a.shy * b.shx + a.sy * b.sy + a.ty * b.w1; ty = a.shy * b.tx + a.sy * b.ty + a.ty * b.w2; w0 = a.w0 * b.sx + a.w1 * b.shy + a.w2 * b.w0; w1 = a.w0 * b.shx + a.w1 * b.sy + a.w2 * b.w1; w2 = a.w0 * b.tx + a.w1 * b.ty + a.w2 * b.w2; return this; } //------------------------------------------------------------------------ public Perspective premultiply(Affine b) { Perspective a = new Perspective(this); sx = a.sx * b.sx + a.shx * b.shy; shx = a.sx * b.shx + a.shx * b.sy; tx = a.sx * b.tx + a.shx * b.ty + a.tx; shy = a.shy * b.sx + a.sy * b.shy; sy = a.shy * b.shx + a.sy * b.sy; ty = a.shy * b.tx + a.sy * b.ty + a.ty; w0 = a.w0 * b.sx + a.w1 * b.shy; w1 = a.w0 * b.shx + a.w1 * b.sy; w2 = a.w0 * b.tx + a.w1 * b.ty + a.w2; return this; } //------------------------------------------------------------------------ public Perspective multiply_inv(Perspective m) { Perspective t = m; t.invert(); return multiply(t); } //------------------------------------------------------------------------ public Perspective trans_perspectivemultiply_inv(Affine m) { Affine t = m; t.invert(); return multiply(t); } //------------------------------------------------------------------------ public Perspective premultiply_inv(Perspective m) { Perspective t = m; t.invert(); Set(t.multiply(this)); return this; } // Multiply inverse of "m" by "this" and assign the result to "this" public Perspective premultiply_inv(Affine m) { Perspective t = new Perspective(m); t.invert(); Set(t.multiply(this)); return this; } //--------------------------------------------------------- Load/Store public void store_to(double[] m) { m[0] = sx; m[1] = shy; m[2] = w0; m[3] = shx; m[4] = sy; m[5] = w1; m[6] = tx; m[7] = ty; m[8] = w2; } //------------------------------------------------------------------------ public Perspective load_from(double[] m) { sx = m[0]; shy = m[1]; w0 = m[2]; shx = m[3]; sy = m[4]; w1 = m[5]; tx = m[6]; ty = m[7]; w2 = m[8]; return this; } //---------------------------------------------------------- Operators // Multiply the matrix by another one and return the result in a separate matrix. public static Perspective operator *(Perspective a, Perspective b) { Perspective temp = a; temp.multiply(b); return temp; } // Multiply the matrix by another one and return the result in a separate matrix. public static Perspective operator *(Perspective a, Affine b) { Perspective temp = a; temp.multiply(b); return temp; } // Multiply the matrix by inverse of another one and return the result in a separate matrix. public static Perspective operator /(Perspective a, Perspective b) { Perspective temp = a; temp.multiply_inv(b); return temp; } // Calculate and return the inverse matrix public static Perspective operator ~(Perspective b) { Perspective ret = b; ret.invert(); return ret; } // Equal operator with default epsilon public static bool operator ==(Perspective a, Perspective b) { return a.is_equal(b, affine_epsilon); } // Not Equal operator with default epsilon public static bool operator !=(Perspective a, Perspective b) { return !a.is_equal(b, affine_epsilon); } public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } //---------------------------------------------------- Transformations // Direct transformation of x and y public void transform(ref double px, ref double py) { double x = px; double y = py; double m = 1.0 / (x * w0 + y * w1 + w2); px = m * (x * sx + y * shx + tx); py = m * (x * shy + y * sy + ty); } // Direct transformation of x and y, affine part only public void transform_affine(ref double x, ref double y) { double tmp = x; x = tmp * sx + y * shx + tx; y = tmp * shy + y * sy + ty; } // Direct transformation of x and y, 2x2 matrix only, no translation public void transform_2x2(ref double x, ref double y) { double tmp = x; x = tmp * sx + y * shx; y = tmp * shy + y * sy; } // Inverse transformation of x and y. It works slow because // it explicitly inverts the matrix on every call. For massive // operations it's better to invert() the matrix and then use // direct transformations. public void inverse_transform(ref double x, ref double y) { Perspective t = new Perspective(this); if (t.invert()) t.transform(ref x, ref y); } //---------------------------------------------------------- Auxiliary public double determinant() { return sx * (sy * w2 - ty * w1) + shx * (ty * w0 - shy * w2) + tx * (shy * w1 - sy * w0); } public double determinant_reciprocal() { return 1.0 / determinant(); } public bool is_valid() { return is_valid(affine_epsilon); } public bool is_valid(double epsilon) { return Math.Abs(sx) > epsilon && Math.Abs(sy) > epsilon && Math.Abs(w2) > epsilon; } public bool is_identity() { return is_identity(affine_epsilon); } public bool is_identity(double epsilon) { return agg_basics.is_equal_eps(sx, 1.0, epsilon) && agg_basics.is_equal_eps(shy, 0.0, epsilon) && agg_basics.is_equal_eps(w0, 0.0, epsilon) && agg_basics.is_equal_eps(shx, 0.0, epsilon) && agg_basics.is_equal_eps(sy, 1.0, epsilon) && agg_basics.is_equal_eps(w1, 0.0, epsilon) && agg_basics.is_equal_eps(tx, 0.0, epsilon) && agg_basics.is_equal_eps(ty, 0.0, epsilon) && agg_basics.is_equal_eps(w2, 1.0, epsilon); } public bool is_equal(Perspective m) { return is_equal(m, affine_epsilon); } public bool is_equal(Perspective m, double epsilon) { return agg_basics.is_equal_eps(sx, m.sx, epsilon) && agg_basics.is_equal_eps(shy, m.shy, epsilon) && agg_basics.is_equal_eps(w0, m.w0, epsilon) && agg_basics.is_equal_eps(shx, m.shx, epsilon) && agg_basics.is_equal_eps(sy, m.sy, epsilon) && agg_basics.is_equal_eps(w1, m.w1, epsilon) && agg_basics.is_equal_eps(tx, m.tx, epsilon) && agg_basics.is_equal_eps(ty, m.ty, epsilon) && agg_basics.is_equal_eps(w2, m.w2, epsilon); } // Determine the major affine parameters. Use with caution // considering possible degenerate cases. public double scale() { double x = 0.707106781 * sx + 0.707106781 * shx; double y = 0.707106781 * shy + 0.707106781 * sy; return Math.Sqrt(x * x + y * y); } public double rotation() { double x1 = 0.0; double y1 = 0.0; double x2 = 1.0; double y2 = 0.0; transform(ref x1, ref y1); transform(ref x2, ref y2); return Math.Atan2(y2 - y1, x2 - x1); } public void translation(out double dx, out double dy) { dx = tx; dy = ty; } public void scaling(out double x, out double y) { double x1 = 0.0; double y1 = 0.0; double x2 = 1.0; double y2 = 1.0; Perspective t = new Perspective(this); t *= Affine.NewRotation(-rotation()); t.transform(ref x1, ref y1); t.transform(ref x2, ref y2); x = x2 - x1; y = y2 - y1; } public void scaling_abs(out double x, out double y) { x = Math.Sqrt(sx * sx + shx * shx); y = Math.Sqrt(shy * shy + sy * sy); } //-------------------------------------------------------------------- public sealed class iterator_x { private double den; private double den_step; private double nom_x; private double nom_x_step; private double nom_y; private double nom_y_step; public double x; public double y; public iterator_x() { } public iterator_x(double px, double py, double step, Perspective m) { den = (px * m.w0 + py * m.w1 + m.w2); den_step = (m.w0 * step); nom_x = (px * m.sx + py * m.shx + m.tx); nom_x_step = (step * m.sx); nom_y = (px * m.shy + py * m.sy + m.ty); nom_y_step = (step * m.shy); x = (nom_x / den); y = (nom_y / den); } public static iterator_x operator ++(iterator_x a) { a.den += a.den_step; a.nom_x += a.nom_x_step; a.nom_y += a.nom_y_step; double d = 1.0 / a.den; a.x = a.nom_x * d; a.y = a.nom_y * d; return a; } }; //-------------------------------------------------------------------- public iterator_x begin(double x, double y, double step) { return new iterator_x(x, y, step, this); } }; }