context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; using ASC.Common; using ASC.Common.Data; using ASC.Common.Data.Sql; using ASC.Common.Data.Sql.Expressions; using ASC.Common.Logging; using ASC.Core; using ASC.Data.Backup.Exceptions; using ASC.Data.Backup.Extensions; using ASC.Data.Backup.Tasks.Data; using ASC.Data.Backup.Tasks.Modules; using ASC.Data.Storage; using Newtonsoft.Json; namespace ASC.Data.Backup.Tasks { public class BackupPortalTask : PortalTaskBase { private const int MaxLength = 250; private const int BatchLimit = 5000; public string BackupFilePath { get; private set; } public int Limit { get; private set; } private bool Dump { get; set; } public BackupPortalTask(ILog logger, int tenantId, string fromConfigPath, string toFilePath, int limit) : base(logger, tenantId, fromConfigPath) { if (string.IsNullOrEmpty(toFilePath)) throw new ArgumentNullException("toFilePath"); BackupFilePath = toFilePath; Limit = limit; Dump = CoreContext.Configuration.Standalone; } public override void RunJob() { Logger.DebugFormat("begin backup {0}", TenantId); CoreContext.TenantManager.SetCurrentTenant(TenantId); using (var writer = new ZipWriteOperator(BackupFilePath)) { if (Dump) { DoDump(writer); } else { var dbFactory = new DbFactory(ConfigPath); var modulesToProcess = GetModulesToProcess().ToList(); var fileGroups = GetFilesGroup(dbFactory); var stepscount = ProcessStorage ? fileGroups.Count : 0; SetStepsCount(modulesToProcess.Count + stepscount); foreach (var module in modulesToProcess) { DoBackupModule(writer, dbFactory, module); } if (ProcessStorage) { DoBackupStorage(writer, fileGroups); } } } Logger.DebugFormat("end backup {0}", TenantId); } private void DoDump(IDataWriteOperator writer) { using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(true.ToString()))) { writer.WriteEntry(KeyHelper.GetDumpKey(), stream); } List<string> tables; var files = new List<BackupFileInfo>(); using (var dbManager = DbManager.FromHttpContext("default", 100000)) { tables = dbManager.ExecuteList("show tables;").Select(r => Convert.ToString(r[0])).ToList(); } var stepscount = tables.Count * 4; // (schema + data) * (dump + zip) if (ProcessStorage) { var tenants = CoreContext.TenantManager.GetTenants(false).Select(r => r.TenantId); foreach (var t in tenants) { files.AddRange(GetFiles(t)); } stepscount += files.Count * 2 + 1; Logger.Debug("files:" + files.Count); } SetStepsCount(stepscount); var excluded = ModuleProvider.AllModules.Where(r => IgnoredModules.Contains(r.ModuleName)).SelectMany(r => r.Tables).Select(r => r.Name).ToList(); excluded.AddRange(IgnoredTables); excluded.Add("res_"); var dir = Path.GetDirectoryName(BackupFilePath); var subDir = Path.Combine(dir, Path.GetFileNameWithoutExtension(BackupFilePath)); var schemeDir = Path.Combine(subDir, KeyHelper.GetDatabaseSchema()); var dataDir = Path.Combine(subDir, KeyHelper.GetDatabaseData()); if (!Directory.Exists(schemeDir)) { Directory.CreateDirectory(schemeDir); } if (!Directory.Exists(dataDir)) { Directory.CreateDirectory(dataDir); } var dict = tables.ToDictionary(t => t, SelectCount); tables.Sort((pair1, pair2) => dict[pair1].CompareTo(dict[pair2])); for (var i = 0; i < tables.Count; i += TasksLimit) { var tasks = new List<Task>(TasksLimit * 2); for (var j = 0; j < TasksLimit && i + j < tables.Count; j++) { var t = tables[i + j]; tasks.Add(Task.Run(() => DumpTableScheme(t, schemeDir))); if (!excluded.Any(t.StartsWith)) { tasks.Add(Task.Run(() => DumpTableData(t, dataDir, dict[t]))); } else { SetStepCompleted(2); } } Task.WaitAll(tasks.ToArray()); ArchiveDir(writer, subDir); } Logger.DebugFormat("dir remove start {0}", subDir); Directory.Delete(subDir, true); Logger.DebugFormat("dir remove end {0}", subDir); if (ProcessStorage) { DoDumpStorage(writer, files); } } private IEnumerable<BackupFileInfo> GetFiles(int tenantId) { var files = GetFilesToProcess(tenantId).ToList(); var exclude = new List<string>(); using (var db = DbManager.FromHttpContext("default")) { var query = new SqlQuery("backup_backup") .Select("storage_path") .Where("tenant_id", tenantId) .Where("storage_type", 0) .Where(!Exp.Eq("storage_path", null)); exclude.AddRange(db.ExecuteList(query).Select(r => Convert.ToString(r[0]))); } files = files.Where(f => !exclude.Any(e => f.Path.Replace('\\', '/').Contains(string.Format("/file_{0}/", e)))).ToList(); return files; } private void DumpTableScheme(string t, string dir) { try { Logger.DebugFormat("dump table scheme start {0}", t); using (var dbManager = DbManager.FromHttpContext("default", 100000)) { var createScheme = dbManager.ExecuteList(string.Format("SHOW CREATE TABLE `{0}`", t)); var creates = new StringBuilder(); creates.AppendFormat("DROP TABLE IF EXISTS `{0}`;", t); creates.AppendLine(); creates.Append(createScheme .Select(r => Convert.ToString(r[1])) .FirstOrDefault()); creates.Append(";"); var path = Path.Combine(dir, t); using (var stream = File.OpenWrite(path)) { var bytes = Encoding.UTF8.GetBytes(creates.ToString()); stream.Write(bytes, 0, bytes.Length); } SetStepCompleted(); } Logger.DebugFormat("dump table scheme stop {0}", t); } catch (Exception e) { Logger.Error(e); throw; } } private int SelectCount(string t) { try { using (var dbManager = DbManager.FromHttpContext("default", 100000)) { dbManager.ExecuteNonQuery("analyze table " + t); return dbManager.ExecuteScalar<int>(new SqlQuery("information_schema.`TABLES`").Select("table_rows").Where("TABLE_NAME", t).Where("TABLE_SCHEMA", dbManager.Connection.Database)); } } catch (Exception e) { Logger.Error(e); throw; } } private void DumpTableData(string t, string dir, int count) { try { if (count == 0) { Logger.DebugFormat("dump table data stop {0}", t); SetStepCompleted(2); return; } Logger.DebugFormat("dump table data start {0}", t); var searchWithPrimary = false; string primaryIndex; int primaryIndexStep = 0; int primaryIndexStart = 0; List<string> columns; using (var dbManager = DbManager.FromHttpContext("default", 100000)) { var columnsData = dbManager.ExecuteList(string.Format("SHOW COLUMNS FROM `{0}`;", t)); columns = columnsData .Select(r => "`" + Convert.ToString(r[0]) + "`") .ToList(); primaryIndex = dbManager .ExecuteList( new SqlQuery("information_schema.`COLUMNS`") .Select("COLUMN_NAME") .Where("TABLE_SCHEMA", dbManager.Connection.Database) .Where("TABLE_NAME", t) .Where("COLUMN_KEY", "PRI") .Where("DATA_TYPE", "int")) .ConvertAll(r => Convert.ToString(r[0])) .FirstOrDefault(); var isLeft = dbManager.ExecuteList(string.Format("SHOW INDEXES FROM {0} WHERE COLUMN_NAME='{1}' AND seq_in_index=1", t, primaryIndex)); searchWithPrimary = isLeft.Count == 1; if (searchWithPrimary) { var minMax = dbManager .ExecuteList(new SqlQuery(t).SelectMax(primaryIndex).SelectMin(primaryIndex)) .ConvertAll(r => new Tuple<int, int>(Convert.ToInt32(r[0]), Convert.ToInt32(r[1]))) .FirstOrDefault(); primaryIndexStart = minMax.Item2; primaryIndexStep = (minMax.Item1 - minMax.Item2) / count; if (primaryIndexStep < Limit) { primaryIndexStep = Limit; } } } var path = Path.Combine(dir, t); var offset = 0; do { List<object[]> result; if (searchWithPrimary) { result = GetDataWithPrimary(t, columns, primaryIndex, primaryIndexStart, primaryIndexStep); primaryIndexStart += primaryIndexStep; } else { result = GetData(t, columns, offset); } offset += Limit; var resultCount = result.Count; if (resultCount == 0) break; SaveToFile(path, t, columns, result); if (resultCount < Limit) break; } while (true); SetStepCompleted(); Logger.DebugFormat("dump table data stop {0}", t); } catch (Exception e) { Logger.Error(e); throw; } } private List<object[]> GetData(string t, List<string> columns, int offset) { using (var dbManager = DbManager.FromHttpContext("default", 100000)) { var query = new SqlQuery(t) .Select(columns.ToArray()) .SetFirstResult(offset) .SetMaxResults(Limit); return dbManager.ExecuteList(query); } } private List<object[]> GetDataWithPrimary(string t, List<string> columns, string primary, int start, int step) { using (var dbManager = DbManager.FromHttpContext("default", 100000)) { var query = new SqlQuery(t) .Select(columns.ToArray()) .Where(Exp.Between(primary, start, start + step)); return dbManager.ExecuteList(query); } } private void SaveToFile(string path, string t, IReadOnlyCollection<string> columns, List<object[]> data) { Logger.DebugFormat("save to file {0}", t); List<object[]> portion; while ((portion = data.Take(BatchLimit).ToList()).Any()) { using (var sw = new StreamWriter(path, true)) using (var writer = new JsonTextWriter(sw)) { writer.QuoteChar = '\''; writer.DateFormatString = "yyyy-MM-dd HH:mm:ss"; sw.Write("REPLACE INTO `{0}` ({1}) VALUES ", t, string.Join(",", columns)); sw.WriteLine(); for (var j = 0; j < portion.Count; j++) { var obj = portion[j]; sw.Write("("); for (var i = 0; i < obj.Length; i++) { var byteArray = obj[i] as byte[]; if (byteArray != null) { sw.Write("0x"); foreach (var b in byteArray) sw.Write("{0:x2}", b); } else { var ser = new JsonSerializer(); ser.Serialize(writer, obj[i]); } if (i != obj.Length - 1) { sw.Write(","); } } sw.Write(")"); if (j != portion.Count - 1) { sw.Write(","); } else { sw.Write(";"); } sw.WriteLine(); } } data = data.Skip(BatchLimit).ToList(); } } private void DoDumpStorage(IDataWriteOperator writer, IReadOnlyList<BackupFileInfo> files) { Logger.Debug("begin backup storage"); var dir = Path.GetDirectoryName(BackupFilePath); var subDir = Path.Combine(dir, Path.GetFileNameWithoutExtension(BackupFilePath)); for (var i = 0; i < files.Count; i += TasksLimit) { var storageDir = Path.Combine(subDir, KeyHelper.GetStorage()); if (!Directory.Exists(storageDir)) { Directory.CreateDirectory(storageDir); } var tasks = new List<Task>(TasksLimit); for (var j = 0; j < TasksLimit && i + j < files.Count; j++) { var t = files[i + j]; tasks.Add(Task.Run(() => DoDumpFile(t, storageDir))); } Task.WaitAll(tasks.ToArray()); ArchiveDir(writer, subDir); Directory.Delete(storageDir, true); } var restoreInfoXml = new XElement("storage_restore", files.Select(file => (object)file.ToXElement()).ToArray()); var tmpPath = Path.Combine(subDir, KeyHelper.GetStorageRestoreInfoZipKey()); Directory.CreateDirectory(Path.GetDirectoryName(tmpPath)); using (var tmpFile = new FileStream(tmpPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read, 4096, FileOptions.DeleteOnClose)) { restoreInfoXml.WriteTo(tmpFile); writer.WriteEntry(KeyHelper.GetStorageRestoreInfoZipKey(), tmpFile); } SetStepCompleted(); Directory.Delete(subDir, true); Logger.Debug("end backup storage"); } private async Task DoDumpFile(BackupFileInfo file, string dir) { var storage = StorageFactory.GetStorage(ConfigPath, file.Tenant.ToString(), file.Module); var filePath = Path.Combine(dir, file.GetZipKey()); var dirName = Path.GetDirectoryName(filePath); Logger.DebugFormat("backup file {0}", filePath); if (!Directory.Exists(dirName) && !string.IsNullOrEmpty(dirName)) { Directory.CreateDirectory(dirName); } if (!WorkContext.IsMono && filePath.Length > MaxLength) { filePath = @"\\?\" + filePath; } using (var fileStream = storage.GetReadStream(file.Domain, file.Path)) using (var tmpFile = File.OpenWrite(filePath)) { await fileStream.CopyToAsync(tmpFile); } SetStepCompleted(); } private void ArchiveDir(IDataWriteOperator writer, string subDir) { Logger.DebugFormat("archive dir start {0}", subDir); foreach (var enumerateFile in Directory.EnumerateFiles(subDir, "*", SearchOption.AllDirectories)) { var f = enumerateFile; if (!WorkContext.IsMono && enumerateFile.Length > MaxLength) { f = @"\\?\" + f; } using (var tmpFile = new FileStream(f, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read, 4096, FileOptions.DeleteOnClose)) { writer.WriteEntry(enumerateFile.Substring(subDir.Length), tmpFile); } SetStepCompleted(); } Logger.DebugFormat("archive dir end {0}", subDir); } private List<IGrouping<string, BackupFileInfo>> GetFilesGroup(DbFactory dbFactory) { var files = GetFilesToProcess(TenantId).ToList(); var exclude = new List<string>(); using (var db = dbFactory.OpenConnection()) using (var command = db.CreateCommand()) { command.CommandText = "select storage_path from backup_backup where tenant_id = " + TenantId + " and storage_type = 0 and storage_path is not null"; using (var reader = command.ExecuteReader()) { while (reader.Read()) { exclude.Add(reader.GetString(0)); } } } files = files.Where(f => !exclude.Any(e => f.Path.Replace('\\', '/').Contains(string.Format("/file_{0}/", e)))).ToList(); return files.GroupBy(file => file.Module).ToList(); } private void DoBackupModule(IDataWriteOperator writer, DbFactory dbFactory, IModuleSpecifics module) { Logger.DebugFormat("begin saving data for module {0}", module.ModuleName); var tablesToProcess = module.Tables.Where(t => !IgnoredTables.Contains(t.Name) && t.InsertMethod != InsertMethod.None).ToList(); var tablesCount = tablesToProcess.Count; var tablesProcessed = 0; using (var connection = dbFactory.OpenConnection()) { foreach (var table in tablesToProcess) { Logger.DebugFormat("begin load table {0}", table.Name); using (var data = new DataTable(table.Name)) { ActionInvoker.Try( state => { data.Clear(); int counts; var offset = 0; do { var t = (TableInfo)state; var dataAdapter = dbFactory.CreateDataAdapter(); dataAdapter.SelectCommand = module.CreateSelectCommand(connection.Fix(), TenantId, t, Limit, offset).WithTimeout(600); counts = ((DbDataAdapter)dataAdapter).Fill(data); offset += Limit; } while (counts == Limit); }, table, maxAttempts: 5, onFailure: error => { throw ThrowHelper.CantBackupTable(table.Name, error); }, onAttemptFailure: error => Logger.Warn("backup attempt failure: {0}", error)); foreach (var col in data.Columns.Cast<DataColumn>().Where(col => col.DataType == typeof(DateTime))) { col.DateTimeMode = DataSetDateTime.Unspecified; } module.PrepareData(data); Logger.DebugFormat("end load table {0}", table.Name); Logger.DebugFormat("begin saving table {0}", table.Name); using (var file = TempStream.Create()) { data.WriteXml(file, XmlWriteMode.WriteSchema); data.Clear(); writer.WriteEntry(KeyHelper.GetTableZipKey(module, data.TableName), file); } Logger.DebugFormat("end saving table {0}", table.Name); } SetCurrentStepProgress((int)((++tablesProcessed * 100) / (double)tablesCount)); } } Logger.DebugFormat("end saving data for module {0}", module.ModuleName); } private void DoBackupStorage(IDataWriteOperator writer, List<IGrouping<string, BackupFileInfo>> fileGroups) { Logger.Debug("begin backup storage"); foreach (var group in fileGroups) { var filesProcessed = 0; var filesCount = group.Count(); foreach (var file in group) { var storage = StorageFactory.GetStorage(ConfigPath, TenantId.ToString(), group.Key); var file1 = file; ActionInvoker.Try(state => { var f = (BackupFileInfo)state; using (var fileStream = storage.GetReadStream(f.Domain, f.Path)) { writer.WriteEntry(file1.GetZipKey(), fileStream); } }, file, 5, error => Logger.WarnFormat("can't backup file ({0}:{1}): {2}", file1.Module, file1.Path, error)); SetCurrentStepProgress((int)(++filesProcessed * 100 / (double)filesCount)); } } var restoreInfoXml = new XElement( "storage_restore", fileGroups .SelectMany(group => group.Select(file => (object)file.ToXElement())) .ToArray()); using (var tmpFile = TempStream.Create()) { restoreInfoXml.WriteTo(tmpFile); writer.WriteEntry(KeyHelper.GetStorageRestoreInfoZipKey(), tmpFile); } Logger.Debug("end backup storage"); } } }
#region License /* The MIT License Copyright (c) 2008 Sky Morey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; using System.Linq; using System.Abstract; using Spring.Objects.Factory; using Spring.Context; using Spring.Objects.Factory.Support; using Spring.Context.Support; using System.Collections.Generic; using System.Collections; namespace Contoso.Abstract { /// <summary> /// ISpringServiceRegistrar /// </summary> public interface ISpringServiceRegistrar : IServiceRegistrar { } /// <summary> /// SpringServiceRegistrar /// </summary> public class SpringServiceRegistrar : ISpringServiceRegistrar, ICloneable, IServiceRegistrarBehaviorAccessor { private SpringServiceLocator _parent; private GenericApplicationContext _container; // IConfigurableApplicationContext private IObjectDefinitionFactory _factory = new DefaultObjectDefinitionFactory(); /// <summary> /// Initializes a new instance of the <see cref="SpringServiceRegistrar"/> class. /// </summary> /// <param name="parent">The parent.</param> /// <param name="container">The container.</param> public SpringServiceRegistrar(SpringServiceLocator parent, GenericApplicationContext container) { _parent = parent; _container = container; LifetimeForRegisters = ServiceRegistrarLifetime.Transient; } object ICloneable.Clone() { return MemberwiseClone(); } // locator /// <summary> /// Gets the locator. /// </summary> public IServiceLocator Locator { get { return _parent; } } // enumerate /// <summary> /// Determines whether this instance has registered. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <returns> /// <c>true</c> if this instance has registered; otherwise, <c>false</c>. /// </returns> public bool HasRegistered<TService>() { return (_container.GetObjectsOfType(typeof(TService)).Count > 0); } /// <summary> /// Determines whether the specified service type has registered. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <returns> /// <c>true</c> if the specified service type has registered; otherwise, <c>false</c>. /// </returns> public bool HasRegistered(Type serviceType) { return (_container.GetObjectsOfType(serviceType).Count > 0); } /// <summary> /// Gets the registrations for. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <returns></returns> public IEnumerable<ServiceRegistration> GetRegistrationsFor(Type serviceType) { return _container.GetObjectsOfType(serviceType).Cast<DictionaryEntry>() .Select(x => { var objectName = (string)x.Key; var objectDefinition = _container.GetObjectDefinition(objectName); return new ServiceRegistration { ServiceType = objectDefinition.ObjectType, ImplementationType = objectDefinition.ObjectType, Name = objectName }; }); } /// <summary> /// Gets the registrations. /// </summary> public IEnumerable<ServiceRegistration> Registrations { get { return _container.GetObjectsOfType(typeof(object)).Cast<DictionaryEntry>() .Select(x => { var objectName = (string)x.Key; var objectDefinition = _container.GetObjectDefinition(objectName); return new ServiceRegistration { ServiceType = objectDefinition.ObjectType, ImplementationType = objectDefinition.ObjectType, Name = objectName }; }); } } // register type /// <summary> /// Gets the lifetime for registers. /// </summary> public ServiceRegistrarLifetime LifetimeForRegisters { get; private set; } /// <summary> /// Registers the specified service type. /// </summary> /// <param name="serviceType">Type of the service.</param> public void Register(Type serviceType) { var b = SetLifetime(ObjectDefinitionBuilder.RootObjectDefinition(_factory, serviceType)); _container.RegisterObjectDefinition(SpringServiceLocator.GetName(serviceType), b.ObjectDefinition); } /// <summary> /// Registers the specified service type. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="name">The name.</param> public void Register(Type serviceType, string name) { var b = SetLifetime(ObjectDefinitionBuilder.RootObjectDefinition(_factory, serviceType)); _container.RegisterObjectDefinition(name, b.ObjectDefinition); } // register implementation /// <summary> /// Registers this instance. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <typeparam name="TImplementation">The type of the implementation.</typeparam> public void Register<TService, TImplementation>() where TService : class where TImplementation : class, TService { var b = SetLifetime(ObjectDefinitionBuilder.RootObjectDefinition(_factory, typeof(TImplementation))); _container.RegisterObjectDefinition(SpringServiceLocator.GetName(typeof(TImplementation)), b.ObjectDefinition); } /// <summary> /// Registers the specified name. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <typeparam name="TImplementation">The type of the implementation.</typeparam> /// <param name="name">The name.</param> public void Register<TService, TImplementation>(string name) where TService : class where TImplementation : class, TService { var b = SetLifetime(ObjectDefinitionBuilder.RootObjectDefinition(_factory, typeof(TImplementation))); _container.RegisterObjectDefinition(name, b.ObjectDefinition); } /// <summary> /// Registers the specified implementation type. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="implementationType">Type of the implementation.</param> public void Register<TService>(Type implementationType) where TService : class { var b = SetLifetime(ObjectDefinitionBuilder.RootObjectDefinition(_factory, implementationType)); _container.RegisterObjectDefinition(SpringServiceLocator.GetName(implementationType), b.ObjectDefinition); } /// <summary> /// Registers the specified implementation type. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="implementationType">Type of the implementation.</param> /// <param name="name">The name.</param> public void Register<TService>(Type implementationType, string name) where TService : class { var b = ObjectDefinitionBuilder.RootObjectDefinition(_factory, implementationType); _container.RegisterObjectDefinition(name, b.ObjectDefinition); } /// <summary> /// Registers the specified service type. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="implementationType">Type of the implementation.</param> public void Register(Type serviceType, Type implementationType) { var b = SetLifetime(ObjectDefinitionBuilder.RootObjectDefinition(_factory, implementationType)); _container.RegisterObjectDefinition(SpringServiceLocator.GetName(implementationType), b.ObjectDefinition); } /// <summary> /// Registers the specified service type. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="implementationType">Type of the implementation.</param> /// <param name="name">The name.</param> public void Register(Type serviceType, Type implementationType, string name) { var b = SetLifetime(ObjectDefinitionBuilder.RootObjectDefinition(_factory, implementationType)); _container.RegisterObjectDefinition(name, b.ObjectDefinition); } // register instance /// <summary> /// Registers the instance. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="instance">The instance.</param> public void RegisterInstance<TService>(TService instance) where TService : class { EnsureTransientLifestyle(); _container.ObjectFactory.RegisterSingleton(SpringServiceLocator.GetName(typeof(TService)), instance); } /// <summary> /// Registers the instance. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="instance">The instance.</param> /// <param name="name">The name.</param> public void RegisterInstance<TService>(TService instance, string name) where TService : class { EnsureTransientLifestyle(); _container.ObjectFactory.RegisterSingleton(name, instance); } /// <summary> /// Registers the instance. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="instance">The instance.</param> public void RegisterInstance(Type serviceType, object instance) { EnsureTransientLifestyle(); _container.ObjectFactory.RegisterSingleton(SpringServiceLocator.GetName(serviceType), instance); } /// <summary> /// Registers the instance. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="instance">The instance.</param> /// <param name="name">The name.</param> public void RegisterInstance(Type serviceType, object instance, string name) { EnsureTransientLifestyle(); _container.ObjectFactory.RegisterSingleton(name, instance); } // register method /// <summary> /// Registers the specified factory method. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="factoryMethod">The factory method.</param> public void Register<TService>(Func<IServiceLocator, TService> factoryMethod) where TService : class { EnsureTransientLifestyle(); Func<TService> func = () => factoryMethod(_parent); _container.ObjectFactory.RegisterSingleton(SpringServiceLocator.GetName(typeof(TService)), func); } /// <summary> /// Registers the specified factory method. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="factoryMethod">The factory method.</param> /// <param name="name">The name.</param> public void Register<TService>(Func<IServiceLocator, TService> factoryMethod, string name) where TService : class { EnsureTransientLifestyle(); Func<TService> func = () => factoryMethod(_parent); _container.ObjectFactory.RegisterSingleton(name, func); } /// <summary> /// Registers the specified service type. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="factoryMethod">The factory method.</param> public void Register(Type serviceType, Func<IServiceLocator, object> factoryMethod) { EnsureTransientLifestyle(); Func<object> func = () => factoryMethod(_parent); _container.ObjectFactory.RegisterSingleton(SpringServiceLocator.GetName(serviceType), func); } /// <summary> /// Registers the specified service type. /// </summary> /// <param name="serviceType">Type of the service.</param> /// <param name="factoryMethod">The factory method.</param> /// <param name="name">The name.</param> public void Register(Type serviceType, Func<IServiceLocator, object> factoryMethod, string name) { EnsureTransientLifestyle(); Func<object> func = () => factoryMethod(_parent); _container.ObjectFactory.RegisterSingleton(name, func); } // interceptor /// <summary> /// Registers the interceptor. /// </summary> /// <param name="interceptor">The interceptor.</param> public void RegisterInterceptor(IServiceLocatorInterceptor interceptor) { _container.ObjectFactory.AddObjectPostProcessor(new Interceptor(interceptor, _container)); } #region Behavior bool IServiceRegistrarBehaviorAccessor.RegisterInLocator { get { return true; } } ServiceRegistrarLifetime IServiceRegistrarBehaviorAccessor.Lifetime { get { return LifetimeForRegisters; } set { LifetimeForRegisters = value; } } #endregion private void EnsureTransientLifestyle() { if (LifetimeForRegisters != ServiceRegistrarLifetime.Transient) throw new NotSupportedException(); } private ObjectDefinitionBuilder SetLifetime(ObjectDefinitionBuilder b) { switch (LifetimeForRegisters) { case ServiceRegistrarLifetime.Transient: break; case ServiceRegistrarLifetime.Singleton: b.SetSingleton(true); break; default: throw new NotSupportedException(); } return b; } } }
using System; using System.Collections.Generic; using System.Linq; using Nop.Core.Caching; using Nop.Core.Data; using Nop.Core.Domain.Orders; using Nop.Services.Events; using Nop.Services.Stores; namespace Nop.Services.Orders { /// <summary> /// Checkout attribute service /// </summary> public partial class CheckoutAttributeService : ICheckoutAttributeService { #region Constants /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : store ID /// {1} : >A value indicating whether we should exlude shippable attributes /// </remarks> private const string CHECKOUTATTRIBUTES_ALL_KEY = "Nop.checkoutattribute.all-{0}-{1}"; /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : checkout attribute ID /// </remarks> private const string CHECKOUTATTRIBUTES_BY_ID_KEY = "Nop.checkoutattribute.id-{0}"; /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : checkout attribute ID /// </remarks> private const string CHECKOUTATTRIBUTEVALUES_ALL_KEY = "Nop.checkoutattributevalue.all-{0}"; /// <summary> /// Key for caching /// </summary> /// <remarks> /// {0} : checkout attribute value ID /// </remarks> private const string CHECKOUTATTRIBUTEVALUES_BY_ID_KEY = "Nop.checkoutattributevalue.id-{0}"; /// <summary> /// Key pattern to clear cache /// </summary> private const string CHECKOUTATTRIBUTES_PATTERN_KEY = "Nop.checkoutattribute."; /// <summary> /// Key pattern to clear cache /// </summary> private const string CHECKOUTATTRIBUTEVALUES_PATTERN_KEY = "Nop.checkoutattributevalue."; #endregion #region Fields private readonly IRepository<CheckoutAttribute> _checkoutAttributeRepository; private readonly IRepository<CheckoutAttributeValue> _checkoutAttributeValueRepository; private readonly IStoreMappingService _storeMappingService; private readonly IEventPublisher _eventPublisher; private readonly ICacheManager _cacheManager; #endregion #region Ctor /// <summary> /// Ctor /// </summary> /// <param name="cacheManager">Cache manager</param> /// <param name="checkoutAttributeRepository">Checkout attribute repository</param> /// <param name="checkoutAttributeValueRepository">Checkout attribute value repository</param> /// <param name="storeMappingService">Store mapping service</param> /// <param name="eventPublisher">Event published</param> public CheckoutAttributeService(ICacheManager cacheManager, IRepository<CheckoutAttribute> checkoutAttributeRepository, IRepository<CheckoutAttributeValue> checkoutAttributeValueRepository, IStoreMappingService storeMappingService, IEventPublisher eventPublisher) { this._cacheManager = cacheManager; this._checkoutAttributeRepository = checkoutAttributeRepository; this._checkoutAttributeValueRepository = checkoutAttributeValueRepository; this._storeMappingService = storeMappingService; this._eventPublisher = eventPublisher; } #endregion #region Methods #region Checkout attributes /// <summary> /// Deletes a checkout attribute /// </summary> /// <param name="checkoutAttribute">Checkout attribute</param> public virtual void DeleteCheckoutAttribute(CheckoutAttribute checkoutAttribute) { if (checkoutAttribute == null) throw new ArgumentNullException("checkoutAttribute"); _checkoutAttributeRepository.Delete(checkoutAttribute); _cacheManager.RemoveByPattern(CHECKOUTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(CHECKOUTATTRIBUTEVALUES_PATTERN_KEY); //event notification _eventPublisher.EntityDeleted(checkoutAttribute); } /// <summary> /// Gets all checkout attributes /// </summary> /// <param name="storeId">Store identifier</param> /// <param name="excludeShippableAttributes">A value indicating whether we should exlude shippable attributes</param> /// <returns>Checkout attributes</returns> public virtual IList<CheckoutAttribute> GetAllCheckoutAttributes(int storeId = 0, bool excludeShippableAttributes = false) { string key = string.Format(CHECKOUTATTRIBUTES_ALL_KEY, storeId, excludeShippableAttributes); return _cacheManager.Get(key, () => { var query = from ca in _checkoutAttributeRepository.Table orderby ca.DisplayOrder, ca.Id select ca; var checkoutAttributes = query.ToList(); if (storeId > 0) { //store mapping checkoutAttributes = checkoutAttributes.Where(ca => _storeMappingService.Authorize(ca)).ToList(); } if (excludeShippableAttributes) { //remove attributes which require shippable products checkoutAttributes = checkoutAttributes.RemoveShippableAttributes().ToList(); } return checkoutAttributes; }); } /// <summary> /// Gets a checkout attribute /// </summary> /// <param name="checkoutAttributeId">Checkout attribute identifier</param> /// <returns>Checkout attribute</returns> public virtual CheckoutAttribute GetCheckoutAttributeById(int checkoutAttributeId) { if (checkoutAttributeId == 0) return null; string key = string.Format(CHECKOUTATTRIBUTES_BY_ID_KEY, checkoutAttributeId); return _cacheManager.Get(key, () => _checkoutAttributeRepository.GetById(checkoutAttributeId)); } /// <summary> /// Inserts a checkout attribute /// </summary> /// <param name="checkoutAttribute">Checkout attribute</param> public virtual void InsertCheckoutAttribute(CheckoutAttribute checkoutAttribute) { if (checkoutAttribute == null) throw new ArgumentNullException("checkoutAttribute"); _checkoutAttributeRepository.Insert(checkoutAttribute); _cacheManager.RemoveByPattern(CHECKOUTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(CHECKOUTATTRIBUTEVALUES_PATTERN_KEY); //event notification _eventPublisher.EntityInserted(checkoutAttribute); } /// <summary> /// Updates the checkout attribute /// </summary> /// <param name="checkoutAttribute">Checkout attribute</param> public virtual void UpdateCheckoutAttribute(CheckoutAttribute checkoutAttribute) { if (checkoutAttribute == null) throw new ArgumentNullException("checkoutAttribute"); _checkoutAttributeRepository.Update(checkoutAttribute); _cacheManager.RemoveByPattern(CHECKOUTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(CHECKOUTATTRIBUTEVALUES_PATTERN_KEY); //event notification _eventPublisher.EntityUpdated(checkoutAttribute); } #endregion #region Checkout attribute values /// <summary> /// Deletes a checkout attribute value /// </summary> /// <param name="checkoutAttributeValue">Checkout attribute value</param> public virtual void DeleteCheckoutAttributeValue(CheckoutAttributeValue checkoutAttributeValue) { if (checkoutAttributeValue == null) throw new ArgumentNullException("checkoutAttributeValue"); _checkoutAttributeValueRepository.Delete(checkoutAttributeValue); _cacheManager.RemoveByPattern(CHECKOUTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(CHECKOUTATTRIBUTEVALUES_PATTERN_KEY); //event notification _eventPublisher.EntityDeleted(checkoutAttributeValue); } /// <summary> /// Gets checkout attribute values by checkout attribute identifier /// </summary> /// <param name="checkoutAttributeId">The checkout attribute identifier</param> /// <returns>Checkout attribute values</returns> public virtual IList<CheckoutAttributeValue> GetCheckoutAttributeValues(int checkoutAttributeId) { string key = string.Format(CHECKOUTATTRIBUTEVALUES_ALL_KEY, checkoutAttributeId); return _cacheManager.Get(key, () => { var query = from cav in _checkoutAttributeValueRepository.Table orderby cav.DisplayOrder, cav.Id where cav.CheckoutAttributeId == checkoutAttributeId select cav; var checkoutAttributeValues = query.ToList(); return checkoutAttributeValues; }); } /// <summary> /// Gets a checkout attribute value /// </summary> /// <param name="checkoutAttributeValueId">Checkout attribute value identifier</param> /// <returns>Checkout attribute value</returns> public virtual CheckoutAttributeValue GetCheckoutAttributeValueById(int checkoutAttributeValueId) { if (checkoutAttributeValueId == 0) return null; string key = string.Format(CHECKOUTATTRIBUTEVALUES_BY_ID_KEY, checkoutAttributeValueId); return _cacheManager.Get(key, () => _checkoutAttributeValueRepository.GetById(checkoutAttributeValueId)); } /// <summary> /// Inserts a checkout attribute value /// </summary> /// <param name="checkoutAttributeValue">Checkout attribute value</param> public virtual void InsertCheckoutAttributeValue(CheckoutAttributeValue checkoutAttributeValue) { if (checkoutAttributeValue == null) throw new ArgumentNullException("checkoutAttributeValue"); _checkoutAttributeValueRepository.Insert(checkoutAttributeValue); _cacheManager.RemoveByPattern(CHECKOUTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(CHECKOUTATTRIBUTEVALUES_PATTERN_KEY); //event notification _eventPublisher.EntityInserted(checkoutAttributeValue); } /// <summary> /// Updates the checkout attribute value /// </summary> /// <param name="checkoutAttributeValue">Checkout attribute value</param> public virtual void UpdateCheckoutAttributeValue(CheckoutAttributeValue checkoutAttributeValue) { if (checkoutAttributeValue == null) throw new ArgumentNullException("checkoutAttributeValue"); _checkoutAttributeValueRepository.Update(checkoutAttributeValue); _cacheManager.RemoveByPattern(CHECKOUTATTRIBUTES_PATTERN_KEY); _cacheManager.RemoveByPattern(CHECKOUTATTRIBUTEVALUES_PATTERN_KEY); //event notification _eventPublisher.EntityUpdated(checkoutAttributeValue); } #endregion #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using Nini.Config; using OpenSim.Data; using OpenSim.Services.Interfaces; using OpenSim.Framework; using OpenSim.Framework.Console; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenMetaverse; using log4net; namespace OpenSim.Services.UserAccountService { public class GridUserService : GridUserServiceBase, IGridUserService { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public GridUserService(IConfigSource config) : base(config) { m_log.Debug("[GRID USER SERVICE]: Starting user grid service"); MainConsole.Instance.Commands.AddCommand( "Users", false, "show grid users online", "show grid users online", "Show number of grid users registered as online.", "This number may not be accurate as a region may crash or not be cleanly shutdown and leave grid users shown as online\n." + "For this reason, users online for more than 5 days are not currently counted", HandleShowGridUsersOnline); } protected void HandleShowGridUsersOnline(string module, string[] cmdparams) { // if (cmdparams.Length != 4) // { // MainConsole.Instance.Output("Usage: show grid users online"); // return; // } // int onlineCount; int onlineRecentlyCount = 0; DateTime now = DateTime.UtcNow; foreach (GridUserData gu in m_Database.GetAll("")) { if (bool.Parse(gu.Data["Online"])) { // onlineCount++; int unixLoginTime = int.Parse(gu.Data["Login"]); if ((now - Util.ToDateTime(unixLoginTime)).Days < 5) onlineRecentlyCount++; } } MainConsole.Instance.OutputFormat("Users online: {0}", onlineRecentlyCount); } public virtual GridUserInfo GetGridUserInfo(string userID) { GridUserData d = null; if (userID.Length > 36) // it's a UUI d = m_Database.Get(userID); else // it's a UUID { GridUserData[] ds = m_Database.GetAll(userID); if (ds == null) return null; if (ds.Length > 0) { d = ds[0]; foreach (GridUserData dd in ds) if (dd.UserID.Length > d.UserID.Length) // find the longest d = dd; } } if (d == null) return null; GridUserInfo info = new GridUserInfo(); info.UserID = d.UserID; info.HomeRegionID = new UUID(d.Data["HomeRegionID"]); info.HomePosition = Vector3.Parse(d.Data["HomePosition"]); info.HomeLookAt = Vector3.Parse(d.Data["HomeLookAt"]); info.LastRegionID = new UUID(d.Data["LastRegionID"]); info.LastPosition = Vector3.Parse(d.Data["LastPosition"]); info.LastLookAt = Vector3.Parse(d.Data["LastLookAt"]); info.Online = bool.Parse(d.Data["Online"]); info.Login = Util.ToDateTime(Convert.ToInt32(d.Data["Login"])); info.Logout = Util.ToDateTime(Convert.ToInt32(d.Data["Logout"])); return info; } public virtual GridUserInfo[] GetGridUserInfo(string[] userIDs) { List<GridUserInfo> ret = new List<GridUserInfo>(); foreach (string id in userIDs) ret.Add(GetGridUserInfo(id)); return ret.ToArray(); } public GridUserInfo LoggedIn(string userID) { m_log.DebugFormat("[GRID USER SERVICE]: User {0} is online", userID); GridUserData d = m_Database.Get(userID); if (d == null) { d = new GridUserData(); d.UserID = userID; } d.Data["Online"] = true.ToString(); d.Data["Login"] = Util.UnixTimeSinceEpoch().ToString(); m_Database.Store(d); return GetGridUserInfo(userID); } public bool LoggedOut(string userID, UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt) { m_log.DebugFormat("[GRID USER SERVICE]: User {0} is offline", userID); GridUserData d = m_Database.Get(userID); if (d == null) { d = new GridUserData(); d.UserID = userID; } d.Data["Online"] = false.ToString(); d.Data["Logout"] = Util.UnixTimeSinceEpoch().ToString(); d.Data["LastRegionID"] = regionID.ToString(); d.Data["LastPosition"] = lastPosition.ToString(); d.Data["LastLookAt"] = lastLookAt.ToString(); return m_Database.Store(d); } public bool SetHome(string userID, UUID homeID, Vector3 homePosition, Vector3 homeLookAt) { GridUserData d = m_Database.Get(userID); if (d == null) { d = new GridUserData(); d.UserID = userID; } d.Data["HomeRegionID"] = homeID.ToString(); d.Data["HomePosition"] = homePosition.ToString(); d.Data["HomeLookAt"] = homeLookAt.ToString(); return m_Database.Store(d); } public bool SetLastPosition(string userID, UUID sessionID, UUID regionID, Vector3 lastPosition, Vector3 lastLookAt) { m_log.DebugFormat("[GRID USER SERVICE]: SetLastPosition for {0}", userID); GridUserData d = m_Database.Get(userID); if (d == null) { d = new GridUserData(); d.UserID = userID; } d.Data["LastRegionID"] = regionID.ToString(); d.Data["LastPosition"] = lastPosition.ToString(); d.Data["LastLookAt"] = lastLookAt.ToString(); return m_Database.Store(d); } } }
using System; using System.Collections.Generic; using System.Linq; #if UNITY_EDITOR using UnityEditor; #endif namespace UnityEngine.FrameRecorder { public class RecorderInfo { public Type recorderType; public Type settings; public Type settingsEditor; public string category; public string displayName; } /// <summary> /// What is this: /// Motivation : /// Notes: /// </summary> // to be internal once inside unity code base public static class RecordersInventory { internal static SortedDictionary<string, RecorderInfo> m_Recorders { get; private set; } static IEnumerable<KeyValuePair<Type, object[]>> FindRecorders() { var attribType = typeof(FrameRecorderAttribute); foreach (var a in AppDomain.CurrentDomain.GetAssemblies()) { foreach (var t in a.GetTypes()) { var attributes = t.GetCustomAttributes(attribType, false); if (attributes.Length != 0) yield return new KeyValuePair<Type, object[]>(t, attributes); } } } static void Init() { #if UNITY_EDITOR if (m_Recorders != null) return; m_Recorders = new SortedDictionary<string, RecorderInfo>(); foreach (var recorder in FindRecorders() ) AddRecorder(recorder.Key); #endif } #if UNITY_EDITOR static SortedDictionary<string, List<RecorderInfo>> m_RecordersByCategory; public static SortedDictionary<string, List<RecorderInfo>> recordersByCategory { get { Init(); return m_RecordersByCategory; } } static string[] m_AvailableCategories; public static string[] availableCategories { get { if (m_AvailableCategories == null) { m_AvailableCategories = RecordersInventory.ListRecorders() .GroupBy(x => x.category) .Select(x => x.Key) .OrderBy(x => x) .ToArray(); } return m_AvailableCategories; } } #endif static bool AddRecorder(Type recorderType) { var recorderAttribs = recorderType.GetCustomAttributes(typeof(FrameRecorderAttribute), false); if (recorderAttribs.Length == 1) { var recorderAttrib = recorderAttribs[0] as FrameRecorderAttribute; if (m_Recorders == null) m_Recorders = new SortedDictionary<string, RecorderInfo>(); var info = new RecorderInfo() { recorderType = recorderType, settings = recorderAttrib.settings, category = recorderAttrib.category, displayName = recorderAttrib.displayName }; m_Recorders.Add(info.recorderType.FullName, info); #if UNITY_EDITOR if (m_RecordersByCategory == null) m_RecordersByCategory = new SortedDictionary<string, List<RecorderInfo>>(); if (!m_RecordersByCategory.ContainsKey(info.category)) m_RecordersByCategory.Add(info.category, new List<RecorderInfo>()); m_RecordersByCategory[info.category].Add(info); // Find associated editor to recorder's settings type. #endif return true; } else { Debug.LogError(String.Format("The class '{0}' does not have a FrameRecorderAttribute attached to it. ", recorderType.FullName)); } return false; } public static RecorderInfo GetRecorderInfo<TRecorder>() where TRecorder : class { return GetRecorderInfo(typeof(TRecorder)); } public static RecorderInfo GetRecorderInfo(Type recorderType) { Init(); if (m_Recorders.ContainsKey(recorderType.FullName)) return m_Recorders[recorderType.FullName]; #if UNITY_EDITOR return null; #else if (AddRecorder(recorderType)) return m_Recorders[recorderType.FullName]; else return null; #endif } public static IEnumerable<RecorderInfo> ListRecorders() { Init(); foreach (var recorderInfo in m_Recorders) { yield return recorderInfo.Value; } } public static Recorder GenerateNewRecorder(Type recorderType, RecorderSettings settings) { Init(); var factory = GetRecorderInfo(recorderType); if (factory != null) { var recorder = ScriptableObject.CreateInstance(recorderType) as Recorder; recorder.Reset(); recorder.settings = settings; return recorder; } else throw new ArgumentException("No factory was registered for " + recorderType.Name); } #if UNITY_EDITOR public static RecorderSettings GenerateNewSettingsAsset(UnityEngine.Object parentAsset, Type recorderType) { Init(); var recorderinfo = GetRecorderInfo(recorderType); if (recorderinfo != null) { RecorderSettings settings = null; settings = ScriptableObject.CreateInstance(recorderinfo.settings) as RecorderSettings; settings.name = "Recorder Settings"; settings.recorderType = recorderType; settings.m_InputsSettings = settings.GetDefaultSourcesSettings().ToArray(); AssetDatabase.AddObjectToAsset(settings, parentAsset); foreach (var obj in settings.m_InputsSettings) AssetDatabase.AddObjectToAsset(obj, parentAsset); AssetDatabase.Refresh(); return settings; } else throw new ArgumentException("No factory was registered for " + recorderType.Name); } #endif } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Aragas.Network.IO; using Org.BouncyCastle.Crypto.Digests; using Org.BouncyCastle.Crypto.Prng; using PCLExt.FileStorage; using PokeD.Core.Data.SCON; using PokeD.Core.Packets.SCON; using PokeD.Core.Packets.SCON.Authorization; using PokeD.Core.Packets.SCON.Chat; using PokeD.Core.Packets.SCON.Logs; using PokeD.Core.Packets.SCON.Script; using PokeD.Core.Packets.SCON.Status; using PokeD.Server.Extensions; using PokeD.Server.IO; using PokeD.Server.Storage.Folders; namespace PokeD.Server.Clients.SCON { public partial class SCONClient { private AuthorizationStatus AuthorizationStatus { get; } private byte[] VerificationToken { get; set; } private bool Authorized { get; set; } private void HandleAuthorizationRequest(AuthorizationRequestPacket packet) { if (Authorized) return; SendPacket(new AuthorizationResponsePacket { AuthorizationStatus = AuthorizationStatus }); if (AuthorizationStatus.HasFlag(AuthorizationStatus.EncryprionEnabled)) { var publicKey = Module.Security.RSAKeyPair.PublicKeyToByteArray(); VerificationToken = new byte[4]; var drg = new DigestRandomGenerator(new Sha512Digest()); drg.NextBytes(VerificationToken); SendPacket(new EncryptionRequestPacket { PublicKey = publicKey, VerificationToken = VerificationToken }); } } private void HandleEncryptionResponse(EncryptionResponsePacket packet) { if (Authorized) return; if (AuthorizationStatus.HasFlag(AuthorizationStatus.EncryprionEnabled)) { var pkcs = new PKCS1Signer(Module.Security.RSAKeyPair); var decryptedToken = pkcs.DeSignData(packet.VerificationToken); for (var i = 0; i < VerificationToken.Length; i++) if (decryptedToken[i] != VerificationToken[i]) { SendPacket(new AuthorizationDisconnectPacket { Reason = "Unable to authenticate." }); return; } Array.Clear(VerificationToken, 0, VerificationToken.Length); var sharedKey = pkcs.DeSignData(packet.SharedSecret); Stream = new ProtobufTransmission<SCONPacket>(Socket, new BouncyCastleAesStream(Socket, sharedKey)); } else SendPacket(new AuthorizationDisconnectPacket { Reason = "Encryption not enabled!" }); } private void HandleAuthorizationPassword(AuthorizationPasswordPacket packet) { if (Authorized) return; if (Module.SCONPassword.Hash == packet.PasswordHash) { Authorized = true; SendPacket(new AuthorizationCompletePacket()); Join(); IsInitialized = true; } else SendPacket(new AuthorizationDisconnectPacket { Reason = "Password not correct!" }); } private void HandleExecuteCommand(ExecuteCommandPacket packet) { if (!Authorized) { SendPacket(new AuthorizationDisconnectPacket { Reason = "Not authorized!" }); return; } Module.ExecuteClientCommand(this, packet.Command); } private void HandleChatReceivePacket(ChatReceivePacket packet) { if (!Authorized) { SendPacket(new AuthorizationDisconnectPacket { Reason = "Not authorized!" }); return; } ChatEnabled = packet.Enabled; } private void HandlePlayerInfoListRequest(PlayerInfoListRequestPacket packet) { if (!Authorized) { SendPacket(new AuthorizationDisconnectPacket { Reason = "Not authorized!" }); return; } SendPacket(new PlayerInfoListResponsePacket { PlayerInfos = Module.AllClientsSelect(clients => clients.ClientInfos().ToList()).ToArray() }); } private void HandleLogListRequest(LogListRequestPacket packet) { if (!Authorized) { SendPacket(new AuthorizationDisconnectPacket { Reason = "Not authorized!" }); return; } var list = new LogsFolder().GetFiles(); var logs = new List<Log>(); foreach (var file in list) logs.Add(new Log { LogFileName = file.Name }); SendPacket(new LogListResponsePacket { Logs = logs.ToArray() }); } private void HandleLogFileRequest(LogFileRequestPacket packet) { if (!Authorized) { SendPacket(new AuthorizationDisconnectPacket { Reason = "Not authorized!" }); return; } if (new LogsFolder().CheckExists(packet.LogFilename) == ExistenceCheckResult.FileExists) using (var reader = new StreamReader(new LogsFolder().GetFile(packet.LogFilename).Open(PCLExt.FileStorage.FileAccess.Read))) { var logText = reader.ReadToEnd(); SendPacket(new LogFileResponsePacket { LogFilename = packet.LogFilename, LogFile = logText }); } } private void HandleCrashLogListRequest(CrashLogListRequestPacket packet) { if (!Authorized) { SendPacket(new AuthorizationDisconnectPacket {Reason = "Not authorized!"}); return; } var list = new CrashLogsFolder().GetFiles(); var crashLogs = new List<Log>(); foreach (var file in list) crashLogs.Add(new Log { LogFileName = file.Name }); SendPacket(new CrashLogListResponsePacket { CrashLogs = crashLogs.ToArray() }); } private void HandleCrashLogFileRequest(CrashLogFileRequestPacket packet) { if (!Authorized) { SendPacket(new AuthorizationDisconnectPacket { Reason = "Not authorized!" }); return; } if (new CrashLogsFolder().CheckExists(packet.CrashLogFilename) == ExistenceCheckResult.FileExists) using (var reader = new StreamReader(new CrashLogsFolder().GetFile(packet.CrashLogFilename).Open(PCLExt.FileStorage.FileAccess.Read))) { var logText = reader.ReadToEnd(); SendPacket(new CrashLogFileResponsePacket { CrashLogFilename = packet.CrashLogFilename, CrashLogFile = logText }); } } private void HandlePlayerDatabaseListRequest(PlayerDatabaseListRequestPacket packet) { if (!Authorized) { SendPacket(new AuthorizationDisconnectPacket { Reason = "Not authorized!" }); return; } SendPacket(new PlayerDatabaseListResponsePacket { PlayerDatabases = new PlayerDatabase[0] }); } private void HandleBanListRequest(BanListRequestPacket packet) { if (!Authorized) { SendPacket(new AuthorizationDisconnectPacket { Reason = "Not authorized!" }); return; } SendPacket(new BanListResponsePacket { Bans = new Ban[0] }); } private void HandleUploadLuaToServer(UploadScriptToServerPacket packet) { } private void HandleReloadNPCs(ReloadScriptPacket packet) { //Module.Server.ReloadNPCs(); } } }
using System; using System.Data; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Data.SqlClient; using Xunit; using NReco.Data; namespace NReco.Data.Tests { public class DbCommandBuilderTests : IClassFixture<SqliteDbFixture> { SqliteDbFixture SqliteDb; public DbCommandBuilderTests(SqliteDbFixture sqliteDb) { SqliteDb = sqliteDb; } [Fact] public void Sqlite_Select() { var cmdBuilder = new DbCommandBuilder(SqliteDb.DbFactory); var countCmd = cmdBuilder.GetSelectCommand( new Query("contacts").Select(QField.Count) ); countCmd.Connection = SqliteDb.DbConnection; SqliteDb.OpenConnection( () => { Assert.Equal(5, Convert.ToInt32( countCmd.ExecuteScalar() ) ); }); } QNode createTestQuery() { return ( (QField)"name" % (QConst)"Anna" | new QNegationNode( (QField)"age" >= (QConst)18 ) ) & ( (QField)"weight" == (QConst)54.3 & new QConditionNode( (QField)"type", Conditions.In, (QConst)new string[] {"Str1", "Str2"} ) ) | ( (QField)"name"!=(QConst)"Petya" & new QConditionNode( (QField)"type", Conditions.Not|Conditions.Null, null) ); } [Fact] public void Select_Speed() { var dbFactory = new DbFactory( SqlClientFactory.Instance ); var cmdGenerator = new DbCommandBuilder(dbFactory); Query q = new Query( "test" ); q.Condition = createTestQuery(); q.Fields = new QField[] { "name", "age" }; // SELECT TEST var stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Start(); for (int i=0; i<10000; i++) { IDbCommand cmd = cmdGenerator.GetSelectCommand( q ); } stopwatch.Stop(); Console.WriteLine("Speedtest for select command generation (10000 times): {0}", stopwatch.Elapsed); } [Fact] public void InsertUpdateDelete_Speed() { var dbFactory = new DbFactory( SqlClientFactory.Instance ); var cmdGenerator = new DbCommandBuilder(dbFactory); var testData = new Dictionary<string,object> { {"name", "Test" }, {"age", 20 }, {"created", DateTime.Now } }; var testQuery = new Query("test", (QField)"id" == (QConst)5 ); var stopwatch = new Stopwatch(); int iterations = 0; stopwatch.Start(); while (iterations < 500) { iterations++; var insertCmd = cmdGenerator.GetInsertCommand( "test", testData); var updateCmd = cmdGenerator.GetUpdateCommand( testQuery, testData); var deleteCmd = cmdGenerator.GetDeleteCommand( testQuery ); } stopwatch.Stop(); Console.WriteLine("Speedtest for DbCommandGenerator Insert+Update+Delete commands ({1} times): {0}", stopwatch.Elapsed, iterations); } [Fact] public void BuildCommands() { var dbFactory = new DbFactory( SqlClientFactory.Instance ); var cmdGenerator = new DbCommandBuilder(dbFactory); var q = new Query( new QTable("test","t") ); q.Condition = createTestQuery(); q.Fields = new QField[] { "name", "t.age", new QField("age_months", "t.age*12") }; // SELECT TEST with prefixes and expressions IDbCommand cmd = cmdGenerator.GetSelectCommand( q ); string masterSQL = "SELECT name,t.age,t.age*12 as age_months FROM test t WHERE (((name LIKE @p0) Or (NOT(age>=@p1))) And ((weight=@p2) And (type IN (@p3,@p4)))) Or ((name<>@p5) And (type IS NOT NULL))"; Assert.Equal( masterSQL, cmd.CommandText.Trim() ); // SELECT WITH TABLE ALIAS TEST cmd = cmdGenerator.GetSelectCommand( new Query("accounts.a", new QConditionNode( (QField)"a.id", Conditions.In, new Query("dbo.accounts.b", (QField)"a.id"!=(QField)"b.id" ) ) ) ); masterSQL = "SELECT * FROM accounts a WHERE a.id IN (SELECT * FROM dbo.accounts b WHERE a.id<>b.id)"; Assert.Equal( masterSQL, cmd.CommandText); // SELECT AGGREGATE cmd = cmdGenerator.GetSelectCommand( new Query("accounts", (QField)"active" == (QConst)true).Select("name", new QAggregateField("qty_sum", "sum", "qty") )); masterSQL = "SELECT name,sum(qty) as qty_sum FROM accounts WHERE active=@p0 GROUP BY name"; Assert.Equal(masterSQL, cmd.CommandText); var testData = new Dictionary<string,object> { {"name", "Test" }, {"age", 20 }, {"weight", 75.6 }, {"type", "staff" } }; // INSERT TEST cmd = cmdGenerator.GetInsertCommand( "test", testData ); masterSQL = "INSERT INTO test (name,age,weight,type) VALUES (@p0,@p1,@p2,@p3)"; Assert.Equal( cmd.CommandText, masterSQL); Assert.Equal( cmd.Parameters.Count, 4); // UPDATE TEST cmd = cmdGenerator.GetUpdateCommand( new Query("test", (QField)"name"==(QConst)"test"), testData ); masterSQL = "UPDATE test SET name=@p0,age=@p1,weight=@p2,type=@p3 WHERE name=@p4"; Assert.Equal( cmd.CommandText, masterSQL); Assert.Equal( cmd.Parameters.Count, 5); // UPDATE TEST (by query) var changes = new Dictionary<string,IQueryValue>() { { "age", (QConst)21 }, { "name", (QConst)"Alexandra" } }; cmd = cmdGenerator.GetUpdateCommand(new Query("test", (QField)"id" == (QConst)1), changes); masterSQL = "UPDATE test SET age=@p0,name=@p1 WHERE id=@p2"; Assert.Equal(masterSQL, cmd.CommandText); Assert.Equal(3, cmd.Parameters.Count); // DELETE BY QUERY TEST cmd = cmdGenerator.GetDeleteCommand( new Query("test", (QField)"id"==(QConst)5 ) ); masterSQL = "DELETE FROM test WHERE id=@p0"; Assert.Equal( cmd.CommandText, masterSQL); Assert.Equal( cmd.Parameters.Count, 1); // ------- escape identifiers asserts -------- dbFactory.IdentifierFormat = "[{0}]"; Assert.Equal( "SELECT [name],[t].[age],t.age*12 as [age_months] FROM [test] [t] WHERE ((([name] LIKE @p0) Or (NOT([age]>=@p1))) And (([weight]=@p2) And ([type] IN (@p3,@p4)))) Or (([name]<>@p5) And ([type] IS NOT NULL))", cmdGenerator.GetSelectCommand( q ).CommandText.Trim() ); Assert.Equal( "INSERT INTO [test] ([name],[age],[weight],[type]) VALUES (@p0,@p1,@p2,@p3)", cmdGenerator.GetInsertCommand( "test", testData ).CommandText ); Assert.Equal( "UPDATE [test] SET [name]=@p0,[age]=@p1,[weight]=@p2,[type]=@p3 WHERE [name]=@p4", cmdGenerator.GetUpdateCommand( new Query("test", (QField)"name"==(QConst)"test"), testData ).CommandText ); Assert.Equal( "DELETE FROM [test] WHERE [id]=@p0", cmdGenerator.GetDeleteCommand( new Query("test", (QField)"id"==(QConst)5 ) ).CommandText ); } [Fact] public void DataView() { var dbFactory = new DbFactory( SqlClientFactory.Instance ); var cmdGenerator = new DbCommandBuilder(dbFactory); cmdGenerator.Views = new Dictionary<string,DbDataView>() { { "persons_view", new DbDataView( @"SELECT @columns FROM persons p LEFT JOIN countries c ON (c.id=p.country_id) @where[ WHERE {0}] @orderby[ ORDER BY {0}]") { FieldMapping = new Dictionary<string,string>() { {"id", "p.id"}, {"count(*)", "count(p.id)" }, {"*", "p.*" }, {"expired", "CASE WHEN DATEDIFF(dd, p.added_date, NOW() )>30 THEN 1 ELSE 0 END" } } } } }; // simple count query test Assert.Equal( "SELECT count(p.id) as cnt FROM persons p LEFT JOIN countries c ON (c.id=p.country_id)", cmdGenerator.GetSelectCommand( new Query("persons_view").Select(QField.Count) ).CommandText.Trim() ); // field mapping in select columns Assert.Equal( "SELECT p.id as id,name,CASE WHEN DATEDIFF(dd, p.added_date, NOW() )>30 THEN 1 ELSE 0 END as expired FROM persons p LEFT JOIN countries c ON (c.id=p.country_id)", cmdGenerator.GetSelectCommand( new Query("persons_view") .Select("id", "name", "expired") ).CommandText.Trim() ); // field mapping in conditions Assert.Equal( "SELECT p.* FROM persons p LEFT JOIN countries c ON (c.id=p.country_id) WHERE (p.id>@p0) And (CASE WHEN DATEDIFF(dd, p.added_date, NOW() )>30 THEN 1 ELSE 0 END=@p1)", cmdGenerator.GetSelectCommand( new Query("persons_view", (QField)"id">(QConst)5 & (QField)"expired"==new QConst(true) ) ).CommandText.Trim() ); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="RectFileWriter.cs" company="Microsoft"> // (c) Microsoft Corporation. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.IO; using System.Linq; using Microsoft.Msagl.Core.Geometry; using Microsoft.Msagl.Core.Geometry.Curves; using Microsoft.Msagl.Core.Layout; using Path = System.IO.Path; namespace Microsoft.Msagl.UnitTests.Rectilinear { using System.Collections.Generic; using Routing; using Routing.Rectilinear; internal class RectFileWriter : IDisposable { private readonly RectilinearEdgeRouterWrapper router; private readonly RectilinearVerifier verifier; // If the writer is instantiated by TestRectilinear it will set these. // Otherwise they have their default values in the header and only the // verifier information is of interest. internal int InitialSeed { get; set; } internal string RandomObstacleArg { get; set; } internal int RandomObstacleCount { get; set; } internal string RandomObstacleDensity { get; set; } internal bool RandomObstacleRotate { get; set; } // For writing out the relationship between free relative ports and their shapes. private readonly Dictionary<Port, Shape> freeRelativePortToShapeMap; private StreamWriter outputFileWriter; private readonly Dictionary<Port, int> portToIdMap = new Dictionary<Port, int>(); private readonly Dictionary<Shape, int> shapeToIdMap = new Dictionary<Shape, int>(); // For large files we may not want to write N^2 vertices and edges; we'll just write and verify the counts. private readonly bool writeGraph; // In some cases we may not want one or more of paths, padded obstacles, or scan segments. private readonly bool writePaths; private readonly bool writeScanSegments; private readonly bool writePaddedObstacles; private readonly bool writeConvexHulls; private readonly bool useFreePortsForObstaclesPorts; private readonly bool useSparseVisibilityGraph; private readonly bool useObstacleRectangles; private readonly double bendPenalty; private readonly bool limitPortVisibilitySpliceToEndpointBoundingBox; private const int FreePortShapeId = -1; private int nextPortId; // post-increment so >= 0 is valid private int NextPortId { get { return nextPortId++; } } private readonly Dictionary<Clump, int> clumpToIdMap = new Dictionary<Clump, int>(); private readonly Dictionary<OverlapConvexHull, int> convexHullToIdMap = new Dictionary<OverlapConvexHull, int>(); private int nextClumpId = 10000; // For easier debugging, start here private int nextConvexHullId = 20000; // For easier debugging, start here private int GetNextClumpId() { return this.nextClumpId++; } private int GetNextConvexHullId() { return this.nextConvexHullId++; } internal RectFileWriter(RectilinearEdgeRouterWrapper router, RectilinearVerifier verifier, Dictionary<Port, Shape> freeRelativePortToShapeMap = null, bool writeGraph = true, bool writePaths = true, bool writeScanSegments = true, bool writePaddedObstacles = true, bool writeConvexHulls = true, bool useFreePortsForObstaclePorts = false ) { this.router = router; this.verifier = verifier; this.freeRelativePortToShapeMap = freeRelativePortToShapeMap; this.writeGraph = writeGraph; this.writePaths = writePaths; this.writeScanSegments = writeScanSegments; this.writePaddedObstacles = writePaddedObstacles; this.writeConvexHulls = writeConvexHulls; this.useFreePortsForObstaclesPorts = useFreePortsForObstaclePorts; this.useSparseVisibilityGraph = router.UseSparseVisibilityGraph; this.useObstacleRectangles = router.UseObstacleRectangles; this.bendPenalty = router.BendPenaltyAsAPercentageOfDistance; this.limitPortVisibilitySpliceToEndpointBoundingBox = router.LimitPortVisibilitySpliceToEndpointBoundingBox; // Don't leave these null - they'll be overwritten by caller in most cases. this.RandomObstacleArg = RectFileStrings.NullStr; this.RandomObstacleDensity = RectFileStrings.NullStr; } internal void WriteFile(string fileName, string commandLine = null) { this.outputFileWriter = new StreamWriter(Path.GetFullPath(fileName)); WriteCommandLineArgs(commandLine); // Prepopulate the shape-to-obstacle map so we can write children and order by shape Id. AssignShapeIds(); // Input parameters and output summary WriteHeader(); // Input detail WriteInputObstacles(); WritePorts(); WriteRoutingSpecs(); // Output detail WritePaddedObstacles(); WriteConvexHulls(); WriteScanSegments(); WriteVisibilityGraph(); WritePaths(); // Done. this.outputFileWriter.Flush(); this.outputFileWriter.Close(); } private void WriteCommandLineArgs(string commandLine) { // First thing to write is the commandline args. // If null != commandLine we're recreating an existing test file. if (null != commandLine) { // Some previously-generated files have " -quiet" which we don't want const string spaceAndQuiet = " -quiet"; var index = commandLine.IndexOf(spaceAndQuiet, StringComparison.OrdinalIgnoreCase); if (index >= 0) { commandLine = commandLine.Remove(index, spaceAndQuiet.Length); } this.outputFileWriter.WriteLine("// " + commandLine); } else { // Skip both program name and the outfile specification. Quote any space-containing args. // This cmdline should be usable from cmdline as well as -updateFile. this.outputFileWriter.Write("//"); var args = Environment.GetCommandLineArgs(); var space = new[] {' '}; for (int ii = 0; ii < args.Length; ++ii) { if (0 == ii) { // Program name continue; } var arg = args[ii]; if (0 == string.Compare("-outFile", arg, StringComparison.OrdinalIgnoreCase)) { // Skip current and next arg. ++ii; continue; } if (0 == string.Compare("-quiet", arg, StringComparison.OrdinalIgnoreCase)) { // Skip current arg. continue; } if (arg.IndexOfAny(space) >= 0) { this.outputFileWriter.Write(" \"" + arg + "\""); continue; } this.outputFileWriter.Write(" " + arg); } this.outputFileWriter.WriteLine(); } } private void AssignShapeIds() { // Assign shape Ids in the ordinal order so the -ports option to TestRectilinear works. int id = 0; foreach (var shape in this.router.Obstacles) { // Post-increment so >= 0 is valid. this.shapeToIdMap.Add(shape, id++); } } private void WriteHeader() { // Input parameters this.outputFileWriter.WriteLine(RectFileStrings.WriteSeed, this.InitialSeed.ToString("X")); this.outputFileWriter.WriteLine(RectFileStrings.WriteRandomArgs, this.RandomObstacleArg, this.RandomObstacleCount, this.RandomObstacleDensity, this.RandomObstacleRotate); this.outputFileWriter.WriteLine(RectFileStrings.WritePadding, this.verifier.RouterPadding); this.outputFileWriter.WriteLine(RectFileStrings.WriteEdgeSeparation, this.verifier.RouterEdgeSeparation); this.outputFileWriter.WriteLine(RectFileStrings.WriteRouteToCenter, this.verifier.RouteToCenterOfObstacles); this.outputFileWriter.WriteLine(RectFileStrings.WriteArrowheadLength, this.verifier.RouterArrowheadLength); // New stuff this.outputFileWriter.WriteLine(RectFileStrings.WriteUseFreePortsForObstaclePorts, this.useFreePortsForObstaclesPorts); this.outputFileWriter.WriteLine(RectFileStrings.WriteUseSparseVisibilityGraph, this.useSparseVisibilityGraph); this.outputFileWriter.WriteLine(RectFileStrings.WriteUseObstacleRectangles, this.useObstacleRectangles); this.outputFileWriter.WriteLine(RectFileStrings.WriteBendPenalty, this.bendPenalty); this.outputFileWriter.WriteLine(RectFileStrings.WriteLimitPortVisibilitySpliceToEndpointBoundingBox, this.limitPortVisibilitySpliceToEndpointBoundingBox); this.outputFileWriter.WriteLine(RectFileStrings.WriteWantPaths, this.verifier.WantPaths); this.outputFileWriter.WriteLine(RectFileStrings.WriteWantNudger, this.verifier.WantNudger); this.outputFileWriter.WriteLine(RectFileStrings.WriteWantVerify, this.verifier.WantVerify); this.outputFileWriter.WriteLine(RectFileStrings.WriteStraightTolerance, this.verifier.StraightTolerance); this.outputFileWriter.WriteLine(RectFileStrings.WriteCornerTolerance, this.verifier.CornerTolerance); // Output summary } private void WriteInputObstacles() { this.outputFileWriter.WriteLine(); this.outputFileWriter.WriteLine(RectFileStrings.BeginUnpaddedObstacles); foreach (var shape in this.router.Obstacles.OrderBy(shape => shapeToIdMap[shape])) { WriteInputShape(shape); WriteChildren(shape.Children); var obstacle = router.ShapeToObstacleMap[shape]; this.WriteClumpId(obstacle); this.WriteConvexHullId(obstacle); } this.outputFileWriter.WriteLine(RectFileStrings.EndUnpaddedObstacles); } private void WriteInputShape(Shape shape) { var curve = shape.BoundaryCurve as Curve; if (null != curve) { this.WriteCurve(shape, curve); return; } var ellipse = shape.BoundaryCurve as Ellipse; if (null != ellipse) { this.WriteEllipse(shape, ellipse); return; } var roundRect = shape.BoundaryCurve as RoundedRect; if (null != roundRect) { this.WriteRoundedRect(shape, roundRect); return; } // this must be a polyline. var poly = (Polyline)shape.BoundaryCurve; this.WritePolyline(shape, poly); } private void WriteCurve(Shape shape, Curve curve) { this.outputFileWriter.WriteLine(RectFileStrings.BeginCurve); if (null != shape) { // If a path, this is null this.outputFileWriter.WriteLine(RectFileStrings.WriteId, shapeToIdMap[shape]); } foreach (var seg in curve.Segments) { this.outputFileWriter.WriteLine(RectFileStrings.WriteSegment, seg.Start.X, seg.Start.Y, seg.End.X, seg.End.Y); } this.outputFileWriter.WriteLine(RectFileStrings.EndCurve); } private void WriteEllipse(Shape shape, Ellipse ellipse) { this.outputFileWriter.WriteLine(RectFileStrings.BeginEllipse); this.outputFileWriter.WriteLine(RectFileStrings.WriteId, shapeToIdMap[shape]); this.outputFileWriter.WriteLine( RectFileStrings.WriteEllipse, ellipse.AxisA.X, ellipse.AxisA.Y, ellipse.AxisB.X, ellipse.AxisB.Y, ellipse.Center.X, ellipse.Center.Y); this.outputFileWriter.WriteLine(RectFileStrings.EndEllipse); } private void WriteRoundedRect(Shape shape, RoundedRect roundRect) { this.outputFileWriter.WriteLine(RectFileStrings.BeginRoundedRect); this.outputFileWriter.WriteLine(RectFileStrings.WriteId, shapeToIdMap[shape]); this.outputFileWriter.WriteLine( RectFileStrings.WriteRoundedRect, roundRect.BoundingBox.Left, roundRect.BoundingBox.Bottom, roundRect.BoundingBox.Width, roundRect.BoundingBox.Height, roundRect.RadiusX, roundRect.RadiusY); this.outputFileWriter.WriteLine(RectFileStrings.EndRoundedRect); } private void WritePolyline(Shape shape, Polyline poly) { this.outputFileWriter.WriteLine(RectFileStrings.BeginPolyline); this.outputFileWriter.WriteLine(RectFileStrings.WriteId, shapeToIdMap[shape]); foreach (var point in poly) { this.outputFileWriter.WriteLine(RectFileStrings.WritePoint, point.X, point.Y); } this.outputFileWriter.WriteLine(RectFileStrings.EndPolyline); } private void WriteChildren(IEnumerable<Shape> children) { // A group is a shape with children. if ((null == children) || !children.Any()) { return; } this.outputFileWriter.WriteLine(RectFileStrings.Children); foreach (var child in children) { this.outputFileWriter.WriteLine(RectFileStrings.WriteId, shapeToIdMap[child]); } } private void WriteClumpId(Obstacle obstacle) { if (!obstacle.IsOverlapped) { return; } int id; if (!this.clumpToIdMap.TryGetValue(obstacle.Clump, out id)) { id = this.GetNextClumpId(); this.clumpToIdMap[obstacle.Clump] = id; } this.outputFileWriter.WriteLine(RectFileStrings.WriteClumpId, id); } private void WriteConvexHullId(Obstacle obstacle) { // This writes for both group and non-group. if (!obstacle.IsInConvexHull) { return; } int id; if (!this.convexHullToIdMap.TryGetValue(obstacle.ConvexHull, out id)) { id = this.GetNextConvexHullId(); this.convexHullToIdMap[obstacle.ConvexHull] = id; } this.outputFileWriter.WriteLine(RectFileStrings.WriteConvexHullId, id); } private void WritePorts() { this.outputFileWriter.WriteLine(); this.outputFileWriter.WriteLine(RectFileStrings.BeginPorts); foreach (var shape in this.router.Obstacles.Where(shape => null != shape.Ports)) { foreach (var port in shape.Ports) { WriteObstaclePort(shape, port); } } foreach (var edgeGeom in this.router.EdgeGeometriesToRoute) { WriteIfFreePort(edgeGeom.SourcePort); WriteIfFreePort(edgeGeom.TargetPort); } this.outputFileWriter.WriteLine(RectFileStrings.EndPorts); } private void WriteObstaclePort(Shape shape, Port port) { Validate.IsFalse(portToIdMap.ContainsKey(port), "Duplicate entries for port in the same or different shape.Ports list(s)"); var relativePort = port as RelativeFloatingPort; if (null != relativePort) { Validate.IsTrue(PointComparer.Equal(shape.BoundingBox.Center, relativePort.CenterDelegate()), "Port CenterDelegate must be Shape.Center for file persistence"); Validate.AreEqual(shape.BoundaryCurve, port.Curve, "Port curve is not the same as that of the Shape in which it is a member"); } portToIdMap.Add(port, NextPortId); WritePort(port, shapeToIdMap[shape]); } private void WriteIfFreePort(Port port) { // Skip this port if we've already processed it. if (portToIdMap.ContainsKey(port)) { return; } int shapeId = FreePortShapeId; if (port is RelativeFloatingPort) { Shape shape; if ((null == this.freeRelativePortToShapeMap) || !this.freeRelativePortToShapeMap.TryGetValue(port, out shape)) { Validate.Fail("Relative FreePorts must be in FreeRelativePortToShapeMap"); return; } shapeId = shapeToIdMap[shape]; } portToIdMap.Add(port, NextPortId); WritePort(port, shapeId); } private void WritePort(Port port, int shapeId) { if (typeof(FloatingPort) == port.GetType()) { this.outputFileWriter.WriteLine(RectFileStrings.WritePort, RectFileStrings.Floating, port.Location.X, port.Location.Y, portToIdMap[port], shapeId); } else { WriteRelativePort(port, shapeId); } WritePortEntries(port); } private void WriteRelativePort(Port port, int shapeId) { var relativePort = port as RelativeFloatingPort; var multiPort = port as MultiLocationFloatingPort; Validate.IsNotNull(relativePort, "Unsupported port type for file persistence"); // ReSharper disable PossibleNullReferenceException // The location in the main WritePort line is relevant only for non-multiPort; for multiPorts // the caller sets location via ActiveOffsetIndex. var portTypeString = (null != multiPort) ? RectFileStrings.Multi : RectFileStrings.Relative; this.outputFileWriter.WriteLine(RectFileStrings.WritePort, portTypeString, relativePort.LocationOffset.X, relativePort.LocationOffset.Y, this.portToIdMap[port], shapeId); // ReSharper restore PossibleNullReferenceException if (null != multiPort) { this.outputFileWriter.WriteLine(RectFileStrings.WriteMultiPortOffsets, multiPort.ActiveOffsetIndex); foreach (var offset in multiPort.LocationOffsets) { this.outputFileWriter.WriteLine(RectFileStrings.WritePoint, offset.X, offset.Y); } } } private void WritePortEntries(Port port) { if (null == port.PortEntry) { return; } var portEntryOnCurve = port.PortEntry as PortEntryOnCurve; Validate.IsNotNull(portEntryOnCurve, "Unknown IPortEntry implementation"); // ReSharper disable PossibleNullReferenceException this.outputFileWriter.WriteLine(RectFileStrings.PortEntryOnCurve); foreach (var span in portEntryOnCurve.Spans) { this.outputFileWriter.WriteLine(RectFileStrings.WritePoint, span.Item1, span.Item2); } // ReSharper restore PossibleNullReferenceException } private void WriteRoutingSpecs() { this.outputFileWriter.WriteLine(); this.outputFileWriter.WriteLine(RectFileStrings.BeginRoutingSpecs); foreach (var geom in this.router.EdgeGeometriesToRoute) { var arrowhead = geom.SourceArrowhead ?? geom.TargetArrowhead; var arrowheadLength = (null == arrowhead) ? 0.0 : arrowhead.Length; var arrowheadWidth = (null == arrowhead) ? 0.0 : arrowhead.Width; this.outputFileWriter.WriteLine(RectFileStrings.WriteEdgeGeometry, portToIdMap[geom.SourcePort], portToIdMap[geom.TargetPort], null != geom.SourceArrowhead, null != geom.TargetArrowhead, arrowheadLength, arrowheadWidth, geom.LineWidth); if (null != geom.Waypoints) { this.outputFileWriter.WriteLine(RectFileStrings.Waypoints); foreach (var waypoint in geom.Waypoints) { this.outputFileWriter.WriteLine(RectFileStrings.WritePoint, waypoint.X, waypoint.Y); } } } this.outputFileWriter.WriteLine(RectFileStrings.EndRoutingSpecs); } private void WritePaddedObstacles() { this.outputFileWriter.WriteLine(); this.outputFileWriter.WriteLine(RectFileStrings.BeginPaddedObstacles); if (this.writePaddedObstacles) { foreach (Obstacle obstacle in this.router.ObstacleTree.GetAllObstacles().OrderBy(obstacle => shapeToIdMap[obstacle.InputShape])) { this.outputFileWriter.WriteLine(RectFileStrings.BeginPolyline); this.outputFileWriter.WriteLine(RectFileStrings.WriteId, shapeToIdMap[obstacle.InputShape]); foreach (Point point in obstacle.PaddedPolyline) { this.outputFileWriter.WriteLine(RectFileStrings.WritePoint, point.X, point.Y); } this.outputFileWriter.WriteLine(RectFileStrings.EndPolyline); } } this.outputFileWriter.WriteLine(RectFileStrings.EndPaddedObstacles); } private void WriteConvexHulls() { this.outputFileWriter.WriteLine(); this.outputFileWriter.WriteLine(RectFileStrings.BeginConvexHulls); if (this.writeConvexHulls) { foreach (var hullIdPair in this.convexHullToIdMap) { this.outputFileWriter.WriteLine(RectFileStrings.BeginPolyline); this.outputFileWriter.WriteLine(RectFileStrings.WriteId, hullIdPair.Value); foreach (Point point in hullIdPair.Key.Polyline) { this.outputFileWriter.WriteLine(RectFileStrings.WritePoint, point.X, point.Y); } this.outputFileWriter.WriteLine(RectFileStrings.EndPolyline); } } this.outputFileWriter.WriteLine(RectFileStrings.EndConvexHulls); } private void WriteScanSegments() { this.outputFileWriter.WriteLine(); this.outputFileWriter.WriteLine(RectFileStrings.BeginHScanSegments); if (this.writeScanSegments) { // These are already ordered as desired in the tree. foreach (var scanSeg in this.router.HorizontalScanLineSegments) { this.outputFileWriter.WriteLine( RectFileStrings.WriteSegment, scanSeg.Start.X, scanSeg.Start.Y, scanSeg.End.X, scanSeg.End.Y); } } this.outputFileWriter.WriteLine(RectFileStrings.EndHScanSegments); this.outputFileWriter.WriteLine(); this.outputFileWriter.WriteLine(RectFileStrings.BeginVScanSegments); if (this.writeScanSegments) { // These are already ordered as desired in the tree. foreach (var scanSeg in this.router.VerticalScanLineSegments) { this.outputFileWriter.WriteLine( RectFileStrings.WriteSegment, scanSeg.Start.X, scanSeg.Start.Y, scanSeg.End.X, scanSeg.End.Y); } } this.outputFileWriter.WriteLine(RectFileStrings.EndVScanSegments); } private void WriteVisibilityGraph() { this.outputFileWriter.WriteLine(); this.outputFileWriter.WriteLine(RectFileStrings.BeginVisibilityVertices); // Put in the begin/end even if !writeGraph, to make reading easier. if (writeGraph) { foreach (Point vertexPoint in this.router.VisibilityGraph.Vertices().Select(v => v.Point).OrderBy(pt => pt, new VertexPointOrderer())) { this.outputFileWriter.WriteLine(RectFileStrings.WritePoint, vertexPoint.X, vertexPoint.Y); } } this.outputFileWriter.WriteLine(RectFileStrings.EndVisibilityVertices); this.outputFileWriter.WriteLine(); this.outputFileWriter.WriteLine(RectFileStrings.BeginVisibilityEdges); if (writeGraph) { foreach (LineSegment edgeSegment in this.router.VisibilityGraph.Edges.Select(edge => new LineSegment(edge.SourcePoint, edge.TargetPoint)). OrderBy(seg => seg, new SegmentOrderer(new TestPointComparer()))) { this.outputFileWriter.WriteLine( RectFileStrings.WriteSegment, edgeSegment.Start.X, edgeSegment.Start.Y, edgeSegment.End.X, edgeSegment.End.Y); } } this.outputFileWriter.WriteLine(RectFileStrings.EndVisibilityEdges); } private void WritePaths() { this.outputFileWriter.WriteLine(); this.outputFileWriter.WriteLine(RectFileStrings.BeginPaths); // Put in the begin/end even if !writePaths, to make reading easier. if (writePaths) { foreach (var geom in this.router.EdgeGeometriesToRoute.Where(geom => null != geom.Curve).OrderBy( geom => geom, new EdgeGeometryOrderer(portToIdMap))) { this.outputFileWriter.WriteLine( RectFileStrings.WritePathEndpoints, portToIdMap[geom.SourcePort], portToIdMap[geom.TargetPort]); var curve = (Curve)geom.Curve; // this is currently always a Curve. WriteCurve(/*shape:*/ null, curve); } } this.outputFileWriter.WriteLine(RectFileStrings.EndPaths); } #region IDisposable Members public void Dispose() { if (null != this.outputFileWriter) { this.outputFileWriter.Dispose(); this.outputFileWriter = null; } } #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Hyak.Common; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Compute; using Microsoft.WindowsAzure.Management.Compute.Models; namespace Microsoft.WindowsAzure.Management.Compute { /// <summary> /// The Service Management API provides programmatic access to much of the /// functionality available through the Management Portal. The Service /// Management API is a REST API. All API operations are performed over /// SSL, and are mutually authenticated using X.509 v3 certificates. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460799.aspx for /// more information) /// </summary> public partial class ComputeManagementClient : ServiceClient<ComputeManagementClient>, IComputeManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private IDeploymentOperations _deployments; /// <summary> /// The Service Management API includes operations for managing the /// deployments in your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460812.aspx /// for more information) /// </summary> public virtual IDeploymentOperations Deployments { get { return this._deployments; } } private IDNSServerOperations _dnsServer; /// <summary> /// The Compute Management API includes operations for managing the dns /// servers for your subscription. /// </summary> public virtual IDNSServerOperations DnsServer { get { return this._dnsServer; } } private IExtensionImageOperations _extensionImages; /// <summary> /// The Service Management API includes operations for managing the /// service and virtual machine extension images in your publisher /// subscription. /// </summary> public virtual IExtensionImageOperations ExtensionImages { get { return this._extensionImages; } } private IHostedServiceOperations _hostedServices; /// <summary> /// The Service Management API includes operations for managing the /// hosted services beneath your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460812.aspx /// for more information) /// </summary> public virtual IHostedServiceOperations HostedServices { get { return this._hostedServices; } } private ILoadBalancerOperations _loadBalancers; /// <summary> /// The Compute Management API includes operations for managing the /// load balancers for your subscription. /// </summary> public virtual ILoadBalancerOperations LoadBalancers { get { return this._loadBalancers; } } private IOperatingSystemOperations _operatingSystems; /// <summary> /// Operations for determining the version of the Azure Guest Operating /// System on which your service is running. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ff684169.aspx /// for more information) /// </summary> public virtual IOperatingSystemOperations OperatingSystems { get { return this._operatingSystems; } } private IServiceCertificateOperations _serviceCertificates; /// <summary> /// Operations for managing service certificates for your subscription. /// (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee795178.aspx /// for more information) /// </summary> public virtual IServiceCertificateOperations ServiceCertificates { get { return this._serviceCertificates; } } private IVirtualMachineDiskOperations _virtualMachineDisks; /// <summary> /// The Service Management API includes operations for managing the /// disks in your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157188.aspx /// for more information) /// </summary> public virtual IVirtualMachineDiskOperations VirtualMachineDisks { get { return this._virtualMachineDisks; } } private IVirtualMachineExtensionOperations _virtualMachineExtensions; /// <summary> /// The Service Management API includes operations for managing the /// virtual machine extensions in your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157206.aspx /// for more information) /// </summary> public virtual IVirtualMachineExtensionOperations VirtualMachineExtensions { get { return this._virtualMachineExtensions; } } private IVirtualMachineOperations _virtualMachines; /// <summary> /// The Service Management API includes operations for managing the /// virtual machines in your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157206.aspx /// for more information) /// </summary> public virtual IVirtualMachineOperations VirtualMachines { get { return this._virtualMachines; } } private IVirtualMachineOSImageOperations _virtualMachineOSImages; /// <summary> /// The Service Management API includes operations for managing the OS /// images in your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157175.aspx /// for more information) /// </summary> public virtual IVirtualMachineOSImageOperations VirtualMachineOSImages { get { return this._virtualMachineOSImages; } } private IVirtualMachineVMImageOperations _virtualMachineVMImages; /// <summary> /// The Service Management API includes operations for managing the /// virtual machine templates in your subscription. /// </summary> public virtual IVirtualMachineVMImageOperations VirtualMachineVMImages { get { return this._virtualMachineVMImages; } } /// <summary> /// Initializes a new instance of the ComputeManagementClient class. /// </summary> public ComputeManagementClient() : base() { this._deployments = new DeploymentOperations(this); this._dnsServer = new DNSServerOperations(this); this._extensionImages = new ExtensionImageOperations(this); this._hostedServices = new HostedServiceOperations(this); this._loadBalancers = new LoadBalancerOperations(this); this._operatingSystems = new OperatingSystemOperations(this); this._serviceCertificates = new ServiceCertificateOperations(this); this._virtualMachineDisks = new VirtualMachineDiskOperations(this); this._virtualMachineExtensions = new VirtualMachineExtensionOperations(this); this._virtualMachines = new VirtualMachineOperations(this); this._virtualMachineOSImages = new VirtualMachineOSImageOperations(this); this._virtualMachineVMImages = new VirtualMachineVMImageOperations(this); this._apiVersion = "2016-06-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the ComputeManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public ComputeManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the ComputeManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public ComputeManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.core.windows.net"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the ComputeManagementClient class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public ComputeManagementClient(HttpClient httpClient) : base(httpClient) { this._deployments = new DeploymentOperations(this); this._dnsServer = new DNSServerOperations(this); this._extensionImages = new ExtensionImageOperations(this); this._hostedServices = new HostedServiceOperations(this); this._loadBalancers = new LoadBalancerOperations(this); this._operatingSystems = new OperatingSystemOperations(this); this._serviceCertificates = new ServiceCertificateOperations(this); this._virtualMachineDisks = new VirtualMachineDiskOperations(this); this._virtualMachineExtensions = new VirtualMachineExtensionOperations(this); this._virtualMachines = new VirtualMachineOperations(this); this._virtualMachineOSImages = new VirtualMachineOSImageOperations(this); this._virtualMachineVMImages = new VirtualMachineVMImageOperations(this); this._apiVersion = "2016-06-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the ComputeManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public ComputeManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the ComputeManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public ComputeManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.core.windows.net"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// ComputeManagementClient instance /// </summary> /// <param name='client'> /// Instance of ComputeManagementClient to clone to /// </param> protected override void Clone(ServiceClient<ComputeManagementClient> client) { base.Clone(client); if (client is ComputeManagementClient) { ComputeManagementClient clonedClient = ((ComputeManagementClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } /// <summary> /// Parse enum values for type CertificateFormat. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static CertificateFormat ParseCertificateFormat(string value) { if ("pfx".Equals(value, StringComparison.OrdinalIgnoreCase)) { return CertificateFormat.Pfx; } if ("cer".Equals(value, StringComparison.OrdinalIgnoreCase)) { return CertificateFormat.Cer; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type CertificateFormat to a string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string CertificateFormatToString(CertificateFormat value) { if (value == CertificateFormat.Pfx) { return "pfx"; } if (value == CertificateFormat.Cer) { return "cer"; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Parse enum values for type LoadBalancerProbeTransportProtocol. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static LoadBalancerProbeTransportProtocol ParseLoadBalancerProbeTransportProtocol(string value) { if ("tcp".Equals(value, StringComparison.OrdinalIgnoreCase)) { return LoadBalancerProbeTransportProtocol.Tcp; } if ("http".Equals(value, StringComparison.OrdinalIgnoreCase)) { return LoadBalancerProbeTransportProtocol.Http; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type LoadBalancerProbeTransportProtocol to a /// string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string LoadBalancerProbeTransportProtocolToString(LoadBalancerProbeTransportProtocol value) { if (value == LoadBalancerProbeTransportProtocol.Tcp) { return "tcp"; } if (value == LoadBalancerProbeTransportProtocol.Http) { return "http"; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx /// for more information) /// </summary> /// <param name='requestId'> /// Required. The request ID for the request you wish to track. The /// request ID is returned in the x-ms-request-id response header for /// every request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public async Task<OperationStatusResponse> GetOperationStatusAsync(string requestId, CancellationToken cancellationToken) { // Validate if (requestId == null) { throw new ArgumentNullException("requestId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("requestId", requestId); TracingAdapter.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Credentials.SubscriptionId); } url = url + "/operations/"; url = url + Uri.EscapeDataString(requestId); string baseUrl = this.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2016-06-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result OperationStatusResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new OperationStatusResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement operationElement = responseDoc.Element(XName.Get("Operation", "http://schemas.microsoft.com/windowsazure")); if (operationElement != null) { XElement idElement = operationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; result.Id = idInstance; } XElement statusElement = operationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure")); if (statusElement != null) { OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), statusElement.Value, true)); result.Status = statusInstance; } XElement httpStatusCodeElement = operationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure")); if (httpStatusCodeElement != null) { HttpStatusCode httpStatusCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, true)); result.HttpStatusCode = httpStatusCodeInstance; } XElement errorElement = operationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure")); if (errorElement != null) { OperationStatusResponse.ErrorDetails errorInstance = new OperationStatusResponse.ErrorDetails(); result.Error = errorInstance; XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure")); if (codeElement != null) { string codeInstance = codeElement.Value; errorInstance.Code = codeInstance; } XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure")); if (messageElement != null) { string messageInstance = messageElement.Value; errorInstance.Message = messageInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.Collections.Generic; using System.Text; using System.IO; using Vestris.ResourceLib; using System.Reflection; using System.Web; using NUnit.Framework; using System.ComponentModel; namespace Vestris.ResourceLibUnitTests { [TestFixture] public class VersionResourceTests { private static readonly object[] TestAssemblies = { new object[] { "atl.dll", 1033 }, new object[] { "ClassLibrary_NET2.0.dll", 0 }, new object[] { "ClassLibrary_NET3.0.dll", 0 }, new object[] { "ClassLibrary_NET3.5.dll", 0 }, new object[] { "ClassLibrary_NET3.5ClientProfile.dll", 0 }, new object[] { "ClassLibrary_NET4.0.dll", 0 }, new object[] { "ClassLibrary_NET4.0ClientProfile.dll", 0 }, new object[] { "ClassLibrary_NET4.5.dll", 0 }, new object[] { "ClassLibrary_NET4.5.1.dll", 0 }, }; [TestCaseSource("TestAssemblies")] public void TestLoadVersionResource(string binaryName, int language) { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\" + binaryName); Assert.IsTrue(File.Exists(filename)); VersionResource versionResource = new VersionResource(); versionResource.Language = ResourceUtil.USENGLISHLANGID; versionResource.LoadFrom(filename); DumpResource.Dump(versionResource); AssertOneVersionResource(filename); } [TestCaseSource("TestAssemblies")] public void TestLoadVersionResourceStrings(string binaryName, int language) { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\" + binaryName); Assert.IsTrue(File.Exists(filename)); VersionResource versionResource = new VersionResource(); versionResource.Language = ResourceUtil.USENGLISHLANGID; versionResource.LoadFrom(filename); DumpResource.Dump(versionResource); AssertOneVersionResource(filename); } [TestCaseSource("TestAssemblies")] public void TestLoadAndSaveVersionResource(string binaryName, int language) { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\" + binaryName); Assert.IsTrue(File.Exists(filename)); VersionResource versionResource = new VersionResource(); versionResource.Language = (ushort)language; versionResource.LoadFrom(filename); DumpResource.Dump(versionResource); versionResource.FileVersion = "1.2.3.4"; versionResource.ProductVersion = "5.6.7.8"; versionResource.FileFlags = 0x2 | 0x8; // private and prerelease StringFileInfo stringFileInfo = (StringFileInfo)versionResource["StringFileInfo"]; stringFileInfo["Comments"] = string.Format("{0}\0", Guid.NewGuid()); stringFileInfo["NewValue"] = string.Format("{0}\0", Guid.NewGuid()); VarFileInfo varFileInfo = (VarFileInfo)versionResource["VarFileInfo"]; varFileInfo[ResourceUtil.USENGLISHLANGID] = 1300; string targetFilename = Path.Combine(Path.GetTempPath(), "test.dll"); File.Copy(filename, targetFilename, true); Console.WriteLine(targetFilename); versionResource.SaveTo(targetFilename); VersionResource newVersionResource = new VersionResource(); newVersionResource.Language = (ushort)language; newVersionResource.LoadFrom(targetFilename); DumpResource.Dump(versionResource); AssertOneVersionResource(targetFilename); Assert.AreEqual(newVersionResource.FileVersion, versionResource.FileVersion); Assert.AreEqual(newVersionResource.ProductVersion, versionResource.ProductVersion); Assert.AreEqual(newVersionResource.FileFlags, versionResource.FileFlags); StringFileInfo testedStringFileInfo = (StringFileInfo)newVersionResource["StringFileInfo"]; foreach (KeyValuePair<string, StringTableEntry> stringResource in testedStringFileInfo.Default.Strings) { Console.WriteLine("{0} = {1}", stringResource.Value.Key, stringResource.Value.StringValue); Assert.AreEqual(stringResource.Value.Value, stringFileInfo[stringResource.Key]); } VarFileInfo newVarFileInfo = (VarFileInfo)newVersionResource["VarFileInfo"]; foreach (KeyValuePair<UInt16, UInt16> varResource in newVarFileInfo.Default.Languages) { Console.WriteLine("{0} = {1}", varResource.Key, varResource.Value); Assert.AreEqual(varResource.Value, varFileInfo[varResource.Key]); } } [TestCaseSource("TestAssemblies")] public void TestDeleteVersionResource(string binaryName, int language) { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\" + binaryName); Assert.IsTrue(File.Exists(filename)); string targetFilename = Path.Combine(Path.GetTempPath(), "testDeleteVersionResource.dll"); File.Copy(filename, targetFilename, true); Console.WriteLine(targetFilename); VersionResource versionResource = new VersionResource(); versionResource.Language = (ushort)language; versionResource.LoadFrom(targetFilename); Console.WriteLine("Name: {0}", versionResource.Name); Console.WriteLine("Type: {0}", versionResource.Type); Console.WriteLine("Language: {0}", versionResource.Language); versionResource.DeleteFrom(targetFilename); try { versionResource.LoadFrom(targetFilename); Assert.Fail("Expected that the deleted resource cannot be found"); } catch (Win32Exception ex) { // expected exception Console.WriteLine("Expected exception: {0}", ex.Message); } AssertNoVersionResource(targetFilename); using (ResourceInfo ri = new ResourceInfo()) { ri.Load(targetFilename); DumpResource.Dump(ri); } } [TestCaseSource("TestAssemblies")] public void TestDeepCopyBytes(string binaryName, int language) { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\" + binaryName); Assert.IsTrue(File.Exists(filename)); VersionResource existingVersionResource = new VersionResource(); existingVersionResource.Language = (ushort)language; Console.WriteLine("Loading {0}", filename); existingVersionResource.LoadFrom(filename); DumpResource.Dump(existingVersionResource); VersionResource versionResource = new VersionResource(); versionResource.FileVersion = existingVersionResource.FileVersion; versionResource.ProductVersion = existingVersionResource.ProductVersion; StringFileInfo existingVersionResourceStringFileInfo = (StringFileInfo)existingVersionResource["StringFileInfo"]; VarFileInfo existingVersionResourceVarFileInfo = (VarFileInfo)existingVersionResource["VarFileInfo"]; // copy string resources, data only StringFileInfo stringFileInfo = new StringFileInfo(); { Dictionary<string, StringTable>.Enumerator enumerator = existingVersionResourceStringFileInfo.Strings.GetEnumerator(); while (enumerator.MoveNext()) { StringTable stringTable = new StringTable(enumerator.Current.Key); stringFileInfo.Strings.Add(enumerator.Current.Key, stringTable); Dictionary<string, StringTableEntry>.Enumerator resourceEnumerator = enumerator.Current.Value.Strings.GetEnumerator(); while (resourceEnumerator.MoveNext()) { StringTableEntry stringResource = new StringTableEntry(resourceEnumerator.Current.Key); stringResource.Value = resourceEnumerator.Current.Value.Value; stringTable.Strings.Add(resourceEnumerator.Current.Key, stringResource); } } } // copy var resources, data only VarFileInfo varFileInfo = new VarFileInfo(); { Dictionary<string, VarTable>.Enumerator enumerator = existingVersionResourceVarFileInfo.Vars.GetEnumerator(); while (enumerator.MoveNext()) { VarTable varTable = new VarTable(enumerator.Current.Key); varFileInfo.Vars.Add(enumerator.Current.Key, varTable); Dictionary<UInt16, UInt16>.Enumerator translationEnumerator = enumerator.Current.Value.Languages.GetEnumerator(); while (translationEnumerator.MoveNext()) { varTable.Languages.Add(translationEnumerator.Current.Key, translationEnumerator.Current.Value); } } } bool firstResourceIsStringFileInfo = existingVersionResource[0] == existingVersionResourceStringFileInfo; if (firstResourceIsStringFileInfo) { versionResource["StringFileInfo"] = stringFileInfo; versionResource["VarFileInfo"] = varFileInfo; } else { versionResource["VarFileInfo"] = varFileInfo; versionResource["StringFileInfo"] = stringFileInfo; } ByteUtils.CompareBytes(existingVersionResource.WriteAndGetBytes(), versionResource.WriteAndGetBytes()); } [TestCaseSource("TestAssemblies")] public void TestDeleteDeepCopyAndSaveVersionResource(string binaryName, int language) { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\" + binaryName); Assert.IsTrue(File.Exists(filename)); string targetFilename = Path.Combine(Path.GetTempPath(), binaryName); File.Copy(filename, targetFilename, true); Console.WriteLine(targetFilename); VersionResource existingVersionResource = new VersionResource(); existingVersionResource.Language = (ushort)language; existingVersionResource.LoadFrom(targetFilename); DumpResource.Dump(existingVersionResource); existingVersionResource.DeleteFrom(targetFilename); VersionResource versionResource = new VersionResource(); versionResource.FileVersion = existingVersionResource.FileVersion; versionResource.ProductVersion = existingVersionResource.ProductVersion; StringFileInfo existingVersionResourceStringFileInfo = (StringFileInfo)existingVersionResource["StringFileInfo"]; VarFileInfo existingVersionResourceVarFileInfo = (VarFileInfo)existingVersionResource["VarFileInfo"]; // copy string resources, data only StringFileInfo stringFileInfo = new StringFileInfo(); versionResource["StringFileInfo"] = stringFileInfo; { Dictionary<string, StringTable>.Enumerator enumerator = existingVersionResourceStringFileInfo.Strings.GetEnumerator(); while (enumerator.MoveNext()) { StringTable stringTable = new StringTable(enumerator.Current.Key); stringFileInfo.Strings.Add(enumerator.Current.Key, stringTable); Dictionary<string, StringTableEntry>.Enumerator resourceEnumerator = enumerator.Current.Value.Strings.GetEnumerator(); while (resourceEnumerator.MoveNext()) { StringTableEntry stringResource = new StringTableEntry(resourceEnumerator.Current.Key); stringResource.Value = resourceEnumerator.Current.Value.Value; stringTable.Strings.Add(resourceEnumerator.Current.Key, stringResource); } } } // copy var resources, data only VarFileInfo varFileInfo = new VarFileInfo(); versionResource["VarFileInfo"] = varFileInfo; { Dictionary<string, VarTable>.Enumerator enumerator = existingVersionResourceVarFileInfo.Vars.GetEnumerator(); while (enumerator.MoveNext()) { VarTable varTable = new VarTable(enumerator.Current.Key); varFileInfo.Vars.Add(enumerator.Current.Key, varTable); Dictionary<UInt16, UInt16>.Enumerator translationEnumerator = enumerator.Current.Value.Languages.GetEnumerator(); while (translationEnumerator.MoveNext()) { varTable.Languages.Add(translationEnumerator.Current.Key, translationEnumerator.Current.Value); } } } versionResource.SaveTo(targetFilename); Console.WriteLine("Reloading {0}", targetFilename); VersionResource newVersionResource = new VersionResource(); newVersionResource.LoadFrom(targetFilename); DumpResource.Dump(newVersionResource); AssertOneVersionResource(targetFilename); Assert.AreEqual(newVersionResource.FileVersion, versionResource.FileVersion); Assert.AreEqual(newVersionResource.ProductVersion, versionResource.ProductVersion); StringFileInfo testedStringFileInfo = (StringFileInfo)newVersionResource["StringFileInfo"]; foreach (KeyValuePair<string, StringTableEntry> stringResource in testedStringFileInfo.Default.Strings) { Assert.AreEqual(stringResource.Value.Value, stringFileInfo[stringResource.Key]); } VarFileInfo newVarFileInfo = (VarFileInfo)newVersionResource["VarFileInfo"]; foreach (KeyValuePair<UInt16, UInt16> varResource in newVarFileInfo.Default.Languages) { Assert.AreEqual(varResource.Value, varFileInfo[varResource.Key]); } } [TestCaseSource("TestAssemblies")] public void TestDeleteAndSaveVersionResource(string binaryName, int language) { Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string filename = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\" + binaryName); Assert.IsTrue(File.Exists(filename)); string targetFilename = Path.Combine(Path.GetTempPath(), "testDeleteAndSaveVersionResource.dll"); File.Copy(filename, targetFilename, true); Console.WriteLine(targetFilename); VersionResource existingVersionResource = new VersionResource(); existingVersionResource.Language = (ushort)language; existingVersionResource.DeleteFrom(targetFilename); VersionResource versionResource = new VersionResource(); versionResource.FileVersion = "1.2.3.4"; versionResource.ProductVersion = "4.5.6.7"; StringFileInfo stringFileInfo = new StringFileInfo(); versionResource[stringFileInfo.Key] = stringFileInfo; StringTable stringFileInfoStrings = new StringTable(); // "040904b0" stringFileInfoStrings.LanguageID = (ushort)language; stringFileInfoStrings.CodePage = 1200; Assert.AreEqual(language, stringFileInfoStrings.LanguageID); Assert.AreEqual(1200, stringFileInfoStrings.CodePage); stringFileInfo.Strings.Add(stringFileInfoStrings.Key, stringFileInfoStrings); stringFileInfoStrings["ProductName"] = "ResourceLib"; stringFileInfoStrings["FileDescription"] = "File updated by ResourceLib\0"; stringFileInfoStrings["CompanyName"] = "Vestris Inc."; stringFileInfoStrings["LegalCopyright"] = "All Rights Reserved\0"; stringFileInfoStrings["EmptyValue"] = ""; stringFileInfoStrings["Comments"] = string.Format("{0}\0", Guid.NewGuid()); stringFileInfoStrings["ProductVersion"] = string.Format("{0}\0", versionResource.ProductVersion); VarFileInfo varFileInfo = new VarFileInfo(); versionResource[varFileInfo.Key] = varFileInfo; VarTable varFileInfoTranslation = new VarTable("Translation"); varFileInfo.Vars.Add(varFileInfoTranslation.Key, varFileInfoTranslation); varFileInfoTranslation[ResourceUtil.USENGLISHLANGID] = 1300; versionResource.SaveTo(targetFilename); Console.WriteLine("Reloading {0}", targetFilename); VersionResource newVersionResource = new VersionResource(); newVersionResource.LoadFrom(targetFilename); DumpResource.Dump(newVersionResource); AssertOneVersionResource(targetFilename); Assert.AreEqual(newVersionResource.FileVersion, versionResource.FileVersion); Assert.AreEqual(newVersionResource.ProductVersion, versionResource.ProductVersion); } [Test] public void TestLoadNeutralDeleteEnglishResource() { // the 6to4svc.dll has an English version info strings resource that is loaded via netural VersionResource vr = new VersionResource(); string testDll = Path.Combine(Path.GetTempPath(), "testLoadNeutralDeleteEnglishResource.dll"); Console.WriteLine(testDll); Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string dll = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\6to4svc.dll"); File.Copy(dll, testDll, true); vr.LoadFrom(testDll); Assert.AreEqual(1033, vr.Language); vr.DeleteFrom(testDll); } [Test] public void TestLoadDeleteGreekResource() { // the 6to4svcgreek.dll has a Greek version info strings resource VersionResource vr = new VersionResource(); vr.Language = 1032; string testDll = Path.Combine(Path.GetTempPath(), "testLoadDeleteGreekResource.dll"); Console.WriteLine(testDll); Uri uri = new Uri(Assembly.GetExecutingAssembly().CodeBase); string dll = Path.Combine(Path.GetDirectoryName(HttpUtility.UrlDecode(uri.AbsolutePath)), "Binaries\\6to4svcgreek.dll"); File.Copy(dll, testDll, true); vr.LoadFrom(testDll); DumpResource.Dump(vr); Assert.AreEqual(1032, vr.Language); vr.DeleteFrom(testDll); } [Test] public void TestDoubleNullTerminator() { StringTableEntry sr = new StringTableEntry("dummy"); string guid = Guid.NewGuid().ToString(); sr.Value = guid; Assert.AreEqual(guid + '\0', sr.Value); Assert.AreEqual(guid, sr.StringValue); Assert.AreEqual(guid.Length + 1, sr.Header.wValueLength); sr.Value = guid + '\0'; Assert.AreEqual(guid + '\0', sr.Value); Assert.AreEqual(guid, sr.StringValue); Assert.AreEqual(guid.Length + 1, sr.Header.wValueLength); sr.Value = guid + "\0\0"; Assert.AreEqual(guid + "\0\0", sr.Value); Assert.AreEqual(guid + '\0', sr.StringValue); Assert.AreEqual(guid.Length + 2, sr.Header.wValueLength); sr.Value = '\0' + guid; Assert.AreEqual('\0' + guid + '\0', sr.Value); Assert.AreEqual('\0' + guid, sr.StringValue); Assert.AreEqual(guid.Length + 2, sr.Header.wValueLength); } #region Helper methods private static void AssertOneVersionResource(string fileName) { Assert.AreEqual( 1, GetOccurrencesOf("StringFileInfo", fileName), "More than one StringFileInfo block found."); Assert.AreEqual( 1, GetOccurrencesOf("VarFileInfo", fileName), "More than one VarFileInfo block found."); } private static void AssertNoVersionResource(string fileName) { Assert.AreEqual( 0, GetOccurrencesOf("StringFileInfo", fileName), "StringFileInfo block found."); Assert.AreEqual( 0, GetOccurrencesOf("VarFileInfo", fileName), "VarFileInfo block found."); } private static int GetOccurrencesOf(string text, string fileName) { byte[] contentData = File.ReadAllBytes(fileName); var chars = new char[contentData.Length / sizeof(char)]; Buffer.BlockCopy(contentData, 0, chars, 0, contentData.Length); var content = new string(chars); int occurrences = 0; int index = -1; while ((index = content.IndexOf(text, index + 1, StringComparison.InvariantCulture)) != -1) { occurrences++; } return occurrences; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Dynamic.Utils; namespace System.Linq.Expressions { /// <summary> /// Emits or clears a sequence point for debug information. /// /// This allows the debugger to highlight the correct source code when /// debugging. /// </summary> [DebuggerTypeProxy(typeof(Expression.DebugInfoExpressionProxy))] public class DebugInfoExpression : Expression { private readonly SymbolDocumentInfo _document; internal DebugInfoExpression(SymbolDocumentInfo document) { _document = document; } /// <summary> /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public sealed override Type Type { get { return typeof(void); } } /// <summary> /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType { get { return ExpressionType.DebugInfo; } } /// <summary> /// Gets the start line of this <see cref="DebugInfoExpression" />. /// </summary> [ExcludeFromCodeCoverage] // Unreachable public virtual int StartLine { get { throw ContractUtils.Unreachable; } } /// <summary> /// Gets the start column of this <see cref="DebugInfoExpression" />. /// </summary> [ExcludeFromCodeCoverage] // Unreachable public virtual int StartColumn { get { throw ContractUtils.Unreachable; } } /// <summary> /// Gets the end line of this <see cref="DebugInfoExpression" />. /// </summary> [ExcludeFromCodeCoverage] // Unreachable public virtual int EndLine { get { throw ContractUtils.Unreachable; } } /// <summary> /// Gets the end column of this <see cref="DebugInfoExpression" />. /// </summary> [ExcludeFromCodeCoverage] // Unreachable public virtual int EndColumn { get { throw ContractUtils.Unreachable; } } /// <summary> /// Gets the <see cref="SymbolDocumentInfo"/> that represents the source file. /// </summary> public SymbolDocumentInfo Document { get { return _document; } } /// <summary> /// Gets the value to indicate if the <see cref="DebugInfoExpression"/> is for clearing a sequence point. /// </summary> [ExcludeFromCodeCoverage] // Unreachable public virtual bool IsClear { get { throw ContractUtils.Unreachable; } } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitDebugInfo(this); } } #region Specialized subclasses internal sealed class SpanDebugInfoExpression : DebugInfoExpression { private readonly int _startLine, _startColumn, _endLine, _endColumn; internal SpanDebugInfoExpression(SymbolDocumentInfo document, int startLine, int startColumn, int endLine, int endColumn) : base(document) { _startLine = startLine; _startColumn = startColumn; _endLine = endLine; _endColumn = endColumn; } public override int StartLine { get { return _startLine; } } public override int StartColumn { get { return _startColumn; } } public override int EndLine { get { return _endLine; } } public override int EndColumn { get { return _endColumn; } } public override bool IsClear { get { return false; } } protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitDebugInfo(this); } } internal sealed class ClearDebugInfoExpression : DebugInfoExpression { internal ClearDebugInfoExpression(SymbolDocumentInfo document) : base(document) { } public override bool IsClear { get { return true; } } public override int StartLine { get { return 0xfeefee; } } public override int StartColumn { get { return 0; } } public override int EndLine { get { return 0xfeefee; } } public override int EndColumn { get { return 0; } } } #endregion public partial class Expression { /// <summary> /// Creates a <see cref="DebugInfoExpression"/> with the specified span. /// </summary> /// <param name="document">The <see cref="SymbolDocumentInfo"/> that represents the source file.</param> /// <param name="startLine">The start line of this <see cref="DebugInfoExpression" />. Must be greater than 0.</param> /// <param name="startColumn">The start column of this <see cref="DebugInfoExpression" />. Must be greater than 0.</param> /// <param name="endLine">The end line of this <see cref="DebugInfoExpression" />. Must be greater or equal than the start line.</param> /// <param name="endColumn">The end column of this <see cref="DebugInfoExpression" />. If the end line is the same as the start line, it must be greater or equal than the start column. In any case, must be greater than 0.</param> /// <returns>An instance of <see cref="DebugInfoExpression"/>.</returns> public static DebugInfoExpression DebugInfo(SymbolDocumentInfo document, int startLine, int startColumn, int endLine, int endColumn) { ContractUtils.RequiresNotNull(document, "document"); if (startLine == 0xfeefee && startColumn == 0 && endLine == 0xfeefee && endColumn == 0) { return new ClearDebugInfoExpression(document); } ValidateSpan(startLine, startColumn, endLine, endColumn); return new SpanDebugInfoExpression(document, startLine, startColumn, endLine, endColumn); } /// <summary> /// Creates a <see cref="DebugInfoExpression"/> for clearing a sequence point. /// </summary> /// <param name="document">The <see cref="SymbolDocumentInfo"/> that represents the source file.</param> /// <returns>An instance of <see cref="DebugInfoExpression"/> for clearning a sequence point.</returns> public static DebugInfoExpression ClearDebugInfo(SymbolDocumentInfo document) { ContractUtils.RequiresNotNull(document, "document"); return new ClearDebugInfoExpression(document); } private static void ValidateSpan(int startLine, int startColumn, int endLine, int endColumn) { if (startLine < 1) { throw Error.OutOfRange("startLine", 1); } if (startColumn < 1) { throw Error.OutOfRange("startColumn", 1); } if (endLine < 1) { throw Error.OutOfRange("endLine", 1); } if (endColumn < 1) { throw Error.OutOfRange("endColumn", 1); } if (startLine > endLine) { throw Error.StartEndMustBeOrdered(); } if (startLine == endLine && startColumn > endColumn) { throw Error.StartEndMustBeOrdered(); } } } }
// 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.Xml.Xsl.XsltOld { using System; using System.Collections; using System.Diagnostics; using System.Xml.XPath; using System.Xml.Xsl.XsltOld.Debugger; internal class DbgData { private VariableAction[] _variables; public XPathNavigator StyleSheet { get; } public DbgData(Compiler compiler) { DbgCompiler dbgCompiler = (DbgCompiler)compiler; StyleSheet = dbgCompiler.Input.Navigator.Clone(); _variables = dbgCompiler.LocalVariables; dbgCompiler.Debugger.OnInstructionCompile(this.StyleSheet); } internal void ReplaceVariables(VariableAction[] vars) { _variables = vars; } // static Empty: private static DbgData s_nullDbgData = new DbgData(); private DbgData() { StyleSheet = null; _variables = Array.Empty<VariableAction>(); } public static DbgData Empty { get { return s_nullDbgData; } } } internal class DbgCompiler : Compiler { private IXsltDebugger _debugger; public DbgCompiler(IXsltDebugger debugger) { _debugger = debugger; } public override IXsltDebugger Debugger { get { return _debugger; } } // Variables // // In XsltDebugger we have to know variables that are visible from each action. // We keepping two different sets of wariables because global and local variables have different rules of visibility. // Globals: All global variables are visible avryware (uncalucaled will have null value), // Duplicated globals from different stilesheets are replaced (by import presidence) // Locals: Visible only in scope and after it was defined. // No duplicates posible. private ArrayList _globalVars = new ArrayList(); private ArrayList _localVars = new ArrayList(); private VariableAction[] _globalVarsCache, _localVarsCache; public virtual VariableAction[] GlobalVariables { get { Debug.Assert(this.Debugger != null); if (_globalVarsCache == null) { _globalVarsCache = (VariableAction[])_globalVars.ToArray(typeof(VariableAction)); } return _globalVarsCache; } } public virtual VariableAction[] LocalVariables { get { Debug.Assert(this.Debugger != null); if (_localVarsCache == null) { _localVarsCache = (VariableAction[])_localVars.ToArray(typeof(VariableAction)); } return _localVarsCache; } } private void DefineVariable(VariableAction variable) { Debug.Assert(this.Debugger != null); if (variable.IsGlobal) { for (int i = 0; i < _globalVars.Count; i++) { VariableAction oldVar = (VariableAction)_globalVars[i]; if (oldVar.Name == variable.Name) { // Duplicate var definition if (variable.Stylesheetid < oldVar.Stylesheetid) { Debug.Assert(variable.VarKey != -1, "Variable was already placed and it should replace prev var."); _globalVars[i] = variable; _globalVarsCache = null; } return; } } _globalVars.Add(variable); _globalVarsCache = null; } else { // local variables never conflict _localVars.Add(variable); _localVarsCache = null; } } private void UnDefineVariables(int count) { Debug.Assert(0 <= count, "This scope can't have more variables than we have in total"); Debug.Assert(count <= _localVars.Count, "This scope can't have more variables than we have in total"); if (count != 0) { _localVars.RemoveRange(_localVars.Count - count, count); _localVarsCache = null; } } internal override void PopScope() { this.UnDefineVariables(this.ScopeManager.CurrentScope.GetVeriablesCount()); base.PopScope(); } // ---------------- Actions: --------------- public override ApplyImportsAction CreateApplyImportsAction() { ApplyImportsAction action = new ApplyImportsActionDbg(); action.Compile(this); return action; } public override ApplyTemplatesAction CreateApplyTemplatesAction() { ApplyTemplatesAction action = new ApplyTemplatesActionDbg(); action.Compile(this); return action; } public override AttributeAction CreateAttributeAction() { AttributeAction action = new AttributeActionDbg(); action.Compile(this); return action; } public override AttributeSetAction CreateAttributeSetAction() { AttributeSetAction action = new AttributeSetActionDbg(); action.Compile(this); return action; } public override CallTemplateAction CreateCallTemplateAction() { CallTemplateAction action = new CallTemplateActionDbg(); action.Compile(this); return action; } public override ChooseAction CreateChooseAction() {//!!! don't need to be here ChooseAction action = new ChooseAction(); action.Compile(this); return action; } public override CommentAction CreateCommentAction() { CommentAction action = new CommentActionDbg(); action.Compile(this); return action; } public override CopyAction CreateCopyAction() { CopyAction action = new CopyActionDbg(); action.Compile(this); return action; } public override CopyOfAction CreateCopyOfAction() { CopyOfAction action = new CopyOfActionDbg(); action.Compile(this); return action; } public override ElementAction CreateElementAction() { ElementAction action = new ElementActionDbg(); action.Compile(this); return action; } public override ForEachAction CreateForEachAction() { ForEachAction action = new ForEachActionDbg(); action.Compile(this); return action; } public override IfAction CreateIfAction(IfAction.ConditionType type) { IfAction action = new IfActionDbg(type); action.Compile(this); return action; } public override MessageAction CreateMessageAction() { MessageAction action = new MessageActionDbg(); action.Compile(this); return action; } public override NewInstructionAction CreateNewInstructionAction() { NewInstructionAction action = new NewInstructionActionDbg(); action.Compile(this); return action; } public override NumberAction CreateNumberAction() { NumberAction action = new NumberActionDbg(); action.Compile(this); return action; } public override ProcessingInstructionAction CreateProcessingInstructionAction() { ProcessingInstructionAction action = new ProcessingInstructionActionDbg(); action.Compile(this); return action; } public override void CreateRootAction() { this.RootAction = new RootActionDbg(); this.RootAction.Compile(this); } public override SortAction CreateSortAction() { SortAction action = new SortActionDbg(); action.Compile(this); return action; } public override TemplateAction CreateTemplateAction() { TemplateAction action = new TemplateActionDbg(); action.Compile(this); return action; } public override TemplateAction CreateSingleTemplateAction() { TemplateAction action = new TemplateActionDbg(); action.CompileSingle(this); return action; } public override TextAction CreateTextAction() { TextAction action = new TextActionDbg(); action.Compile(this); return action; } public override UseAttributeSetsAction CreateUseAttributeSetsAction() { UseAttributeSetsAction action = new UseAttributeSetsActionDbg(); action.Compile(this); return action; } public override ValueOfAction CreateValueOfAction() { ValueOfAction action = new ValueOfActionDbg(); action.Compile(this); return action; } public override VariableAction CreateVariableAction(VariableType type) { VariableAction action = new VariableActionDbg(type); action.Compile(this); return action; } public override WithParamAction CreateWithParamAction() { WithParamAction action = new WithParamActionDbg(); action.Compile(this); return action; } // ---------------- Events: --------------- public override BeginEvent CreateBeginEvent() { return new BeginEventDbg(this); } public override TextEvent CreateTextEvent() { return new TextEventDbg(this); } // Debugger enabled implemetation of most compiled actions private class ApplyImportsActionDbg : ApplyImportsAction { internal override void Compile(Compiler compiler) { base.Compile(compiler); } internal override void Execute(Processor processor, ActionFrame frame) { if (frame.State == Initialized) { processor.OnInstructionExecute(); } base.Execute(processor, frame); } } private class ApplyTemplatesActionDbg : ApplyTemplatesAction { internal override void Compile(Compiler compiler) { base.Compile(compiler); } internal override void Execute(Processor processor, ActionFrame frame) { if (frame.State == Initialized) { processor.OnInstructionExecute(); } base.Execute(processor, frame); } } private class AttributeActionDbg : AttributeAction { internal override void Compile(Compiler compiler) { base.Compile(compiler); } internal override void Execute(Processor processor, ActionFrame frame) { if (frame.State == Initialized) { processor.OnInstructionExecute(); } base.Execute(processor, frame); } } private class AttributeSetActionDbg : AttributeSetAction { internal override void Compile(Compiler compiler) { base.Compile(compiler); } internal override void Execute(Processor processor, ActionFrame frame) { if (frame.State == Initialized) { processor.OnInstructionExecute(); } base.Execute(processor, frame); } } private class CallTemplateActionDbg : CallTemplateAction { internal override void Compile(Compiler compiler) { base.Compile(compiler); } internal override void Execute(Processor processor, ActionFrame frame) { if (frame.State == Initialized) { processor.OnInstructionExecute(); } base.Execute(processor, frame); } } private class CommentActionDbg : CommentAction { internal override void Compile(Compiler compiler) { base.Compile(compiler); } internal override void Execute(Processor processor, ActionFrame frame) { if (frame.State == Initialized) { processor.OnInstructionExecute(); } base.Execute(processor, frame); } } private class CopyActionDbg : CopyAction { internal override void Compile(Compiler compiler) { base.Compile(compiler); } internal override void Execute(Processor processor, ActionFrame frame) { if (frame.State == Initialized) { processor.OnInstructionExecute(); } base.Execute(processor, frame); } } private class CopyOfActionDbg : CopyOfAction { internal override void Compile(Compiler compiler) { base.Compile(compiler); } internal override void Execute(Processor processor, ActionFrame frame) { if (frame.State == Initialized) { processor.OnInstructionExecute(); } base.Execute(processor, frame); } } private class ElementActionDbg : ElementAction { internal override void Compile(Compiler compiler) { base.Compile(compiler); } internal override void Execute(Processor processor, ActionFrame frame) { if (frame.State == Initialized) { processor.OnInstructionExecute(); } base.Execute(processor, frame); } } private class ForEachActionDbg : ForEachAction { internal override void Compile(Compiler compiler) { base.Compile(compiler); } internal override void Execute(Processor processor, ActionFrame frame) { if (frame.State == Initialized) { processor.PushDebuggerStack(); processor.OnInstructionExecute(); } base.Execute(processor, frame); if (frame.State == Finished) { processor.PopDebuggerStack(); } } } private class IfActionDbg : IfAction { internal IfActionDbg(ConditionType type) : base(type) { } internal override void Compile(Compiler compiler) { base.Compile(compiler); } internal override void Execute(Processor processor, ActionFrame frame) { if (frame.State == Initialized) { processor.OnInstructionExecute(); } base.Execute(processor, frame); } } private class MessageActionDbg : MessageAction { internal override void Compile(Compiler compiler) { base.Compile(compiler); } internal override void Execute(Processor processor, ActionFrame frame) { if (frame.State == Initialized) { processor.OnInstructionExecute(); } base.Execute(processor, frame); } } private class NewInstructionActionDbg : NewInstructionAction { internal override void Compile(Compiler compiler) { base.Compile(compiler); } internal override void Execute(Processor processor, ActionFrame frame) { if (frame.State == Initialized) { processor.OnInstructionExecute(); } base.Execute(processor, frame); } } private class NumberActionDbg : NumberAction { internal override void Compile(Compiler compiler) { base.Compile(compiler); } internal override void Execute(Processor processor, ActionFrame frame) { if (frame.State == Initialized) { processor.OnInstructionExecute(); } base.Execute(processor, frame); } } private class ProcessingInstructionActionDbg : ProcessingInstructionAction { internal override void Compile(Compiler compiler) { base.Compile(compiler); } internal override void Execute(Processor processor, ActionFrame frame) { if (frame.State == Initialized) { processor.OnInstructionExecute(); } base.Execute(processor, frame); } } private class RootActionDbg : RootAction { private DbgData _dbgData; // SxS: This method does not take any resource name and does not expose any resources to the caller. // It's OK to suppress the SxS warning. internal override void Compile(Compiler compiler) { _dbgData = new DbgData(compiler); base.Compile(compiler); Debug.Assert(compiler.Debugger != null); string builtIn = compiler.Debugger.GetBuiltInTemplatesUri(); if (builtIn != null && builtIn.Length != 0) { compiler.AllowBuiltInMode = true; builtInSheet = compiler.RootAction.CompileImport(compiler, compiler.ResolveUri(builtIn), int.MaxValue); compiler.AllowBuiltInMode = false; } _dbgData.ReplaceVariables(((DbgCompiler)compiler).GlobalVariables); } internal override void Execute(Processor processor, ActionFrame frame) { if (frame.State == Initialized) { processor.PushDebuggerStack(); processor.OnInstructionExecute(); processor.PushDebuggerStack(); } base.Execute(processor, frame); if (frame.State == Finished) { processor.PopDebuggerStack(); processor.PopDebuggerStack(); } } } private class SortActionDbg : SortAction { internal override void Compile(Compiler compiler) { base.Compile(compiler); } internal override void Execute(Processor processor, ActionFrame frame) { if (frame.State == Initialized) { processor.OnInstructionExecute(); } base.Execute(processor, frame); } } private class TemplateActionDbg : TemplateAction { internal override void Compile(Compiler compiler) { base.Compile(compiler); } internal override void Execute(Processor processor, ActionFrame frame) { if (frame.State == Initialized) { processor.PushDebuggerStack(); processor.OnInstructionExecute(); } base.Execute(processor, frame); if (frame.State == Finished) { processor.PopDebuggerStack(); } } } private class TextActionDbg : TextAction { internal override void Compile(Compiler compiler) { base.Compile(compiler); } internal override void Execute(Processor processor, ActionFrame frame) { if (frame.State == Initialized) { processor.OnInstructionExecute(); } base.Execute(processor, frame); } } private class UseAttributeSetsActionDbg : UseAttributeSetsAction { internal override void Compile(Compiler compiler) { base.Compile(compiler); } internal override void Execute(Processor processor, ActionFrame frame) { if (frame.State == Initialized) { processor.OnInstructionExecute(); } base.Execute(processor, frame); } } private class ValueOfActionDbg : ValueOfAction { internal override void Compile(Compiler compiler) { base.Compile(compiler); } internal override void Execute(Processor processor, ActionFrame frame) { if (frame.State == Initialized) { processor.OnInstructionExecute(); } base.Execute(processor, frame); } } private class VariableActionDbg : VariableAction { internal VariableActionDbg(VariableType type) : base(type) { } private DbgData _dbgData; internal override void Compile(Compiler compiler) { _dbgData = new DbgData(compiler); base.Compile(compiler); ((DbgCompiler)compiler).DefineVariable(this); } internal override void Execute(Processor processor, ActionFrame frame) { if (frame.State == Initialized) { processor.OnInstructionExecute(); } base.Execute(processor, frame); } } private class WithParamActionDbg : WithParamAction { internal override void Compile(Compiler compiler) { base.Compile(compiler); } internal override void Execute(Processor processor, ActionFrame frame) { if (frame.State == Initialized) { processor.OnInstructionExecute(); } base.Execute(processor, frame); } } // ---------------- Events: --------------- private class BeginEventDbg : BeginEvent { private DbgData _dbgData; internal override DbgData DbgData { get { return _dbgData; } } public BeginEventDbg(Compiler compiler) : base(compiler) { _dbgData = new DbgData(compiler); } public override bool Output(Processor processor, ActionFrame frame) { this.OnInstructionExecute(processor); return base.Output(processor, frame); } } private class TextEventDbg : TextEvent { private DbgData _dbgData; internal override DbgData DbgData { get { return _dbgData; } } public TextEventDbg(Compiler compiler) : base(compiler) { _dbgData = new DbgData(compiler); } public override bool Output(Processor processor, ActionFrame frame) { this.OnInstructionExecute(processor); return base.Output(processor, frame); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.ComponentModel; using System.Diagnostics.Contracts; using System.ServiceModel.Channels; using System.Xml; namespace System.ServiceModel { public class NetTcpBinding : Binding { // private BindingElements private TcpTransportBindingElement _transport; private BinaryMessageEncodingBindingElement _encoding; private long _maxBufferPoolSize; private NetTcpSecurity _security = new NetTcpSecurity(); public NetTcpBinding() { Initialize(); } public NetTcpBinding(SecurityMode securityMode) : this() { _security.Mode = securityMode; } public NetTcpBinding(string configurationName) : this() { if (!String.IsNullOrEmpty(configurationName)) { throw ExceptionHelper.PlatformNotSupported(); } } private NetTcpBinding(TcpTransportBindingElement transport, BinaryMessageEncodingBindingElement encoding, NetTcpSecurity security) : this() { _security = security; } [DefaultValue(ConnectionOrientedTransportDefaults.TransferMode)] public TransferMode TransferMode { get { return _transport.TransferMode; } set { _transport.TransferMode = value; } } [DefaultValue(TransportDefaults.MaxBufferPoolSize)] public long MaxBufferPoolSize { get { return _maxBufferPoolSize; } set { _maxBufferPoolSize = value; } } [DefaultValue(TransportDefaults.MaxBufferSize)] public int MaxBufferSize { get { return _transport.MaxBufferSize; } set { _transport.MaxBufferSize = value; } } [DefaultValue(TransportDefaults.MaxReceivedMessageSize)] public long MaxReceivedMessageSize { get { return _transport.MaxReceivedMessageSize; } set { _transport.MaxReceivedMessageSize = value; } } public XmlDictionaryReaderQuotas ReaderQuotas { get { return _encoding.ReaderQuotas; } set { if (value == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); value.CopyTo(_encoding.ReaderQuotas); } } public override string Scheme { get { return _transport.Scheme; } } public EnvelopeVersion EnvelopeVersion { get { return EnvelopeVersion.Soap12; } } public NetTcpSecurity Security { get { return _security; } set { if (value == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); _security = value; } } private void Initialize() { _transport = new TcpTransportBindingElement(); _encoding = new BinaryMessageEncodingBindingElement(); // NetNative and CoreCLR initialize to what TransportBindingElement does in the desktop // This property is not available in shipped contracts _maxBufferPoolSize = TransportDefaults.MaxBufferPoolSize; } // check that properties of the HttpTransportBindingElement and // MessageEncodingBindingElement not exposed as properties on BasicHttpBinding // match default values of the binding elements private bool IsBindingElementsMatch(TcpTransportBindingElement transport, BinaryMessageEncodingBindingElement encoding) { if (!_transport.IsMatch(transport)) return false; if (!_encoding.IsMatch(encoding)) return false; return true; } private void CheckSettings() { #if FEATURE_NETNATIVE // In .NET Native, some settings for the binding security are not supported; this check is not necessary for CoreCLR NetTcpSecurity security = this.Security; if (security == null) { return; } SecurityMode mode = security.Mode; if (mode == SecurityMode.None) { return; } else if (mode == SecurityMode.Message) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.UnsupportedSecuritySetting, "Mode", mode))); } // Message.ClientCredentialType = Certificate, IssuedToken or Windows are not supported. if (mode == SecurityMode.TransportWithMessageCredential) { MessageSecurityOverTcp message = security.Message; if (message != null) { MessageCredentialType mct = message.ClientCredentialType; if ((mct == MessageCredentialType.Certificate) || (mct == MessageCredentialType.IssuedToken) || (mct == MessageCredentialType.Windows)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.UnsupportedSecuritySetting, "Message.ClientCredentialType", mct))); } } } // Transport.ClientCredentialType = Certificate is not supported. Contract.Assert((mode == SecurityMode.Transport) || (mode == SecurityMode.TransportWithMessageCredential), "Unexpected SecurityMode value: " + mode); TcpTransportSecurity transport = security.Transport; if ((transport != null) && (transport.ClientCredentialType == TcpClientCredentialType.Certificate)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.UnsupportedSecuritySetting, "Transport.ClientCredentialType", transport.ClientCredentialType))); } #endif // FEATURE_NETNATIVE } public override BindingElementCollection CreateBindingElements() { this.CheckSettings(); // return collection of BindingElements BindingElementCollection bindingElements = new BindingElementCollection(); // order of BindingElements is important // add security (*optional) SecurityBindingElement wsSecurity = CreateMessageSecurity(); if (wsSecurity != null) bindingElements.Add(wsSecurity); // add encoding bindingElements.Add(_encoding); // add transport security BindingElement transportSecurity = CreateTransportSecurity(); if (transportSecurity != null) { bindingElements.Add(transportSecurity); } // add transport (tcp) bindingElements.Add(_transport); return bindingElements.Clone(); } private BindingElement CreateTransportSecurity() { return _security.CreateTransportSecurity(); } private static UnifiedSecurityMode GetModeFromTransportSecurity(BindingElement transport) { return NetTcpSecurity.GetModeFromTransportSecurity(transport); } private static bool SetTransportSecurity(BindingElement transport, SecurityMode mode, TcpTransportSecurity transportSecurity) { return NetTcpSecurity.SetTransportSecurity(transport, mode, transportSecurity); } private SecurityBindingElement CreateMessageSecurity() { if (_security.Mode == SecurityMode.Message || _security.Mode == SecurityMode.TransportWithMessageCredential) { throw ExceptionHelper.PlatformNotSupported("NetTcpBinding.CreateMessageSecurity is not supported."); } else { return null; } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.HSSF.UserModel { using NPOI.HSSF.Record; using NPOI.HSSF.Record.CF; using NPOI.HSSF.Util; using NPOI.SS.UserModel; using System; /** * High level representation for Font Formatting component * of Conditional Formatting Settings * * @author Dmitriy Kumshayev * */ public class HSSFFontFormatting : IFontFormatting { private FontFormatting fontFormatting; private HSSFWorkbook workbook; public HSSFFontFormatting(CFRuleBase cfRuleRecord, HSSFWorkbook workbook) { this.fontFormatting = cfRuleRecord.FontFormatting; this.workbook = workbook; } protected FontFormatting GetFontFormattingBlock() { return fontFormatting; } /** * Get the type of base or subscript for the font * * @return base or subscript option */ public FontSuperScript EscapementType { get { return (FontSuperScript)fontFormatting.EscapementType; } set { switch (value) { case FontSuperScript.Sub: case FontSuperScript.Super: fontFormatting.EscapementType = value; fontFormatting.IsEscapementTypeModified = true; break; case FontSuperScript.None: fontFormatting.EscapementType = value; fontFormatting.IsEscapementTypeModified = false; break; } } } /** * @return font color index */ public short FontColorIndex { get { return fontFormatting.FontColorIndex; } set { fontFormatting.FontColorIndex=(value); } } public IColor FontColor { get { return workbook.GetCustomPalette().GetColor(FontColorIndex); } set { HSSFColor hcolor = HSSFColor.ToHSSFColor(value); if (hcolor == null) { fontFormatting.FontColorIndex = ((short)0); } else { fontFormatting.FontColorIndex = (hcolor.Indexed); } } } /** * Gets the height of the font in 1/20th point Units * * @return fontheight (in points/20); or -1 if not modified */ public int FontHeight { get { return fontFormatting.FontHeight; } set { fontFormatting.FontHeight=(value); } } /** * Get the font weight for this font (100-1000dec or 0x64-0x3e8). Default Is * 0x190 for normal and 0x2bc for bold * * @return bw - a number between 100-1000 for the fonts "boldness" */ public short FontWeight { get { return fontFormatting.FontWeight; } } /** * @return * @see org.apache.poi.hssf.record.cf.FontFormatting#GetRawRecord() */ protected byte[] GetRawRecord() { return fontFormatting.RawRecord; } /** * Get the type of Underlining for the font * * @return font Underlining type * * @see #U_NONE * @see #U_SINGLE * @see #U_DOUBLE * @see #U_SINGLE_ACCOUNTING * @see #U_DOUBLE_ACCOUNTING */ public FontUnderlineType UnderlineType { get { return (FontUnderlineType)fontFormatting.UnderlineType; } set { switch (value) { case FontUnderlineType.Single: case FontUnderlineType.Double: case FontUnderlineType.SingleAccounting: case FontUnderlineType.DoubleAccounting: fontFormatting.UnderlineType = value; IsUnderlineTypeModified = true; break; case FontUnderlineType.None: fontFormatting.UnderlineType = value; IsUnderlineTypeModified = false; break; } } } /** * Get whether the font weight Is Set to bold or not * * @return bold - whether the font Is bold or not */ public bool IsBold { get { return fontFormatting.IsFontWeightModified && fontFormatting.IsBold; } } /** * @return true if escapement type was modified from default */ public bool IsEscapementTypeModified { get{ return fontFormatting.IsEscapementTypeModified; } set { fontFormatting.IsEscapementTypeModified=value; } } /** * @return true if font cancellation was modified from default */ public bool IsFontCancellationModified { get{ return fontFormatting.IsFontCancellationModified; } set { fontFormatting.IsFontCancellationModified=(value); } } /** * @return true if font outline type was modified from default */ public bool IsFontOutlineModified { get { return fontFormatting.IsFontOutlineModified; } set { fontFormatting.IsFontOutlineModified=(value); } } /** * @return true if font shadow type was modified from default */ public bool IsFontShadowModified { get { return fontFormatting.IsFontShadowModified; } set { fontFormatting.IsFontShadowModified=value; } } /** * @return true if font style was modified from default */ public bool IsFontStyleModified { get { return fontFormatting.IsFontStyleModified; } set { fontFormatting.IsFontStyleModified=value; } } /** * @return true if font style was Set to <i>italic</i> */ public bool IsItalic { get { return fontFormatting.IsFontStyleModified && fontFormatting.IsItalic; } } /** * @return true if font outline Is on */ public bool IsOutlineOn { get { return fontFormatting.IsFontOutlineModified && fontFormatting.IsOutlineOn; } set { fontFormatting.IsOutlineOn=value; fontFormatting.IsFontOutlineModified=value; } } /** * @return true if font shadow Is on */ public bool IsShadowOn { get{return fontFormatting.IsFontOutlineModified && fontFormatting.IsShadowOn;} set { fontFormatting.IsShadowOn=value; fontFormatting.IsFontShadowModified=value; } } /** * @return true if font strikeout Is on */ public bool IsStrikeout { get { return fontFormatting.IsFontCancellationModified && fontFormatting.IsStruckout; } set { fontFormatting.IsStruckout = (value); fontFormatting.IsFontCancellationModified = (value); } } /** * @return true if font Underline type was modified from default */ public bool IsUnderlineTypeModified { get{return fontFormatting.IsUnderlineTypeModified;} set { fontFormatting.IsUnderlineTypeModified=value; } } /** * @return true if font weight was modified from default */ public bool IsFontWeightModified { get{ return fontFormatting.IsFontWeightModified; } } /** * Set font style options. * * @param italic - if true, Set posture style to italic, otherwise to normal * @param bold- if true, Set font weight to bold, otherwise to normal */ public void SetFontStyle(bool italic, bool bold) { bool modified = italic || bold; fontFormatting.IsItalic=italic; fontFormatting.IsBold=bold; fontFormatting.IsFontStyleModified=modified; fontFormatting.IsFontWeightModified=modified; } /** * Set font style options to default values (non-italic, non-bold) */ public void ResetFontStyle() { SetFontStyle(false, false); } } }
//------------------------------------------------------------------------------ // <copyright file="PeerApplication.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Net.PeerToPeer.Collaboration { using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Runtime.InteropServices; using System.Text; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.ComponentModel; using System.Runtime.Serialization; using System.Security.Permissions; /// <summary> /// This class handles all the functionality and events associated with the Collaboration /// Peer Application /// </summary> [Serializable] public class PeerApplication : IDisposable, IEquatable<PeerApplication>, ISerializable { private const int c_16K = 16384; private Guid m_id; private byte[] m_data; private string m_description; private string m_path; private string m_commandLineArgs; private PeerScope m_peerScope; private ISynchronizeInvoke m_synchronizingObject; // // Initialize on first access of this class // // <SecurityKernel Critical="True" Ring="1"> // <ReferencesCritical Name="Method: CollaborationHelperFunctions.Initialize():System.Void" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] static PeerApplication() { CollaborationHelperFunctions.Initialize(); } public PeerApplication(){} public PeerApplication( Guid id, string description, byte[] data, string path, string commandLineArgs, PeerScope peerScope) { if ((data != null) && (data.Length > c_16K)) throw new ArgumentException(SR.GetString(SR.Collab_ApplicationDataSizeFailed), "data"); m_id = id; m_description = description; m_data = data; m_path = path; m_commandLineArgs = commandLineArgs; m_peerScope = peerScope; } /// <summary> /// Constructor to enable serialization /// </summary> [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] protected PeerApplication(SerializationInfo serializationInfo, StreamingContext streamingContext) { m_id = (Guid) serializationInfo.GetValue("_Id", typeof(Guid)); m_data = (byte []) serializationInfo.GetValue("_Data", typeof(byte[])); m_description = serializationInfo.GetString("_Description"); m_path = serializationInfo.GetString("_Path"); m_commandLineArgs = serializationInfo.GetString("_CommandLineArgs"); m_peerScope = (PeerScope) serializationInfo.GetInt32("_Scope"); } public Guid Id { get { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); return m_id; } set { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); m_id = value; } } public byte[] Data { get { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); return m_data; } set { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); if ((value != null) && (value.Length > c_16K)) throw new ArgumentException(SR.GetString(SR.Collab_ApplicationDataSizeFailed)); m_data = value; } } public string Description { get{ if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); return m_description; } set { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); m_description = value; } } public string Path { get { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); return m_path; } set { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); m_path = value; } } public string CommandLineArgs { get { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); return m_commandLineArgs; } set { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); m_commandLineArgs = value; } } public PeerScope PeerScope { get { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); return m_peerScope; } set { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); m_peerScope = value; } } /// <summary> /// Gets and set the object used to marshall event handlers calls for stand alone /// events /// </summary> [Browsable(false), DefaultValue(null), Description(SR.SynchronizingObject)] public ISynchronizeInvoke SynchronizingObject { get { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); return m_synchronizingObject; } set { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); m_synchronizingObject = value; } } private event EventHandler<ApplicationChangedEventArgs> m_applicationChanged; public event EventHandler<ApplicationChangedEventArgs> ApplicationChanged { // <SecurityKernel Critical="True" Ring="1"> // <ReferencesCritical Name="Method: AddApplicationChanged(EventHandler`1<System.Net.PeerToPeer.Collaboration.ApplicationChangedEventArgs>):Void" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] add { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); PeerCollaborationPermission.UnrestrictedPeerCollaborationPermission.Demand(); AddApplicationChanged(value); } // <SecurityKernel Critical="True" Ring="2"> // <ReferencesCritical Name="Method: RemoveApplicationChanged(EventHandler`1<System.Net.PeerToPeer.Collaboration.ApplicationChangedEventArgs>):Void" Ring="2" /> // </SecurityKernel> [System.Security.SecurityCritical] remove { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); PeerCollaborationPermission.UnrestrictedPeerCollaborationPermission.Demand(); RemoveApplicationChanged(value); } } #region Application changed event variables private object m_lockAppChangedEvent; private object LockAppChangedEvent { get{ if (m_lockAppChangedEvent == null){ object o = new object(); Interlocked.CompareExchange(ref m_lockAppChangedEvent, o, null); } return m_lockAppChangedEvent; } } private RegisteredWaitHandle m_regAppChangedWaitHandle; private AutoResetEvent m_appChangedEvent; private SafeCollabEvent m_safeAppChangedEvent; #endregion // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeCollabNativeMethods.PeerCollabRegisterEvent(Microsoft.Win32.SafeHandles.SafeWaitHandle,System.UInt32,System.Net.PeerToPeer.Collaboration.PEER_COLLAB_EVENT_REGISTRATION&,System.Net.PeerToPeer.Collaboration.SafeCollabEvent&):System.Int32" /> // <SatisfiesLinkDemand Name="GCHandle.Alloc(System.Object,System.Runtime.InteropServices.GCHandleType):System.Runtime.InteropServices.GCHandle" /> // <SatisfiesLinkDemand Name="GCHandle.AddrOfPinnedObject():System.IntPtr" /> // <SatisfiesLinkDemand Name="WaitHandle.get_SafeWaitHandle():Microsoft.Win32.SafeHandles.SafeWaitHandle" /> // <SatisfiesLinkDemand Name="GCHandle.Free():System.Void" /> // <ReferencesCritical Name="Method: ApplicationChangedCallback(Object, Boolean):Void" Ring="1" /> // <ReferencesCritical Name="Field: m_safeAppChangedEvent" Ring="1" /> // <ReferencesCritical Name="Method: PeerToPeerException.CreateFromHr(System.String,System.Int32):System.Net.PeerToPeer.PeerToPeerException" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] private void AddApplicationChanged(EventHandler<ApplicationChangedEventArgs> callback) { // // Register a wait handle if one has not been registered already // Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "AddApplicationChanged() called."); lock (LockAppChangedEvent){ if (m_applicationChanged == null){ if (m_id.Equals(Guid.Empty)){ throw new PeerToPeerException("No application guid defined"); } m_appChangedEvent = new AutoResetEvent(false); // // Register callback with a wait handle // m_regAppChangedWaitHandle = ThreadPool.RegisterWaitForSingleObject(m_appChangedEvent, //Event that triggers the callback new WaitOrTimerCallback(ApplicationChangedCallback), //callback to be called null, //state to be passed -1, //Timeout - aplicable only for timers false //call us everytime the event is set ); PEER_COLLAB_EVENT_REGISTRATION pcer = new PEER_COLLAB_EVENT_REGISTRATION(); pcer.eventType = PeerCollabEventType.EndPointApplicationChanged; GUID guid = CollaborationHelperFunctions.ConvertGuidToGUID(m_id); GCHandle guidHandle = GCHandle.Alloc(guid, GCHandleType.Pinned); pcer.pInstance = guidHandle.AddrOfPinnedObject(); // // Register event with collab // try{ Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Registering event with App ID {0}", m_id.ToString()); int errorCode = UnsafeCollabNativeMethods.PeerCollabRegisterEvent( m_appChangedEvent.SafeWaitHandle, 1, ref pcer, out m_safeAppChangedEvent); if (errorCode != 0){ Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabRegisterEvent returned with errorcode {0}", errorCode); throw PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_ApplicationChangedRegFailed), errorCode); } } finally{ if (guidHandle.IsAllocated) guidHandle.Free(); } } m_applicationChanged += callback; } Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "AddApplicationChanged() successful."); } // <SecurityKernel Critical="True" Ring="1"> // <ReferencesCritical Name="Field: m_safeAppChangedEvent" Ring="1" /> // <ReferencesCritical Name="Method: CollaborationHelperFunctions.CleanEventVars(System.Threading.RegisteredWaitHandle&,System.Net.PeerToPeer.Collaboration.SafeCollabEvent&,System.Threading.AutoResetEvent&):System.Void" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] private void RemoveApplicationChanged(EventHandler<ApplicationChangedEventArgs> callback) { Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "RemoveApplicationChanged() called."); lock (LockAppChangedEvent){ m_applicationChanged -= callback; if (m_applicationChanged == null){ CollaborationHelperFunctions.CleanEventVars(ref m_regAppChangedWaitHandle, ref m_safeAppChangedEvent, ref m_appChangedEvent); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Clean ApplicationChanged variables successful."); } } Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "RemoveApplicationChanged() successful."); } protected virtual void OnApplicationChanged(ApplicationChangedEventArgs appChangedArgs) { EventHandler<ApplicationChangedEventArgs> handlerCopy = m_applicationChanged; if (handlerCopy != null){ if (SynchronizingObject != null && SynchronizingObject.InvokeRequired) SynchronizingObject.BeginInvoke(handlerCopy, new object[] { this, appChangedArgs }); else handlerCopy(this, appChangedArgs); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Fired the application changed event callback."); } } // // Handles the callback when there is an application changed event from native collaboration // // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeCollabNativeMethods.PeerCollabGetEventData(System.Net.PeerToPeer.Collaboration.SafeCollabEvent,System.Net.PeerToPeer.Collaboration.SafeCollabData&):System.Int32" /> // <SatisfiesLinkDemand Name="SafeHandle.get_IsInvalid():System.Boolean" /> // <SatisfiesLinkDemand Name="SafeHandle.DangerousGetHandle():System.IntPtr" /> // <SatisfiesLinkDemand Name="Marshal.PtrToStructure(System.IntPtr,System.Type):System.Object" /> // <SatisfiesLinkDemand Name="SafeHandle.Dispose():System.Void" /> // <ReferencesCritical Name="Local eventData of type: SafeCollabData" Ring="1" /> // <ReferencesCritical Name="Field: m_safeAppChangedEvent" Ring="1" /> // <ReferencesCritical Name="Method: PeerToPeerException.CreateFromHr(System.String,System.Int32):System.Net.PeerToPeer.PeerToPeerException" Ring="1" /> // <ReferencesCritical Name="Method: CollaborationHelperFunctions.ConvertPEER_APPLICATIONToPeerApplication(System.Net.PeerToPeer.Collaboration.PEER_APPLICATION):System.Net.PeerToPeer.Collaboration.PeerApplication" Ring="1" /> // <ReferencesCritical Name="Method: CollaborationHelperFunctions.ConvertPEER_ENDPOINTToPeerEndPoint(System.Net.PeerToPeer.Collaboration.PEER_ENDPOINT):System.Net.PeerToPeer.Collaboration.PeerEndPoint" Ring="1" /> // <ReferencesCritical Name="Method: CollaborationHelperFunctions.ConvertPEER_CONTACTToPeerContact(System.Net.PeerToPeer.Collaboration.PEER_CONTACT):System.Net.PeerToPeer.Collaboration.PeerContact" Ring="2" /> // </SecurityKernel> [System.Security.SecurityCritical] private void ApplicationChangedCallback(object state, bool timedOut) { SafeCollabData eventData = null; int errorCode = 0; Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "ApplicationChangedCallback() called."); if (m_Disposed) return; while (true){ ApplicationChangedEventArgs appChangedArgs = null; // // Get the event data for the fired event // try{ lock (LockAppChangedEvent) { if (m_safeAppChangedEvent.IsInvalid) return; errorCode = UnsafeCollabNativeMethods.PeerCollabGetEventData(m_safeAppChangedEvent, out eventData); } if (errorCode == UnsafeCollabReturnCodes.PEER_S_NO_EVENT_DATA) break; else if (errorCode != 0){ Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabGetEventData returned with errorcode {0}", errorCode); throw PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_GetApplicationChangedDataFailed), errorCode); } PEER_COLLAB_EVENT_DATA ped = (PEER_COLLAB_EVENT_DATA)Marshal.PtrToStructure(eventData.DangerousGetHandle(), typeof(PEER_COLLAB_EVENT_DATA)); if (ped.eventType == PeerCollabEventType.EndPointApplicationChanged){ PEER_EVENT_APPLICATION_CHANGED_DATA appData = ped.applicationChangedData; PEER_APPLICATION pa = (PEER_APPLICATION)Marshal.PtrToStructure(appData.pApplication, typeof(PEER_APPLICATION)); PeerApplication peerApplication = CollaborationHelperFunctions.ConvertPEER_APPLICATIONToPeerApplication(pa); ; // // Check if the Guid of the fired app is indeed our guid // if (Guid.Equals(m_id, peerApplication.Id)){ PeerContact peerContact = null; PeerEndPoint peerEndPoint = null; if (appData.pContact != IntPtr.Zero){ PEER_CONTACT pc = (PEER_CONTACT)Marshal.PtrToStructure(appData.pContact, typeof(PEER_CONTACT)); peerContact = CollaborationHelperFunctions.ConvertPEER_CONTACTToPeerContact(pc); } if (appData.pEndPoint != IntPtr.Zero){ PEER_ENDPOINT pe = (PEER_ENDPOINT)Marshal.PtrToStructure(appData.pEndPoint, typeof(PEER_ENDPOINT)); peerEndPoint = CollaborationHelperFunctions.ConvertPEER_ENDPOINTToPeerEndPoint(pe); } appChangedArgs = new ApplicationChangedEventArgs(peerEndPoint, peerContact, appData.changeType, peerApplication); } } } finally{ if (eventData != null) eventData.Dispose(); } // // Fire the callback with the marshalled event args data // if(appChangedArgs != null) OnApplicationChanged(appChangedArgs); } Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Leaving ApplicationChangedCallback()."); } public bool Equals(PeerApplication other) { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); if (other != null){ return Guid.Equals(other.Id, m_id); } return false; } public override bool Equals(object obj) { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); PeerApplication comparandPeerApplication = obj as PeerApplication; if (comparandPeerApplication != null){ return Guid.Equals(comparandPeerApplication.Id, Id); } return false; } public new static bool Equals(object objA, object objB) { PeerApplication comparandPeerApplication1 = objA as PeerApplication; PeerApplication comparandPeerApplication2 = objB as PeerApplication; if ((comparandPeerApplication1 != null) && (comparandPeerApplication2 != null)){ return Guid.Equals(comparandPeerApplication1.Id, comparandPeerApplication2.Id); } return false; } public override int GetHashCode() { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); return Id.GetHashCode(); } public override string ToString() { if (m_Disposed) throw new ObjectDisposedException(this.GetType().FullName); return Id.ToString() + " " + Description; } private bool m_Disposed; // <SecurityKernel Critical="True" Ring="2"> // <ReferencesCritical Name="Method: Dispose(Boolean):Void" Ring="2" /> // </SecurityKernel> [System.Security.SecurityCritical] public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // <SecurityKernel Critical="True" Ring="1"> // <ReferencesCritical Name="Field: m_safeAppChangedEvent" Ring="1" /> // <ReferencesCritical Name="Method: CollaborationHelperFunctions.CleanEventVars(System.Threading.RegisteredWaitHandle&,System.Net.PeerToPeer.Collaboration.SafeCollabEvent&,System.Threading.AutoResetEvent&):System.Void" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] protected virtual void Dispose(bool disposing) { if (!m_Disposed){ CollaborationHelperFunctions.CleanEventVars(ref m_regAppChangedWaitHandle, ref m_safeAppChangedEvent, ref m_appChangedEvent); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Clean ApplicationChanged variables successful."); m_Disposed = true; } } // <SecurityKernel Critical="True" Ring="0"> // <SatisfiesLinkDemand Name="GetObjectData(SerializationInfo, StreamingContext):Void" /> // </SecurityKernel> [SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Justification = "System.Net.dll is still using pre-v4 security model and needs this demand")] [System.Security.SecurityCritical] [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter, SerializationFormatter = true)] void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { GetObjectData(info, context); } /// <summary> /// This is made virtual so that derived types can be implemented correctly /// </summary> [SecurityPermission(SecurityAction.LinkDemand, SerializationFormatter = true)] protected virtual void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("_Id", m_id); info.AddValue("_Data", m_data); info.AddValue("_Description", m_description); info.AddValue("_Path", m_path); info.AddValue("_CommandLineArgs", m_commandLineArgs); info.AddValue("_Scope", m_peerScope); } // // Tracing information for Peer Application // internal void TracePeerApplication() { Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "Contents of the PeerApplication"); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "\tGuid: {0}", Id); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "\tDescription: {0}", Description); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "\tPath: {0}", Path); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "\tCommandLineArgs: {0}", CommandLineArgs); Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "\tPeerScope: {0}", PeerScope); if (Data != null){ if (Logging.P2PTraceSource.Switch.ShouldTrace(TraceEventType.Verbose)){ Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "\tApplication data:"); Logging.DumpData(Logging.P2PTraceSource, TraceEventType.Verbose, Logging.P2PTraceSource.MaxDataSize, Data, 0, Data.Length); } else{ Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "\tApplication data length {0}", Data.Length); } } } } // // Manages collection of peer applications // [Serializable] public class PeerApplicationCollection : Collection<PeerApplication> { internal PeerApplicationCollection() { } protected override void SetItem(int index, PeerApplication item) { // nulls not allowed if (item == null){ throw new ArgumentNullException("item"); } base.SetItem(index, item); } protected override void InsertItem(int index, PeerApplication item) { // nulls not allowed if (item == null){ throw new ArgumentNullException("item"); } base.InsertItem(index, item); } public override string ToString() { bool first = true; StringBuilder builder = new StringBuilder(); foreach (PeerApplication peerApplication in this){ if(!first){ builder.Append(", "); } else{ first = false; } builder.Append(peerApplication.ToString()); } return builder.ToString(); } } }
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Umbraco.Cms.Core.Models.Blocks; using Umbraco.Extensions; namespace Umbraco.Cms.Core.PropertyEditors { /// <summary> /// A handler for Block editors used to bind to notifications /// </summary> public class BlockEditorPropertyHandler : ComplexPropertyEditorContentNotificationHandler { private readonly BlockListEditorDataConverter _converter = new BlockListEditorDataConverter(); private readonly ILogger _logger; public BlockEditorPropertyHandler(ILogger<BlockEditorPropertyHandler> logger) { _logger = logger; } protected override string EditorAlias => Constants.PropertyEditors.Aliases.BlockList; protected override string FormatPropertyValue(string rawJson, bool onlyMissingKeys) { // the block editor doesn't ever have missing UDIs so when this is true there's nothing to process if (onlyMissingKeys) return rawJson; return ReplaceBlockListUdis(rawJson, null); } // internal for tests internal string ReplaceBlockListUdis(string rawJson, Func<Guid> createGuid = null) { // used so we can test nicely if (createGuid == null) createGuid = () => Guid.NewGuid(); if (string.IsNullOrWhiteSpace(rawJson) || !rawJson.DetectIsJson()) return rawJson; // Parse JSON // This will throw a FormatException if there are null UDIs (expected) var blockListValue = _converter.Deserialize(rawJson); UpdateBlockListRecursively(blockListValue, createGuid); return JsonConvert.SerializeObject(blockListValue.BlockValue); } private void UpdateBlockListRecursively(BlockEditorData blockListData, Func<Guid> createGuid) { var oldToNew = new Dictionary<Udi, Udi>(); MapOldToNewUdis(oldToNew, blockListData.BlockValue.ContentData, createGuid); MapOldToNewUdis(oldToNew, blockListData.BlockValue.SettingsData, createGuid); for (var i = 0; i < blockListData.References.Count; i++) { var reference = blockListData.References[i]; var hasContentMap = oldToNew.TryGetValue(reference.ContentUdi, out var contentMap); Udi settingsMap = null; var hasSettingsMap = reference.SettingsUdi != null && oldToNew.TryGetValue(reference.SettingsUdi, out settingsMap); if (hasContentMap) { // replace the reference blockListData.References.RemoveAt(i); blockListData.References.Insert(i, new ContentAndSettingsReference(contentMap, hasSettingsMap ? settingsMap : null)); } } // build the layout with the new UDIs var layout = (JArray)blockListData.Layout; layout.Clear(); foreach (var reference in blockListData.References) { layout.Add(JObject.FromObject(new BlockListLayoutItem { ContentUdi = reference.ContentUdi, SettingsUdi = reference.SettingsUdi })); } RecursePropertyValues(blockListData.BlockValue.ContentData, createGuid); RecursePropertyValues(blockListData.BlockValue.SettingsData, createGuid); } private void RecursePropertyValues(IEnumerable<BlockItemData> blockData, Func<Guid> createGuid) { foreach (var data in blockData) { // check if we need to recurse (make a copy of the dictionary since it will be modified) foreach (var propertyAliasToBlockItemData in new Dictionary<string, object>(data.RawPropertyValues)) { if (propertyAliasToBlockItemData.Value is JToken jtoken) { if (ProcessJToken(jtoken, createGuid, out var result)) { // need to re-save this back to the RawPropertyValues data.RawPropertyValues[propertyAliasToBlockItemData.Key] = result; } } else { var asString = propertyAliasToBlockItemData.Value?.ToString(); if (asString != null && asString.DetectIsJson()) { // this gets a little ugly because there could be some other complex editor that contains another block editor // and since we would have no idea how to parse that, all we can do is try JSON Path to find another block editor // of our type JToken json = null; try { json = JToken.Parse(asString); } catch (Exception) { // See issue https://github.com/umbraco/Umbraco-CMS/issues/10879 // We are detecting JSON data by seeing if a string is surrounded by [] or {} // If people enter text like [PLACEHOLDER] JToken parsing fails, it's safe to ignore though // Logging this just in case in the future we find values that are not safe to ignore _logger.LogWarning( "The property {PropertyAlias} on content type {ContentTypeKey} has a value of: {BlockItemValue} - this was recognized as JSON but could not be parsed", data.Key, propertyAliasToBlockItemData.Key, asString); } if (json != null && ProcessJToken(json, createGuid, out var result)) { // need to re-save this back to the RawPropertyValues data.RawPropertyValues[propertyAliasToBlockItemData.Key] = result; } } } } } } private bool ProcessJToken(JToken json, Func<Guid> createGuid, out JToken result) { var updated = false; result = json; // select all tokens (flatten) var allProperties = json.SelectTokens("$..*").Select(x => x.Parent as JProperty).WhereNotNull().ToList(); foreach (var prop in allProperties) { if (prop.Name == Constants.PropertyEditors.Aliases.BlockList) { // get it's parent 'layout' and it's parent's container var layout = prop.Parent?.Parent as JProperty; if (layout != null && layout.Parent is JObject layoutJson) { // recurse var blockListValue = _converter.ConvertFrom(layoutJson); UpdateBlockListRecursively(blockListValue, createGuid); // set new value if (layoutJson.Parent != null) { // we can replace the object layoutJson.Replace(JObject.FromObject(blockListValue.BlockValue)); updated = true; } else { // if there is no parent it means that this json property was the root, in which case we just return result = JObject.FromObject(blockListValue.BlockValue); return true; } } } else if (prop.Name != "layout" && prop.Name != "contentData" && prop.Name != "settingsData" && prop.Name != "contentTypeKey") { // this is an arbitrary property that could contain a nested complex editor var propVal = prop.Value?.ToString(); // check if this might contain a nested Block Editor if (!propVal.IsNullOrWhiteSpace() && propVal.DetectIsJson() && propVal.InvariantContains(Constants.PropertyEditors.Aliases.BlockList)) { if (_converter.TryDeserialize(propVal, out var nestedBlockData)) { // recurse UpdateBlockListRecursively(nestedBlockData, createGuid); // set the value to the updated one prop.Value = JObject.FromObject(nestedBlockData.BlockValue); updated = true; } } } } return updated; } private void MapOldToNewUdis(Dictionary<Udi, Udi> oldToNew, IEnumerable<BlockItemData> blockData, Func<Guid> createGuid) { foreach (var data in blockData) { // This should never happen since a FormatException will be thrown if one is empty but we'll keep this here if (data.Udi == null) throw new InvalidOperationException("Block data cannot contain a null UDI"); // replace the UDIs var newUdi = GuidUdi.Create(Constants.UdiEntityType.Element, createGuid()); oldToNew[data.Udi] = newUdi; data.Udi = newUdi; } } } }
using UnityEngine; using System.Collections.Generic; namespace UnityEngine.UI { public static class DefaultControls { public struct Resources { public Sprite standard; public Sprite background; public Sprite inputField; public Sprite knob; public Sprite checkmark; public Sprite dropdown; public Sprite mask; } private const float kWidth = 160f; private const float kThickHeight = 30f; private const float kThinHeight = 20f; private static Vector2 s_ThickElementSize = new Vector2(kWidth, kThickHeight); private static Vector2 s_ThinElementSize = new Vector2(kWidth, kThinHeight); private static Vector2 s_ImageElementSize = new Vector2(100f, 100f); private static Color s_DefaultSelectableColor = new Color(1f, 1f, 1f, 1f); private static Color s_PanelColor = new Color(1f, 1f, 1f, 0.392f); private static Color s_TextColor = new Color(50f / 255f, 50f / 255f, 50f / 255f, 1f); // Helper methods at top private static GameObject CreateUIElementRoot(string name, Vector2 size) { GameObject child = new GameObject(name); RectTransform rectTransform = child.AddComponent<RectTransform>(); rectTransform.sizeDelta = size; return child; } static GameObject CreateUIObject(string name, GameObject parent) { GameObject go = new GameObject(name); go.AddComponent<RectTransform>(); SetParentAndAlign(go, parent); return go; } private static void SetDefaultTextValues(Text lbl) { // Set text values we want across UI elements in default controls. // Don't set values which are the same as the default values for the Text component, // since there's no point in that, and it's good to keep them as consistent as possible. lbl.color = s_TextColor; } private static void SetDefaultColorTransitionValues(Selectable slider) { ColorBlock colors = slider.colors; colors.highlightedColor = new Color(0.882f, 0.882f, 0.882f); colors.pressedColor = new Color(0.698f, 0.698f, 0.698f); colors.disabledColor = new Color(0.521f, 0.521f, 0.521f); } private static void SetParentAndAlign(GameObject child, GameObject parent) { if (parent == null) return; child.transform.SetParent(parent.transform, false); SetLayerRecursively(child, parent.layer); } private static void SetLayerRecursively(GameObject go, int layer) { go.layer = layer; Transform t = go.transform; for (int i = 0; i < t.childCount; i++) SetLayerRecursively(t.GetChild(i).gameObject, layer); } // Actual controls public static GameObject CreatePanel(Sprite background) { GameObject panelRoot = CreateUIElementRoot("Panel", s_ThickElementSize); // Set RectTransform to stretch RectTransform rectTransform = panelRoot.GetComponent<RectTransform>(); rectTransform.anchorMin = Vector2.zero; rectTransform.anchorMax = Vector2.one; rectTransform.anchoredPosition = Vector2.zero; rectTransform.sizeDelta = Vector2.zero; Image image = panelRoot.AddComponent<Image>(); image.sprite = background; image.type = Image.Type.Sliced; image.color = s_PanelColor; return panelRoot; } public static GameObject CreatePanel(Resources resources) { return CreatePanel(resources.background); } public static GameObject CreateButton(Resources resources) { GameObject buttonRoot = CreateUIElementRoot("Button", s_ThickElementSize); GameObject childText = new GameObject("Text"); SetParentAndAlign(childText, buttonRoot); Image image = buttonRoot.AddComponent<Image>(); image.sprite = resources.standard; image.type = Image.Type.Sliced; image.color = s_DefaultSelectableColor; Button bt = buttonRoot.AddComponent<Button>(); SetDefaultColorTransitionValues(bt); Text text = childText.AddComponent<Text>(); text.text = "Button"; text.alignment = TextAnchor.MiddleCenter; SetDefaultTextValues(text); RectTransform textRectTransform = childText.GetComponent<RectTransform>(); textRectTransform.anchorMin = Vector2.zero; textRectTransform.anchorMax = Vector2.one; textRectTransform.sizeDelta = Vector2.zero; return buttonRoot; } public static GameObject CreateText(Resources resources) { GameObject go = CreateUIElementRoot("Text", s_ThickElementSize); Text lbl = go.AddComponent<Text>(); lbl.text = "New Text"; SetDefaultTextValues(lbl); return go; } public static GameObject CreateImage(Resources resources) { GameObject go = CreateUIElementRoot("Image", s_ImageElementSize); go.AddComponent<Image>(); return go; } public static GameObject CreateRawImage(Resources resources) { GameObject go = CreateUIElementRoot("RawImage", s_ImageElementSize); go.AddComponent<RawImage>(); return go; } public static GameObject CreateSlider(Resources resources) { // Create GOs Hierarchy GameObject root = CreateUIElementRoot("Slider", s_ThinElementSize); GameObject background = CreateUIObject("Background", root); GameObject fillArea = CreateUIObject("Fill Area", root); GameObject fill = CreateUIObject("Fill", fillArea); GameObject handleArea = CreateUIObject("Handle Slide Area", root); GameObject handle = CreateUIObject("Handle", handleArea); // Background Image backgroundImage = background.AddComponent<Image>(); backgroundImage.sprite = resources.background; backgroundImage.type = Image.Type.Sliced; backgroundImage.color = s_DefaultSelectableColor; RectTransform backgroundRect = background.GetComponent<RectTransform>(); backgroundRect.anchorMin = new Vector2(0, 0.25f); backgroundRect.anchorMax = new Vector2(1, 0.75f); backgroundRect.sizeDelta = new Vector2(0, 0); // Fill Area RectTransform fillAreaRect = fillArea.GetComponent<RectTransform>(); fillAreaRect.anchorMin = new Vector2(0, 0.25f); fillAreaRect.anchorMax = new Vector2(1, 0.75f); fillAreaRect.anchoredPosition = new Vector2(-5, 0); fillAreaRect.sizeDelta = new Vector2(-20, 0); // Fill Image fillImage = fill.AddComponent<Image>(); fillImage.sprite = resources.standard; fillImage.type = Image.Type.Sliced; fillImage.color = s_DefaultSelectableColor; RectTransform fillRect = fill.GetComponent<RectTransform>(); fillRect.sizeDelta = new Vector2(10, 0); // Handle Area RectTransform handleAreaRect = handleArea.GetComponent<RectTransform>(); handleAreaRect.sizeDelta = new Vector2(-20, 0); handleAreaRect.anchorMin = new Vector2(0, 0); handleAreaRect.anchorMax = new Vector2(1, 1); // Handle Image handleImage = handle.AddComponent<Image>(); handleImage.sprite = resources.knob; handleImage.color = s_DefaultSelectableColor; RectTransform handleRect = handle.GetComponent<RectTransform>(); handleRect.sizeDelta = new Vector2(20, 0); // Setup slider component Slider slider = root.AddComponent<Slider>(); slider.fillRect = fill.GetComponent<RectTransform>(); slider.handleRect = handle.GetComponent<RectTransform>(); slider.targetGraphic = handleImage; slider.direction = Slider.Direction.LeftToRight; SetDefaultColorTransitionValues(slider); return root; } public static GameObject CreateScrollbar(Resources resources) { // Create GOs Hierarchy GameObject scrollbarRoot = CreateUIElementRoot("Scrollbar", s_ThinElementSize); GameObject sliderArea = CreateUIObject("Sliding Area", scrollbarRoot); GameObject handle = CreateUIObject("Handle", sliderArea); Image bgImage = scrollbarRoot.AddComponent<Image>(); bgImage.sprite = resources.background; bgImage.type = Image.Type.Sliced; bgImage.color = s_DefaultSelectableColor; Image handleImage = handle.AddComponent<Image>(); handleImage.sprite = resources.standard; handleImage.type = Image.Type.Sliced; handleImage.color = s_DefaultSelectableColor; RectTransform sliderAreaRect = sliderArea.GetComponent<RectTransform>(); sliderAreaRect.sizeDelta = new Vector2(-20, -20); sliderAreaRect.anchorMin = Vector2.zero; sliderAreaRect.anchorMax = Vector2.one; RectTransform handleRect = handle.GetComponent<RectTransform>(); handleRect.sizeDelta = new Vector2(20, 20); Scrollbar scrollbar = scrollbarRoot.AddComponent<Scrollbar>(); scrollbar.handleRect = handleRect; scrollbar.targetGraphic = handleImage; SetDefaultColorTransitionValues(scrollbar); return scrollbarRoot; } public static GameObject CreateToggle(Resources resources) { // Set up hierarchy GameObject toggleRoot = CreateUIElementRoot("Toggle", s_ThinElementSize); GameObject background = CreateUIObject("Background", toggleRoot); GameObject checkmark = CreateUIObject("Checkmark", background); GameObject childLabel = CreateUIObject("Label", toggleRoot); // Set up components Toggle toggle = toggleRoot.AddComponent<Toggle>(); toggle.isOn = true; Image bgImage = background.AddComponent<Image>(); bgImage.sprite = resources.standard; bgImage.type = Image.Type.Sliced; bgImage.color = s_DefaultSelectableColor; Image checkmarkImage = checkmark.AddComponent<Image>(); checkmarkImage.sprite = resources.checkmark; Text label = childLabel.AddComponent<Text>(); label.text = "Toggle"; SetDefaultTextValues(label); toggle.graphic = checkmarkImage; toggle.targetGraphic = bgImage; SetDefaultColorTransitionValues(toggle); RectTransform bgRect = background.GetComponent<RectTransform>(); bgRect.anchorMin = new Vector2(0f, 1f); bgRect.anchorMax = new Vector2(0f, 1f); bgRect.anchoredPosition = new Vector2(10f, -10f); bgRect.sizeDelta = new Vector2(kThinHeight, kThinHeight); RectTransform checkmarkRect = checkmark.GetComponent<RectTransform>(); checkmarkRect.anchorMin = new Vector2(0.5f, 0.5f); checkmarkRect.anchorMax = new Vector2(0.5f, 0.5f); checkmarkRect.anchoredPosition = Vector2.zero; checkmarkRect.sizeDelta = new Vector2(20f, 20f); RectTransform labelRect = childLabel.GetComponent<RectTransform>(); labelRect.anchorMin = new Vector2(0f, 0f); labelRect.anchorMax = new Vector2(1f, 1f); labelRect.offsetMin = new Vector2(23f, 1f); labelRect.offsetMax = new Vector2(-5f, -2f); return toggleRoot; } public static GameObject CreateInputField(Resources resources) { GameObject root = CreateUIElementRoot("InputField", s_ThickElementSize); GameObject childPlaceholder = CreateUIObject("Placeholder", root); GameObject childText = CreateUIObject("Text", root); Image image = root.AddComponent<Image>(); image.sprite = resources.inputField; image.type = Image.Type.Sliced; image.color = s_DefaultSelectableColor; InputField inputField = root.AddComponent<InputField>(); SetDefaultColorTransitionValues(inputField); Text text = childText.AddComponent<Text>(); text.text = ""; text.supportRichText = false; SetDefaultTextValues(text); Text placeholder = childPlaceholder.AddComponent<Text>(); placeholder.text = "Enter text..."; placeholder.fontStyle = FontStyle.Italic; // Make placeholder color half as opaque as normal text color. Color placeholderColor = text.color; placeholderColor.a *= 0.5f; placeholder.color = placeholderColor; RectTransform textRectTransform = childText.GetComponent<RectTransform>(); textRectTransform.anchorMin = Vector2.zero; textRectTransform.anchorMax = Vector2.one; textRectTransform.sizeDelta = Vector2.zero; textRectTransform.offsetMin = new Vector2(10, 6); textRectTransform.offsetMax = new Vector2(-10, -7); RectTransform placeholderRectTransform = childPlaceholder.GetComponent<RectTransform>(); placeholderRectTransform.anchorMin = Vector2.zero; placeholderRectTransform.anchorMax = Vector2.one; placeholderRectTransform.sizeDelta = Vector2.zero; placeholderRectTransform.offsetMin = new Vector2(10, 6); placeholderRectTransform.offsetMax = new Vector2(-10, -7); inputField.textComponent = text; inputField.placeholder = placeholder; return root; } public static GameObject CreateDropdown(Resources resources) { GameObject root = CreateUIElementRoot("Dropdown", s_ThickElementSize); GameObject label = CreateUIObject("Label", root); GameObject arrow = CreateUIObject("Arrow", root); GameObject template = CreateUIObject("Template", root); GameObject viewport = CreateUIObject("Viewport", template); GameObject content = CreateUIObject("Content", viewport); GameObject item = CreateUIObject("Item", content); GameObject itemBackground = CreateUIObject("Item Background", item); GameObject itemCheckmark = CreateUIObject("Item Checkmark", item); GameObject itemLabel = CreateUIObject("Item Label", item); // Sub controls. GameObject scrollbar = CreateScrollbar(resources); scrollbar.name = "Scrollbar"; SetParentAndAlign(scrollbar, template); Scrollbar scrollbarScrollbar = scrollbar.GetComponent<Scrollbar>(); scrollbarScrollbar.SetDirection(Scrollbar.Direction.BottomToTop, true); RectTransform vScrollbarRT = scrollbar.GetComponent<RectTransform>(); vScrollbarRT.anchorMin = Vector2.right; vScrollbarRT.anchorMax = Vector2.one; vScrollbarRT.pivot = Vector2.one; vScrollbarRT.sizeDelta = new Vector2(vScrollbarRT.sizeDelta.x, 0); // Setup item UI components. Text itemLabelText = itemLabel.AddComponent<Text>(); SetDefaultTextValues(itemLabelText); itemLabelText.alignment = TextAnchor.MiddleLeft; Image itemBackgroundImage = itemBackground.AddComponent<Image>(); itemBackgroundImage.color = new Color32(245, 245, 245, 255); Image itemCheckmarkImage = itemCheckmark.AddComponent<Image>(); itemCheckmarkImage.sprite = resources.checkmark; Toggle itemToggle = item.AddComponent<Toggle>(); itemToggle.targetGraphic = itemBackgroundImage; itemToggle.graphic = itemCheckmarkImage; itemToggle.isOn = true; // Setup template UI components. Image templateImage = template.AddComponent<Image>(); templateImage.sprite = resources.standard; templateImage.type = Image.Type.Sliced; ScrollRect templateScrollRect = template.AddComponent<ScrollRect>(); templateScrollRect.content = (RectTransform)content.transform; templateScrollRect.viewport = (RectTransform)viewport.transform; templateScrollRect.horizontal = false; templateScrollRect.movementType = ScrollRect.MovementType.Clamped; templateScrollRect.verticalScrollbar = scrollbarScrollbar; templateScrollRect.verticalScrollbarVisibility = ScrollRect.ScrollbarVisibility.AutoHideAndExpandViewport; templateScrollRect.verticalScrollbarSpacing = -3; Mask scrollRectMask = viewport.AddComponent<Mask>(); scrollRectMask.showMaskGraphic = false; Image viewportImage = viewport.AddComponent<Image>(); viewportImage.sprite = resources.mask; viewportImage.type = Image.Type.Sliced; // Setup dropdown UI components. Text labelText = label.AddComponent<Text>(); SetDefaultTextValues(labelText); labelText.text = "Option A"; labelText.alignment = TextAnchor.MiddleLeft; Image arrowImage = arrow.AddComponent<Image>(); arrowImage.sprite = resources.dropdown; Image backgroundImage = root.AddComponent<Image>(); backgroundImage.sprite = resources.standard; backgroundImage.color = s_DefaultSelectableColor; backgroundImage.type = Image.Type.Sliced; Dropdown dropdown = root.AddComponent<Dropdown>(); dropdown.targetGraphic = backgroundImage; SetDefaultColorTransitionValues(dropdown); dropdown.template = template.GetComponent<RectTransform>(); dropdown.captionText = labelText; dropdown.itemText = itemLabelText; // Setting default Item list. itemLabelText.text = "Option A"; dropdown.options.Add(new Dropdown.OptionData {text = "Option A"}); dropdown.options.Add(new Dropdown.OptionData {text = "Option B"}); dropdown.options.Add(new Dropdown.OptionData {text = "Option C"}); // Set up RectTransforms. RectTransform labelRT = label.GetComponent<RectTransform>(); labelRT.anchorMin = Vector2.zero; labelRT.anchorMax = Vector2.one; labelRT.offsetMin = new Vector2(10, 6); labelRT.offsetMax = new Vector2(-25, -7); RectTransform arrowRT = arrow.GetComponent<RectTransform>(); arrowRT.anchorMin = new Vector2(1, 0.5f); arrowRT.anchorMax = new Vector2(1, 0.5f); arrowRT.sizeDelta = new Vector2(20, 20); arrowRT.anchoredPosition = new Vector2(-15, 0); RectTransform templateRT = template.GetComponent<RectTransform>(); templateRT.anchorMin = new Vector2(0, 0); templateRT.anchorMax = new Vector2(1, 0); templateRT.pivot = new Vector2(0.5f, 1); templateRT.anchoredPosition = new Vector2(0, 2); templateRT.sizeDelta = new Vector2(0, 150); RectTransform viewportRT = viewport.GetComponent<RectTransform>(); viewportRT.anchorMin = new Vector2(0, 0); viewportRT.anchorMax = new Vector2(1, 1); viewportRT.sizeDelta = new Vector2(-18, 0); viewportRT.pivot = new Vector2(0, 1); RectTransform contentRT = content.GetComponent<RectTransform>(); contentRT.anchorMin = new Vector2(0f, 1); contentRT.anchorMax = new Vector2(1f, 1); contentRT.pivot = new Vector2(0.5f, 1); contentRT.anchoredPosition = new Vector2(0, 0); contentRT.sizeDelta = new Vector2(0, 28); RectTransform itemRT = item.GetComponent<RectTransform>(); itemRT.anchorMin = new Vector2(0, 0.5f); itemRT.anchorMax = new Vector2(1, 0.5f); itemRT.sizeDelta = new Vector2(0, 20); RectTransform itemBackgroundRT = itemBackground.GetComponent<RectTransform>(); itemBackgroundRT.anchorMin = Vector2.zero; itemBackgroundRT.anchorMax = Vector2.one; itemBackgroundRT.sizeDelta = Vector2.zero; RectTransform itemCheckmarkRT = itemCheckmark.GetComponent<RectTransform>(); itemCheckmarkRT.anchorMin = new Vector2(0, 0.5f); itemCheckmarkRT.anchorMax = new Vector2(0, 0.5f); itemCheckmarkRT.sizeDelta = new Vector2(20, 20); itemCheckmarkRT.anchoredPosition = new Vector2(10, 0); RectTransform itemLabelRT = itemLabel.GetComponent<RectTransform>(); itemLabelRT.anchorMin = Vector2.zero; itemLabelRT.anchorMax = Vector2.one; itemLabelRT.offsetMin = new Vector2(20, 1); itemLabelRT.offsetMax = new Vector2(-10, -2); template.SetActive(false); return root; } public static GameObject CreateScrollView(Resources resources) { GameObject root = CreateUIElementRoot("Scroll View", new Vector2(200, 200)); GameObject viewport = CreateUIObject("Viewport", root); GameObject content = CreateUIObject("Content", viewport); // Sub controls. GameObject hScrollbar = CreateScrollbar(resources); hScrollbar.name = "Scrollbar Horizontal"; SetParentAndAlign(hScrollbar, root); RectTransform hScrollbarRT = hScrollbar.GetComponent<RectTransform>(); hScrollbarRT.anchorMin = Vector2.zero; hScrollbarRT.anchorMax = Vector2.right; hScrollbarRT.pivot = Vector2.zero; hScrollbarRT.sizeDelta = new Vector2(0, hScrollbarRT.sizeDelta.y); GameObject vScrollbar = CreateScrollbar(resources); vScrollbar.name = "Scrollbar Vertical"; SetParentAndAlign(vScrollbar, root); vScrollbar.GetComponent<Scrollbar>().SetDirection(Scrollbar.Direction.BottomToTop, true); RectTransform vScrollbarRT = vScrollbar.GetComponent<RectTransform>(); vScrollbarRT.anchorMin = Vector2.right; vScrollbarRT.anchorMax = Vector2.one; vScrollbarRT.pivot = Vector2.one; vScrollbarRT.sizeDelta = new Vector2(vScrollbarRT.sizeDelta.x, 0); // Setup RectTransforms. // Make viewport fill entire scroll view. RectTransform viewportRT = viewport.GetComponent<RectTransform>(); viewportRT.anchorMin = Vector2.zero; viewportRT.anchorMax = Vector2.one; viewportRT.sizeDelta = Vector2.zero; viewportRT.pivot = Vector2.up; // Make context match viewpoprt width and be somewhat taller. // This will show the vertical scrollbar and not the horizontal one. RectTransform contentRT = content.GetComponent<RectTransform>(); contentRT.anchorMin = Vector2.up; contentRT.anchorMax = Vector2.one; contentRT.sizeDelta = new Vector2(0, 300); contentRT.pivot = Vector2.up; // Setup UI components. ScrollRect scrollRect = root.AddComponent<ScrollRect>(); scrollRect.content = contentRT; scrollRect.viewport = viewportRT; scrollRect.horizontalScrollbar = hScrollbar.GetComponent<Scrollbar>(); scrollRect.verticalScrollbar = vScrollbar.GetComponent<Scrollbar>(); scrollRect.horizontalScrollbarVisibility = ScrollRect.ScrollbarVisibility.AutoHideAndExpandViewport; scrollRect.verticalScrollbarVisibility = ScrollRect.ScrollbarVisibility.AutoHideAndExpandViewport; scrollRect.horizontalScrollbarSpacing = -3; scrollRect.verticalScrollbarSpacing = -3; Image rootImage = root.AddComponent<Image>(); rootImage.sprite = resources.background; rootImage.type = Image.Type.Sliced; rootImage.color = s_PanelColor; Mask viewportMask = viewport.AddComponent<Mask>(); viewportMask.showMaskGraphic = false; Image viewportImage = viewport.AddComponent<Image>(); viewportImage.sprite = resources.mask; viewportImage.type = Image.Type.Sliced; return root; } } }
using System; using System.Collections.Generic; using System.Linq; using Moq; using NuGet.Test.Mocks; using Xunit; namespace NuGet.Test { public class PackageWalkerTest { [Fact] public void ReverseDependencyWalkerUsersVersionAndIdToDetermineVisited() { // Arrange // A 1.0 -> B 1.0 IPackage packageA1 = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "[1.0]") }); // A 2.0 -> B 2.0 IPackage packageA2 = PackageUtility.CreatePackage("A", "2.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "[2.0]") }); IPackage packageB1 = PackageUtility.CreatePackage("B", "1.0"); IPackage packageB2 = PackageUtility.CreatePackage("B", "2.0"); var mockRepository = new MockPackageRepository(); mockRepository.AddPackage(packageA1); mockRepository.AddPackage(packageA2); mockRepository.AddPackage(packageB1); mockRepository.AddPackage(packageB2); // Act IDependentsResolver lookup = new DependentsWalker(mockRepository); // Assert Assert.Equal(0, lookup.GetDependents(packageA1).Count()); Assert.Equal(0, lookup.GetDependents(packageA2).Count()); Assert.Equal(1, lookup.GetDependents(packageB1).Count()); Assert.Equal(1, lookup.GetDependents(packageB2).Count()); } [Fact] public void ResolveDependenciesForInstallPackageWithUnknownDependencyThrows() { // Arrange IPackage package = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackageOperationResolver resolver = new InstallWalker(new MockPackageRepository(), new MockPackageRepository(), NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(package), "Unable to resolve dependency 'B'."); } [Fact] public void ResolveDependenciesForInstallPackageResolvesDependencyUsingDependencyProvider() { // Arrange IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageB = PackageUtility.CreatePackage("B"); var repository = new Mock<PackageRepositoryBase>(); repository.Setup(c => c.GetPackages()).Returns(new[] { packageA }.AsQueryable()); var dependencyProvider = repository.As<IDependencyResolver>(); dependencyProvider.Setup(c => c.ResolveDependency(It.Is<PackageDependency>(p => p.Id == "B"), It.IsAny<IPackageConstraintProvider>(), false, true)) .Returns(packageB).Verifiable(); var localRepository = new MockPackageRepository(); IPackageOperationResolver resolver = new InstallWalker(localRepository, repository.Object, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false); // Act var operations = resolver.ResolveOperations(packageA).ToList(); // Assert Assert.Equal(2, operations.Count); Assert.Equal(PackageAction.Install, operations.First().Action); Assert.Equal(packageB, operations.First().Package); Assert.Equal(PackageAction.Install, operations.Last().Action); Assert.Equal(packageA, operations.Last().Package); dependencyProvider.Verify(); } [Fact] public void ResolveDependenciesForInstallPackageResolvesDependencyWithConstraintsUsingDependencyResolver() { // Arrange var packageDependency = new PackageDependency("B", new VersionSpec { MinVersion = new SemanticVersion("1.1") }); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { packageDependency }); IPackage packageB12 = PackageUtility.CreatePackage("B", "1.2"); var repository = new Mock<PackageRepositoryBase>(MockBehavior.Strict); repository.Setup(c => c.GetPackages()).Returns(new[] { packageA }.AsQueryable()); var dependencyProvider = repository.As<IDependencyResolver>(); dependencyProvider.Setup(c => c.ResolveDependency(packageDependency, It.IsAny<IPackageConstraintProvider>(), false, true)) .Returns(packageB12).Verifiable(); var localRepository = new MockPackageRepository(); IPackageOperationResolver resolver = new InstallWalker(localRepository, repository.Object, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false); // Act var operations = resolver.ResolveOperations(packageA).ToList(); // Assert Assert.Equal(2, operations.Count); Assert.Equal(PackageAction.Install, operations.First().Action); Assert.Equal(packageB12, operations.First().Package); Assert.Equal(PackageAction.Install, operations.Last().Action); Assert.Equal(packageA, operations.Last().Package); dependencyProvider.Verify(); } [Fact] public void ResolveDependenciesForInstallCircularReferenceThrows() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("A") }); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageB); IPackageOperationResolver resolver = new InstallWalker(localRepository, sourceRepository, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageA), "Circular dependency detected 'A 1.0 => B 1.0 => A 1.0'."); } [Fact] public void ResolveDependenciesForInstallDiamondDependencyGraph() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); // A -> [B, C] // B -> [D] // C -> [D] // A // / \ // B C // \ / // D IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B"), new PackageDependency("C") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("D") }); IPackage packageC = PackageUtility.CreatePackage("C", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("D") }); IPackage packageD = PackageUtility.CreatePackage("D", "1.0"); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageB); sourceRepository.AddPackage(packageC); sourceRepository.AddPackage(packageD); IPackageOperationResolver resolver = new InstallWalker(localRepository, sourceRepository, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false); // Act var packages = resolver.ResolveOperations(packageA).ToList(); // Assert var dict = packages.ToDictionary(p => p.Package.Id); Assert.Equal(4, packages.Count); Assert.NotNull(dict["A"]); Assert.NotNull(dict["B"]); Assert.NotNull(dict["C"]); Assert.NotNull(dict["D"]); } [Fact] public void ResolveDependenciesForInstallDiamondDependencyGraphWithDifferntVersionOfSamePackage() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); // A -> [B, C] // B -> [D >= 1, E >= 2] // C -> [D >= 2, E >= 1] // A // / \ // B C // | \ | \ // D1 E2 D2 E1 IPackage packageA = PackageUtility.CreateProjectLevelPackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B"), new PackageDependency("C") }); IPackage packageB = PackageUtility.CreateProjectLevelPackage("B", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("D", "1.0"), PackageDependency.CreateDependency("E", "2.0") }); IPackage packageC = PackageUtility.CreateProjectLevelPackage("C", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("D", "2.0"), PackageDependency.CreateDependency("E", "1.0") }); IPackage packageD10 = PackageUtility.CreateProjectLevelPackage("D", "1.0"); IPackage packageD20 = PackageUtility.CreateProjectLevelPackage("D", "2.0"); IPackage packageE10 = PackageUtility.CreateProjectLevelPackage("E", "1.0"); IPackage packageE20 = PackageUtility.CreateProjectLevelPackage("E", "2.0"); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageB); sourceRepository.AddPackage(packageC); sourceRepository.AddPackage(packageD20); sourceRepository.AddPackage(packageD10); sourceRepository.AddPackage(packageE20); sourceRepository.AddPackage(packageE10); IPackageOperationResolver resolver = new InstallWalker(localRepository, sourceRepository, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false); // Act var operations = resolver.ResolveOperations(packageA).ToList(); var projectOperations = resolver.ResolveOperations(packageA).ToList(); // Assert Assert.Equal(5, operations.Count); Assert.Equal("E", operations[0].Package.Id); Assert.Equal(new SemanticVersion("2.0"), operations[0].Package.Version); Assert.Equal("B", operations[1].Package.Id); Assert.Equal("D", operations[2].Package.Id); Assert.Equal(new SemanticVersion("2.0"), operations[2].Package.Version); Assert.Equal("C", operations[3].Package.Id); Assert.Equal("A", operations[4].Package.Id); Assert.Equal(5, projectOperations.Count); Assert.Equal("E", projectOperations[0].Package.Id); Assert.Equal(new SemanticVersion("2.0"), projectOperations[0].Package.Version); Assert.Equal("B", projectOperations[1].Package.Id); Assert.Equal("D", projectOperations[2].Package.Id); Assert.Equal(new SemanticVersion("2.0"), projectOperations[2].Package.Version); Assert.Equal("C", projectOperations[3].Package.Id); Assert.Equal("A", projectOperations[4].Package.Id); } [Fact] public void UninstallWalkerIgnoresMissingDependencies() { // Arrange var localRepository = new MockPackageRepository(); // A -> [B, C] // B -> [D] // C -> [D] IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B"), new PackageDependency("C") }); IPackage packageC = PackageUtility.CreatePackage("C", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("D") }); IPackage packageD = PackageUtility.CreatePackage("D", "1.0"); localRepository.AddPackage(packageA); localRepository.AddPackage(packageC); localRepository.AddPackage(packageD); IPackageOperationResolver resolver = new UninstallWalker(localRepository, new DependentsWalker(localRepository), NullLogger.Instance, removeDependencies: true, forceRemove: false); // Act var packages = resolver.ResolveOperations(packageA) .ToDictionary(p => p.Package.Id); // Assert Assert.Equal(3, packages.Count); Assert.NotNull(packages["A"]); Assert.NotNull(packages["C"]); Assert.NotNull(packages["D"]); } [Fact] public void ResolveDependenciesForUninstallDiamondDependencyGraph() { // Arrange var localRepository = new MockPackageRepository(); // A -> [B, C] // B -> [D] // C -> [D] // A // / \ // B C // \ / // D IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B"), new PackageDependency("C") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("D") }); IPackage packageC = PackageUtility.CreatePackage("C", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("D") }); IPackage packageD = PackageUtility.CreatePackage("D", "1.0"); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); localRepository.AddPackage(packageC); localRepository.AddPackage(packageD); IPackageOperationResolver resolver = new UninstallWalker(localRepository, new DependentsWalker(localRepository), NullLogger.Instance, removeDependencies: true, forceRemove: false); // Act var packages = resolver.ResolveOperations(packageA) .ToDictionary(p => p.Package.Id); // Assert Assert.Equal(4, packages.Count); Assert.NotNull(packages["A"]); Assert.NotNull(packages["B"]); Assert.NotNull(packages["C"]); Assert.NotNull(packages["D"]); } [Fact] public void ResolveDependencyForInstallCircularReferenceWithDifferentVersionOfPackageReferenceThrows() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); IPackage packageA10 = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageA15 = PackageUtility.CreatePackage("A", "1.5", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageB10 = PackageUtility.CreatePackage("B", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("A", "[1.5]") }); sourceRepository.AddPackage(packageA10); sourceRepository.AddPackage(packageA15); sourceRepository.AddPackage(packageB10); IPackageOperationResolver resolver = new InstallWalker(localRepository, sourceRepository, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageA10), "Circular dependency detected 'A 1.0 => B 1.0 => A 1.5'."); } [Fact] public void ResolvingDependencyForUpdateWithConflictingDependents() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); // A 1.0 -> B [1.0] IPackage A10 = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "[1.0]") }, content: new[] { "a1" }); // A 2.0 -> B (any version) IPackage A20 = PackageUtility.CreatePackage("A", "2.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }, content: new[] { "a2" }); IPackage B10 = PackageUtility.CreatePackage("B", "1.0", content: new[] { "b1" }); IPackage B101 = PackageUtility.CreatePackage("B", "1.0.1", content: new[] { "b101" }); IPackage B20 = PackageUtility.CreatePackage("B", "2.0", content: new[] { "a2" }); localRepository.Add(A10); localRepository.Add(B10); sourceRepository.AddPackage(A10); sourceRepository.AddPackage(A20); sourceRepository.AddPackage(B10); sourceRepository.AddPackage(B101); sourceRepository.AddPackage(B20); IPackageOperationResolver resolver = new UpdateWalker(localRepository, sourceRepository, new DependentsWalker(localRepository), NullConstraintProvider.Instance, NullLogger.Instance, updateDependencies: true, allowPrereleaseVersions: false) { AcceptedTargets = PackageTargets.Project }; // Act var packages = resolver.ResolveOperations(B101).ToList(); // Assert Assert.Equal(4, packages.Count); AssertOperation("A", "1.0", PackageAction.Uninstall, packages[0]); AssertOperation("B", "1.0", PackageAction.Uninstall, packages[1]); AssertOperation("A", "2.0", PackageAction.Install, packages[2]); AssertOperation("B", "1.0.1", PackageAction.Install, packages[3]); } [Fact] public void ResolvingDependencyForUpdateThatHasAnUnsatisfiedConstraint() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); var constraintProvider = new Mock<IPackageConstraintProvider>(); constraintProvider.Setup(m => m.GetConstraint("B")).Returns(VersionUtility.ParseVersionSpec("[1.4]")); constraintProvider.Setup(m => m.Source).Returns("foo"); IPackage A10 = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "1.5") }); IPackage A20 = PackageUtility.CreatePackage("A", "2.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "2.0") }); IPackage B15 = PackageUtility.CreatePackage("B", "1.5"); IPackage B20 = PackageUtility.CreatePackage("B", "2.0"); localRepository.Add(A10); localRepository.Add(B15); sourceRepository.AddPackage(A10); sourceRepository.AddPackage(A20); sourceRepository.AddPackage(B15); sourceRepository.AddPackage(B20); IPackageOperationResolver resolver = new InstallWalker(localRepository, sourceRepository, constraintProvider.Object, null, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(A20), "Unable to resolve dependency 'B (\u2265 2.0)'.'B' has an additional constraint (= 1.4) defined in foo."); } [Fact] public void ResolveDependencyForInstallPackageWithDependencyThatDoesntMeetMinimumVersionThrows() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "1.5") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.4"); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageB); IPackageOperationResolver resolver = new InstallWalker(localRepository, sourceRepository, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageA), "Unable to resolve dependency 'B (\u2265 1.5)'."); } [Fact] public void ResolveDependencyForInstallPackageWithDependencyThatDoesntMeetExactVersionThrows() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "[1.5]") }); sourceRepository.AddPackage(packageA); IPackage packageB = PackageUtility.CreatePackage("B", "1.4"); sourceRepository.AddPackage(packageB); IPackageOperationResolver resolver = new InstallWalker(localRepository, sourceRepository, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageA), "Unable to resolve dependency 'B (= 1.5)'."); } [Fact] public void ResolveOperationsForInstallSameDependencyAtDifferentLevelsInGraph() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); // A1 -> B1, C1 IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "1.0"), PackageDependency.CreateDependency("C", "1.0") }); // B1 IPackage packageB = PackageUtility.CreatePackage("B", "1.0"); // C1 -> B1, D1 IPackage packageC = PackageUtility.CreatePackage("C", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "1.0"), PackageDependency.CreateDependency("D", "1.0") }); // D1 -> B1 IPackage packageD = PackageUtility.CreatePackage("D", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "1.0") }); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageB); sourceRepository.AddPackage(packageC); sourceRepository.AddPackage(packageD); IPackageOperationResolver resolver = new InstallWalker(localRepository, sourceRepository, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false); // Act & Assert var packages = resolver.ResolveOperations(packageA).ToList(); Assert.Equal(4, packages.Count); Assert.Equal("B", packages[0].Package.Id); Assert.Equal("D", packages[1].Package.Id); Assert.Equal("C", packages[2].Package.Id); Assert.Equal("A", packages[3].Package.Id); } [Fact] public void ResolveDependenciesForInstallSameDependencyAtDifferentLevelsInGraphDuringUpdate() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); // A1 -> B1, C1 IPackage packageA = PackageUtility.CreatePackage("A", "1.0", content: new[] { "A1" }, dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "1.0"), PackageDependency.CreateDependency("C", "1.0") }); // B1 IPackage packageB = PackageUtility.CreatePackage("B", "1.0", new[] { "B1" }); // C1 -> B1, D1 IPackage packageC = PackageUtility.CreatePackage("C", "1.0", content: new[] { "C1" }, dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "1.0"), PackageDependency.CreateDependency("D", "1.0") }); // D1 -> B1 IPackage packageD = PackageUtility.CreatePackage("D", "1.0", content: new[] { "A1" }, dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "1.0") }); // A2 -> B2, C2 IPackage packageA2 = PackageUtility.CreatePackage("A", "2.0", content: new[] { "A2" }, dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "2.0"), PackageDependency.CreateDependency("C", "2.0") }); // B2 IPackage packageB2 = PackageUtility.CreatePackage("B", "2.0", new[] { "B2" }); // C2 -> B2, D2 IPackage packageC2 = PackageUtility.CreatePackage("C", "2.0", content: new[] { "C2" }, dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "2.0"), PackageDependency.CreateDependency("D", "2.0") }); // D2 -> B2 IPackage packageD2 = PackageUtility.CreatePackage("D", "2.0", content: new[] { "D2" }, dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "2.0") }); sourceRepository.AddPackage(packageA); sourceRepository.AddPackage(packageB); sourceRepository.AddPackage(packageC); sourceRepository.AddPackage(packageD); sourceRepository.AddPackage(packageA2); sourceRepository.AddPackage(packageB2); sourceRepository.AddPackage(packageC2); sourceRepository.AddPackage(packageD2); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); localRepository.AddPackage(packageC); localRepository.AddPackage(packageD); IPackageOperationResolver resolver = new UpdateWalker(localRepository, sourceRepository, new DependentsWalker(localRepository), NullConstraintProvider.Instance, NullLogger.Instance, updateDependencies: true, allowPrereleaseVersions: false); var operations = resolver.ResolveOperations(packageA2).ToList(); Assert.Equal(8, operations.Count); AssertOperation("A", "1.0", PackageAction.Uninstall, operations[0]); AssertOperation("C", "1.0", PackageAction.Uninstall, operations[1]); AssertOperation("D", "1.0", PackageAction.Uninstall, operations[2]); AssertOperation("B", "1.0", PackageAction.Uninstall, operations[3]); AssertOperation("B", "2.0", PackageAction.Install, operations[4]); AssertOperation("D", "2.0", PackageAction.Install, operations[5]); AssertOperation("C", "2.0", PackageAction.Install, operations[6]); AssertOperation("A", "2.0", PackageAction.Install, operations[7]); } [Fact] public void ResolveDependenciesForInstallPackageWithDependencyReturnsPackageAndDependency() { // Arrange var localRepository = new MockPackageRepository(); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0"); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); IPackageOperationResolver resolver = new UninstallWalker(localRepository, new DependentsWalker(localRepository), NullLogger.Instance, removeDependencies: true, forceRemove: false); // Act var packages = resolver.ResolveOperations(packageA) .ToDictionary(p => p.Package.Id); // Assert Assert.Equal(2, packages.Count); Assert.NotNull(packages["A"]); Assert.NotNull(packages["B"]); } [Fact] public void ResolveDependenciesForUninstallPackageWithDependentThrows() { // Arrange var localRepository = new MockPackageRepository(); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0"); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); IPackageOperationResolver resolver = new UninstallWalker(localRepository, new DependentsWalker(localRepository), NullLogger.Instance, removeDependencies: false, forceRemove: false); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageB), "Unable to uninstall 'B 1.0' because 'A 1.0' depends on it."); } [Fact] public void ResolveDependenciesForUninstallPackageWithDependentAndRemoveDependenciesThrows() { // Arrange var localRepository = new MockPackageRepository(); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0"); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); IPackageOperationResolver resolver = new UninstallWalker(localRepository, new DependentsWalker(localRepository), NullLogger.Instance, removeDependencies: true, forceRemove: false); // Act & Assert ExceptionAssert.Throws<InvalidOperationException>(() => resolver.ResolveOperations(packageB), "Unable to uninstall 'B 1.0' because 'A 1.0' depends on it."); } [Fact] public void ResolveDependenciesForUninstallPackageWithDependentAndForceReturnsPackage() { // Arrange var localRepository = new MockPackageRepository(); IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0"); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); IPackageOperationResolver resolver = new UninstallWalker(localRepository, new DependentsWalker(localRepository), NullLogger.Instance, removeDependencies: false, forceRemove: true); // Act var packages = resolver.ResolveOperations(packageB) .ToDictionary(p => p.Package.Id); // Assert Assert.Equal(1, packages.Count); Assert.NotNull(packages["B"]); } [Fact] public void ResolveDependenciesForUninstallPackageWithRemoveDependenciesExcludesDependencyIfDependencyInUse() { // Arrange var localRepository = new MockPackageRepository(); // A 1.0 -> [B, C] IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B"), new PackageDependency("C") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0"); IPackage packageC = PackageUtility.CreatePackage("C", "1.0"); // D -> [C] IPackage packageD = PackageUtility.CreatePackage("D", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("C"), }); localRepository.AddPackage(packageD); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); localRepository.AddPackage(packageC); IPackageOperationResolver resolver = new UninstallWalker(localRepository, new DependentsWalker(localRepository), NullLogger.Instance, removeDependencies: true, forceRemove: false); // Act var packages = resolver.ResolveOperations(packageA) .ToDictionary(p => p.Package.Id); // Assert Assert.Equal(2, packages.Count); Assert.NotNull(packages["A"]); Assert.NotNull(packages["B"]); } [Fact] public void ResolveDependenciesForUninstallPackageWithRemoveDependenciesSetAndForceReturnsAllDependencies() { // Arrange var localRepository = new MockPackageRepository(); // A 1.0 -> [B, C] IPackage packageA = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B"), new PackageDependency("C") }); IPackage packageB = PackageUtility.CreatePackage("B", "1.0"); IPackage packageC = PackageUtility.CreatePackage("C", "1.0"); // D -> [C] IPackage packageD = PackageUtility.CreatePackage("D", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("C"), }); localRepository.AddPackage(packageA); localRepository.AddPackage(packageB); localRepository.AddPackage(packageC); localRepository.AddPackage(packageD); IPackageOperationResolver resolver = new UninstallWalker(localRepository, new DependentsWalker(localRepository), NullLogger.Instance, removeDependencies: true, forceRemove: true); // Act var packages = resolver.ResolveOperations(packageA) .ToDictionary(p => p.Package.Id); // Assert Assert.NotNull(packages["A"]); Assert.NotNull(packages["B"]); Assert.NotNull(packages["C"]); } [Fact] public void ProjectInstallWalkerIgnoresSolutionLevelPackages() { // Arrange var localRepository = new MockPackageRepository(); var sourceRepository = new MockPackageRepository(); IPackage projectPackage = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { PackageDependency.CreateDependency("B", "[1.5]") }, content: new[] { "content" }); sourceRepository.AddPackage(projectPackage); IPackage toolsPackage = PackageUtility.CreatePackage("B", "1.5", tools: new[] { "init.ps1" }); sourceRepository.AddPackage(toolsPackage); IPackageOperationResolver resolver = new UpdateWalker(localRepository, sourceRepository, new DependentsWalker(localRepository), NullConstraintProvider.Instance, NullLogger.Instance, updateDependencies: true, allowPrereleaseVersions: false) { AcceptedTargets = PackageTargets.Project }; // Act var packages = resolver.ResolveOperations(projectPackage) .ToDictionary(p => p.Package.Id); // Assert Assert.Equal(1, packages.Count); Assert.NotNull(packages["A"]); } [Fact] public void AfterPackageWalkMetaPackageIsClassifiedTheSameAsDependencies() { // Arrange var mockRepository = new MockPackageRepository(); var walker = new TestWalker(mockRepository); IPackage metaPackage = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B"), new PackageDependency("C") }); IPackage projectPackageA = PackageUtility.CreatePackage("B", "1.0", content: new[] { "contentB" }); IPackage projectPackageB = PackageUtility.CreatePackage("C", "1.0", content: new[] { "contentC" }); mockRepository.AddPackage(projectPackageA); mockRepository.AddPackage(projectPackageB); Assert.Equal(PackageTargets.None, walker.GetPackageInfo(metaPackage).Target); // Act walker.Walk(metaPackage); // Assert Assert.Equal(PackageTargets.Project, walker.GetPackageInfo(metaPackage).Target); } [Fact] public void LocalizedIntelliSenseFileCountsAsProjectTarget() { // Arrange var mockRepository = new MockPackageRepository(); var walker = new TestWalker(mockRepository); IPackage runtimePackage = PackageUtility.CreatePackage("A", "1.0", assemblyReferences: new[] { @"lib\A.dll", @"lib\A.xml" }); IPackage satellitePackage = PackageUtility.CreatePackage("A.fr-fr", "1.0", dependencies: new[] { new PackageDependency("A") }, satelliteAssemblies: new[] { @"lib\fr-fr\A.xml" }, language: "fr-fr"); mockRepository.AddPackage(runtimePackage); mockRepository.AddPackage(satellitePackage); // Act walker.Walk(satellitePackage); // Assert Assert.Equal(PackageTargets.Project, walker.GetPackageInfo(satellitePackage).Target); } [Fact] public void AfterPackageWalkSatellitePackageIsClassifiedTheSameAsDependencies() { // Arrange var mockRepository = new MockPackageRepository(); var walker = new TestWalker(mockRepository); IPackage runtimePackage = PackageUtility.CreatePackage("A", "1.0", assemblyReferences: new[] { @"lib\A.dll" }); IPackage satellitePackage = PackageUtility.CreatePackage("A.fr-fr", "1.0", dependencies: new[] { new PackageDependency("A") }, satelliteAssemblies: new[] { @"lib\fr-fr\A.resources.dll" }, language: "fr-fr"); mockRepository.AddPackage(runtimePackage); mockRepository.AddPackage(satellitePackage); // Act walker.Walk(satellitePackage); // Assert Assert.Equal(PackageTargets.Project, walker.GetPackageInfo(satellitePackage).Target); } [Fact] public void MetaPackageWithMixedTargetsThrows() { // Arrange var mockRepository = new MockPackageRepository(); var walker = new TestWalker(mockRepository); IPackage metaPackage = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B"), new PackageDependency("C") }); IPackage projectPackageA = PackageUtility.CreatePackage("B", "1.0", content: new[] { "contentB" }); IPackage solutionPackage = PackageUtility.CreatePackage("C", "1.0", tools: new[] { "tools" }); mockRepository.AddPackage(projectPackageA); mockRepository.AddPackage(solutionPackage); // Act && Assert ExceptionAssert.Throws<InvalidOperationException>(() => walker.Walk(metaPackage), "Child dependencies of dependency only packages cannot mix external and project packages."); } [Fact] public void ExternalPackagesThatDepdendOnProjectLevelPackagesThrows() { // Arrange var mockRepository = new MockPackageRepository(); var walker = new TestWalker(mockRepository); IPackage solutionPackage = PackageUtility.CreatePackage("A", "1.0", dependencies: new List<PackageDependency> { new PackageDependency("B") }, tools: new[] { "install.ps1" }); IPackage projectPackageA = PackageUtility.CreatePackage("B", "1.0", content: new[] { "contentB" }); mockRepository.AddPackage(projectPackageA); mockRepository.AddPackage(solutionPackage); // Act && Assert ExceptionAssert.Throws<InvalidOperationException>(() => walker.Walk(solutionPackage), "External packages cannot depend on packages that target projects."); } [Fact] public void InstallWalkerResolvesLowestMajorAndMinorVersionButHighestBuildAndRevisionForDependencies() { // Arrange // A 1.0 -> B 1.0 // B 1.0 -> C 1.1 // C 1.1 -> D 1.0 var A10 = PackageUtility.CreatePackage("A", "1.0", dependencies: new[] { PackageDependency.CreateDependency("B", "1.0") }); var repository = new MockPackageRepository() { PackageUtility.CreatePackage("B", "2.0", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }), PackageUtility.CreatePackage("B", "1.0", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }), PackageUtility.CreatePackage("B", "1.0.1"), A10, PackageUtility.CreatePackage("D", "2.0"), PackageUtility.CreatePackage("C", "1.1.3", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }), PackageUtility.CreatePackage("C", "1.1.1", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }), PackageUtility.CreatePackage("C", "1.5.1", dependencies: new[] { PackageDependency.CreateDependency("D", "1.0") }), PackageUtility.CreatePackage("B", "1.0.9", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }), PackageUtility.CreatePackage("B", "1.1", dependencies: new[] { PackageDependency.CreateDependency("C", "1.1") }) }; IPackageOperationResolver resolver = new InstallWalker(new MockPackageRepository(), repository, NullLogger.Instance, ignoreDependencies: false, allowPrereleaseVersions: false); // Act var packages = resolver.ResolveOperations(A10).ToList(); // Assert Assert.Equal(4, packages.Count); Assert.Equal("D", packages[0].Package.Id); Assert.Equal(new SemanticVersion("2.0"), packages[0].Package.Version); Assert.Equal("C", packages[1].Package.Id); Assert.Equal(new SemanticVersion("1.1.3"), packages[1].Package.Version); Assert.Equal("B", packages[2].Package.Id); Assert.Equal(new SemanticVersion("1.0.9"), packages[2].Package.Version); Assert.Equal("A", packages[3].Package.Id); Assert.Equal(new SemanticVersion("1.0"), packages[3].Package.Version); } private void AssertOperation(string expectedId, string expectedVersion, PackageAction expectedAction, PackageOperation operation) { Assert.Equal(expectedAction, operation.Action); Assert.Equal(expectedId, operation.Package.Id); Assert.Equal(new SemanticVersion(expectedVersion), operation.Package.Version); } private class TestWalker : PackageWalker { private readonly IPackageRepository _repository; public TestWalker(IPackageRepository repository) { _repository = repository; } protected override IPackage ResolveDependency(PackageDependency dependency) { return _repository.ResolveDependency(dependency, AllowPrereleaseVersions, false); } } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.dll // Description: The core libraries for the DotSpatial project. // // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 2/20/2008 3:42:21 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Linq; using DotSpatial.Data; using DotSpatial.Projections; using DotSpatial.Serialization; namespace DotSpatial.Symbology { /// <summary> /// A raster layer describes using a single raster, and the primary application will be using this as a texture. /// </summary> public class RasterLayer : Layer, IRasterLayer { #region Fields [Serialize("Symbolizer", ConstructorArgumentIndex = 1)] private IRasterSymbolizer _symbolizer; private IGetBitmap _bitmapGetter; /// <summary> /// Gets or sets maximum number of cells which can be stored in memory. /// By default it is 8000 * 8000. /// </summary> public static int MaxCellsInMemory = 8000 * 8000; #endregion #region Constructors /// <summary> /// Opens the specified fileName using the layer manager. /// </summary> /// <param name="fileName"></param> /// <param name="symbolizer"></param> public RasterLayer(string fileName, IRasterSymbolizer symbolizer) { DataSet = DataManager.DefaultDataManager.OpenRaster(fileName); Symbolizer = symbolizer; } /// <summary> /// Opens the specified fileName and automatically creates a raster that can be used by this raster layer. /// </summary> /// <param name="fileName">The string fileName to use in order to open the file</param> /// <param name="inProgressHandler">The progress handler to show progress messages</param> public RasterLayer(string fileName, IProgressHandler inProgressHandler) : base(inProgressHandler) { DataSet = DataManager.DefaultDataManager.OpenRaster(fileName, true, inProgressHandler); Symbolizer = new RasterSymbolizer(this); } /// <summary> /// Creates a new raster layer using the progress handler defined on the DefaultLayerManager /// </summary> /// <param name="raster">The raster to create this layer for</param> public RasterLayer(IRaster raster) { DataSet = raster; Symbolizer = new RasterSymbolizer(this); } /// <summary> /// Creates a new instance of RasterLayer /// </summary> /// <param name="raster">The Raster</param> /// <param name="inProgressHandler">The Progress handler for any status updates</param> public RasterLayer(IRaster raster, IProgressHandler inProgressHandler) : base(inProgressHandler) { DataSet = raster; Symbolizer = new RasterSymbolizer(this); } #endregion #region Methods /// <summary> /// This only updates the bitmap representation of the raster. It does not write to a file unless /// the file is too large to fit in memory, in which case it will update the pyramid image. /// </summary> public void WriteBitmap() { WriteBitmap(ProgressHandler); } /// <summary> /// This only updates the bitmap representation of this raster. This can be overridden, but currently /// uses the default implementation. /// </summary> /// <param name="progressHandler">An implementation of IProgressHandler to receive status messages</param> public virtual void WriteBitmap(IProgressHandler progressHandler) { DefaultWriteBitmap(progressHandler); } /// <summary> /// Creates a bmp texture and saves it to the specified fileName. /// </summary> /// <param name="fileName">The string fileName to write to</param> /// <param name="bandType">The color band type.</param> public void ExportBitmap(string fileName, ImageBandType bandType) { ExportBitmap(fileName, DataSet.ProgressHandler, bandType); } /// <summary> /// Creates a new filename and saves the content from the current BitmapGetter to the /// file format. This relies on the DataManager and will only be successful for /// formats supported by the write format possibility. This will not update this raster /// </summary> /// <param name="fileName">The string fileName to write to</param> /// <param name="progressHandler">The progress handler for creating a new bitmap.</param> /// <param name="bandType">The band type ot use.</param> public void ExportBitmap(string fileName, IProgressHandler progressHandler, ImageBandType bandType) { int rows = DataSet.NumRowsInFile; int cols = DataSet.NumColumnsInFile; IImageData result = DataManager.DefaultDataManager.CreateImage(fileName, rows, cols, false, progressHandler, bandType); int numBlocks = 1; const int maxRc = 8000 * 8000; if (rows * cols > maxRc) { numBlocks = Convert.ToInt32(Math.Ceiling(maxRc / (double)cols)); } int blockRows = maxRc / cols; ProjectionHelper ph = new ProjectionHelper(DataSet.Extent, new Rectangle(0, 0, cols, rows)); for (int iblock = 0; iblock < numBlocks; iblock++) { int rowCount = blockRows; if (iblock == numBlocks - 1) rowCount = rows - blockRows * iblock; Rectangle r = new Rectangle(0, iblock * blockRows, cols, rowCount); Bitmap block = BitmapGetter.GetBitmap(ph.PixelToProj(r), r); result.WriteBlock(block, 0, iblock * blockRows); } } /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing) { BitmapGetter = null; RasterLayerActions = null; Symbolizer = null; } base.Dispose(disposing); } /// <summary> /// Render the full raster block by block, and then save the values to the pyramid raster. /// This will probably be nasty and time consuming, but what can you do. /// </summary> /// <param name="pyrFile"></param> /// <param name="progressHandler"></param> /// <returns></returns> public IImageData CreatePyramidImage(string pyrFile, IProgressHandler progressHandler) { PyramidImage py = new PyramidImage(pyrFile, DataSet.Bounds); int width = DataSet.Bounds.NumColumns; int blockHeight = 32000000 / width; if (blockHeight > DataSet.Bounds.NumRows) blockHeight = DataSet.Bounds.NumRows; int numBlocks = (int)Math.Ceiling(DataSet.Bounds.NumRows / (double)blockHeight); int count = DataSet.NumRows; if (_symbolizer.ShadedRelief.IsUsed) { count = count * 2; } ProgressMeter pm = new ProgressMeter(progressHandler, "Creating Pyramids", count); PerformanceCounter pcRemaining = new PerformanceCounter("Memory", "Available Bytes"); Process proc = Process.GetCurrentProcess(); long mem; long freeRAM; for (int j = 0; j < numBlocks; j++) { int h = blockHeight; if (j == numBlocks - 1) { h = DataSet.Bounds.NumRows - j * blockHeight; } mem = proc.PrivateMemorySize64 / 1000000; freeRAM = Convert.ToInt64(pcRemaining.NextValue()) / 1000000; Debug.WriteLine("Memory before: " + mem + ", " + freeRAM + " remaining."); pm.BaseMessage = "Reading from Raster"; pm.SendProgress(); using (IRaster r = DataSet.ReadBlock(0, j * blockHeight, width, h)) { byte[] vals = new byte[h * 4 * width]; r.DrawToBitmap(Symbolizer, vals, width * 4, pm); pm.BaseMessage = "Writing to Pyramids"; pm.SendProgress(); py.WriteWindow(vals, j * blockHeight, 0, h, width, 0); Symbolizer.HillShade = null; } mem = proc.PrivateMemorySize64 / 1000000; freeRAM = Convert.ToInt64(pcRemaining.NextValue()) / 1000000; Debug.WriteLine("Memory after: " + mem + "Mb | " + freeRAM + " remaining Mb."); } pm.Reset(); py.ProgressHandler = ProgressHandler; py.CreatePyramids(); py.WriteHeader(pyrFile); return py; } /// <summary> /// This does not have to be used to work, but provides a default implementation for writing bitmap, /// and will be used by the MapRasterLayer class during file creation. /// </summary> /// <param name="progressHandler"></param> protected void DefaultWriteBitmap(IProgressHandler progressHandler) { if ((long)DataSet.NumRowsInFile * DataSet.NumColumnsInFile > MaxCellsInMemory) { // For huge images, assume that GDAL or something was needed anyway, // and we would rather avoid having to re-create the pyramids if there is any chance // that the old values will work ok. string pyrFile = Path.ChangeExtension(DataSet.Filename, ".mwi"); BitmapGetter = CreatePyramidImage(pyrFile, progressHandler); OnItemChanged(this); return; } Bitmap bmp = new Bitmap(DataSet.NumColumns, DataSet.NumRows, PixelFormat.Format32bppArgb); if (_symbolizer.DrapeVectorLayers == false) { // Generate the colorscheme, modified by hillshading if that hillshading is used all in one pass DataSet.DrawToBitmap(Symbolizer, bmp, progressHandler); } else { // work backwards. when we get to this layer do the colorscheme. // First, use this raster and its colorscheme to drop the background DataSet.PaintColorSchemeToBitmap(Symbolizer, bmp, progressHandler); // Set up a graphics object with a transformation pre-set so drawing a geographic coordinate // will draw to the correct location on the bitmap Graphics g = Graphics.FromImage(bmp); g.SmoothingMode = SmoothingMode.AntiAlias; Extent extents = DataSet.Extent; Rectangle target = new Rectangle(0, 0, bmp.Width, bmp.Height); ImageProjection ip = new ImageProjection(extents, target); // Cycle through each layer, and as long as it is not this layer, draw the bmp foreach (ILegendItem layer in GetParentItem().LegendItems) { // Temporarily I am only interested in doing this for vector datasets IFeatureLayer fl = layer as IFeatureLayer; if (fl == null) continue; fl.DrawSnapShot(g, ip); } if (Symbolizer.ShadedRelief.IsUsed) { // After we have drawn the underlying texture, apply a hillshade if it is requested Symbolizer.PaintShadingToBitmap(bmp, progressHandler); } } InRamImage image = new InRamImage(bmp); image.Bounds = DataSet.Bounds.Copy(); BitmapGetter = image; Symbolizer.Validate(); OnInvalidate(this, EventArgs.Empty); OnItemChanged(); } /// <summary> /// Handles the situation for exporting the layer as a new source. /// </summary> protected override void OnExportData() { var rla = RasterLayerActions; if (rla != null) { rla.ExportData(DataSet); } } #endregion #region properties /// <summary> /// Gets or sets custom actions for RasterLayer /// </summary> [Browsable(false)] public IRasterLayerActions RasterLayerActions { get; set; } /// <summary> /// Gets or sets the boundaries of the raster. /// </summary> /// <remarks> /// [Editor(typeof(Forms.PropertyGridEditor), typeof(UITypeEditor))] /// [TypeConverter(typeof(Forms.GeneralTypeConverter))] /// </remarks> [Category("Bounds")] [Description("Shows more detail about the geographic position of the raster.")] public virtual IRasterBounds Bounds { get { if (DataSet != null) return DataSet.Bounds; return null; } set { if (DataSet != null) DataSet.Bounds = value; if (BitmapGetter != null) BitmapGetter.Bounds = value; } } /// <summary> /// This is what the raster layer uses to retrieve a bitmap representing the specified /// extent. This could later be redesigned to generate the bitmap on the fly, but I think /// that that would be slow, so caching is probably better. /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public IGetBitmap BitmapGetter { get { return _bitmapGetter; } set { if (value == _bitmapGetter) return; if (_bitmapGetter != null) _bitmapGetter.Dispose(); // Dispose previous bitmapGetter to avoid memory leaks _bitmapGetter = value; } } /// <summary> /// Gets the geographic height of the cells for this raster (North-South) /// </summary> [Category("Raster Properties"), Description("The geographic width of each cell in this raster.")] public virtual double CellHeight { get { if (DataSet != null) return DataSet.CellHeight; return 0; } } /// <summary> /// Gets the geographic width of the cells for this raster (East-West) /// </summary> [Category("Raster Properties"), Description("The geographic width of each cell in this raster.")] public virtual double CellWidth { get { if (DataSet != null) return DataSet.CellWidth; return 0; } } /// <summary> /// Gets or sets whether this should appear as checked in the legend. This is also how the /// layer will /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override bool Checked { get { if (_symbolizer == null) return true; return _symbolizer.IsVisible; } set { if (_symbolizer == null) return; if (value != _symbolizer.IsVisible) { IsVisible = value; } } } /// <summary> /// Gets the data type of the values in this raster. /// </summary> [Category("Raster Properties"), Description("The numeric data type of the values in this raster.")] public Type DataType { get { if (DataSet != null) return DataSet.DataType; return null; } } /// <summary> /// Gets the eastern boundary of this raster. /// </summary> [Category("Bounds"), Description("The East boundary of this raster.")] public virtual double East { get { return (DataSet != null && DataSet.Bounds != null) ? DataSet.Bounds.Right() : 0; } } /// <summary> /// This is a conversion factor that is required in order to convert the elevation units into the same units as the geospatial projection for the latitude and logitude values of the grid. /// </summary> [DisplayName(@"Elevation Factor"), Category("Symbology"), Description("This is a conversion factor that is required in order to convert the elevation units into the same units as the geospatial projection for the latitude and logitude values of the grid.")] public virtual float ElevationFactor { get { if (_symbolizer != null) return _symbolizer.ElevationFactor; return 0f; } set { if (_symbolizer == null) return; _symbolizer.ElevationFactor = value; } } /// <summary> /// Obtains an envelope /// </summary> /// <returns></returns> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override Extent Extent { get { if (DataSet != null) return DataSet.Extent; return null; } } /// <summary> /// Gets the exaggeration beyond normal elevation values. A value of 1 is normal elevation, /// a value of 0 would be flat, while a value of 2 would be twice the normal elevation. /// This applies to the three-dimensional rendering and is not related to the shaded relief pattern /// created by the texture. /// </summary> [DisplayName(@"Extrusion")] [Category("Symbology")] [Description("the exaggeration beyond normal elevation values. A value of 1 is normal elevation, a value of 0 would be flat, while a value of 2 would be twice the normal elevation. This applies to the three-dimensional rendering and is not related to the shaded relief pattern created by the texture.")] public virtual float Extrusion { get { if (_symbolizer != null) return _symbolizer.Extrusion; return 0f; } set { if (_symbolizer == null) return; _symbolizer.Extrusion = value; } } /// <summary> /// Gets the file name where this raster is saved. /// </summary> [Category("Raster Properties")] [Description("The file name of this raster.")] public string Filename { get { if (DataSet != null) return DataSet.Filename; return "No Raster Specified"; } } /// <summary> /// Gets the relative file path to where this raster is saved. /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Serialize("FilePath", ConstructorArgumentIndex = 0)] public string FilePath { get { if (DataSet != null) return DataSet.FilePath; return null; } } /// <summary> /// If this is false, then the drawing function will not render anything. /// Warning! This will also prevent any execution of calculations that take place /// as part of the drawing methods and will also abort the drawing methods of any /// sub-members to this IRenderable. /// </summary> [Category("Symbology")] [DisplayName(@"Visible")] [Description("Controls whether or not this layer will be drawn.")] public override bool IsVisible { get { if (_symbolizer != null) return _symbolizer.IsVisible; return false; } set { if (_symbolizer == null) return; _symbolizer.IsVisible = value; OnVisibleChanged(this, EventArgs.Empty); } } /// <summary> /// Gets or sets the complete list of legend items contained within this legend item /// </summary> [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public override IEnumerable<ILegendItem> LegendItems { get { if (_symbolizer == null) return null; return _symbolizer.Scheme.Categories.Cast<ILegendItem>(); } } /// <summary> /// The text that will appear in the legend /// </summary> [Category("Appearance"), DisplayName(@"Caption"), Description(" The text that will appear in the legend")] public override string LegendText { get { if (base.LegendText == null && DataSet != null) base.LegendText = DataSet.Name; return base.LegendText; } set { base.LegendText = value; } } /// <summary> /// Gets the maximum value of this raster. If this is an elevation raster, this is also the top. /// </summary> [Category("Raster Properties"), Description("The maximum value of this raster. If this is an elevation raster, this is also the top.")] public virtual double Maximum { get { if (DataSet != null) return DataSet.Maximum; return 0; } } /// <summary> /// Gets the minimum value of this raster. If this is an elevation raster, this is also the bottom. /// </summary> [Category("Raster Properties"), Description("The minimum value of this raster. If this is an elevation raster, this is also the bottom.")] public virtual double Minimum { get { if (DataSet != null) return DataSet.Minimum; return 0; } } /// <summary> /// Gets the value that is used when no actual data exists for the specified location. /// </summary> [Category("Raster Properties"), Description("The value that is used when no actual data exists for the specified location.")] public virtual double NoDataValue { get { if (DataSet != null) return DataSet.NoDataValue; return 0; } } /// <summary> /// Gets the northern boundary of this raster. /// </summary> [Category("Bounds"), Description("The North boundary of this raster.")] public virtual double North { get { if (DataSet != null && DataSet.Bounds != null) return DataSet.Bounds.Top(); return 0; } } /// <summary> /// Gets the number of bands in this raster. /// </summary> [DisplayName(@"Number of Bands"), Category("Raster Properties"), Description("Gets the number of bands in this raster.")] public virtual int NumBands { get { if (DataSet != null) return DataSet.NumBands; return 0; } } /// <summary> /// Gets the number of columns in this raster. /// </summary> [DisplayName(@"Number of Columns"), Category("Raster Properties"), Description("Gets the number of columns in this raster.")] public virtual int NumColumns { get { if (DataSet != null) return DataSet.NumColumns; return 0; } } /// <summary> /// Gets the number of rows in this raster. /// </summary> [DisplayName(@"Number of Rows"), Category("Raster Properties"), Description("Gets the number of rows in this raster.")] public virtual int NumRows { get { if (DataSet != null) return DataSet.NumRows; return 0; } } /// <summary> /// Gets or sets the underlying dataset /// </summary> /// <remarks> /// [TypeConverter(typeof(Forms.GeneralTypeConverter))] /// [Editor(typeof(Forms.PropertyGridEditor), typeof(UITypeEditor))] /// </remarks> [Category("Data")] [DisplayName(@"Raster Properties")] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description("This gives access to more comprehensive information about the underlying data.")] [ShallowCopy] [Browsable(false)] public new IRaster DataSet { get { return base.DataSet as IRaster; } set { base.DataSet = value; } } /// <summary> /// Gets or sets the collection of symbolzier properties to use for this raster. /// [Editor(typeof(Forms.RasterColorSchemeEditor), typeof(UITypeEditor))] /// [TypeConverter(typeof(Forms.GeneralTypeConverter))] /// </summary> [Category("Symbology")] [DisplayName(@"Color Scheme")] [Browsable(false)] [ShallowCopy] public IRasterSymbolizer Symbolizer { get { return _symbolizer; } set { if (_symbolizer == value) return; if (_symbolizer != null) _symbolizer.ColorSchemeUpdated -= _symbolizer_SymbologyUpdated; _symbolizer = value; if (_symbolizer == null) return; _symbolizer.ParentLayer = this; _symbolizer.Scheme.SetParentItem(this); _symbolizer.ColorSchemeUpdated += _symbolizer_SymbologyUpdated; } } /// <summary> /// Gets the southern boundary of this raster. /// </summary> [Category("Bounds"), Description("The South boundary of this raster.")] public virtual double South { get { if (DataSet != null && DataSet.Bounds != null) return DataSet.Bounds.Bottom(); return 0; } } /// <summary> /// Gets the western boundary of this raster. /// </summary> [Category("Bounds"), Description("The West boundary of this raster.")] public virtual double West { get { if (DataSet != null && DataSet.Bounds != null) return DataSet.Bounds.Left(); return 0; } } #endregion /// <summary> /// Occurs when this member should raise the shared event to show the property dialog for this raster layer. /// </summary> /// <param name="e"></param> protected override void OnShowProperties(HandledEventArgs e) { var rla = RasterLayerActions; if (rla != null) rla.ShowProperties(this); e.Handled = true; } #region Event Handlers /// <summary> /// Reprojects the dataset for this layer. /// </summary> /// <param name="targetProjection">The target projection to use.</param> public override void Reproject(ProjectionInfo targetProjection) { if (DataSet != null) { DataSet.Reproject(targetProjection); if (BitmapGetter != null) { double[] aff = new double[6]; Array.Copy(DataSet.Bounds.AffineCoefficients, aff, 6); BitmapGetter.Bounds.AffineCoefficients = aff; } } } private void _symbolizer_SymbologyUpdated(object sender, EventArgs e) { OnItemChanged(); } #endregion #region Nested Class : ProjectionHelper private class ProjectionHelper : IProj { /// <summary> /// Initializes a new instance of the ProjectionHelper class. /// </summary> /// <param name="geographicExtents">The geographic extents to project to and from.</param> /// <param name="viewRectangle">The view rectangle in pixels to transform with.</param> public ProjectionHelper(Extent geographicExtents, Rectangle viewRectangle) { GeographicExtents = geographicExtents; ImageRectangle = viewRectangle; } /// <summary> /// Gets or sets the geographic extent to use. /// </summary> public Extent GeographicExtents { get; set; } /// <summary> /// Gets or sets the rectangular pixel region to use. /// </summary> public Rectangle ImageRectangle { get; set; } } #endregion } }
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using VirtualObjects.CodeGenerators; using VirtualObjects.Config; using VirtualObjects.Connections; using VirtualObjects.Core; using VirtualObjects.CRUD; using VirtualObjects.EntityProvider; using VirtualObjects.Exceptions; using VirtualObjects.Programability; using VirtualObjects.Queries; using VirtualObjects.Queries.Execution; using VirtualObjects.Queries.Formatters; using VirtualObjects.Queries.Mapping; using VirtualObjects.Queries.Translation; namespace VirtualObjects { class ModulesConfiguration : IModulesConfiguration { private SessionConfiguration _configuration; public ModulesConfiguration(SessionConfiguration configuration, IDbConnectionProvider connectionProvider) { InternalInitialize(configuration); _configuration.ConnectionProvider = connectionProvider; Initialize(configuration); } public ModulesConfiguration(SessionConfiguration configuration, string connectionProvider) { InternalInitialize(configuration); _configuration.ConnectionProvider = new NamedDbConnectionProvider(connectionProvider); Initialize(_configuration); } public ModulesConfiguration(SessionConfiguration configuration) { InternalInitialize(configuration); Initialize(configuration ?? new SessionConfiguration()); } private void InternalInitialize(SessionConfiguration configuration) { _configuration = configuration ?? new SessionConfiguration(); _configuration.Initialize(); _configuration.ConfigureMappingBuilder(_configuration.TranslationConfigurationBuilder); } private void Initialize(SessionConfiguration configuration) { ConnectionProvider = configuration.ConnectionProvider ?? new NamedDbConnectionProvider(); Logger = configuration.Logger ?? new TextWriterStub(); Formmater = configuration.Formatter ?? new SqlFormatter(configuration.FunctionTranslation); ConnectionManager = new Connection(ConnectionProvider, Logger, new SqlProgramability()); EntityBag = new HybridEntityBag(new EntityBag()); EntityProvider = new EntityProviderComposite( new IEntityProvider[] { new EntityModelProvider(), new DynamicTypeProvider(), new CollectionTypeEntityProvider() }); EntityMapper = new EntityInfoModelMapper(); EntitiesMapper = new EntityModelEntitiesMapper(); OperationsProvider = new OperationsProvider(Formmater, EntityMapper, EntityProvider); TranslationConfiguration = configuration.TranslationConfigurationBuilder.Build(); EntityInfoCodeGeneratorFactory = new EntityInfoCodeGeneratorFactory(EntityBag, TranslationConfiguration, configuration); Mapper = new Mapper(EntityBag, TranslationConfiguration, OperationsProvider, EntityInfoCodeGeneratorFactory); SessionContext = new SessionContext { Connection = ConnectionManager, Map = Mapper.Map, Mapper = Mapper }; Translator = new CachingTranslator(Formmater, Mapper, EntityBag, configuration); QueryExecutor = new CompositeExecutor( new IQueryExecutor[] { new CountQueryExecutor(Translator), new SingleQueryExecutor(EntitiesMapper, Translator), new QueryExecutor(EntitiesMapper, Translator) }); QueryProvider = new QueryProvider(QueryExecutor, SessionContext, Translator); SessionContext.QueryProvider = QueryProvider; Session = new InternalSession(SessionContext); } public IQueryExecutor QueryExecutor { get; set; } public EntityInfoCodeGeneratorFactory EntityInfoCodeGeneratorFactory { get; set; } public ITranslationConfiguration TranslationConfiguration { get; set; } public IEntityProvider EntityProvider { get; set; } public EntityInfoModelMapper EntityMapper { get; set; } public IFormatter Formmater { get; set; } public OperationsProvider OperationsProvider { get; set; } public HybridEntityBag EntityBag { get; set; } public Mapper Mapper { get; set; } public TextWriter Logger { get; set; } public IDbConnectionProvider ConnectionProvider { get; set; } public ISession Session { get; private set; } public IConnection ConnectionManager { get; private set; } public IQueryTranslator Translator { get; private set; } public IQueryProvider QueryProvider { get; private set; } public SessionContext SessionContext { get; private set; } public IEntitiesMapper EntitiesMapper { get; private set; } } interface IModulesConfiguration { ISession Session { get; } IConnection ConnectionManager { get; } IQueryTranslator Translator { get; } IQueryProvider QueryProvider { get; } SessionContext SessionContext { get; } IEntitiesMapper EntitiesMapper { get; } } /// <summary> /// /// </summary> public class Session : ISession { internal ISession InternalSession { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="Session"/> class. /// </summary> public Session() : this(configuration: null, connectionName: null) { } /// <summary> /// Gets the connection string. /// </summary> /// <value> /// The connection string. /// </value> public String ConnectionString { get { return ((InternalSession) InternalSession).Context.Connection.ConnectionString; } } /// <summary> /// Initializes a new instance of the <see cref="Session"/> class. /// </summary> /// <param name="configuration">The configuration.</param> /// <param name="connectionProvider">The connection provider.</param> public Session(SessionConfiguration configuration = null, IDbConnectionProvider connectionProvider = null) : this(new ModulesConfiguration(configuration, connectionProvider)) { } /// <summary> /// Initializes a new instance of the <see cref="Session"/> class. /// </summary> /// <param name="configuration">The configuration.</param> /// <param name="connectionName">Name of the connection.</param> public Session(SessionConfiguration configuration = null, String connectionName = null) : this(new ModulesConfiguration(configuration, connectionName)) { } /// <summary> /// Initializes a new instance of the <see cref="Session"/> class. /// </summary> /// <param name="configuration">The configuration.</param> public Session(SessionConfiguration configuration) : this(new ModulesConfiguration(configuration)) { } /// <summary> /// Initializes a new instance of the <see cref="Session"/> class. /// </summary> /// <param name="container">The container.</param> internal Session(IModulesConfiguration container) { InternalSession = container.Session; } /// <summary> /// Gets the connection. /// </summary> /// <value> /// The connection. /// </value> public IDbConnection Connection { get { return InternalSession.Connection; } } /// <summary> /// Gets all entities of TEntity type. /// </summary> /// <typeparam name="TEntity">The type of the entity.</typeparam> /// <returns></returns> public IQueryable<TEntity> GetAll<TEntity>() where TEntity : class, new() { return InternalSession.GetAll<TEntity>(); } /// <summary> /// Gets the raw data. /// </summary> /// <param name="query">The query.</param> /// <returns></returns> public IDataReader GetRawData(string query) { return InternalSession.GetRawData(query); } /// <summary> /// Gets the entity by its ID. /// </summary> /// <typeparam name="TEntity">The type of the entity.</typeparam> /// <param name="entity">The entity.</param> /// <returns></returns> public TEntity GetById<TEntity>(TEntity entity) where TEntity : class, new() { return InternalSession.GetById(entity); } /// <summary> /// Gets how many entities existe of the given TEntity type. /// </summary> /// <typeparam name="TEntity">The type of the entity.</typeparam> /// <returns></returns> public int Count<TEntity>() { return InternalSession.Count<TEntity>(); } /// <summary> /// Inserts the specified entity. /// </summary> /// <typeparam name="TEntity">The type of the entity.</typeparam> /// <param name="entity">The entity.</param> /// <returns></returns> public TEntity Insert<TEntity>(TEntity entity) where TEntity : class, new() { return InternalSession.Insert(entity); } /// <summary> /// Updates the specified entity. /// </summary> /// <typeparam name="TEntity">The type of the entity.</typeparam> /// <param name="entity">The entity.</param> /// <returns></returns> public TEntity Update<TEntity>(TEntity entity) where TEntity : class, new() { return InternalSession.Update(entity); } /// <summary> /// Deletes the specified entity. /// </summary> /// <typeparam name="TEntity">The type of the entity.</typeparam> /// <param name="entity">The entity.</param> /// <returns></returns> public bool Delete<TEntity>(TEntity entity) where TEntity : class, new() { return InternalSession.Delete(entity); } /// <summary> /// Begins the transaction. /// </summary> /// <param name="isolation"></param> /// <returns></returns> public ITransaction BeginTransaction(IsolationLevel isolation = IsolationLevel.Unspecified) { return InternalSession.BeginTransaction(isolation); } /// <summary> /// Executes the store procedure. /// </summary> /// <param name="storeProcedure">The store procedure.</param> /// <param name="args">The arguments.</param> /// <returns></returns> public int ExecuteStoreProcedure(string storeProcedure, IEnumerable<KeyValuePair<string, object>> args) { return InternalSession.ExecuteStoreProcedure(storeProcedure, args); } #region IDisposable Members private bool _disposed; /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if ( !_disposed ) { if ( disposing ) { InternalSession.Dispose(); } InternalSession = null; _disposed = true; } } #endregion } /// <summary> /// A session that will connect to an excel file. /// Default Provider: System.Data.OleDb /// ConnectionString : Provider=Microsoft.ACE.OLEDB.12.0;Data Source='{0}';Extended Properties='Excel 12.0;HDR=YES;IMEX=1;'; /// </summary> public class ExcelSession : Session { /// <summary> /// /// </summary> public enum Extension { /// <summary> /// The XLS /// </summary> Xls, /// <summary> /// The XLSX /// </summary> Xlsx, } static readonly IDictionary<String, String> Masks = new Dictionary<String, String>(); static ExcelSession() { Masks.Add(Extension.Xls.ToString().ToLower(), "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='{0}';Extended Properties='Excel 8.0;HDR=YES;'"); Masks.Add(Extension.Xlsx.ToString().ToLower(), "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='{0}';Extended Properties='Excel 12.0;HDR=YES;'"); } /// <summary> /// Initializes a new instance of the <see cref="ExcelSession" /> class. /// </summary> /// <param name="filename">The filename.</param> /// <param name="configuration"></param> public ExcelSession(string filename, SessionConfiguration configuration = null) : base(PrepareConfiguration(configuration), new DbConnectionProvider("System.Data.OleDb", BuildConnectionString(filename.ToLower()))) { } private static SessionConfiguration PrepareConfiguration(SessionConfiguration configuration) { if (configuration == null) { configuration = new SessionConfiguration(); } configuration.Formatter = new ExcelFormatter(configuration.FunctionTranslation); return configuration; } private static String BuildConnectionString(String filename) { try { return String.Format(Masks[ParseExtension(filename)], filename); } catch ( Exception ex ) { throw new VirtualObjectsException(Errors.Excel_UnableToCreateConnectionString, new { FileName = filename }, ex); } } private static String ParseExtension(String filename) { return filename.Substring(filename.LastIndexOf('.') + 1); } } }
// <copyright file="FileSystemTreeCollection.cs" company="Fubar Development Junker"> // Copyright (c) Fubar Development Junker. All rights reserved. // </copyright> using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using FubarDev.WebDavServer.FileSystem; using FubarDev.WebDavServer.Tests.Support.ServiceBuilders; using Microsoft.Extensions.DependencyInjection; using Xunit; namespace FubarDev.WebDavServer.Tests.FileSystem { public abstract class FileSystemTreeCollection<T> : IClassFixture<T>, IDisposable where T : class, IFileSystemServices { private readonly IServiceScope _serviceScope; protected FileSystemTreeCollection(T fsServices) { var serviceScopeFactory = fsServices.ServiceProvider.GetRequiredService<IServiceScopeFactory>(); _serviceScope = serviceScopeFactory.CreateScope(); FileSystem = _serviceScope.ServiceProvider.GetRequiredService<IFileSystem>(); } public IFileSystem FileSystem { get; } [Fact] public async Task Empty() { var ct = CancellationToken.None; var root = await FileSystem.Root.ConfigureAwait(false); var rootNode = await root.GetNodeAsync(int.MaxValue, ct).ConfigureAwait(false); Assert.Same(root, rootNode.Collection); Assert.Equal(0, rootNode.Documents.Count); Assert.Equal(0, rootNode.Nodes.Count); } [Fact] public async Task SingleEmptyDirectory() { var ct = CancellationToken.None; var root = await FileSystem.Root.ConfigureAwait(false); await root.CreateCollectionAsync("test1", ct).ConfigureAwait(false); var rootNode = await root.GetNodeAsync(int.MaxValue, ct).ConfigureAwait(false); Assert.Same(root, rootNode.Collection); Assert.Equal(0, rootNode.Documents.Count); Assert.Collection( rootNode.Nodes, node => { Assert.NotNull(node.Collection); Assert.Equal("test1", node.Collection.Name); Assert.Same(rootNode.Collection, node.Collection.Parent); Assert.Equal(0, node.Documents.Count); Assert.Equal(0, node.Nodes.Count); }); } [Fact] public async Task TwoNestedEmptyDirectories() { var ct = CancellationToken.None; var root = await FileSystem.Root.ConfigureAwait(false); var test1 = await root.CreateCollectionAsync("test1", ct).ConfigureAwait(false); await test1.CreateCollectionAsync("test1.1", ct).ConfigureAwait(false); var rootNode = await root.GetNodeAsync(int.MaxValue, ct).ConfigureAwait(false); Assert.Same(root, rootNode.Collection); Assert.Equal(0, rootNode.Documents.Count); Assert.Collection( rootNode.Nodes, node1 => { Assert.NotNull(node1.Collection); Assert.Equal("test1", node1.Collection.Name); Assert.Same(rootNode.Collection, node1.Collection.Parent); Assert.Equal(0, node1.Documents.Count); Assert.Collection( node1.Nodes, node2 => { Assert.NotNull(node2.Collection); Assert.Equal("test1.1", node2.Collection.Name); Assert.Same(node1.Collection, node2.Collection.Parent); Assert.Equal(0, node2.Documents.Count); Assert.Equal(0, node2.Nodes.Count); }); }); } [Fact] public async Task TwoEmptyDirectories() { var ct = CancellationToken.None; var root = await FileSystem.Root.ConfigureAwait(false); await root.CreateCollectionAsync("test1", ct).ConfigureAwait(false); await root.CreateCollectionAsync("test2", ct).ConfigureAwait(false); var rootNode = await root.GetNodeAsync(int.MaxValue, ct).ConfigureAwait(false); Assert.Same(root, rootNode.Collection); Assert.Equal(0, rootNode.Documents.Count); Assert.Collection( rootNode.Nodes.OrderBy(n => n.Name), node => { Assert.NotNull(node.Collection); Assert.Equal("test1", node.Collection.Name); Assert.Same(rootNode.Collection, node.Collection.Parent); Assert.Equal(0, node.Documents.Count); Assert.Equal(0, node.Nodes.Count); }, node => { Assert.NotNull(node.Collection); Assert.Equal("test2", node.Collection.Name); Assert.Same(rootNode.Collection, node.Collection.Parent); Assert.Equal(0, node.Documents.Count); Assert.Equal(0, node.Nodes.Count); }); } [Fact] public async Task TwoDirectoriesWithOneEmptyChildDirectory() { var ct = CancellationToken.None; var root = await FileSystem.Root.ConfigureAwait(false); var test1 = await root.CreateCollectionAsync("test1", ct).ConfigureAwait(false); await test1.CreateCollectionAsync("test1.1", ct).ConfigureAwait(false); var test2 = await root.CreateCollectionAsync("test2", ct).ConfigureAwait(false); await test2.CreateCollectionAsync("test2.1", ct).ConfigureAwait(false); var rootNode = await root.GetNodeAsync(int.MaxValue, ct).ConfigureAwait(false); Assert.Same(root, rootNode.Collection); Assert.Equal(0, rootNode.Documents.Count); Assert.Collection( rootNode.Nodes.OrderBy(n => n.Name), node1 => { Assert.NotNull(node1.Collection); Assert.Equal("test1", node1.Collection.Name); Assert.Same(rootNode.Collection, node1.Collection.Parent); Assert.Equal(0, node1.Documents.Count); Assert.Collection( node1.Nodes, node2 => { Assert.NotNull(node2.Collection); Assert.Equal("test1.1", node2.Collection.Name); Assert.Same(node1.Collection, node2.Collection.Parent); Assert.Equal(0, node2.Documents.Count); Assert.Equal(0, node2.Nodes.Count); }); }, node1 => { Assert.NotNull(node1.Collection); Assert.Equal("test2", node1.Collection.Name); Assert.Same(rootNode.Collection, node1.Collection.Parent); Assert.Equal(0, node1.Documents.Count); Assert.Collection( node1.Nodes, node2 => { Assert.NotNull(node2.Collection); Assert.Equal("test2.1", node2.Collection.Name); Assert.Same(node1.Collection, node2.Collection.Parent); Assert.Equal(0, node2.Documents.Count); Assert.Equal(0, node2.Nodes.Count); }); }); } [Fact] public async Task TwoDirectoriesWithTwoEmptyChildDirectories() { var ct = CancellationToken.None; var root = await FileSystem.Root.ConfigureAwait(false); var test1 = await root.CreateCollectionAsync("test1", ct).ConfigureAwait(false); await test1.CreateCollectionAsync("test1.1", ct).ConfigureAwait(false); await test1.CreateCollectionAsync("test1.2", ct).ConfigureAwait(false); var test2 = await root.CreateCollectionAsync("test2", ct).ConfigureAwait(false); await test2.CreateCollectionAsync("test2.1", ct).ConfigureAwait(false); await test2.CreateCollectionAsync("test2.2", ct).ConfigureAwait(false); var rootNode = await root.GetNodeAsync(int.MaxValue, ct).ConfigureAwait(false); Assert.Same(root, rootNode.Collection); Assert.Equal(0, rootNode.Documents.Count); Assert.Collection( rootNode.Nodes.OrderBy(n => n.Name), node1 => { Assert.NotNull(node1.Collection); Assert.Equal("test1", node1.Collection.Name); Assert.Same(rootNode.Collection, node1.Collection.Parent); Assert.Equal(0, node1.Documents.Count); Assert.Collection( node1.Nodes.OrderBy(n => n.Name), node2 => { Assert.NotNull(node2.Collection); Assert.Equal("test1.1", node2.Collection.Name); Assert.Same(node1.Collection, node2.Collection.Parent); Assert.Equal(0, node2.Documents.Count); Assert.Equal(0, node2.Nodes.Count); }, node2 => { Assert.NotNull(node2.Collection); Assert.Equal("test1.2", node2.Collection.Name); Assert.Same(node1.Collection, node2.Collection.Parent); Assert.Equal(0, node2.Documents.Count); Assert.Equal(0, node2.Nodes.Count); }); }, node1 => { Assert.NotNull(node1.Collection); Assert.Equal("test2", node1.Collection.Name); Assert.Same(rootNode.Collection, node1.Collection.Parent); Assert.Equal(0, node1.Documents.Count); Assert.Collection( node1.Nodes.OrderBy(n => n.Name), node2 => { Assert.NotNull(node2.Collection); Assert.Equal("test2.1", node2.Collection.Name); Assert.Same(node1.Collection, node2.Collection.Parent); Assert.Equal(0, node2.Documents.Count); Assert.Equal(0, node2.Nodes.Count); }, node2 => { Assert.NotNull(node2.Collection); Assert.Equal("test2.2", node2.Collection.Name); Assert.Same(node1.Collection, node2.Collection.Parent); Assert.Equal(0, node2.Documents.Count); Assert.Equal(0, node2.Nodes.Count); }); }); } [Fact] public async Task TwoDirectoriesWithTwoEmptyFiles() { var ct = CancellationToken.None; var root = await FileSystem.Root.ConfigureAwait(false); var test1 = await root.CreateCollectionAsync("test1", ct).ConfigureAwait(false); await test1.CreateDocumentAsync("test1.1", ct).ConfigureAwait(false); await test1.CreateDocumentAsync("test1.2", ct).ConfigureAwait(false); var test2 = await root.CreateCollectionAsync("test2", ct).ConfigureAwait(false); await test2.CreateDocumentAsync("test2.1", ct).ConfigureAwait(false); await test2.CreateDocumentAsync("test2.2", ct).ConfigureAwait(false); var rootNode = await root.GetNodeAsync(int.MaxValue, ct).ConfigureAwait(false); Assert.Same(root, rootNode.Collection); Assert.Equal(0, rootNode.Documents.Count); Assert.Collection( rootNode.Nodes.OrderBy(n => n.Name), node1 => { Assert.NotNull(node1.Collection); Assert.Equal("test1", node1.Collection.Name); Assert.Same(rootNode.Collection, node1.Collection.Parent); Assert.Equal(0, node1.Nodes.Count); Assert.Collection( node1.Documents.OrderBy(n => n.Name), document => { Assert.Equal("test1.1", document.Name); Assert.Same(node1.Collection, document.Parent); }, document => { Assert.Equal("test1.2", document.Name); Assert.Same(node1.Collection, document.Parent); }); }, node1 => { Assert.NotNull(node1.Collection); Assert.Equal("test2", node1.Collection.Name); Assert.Same(rootNode.Collection, node1.Collection.Parent); Assert.Equal(0, node1.Nodes.Count); Assert.Collection( node1.Documents.OrderBy(n => n.Name), document => { Assert.Equal("test2.1", document.Name); Assert.Same(node1.Collection, document.Parent); }, document => { Assert.Equal("test2.2", document.Name); Assert.Same(node1.Collection, document.Parent); }); }); } [Fact] public async Task TwoDirectoriesWithTwoEmptyFilesAndEmptyDirectory() { var ct = CancellationToken.None; var root = await FileSystem.Root.ConfigureAwait(false); var test1 = await root.CreateCollectionAsync("test1", ct).ConfigureAwait(false); await test1.CreateDocumentAsync("test1.1", ct).ConfigureAwait(false); await test1.CreateCollectionAsync("test1.2", ct).ConfigureAwait(false); await test1.CreateDocumentAsync("test1.3", ct).ConfigureAwait(false); var test2 = await root.CreateCollectionAsync("test2", ct).ConfigureAwait(false); await test2.CreateDocumentAsync("test2.1", ct).ConfigureAwait(false); await test2.CreateCollectionAsync("test2.2", ct).ConfigureAwait(false); await test2.CreateDocumentAsync("test2.3", ct).ConfigureAwait(false); var rootNode = await root.GetNodeAsync(int.MaxValue, ct).ConfigureAwait(false); Assert.Same(root, rootNode.Collection); Assert.Equal(0, rootNode.Documents.Count); Assert.Collection( rootNode.Nodes.OrderBy(n => n.Name), node1 => { Assert.NotNull(node1.Collection); Assert.Equal("test1", node1.Collection.Name); Assert.Same(rootNode.Collection, node1.Collection.Parent); Assert.Collection( node1.Nodes.OrderBy(n => n.Name), node2 => { Assert.NotNull(node2.Collection); Assert.Equal("test1.2", node2.Collection.Name); Assert.Same(node1.Collection, node2.Collection.Parent); Assert.Equal(0, node2.Documents.Count); Assert.Equal(0, node2.Nodes.Count); }); Assert.Collection( node1.Documents.OrderBy(n => n.Name), document => { Assert.Equal("test1.1", document.Name); Assert.Same(node1.Collection, document.Parent); }, document => { Assert.Equal("test1.3", document.Name); Assert.Same(node1.Collection, document.Parent); }); }, node1 => { Assert.NotNull(node1.Collection); Assert.Equal("test2", node1.Collection.Name); Assert.Same(rootNode.Collection, node1.Collection.Parent); Assert.Collection( node1.Nodes.OrderBy(n => n.Name), node2 => { Assert.NotNull(node2.Collection); Assert.Equal("test2.2", node2.Collection.Name); Assert.Same(node1.Collection, node2.Collection.Parent); Assert.Equal(0, node2.Documents.Count); Assert.Equal(0, node2.Nodes.Count); }); Assert.Collection( node1.Documents.OrderBy(n => n.Name), document => { Assert.Equal("test2.1", document.Name); Assert.Same(node1.Collection, document.Parent); }, document => { Assert.Equal("test2.3", document.Name); Assert.Same(node1.Collection, document.Parent); }); }); } public void Dispose() { _serviceScope.Dispose(); } } }
// #define SENSOR_DEBUG #if UNITY_IPHONE || SENSOR_DEBUG using UnityEngine; class SensorDeviceIPhone : SensorDeviceUnity { protected override void AwakeDevice() { // get all sensor informations (including whether they are available) for (var i = 1; i <= Sensor.Count; i++) { // fill the sensor information array Type sensorType = (Type) i; Sensors[i] = new Sensor.Information( IsSensorAvailable(sensorType), GetMaximumRange(sensorType), GetMinDelay(sensorType), GetName(sensorType), GetPower(sensorType), GetResolution(sensorType), GetVendor(sensorType), GetVersion(sensorType), Description[i]); Sensors [i].gotFirstValue = true; } base.AwakeDevice(); } #region Internal Helpers private static bool IsSensorAvailable(Type idx) { switch (idx) { case Type.Accelerometer: return SystemInfo.supportsAccelerometer; case Type.Orientation: case Type.MagneticField: case Type.MagneticFieldUncalibrated: return true; case Type.Gyroscope: case Type.Gravity: case Type.RotationVector: case Type.LinearAcceleration: case Type.GameRotationVector: case Type.GeomagneticRotationVector: case Type.GyroscopeUncalibrated: //return SystemInfo.supportsGyroscope; return true; // this is iOS, always true case Type.Light: case Type.Pressure: case Type.Temperature: case Type.Proximity: case Type.RelativeHumidity: case Type.AmbientTemperature: case Type.SignificantMotion: case Type.StepDetector: case Type.StepCounter: default: return false; } } private static float GetMaximumRange(Type idx) { return -1; } private static int GetMinDelay(Type idx) { return -1; } private static string GetName(Type idx) { switch (idx) { #pragma warning disable 162 case Type.Accelerometer: return "Accelerometer"; break; case Type.MagneticField: return "MagneticField"; break; case Type.Orientation: return "Orientation"; break; case Type.Gyroscope: return "Gyroscope"; break; case Type.Light: return "Light"; break; case Type.Pressure: return "Pressure"; break; case Type.Temperature: return "Temperature"; break; case Type.Proximity: return "Proximity"; break; case Type.Gravity: return "Gravity"; break; case Type.LinearAcceleration: return "LinearAcceleration"; break; case Type.RotationVector: return "RotationVector"; break; case Type.RelativeHumidity: return "RelativeHumidity"; break; case Type.AmbientTemperature: return "AmbientTemperature"; break; case Type.MagneticFieldUncalibrated: return "MagneticFieldUncalibrated"; break; case Type.GameRotationVector: return "GameRotationVector"; break; case Type.GyroscopeUncalibrated: return "GyroscopeUncalibrated"; break; case Type.SignificantMotion: return "SignificantMotion"; break; case Type.StepDetector: return "StepDetector"; break; case Type.StepCounter: return "StepCounter"; break; case Type.GeomagneticRotationVector: return "GeomagneticRotationVector"; break; default: return "Unknown"; #pragma warning restore 162 } } private static float GetPower(Type idx) { return -1; } private static float GetResolution(Type idx) { return -1; } private static string GetVendor(Type idx) { return "Unknown"; } private static int GetVersion(Type idx) { return -1; } #endregion protected override bool ActivateDeviceSensor(Type sensorID, Sensor.Delay sensorSpeed) { switch (sensorID) { case Type.Accelerometer: Input.gyro.enabled = true; SetSensorOn(sensorID); return true; case Type.Orientation: case Type.MagneticField: case Type.MagneticFieldUncalibrated: Input.compass.enabled = true; SetSensorOn(sensorID); return true; case Type.Gyroscope: case Type.Gravity: case Type.RotationVector: case Type.LinearAcceleration: case Type.GameRotationVector: case Type.GeomagneticRotationVector: case Type.GyroscopeUncalibrated: Input.gyro.enabled = true; SetSensorOn(sensorID); return true; case Type.Light: case Type.Pressure: case Type.Temperature: case Type.Proximity: case Type.RelativeHumidity: case Type.AmbientTemperature: case Type.SignificantMotion: case Type.StepDetector: case Type.StepCounter: default: return base.ActivateDeviceSensor(sensorID, sensorSpeed); } } protected override bool DeactivateDeviceSensor(Type sensorID) { switch (sensorID) { case Type.Accelerometer: SetSensorOff(sensorID); return true; case Type.Orientation: case Type.MagneticField: case Type.MagneticFieldUncalibrated: SetSensorOff(sensorID); Input.compass.enabled = Sensors[(int)Type.Orientation].active || Sensors[(int)Type.MagneticField].active; return true; case Type.Gyroscope: case Type.Gravity: case Type.RotationVector: case Type.LinearAcceleration: case Type.GameRotationVector: case Type.GeomagneticRotationVector: case Type.GyroscopeUncalibrated: SetSensorOff(sensorID); Input.gyro.enabled = Sensors[(int)Type.Gyroscope].active || Sensors[(int)Type.Gravity].active || Sensors[(int)Type.RotationVector].active; return true; case Type.Light: case Type.Pressure: case Type.Temperature: case Type.Proximity: case Type.RelativeHumidity: case Type.AmbientTemperature: case Type.SignificantMotion: case Type.StepDetector: case Type.StepCounter: default: return base.DeactivateDeviceSensor(sensorID); } } Vector3 lastAcceleration; new Vector3 linearAcceleration; protected override Vector3 GetDeviceSensor(Type sensorID) { switch (sensorID) { case Type.Accelerometer: return Input.acceleration.normalized; case Type.Orientation: return new Vector3(Input.compass.magneticHeading, 0, 0); case Type.MagneticField: case Type.MagneticFieldUncalibrated: return Input.compass.rawVector; case Type.Gyroscope: case Type.RotationVector: case Type.GameRotationVector: case Type.GeomagneticRotationVector: return Input.gyro.attitude.eulerAngles; case Type.Gravity: return Input.gyro.gravity; case Type.LinearAcceleration: linearAcceleration = Input.acceleration - lastAcceleration; lastAcceleration = Input.acceleration; return linearAcceleration * 10; // hack because of lower values for iOS devices (why?) case Type.Light: case Type.Pressure: case Type.Temperature: case Type.Proximity: case Type.RelativeHumidity: case Type.AmbientTemperature: case Type.SignificantMotion: case Type.StepDetector: case Type.StepCounter: default: return base.GetDeviceSensor(sensorID); } } protected override Vector3 _getDeviceOrientation() { return Input.compass.rawVector; } protected override Sensor.SurfaceRotation GetSurfaceRotation() { switch (Input.deviceOrientation) { case DeviceOrientation.Portrait: return Sensor.SurfaceRotation.Rotation0; case DeviceOrientation.PortraitUpsideDown: return Sensor.SurfaceRotation.Rotation180; case DeviceOrientation.LandscapeLeft: return Sensor.SurfaceRotation.Rotation90; case DeviceOrientation.LandscapeRight: return Sensor.SurfaceRotation.Rotation270; default: return Sensor.SurfaceRotation.Rotation0; } } public Quaternion GetPreMult() { return preMult; } protected override Quaternion QuaternionFromDeviceRotationVector(Vector3 v) { CalculateRotations(); var r = preMult * Quaternion.Euler(v) * postMult; return r; } Quaternion preMult = Quaternion.identity; Quaternion postMult = Quaternion.identity; void CalculateRotations() { // Portrait devices if( UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPhone || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPhone3G || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPhone4 || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPhone4S #if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_5_0 || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPhone5 || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPhoneUnknown #endif #if UNITY_4_6 || UNITY_5_0 || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPhone5C || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPhone5S || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPhone6 || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPhone6Plus #endif || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPodTouch1Gen || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPodTouch2Gen || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPodTouch3Gen || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPodTouch4Gen #if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_5_0 || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPodTouch5Gen || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPodTouchUnknown #endif #if UNITY_5_1 || UNITY_5_2 || UNITY_5_3_OR_NEWER || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPhone6S || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPhone6SPlus || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPhoneSE1Gen || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPodTouch5Gen || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPodTouchUnknown || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPhoneUnknown #endif || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.Unknown ) { preMult = Quaternion.Euler(90,-90,0); // to be tested //if (Screen.orientation == ScreenOrientation.LandscapeLeft) { // postMult = Quaternion.Euler(0,0,90); //} else if (Screen.orientation == ScreenOrientation.LandscapeRight) { // postMult = Quaternion.Euler(0,0,270); //} else if (Screen.orientation == ScreenOrientation.Portrait) { postMult = Quaternion.Euler(0,0,180); //} else if (Screen.orientation == ScreenOrientation.PortraitUpsideDown) { // postMult = Quaternion.Euler(0,0,0); //} } // landscape devices else if( UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPad1Gen || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPad2Gen || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPad3Gen #if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_5_0 || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPad4Gen || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPadMini1Gen || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPadUnknown #endif #if UNITY_4_6 || UNITY_5_0 || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPadAir1 || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPadAir2 || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPadMini2Gen || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPadMini3Gen #endif #if UNITY_5_1 || UNITY_5_2 || UNITY_5_3_OR_NEWER || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPad4Gen || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPadMini4Gen || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPadPro1Gen || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPadPro10Inch1Gen #endif ) { preMult = Quaternion.Euler(90,0,90); // all the same (?) if (Screen.orientation == ScreenOrientation.LandscapeLeft) { postMult = Quaternion.Euler(0,0,180); } else if (Screen.orientation == ScreenOrientation.LandscapeRight) { postMult = Quaternion.Euler(0,0,180); } else if (Screen.orientation == ScreenOrientation.Portrait) { postMult = Quaternion.Euler(0,0,180); } else if (Screen.orientation == ScreenOrientation.PortraitUpsideDown) { postMult = Quaternion.Euler(0,0,180); } } } protected override void CompensateDeviceOrientation(ref Vector3 k) { switch (surfaceRotation) { case Sensor.SurfaceRotation.Rotation90: k.x += 90; break; case Sensor.SurfaceRotation.Rotation270: k.x -= 90; break; case Sensor.SurfaceRotation.Rotation180: k.x += 180; break; } } protected override ScreenOrientation ScreenOrientationDevice { get { if( UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPad1Gen || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPad2Gen || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPad3Gen #if UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6 || UNITY_5_0 || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPad4Gen || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPadMini1Gen || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPadUnknown #endif #if UNITY_4_6 || UNITY_5_0 || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPadAir1 || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPadAir2 || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPadMini2Gen || UnityEngine.iOS.Device.generation == UnityEngine.iOS.DeviceGeneration.iPadMini3Gen #endif ) return ScreenOrientation.LandscapeLeft; else return ScreenOrientation.Portrait; } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace Internal.TypeSystem { /// <summary> /// Represents the fundamental base type of all types within the type system. /// </summary> public abstract partial class TypeDesc : TypeSystemEntity { public static readonly TypeDesc[] EmptyTypes = new TypeDesc[0]; /// Inherited types are required to override, and should use the algorithms /// in TypeHashingAlgorithms in their implementation. public abstract override int GetHashCode(); public override bool Equals(Object o) { // Its only valid to compare two TypeDescs in the same context Debug.Assert(o == null || !(o is TypeDesc) || Object.ReferenceEquals(((TypeDesc)o).Context, this.Context)); return Object.ReferenceEquals(this, o); } #if DEBUG public static bool operator ==(TypeDesc left, TypeDesc right) { // Its only valid to compare two TypeDescs in the same context Debug.Assert(Object.ReferenceEquals(left, null) || Object.ReferenceEquals(right, null) || Object.ReferenceEquals(left.Context, right.Context)); return Object.ReferenceEquals(left, right); } public static bool operator !=(TypeDesc left, TypeDesc right) { // Its only valid to compare two TypeDescs in the same context Debug.Assert(Object.ReferenceEquals(left, null) || Object.ReferenceEquals(right, null) || Object.ReferenceEquals(left.Context, right.Context)); return !Object.ReferenceEquals(left, right); } #endif // The most frequently used type properties are cached here to avoid excesive virtual calls private TypeFlags _typeFlags; /// <summary> /// Gets the generic instantiation information of this type. /// For generic definitions, retrieves the generic parameters of the type. /// For generic instantiation, retrieves the generic arguments of the type. /// </summary> public virtual Instantiation Instantiation { get { return Instantiation.Empty; } } /// <summary> /// Gets a value indicating whether this type has a generic instantiation. /// This will be true for generic type instantiations and generic definitions. /// </summary> public bool HasInstantiation { get { return this.Instantiation.Length != 0; } } internal void SetWellKnownType(WellKnownType wellKnownType) { TypeFlags flags; switch (wellKnownType) { case WellKnownType.Void: case WellKnownType.Boolean: case WellKnownType.Char: case WellKnownType.SByte: case WellKnownType.Byte: case WellKnownType.Int16: case WellKnownType.UInt16: case WellKnownType.Int32: case WellKnownType.UInt32: case WellKnownType.Int64: case WellKnownType.UInt64: case WellKnownType.IntPtr: case WellKnownType.UIntPtr: case WellKnownType.Single: case WellKnownType.Double: flags = (TypeFlags)wellKnownType; break; case WellKnownType.ValueType: case WellKnownType.Enum: flags = TypeFlags.Class; break; case WellKnownType.Nullable: flags = TypeFlags.Nullable; break; case WellKnownType.Object: case WellKnownType.String: case WellKnownType.Array: case WellKnownType.MulticastDelegate: case WellKnownType.Exception: flags = TypeFlags.Class; break; case WellKnownType.RuntimeTypeHandle: case WellKnownType.RuntimeMethodHandle: case WellKnownType.RuntimeFieldHandle: case WellKnownType.TypedReference: case WellKnownType.ByReferenceOfT: flags = TypeFlags.ValueType; break; default: throw new ArgumentException(); } _typeFlags = flags; } protected abstract TypeFlags ComputeTypeFlags(TypeFlags mask); [MethodImpl(MethodImplOptions.NoInlining)] private TypeFlags InitializeTypeFlags(TypeFlags mask) { TypeFlags flags = ComputeTypeFlags(mask); if ((flags & mask) == 0) flags = Context.ComputeTypeFlags(this, flags, mask); Debug.Assert((flags & mask) != 0); _typeFlags |= flags; return flags & mask; } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected internal TypeFlags GetTypeFlags(TypeFlags mask) { TypeFlags flags = _typeFlags & mask; if (flags != 0) return flags; return InitializeTypeFlags(mask); } /// <summary> /// Retrieves the category of the type. This is one of the possible values of /// <see cref="TypeFlags"/> less than <see cref="TypeFlags.CategoryMask"/>. /// </summary> public TypeFlags Category { get { return GetTypeFlags(TypeFlags.CategoryMask); } } /// <summary> /// Gets a value indicating whether this type is an interface type. /// </summary> public bool IsInterface { get { return GetTypeFlags(TypeFlags.CategoryMask) == TypeFlags.Interface; } } /// <summary> /// Gets a value indicating whether this type is a value type (not a reference type). /// </summary> public bool IsValueType { get { return GetTypeFlags(TypeFlags.CategoryMask) < TypeFlags.Class; } } /// <summary> /// Gets a value indicating whether this is one of the primitive types (boolean, char, void, /// a floating point, or an integer type). /// </summary> public bool IsPrimitive { get { return GetTypeFlags(TypeFlags.CategoryMask) < TypeFlags.ValueType; } } /// <summary> /// Gets a value indicating whether this is an enum type. /// Access <see cref="UnderlyingType"/> to retrieve the underlying integral type. /// </summary> public bool IsEnum { get { return GetTypeFlags(TypeFlags.CategoryMask) == TypeFlags.Enum; } } /// <summary> /// Gets a value indicating whether this is a delegate type. /// </summary> public bool IsDelegate { get { var baseType = this.BaseType; return (baseType != null) ? baseType.IsWellKnownType(WellKnownType.MulticastDelegate) : false; } } /// <summary> /// Gets a value indicating whether this is System.Void type. /// </summary> public bool IsVoid { get { return GetTypeFlags(TypeFlags.CategoryMask) == TypeFlags.Void; } } /// <summary> /// Gets a value indicating whether this is System.String type. /// </summary> public bool IsString { get { return this.IsWellKnownType(WellKnownType.String); } } /// <summary> /// Gets a value indicating whether this is System.Object type. /// </summary> public bool IsObject { get { return this.IsWellKnownType(WellKnownType.Object); } } /// <summary> /// Gets a value indicating whether this is a generic definition, or /// an instance of System.Nullable`1. /// </summary> public bool IsNullable { get { return this.GetTypeDefinition().IsWellKnownType(WellKnownType.Nullable); } } /// <summary> /// Gets a value indicating whether this is a generic definition, or /// an instance of System.ByReference`1. /// </summary> public bool IsByReferenceOfT { get { return this.GetTypeDefinition().IsWellKnownType(WellKnownType.ByReferenceOfT); } } /// <summary> /// Gets a value indicating whether this is an array type (<see cref="ArrayType"/>). /// Note this will return true for both multidimensional array types and vector types. /// Use <see cref="IsSzArray"/> to check for vector types. /// </summary> public bool IsArray { get { return this is ArrayType; } } /// <summary> /// Gets a value indicating whether this is a vector type. A vector is a single-dimensional /// array with a zero lower bound. To check for arrays in general, use <see cref="IsArray"/>. /// </summary> public bool IsSzArray { get { return this.IsArray && ((ArrayType)this).IsSzArray; } } /// <summary> /// Gets a value indicating whether this is a non-vector array type. /// To check for arrays in general, use <see cref="IsArray"/>. /// </summary> public bool IsMdArray { get { return this.IsArray && ((ArrayType)this).IsMdArray; } } /// <summary> /// Gets a value indicating whether this is a managed pointer type (<see cref="ByRefType"/>). /// </summary> public bool IsByRef { get { return this is ByRefType; } } /// <summary> /// Gets a value indicating whether this is an unmanaged pointer type (<see cref="PointerType"/>). /// </summary> public bool IsPointer { get { return this is PointerType; } } /// <summary> /// Gets a value indicating whether this is an unmanaged function pointer type (<see cref="FunctionPointerType"/>). /// </summary> public bool IsFunctionPointer { get { return this is FunctionPointerType; } } /// <summary> /// Gets a value indicating whether this is a <see cref="SignatureTypeVariable"/> or <see cref="SignatureMethodVariable"/>. /// </summary> public bool IsSignatureVariable { get { return this is SignatureTypeVariable || this is SignatureMethodVariable; } } /// <summary> /// Gets a value indicating whether this is a generic parameter (<see cref="GenericParameterDesc"/>). /// </summary> public bool IsGenericParameter { get { return GetTypeFlags(TypeFlags.CategoryMask) == TypeFlags.GenericParameter; } } /// <summary> /// Gets a value indicating whether this is a pointer, byref, array, or szarray type, /// and can be used as a ParameterizedType. /// </summary> public bool IsParameterizedType { get { TypeFlags flags = GetTypeFlags(TypeFlags.CategoryMask); Debug.Assert((flags >= TypeFlags.Array && flags <= TypeFlags.Pointer) == (this is ParameterizedType)); return (flags >= TypeFlags.Array && flags <= TypeFlags.Pointer); } } /// <summary> /// Gets a value indicating whether this is a class, an interface, a value type, or a /// generic instance of one of them. /// </summary> public bool IsDefType { get { Debug.Assert(GetTypeFlags(TypeFlags.CategoryMask) <= TypeFlags.Interface == this is DefType); return GetTypeFlags(TypeFlags.CategoryMask) <= TypeFlags.Interface; } } /// <summary> /// Gets a value indicating whether locations of this type refer to an object on the GC heap. /// </summary> public bool IsGCPointer { get { TypeFlags category = GetTypeFlags(TypeFlags.CategoryMask); return category == TypeFlags.Class || category == TypeFlags.Array || category == TypeFlags.SzArray || category == TypeFlags.Interface; } } /// <summary> /// Gets the type from which this type derives from, or null if there's no such type. /// </summary> public virtual DefType BaseType { get { return null; } } /// <summary> /// Gets a value indicating whether this type has a base type. /// </summary> public bool HasBaseType { get { return BaseType != null; } } /// <summary> /// If this is an enum type, gets the underlying integral type of the enum type. /// For all other types, returns 'this'. /// </summary> public virtual TypeDesc UnderlyingType { get { if (!this.IsEnum) return this; // TODO: Cache the result? foreach (var field in this.GetFields()) { if (!field.IsStatic) return field.FieldType; } throw new TypeSystemException.TypeLoadException(ExceptionStringID.ClassLoadGeneral, this); } } /// <summary> /// Gets a value indicating whether this type has a class constructor method. /// Use <see cref="GetStaticConstructor"/> to retrieve it. /// </summary> public bool HasStaticConstructor { get { return (GetTypeFlags(TypeFlags.HasStaticConstructor | TypeFlags.HasStaticConstructorComputed) & TypeFlags.HasStaticConstructor) != 0; } } /// <summary> /// Gets all methods on this type defined within the type's metadata. /// This will not include methods injected by the type system context. /// </summary> public virtual IEnumerable<MethodDesc> GetMethods() { return MethodDesc.EmptyMethods; } /// <summary> /// Gets a named method on the type. This method only looks at methods defined /// in type's metadata. The <paramref name="signature"/> parameter can be null. /// If signature is not specified and there are multiple matches, the first one /// is returned. Returns null if method not found. /// </summary> // TODO: Substitutions, generics, modopts, ... public virtual MethodDesc GetMethod(string name, MethodSignature signature) { foreach (var method in GetMethods()) { if (method.Name == name) { if (signature == null || signature.Equals(method.Signature)) return method; } } return null; } /// <summary> /// Retrieves the class constructor method of this type. /// </summary> /// <returns></returns> public virtual MethodDesc GetStaticConstructor() { return null; } /// <summary> /// Retrieves the public parameterless constructor method of the type, or null if there isn't one /// or the type is abstract. /// </summary> public virtual MethodDesc GetDefaultConstructor() { return null; } /// <summary> /// Gets all fields on the type as defined in the metadata. /// </summary> public virtual IEnumerable<FieldDesc> GetFields() { return FieldDesc.EmptyFields; } /// <summary> /// Gets a named field on the type. Returns null if the field wasn't found. /// </summary> // TODO: Substitutions, generics, modopts, ... // TODO: field signature public virtual FieldDesc GetField(string name) { foreach (var field in GetFields()) { if (field.Name == name) return field; } return null; } public virtual TypeDesc InstantiateSignature(Instantiation typeInstantiation, Instantiation methodInstantiation) { return this; } /// <summary> /// Gets the definition of the type. If this is a generic type instance, /// this method strips the instantiation (E.g C&lt;int&gt; -> C&lt;T&gt;) /// </summary> public virtual TypeDesc GetTypeDefinition() { return this; } /// <summary> /// Gets a value indicating whether this is a type definition. Returns false /// if this is an instantiated generic type. /// </summary> public bool IsTypeDefinition { get { return GetTypeDefinition() == this; } } /// <summary> /// Determine if two types share the same type definition /// </summary> public bool HasSameTypeDefinition(TypeDesc otherType) { return GetTypeDefinition() == otherType.GetTypeDefinition(); } /// <summary> /// Gets a value indicating whether this type has a finalizer method. /// Use <see cref="GetFinalizer"/> to retrieve the method. /// </summary> public bool HasFinalizer { get { return (GetTypeFlags(TypeFlags.HasFinalizer | TypeFlags.HasFinalizerComputed) & TypeFlags.HasFinalizer) != 0; } } /// <summary> /// Gets the finalizer method (an override of the System.Object::Finalize method) /// if this type has one. Returns null if the type doesn't define one. /// </summary> public virtual MethodDesc GetFinalizer() { return null; } /// <summary> /// Gets a value indicating whether this type has generic variance (the definition of the type /// has a generic parameter that is co- or contravariant). /// </summary> public bool HasVariance { get { return (GetTypeFlags(TypeFlags.HasGenericVariance | TypeFlags.HasGenericVarianceComputed) & TypeFlags.HasGenericVariance) != 0; } } /// <summary> /// Gets a value indicating whether this type is an uninstantiated definition of a generic type. /// </summary> public bool IsGenericDefinition { get { return HasInstantiation && IsTypeDefinition; } } } }
// // CalendarMonthView.cs // // Converted to MonoTouch on 1/22/09 - Eduardo Scoz || http://escoz.com // Originally reated by Devin Ross on 7/28/09 - tapku.com || http://github.com/devinross/tapkulibrary // /* 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.Drawing; using CoreGraphics; using Foundation; using UIKit; using TodoApp.Helpers; namespace TodoApp.iOS.Controls { public delegate void DateSelected( DateTime date ); public delegate void MonthChanged( DateTime monthSelected ); public sealed class CalendarMonthView : UIView { private readonly int headerHeight; private readonly bool showHeader; private readonly float width; public DateTime CurrentMonthYear; public DateTime CurrentSelectedDate; public Func<DateTime, bool> IsDateAvailable; public Func<DateTime, bool> IsDayMarkedDelegate; public Action<DateTime> MonthChanged; public Action<DateTime> OnDateSelected; public Action<DateTime> OnFinishedDateSelection; public Action SwipedUp; private bool calendarIsLoaded; private MonthGridView monthGridView; private UIScrollView scrollView; #region Calendar view settings public int BoxHeight = 33; public int BoxWidth = 46; public float DayCellPadding = 1.5f; public int HorizontalPadding = 10; public int LinesCount = 6; public int VerticalPadding = 10; #endregion public CalendarMonthView( DateTime selectedDate, bool showHeader, float width = 320 ) { if (Math.Abs(width - 320) < 0.1) width = (float) UIScreen.MainScreen.Bounds.Size.Width; this.width = width; this.showHeader = showHeader; if (showHeader) headerHeight = 20; BoxWidth = Convert.ToInt32(Math.Ceiling(width/7)) - (int) Math.Ceiling(2*HorizontalPadding/7.0); int height = BoxHeight*LinesCount + 2*VerticalPadding + 10; // Calendar view frame (header, calendar, paddings). Frame = showHeader ? new RectangleF(0, 0, width, height + headerHeight) : new RectangleF(0, 0, width, height); BackgroundColor = UIColor.White; ClipsToBounds = true; CurrentSelectedDate = selectedDate; CurrentDate = DateTime.Now.Date; CurrentMonthYear = new DateTime(CurrentSelectedDate.Year, CurrentSelectedDate.Month, 1); // Actions on swipe. var swipeLeft = new UISwipeGestureRecognizer(MonthViewSwipedLeft) { Direction = UISwipeGestureRecognizerDirection.Left }; AddGestureRecognizer(swipeLeft); var swipeRight = new UISwipeGestureRecognizer(MonthViewSwipedRight) { Direction = UISwipeGestureRecognizerDirection.Right }; AddGestureRecognizer(swipeRight); var swipeUp = new UISwipeGestureRecognizer(MonthViewSwipedUp) { Direction = UISwipeGestureRecognizerDirection.Up }; AddGestureRecognizer(swipeUp); } private DateTime CurrentDate { get; set; } public void SetDate( DateTime newDate ) { bool right = true; CurrentSelectedDate = newDate; int monthsDiff = (newDate.Month - CurrentMonthYear.Month) + 12*(newDate.Year - CurrentMonthYear.Year); if (monthsDiff != 0) { if (monthsDiff < 0) { right = false; monthsDiff = -monthsDiff; } for (int i = 0; i < monthsDiff; i++) { MoveCalendarMonths(right, true); } } else { RebuildGrid(right, false); } } private void MonthViewSwipedUp( UISwipeGestureRecognizer ges ) { SwipedUp.Dispatch(); } private void MonthViewSwipedRight( UISwipeGestureRecognizer ges ) { // Move to previous month. MoveCalendarMonths(false, true); } private void MonthViewSwipedLeft( UISwipeGestureRecognizer ges ) { // Move to next month. MoveCalendarMonths(true, true); } /// <summary> /// Update calendar month view. /// </summary> public override void SetNeedsDisplay() { base.SetNeedsDisplay(); if (monthGridView != null) monthGridView.Update(); } public override void LayoutSubviews() { if (calendarIsLoaded) return; scrollView = new UIScrollView { ContentSize = new SizeF(width, 260), ScrollEnabled = false, Frame = new RectangleF(0, 16 + headerHeight, width, (float) Frame.Height - 16), BackgroundColor = UIColor.White }; LoadInitialGrids(); BackgroundColor = UIColor.Clear; AddSubview(scrollView); scrollView.AddSubview(monthGridView); calendarIsLoaded = true; } public void DeselectDate() { if (monthGridView != null) monthGridView.DeselectDayView(); } /// <summary> /// Change calendar month. /// </summary> /// <param name="right">Direction of the transition.</param> /// <param name="animated">Animate transition.</param> public void MoveCalendarMonths( bool right, bool animated ) { CurrentMonthYear = CurrentMonthYear.AddMonths(right ? 1 : -1); RebuildGrid(right, animated); } /// <summary> /// Rebuild month grid. /// </summary> /// <param name="right">Direction of the transition.</param> /// <param name="animated">Animate transition.</param> public void RebuildGrid( bool right, bool animated ) { UserInteractionEnabled = false; // Get new month grid. MonthGridView gridToMove = CreateNewGrid(CurrentMonthYear); nfloat pointsToMove = (right ? Frame.Width : -Frame.Width); gridToMove.Frame = new RectangleF(new PointF((float) pointsToMove, VerticalPadding/2.0f), (SizeF) gridToMove.Frame.Size); scrollView.AddSubview(gridToMove); if (animated) { BeginAnimations("changeMonth"); SetAnimationDuration(0.4); SetAnimationDelay(0.1); SetAnimationCurve(UIViewAnimationCurve.EaseInOut); } monthGridView.Center = new PointF((float) (monthGridView.Center.X - pointsToMove), (float) monthGridView.Center.Y); gridToMove.Center = new PointF((float) (gridToMove.Center.X - pointsToMove + HorizontalPadding), (float) gridToMove.Center.Y); monthGridView.Alpha = 0; SetNeedsDisplay(); if (animated) CommitAnimations(); monthGridView = gridToMove; UserInteractionEnabled = true; if (MonthChanged != null) MonthChanged(CurrentMonthYear); } /// <summary> /// Create new month grid. /// </summary> /// <param name="date">Needed month.</param> /// <returns>Return new calendar month grid view.</returns> private MonthGridView CreateNewGrid( DateTime date ) { var grid = new MonthGridView(this, date) {CurrentDate = CurrentDate}; grid.BuildGrid(); grid.Frame = new RectangleF(HorizontalPadding, VerticalPadding/2.0f, width - HorizontalPadding, (float) Frame.Height - 16); return grid; } private void LoadInitialGrids() { monthGridView = CreateNewGrid(CurrentMonthYear); } public override void Draw( CGRect rect ) { using (CGContext context = UIGraphics.GetCurrentContext()) { context.SetFillColor(UIColor.White.CGColor); context.FillRect(new RectangleF(0, 0, width, 18 + headerHeight)); } // Add day of week labels (monday, tuesday, etc). DrawDayLabels(rect); // Displat month header. if (showHeader) DrawMonthLabel(rect); } private void DrawMonthLabel( CGRect rect ) { var r = new RectangleF(new PointF(0, 2), new SizeF {Width = width - HorizontalPadding*2, Height = 42}); UIColor.DarkGray.SetColor(); new NSString(CurrentMonthYear.ToString("MMMM yyyy")).DrawString(r, UIFont.BoldSystemFontOfSize(16), UILineBreakMode.WordWrap, UITextAlignment.Center); } /// <summary> /// Draw day of week labels. /// </summary> private void DrawDayLabels( CGRect rect ) { // Font size. UIFont font = UIFont.BoldSystemFontOfSize(11); // Font color. UIColor.Gray.SetColor(); CGContext context = UIGraphics.GetCurrentContext(); context.SaveState(); int i = 0; foreach (string d in Enum.GetNames(typeof (DayOfWeek))) { new NSString(d.Substring(0, 3)).DrawString( new RectangleF(i*BoxWidth + HorizontalPadding, VerticalPadding/2.0f + headerHeight, BoxWidth, 10), font, UILineBreakMode.WordWrap, UITextAlignment.Center); i++; } context.RestoreState(); } } public sealed class MonthGridView : UIView { private readonly CalendarMonthView calendarMonthView; private readonly IList<CalendarDayView> dayTiles = new List<CalendarDayView>(); public int WeekdayOfFirst; private DateTime currentMonth; public MonthGridView( CalendarMonthView calendarMonthView, DateTime month ) { this.calendarMonthView = calendarMonthView; currentMonth = month.Date; var tapped = new UITapGestureRecognizer(OnTap); AddGestureRecognizer(tapped); } public DateTime CurrentDate { get; set; } public int Lines { get; set; } private CalendarDayView SelectedDayView { get; set; } public IList<DateTime> Marks { get; set; } private void OnTap( UITapGestureRecognizer tapRecg ) { CGPoint loc = tapRecg.LocationInView(this); if (SelectDayView((PointF) loc) && calendarMonthView.OnDateSelected != null) calendarMonthView.OnDateSelected(new DateTime(currentMonth.Year, currentMonth.Month, (int) SelectedDayView.Tag)); } public void Update() { foreach (CalendarDayView v in dayTiles) UpdateDayView(v); SetNeedsDisplay(); } public void UpdateDayView( CalendarDayView dayView ) { dayView.Marked = calendarMonthView.IsDayMarkedDelegate != null && calendarMonthView.IsDayMarkedDelegate(dayView.Date); dayView.Available = calendarMonthView.IsDateAvailable == null || calendarMonthView.IsDateAvailable(dayView.Date); } /// <summary> /// Build month grid. /// </summary> public void BuildGrid() { DateTime previousMonth = currentMonth.AddMonths(-1); int daysInPreviousMonth = DateTime.DaysInMonth(previousMonth.Year, previousMonth.Month); int daysInMonth = DateTime.DaysInMonth(currentMonth.Year, currentMonth.Month); WeekdayOfFirst = (int) currentMonth.DayOfWeek; int lead = daysInPreviousMonth - (WeekdayOfFirst - 1); int boxWidth = calendarMonthView.BoxWidth; int boxHeight = calendarMonthView.BoxHeight; // Build previous month's days. for (int i = 1; i <= WeekdayOfFirst; i++) { var viewDay = new DateTime(currentMonth.Year, currentMonth.Month, i); var dayView = new CalendarDayView(calendarMonthView) { Frame = new RectangleF((i - 1)*boxWidth - 1, 0, boxWidth, boxHeight), Date = viewDay, Text = lead.ToString() }; AddSubview(dayView); dayTiles.Add(dayView); lead++; } int position = WeekdayOfFirst + 1; int line = 0; // Current month. for (int i = 1; i <= daysInMonth; i++) { var viewDay = new DateTime(currentMonth.Year, currentMonth.Month, i); var dayView = new CalendarDayView(calendarMonthView) { Frame = new RectangleF((position - 1)*boxWidth - 1, line*boxHeight, boxWidth, boxHeight), Today = (CurrentDate.Date == viewDay.Date), Text = i.ToString(), Active = true, Tag = i, Selected = (viewDay.Date == calendarMonthView.CurrentSelectedDate.Date), Date = viewDay }; UpdateDayView(dayView); if (dayView.Selected) SelectedDayView = dayView; AddSubview(dayView); dayTiles.Add(dayView); position++; if (position > 7) { position = 1; line++; } } // Next month. int dayCounter = 1; if (position != 1) { for (int i = position; i < 8; i++) { var viewDay = new DateTime(currentMonth.Year, currentMonth.Month, i); var dayView = new CalendarDayView(calendarMonthView) { Frame = new RectangleF((i - 1)*boxWidth - 1, line*boxHeight, boxWidth, boxHeight), Text = dayCounter.ToString(), Date = viewDay, }; UpdateDayView(dayView); AddSubview(dayView); dayTiles.Add(dayView); dayCounter++; } } while (line < calendarMonthView.LinesCount - 1) { line++; for (int i = 1; i < 8; i++) { var viewDay = new DateTime(currentMonth.Year, currentMonth.Month, i); var dayView = new CalendarDayView(calendarMonthView) { Frame = new RectangleF((i - 1)*boxWidth - 1, line*boxHeight, boxWidth, boxHeight), Text = dayCounter.ToString(), Date = viewDay, }; UpdateDayView(dayView); AddSubview(dayView); dayTiles.Add(dayView); dayCounter++; } } Frame = new RectangleF((PointF) Frame.Location, new SizeF((float) Frame.Width, (line + 1)*boxHeight)); Lines = (position == 1 ? line - 1 : line); if (SelectedDayView != null) BringSubviewToFront(SelectedDayView); } private bool SelectDayView( PointF p ) { int index = ((int) p.Y/calendarMonthView.BoxHeight)*7 + ((int) p.X/calendarMonthView.BoxWidth); if (index < 0 || index >= dayTiles.Count) return false; CalendarDayView newSelectedDayView = dayTiles[index]; if (newSelectedDayView == SelectedDayView) return false; if (!newSelectedDayView.Active) { int day = int.Parse(newSelectedDayView.Text); if (day > 15) calendarMonthView.MoveCalendarMonths(false, true); else calendarMonthView.MoveCalendarMonths(true, true); return false; } if (!newSelectedDayView.Active && !newSelectedDayView.Available) { return false; } if (SelectedDayView != null) SelectedDayView.Selected = false; BringSubviewToFront(newSelectedDayView); newSelectedDayView.Selected = true; SelectedDayView = newSelectedDayView; calendarMonthView.CurrentSelectedDate = SelectedDayView.Date; SetNeedsDisplay(); return true; } public void DeselectDayView() { if (SelectedDayView == null) return; SelectedDayView.Selected = false; SelectedDayView = null; SetNeedsDisplay(); } } public sealed class CalendarDayView : UIView { private readonly CalendarMonthView monthView; private bool isActive; private bool isAvailable; private bool isMarked; private bool isSelected; private bool isToday; private string text; public CalendarDayView( CalendarMonthView monthView ) { this.monthView = monthView; BackgroundColor = UIColor.White; } public DateTime Date { get; set; } public bool Available { get { return isAvailable; } set { isAvailable = value; SetNeedsDisplay(); } } public string Text { get { return text; } set { text = value; SetNeedsDisplay(); } } public bool Active { get { return isActive; } set { isActive = value; SetNeedsDisplay(); } } public bool Today { get { return isToday; } set { isToday = value; SetNeedsDisplay(); } } public bool Selected { get { return isSelected; } set { isSelected = value; SetNeedsDisplay(); } } public bool Marked { get { return isMarked; } set { isMarked = value; SetNeedsDisplay(); } } public override void Draw( CGRect rect ) { // Day cell background. UIImage img; // Text color. UIColor color = UIColor.Gray; if (!Active || !Available) { // Day of next or previous month. img = UIImage.FromBundle("Images/Calendar/datecell_unactive.png").CreateResizableImage(new UIEdgeInsets(4, 4, 4, 4)); } else if (Today && Selected) { // Selected today. color = UIColor.White; img = UIImage.FromBundle("Images/Calendar/todayselected.png").CreateResizableImage(new UIEdgeInsets(4, 4, 4, 4)); } else if (Today) { // Unselected today. img = UIImage.FromBundle("Images/Calendar/today.png").CreateResizableImage(new UIEdgeInsets(4, 4, 4, 4)); } else if (Selected || Marked) { // Selected day. img = UIImage.FromBundle("Images/Calendar/datecellselected.png").CreateResizableImage(new UIEdgeInsets(4, 4, 4, 4)); } else { // Default day. img = UIImage.FromBundle("Images/Calendar/datecell.png").CreateResizableImage(new UIEdgeInsets(4, 4, 4, 4)); } img.Draw(new RectangleF(0, 0, monthView.BoxWidth - monthView.DayCellPadding, monthView.BoxHeight - monthView.DayCellPadding)); color.SetColor(); var inflated = new RectangleF(0, 7, (float) Bounds.Width, (float) Bounds.Height); new NSString(Text).DrawString( inflated, UIFont.BoldSystemFontOfSize(12), UILineBreakMode.WordWrap, UITextAlignment.Center); } } }
// 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. /* * Ordered String/String[] collection of name/value pairs with support for null key * Wraps NameObject collection * */ using System.Runtime.Serialization; using System.Text; namespace System.Collections.Specialized { /// <devdoc> /// <para>Represents a sorted collection of associated <see cref='System.String' qualify='true'/> keys and <see cref='System.String' qualify='true'/> values that /// can be accessed either with the hash code of the key or with the index.</para> /// </devdoc> public class NameValueCollection : NameObjectCollectionBase { private string[] _all; // Do not rename (binary serialization) private string[] _allKeys; // Do not rename (binary serialization) // // Constructors // /// <devdoc> /// <para>Creates an empty <see cref='System.Collections.Specialized.NameValueCollection'/> with the default initial capacity /// and using the default case-insensitive hash code provider and the default /// case-insensitive comparer.</para> /// </devdoc> public NameValueCollection() : base() { } /// <devdoc> /// <para>Copies the entries from the specified <see cref='System.Collections.Specialized.NameValueCollection'/> to a new <see cref='System.Collections.Specialized.NameValueCollection'/> with the same initial capacity as /// the number of entries copied and using the default case-insensitive hash code /// provider and the default case-insensitive comparer.</para> /// </devdoc> public NameValueCollection(NameValueCollection col) : base(col != null ? col.Comparer : null) { Add(col); } [Obsolete("Please use NameValueCollection(IEqualityComparer) instead.")] public NameValueCollection(IHashCodeProvider hashProvider, IComparer comparer) : base(hashProvider, comparer) { } /// <devdoc> /// <para>Creates an empty <see cref='System.Collections.Specialized.NameValueCollection'/> with /// the specified initial capacity and using the default case-insensitive hash code /// provider and the default case-insensitive comparer.</para> /// </devdoc> public NameValueCollection(int capacity) : base(capacity) { } public NameValueCollection(IEqualityComparer equalityComparer) : base(equalityComparer) { } public NameValueCollection(int capacity, IEqualityComparer equalityComparer) : base(capacity, equalityComparer) { } /// <devdoc> /// <para>Copies the entries from the specified <see cref='System.Collections.Specialized.NameValueCollection'/> to a new <see cref='System.Collections.Specialized.NameValueCollection'/> with the specified initial capacity or the /// same initial capacity as the number of entries copied, whichever is greater, and /// using the default case-insensitive hash code provider and the default /// case-insensitive comparer.</para> /// </devdoc> public NameValueCollection(int capacity, NameValueCollection col) : base(capacity, (col != null ? col.Comparer : null)) { if (col == null) { throw new ArgumentNullException(nameof(col)); } this.Comparer = col.Comparer; Add(col); } [Obsolete("Please use NameValueCollection(Int32, IEqualityComparer) instead.")] public NameValueCollection(int capacity, IHashCodeProvider hashProvider, IComparer comparer) : base(capacity, hashProvider, comparer) { } protected NameValueCollection(SerializationInfo info, StreamingContext context) : base(info, context) { } // // Helper methods // /// <devdoc> /// <para> Resets the cached arrays of the collection to <see langword='null'/>.</para> /// </devdoc> protected void InvalidateCachedArrays() { _all = null; _allKeys = null; } private static string GetAsOneString(ArrayList list) { int n = (list != null) ? list.Count : 0; if (n == 1) { return (string)list[0]; } else if (n > 1) { StringBuilder s = new StringBuilder((string)list[0]); for (int i = 1; i < n; i++) { s.Append(','); s.Append((string)list[i]); } return s.ToString(); } else { return null; } } private static string[] GetAsStringArray(ArrayList list) { int n = (list != null) ? list.Count : 0; if (n == 0) return null; string[] array = new string[n]; list.CopyTo(0, array, 0, n); return array; } // // Misc public APIs // /// <devdoc> /// <para>Copies the entries in the specified <see cref='System.Collections.Specialized.NameValueCollection'/> to the current <see cref='System.Collections.Specialized.NameValueCollection'/>.</para> /// </devdoc> public void Add(NameValueCollection c) { if (c == null) { throw new ArgumentNullException(nameof(c)); } InvalidateCachedArrays(); int n = c.Count; for (int i = 0; i < n; i++) { string key = c.GetKey(i); string[] values = c.GetValues(i); if (values != null) { for (int j = 0; j < values.Length; j++) Add(key, values[j]); } else { Add(key, null); } } } /// <devdoc> /// <para>Invalidates the cached arrays and removes all entries /// from the <see cref='System.Collections.Specialized.NameValueCollection'/>.</para> /// </devdoc> public virtual void Clear() { if (IsReadOnly) throw new NotSupportedException(SR.CollectionReadOnly); InvalidateCachedArrays(); BaseClear(); } public void CopyTo(Array dest, int index) { if (dest == null) { throw new ArgumentNullException(nameof(dest)); } if (dest.Rank != 1) { throw new ArgumentException(SR.Arg_MultiRank, nameof(dest)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum_Index); } if (dest.Length - index < Count) { throw new ArgumentException(SR.Arg_InsufficientSpace); } int n = Count; if (_all == null) { string[] all = new string[n]; for (int i = 0; i < n; i++) { all[i] = Get(i); dest.SetValue(all[i], i + index); } _all = all; // wait until end of loop to set _all reference in case Get throws } else { for (int i = 0; i < n; i++) { dest.SetValue(_all[i], i + index); } } } /// <devdoc> /// <para>Gets a value indicating whether the <see cref='System.Collections.Specialized.NameValueCollection'/> contains entries whose keys are not <see langword='null'/>.</para> /// </devdoc> public bool HasKeys() { return InternalHasKeys(); } /// <devdoc> /// <para>Allows derived classes to alter HasKeys().</para> /// </devdoc> internal virtual bool InternalHasKeys() { return BaseHasKeys(); } // // Access by name // /// <devdoc> /// <para>Adds an entry with the specified name and value into the /// <see cref='System.Collections.Specialized.NameValueCollection'/>.</para> /// </devdoc> public virtual void Add(string name, string value) { if (IsReadOnly) throw new NotSupportedException(SR.CollectionReadOnly); InvalidateCachedArrays(); ArrayList values = (ArrayList)BaseGet(name); if (values == null) { // new key - add new key with single value values = new ArrayList(1); if (value != null) values.Add(value); BaseAdd(name, values); } else { // old key -- append value to the list of values if (value != null) values.Add(value); } } /// <devdoc> /// <para> Gets the values associated with the specified key from the <see cref='System.Collections.Specialized.NameValueCollection'/> combined into one comma-separated list.</para> /// </devdoc> public virtual string Get(string name) { ArrayList values = (ArrayList)BaseGet(name); return GetAsOneString(values); } /// <devdoc> /// <para>Gets the values associated with the specified key from the <see cref='System.Collections.Specialized.NameValueCollection'/>.</para> /// </devdoc> public virtual string[] GetValues(string name) { ArrayList values = (ArrayList)BaseGet(name); return GetAsStringArray(values); } /// <devdoc> /// <para>Adds a value to an entry in the <see cref='System.Collections.Specialized.NameValueCollection'/>.</para> /// </devdoc> public virtual void Set(string name, string value) { if (IsReadOnly) throw new NotSupportedException(SR.CollectionReadOnly); InvalidateCachedArrays(); ArrayList values = new ArrayList(1); values.Add(value); BaseSet(name, values); } /// <devdoc> /// <para>Removes the entries with the specified key from the <see cref='System.Collections.Specialized.NameObjectCollectionBase'/> instance.</para> /// </devdoc> public virtual void Remove(string name) { InvalidateCachedArrays(); BaseRemove(name); } /// <devdoc> /// <para> Represents the entry with the specified key in the /// <see cref='System.Collections.Specialized.NameValueCollection'/>.</para> /// </devdoc> public string this[string name] { get { return Get(name); } set { Set(name, value); } } // // Indexed access // /// <devdoc> /// <para> /// Gets the values at the specified index of the <see cref='System.Collections.Specialized.NameValueCollection'/> combined into one /// comma-separated list.</para> /// </devdoc> public virtual string Get(int index) { ArrayList values = (ArrayList)BaseGet(index); return GetAsOneString(values); } /// <devdoc> /// <para> Gets the values at the specified index of the <see cref='System.Collections.Specialized.NameValueCollection'/>.</para> /// </devdoc> public virtual string[] GetValues(int index) { ArrayList values = (ArrayList)BaseGet(index); return GetAsStringArray(values); } /// <devdoc> /// <para>Gets the key at the specified index of the <see cref='System.Collections.Specialized.NameValueCollection'/>.</para> /// </devdoc> public virtual string GetKey(int index) { return BaseGetKey(index); } /// <devdoc> /// <para>Represents the entry at the specified index of the <see cref='System.Collections.Specialized.NameValueCollection'/>.</para> /// </devdoc> public string this[int index] { get { return Get(index); } } // // Access to keys and values as arrays // /// <devdoc> /// <para>Gets all the keys in the <see cref='System.Collections.Specialized.NameValueCollection'/>. </para> /// </devdoc> public virtual string[] AllKeys { get { if (_allKeys == null) _allKeys = BaseGetAllKeys(); return _allKeys; } } } }
using Lidgren.Network; using Microsoft.Xna.Framework; using System.Collections.Generic; using AsteroidShooter; using GameNetworking; namespace Utilities { public static class Random { private static System.Random generator = new System.Random(); public static float RandFloat(float min, float max) { return min + (float)generator.NextDouble() * (max - min); } public static int RandInt(int min, int max) { return generator.Next(min, max); } } public class NetworkInfo<T> { public T Entity { get; set; } public bool IsLocal { get; set; } public NetworkInfo() { Entity = default(T); IsLocal = false; } public NetworkInfo(T entity, bool local) { Entity = entity; IsLocal = local; } } public static class NetworkAPI { public static NetClient Client; public enum MessageType { Create, Update } public enum EntityType { World, Ship, Asteroid, Projectile } public static int NextID { get { int r = Random.RandInt(0, 1000000000); return r.GetHashCode(); } } public static Dictionary<int, NetworkInfo<Ship>> ShipInfos = new Dictionary<int, NetworkInfo<Ship>>(); public static Dictionary<int, NetworkInfo<Projectile>> ProjectileInfos = new Dictionary<int, NetworkInfo<Projectile>>(); public static Dictionary<int, NetworkInfo<Asteroid>> AsteroidInfos = new Dictionary<int, NetworkInfo<Asteroid>>(); public static Dictionary<EntityType, Dictionary<MessageType, Dictionary<int, NetIncomingMessage>>> ReceivedMessages = new Dictionary<EntityType, Dictionary<MessageType, Dictionary<int, NetIncomingMessage>>>(); /*protocol: -- Full synchronization item 0 = message type item 1 = entity type item 2 = entity id rest = fields -- Partial synchronization item 0 = message type item 1 = entity type item 2 = entity id item 3 = field id rest = field value */ /* Order of fields: Asteroids, Ships */ public static NetOutgoingMessage CreateWorldMessage(World world, NetClient client) { NetOutgoingMessage message = client.CreateMessage(); message.Write((int)MessageType.Create); message.Write((int)EntityType.World); message.Write(world.ID); NetOutgoingMessage asteroidsMessage = NetworkUtils.BuildMessage<Asteroid>(world.Asteroids, client, CreateAsteroidMessage); NetOutgoingMessage shipsMessage = NetworkUtils.BuildMessage<Ship>(world.Ships, client, CreateShipMessage); message.Write(asteroidsMessage); message.Write(shipsMessage); return message; } public static NetOutgoingMessage CreateWorldMessage(World world, NetClient client, int fieldId) { NetOutgoingMessage message = client.CreateMessage(); message.Write((int)MessageType.Update); message.Write((int)EntityType.World); message.Write(world.ID); NetOutgoingMessage asteroidsMessage; NetOutgoingMessage shipsMessage; message.Write(fieldId); switch (fieldId) { case 0: asteroidsMessage = NetworkUtils.BuildMessage<Asteroid>(world.Asteroids, client, CreateAsteroidMessage); message.Write(asteroidsMessage); break; case 1: shipsMessage = NetworkUtils.BuildMessage<Ship>(world.Ships, client, CreateShipMessage); message.Write(shipsMessage); break; default: throw new System.ArgumentException("Unsupported field in World" + fieldId); } return message; } /* Order of fields: score, projectile list, position, health, color R, color G, color B */ public static NetOutgoingMessage CreateShipMessage(Ship ship, NetClient client) { NetOutgoingMessage message = client.CreateMessage(); message.Write((int)MessageType.Create); message.Write((int)EntityType.Ship); message.Write(ship.ID); NetOutgoingMessage projMessage = NetworkUtils.BuildMessage<Projectile>(ship.Projectiles, client, CreateProjectileMessage); NetOutgoingMessage posMessage = NetworkUtils.BuildMessage(ship.Position, client); message.Write(ship.Score); message.Write(projMessage); message.Write(posMessage); message.Write(ship.Health); message.Write(ship.Color.R); message.Write(ship.Color.G); message.Write(ship.Color.B); return message; } public static NetOutgoingMessage CreateShipMessage(Ship ship, NetClient client, int fieldID) { NetOutgoingMessage message = client.CreateMessage(); message.Write((int)MessageType.Update); message.Write((int)EntityType.Ship); message.Write(ship.ID); NetOutgoingMessage projectilesMessage; NetOutgoingMessage posMessage; message.Write(fieldID); switch(fieldID) { case 0: message.Write(ship.Score); break; case 1: projectilesMessage = NetworkUtils.BuildMessage<Projectile>(ship.Projectiles, client, CreateProjectileMessage); message.Write(projectilesMessage); break; case 2: posMessage = NetworkUtils.BuildMessage(ship.Position, client); message.Write(posMessage); break; case 3: message.Write(ship.Health); break; case 4: message.Write(ship.Color.R); message.Write(ship.Color.G); message.Write(ship.Color.B); break; default: throw new System.ArgumentException("Unsupported field in Ship: " + fieldID); } return message; } /* Order of fields: position, owner ref */ public static NetOutgoingMessage CreateProjectileMessage(Projectile proj, NetClient client) { NetOutgoingMessage message = client.CreateMessage(); message.Write((int)MessageType.Create); message.Write((int)EntityType.Projectile); message.Write(proj.ID); NetOutgoingMessage vectorMessage = NetworkUtils.BuildMessage(proj.Position, client); message.Write(vectorMessage); message.Write(proj.Owner.ID); return message; } public static NetOutgoingMessage CreateProjectileMessage(Projectile proj, NetClient client, int fieldId) { NetOutgoingMessage message = client.CreateMessage(); message.Write((int)MessageType.Update); message.Write((int)EntityType.Projectile); message.Write(proj.ID); NetOutgoingMessage posMessage; message.Write(fieldId); switch(fieldId) { case 0: posMessage = NetworkUtils.BuildMessage(proj.Position, client); message.Write(posMessage); break; default: throw new System.ArgumentException("Unsupported field in Projectile: " + fieldId); } return message; } /* Order of fields: position, damage*/ public static NetOutgoingMessage CreateAsteroidMessage(Asteroid asteroid, NetClient client) { NetOutgoingMessage message = client.CreateMessage(); message.Write((int)MessageType.Create); message.Write((int)EntityType.Asteroid); message.Write(asteroid.ID); NetOutgoingMessage vectorMessage = NetworkUtils.BuildMessage(asteroid.Position, client); message.Write(vectorMessage); message.Write(asteroid.Damage); return message; } public static NetOutgoingMessage CreateAsteroidMessage(Asteroid asteroid, NetClient client, int fieldId) { NetOutgoingMessage message = client.CreateMessage(); message.Write((int)MessageType.Update); message.Write((int)EntityType.Asteroid); message.Write(asteroid.ID); NetOutgoingMessage posMessage; message.Write(fieldId); switch(fieldId) { case 0: posMessage = NetworkUtils.BuildMessage(asteroid.Position, client); message.Write(posMessage); break; case 1: message.Write(asteroid.Damage); break; default: throw new System.ArgumentException("Unsupported field in Asteroid: " + fieldId); } return message; } public static bool ContainsRightMessage(EntityType entityType, MessageType messageType) { return ReceivedMessages.ContainsKey(entityType) && ReceivedMessages[entityType].ContainsKey(messageType); } public static NetIncomingMessage FindRightMessage(EntityType entityType, MessageType messageType, int id) { return ReceivedMessages[entityType][messageType][id]; } public static Asteroid ReceiveNewAsteroidMessage(int id) { NetIncomingMessage message = FindRightMessage(EntityType.Asteroid, MessageType.Create, id); Vector2 position = NetworkUtils.ReceiveVector2(message); int damage = message.ReadInt32(); Asteroid asteroid = new Asteroid(position); asteroid.Damage = damage; AsteroidInfos.Add(id, new NetworkInfo<Asteroid>(asteroid, false)); return asteroid; } public static Asteroid ReceiveUpdatedAsteroidMessage(int id) { } public static void DispatchMessages(NetClient client) { List<NetIncomingMessage> messages = new List<NetIncomingMessage>(); client.ReadMessages(messages); for (int i = 0; i < messages.Count; i++) { if (messages[i].MessageType == NetIncomingMessageType.Data) { MessageType messageType = (MessageType)messages[i].ReadInt32(); EntityType entityType = (EntityType)messages[i].ReadInt32(); int entityId = messages[i].ReadInt32(); ReceivedMessages[entityType][messageType][entityId] = messages[i]; } } } } }
#region File Description //----------------------------------------------------------------------------- // MenuScreen.cs // // XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input.Touch; using Microsoft.Xna.Framework.Input; using FarseerPhysics.SamplesFramework; #endregion namespace GameStateManagement { /// <summary> /// Base class for screens that contain a menu of options. The user can /// move up and down to select an entry, or cancel to back out of the screen. /// </summary> public class MenuScreen : GameScreen { #region Fields // the number of pixels to pad above and below menu entries for touch input const int menuEntryPadding = 10; private List<MenuEntry> menuEntries = new List<MenuEntry>(); int selectedEntry = 0; string menuTitle; InputAction menuUp; InputAction menuDown; InputAction menuSelect; InputAction menuCancel; #endregion #region Properties /// <summary> /// Gets the list of menu entries, so derived classes can add /// or change the menu contents. /// </summary> protected IList<MenuEntry> MenuEntries { get { return menuEntries; } } #endregion #region Initialization /// <summary> /// Constructor. /// </summary> public MenuScreen(string menuTitle) { this.menuTitle = menuTitle; // menus generally only need Tap for menu selection EnabledGestures = GestureType.Tap; TransitionOnTime = TimeSpan.FromSeconds(0.5); TransitionOffTime = TimeSpan.FromSeconds(0.5); menuUp = new InputAction( new Buttons[] { Buttons.DPadUp, Buttons.LeftThumbstickUp }, new Keys[] { Keys.Up }, true); menuDown = new InputAction( new Buttons[] { Buttons.DPadDown, Buttons.LeftThumbstickDown }, new Keys[] { Keys.Down }, true); menuSelect = new InputAction( new Buttons[] { Buttons.A, Buttons.Start }, new Keys[] { Keys.Enter, Keys.Space }, true); menuCancel = new InputAction( new Buttons[] { Buttons.B, Buttons.Back }, new Keys[] { Keys.Escape }, true); } #endregion public void AddMenuItem(string name) { menuEntries.Add(new MenuEntry(name)); } #region Handle Input /// <summary> /// Allows the screen to create the hit bounds for a particular menu entry. /// </summary> protected virtual Rectangle GetMenuEntryHitBounds(MenuEntry entry) { // the hit bounds are the entire width of the screen, and the height of the entry // with some additional padding above and below. return new Rectangle( 0, (int)entry.Position.Y - menuEntryPadding, ScreenManager.GraphicsDevice.Viewport.Width, entry.GetHeight(this) + (menuEntryPadding * 2)); } /// <summary> /// Responds to user input, changing the selected entry and accepting /// or cancelling the menu. /// </summary> public override void HandleInput(GameTime gameTime, InputState input) { // For input tests we pass in our ControllingPlayer, which may // either be null (to accept input from any player) or a specific index. // If we pass a null controlling player, the InputState helper returns to // us which player actually provided the input. We pass that through to // OnSelectEntry and OnCancel, so they can tell which player triggered them. #if WINDOWS || XBOX360 PlayerIndex playerIndex; // Move to the previous menu entry? if (menuUp.Evaluate(input, ControllingPlayer, out playerIndex)) { selectedEntry--; if (selectedEntry < 0) selectedEntry = menuEntries.Count - 1; } // Move to the next menu entry? if (menuDown.Evaluate(input, ControllingPlayer, out playerIndex)) { selectedEntry++; if (selectedEntry >= menuEntries.Count) selectedEntry = 0; } if (menuSelect.Evaluate(input, ControllingPlayer, out playerIndex)) { OnSelectEntry(selectedEntry, playerIndex); } else if (menuCancel.Evaluate(input, ControllingPlayer, out playerIndex)) { OnCancel(playerIndex); } #endif #if WINDOWS_PHONE //selectedEntry = 1; PlayerIndex player; if (input.IsNewButtonPress(Buttons.Back, ControllingPlayer, out player)) { OnCancel(player); } // look for any taps that occurred and select any entries that were tapped foreach (GestureSample gesture in input.Gestures) { //System.Diagnostics.Debugger.Break(); if (gesture.GestureType == GestureType.Tap) { // convert the position to a Point that we can test against a Rectangle Point tapLocation = new Point((int)gesture.Position.X, (int)gesture.Position.Y); // iterate the entries to see if any were tapped for (int i = 0; i < menuEntries.Count; i++) { MenuEntry menuEntry = menuEntries[i]; if (GetMenuEntryHitBounds(menuEntry).Contains(tapLocation)) { // select the entry. since gestures are only available on Windows Phone, // we can safely pass PlayerIndex.One to all entries since there is only // one player on Windows Phone. OnSelectEntry(i, PlayerIndex.One); } } } } #endif } /// <summary> /// Handler for when the user has chosen a menu entry. /// </summary> protected virtual void OnSelectEntry(int entryIndex, PlayerIndex playerIndex) { menuEntries[entryIndex].OnSelectEntry(playerIndex); } /// <summary> /// Handler for when the user has cancelled the menu. /// </summary> protected virtual void OnCancel(PlayerIndex playerIndex) { ExitScreen(); } /// <summary> /// Helper overload makes it easy to use OnCancel as a MenuEntry event handler. /// </summary> protected void OnCancel(object sender, PlayerIndexEventArgs e) { OnCancel(e.PlayerIndex); } #endregion #region Update and Draw /// <summary> /// Allows the screen the chance to position the menu entries. By default /// all menu entries are lined up in a vertical list, centered on the screen. /// </summary> protected virtual void UpdateMenuEntryLocations() { // Make the menu slide into place during transitions, using a // power curve to make things look more interesting (this makes // the movement slow down as it nears the end). float transitionOffset = (float)Math.Pow(TransitionPosition, 2); // start at Y = 175; each X value is generated per entry Vector2 position = new Vector2(0f, 175f); // update each menu entry's location in turn for (int i = 0; i < menuEntries.Count; i++) { MenuEntry menuEntry = menuEntries[i]; // each entry is to be centered horizontally position.X = ScreenManager.GraphicsDevice.Viewport.Width / 2 - menuEntry.GetWidth(this) / 2; if (ScreenState == ScreenState.TransitionOn) position.X -= transitionOffset * 256; else position.X += transitionOffset * 512; // set the entry's position menuEntry.Position = position; // move down for the next entry the size of this entry position.Y += menuEntry.GetHeight(this); } } /// <summary> /// Updates the menu. /// </summary> public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen); // Update each nested MenuEntry object. for (int i = 0; i < menuEntries.Count; i++) { bool isSelected = IsActive && (i == selectedEntry); menuEntries[i].Update(this, isSelected, gameTime); } } /// <summary> /// Draws the menu. /// </summary> public override void Draw(GameTime gameTime) { // make sure our entries are in the right place before we draw them UpdateMenuEntryLocations(); GraphicsDevice graphics = ScreenManager.GraphicsDevice; SpriteBatch spriteBatch = ScreenManager.SpriteBatch; SpriteFont font = ScreenManager.Font; spriteBatch.Begin(); // Draw each menu entry in turn. for (int i = 0; i < menuEntries.Count; i++) { MenuEntry menuEntry = menuEntries[i]; bool isSelected = IsActive && (i == selectedEntry); menuEntry.Draw(this, isSelected, gameTime); } // Make the menu slide into place during transitions, using a // power curve to make things look more interesting (this makes // the movement slow down as it nears the end). float transitionOffset = (float)Math.Pow(TransitionPosition, 2); // Draw the menu title centered on the screen Vector2 titlePosition = new Vector2(graphics.Viewport.Width / 2, 80); Vector2 titleOrigin = font.MeasureString(menuTitle) / 2; Color titleColor = new Color(192, 192, 192) * TransitionAlpha; float titleScale = 1.25f; titlePosition.Y -= transitionOffset * 100; spriteBatch.DrawString(font, menuTitle, titlePosition, titleColor, 0, titleOrigin, titleScale, SpriteEffects.None, 0); spriteBatch.End(); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System.Threading; using System.Threading.Tasks; namespace System.IO.Tests { public class UmsTests { internal static void UmsInvariants(UnmanagedMemoryStream stream) { Assert.False(stream.CanTimeout); } internal static void ReadUmsInvariants(UnmanagedMemoryStream stream) { UmsInvariants(stream); Assert.True(stream.CanRead); Assert.False(stream.CanWrite); Assert.True(stream.CanSeek); Assert.Throws<NotSupportedException>(() => stream.SetLength(1000)); } internal static void WriteUmsInvariants(UnmanagedMemoryStream stream) { UmsInvariants(stream); Assert.False(stream.CanRead); Assert.True(stream.CanWrite); Assert.True(stream.CanSeek); } internal static void ReadWriteUmsInvariants(UnmanagedMemoryStream stream) { UmsInvariants(stream); Assert.True(stream.CanRead); Assert.True(stream.CanWrite); Assert.True(stream.CanSeek); } [Fact] public static void PositionTests() { using (var manager = new UmsManager(FileAccess.ReadWrite, 1000)) { UnmanagedMemoryStream stream = manager.Stream; UmsTests.ReadWriteUmsInvariants(stream); Assert.Throws<ArgumentOutOfRangeException>(() => { stream.Position = -1; }); // "Non-negative number required." Assert.Throws<ArgumentOutOfRangeException>(() => { stream.Position = unchecked(long.MaxValue + 1); }); Assert.Throws<ArgumentOutOfRangeException>(() => { stream.Position = int.MinValue; }); stream.Position = stream.Length; Assert.Equal(stream.Position, stream.Length); stream.Position = stream.Capacity; Assert.Equal(stream.Position, stream.Capacity); int mid = (int)stream.Length / 2; stream.Position = mid; Assert.Equal(stream.Position, mid); } } [Fact] public static void LengthTests() { using (var manager = new UmsManager(FileAccess.ReadWrite, 1000)) { UnmanagedMemoryStream stream = manager.Stream; UmsTests.ReadWriteUmsInvariants(stream); Assert.Throws<IOException>(() => stream.SetLength(1001)); Assert.Throws<ArgumentOutOfRangeException>(() => stream.SetLength(sbyte.MinValue)); const long expectedLength = 500; stream.Position = 501; stream.SetLength(expectedLength); Assert.Equal(expectedLength, stream.Length); Assert.Equal(expectedLength, stream.Position); } } [Fact] public static void SeekTests() { const int length = 1000; using (var manager = new UmsManager(FileAccess.ReadWrite, length)) { UnmanagedMemoryStream stream = manager.Stream; UmsTests.ReadWriteUmsInvariants(stream); Assert.Throws<IOException>(() => stream.Seek(unchecked(int.MaxValue + 1), SeekOrigin.Begin)); Assert.Throws<IOException>(() => stream.Seek(long.MinValue, SeekOrigin.End)); AssertExtensions.Throws<ArgumentException>(null, () => stream.Seek(0, (SeekOrigin)7)); // Invalid seek origin stream.Seek(10, SeekOrigin.Begin); Assert.Equal(10, stream.Position); Assert.Throws<IOException>(() => stream.Seek(-1, SeekOrigin.Begin)); // An attempt was made to move the position before the beginning of the stream Assert.Equal(10, stream.Position); Assert.Throws<IOException>(() => stream.Seek(-(stream.Position + 1), SeekOrigin.Current)); // An attempt was made to move the position before the beginning of the stream Assert.Equal(10, stream.Position); Assert.Throws<IOException>(() => stream.Seek(-(stream.Length + 1), SeekOrigin.End)); // "An attempt was made to move the position before the beginning of the stream." Assert.Equal(10, stream.Position); // Seek from SeekOrigin.Begin stream.Seek(0, SeekOrigin.Begin); for (int position = 0; position < stream.Length; position++) { stream.Seek(position, SeekOrigin.Begin); Assert.Equal(position, stream.Position); } for (int position = (int)stream.Length; position >= 0; position--) { stream.Seek(position, SeekOrigin.Begin); Assert.Equal(position, stream.Position); } stream.Seek(0, SeekOrigin.Begin); // Seek from SeekOrigin.End for (int position = 0; position < stream.Length; position++) { stream.Seek(-position, SeekOrigin.End); Assert.Equal(length - position, stream.Position); } for (int position = (int)stream.Length; position >= 0; position--) { stream.Seek(-position, SeekOrigin.End); Assert.Equal(length - position, stream.Position); } // Seek from SeekOrigin.Current stream.Seek(0, SeekOrigin.Begin); for (int position = 0; position < stream.Length; position++) { stream.Seek(1, SeekOrigin.Current); Assert.Equal(position + 1, stream.Position); } for (int position = (int)stream.Length; position > 0; position--) { stream.Seek(-1, SeekOrigin.Current); Assert.Equal(position - 1, stream.Position); } } } [Fact] public static void CannotUseStreamAfterDispose() { using (var manager = new UmsManager(FileAccess.ReadWrite, 1000)) { UnmanagedMemoryStream stream = manager.Stream; UmsTests.ReadWriteUmsInvariants(stream); stream.Dispose(); Assert.False(stream.CanRead); Assert.False(stream.CanWrite); Assert.False(stream.CanSeek); Assert.Throws<ObjectDisposedException>(() => { long x = stream.Capacity; }); Assert.Throws<ObjectDisposedException>(() => { long y = stream.Length; }); Assert.Throws<ObjectDisposedException>(() => { stream.SetLength(2); }); Assert.Throws<ObjectDisposedException>(() => { long z = stream.Position; }); Assert.Throws<ObjectDisposedException>(() => { stream.Position = 2; }); Assert.Throws<ObjectDisposedException>(() => stream.Seek(0, SeekOrigin.Begin)); Assert.Throws<ObjectDisposedException>(() => stream.Seek(0, SeekOrigin.Current)); Assert.Throws<ObjectDisposedException>(() => stream.Seek(0, SeekOrigin.End)); Assert.Throws<ObjectDisposedException>(() => stream.Flush()); Assert.Throws<ObjectDisposedException>(() => stream.FlushAsync(CancellationToken.None).GetAwaiter().GetResult()); byte[] buffer = ArrayHelpers.CreateByteArray(10); Assert.Throws<ObjectDisposedException>(() => stream.Read(buffer, 0, buffer.Length)); Assert.Throws<ObjectDisposedException>(() => stream.ReadAsync(buffer, 0, buffer.Length).GetAwaiter().GetResult()); Assert.Throws<ObjectDisposedException>(() => stream.ReadByte()); Assert.Throws<ObjectDisposedException>(() => stream.WriteByte(0)); Assert.Throws<ObjectDisposedException>(() => stream.Write(buffer, 0, buffer.Length)); Assert.Throws<ObjectDisposedException>(() => stream.WriteAsync(buffer, 0, buffer.Length).GetAwaiter().GetResult()); } } [Fact] public static void CopyToTest() { byte[] testData = ArrayHelpers.CreateByteArray(8192); using (var manager = new UmsManager(FileAccess.Read, testData)) { UnmanagedMemoryStream ums = manager.Stream; UmsTests.ReadUmsInvariants(ums); MemoryStream destination = new MemoryStream(); destination.Position = 0; ums.CopyTo(destination); Assert.Equal(testData, destination.ToArray()); destination.Position = 0; ums.CopyTo(destination, 1); Assert.Equal(testData, destination.ToArray()); } // copy to disposed stream should throw using (var manager = new UmsManager(FileAccess.Read, testData)) { UnmanagedMemoryStream ums = manager.Stream; UmsTests.ReadUmsInvariants(ums); MemoryStream destination = new MemoryStream(); destination.Dispose(); Assert.Throws<ObjectDisposedException>(() => ums.CopyTo(destination)); } // copy from disposed stream should throw using (var manager = new UmsManager(FileAccess.Read, testData)) { UnmanagedMemoryStream ums = manager.Stream; UmsTests.ReadUmsInvariants(ums); ums.Dispose(); MemoryStream destination = new MemoryStream(); Assert.Throws<ObjectDisposedException>(() => ums.CopyTo(destination)); } // copying to non-writable stream should throw using (var manager = new UmsManager(FileAccess.Read, testData)) { UnmanagedMemoryStream ums = manager.Stream; UmsTests.ReadUmsInvariants(ums); MemoryStream destination = new MemoryStream(new byte[0], false); Assert.Throws<NotSupportedException>(() => ums.CopyTo(destination)); } // copying from non-readable stream should throw using (var manager = new UmsManager(FileAccess.Write, testData)) { UnmanagedMemoryStream ums = manager.Stream; UmsTests.WriteUmsInvariants(ums); MemoryStream destination = new MemoryStream(new byte[0], false); Assert.Throws<NotSupportedException>(() => ums.CopyTo(destination)); } } [Fact] public static async Task CopyToAsyncTest() { byte[] testData = ArrayHelpers.CreateByteArray(8192); using (var manager = new UmsManager(FileAccess.Read, testData)) { UnmanagedMemoryStream ums = manager.Stream; UmsTests.ReadUmsInvariants(ums); MemoryStream destination = new MemoryStream(); destination.Position = 0; await ums.CopyToAsync(destination); Assert.Equal(testData, destination.ToArray()); destination.Position = 0; await ums.CopyToAsync(destination, 2); Assert.Equal(testData, destination.ToArray()); destination.Position = 0; await ums.CopyToAsync(destination, 0x1000, new CancellationTokenSource().Token); Assert.Equal(testData, destination.ToArray()); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => ums.CopyToAsync(destination, 0x1000, new CancellationToken(true))); } // copy to disposed stream should throw using (var manager = new UmsManager(FileAccess.Read, testData)) { UnmanagedMemoryStream ums = manager.Stream; UmsTests.ReadUmsInvariants(ums); MemoryStream destination = new MemoryStream(); destination.Dispose(); await Assert.ThrowsAsync<ObjectDisposedException>(() => ums.CopyToAsync(destination)); } // copy from disposed stream should throw using (var manager = new UmsManager(FileAccess.Read, testData)) { UnmanagedMemoryStream ums = manager.Stream; UmsTests.ReadUmsInvariants(ums); ums.Dispose(); MemoryStream destination = new MemoryStream(); await Assert.ThrowsAsync<ObjectDisposedException>(() => ums.CopyToAsync(destination)); } // copying to non-writable stream should throw using (var manager = new UmsManager(FileAccess.Read, testData)) { UnmanagedMemoryStream ums = manager.Stream; UmsTests.ReadUmsInvariants(ums); MemoryStream destination = new MemoryStream(new byte[0], false); await Assert.ThrowsAsync<NotSupportedException>(() => ums.CopyToAsync(destination)); } // copying from non-readable stream should throw using (var manager = new UmsManager(FileAccess.Write, testData)) { UnmanagedMemoryStream ums = manager.Stream; UmsTests.WriteUmsInvariants(ums); MemoryStream destination = new MemoryStream(new byte[0], false); await Assert.ThrowsAsync<NotSupportedException>(() => ums.CopyToAsync(destination)); } } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.ComponentModel.Design; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using System.Windows; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Project; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Threading; using Microsoft.VisualStudioTools.Project; using Task = System.Threading.Tasks.Task; namespace Microsoft.PythonTools.Profiling { using global::DiagnosticsHub.Packaging.Interop; using Microsoft.DiagnosticsHub.Packaging.InteropEx; /// <summary> /// This is the class that implements the package exposed by this assembly. /// /// The minimum requirement for a class to be considered a valid package for Visual Studio /// is to implement the IVsPackage interface and register itself with the shell. /// This package uses the helper classes defined inside the Managed Package Framework (MPF) /// to do it: it derives from the Package class that provides the implementation of the /// IVsPackage interface and uses the registration attributes defined in the framework to /// register itself and its components with the shell. /// </summary> // This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is // a package. [PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)] // This attribute is used to register the informations needed to show the this package // in the Help/About dialog of Visual Studio. [InstalledProductRegistration("#110", "#112", AssemblyVersionInfo.Version, IconResourceID = 400)] // This attribute is needed to let the shell know that this package exposes some menus. [ProvideMenuResource("Menus.ctmenu", 1)] [Guid(GuidList.guidPythonProfilingPkgString)] // set the window to dock where Toolbox/Performance Explorer dock by default [ProvideToolWindow(typeof(PerfToolWindow), Orientation = ToolWindowOrientation.Left, Style = VsDockStyle.Tabbed, Window = EnvDTE.Constants.vsWindowKindToolbox)] [ProvideFileFilter("{81da0100-e6db-4783-91ea-c38c3fa1b81e}", "/1", "#113", 100)] [ProvideEditorExtension(typeof(ProfilingSessionEditorFactory), ".pyperf", 50, ProjectGuid = "{81da0100-e6db-4783-91ea-c38c3fa1b81e}", NameResourceID = 105, DefaultName = "PythonPerfSession")] [ProvideAutomationObject("PythonProfiling")] internal sealed class PythonProfilingPackage : AsyncPackage { internal static PythonProfilingPackage Instance; private static ProfiledProcess _profilingProcess; // process currently being profiled internal static readonly string PythonProjectGuid = "{888888a0-9f3d-457c-b088-3a5042f75d52}"; internal static readonly string PerformanceFileFilter = Strings.PerformanceReportFilesFilter; private AutomationProfiling _profilingAutomation; private static OleMenuCommand _stopCommand, _startCommand; #if EXTERNAL_PROFILER_DRIVER private const string ExternalProfilerDriverExe = "ExternalProfilerDriver.exe"; #endif /// <summary> /// Default constructor of the package. /// Inside this method you can place any initialization code that does not require /// any Visual Studio service because at this point the package object is created but /// not sited yet inside Visual Studio environment. The place to do all the other /// initialization is the Initialize method. /// </summary> public PythonProfilingPackage() { Instance = this; } protected override void Dispose(bool disposing) { if (disposing) { var process = _profilingProcess; _profilingProcess = null; if (process != null) { process.Dispose(); } } base.Dispose(disposing); } protected override int CreateToolWindow(ref Guid toolWindowType, int id) => toolWindowType == PerfToolWindow.WindowGuid ? CreatePerfToolWindow(id) : base.CreateToolWindow(ref toolWindowType, id); private int CreatePerfToolWindow(int id) { try { var type = typeof(PerfToolWindow); var toolWindow = FindWindowPane(type, id, false) ?? CreateToolWindow(type, id, this); return toolWindow != null ? VSConstants.S_OK : VSConstants.E_FAIL; } catch (Exception ex) { return Marshal.GetHRForException(ex); } } protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress) { Trace.WriteLine("Entering InitializeAsync() of: {0}".FormatUI(this)); await base.InitializeAsync(cancellationToken, progress); await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); // Ensure Python Tools package is loaded var shell = (IVsShell7)GetService(typeof(SVsShell)); var ptvsPackage = GuidList.guidPythonToolsPackage; await shell.LoadPackageAsync(ref ptvsPackage); // Add our command handlers for menu (commands must exist in the .vsct file) if (GetService(typeof(IMenuCommandService)) is OleMenuCommandService mcs) { // Create the command for the menu item. CommandID menuCommandID = new CommandID(GuidList.guidPythonProfilingCmdSet, (int)PkgCmdIDList.cmdidStartPythonProfiling); MenuCommand menuItem = new MenuCommand(StartProfilingWizard, menuCommandID); mcs.AddCommand(menuItem); // Create the command for the menu item. menuCommandID = new CommandID(GuidList.guidPythonProfilingCmdSet, (int)PkgCmdIDList.cmdidPerfExplorer); var oleMenuItem = new OleMenuCommand((o, e) => ShowPeformanceExplorerAsync().DoNotWait(), menuCommandID); mcs.AddCommand(oleMenuItem); menuCommandID = new CommandID(GuidList.guidPythonProfilingCmdSet, (int)PkgCmdIDList.cmdidAddPerfSession); menuItem = new MenuCommand((o, e) => AddPerformanceSessionAsync().DoNotWait(), menuCommandID); mcs.AddCommand(menuItem); menuCommandID = new CommandID(GuidList.guidPythonProfilingCmdSet, (int)PkgCmdIDList.cmdidStartProfiling); oleMenuItem = _startCommand = new OleMenuCommand((o, e) => StartProfilingAsync().DoNotWait(), menuCommandID); oleMenuItem.BeforeQueryStatus += IsProfilingActive; mcs.AddCommand(oleMenuItem); menuCommandID = new CommandID(GuidList.guidPythonProfilingCmdSet, (int)PkgCmdIDList.cmdidStopProfiling); _stopCommand = oleMenuItem = new OleMenuCommand(StopProfiling, menuCommandID); oleMenuItem.BeforeQueryStatus += IsProfilingInactive; mcs.AddCommand(oleMenuItem); } //Create Editor Factory. Note that the base Package class will call Dispose on it. RegisterEditorFactory(new ProfilingSessionEditorFactory(this)); } protected override object GetAutomationObject(string name) { if (name == "PythonProfiling") { if (_profilingAutomation == null) { var pane = (PerfToolWindow)JoinableTaskFactory.Run(GetPerfToolWindowAsync); _profilingAutomation = new AutomationProfiling(pane.Sessions); } return _profilingAutomation; } return base.GetAutomationObject(name); } internal static Guid GetStartupProjectGuid(IServiceProvider serviceProvider) { var buildMgr = (IVsSolutionBuildManager)serviceProvider.GetService(typeof(IVsSolutionBuildManager)); if (buildMgr != null && ErrorHandler.Succeeded(buildMgr.get_StartupProject(out var hierarchy)) && hierarchy != null) { if (ErrorHandler.Succeeded(hierarchy.GetGuidProperty( (uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID.VSHPROPID_ProjectIDGuid, out var guid ))) { return guid; } } return Guid.Empty; } internal IVsSolution Solution { get { return GetService(typeof(SVsSolution)) as IVsSolution; } } /// <summary> /// This function is the callback used to execute a command when the a menu item is clicked. /// See the Initialize method to see how the menu item is associated to this function using /// the OleMenuCommandService service and the MenuCommand class. /// </summary> private void StartProfilingWizard(object sender, EventArgs e) { if (!IsProfilingInstalled()) { MessageBox.Show(Strings.ProfilingSupportMissingError, Strings.ProductTitle); return; } var targetView = new ProfilingTargetView(this); var dialog = new LaunchProfiling(this, targetView); var res = dialog.ShowModal() ?? false; if (res && targetView.IsValid) { var target = targetView.GetTarget(); if (target != null) { ProfileTarget(target); } } } internal SessionNode ProfileTarget(ProfilingTarget target, bool openReport = true) { return JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(); var name = target.GetProfilingName(this, out var save); var explorer = await ShowPerformanceExplorerAsync(); var session = explorer.Sessions.AddTarget(target, name, save); StartProfiling(target, session, openReport); return session; }); } internal void StartProfiling(ProfilingTarget target, SessionNode session, bool openReport = true) { JoinableTaskFactory.Run(async () => { await JoinableTaskFactory.SwitchToMainThreadAsync(); if (!Utilities.SaveDirtyFiles()) { // Abort return; } if (target.ProjectTarget != null) { ProfileProjectTarget(session, target.ProjectTarget, openReport, target.UseVTune); } else if (target.StandaloneTarget != null) { ProfileStandaloneTarget(session, target.StandaloneTarget, openReport, target.UseVTune); } else { if (MessageBox.Show(Strings.ProfilingSessionNotConfigured, Strings.NoProfilingTargetTitle, MessageBoxButton.YesNo) == MessageBoxResult.Yes) { var newTarget = session.OpenTargetProperties(); if (newTarget != null && (newTarget.ProjectTarget != null || newTarget.StandaloneTarget != null)) { StartProfiling(newTarget, session, openReport); } } } }); } private void ProfileProjectTarget(SessionNode session, ProjectTarget projectTarget, bool openReport, bool useVTune) { var project = Solution.EnumerateLoadedPythonProjects() .SingleOrDefault(p => p.GetProjectIDGuidProperty() == projectTarget.TargetProject); if (project != null) { ProfileProject(session, project, openReport, useVTune); } else { MessageBox.Show(Strings.ProjectNotFoundInSolution, Strings.ProductTitle); } } private static void ProfileProject(SessionNode session, PythonProjectNode project, bool openReport, bool useVTune) { LaunchConfiguration config = null; try { config = project?.GetLaunchConfigurationOrThrow(); } catch (NoInterpretersException ex) { PythonToolsPackage.OpenNoInterpretersHelpPage(session._serviceProvider, ex.HelpPage); return; } catch (MissingInterpreterException ex) { MessageBox.Show(ex.Message, Strings.ProductTitle); return; } catch (IOException ex) { MessageBox.Show(ex.Message, Strings.ProductTitle); return; } if (config == null) { MessageBox.Show(Strings.ProjectInterpreterNotFound.FormatUI(project.GetNameProperty()), Strings.ProductTitle); return; } if (string.IsNullOrEmpty(config.ScriptName)) { MessageBox.Show(Strings.NoProjectStartupFile, Strings.ProductTitle); return; } if (string.IsNullOrEmpty(config.WorkingDirectory) || config.WorkingDirectory == ".") { config.WorkingDirectory = project.ProjectHome; if (string.IsNullOrEmpty(config.WorkingDirectory)) { config.WorkingDirectory = Path.GetDirectoryName(config.ScriptName); } } #if EXTERNAL_PROFILER_DRIVER if (useVTune) { RunVTune(session, config, openReport); } else { #endif RunProfiler(session, config, openReport); #if EXTERNAL_PROFILER_DRIVER } #endif } private static void ProfileStandaloneTarget(SessionNode session, StandaloneTarget runTarget, bool openReport, bool useVTune) { LaunchConfiguration config; if (runTarget.PythonInterpreter != null) { var registry = session._serviceProvider.GetComponentModel().GetService<IInterpreterRegistryService>(); var interpreter = registry.FindConfiguration(runTarget.PythonInterpreter.Id); if (interpreter == null) { return; } config = new LaunchConfiguration(interpreter); } else { config = new LaunchConfiguration(null); } config.InterpreterPath = runTarget.InterpreterPath; config.ScriptName = runTarget.Script; config.ScriptArguments = runTarget.Arguments; config.WorkingDirectory = runTarget.WorkingDirectory; #if EXTERNAL_PROFILER_DRIVER if (useVTune) { RunVTune(session, config, openReport); } else { #endif RunProfiler(session, config, openReport); #if EXTERNAL_PROFILER_DRIVER } #endif } #if EXTERNAL_PROFILER_DRIVER private static void RunVTune(SessionNode session, LaunchConfiguration config, bool openReport) { var interpreter = config.GetInterpreterPath(); if (!File.Exists(interpreter)) { MessageBox.Show(Strings.CannotFindPythonInterpreter, Strings.ProductTitle); return; } string outPathDir = Path.GetTempPath(); var subpath = Path.Combine(outPathDir, Path.GetRandomFileName()); while (Directory.Exists(subpath) || File.Exists(subpath)) { subpath = Path.Combine(outPathDir, Path.GetRandomFileName()); } outPathDir = subpath; string outPath = Path.Combine(outPathDir, "pythontrace.diagsession"); var driver = PythonToolsInstallPath.GetFile(ExternalProfilerDriverExe, typeof(PythonProfilingPackage).Assembly); var procInfo = new ProcessStartInfo(driver) { CreateNoWindow = false, Arguments = string.Join(" ", new[] { "-d", ProcessOutput.QuoteSingleArgument(outPathDir), "--", ProcessOutput.QuoteSingleArgument(interpreter), config.InterpreterArguments, string.IsNullOrEmpty(config.ScriptName) ? "" : ProcessOutput.QuoteSingleArgument(config.ScriptName), config.ScriptArguments }), WorkingDirectory = config.WorkingDirectory, }; var proc = new Process { StartInfo = procInfo }; var dte = (EnvDTE.DTE)session._serviceProvider.GetService(typeof(EnvDTE.DTE)); proc.EnableRaisingEvents = true; proc.Exited += (_, args) => { if (!File.Exists(Path.Combine(outPathDir, "Sample.dwjson"))) { MessageBox.Show(Strings.CannotFindGeneratedFile, Strings.ProductTitle); } else { PackageTrace(outPathDir); dte.ItemOperations.OpenFile(Path.Combine(outPathDir, "trace.diagsession")); } }; proc.Start(); } #endif private static void RunProfiler(SessionNode session, LaunchConfiguration config, bool openReport) { var process = new ProfiledProcess( (PythonToolsService)session._serviceProvider.GetService(typeof(PythonToolsService)), config.GetInterpreterPath(), string.Join(" ", ProcessOutput.QuoteSingleArgument(config.ScriptName), config.ScriptArguments), config.WorkingDirectory, session._serviceProvider.GetPythonToolsService().GetFullEnvironment(config) ); string baseName = Path.GetFileNameWithoutExtension(session.Filename); string date = DateTime.Now.ToString("yyyyMMdd"); string outPath = Path.Combine(Path.GetTempPath(), baseName + "_" + date + ".vsp"); int count = 1; while (File.Exists(outPath)) { outPath = Path.Combine(Path.GetTempPath(), baseName + "_" + date + "(" + count + ").vsp"); count++; } process.ProcessExited += (sender, args) => { _profilingProcess = null; _stopCommand.Enabled = false; _startCommand.Enabled = true; if (openReport && File.Exists(outPath)) { for (int retries = 10; retries > 0; --retries) { try { using (new FileStream(outPath, FileMode.Open, FileAccess.Read, FileShare.None)) { } break; } catch (IOException) { Thread.Sleep(100); } } ((PythonProfilingPackage)session._serviceProvider).OpenFileAsync(outPath).DoNotWait(); } }; session.AddProfile(outPath); process.StartProfiling(outPath); _profilingProcess = process; _stopCommand.Enabled = true; _startCommand.Enabled = false; } private async Task OpenFileAsync(string outPath) { await JoinableTaskFactory.SwitchToMainThreadAsync(DisposalToken); var dte = (EnvDTE.DTE)GetService(typeof(EnvDTE.DTE)); dte.ItemOperations.OpenFile(outPath); } /// <summary> /// This function is the callback used to execute a command when the a menu item is clicked. /// See the Initialize method to see how the menu item is associated to this function using /// the OleMenuCommandService service and the MenuCommand class. /// </summary> private async Task ShowPeformanceExplorerAsync() { try { await ShowPerformanceExplorerAsync(); } catch (Exception ex) when (!ex.IsCriticalException()) { MessageBox.Show(Strings.ProfilingSupportMissingError, Strings.ProductTitle); } } internal async Task<PerfToolWindow> ShowPerformanceExplorerAsync() { if (!IsProfilingInstalled()) { throw new InvalidOperationException(); } var windowPane = await GetPerfToolWindowAsync(); if (!(windowPane is PerfToolWindow pane)) { throw new InvalidOperationException(); } if (!(pane.Frame is IVsWindowFrame frame)) { throw new InvalidOperationException(); } ErrorHandler.ThrowOnFailure(frame.Show()); return pane; } private async Task<WindowPane> GetPerfToolWindowAsync() { await JoinableTaskFactory.SwitchToMainThreadAsync(DisposalToken); var type = typeof(PerfToolWindow); return FindWindowPane(type, 0, false) ?? CreateToolWindow(type, 0, this); } private async Task AddPerformanceSessionAsync() { await JoinableTaskFactory.SwitchToMainThreadAsync(DisposalToken); var dte = (EnvDTE.DTE)GetService(typeof(EnvDTE.DTE)); var filename = Strings.PerformanceBaseFileName + ".pyperf"; var save = false; if (dte.Solution.IsOpen && !string.IsNullOrEmpty(dte.Solution.FullName)) { filename = Path.Combine(Path.GetDirectoryName(dte.Solution.FullName), filename); save = true; } var explorer = await ShowPerformanceExplorerAsync(); explorer.Sessions.AddTarget(new ProfilingTarget(), filename, save); } private async Task StartProfilingAsync() { var explorer = await ShowPerformanceExplorerAsync(); explorer.Sessions.StartProfiling(); } private void StopProfiling(object sender, EventArgs e) { var process = _profilingProcess; if (process != null) { process.StopProfiling(); } } private void IsProfilingActive(object sender, EventArgs args) { var oleMenu = sender as OleMenuCommand; if (_profilingProcess != null) { oleMenu.Enabled = false; } else { oleMenu.Enabled = true; } } private void IsProfilingInactive(object sender, EventArgs args) { var oleMenu = sender as OleMenuCommand; if (_profilingProcess != null) { oleMenu.Enabled = true; } else { oleMenu.Enabled = false; } } internal bool IsProfilingInstalled() { IVsShell shell = (IVsShell)GetService(typeof(IVsShell)); Guid perfGuid = GuidList.GuidPerfPkg; int installed; ErrorHandler.ThrowOnFailure( shell.IsPackageInstalled(ref perfGuid, out installed) ); return installed != 0; } public bool IsProfiling { get { return _profilingProcess != null; } } #if EXTERNAL_PROFILER_DRIVER public static bool CheckForExternalProfiler() { var driver = PythonToolsInstallPath.TryGetFile(ExternalProfilerDriverExe, typeof(PythonProfilingPackage).Assembly); if (string.IsNullOrEmpty(driver)) { return false; } try { var psi = new ProcessStartInfo(driver, "-p") { UseShellExecute = false, // Arguments = args, CreateNoWindow = true, RedirectStandardOutput = false, RedirectStandardError = false, }; using (var process = Process.Start(psi)) { process.WaitForExit(); return (process.ExitCode == 0); } } catch (Exception ex) { Debug.Fail($"Failed to launch {driver} because {ex}"); } return false; } public static void PackageTrace(string dirname) { var cpuToolId = new Guid("96f1f3e8-f762-4cd2-8ed9-68ec25c2c722"); using (var package = DhPackage.CreateLegacyPackage()) { package.AddTool(ref cpuToolId); // Contains the data to analyze package.CreateResourceFromPath( "DiagnosticsHub.Resource.DWJsonFile", Path.Combine(dirname, "Sample.dwjson"), null, CompressionOption.CompressionOption_Normal); // Counter data to show in swimlane package.CreateResourceFromPath( "DiagnosticsHub.Resource.CountersFile", Path.Combine(dirname, "Session.counters"), null, CompressionOption.CompressionOption_Normal); // You can add the commit option (CommitOption.CommitOption_CleanUpResources) and it will delete // the resources added from disk after they have been committed to the DiagSession package.CommitToPath(Path.Combine(dirname, "trace"), CommitOption.CommitOption_Archive); } } #endif } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Staff Purchasing Group Link Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class RQRELDataSet : EduHubDataSet<RQREL> { /// <inheritdoc /> public override string Name { get { return "RQREL"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal RQRELDataSet(EduHubContext Context) : base(Context) { Index_RQPGKEY = new Lazy<Dictionary<string, IReadOnlyList<RQREL>>>(() => this.ToGroupedDictionary(i => i.RQPGKEY)); Index_SFKEY = new Lazy<NullDictionary<string, IReadOnlyList<RQREL>>>(() => this.ToGroupedNullDictionary(i => i.SFKEY)); Index_SFKEY_RQPGKEY = new Lazy<Dictionary<Tuple<string, string>, RQREL>>(() => this.ToDictionary(i => Tuple.Create(i.SFKEY, i.RQPGKEY))); Index_TID = new Lazy<Dictionary<int, RQREL>>(() => this.ToDictionary(i => i.TID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="RQREL" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="RQREL" /> fields for each CSV column header</returns> internal override Action<RQREL, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<RQREL, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "RQPGKEY": mapper[i] = (e, v) => e.RQPGKEY = v; break; case "SFKEY": mapper[i] = (e, v) => e.SFKEY = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="RQREL" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="RQREL" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="RQREL" /> entities</param> /// <returns>A merged <see cref="IEnumerable{RQREL}"/> of entities</returns> internal override IEnumerable<RQREL> ApplyDeltaEntities(IEnumerable<RQREL> Entities, List<RQREL> DeltaEntities) { HashSet<Tuple<string, string>> Index_SFKEY_RQPGKEY = new HashSet<Tuple<string, string>>(DeltaEntities.Select(i => Tuple.Create(i.SFKEY, i.RQPGKEY))); HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.RQPGKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = false; overwritten = overwritten || Index_SFKEY_RQPGKEY.Remove(Tuple.Create(entity.SFKEY, entity.RQPGKEY)); overwritten = overwritten || Index_TID.Remove(entity.TID); if (entity.RQPGKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<string, IReadOnlyList<RQREL>>> Index_RQPGKEY; private Lazy<NullDictionary<string, IReadOnlyList<RQREL>>> Index_SFKEY; private Lazy<Dictionary<Tuple<string, string>, RQREL>> Index_SFKEY_RQPGKEY; private Lazy<Dictionary<int, RQREL>> Index_TID; #endregion #region Index Methods /// <summary> /// Find RQREL by RQPGKEY field /// </summary> /// <param name="RQPGKEY">RQPGKEY value used to find RQREL</param> /// <returns>List of related RQREL entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<RQREL> FindByRQPGKEY(string RQPGKEY) { return Index_RQPGKEY.Value[RQPGKEY]; } /// <summary> /// Attempt to find RQREL by RQPGKEY field /// </summary> /// <param name="RQPGKEY">RQPGKEY value used to find RQREL</param> /// <param name="Value">List of related RQREL entities</param> /// <returns>True if the list of related RQREL entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByRQPGKEY(string RQPGKEY, out IReadOnlyList<RQREL> Value) { return Index_RQPGKEY.Value.TryGetValue(RQPGKEY, out Value); } /// <summary> /// Attempt to find RQREL by RQPGKEY field /// </summary> /// <param name="RQPGKEY">RQPGKEY value used to find RQREL</param> /// <returns>List of related RQREL entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<RQREL> TryFindByRQPGKEY(string RQPGKEY) { IReadOnlyList<RQREL> value; if (Index_RQPGKEY.Value.TryGetValue(RQPGKEY, out value)) { return value; } else { return null; } } /// <summary> /// Find RQREL by SFKEY field /// </summary> /// <param name="SFKEY">SFKEY value used to find RQREL</param> /// <returns>List of related RQREL entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<RQREL> FindBySFKEY(string SFKEY) { return Index_SFKEY.Value[SFKEY]; } /// <summary> /// Attempt to find RQREL by SFKEY field /// </summary> /// <param name="SFKEY">SFKEY value used to find RQREL</param> /// <param name="Value">List of related RQREL entities</param> /// <returns>True if the list of related RQREL entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySFKEY(string SFKEY, out IReadOnlyList<RQREL> Value) { return Index_SFKEY.Value.TryGetValue(SFKEY, out Value); } /// <summary> /// Attempt to find RQREL by SFKEY field /// </summary> /// <param name="SFKEY">SFKEY value used to find RQREL</param> /// <returns>List of related RQREL entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<RQREL> TryFindBySFKEY(string SFKEY) { IReadOnlyList<RQREL> value; if (Index_SFKEY.Value.TryGetValue(SFKEY, out value)) { return value; } else { return null; } } /// <summary> /// Find RQREL by SFKEY and RQPGKEY fields /// </summary> /// <param name="SFKEY">SFKEY value used to find RQREL</param> /// <param name="RQPGKEY">RQPGKEY value used to find RQREL</param> /// <returns>Related RQREL entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public RQREL FindBySFKEY_RQPGKEY(string SFKEY, string RQPGKEY) { return Index_SFKEY_RQPGKEY.Value[Tuple.Create(SFKEY, RQPGKEY)]; } /// <summary> /// Attempt to find RQREL by SFKEY and RQPGKEY fields /// </summary> /// <param name="SFKEY">SFKEY value used to find RQREL</param> /// <param name="RQPGKEY">RQPGKEY value used to find RQREL</param> /// <param name="Value">Related RQREL entity</param> /// <returns>True if the related RQREL entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySFKEY_RQPGKEY(string SFKEY, string RQPGKEY, out RQREL Value) { return Index_SFKEY_RQPGKEY.Value.TryGetValue(Tuple.Create(SFKEY, RQPGKEY), out Value); } /// <summary> /// Attempt to find RQREL by SFKEY and RQPGKEY fields /// </summary> /// <param name="SFKEY">SFKEY value used to find RQREL</param> /// <param name="RQPGKEY">RQPGKEY value used to find RQREL</param> /// <returns>Related RQREL entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public RQREL TryFindBySFKEY_RQPGKEY(string SFKEY, string RQPGKEY) { RQREL value; if (Index_SFKEY_RQPGKEY.Value.TryGetValue(Tuple.Create(SFKEY, RQPGKEY), out value)) { return value; } else { return null; } } /// <summary> /// Find RQREL by TID field /// </summary> /// <param name="TID">TID value used to find RQREL</param> /// <returns>Related RQREL entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public RQREL FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find RQREL by TID field /// </summary> /// <param name="TID">TID value used to find RQREL</param> /// <param name="Value">Related RQREL entity</param> /// <returns>True if the related RQREL entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out RQREL Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find RQREL by TID field /// </summary> /// <param name="TID">TID value used to find RQREL</param> /// <returns>Related RQREL entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public RQREL TryFindByTID(int TID) { RQREL value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a RQREL table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[RQREL]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[RQREL]( [TID] int IDENTITY NOT NULL, [RQPGKEY] varchar(10) NOT NULL, [SFKEY] varchar(4) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [RQREL_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE CLUSTERED INDEX [RQREL_Index_RQPGKEY] ON [dbo].[RQREL] ( [RQPGKEY] ASC ); CREATE NONCLUSTERED INDEX [RQREL_Index_SFKEY] ON [dbo].[RQREL] ( [SFKEY] ASC ); CREATE NONCLUSTERED INDEX [RQREL_Index_SFKEY_RQPGKEY] ON [dbo].[RQREL] ( [SFKEY] ASC, [RQPGKEY] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[RQREL]') AND name = N'RQREL_Index_SFKEY') ALTER INDEX [RQREL_Index_SFKEY] ON [dbo].[RQREL] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[RQREL]') AND name = N'RQREL_Index_SFKEY_RQPGKEY') ALTER INDEX [RQREL_Index_SFKEY_RQPGKEY] ON [dbo].[RQREL] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[RQREL]') AND name = N'RQREL_Index_TID') ALTER INDEX [RQREL_Index_TID] ON [dbo].[RQREL] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[RQREL]') AND name = N'RQREL_Index_SFKEY') ALTER INDEX [RQREL_Index_SFKEY] ON [dbo].[RQREL] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[RQREL]') AND name = N'RQREL_Index_SFKEY_RQPGKEY') ALTER INDEX [RQREL_Index_SFKEY_RQPGKEY] ON [dbo].[RQREL] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[RQREL]') AND name = N'RQREL_Index_TID') ALTER INDEX [RQREL_Index_TID] ON [dbo].[RQREL] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="RQREL"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="RQREL"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<RQREL> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<Tuple<string, string>> Index_SFKEY_RQPGKEY = new List<Tuple<string, string>>(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_SFKEY_RQPGKEY.Add(Tuple.Create(entity.SFKEY, entity.RQPGKEY)); Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[RQREL] WHERE"); // Index_SFKEY_RQPGKEY builder.Append("("); for (int index = 0; index < Index_SFKEY_RQPGKEY.Count; index++) { if (index != 0) builder.Append(" OR "); // SFKEY if (Index_SFKEY_RQPGKEY[index].Item1 == null) { builder.Append("([SFKEY] IS NULL"); } else { var parameterSFKEY = $"@p{parameterIndex++}"; builder.Append("([SFKEY]=").Append(parameterSFKEY); command.Parameters.Add(parameterSFKEY, SqlDbType.VarChar, 4).Value = Index_SFKEY_RQPGKEY[index].Item1; } // RQPGKEY var parameterRQPGKEY = $"@p{parameterIndex++}"; builder.Append(" AND [RQPGKEY]=").Append(parameterRQPGKEY).Append(")"); command.Parameters.Add(parameterRQPGKEY, SqlDbType.VarChar, 10).Value = Index_SFKEY_RQPGKEY[index].Item2; } builder.AppendLine(") OR"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the RQREL data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the RQREL data set</returns> public override EduHubDataSetDataReader<RQREL> GetDataSetDataReader() { return new RQRELDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the RQREL data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the RQREL data set</returns> public override EduHubDataSetDataReader<RQREL> GetDataSetDataReader(List<RQREL> Entities) { return new RQRELDataReader(new EduHubDataSetLoadedReader<RQREL>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class RQRELDataReader : EduHubDataSetDataReader<RQREL> { public RQRELDataReader(IEduHubDataSetReader<RQREL> Reader) : base (Reader) { } public override int FieldCount { get { return 6; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // RQPGKEY return Current.RQPGKEY; case 2: // SFKEY return Current.SFKEY; case 3: // LW_DATE return Current.LW_DATE; case 4: // LW_TIME return Current.LW_TIME; case 5: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // SFKEY return Current.SFKEY == null; case 3: // LW_DATE return Current.LW_DATE == null; case 4: // LW_TIME return Current.LW_TIME == null; case 5: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // RQPGKEY return "RQPGKEY"; case 2: // SFKEY return "SFKEY"; case 3: // LW_DATE return "LW_DATE"; case 4: // LW_TIME return "LW_TIME"; case 5: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "RQPGKEY": return 1; case "SFKEY": return 2; case "LW_DATE": return 3; case "LW_TIME": return 4; case "LW_USER": return 5; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using IndexReader = Lucene.Net.Index.IndexReader; using Term = Lucene.Net.Index.Term; using TermDocs = Lucene.Net.Index.TermDocs; using ToStringUtils = Lucene.Net.Util.ToStringUtils; namespace Lucene.Net.Search { /// <summary>A Query that matches documents containing a term. /// This may be combined with other terms with a {@link BooleanQuery}. /// </summary> [Serializable] public class TermQuery : Query { private Term term; [Serializable] private class TermWeight : Weight { private void InitBlock(TermQuery enclosingInstance) { this.enclosingInstance = enclosingInstance; } private TermQuery enclosingInstance; public TermQuery Enclosing_Instance { get { return enclosingInstance; } } private Similarity similarity; private float value_Renamed; private float idf; private float queryNorm; private float queryWeight; public TermWeight(TermQuery enclosingInstance, Searcher searcher) { InitBlock(enclosingInstance); this.similarity = Enclosing_Instance.GetSimilarity(searcher); idf = similarity.Idf(Enclosing_Instance.term, searcher); // compute idf } public override System.String ToString() { return "weight(" + Enclosing_Instance + ")"; } public virtual Query GetQuery() { return Enclosing_Instance; } public virtual float GetValue() { return value_Renamed; } public virtual float SumOfSquaredWeights() { queryWeight = idf * Enclosing_Instance.GetBoost(); // compute query weight return queryWeight * queryWeight; // square it } public virtual void Normalize(float queryNorm) { this.queryNorm = queryNorm; queryWeight *= queryNorm; // normalize query weight value_Renamed = queryWeight * idf; // idf for document } public virtual Scorer Scorer(IndexReader reader) { TermDocs termDocs = reader.TermDocs(Enclosing_Instance.term); if (termDocs == null) return null; return new TermScorer(this, termDocs, similarity, reader.Norms(Enclosing_Instance.term.Field())); } public virtual Explanation Explain(IndexReader reader, int doc) { ComplexExplanation result = new ComplexExplanation(); result.SetDescription("weight(" + GetQuery() + " in " + doc + "), product of:"); Explanation idfExpl = new Explanation(idf, "idf(docFreq=" + reader.DocFreq(Enclosing_Instance.term) + ", numDocs=" + reader.NumDocs() + ")"); // explain query weight Explanation queryExpl = new Explanation(); queryExpl.SetDescription("queryWeight(" + GetQuery() + "), product of:"); Explanation boostExpl = new Explanation(Enclosing_Instance.GetBoost(), "boost"); if (Enclosing_Instance.GetBoost() != 1.0f) queryExpl.AddDetail(boostExpl); queryExpl.AddDetail(idfExpl); Explanation queryNormExpl = new Explanation(queryNorm, "queryNorm"); queryExpl.AddDetail(queryNormExpl); queryExpl.SetValue(boostExpl.GetValue() * idfExpl.GetValue() * queryNormExpl.GetValue()); result.AddDetail(queryExpl); // explain field weight System.String field = Enclosing_Instance.term.Field(); ComplexExplanation fieldExpl = new ComplexExplanation(); fieldExpl.SetDescription("fieldWeight(" + Enclosing_Instance.term + " in " + doc + "), product of:"); Explanation tfExpl = Scorer(reader).Explain(doc); fieldExpl.AddDetail(tfExpl); fieldExpl.AddDetail(idfExpl); Explanation fieldNormExpl = new Explanation(); byte[] fieldNorms = reader.Norms(field); float fieldNorm = fieldNorms != null ? Similarity.DecodeNorm(fieldNorms[doc]) : 0.0f; fieldNormExpl.SetValue(fieldNorm); fieldNormExpl.SetDescription("fieldNorm(field=" + field + ", doc=" + doc + ")"); fieldExpl.AddDetail(fieldNormExpl); fieldExpl.SetMatch(tfExpl.IsMatch()); fieldExpl.SetValue(tfExpl.GetValue() * idfExpl.GetValue() * fieldNormExpl.GetValue()); result.AddDetail(fieldExpl); System.Boolean tempAux = fieldExpl.GetMatch(); result.SetMatch(tempAux); // combine them result.SetValue(queryExpl.GetValue() * fieldExpl.GetValue()); if (queryExpl.GetValue() == 1.0f) return fieldExpl; return result; } } /// <summary>Constructs a query for the term <code>t</code>. </summary> public TermQuery(Term t) { term = t; } /// <summary>Returns the term of this query. </summary> public virtual Term GetTerm() { return term; } protected internal override Weight CreateWeight(Searcher searcher) { return new TermWeight(this, searcher); } public override void ExtractTerms(System.Collections.Hashtable terms) { Term term = GetTerm(); if (terms.Contains(term) == false) { terms.Add(term, term); } } /// <summary>Prints a user-readable version of this query. </summary> public override System.String ToString(System.String field) { System.Text.StringBuilder buffer = new System.Text.StringBuilder(); if (!term.Field().Equals(field)) { buffer.Append(term.Field()); buffer.Append(":"); } buffer.Append(term.Text()); buffer.Append(ToStringUtils.Boost(GetBoost())); return buffer.ToString(); } /// <summary>Returns true iff <code>o</code> is equal to this. </summary> public override bool Equals(object o) { if (!(o is TermQuery)) return false; TermQuery other = (TermQuery) o; return (this.GetBoost() == other.GetBoost()) && this.term.Equals(other.term); } /// <summary>Returns a hash code value for this object.</summary> public override int GetHashCode() { return BitConverter.ToInt32(BitConverter.GetBytes(GetBoost()), 0) ^ term.GetHashCode(); } } }
using Lucene.Net.Diagnostics; using Lucene.Net.Documents; using Lucene.Net.Support; using NUnit.Framework; using System; using System.Collections.Generic; using Assert = Lucene.Net.TestFramework.Assert; namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using BooleanWeight = Lucene.Net.Search.BooleanQuery.BooleanWeight; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using IBits = Lucene.Net.Util.IBits; using IndexReader = Lucene.Net.Index.IndexReader; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using Term = Lucene.Net.Index.Term; using TextField = TextField; [TestFixture] public class TestBooleanScorer : LuceneTestCase { private const string FIELD = "category"; [Test] public virtual void TestMethod() { Directory directory = NewDirectory(); string[] values = new string[] { "1", "2", "3", "4" }; RandomIndexWriter writer = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, directory); for (int i = 0; i < values.Length; i++) { Document doc = new Document(); doc.Add(NewStringField(FIELD, values[i], Field.Store.YES)); writer.AddDocument(doc); } IndexReader ir = writer.GetReader(); writer.Dispose(); BooleanQuery booleanQuery1 = new BooleanQuery(); booleanQuery1.Add(new TermQuery(new Term(FIELD, "1")), Occur.SHOULD); booleanQuery1.Add(new TermQuery(new Term(FIELD, "2")), Occur.SHOULD); BooleanQuery query = new BooleanQuery(); query.Add(booleanQuery1, Occur.MUST); query.Add(new TermQuery(new Term(FIELD, "9")), Occur.MUST_NOT); IndexSearcher indexSearcher = NewSearcher(ir); ScoreDoc[] hits = indexSearcher.Search(query, null, 1000).ScoreDocs; Assert.AreEqual(2, hits.Length, "Number of matched documents"); ir.Dispose(); directory.Dispose(); } [Test] public virtual void TestEmptyBucketWithMoreDocs() { // this test checks the logic of nextDoc() when all sub scorers have docs // beyond the first bucket (for example). Currently, the code relies on the // 'more' variable to work properly, and this test ensures that if the logic // changes, we have a test to back it up. Directory directory = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, directory); writer.Commit(); IndexReader ir = writer.GetReader(); writer.Dispose(); IndexSearcher searcher = NewSearcher(ir); BooleanWeight weight = (BooleanWeight)(new BooleanQuery()).CreateWeight(searcher); BulkScorer[] scorers = new BulkScorer[] { new BulkScorerAnonymousClass() }; BooleanScorer bs = new BooleanScorer(weight, false, 1, scorers, Collections.EmptyList<BulkScorer>(), scorers.Length); IList<int> hits = new List<int>(); bs.Score(new CollectorAnonymousClass(this, hits)); Assert.AreEqual(1, hits.Count, "should have only 1 hit"); Assert.AreEqual(3000, (int)hits[0], "hit should have been docID=3000"); ir.Dispose(); directory.Dispose(); } private class BulkScorerAnonymousClass : BulkScorer { private int doc = -1; public override bool Score(ICollector c, int maxDoc) { if (Debugging.AssertsEnabled) Debugging.Assert(doc == -1); doc = 3000; FakeScorer fs = new FakeScorer(); fs.doc = doc; fs.score = 1.0f; c.SetScorer(fs); c.Collect(3000); return false; } } private class CollectorAnonymousClass : ICollector { private readonly TestBooleanScorer outerInstance; private readonly IList<int> hits; public CollectorAnonymousClass(TestBooleanScorer outerInstance, IList<int> hits) { this.outerInstance = outerInstance; this.hits = hits; } internal int docBase; public virtual void SetScorer(Scorer scorer) { } public virtual void Collect(int doc) { hits.Add(docBase + doc); } public virtual void SetNextReader(AtomicReaderContext context) { docBase = context.DocBase; } public virtual bool AcceptsDocsOutOfOrder => true; } [Test] public virtual void TestMoreThan32ProhibitedClauses() { Directory d = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, d); Document doc = new Document(); doc.Add(new TextField("field", "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", Field.Store.NO)); w.AddDocument(doc); doc = new Document(); doc.Add(new TextField("field", "33", Field.Store.NO)); w.AddDocument(doc); IndexReader r = w.GetReader(); w.Dispose(); // we don't wrap with AssertingIndexSearcher in order to have the original scorer in setScorer. IndexSearcher s = NewSearcher(r, true, false); BooleanQuery q = new BooleanQuery(); for (int term = 0; term < 33; term++) { q.Add(new BooleanClause(new TermQuery(new Term("field", "" + term)), Occur.MUST_NOT)); } q.Add(new BooleanClause(new TermQuery(new Term("field", "33")), Occur.SHOULD)); int[] count = new int[1]; s.Search(q, new CollectorAnonymousClass2(this, doc, count)); Assert.AreEqual(1, count[0]); r.Dispose(); d.Dispose(); } private class CollectorAnonymousClass2 : ICollector { private readonly TestBooleanScorer outerInstance; private Document doc; private readonly int[] count; public CollectorAnonymousClass2(TestBooleanScorer outerInstance, Document doc, int[] count) { this.outerInstance = outerInstance; this.doc = doc; this.count = count; } public virtual void SetScorer(Scorer scorer) { // Make sure we got BooleanScorer: Type clazz = scorer.GetType(); Assert.AreEqual(typeof(FakeScorer).Name, clazz.Name, "Scorer is implemented by wrong class"); } public virtual void Collect(int doc) { count[0]++; } public virtual void SetNextReader(AtomicReaderContext context) { } public virtual bool AcceptsDocsOutOfOrder => true; } /// <summary> /// Throws UOE if Weight.scorer is called </summary> private class CrazyMustUseBulkScorerQuery : Query { public override string ToString(string field) { return "MustUseBulkScorerQuery"; } public override Weight CreateWeight(IndexSearcher searcher) { return new WeightAnonymousClass(this); } private class WeightAnonymousClass : Weight { private readonly CrazyMustUseBulkScorerQuery outerInstance; public WeightAnonymousClass(CrazyMustUseBulkScorerQuery outerInstance) { this.outerInstance = outerInstance; } public override Explanation Explain(AtomicReaderContext context, int doc) { throw UnsupportedOperationException.Create(); } public override Query Query => outerInstance; public override float GetValueForNormalization() { return 1.0f; } public override void Normalize(float norm, float topLevelBoost) { } public override Scorer GetScorer(AtomicReaderContext context, IBits acceptDocs) { throw UnsupportedOperationException.Create(); } public override BulkScorer GetBulkScorer(AtomicReaderContext context, bool scoreDocsInOrder, IBits acceptDocs) { return new BulkScorerAnonymousClass(this); } private class BulkScorerAnonymousClass : BulkScorer { private readonly WeightAnonymousClass outerInstance; public BulkScorerAnonymousClass(WeightAnonymousClass outerInstance) { this.outerInstance = outerInstance; } public override bool Score(ICollector collector, int max) { collector.SetScorer(new FakeScorer()); collector.Collect(0); return false; } } } } /// <summary> /// Make sure BooleanScorer can embed another /// BooleanScorer. /// </summary> [Test] public virtual void TestEmbeddedBooleanScorer() { Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif Random, dir); Document doc = new Document(); doc.Add(NewTextField("field", "doctors are people who prescribe medicines of which they know little, to cure diseases of which they know less, in human beings of whom they know nothing", Field.Store.NO)); w.AddDocument(doc); IndexReader r = w.GetReader(); w.Dispose(); IndexSearcher s = NewSearcher(r); BooleanQuery q1 = new BooleanQuery(); q1.Add(new TermQuery(new Term("field", "little")), Occur.SHOULD); q1.Add(new TermQuery(new Term("field", "diseases")), Occur.SHOULD); BooleanQuery q2 = new BooleanQuery(); q2.Add(q1, Occur.SHOULD); q2.Add(new CrazyMustUseBulkScorerQuery(), Occur.SHOULD); Assert.AreEqual(1, s.Search(q2, 10).TotalHits); r.Dispose(); dir.Dispose(); } } }
/* * 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 ArrayUtil = Lucene.Net.Util.ArrayUtil; namespace Lucene.Net.Index { /// <summary>This is just a "splitter" class: it lets you wrap two /// DocFieldConsumer instances as a single consumer. /// </summary> sealed class DocFieldConsumers:DocFieldConsumer { private void InitBlock() { docFreeList = new PerDoc[1]; } internal DocFieldConsumer one; internal DocFieldConsumer two; public DocFieldConsumers(DocFieldConsumer one, DocFieldConsumer two) { InitBlock(); this.one = one; this.two = two; } internal override void SetFieldInfos(FieldInfos fieldInfos) { base.SetFieldInfos(fieldInfos); one.SetFieldInfos(fieldInfos); two.SetFieldInfos(fieldInfos); } public override void Flush(System.Collections.IDictionary threadsAndFields, SegmentWriteState state) { System.Collections.IDictionary oneThreadsAndFields = new System.Collections.Hashtable(); System.Collections.IDictionary twoThreadsAndFields = new System.Collections.Hashtable(); System.Collections.IEnumerator it = new System.Collections.Hashtable(threadsAndFields).GetEnumerator(); while (it.MoveNext()) { System.Collections.DictionaryEntry entry = (System.Collections.DictionaryEntry) it.Current; DocFieldConsumersPerThread perThread = (DocFieldConsumersPerThread) entry.Key; System.Collections.ICollection fields = (System.Collections.ICollection) entry.Value; System.Collections.IEnumerator fieldsIt = fields.GetEnumerator(); System.Collections.Hashtable oneFields = new System.Collections.Hashtable(); System.Collections.Hashtable twoFields = new System.Collections.Hashtable(); while (fieldsIt.MoveNext()) { DocFieldConsumersPerField perField = (DocFieldConsumersPerField) fieldsIt.Current; SupportClass.CollectionsHelper.AddIfNotContains(oneFields, perField.one); SupportClass.CollectionsHelper.AddIfNotContains(twoFields, perField.two); } oneThreadsAndFields[perThread.one] = oneFields; twoThreadsAndFields[perThread.two] = twoFields; } one.Flush(oneThreadsAndFields, state); two.Flush(twoThreadsAndFields, state); } public override void CloseDocStore(SegmentWriteState state) { try { one.CloseDocStore(state); } finally { two.CloseDocStore(state); } } public override void Abort() { try { one.Abort(); } finally { two.Abort(); } } public override bool FreeRAM() { bool any = one.FreeRAM(); any |= two.FreeRAM(); return any; } public override DocFieldConsumerPerThread AddThread(DocFieldProcessorPerThread docFieldProcessorPerThread) { return new DocFieldConsumersPerThread(docFieldProcessorPerThread, this, one.AddThread(docFieldProcessorPerThread), two.AddThread(docFieldProcessorPerThread)); } internal PerDoc[] docFreeList; internal int freeCount; internal int allocCount; internal PerDoc GetPerDoc() { lock (this) { if (freeCount == 0) { allocCount++; if (allocCount > docFreeList.Length) { // Grow our free list up front to make sure we have // enough space to recycle all outstanding PerDoc // instances System.Diagnostics.Debug.Assert(allocCount == 1 + docFreeList.Length); docFreeList = new PerDoc[ArrayUtil.GetNextSize(allocCount)]; } return new PerDoc(this); } else return docFreeList[--freeCount]; } } internal void FreePerDoc(PerDoc perDoc) { lock (this) { System.Diagnostics.Debug.Assert(freeCount < docFreeList.Length); docFreeList[freeCount++] = perDoc; } } internal class PerDoc:DocumentsWriter.DocWriter { public PerDoc(DocFieldConsumers enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(DocFieldConsumers enclosingInstance) { this.enclosingInstance = enclosingInstance; } private DocFieldConsumers enclosingInstance; public DocFieldConsumers Enclosing_Instance { get { return enclosingInstance; } } internal DocumentsWriter.DocWriter one; internal DocumentsWriter.DocWriter two; public override long SizeInBytes() { return one.SizeInBytes() + two.SizeInBytes(); } public override void Finish() { try { try { one.Finish(); } finally { two.Finish(); } } finally { Enclosing_Instance.FreePerDoc(this); } } public override void Abort() { try { try { one.Abort(); } finally { two.Abort(); } } finally { Enclosing_Instance.FreePerDoc(this); } } } } }
using System; using System.IO; using System.Collections; using System.Windows.Forms; using Tamir.SharpSsh.jsch; /* Sftp.cs * ==================================================================== * The following example was posted with the original JSch java library, * and is translated to C# to show the usage of SharpSSH JSch API * ==================================================================== * */ namespace sharpSshTest.jsch_samples { /// <summary> /// This program will demonstrate the sftp protocol support. /// You will be asked username, host and passwd. /// If everything works fine, you will get a prompt 'sftp>'. /// 'help' command will show available command. /// In current implementation, the destination path for 'get' and 'put' /// commands must be a file, not a directory. /// </summary> public class Sftp { public static void RunExample(String[] arg) { try { JSch jsch=new JSch(); InputForm inForm = new InputForm(); inForm.Text = "Enter username@hostname"; inForm.textBox1.Text = Environment.UserName+"@localhost"; if (!inForm.PromptForInput()) { Console.WriteLine("Cancelled"); return; } String host = inForm.textBox1.Text; String user=host.Substring(0, host.IndexOf('@')); host=host.Substring(host.IndexOf('@')+1); Session session=jsch.getSession(user, host, 22); // username and password will be given via UserInfo interface. UserInfo ui=new MyUserInfo(); session.setUserInfo(ui); session.connect(); Channel channel=session.openChannel("sftp"); channel.connect(); ChannelSftp c=(ChannelSftp)channel; Stream ins=Console.OpenStandardInput(); TextWriter outs=Console.Out; ArrayList cmds=new ArrayList(); byte[] buf=new byte[1024]; int i; String str; int level=0; while(true) { outs.Write("sftp> "); cmds.Clear(); i=ins.Read(buf, 0, 1024); if(i<=0)break; i--; if(i>0 && buf[i-1]==0x0d)i--; //str=Util.getString(buf, 0, i); //Console.WriteLine("|"+str+"|"); int s=0; for(int ii=0; ii<i; ii++) { if(buf[ii]==' ') { if(ii-s>0){ cmds.Add(Util.getString(buf, s, ii-s)); } while(ii<i){if(buf[ii]!=' ')break; ii++;} s=ii; } } if(s<i){ cmds.Add(Util.getString(buf, s, i-s)); } if(cmds.Count==0)continue; String cmd=(String)cmds[0]; if(cmd.Equals("quit")) { c.quit(); break; } if(cmd.Equals("exit")) { c.exit(); break; } if(cmd.Equals("rekey")) { session.rekey(); continue; } if(cmd.Equals("compression")) { if(cmds.Count<2) { outs.WriteLine("compression level: "+level); continue; } try { level=int.Parse((String)cmds[1]); Hashtable config=new Hashtable(); if(level==0) { config.Add("compression.s2c", "none"); config.Add("compression.c2s", "none"); } else { config.Add("compression.s2c", "zlib,none"); config.Add("compression.c2s", "zlib,none"); } session.setConfig(config); } catch{}//(Exception e){} continue; } if(cmd.Equals("cd") || cmd.Equals("lcd")) { if(cmds.Count<2) continue; String path=(String)cmds[1]; try { if(cmd.Equals("cd")) c.cd(path); else c.lcd(path); } catch(SftpException e) { Console.WriteLine(e.message); } continue; } if(cmd.Equals("rm") || cmd.Equals("rmdir") || cmd.Equals("mkdir")) { if(cmds.Count<2) continue; String path=(String)cmds[1]; try { if(cmd.Equals("rm")) c.rm(path); else if(cmd.Equals("rmdir")) c.rmdir(path); else c.mkdir(path); } catch(SftpException e) { Console.WriteLine(e.message); } continue; } if(cmd.Equals("chgrp") || cmd.Equals("chown") || cmd.Equals("chmod")) { if(cmds.Count!=3) continue; String path=(String)cmds[2]; int foo=0; if(cmd.Equals("chmod")) { byte[] bar=Util.getBytes((String)cmds[1]); int k; for(int j=0; j<bar.Length; j++) { k=bar[j]; if(k<'0'||k>'7'){foo=-1; break;} foo<<=3; foo|=(k-'0'); } if(foo==-1)continue; } else { try{foo=int.Parse((String)cmds[1]);} catch{}//(Exception e){continue;} } try { if(cmd.Equals("chgrp")){ c.chgrp(foo, path); } else if(cmd.Equals("chown")){ c.chown(foo, path); } else if(cmd.Equals("chmod")){ c.chmod(foo, path); } } catch(SftpException e) { Console.WriteLine(e.message); } continue; } if(cmd.Equals("pwd") || cmd.Equals("lpwd")) { str=(cmd.Equals("pwd")?"Remote":"Local"); str+=" working directory: "; if(cmd.Equals("pwd")) str+=c.pwd(); else str+=c.lpwd(); outs.WriteLine(str); continue; } if(cmd.Equals("ls") || cmd.Equals("dir")) { String path="."; if(cmds.Count==2) path=(String)cmds[1]; try { ArrayList vv=c.ls(path); if(vv!=null) { for(int ii=0; ii<vv.Count; ii++) { object obj = vv[ii]; if(obj is ChannelSftp.LsEntry) outs.WriteLine(vv[ii]); } } } catch(SftpException e) { Console.WriteLine(e.message); } continue; } if(cmd.Equals("lls") || cmd.Equals("ldir")) { String path="."; if(cmds.Count==2) path=(String)cmds[1]; try { //java.io.File file=new java.io.File(path); if(!File.Exists(path)) { outs.WriteLine(path+": No such file or directory"); continue; } if(Directory.Exists(path)) { String[] list=Directory.GetDirectories(path); for(int ii=0; ii<list.Length; ii++) { outs.WriteLine(list[ii]); } continue; } outs.WriteLine(path); } catch(Exception e) { Console.WriteLine(e); } continue; } if(cmd.Equals("get") || cmd.Equals("get-resume") || cmd.Equals("get-append") || cmd.Equals("put") || cmd.Equals("put-resume") || cmd.Equals("put-append") ) { if(cmds.Count!=2 && cmds.Count!=3) continue; String p1=(String)cmds[1]; // String p2=p1; String p2="."; if(cmds.Count==3)p2=(String)cmds[2]; try { SftpProgressMonitor monitor=new MyProgressMonitor(); if(cmd.StartsWith("get")) { int mode=ChannelSftp.OVERWRITE; if(cmd.Equals("get-resume")){ mode=ChannelSftp.RESUME; } else if(cmd.Equals("get-append")){ mode=ChannelSftp.APPEND; } c.get(p1, p2, monitor, mode); } else { int mode=ChannelSftp.OVERWRITE; if(cmd.Equals("put-resume")){ mode=ChannelSftp.RESUME; } else if(cmd.Equals("put-append")){ mode=ChannelSftp.APPEND; } c.put(p1, p2, monitor, mode); } } catch(SftpException e) { Console.WriteLine(e.message); } continue; } if(cmd.Equals("ln") || cmd.Equals("symlink") || cmd.Equals("rename")) { if(cmds.Count!=3) continue; String p1=(String)cmds[1]; String p2=(String)cmds[2]; try { if(cmd.Equals("rename")) c.rename(p1, p2); else c.symlink(p1, p2); } catch(SftpException e) { Console.WriteLine(e.message); } continue; } if(cmd.Equals("stat") || cmd.Equals("lstat")) { if(cmds.Count!=2) continue; String p1=(String)cmds[1]; SftpATTRS attrs=null; try { if(cmd.Equals("stat")) attrs=c.stat(p1); else attrs=c.lstat(p1); } catch(SftpException e) { Console.WriteLine(e.message); } if(attrs!=null) { outs.WriteLine(attrs); } else { } continue; } if(cmd.Equals("version")) { outs.WriteLine("SFTP protocol version "+c.version()); continue; } if(cmd.Equals("help") || cmd.Equals("?")) { outs.WriteLine(help); continue; } outs.WriteLine("unimplemented command: "+cmd); } session.disconnect(); } catch(Exception e) { Console.WriteLine(e); } } public class MyUserInfo : UserInfo { public String getPassword(){ return passwd; } public bool promptYesNo(String str) { DialogResult returnVal = MessageBox.Show( str, "SharpSSH", MessageBoxButtons.YesNo, MessageBoxIcon.Warning); return (returnVal==DialogResult.Yes); } String passwd; InputForm passwordField=new InputForm(); public String getPassphrase(){ return null; } public bool promptPassphrase(String message){ return true; } public bool promptPassword(String message) { InputForm inForm = new InputForm(); inForm.Text = message; inForm.PasswordField = true; if ( inForm.PromptForInput() ) { passwd=inForm.getText(); return true; } else{ return false; } } public void showMessage(String message) { MessageBox.Show( message, "SharpSSH", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } } public class MyProgressMonitor : SftpProgressMonitor { private ConsoleProgressBar bar; private long c = 0; private long max = 0; private long percent=-1; int elapsed=-1; System.Timers.Timer timer; public override void init(int op, String src, String dest, long max) { bar = new ConsoleProgressBar(); this.max=max; elapsed=0; timer=new System.Timers.Timer(1000); timer.Start(); timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); } public override bool count(long c) { this.c += c; if(percent>=this.c*100/max){ return true; } percent=this.c*100/max; string note = ("Transfering... [Elapsed time: "+elapsed+"]"); bar.Update((int)this.c, (int)max, note); return true; } public override void end() { if (timer != null) { timer.Stop(); timer.Dispose(); } string note = ("Done in "+elapsed+" seconds!"); if (bar != null) { bar.Update((int) this.c, (int) max, note); bar = null; } } private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { this.elapsed++; } } private static String help = " Available commands:\n"+ " * means unimplemented command.\n"+ "cd path Change remote directory to 'path'\n"+ "lcd path Change local directory to 'path'\n"+ "chgrp grp path Change group of file 'path' to 'grp'\n"+ "chmod mode path Change permissions of file 'path' to 'mode'\n"+ "chown own path Change owner of file 'path' to 'own'\n"+ "help Display this help text\n"+ "get remote-path [local-path] Download file\n"+ "get-resume remote-path [local-path] Resume to download file.\n"+ "get-append remote-path [local-path] Append remote file to local file\n"+ "*lls [ls-options [path]] Display local directory listing\n"+ "ln oldpath newpath Symlink remote file\n"+ "*lmkdir path Create local directory\n"+ "lpwd Print local working directory\n"+ "ls [path] Display remote directory listing\n"+ "*lumask umask Set local umask to 'umask'\n"+ "mkdir path Create remote directory\n"+ "put local-path [remote-path] Upload file\n"+ "put-resume local-path [remote-path] Resume to upload file\n"+ "put-append local-path [remote-path] Append local file to remote file.\n"+ "pwd Display remote working directory\n"+ "stat path Display info about path\n"+ "exit Quit sftp\n"+ "quit Quit sftp\n"+ "rename oldpath newpath Rename remote file\n"+ "rmdir path Remove remote directory\n"+ "rm path Delete remote file\n"+ "symlink oldpath newpath Symlink remote file\n"+ "rekey Key re-exchanging\n"+ "compression level Packet compression will be enabled\n"+ "version Show SFTP version\n"+ "? Synonym for help"; } }
namespace Merchello.Web.Models.ContentEditing.Content { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using AutoMapper; using Merchello.Core; using Merchello.Core.Models.DetachedContent; using Merchello.Core.ValueConverters; using Merchello.Web.Models.VirtualContent; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; /// <summary> /// Utility mapping extensions for <see cref="ProductVariantDetachedContentDisplay"/>. /// </summary> internal static class DetachedContentDisplayExtensions { /// <summary> /// The to product variant detached content display. /// </summary> /// <param name="detachedContent"> /// The detached content. /// </param> /// <returns> /// The <see cref="ProductVariantDetachedContentDisplay"/>. /// </returns> public static ProductVariantDetachedContentDisplay ToProductVariantDetachedContentDisplay( this IProductVariantDetachedContent detachedContent) { return Mapper.Map<ProductVariantDetachedContentDisplay>(detachedContent); } /// <summary> /// Maps <see cref="ProductVariantDetachedContentDisplay"/> to <see cref="IProductVariantDetachedContent"/>. /// </summary> /// <param name="display"> /// The display. /// </param> /// <param name="productVariantKey"> /// The product Variant Key. /// </param> /// <returns> /// The <see cref="IProductVariantDetachedContent"/>. /// </returns> public static IProductVariantDetachedContent ToProductVariantDetachedContent(this ProductVariantDetachedContentDisplay display, Guid productVariantKey) { var contentType = new DetachedContentType( display.DetachedContentType.EntityTypeField.TypeKey, display.DetachedContentType.UmbContentType.Key) { Key = display.DetachedContentType.Key, Name = display.DetachedContentType.Name, Description = display.DetachedContentType.Description }; // Assign the default template var templateId = 0; if (display.TemplateId == 0 && display.DetachedContentType.UmbContentType.DefaultTemplateId != 0) { templateId = display.DetachedContentType.UmbContentType.DefaultTemplateId; } var pvdc = new ProductVariantDetachedContent(productVariantKey, contentType, display.CultureName, new DetachedDataValuesCollection(display.DetachedDataValues)) { TemplateId = templateId, Slug = display.Slug, CanBeRendered = display.CanBeRendered }; if (!display.Key.Equals(Guid.Empty)) pvdc.Key = display.Key; return pvdc; } /// <summary> /// The to product variant detached content. /// </summary> /// <param name="display"> /// The display. /// </param> /// <param name="destination"> /// The destination. /// </param> /// <returns> /// The <see cref="IProductVariantDetachedContent"/>. /// </returns> public static IProductVariantDetachedContent ToProductVariantDetachedContent( this ProductVariantDetachedContentDisplay display, IProductVariantDetachedContent destination) { destination.Slug = display.Slug; destination.TemplateId = display.TemplateId; destination.CanBeRendered = display.CanBeRendered; // Find any detached content items that should be removed var validPropertyTypeAliases = display.DetachedDataValues.Select(x => x.Key); var removers = destination.DetachedDataValues.Where(x => validPropertyTypeAliases.All(y => y != x.Key)); foreach (var remove in removers) { destination.DetachedDataValues.RemoveValue(remove.Key); } foreach (var item in display.DetachedDataValues) { if (!item.Key.IsNullOrWhiteSpace()) destination.DetachedDataValues.AddOrUpdate(item.Key, item.Value, (x, y) => item.Value); } return destination; } /// <summary> /// The data values as published properties. /// </summary> /// <param name="container"> /// The <see cref="ProductVariantDetachedContentDisplay"/>. /// </param> /// <param name="contentType"> /// The content type. /// </param> /// <returns> /// The <see cref="IEnumerable{IPublishedProperty}"/>. /// </returns> public static IEnumerable<IPublishedProperty> DataValuesAsPublishedProperties(this IHaveDetachedDataValues container, PublishedContentType contentType) { var properties = new List<IPublishedProperty>(); foreach (var dcv in container.DetachedDataValues) { var propType = contentType.GetPropertyType(dcv.Key); object valObj; try { valObj = DetachedValuesConverter.Current.ConvertDbForContent(propType, dcv).Value; } catch { valObj = dcv.Value; } if (propType != null) { properties.Add(new DetachedPublishedProperty(propType, valObj)); } } return properties; } /// <summary> /// Ensures the attribute data values. /// </summary> /// <param name="attribute"> /// The attribute. /// </param> /// <remarks> /// This is required as some options are shared and the attribute data values are not serialized into the /// Examine index for these attributes. /// </remarks> /// <returns> /// The detached contents. /// </returns> internal static void EnsureAttributeDetachedDataValues(this ProductAttributeDisplay attribute) { if (attribute.DetachedDataValues != null && attribute.DetachedDataValues.Any()) return; var pa = MerchelloContext.Current.Services.ProductOptionService.GetProductAttributeByKey(attribute.Key); attribute.DetachedDataValues = pa.DetachedDataValues.AsEnumerable(); } /// <summary> /// Utility for setting the IsForBackOfficeEditor property. /// </summary> /// <param name="display"> /// The display. /// </param> /// <param name="conversionType"> /// The value conversion type. /// </param> internal static void EnsureValueConversion(this ProductDisplay display, DetachedValuesConversionType conversionType = DetachedValuesConversionType.Db) { ((ProductDisplayBase)display).EnsureValueConversion(conversionType); if (display.ProductVariants.Any()) { foreach (var variant in display.ProductVariants) { variant.EnsureValueConversion(conversionType); } } } /// <summary> /// Utility for setting the IsForBackOfficeEditor property. /// </summary> /// <param name="display"> /// The display. /// </param> /// <param name="conversionType"> /// The value conversion type. /// </param> internal static void EnsureValueConversion(this ProductDisplayBase display, DetachedValuesConversionType conversionType = DetachedValuesConversionType.Db) { if (display == null) return; if (display.DetachedContents.Any()) { foreach (var dc in display.DetachedContents) { var contentType = DetachedValuesConverter.Current.GetContentTypeByKey(dc.DetachedContentType.UmbContentType.Key); if (dc.ValueConversion != conversionType && contentType != null) { dc.DetachedDataValues = DetachedValuesConverter.Current.Convert(contentType, dc.DetachedDataValues, conversionType); dc.ValueConversion = conversionType; } } } } internal static void EnsureValueConversion(this ProductOptionDisplay display, DetachedValuesConversionType conversionType = DetachedValuesConversionType.Db) { if (display.DetachedContentTypeKey.Equals(Guid.Empty)) return; var contentType = new Lazy<IContentType>(() => DetachedValuesConverter.Current.GetContentTypeByKey(display.DetachedContentTypeKey)); foreach (var choice in display.Choices.Where(x => x.ValueConversion != conversionType)) { if (contentType.Value != null) { choice.EnsureValueConversion(contentType.Value, conversionType); } } } internal static void EnsureValueConversion(this ProductAttributeDisplay display, IContentType contentType, DetachedValuesConversionType conversionType = DetachedValuesConversionType.Db) { if (display.ValueConversion == conversionType) return; display.ValueConversion = conversionType; display.DetachedDataValues = DetachedValuesConverter.Current.Convert(contentType, display.DetachedDataValues, conversionType); } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.IO; using System.Globalization; using System.Xml; using Xunit; namespace System.Data.Tests { public class DataSetReadXmlSchemaTest : DataSetAssertion, IDisposable { private DataSet CreateTestSet() { var ds = new DataSet(); ds.Tables.Add("Table1"); ds.Tables.Add("Table2"); ds.Tables[0].Columns.Add("Column1_1"); ds.Tables[0].Columns.Add("Column1_2"); ds.Tables[0].Columns.Add("Column1_3"); ds.Tables[1].Columns.Add("Column2_1"); ds.Tables[1].Columns.Add("Column2_2"); ds.Tables[1].Columns.Add("Column2_3"); ds.Tables[0].Rows.Add(new object[] { "ppp", "www", "xxx" }); ds.Relations.Add("Rel1", ds.Tables[0].Columns[2], ds.Tables[1].Columns[0]); return ds; } private CultureInfo _currentCultureBackup; public DataSetReadXmlSchemaTest() { _currentCultureBackup = CultureInfo.CurrentCulture; ; CultureInfo.CurrentCulture = new CultureInfo("fi-FI"); } public void Dispose() { CultureInfo.CurrentCulture = _currentCultureBackup; } [Fact] public void SingleElementTreatmentDifference() { // This is one of the most complicated case. When the content // type particle of 'Root' element is a complex element, it // is DataSet element. Otherwise, it is just a data table. // // But also note that there is another test named // LocaleOnRootWithoutIsDataSet(), that tests if locale on // the (mere) data table modifies *DataSet's* locale. // Moreover, when the schema contains another element // (regardless of its schema type), the elements will // never be treated as a DataSet. string xsbase = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' id='hoge'> <xs:element name='Root'> <!-- When simple, it becomes table. When complex, it becomes DataSet --> <xs:complexType> <xs:choice> {0} </xs:choice> </xs:complexType> </xs:element> </xs:schema>"; string xsbase2 = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' id='hoge'> <xs:element name='Root'> <!-- When simple, it becomes table. When complex, it becomes DataSet --> <xs:complexType> <xs:choice> {0} </xs:choice> </xs:complexType> </xs:element> <xs:element name='more' type='xs:string' /> </xs:schema>"; string simple = "<xs:element name='Child' type='xs:string' />"; string complex = @"<xs:element name='Child'> <xs:complexType> <xs:attribute name='a1' /> <xs:attribute name='a2' type='xs:integer' /> </xs:complexType> </xs:element>"; string elref = "<xs:element ref='more' />"; string xs2 = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' id='hoge'> <xs:element name='Root' type='RootType' /> <xs:complexType name='RootType'> <xs:choice> <xs:element name='Child'> <xs:complexType> <xs:attribute name='a1' /> <xs:attribute name='a2' type='xs:integer' /> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:schema>"; var ds = new DataSet(); string xs = string.Format(xsbase, simple); ds.ReadXmlSchema(new StringReader(xs)); AssertDataSet("simple", ds, "hoge", 1, 0); AssertDataTable("simple", ds.Tables[0], "Root", 1, 0, 0, 0, 0, 0); // reference to global complex type ds = new DataSet(); ds.ReadXmlSchema(new StringReader(xs2)); AssertDataSet("external complexType", ds, "hoge", 2, 1); AssertDataTable("external Tab1", ds.Tables[0], "Root", 1, 0, 0, 1, 1, 1); AssertDataTable("external Tab2", ds.Tables[1], "Child", 3, 0, 1, 0, 1, 0); // xsbase2 + complex -> datatable ds = new DataSet(); xs = string.Format(xsbase2, complex); ds.ReadXmlSchema(new StringReader(xs)); AssertDataSet("complex", ds, "hoge", 2, 1); AssertDataTable("complex", ds.Tables[0], "Root", 1, 0, 0, 1, 1, 1); DataTable dt = ds.Tables[1]; AssertDataTable("complex", dt, "Child", 3, 0, 1, 0, 1, 0); AssertDataColumn("a1", dt.Columns["a1"], "a1", true, false, 0, 1, "a1", MappingType.Attribute, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, /*0*/-1, string.Empty, false, false); AssertDataColumn("a2", dt.Columns["a2"], "a2", true, false, 0, 1, "a2", MappingType.Attribute, typeof(long), DBNull.Value, string.Empty, -1, string.Empty, /*1*/-1, string.Empty, false, false); AssertDataColumn("Root_Id", dt.Columns[2], "Root_Id", true, false, 0, 1, "Root_Id", MappingType.Hidden, typeof(int), DBNull.Value, string.Empty, -1, string.Empty, 2, string.Empty, false, false); // xsbase + complex -> dataset ds = new DataSet(); xs = string.Format(xsbase, complex); ds.ReadXmlSchema(new StringReader(xs)); AssertDataSet("complex", ds, "Root", 1, 0); ds = new DataSet(); xs = string.Format(xsbase2, elref); ds.ReadXmlSchema(new StringReader(xs)); AssertDataSet("complex", ds, "hoge", 1, 0); AssertDataTable("complex", ds.Tables[0], "Root", 1, 0, 0, 0, 0, 0); } [Fact] public void SuspiciousDataSetElement() { string schema = @"<?xml version='1.0'?> <xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'> <xsd:attribute name='foo' type='xsd:string'/> <xsd:attribute name='bar' type='xsd:string'/> <xsd:complexType name='attRef'> <xsd:attribute name='att1' type='xsd:int'/> <xsd:attribute name='att2' type='xsd:string'/> </xsd:complexType> <xsd:element name='doc'> <xsd:complexType> <xsd:choice> <xsd:element name='elem' type='attRef'/> </xsd:choice> </xsd:complexType> </xsd:element> </xsd:schema>"; var ds = new DataSet(); ds.ReadXmlSchema(new StringReader(schema)); AssertDataSet("ds", ds, "doc", 1, 0); AssertDataTable("table", ds.Tables[0], "elem", 2, 0, 0, 0, 0, 0); } [Fact] public void UnusedComplexTypesIgnored() { string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' id='hoge'> <xs:element name='Root'> <xs:complexType> <xs:sequence> <xs:element name='Child' type='xs:string' /> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name='unusedType'> <xs:sequence> <xs:element name='Orphan' type='xs:string' /> </xs:sequence> </xs:complexType> </xs:schema>"; var ds = new DataSet(); ds.ReadXmlSchema(new StringReader(xs)); // Here "unusedType" table is never imported. AssertDataSet("ds", ds, "hoge", 1, 0); AssertDataTable("dt", ds.Tables[0], "Root", 1, 0, 0, 0, 0, 0); } [Fact] public void SimpleTypeComponentsIgnored() { string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='Root' type='xs:string'/> <xs:attribute name='Attr' type='xs:string'/> </xs:schema>"; var ds = new DataSet(); ds.ReadXmlSchema(new StringReader(xs)); // nothing is imported. AssertDataSet("ds", ds, "NewDataSet", 0, 0); } [Fact] public void IsDataSetAndTypeIgnored() { string xsbase = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'> <xs:element name='Root' type='unusedType' msdata:IsDataSet='{0}'> </xs:element> <xs:complexType name='unusedType'> <xs:sequence> <xs:element name='Child' type='xs:string' /> </xs:sequence> </xs:complexType> </xs:schema>"; // Even if a global element uses a complexType, it will be // ignored if the element has msdata:IsDataSet='true' string xs = string.Format(xsbase, "true"); var ds = new DataSet(); ds.ReadXmlSchema(new StringReader(xs)); AssertDataSet("ds", ds, "Root", 0, 0); // name is "Root" // But when explicit msdata:IsDataSet value is "false", then // treat as usual. xs = string.Format(xsbase, "false"); ds = new DataSet(); ds.ReadXmlSchema(new StringReader(xs)); AssertDataSet("ds", ds, "NewDataSet", 1, 0); } [Fact] public void NestedReferenceNotAllowed() { string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'> <xs:element name='Root' type='unusedType' msdata:IsDataSet='true'> </xs:element> <xs:complexType name='unusedType'> <xs:sequence> <xs:element name='Child' type='xs:string' /> </xs:sequence> </xs:complexType> <xs:element name='Foo'> <xs:complexType> <xs:sequence> <xs:element ref='Root' /> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>"; // DataSet element cannot be converted into a DataTable. // (i.e. cannot be referenced in any other elements) var ds = new DataSet(); Assert.Throws<ArgumentException>(() => { ds.ReadXmlSchema(new StringReader(xs)); }); } [Fact] public void IsDataSetOnLocalElementIgnored() { string xsbase = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'> <xs:element name='Root' type='unusedType'> </xs:element> <xs:complexType name='unusedType'> <xs:sequence> <xs:element name='Child' type='xs:string' msdata:IsDataSet='True' /> </xs:sequence> </xs:complexType> </xs:schema>"; // msdata:IsDataSet does not affect even if the value is invalid string xs = string.Format(xsbase, "true"); var ds = new DataSet(); ds.ReadXmlSchema(new StringReader(xs)); // Child should not be regarded as DataSet element AssertDataSet("ds", ds, "NewDataSet", 1, 0); } [Fact] public void LocaleOnRootWithoutIsDataSet() { string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'> <xs:element name='Root' msdata:Locale='ja-JP'> <xs:complexType> <xs:sequence> <xs:element name='Child' type='xs:string' /> </xs:sequence> <xs:attribute name='Attr' type='xs:integer' /> </xs:complexType> </xs:element> </xs:schema>"; var ds = new DataSet(); ds.ReadXmlSchema(new StringReader(xs)); AssertDataSet("ds", ds, "NewDataSet", 1, 0); Assert.Equal("fi-FI", ds.Locale.Name); // DataSet's Locale comes from current thread DataTable dt = ds.Tables[0]; AssertDataTable("dt", dt, "Root", 2, 0, 0, 0, 0, 0); Assert.Equal("ja-JP", dt.Locale.Name); // DataTable's Locale comes from msdata:Locale AssertDataColumn("col1", dt.Columns[0], "Attr", true, false, 0, 1, "Attr", MappingType.Attribute, typeof(long), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); AssertDataColumn("col2", dt.Columns[1], "Child", false, false, 0, 1, "Child", MappingType.Element, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false); } [Fact] public void ElementHasIdentityConstraint() { string constraints = @" <xs:key name='key'> <xs:selector xpath='./any/string_is_OK/R1'/> <xs:field xpath='Child2'/> </xs:key> <xs:keyref name='kref' refer='key'> <xs:selector xpath='.//R2'/> <xs:field xpath='Child2'/> </xs:keyref>"; string xsbase = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'> <xs:element name='DS' msdata:IsDataSet='true'> <xs:complexType> <xs:choice> <xs:element ref='R1' /> <xs:element ref='R2' /> </xs:choice> </xs:complexType> {0} </xs:element> <xs:element name='R1' type='RootType'> {1} </xs:element> <xs:element name='R2' type='RootType'> </xs:element> <xs:complexType name='RootType'> <xs:choice> <xs:element name='Child1' type='xs:string'> {2} </xs:element> <xs:element name='Child2' type='xs:string' /> </xs:choice> <xs:attribute name='Attr' type='xs:integer' /> </xs:complexType> </xs:schema>"; // Constraints on DataSet element. // Note that in xs:key xpath is crazy except for the last step string xs = string.Format(xsbase, constraints, string.Empty, string.Empty); var ds = new DataSet(); ds.ReadXmlSchema(new StringReader(xs)); Assert.Equal(1, ds.Relations.Count); // Constraints on another global element - just ignored xs = string.Format(xsbase, string.Empty, constraints, string.Empty); ds = new DataSet(); ds.ReadXmlSchema(new StringReader(xs)); Assert.Equal(0, ds.Relations.Count); // Constraints on local element - just ignored xs = string.Format(xsbase, string.Empty, string.Empty, constraints); ds = new DataSet(); ds.ReadXmlSchema(new StringReader(xs)); Assert.Equal(0, ds.Relations.Count); } [Fact] public void PrefixedTargetNS() { string xs = @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata' xmlns:x='urn:foo' targetNamespace='urn:foo' elementFormDefault='qualified'> <xs:element name='DS' msdata:IsDataSet='true'> <xs:complexType> <xs:choice> <xs:element ref='x:R1' /> <xs:element ref='x:R2' /> </xs:choice> </xs:complexType> <xs:key name='key'> <xs:selector xpath='./any/string_is_OK/x:R1'/> <xs:field xpath='x:Child2'/> </xs:key> <xs:keyref name='kref' refer='x:key'> <xs:selector xpath='.//x:R2'/> <xs:field xpath='x:Child2'/> </xs:keyref> </xs:element> <xs:element name='R3' type='x:RootType' /> <xs:complexType name='extracted'> <xs:choice> <xs:element ref='x:R1' /> <xs:element ref='x:R2' /> </xs:choice> </xs:complexType> <xs:element name='R1' type='x:RootType'> <xs:unique name='Rkey'> <xs:selector xpath='.//x:Child1'/> <xs:field xpath='.'/> </xs:unique> <xs:keyref name='Rkref' refer='x:Rkey'> <xs:selector xpath='.//x:Child2'/> <xs:field xpath='.'/> </xs:keyref> </xs:element> <xs:element name='R2' type='x:RootType'> </xs:element> <xs:complexType name='RootType'> <xs:choice> <xs:element name='Child1' type='xs:string'> </xs:element> <xs:element name='Child2' type='xs:string' /> </xs:choice> <xs:attribute name='Attr' type='xs:integer' /> </xs:complexType> </xs:schema>"; // No prefixes on tables and columns var ds = new DataSet(); ds.ReadXmlSchema(new StringReader(xs)); AssertDataSet("ds", ds, "DS", 3, 1); DataTable dt = ds.Tables[0]; AssertDataTable("R3", dt, "R3", 3, 0, 0, 0, 0, 0); AssertDataColumn("col1", dt.Columns[0], "Attr", true, false, 0, 1, "Attr", MappingType.Attribute, typeof(long), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); } [Fact] public void ReadTest1() { DataSet ds = CreateTestSet(); StringWriter sw = new StringWriter(); ds.WriteXmlSchema(sw); string schema = sw.ToString(); // ReadXmlSchema() ds = new DataSet(); ds.ReadXmlSchema(new XmlTextReader(schema, XmlNodeType.Document, null)); ReadTest1Check(ds); // ReadXml() should also be the same ds = new DataSet(); ds.ReadXml(new XmlTextReader(schema, XmlNodeType.Document, null)); ReadTest1Check(ds); } private void ReadTest1Check(DataSet ds) { AssertDataSet("dataset", ds, "NewDataSet", 2, 1); AssertDataTable("tbl1", ds.Tables[0], "Table1", 3, 0, 0, 1, 1, 0); AssertDataTable("tbl2", ds.Tables[1], "Table2", 3, 0, 1, 0, 1, 0); DataRelation rel = ds.Relations[0]; AssertDataRelation("rel", rel, "Rel1", false, new string[] { "Column1_3" }, new string[] { "Column2_1" }, true, true); AssertUniqueConstraint("uc", rel.ParentKeyConstraint, "Constraint1", false, new string[] { "Column1_3" }); AssertForeignKeyConstraint("fk", rel.ChildKeyConstraint, "Rel1", AcceptRejectRule.None, Rule.Cascade, Rule.Cascade, new string[] { "Column2_1" }, new string[] { "Column1_3" }); } [Fact] // 001-004 public void TestSampleFileNoTables() { var ds = new DataSet(); ds.ReadXmlSchema(new StringReader(@"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'><!-- empty --></xs:schema>")); AssertDataSet("001", ds, "NewDataSet", 0, 0); ds = new DataSet(); ds.ReadXmlSchema(new StringReader(@"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'><xs:element name='foo' /></xs:schema>")); AssertDataSet("002", ds, "NewDataSet", 0, 0); ds = new DataSet(); ds.ReadXmlSchema(new StringReader( @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='foo' type='xs:integer' /> <xs:element name='bar' type='xs:string' /> </xs:schema>")); AssertDataSet("003", ds, "NewDataSet", 0, 0); ds = new DataSet(); ds.ReadXmlSchema(new StringReader( @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='foo' type='st' /> <xs:simpleType name='st'> <xs:restriction base='xs:string'> <xs:maxLength value='5' /> </xs:restriction> </xs:simpleType> </xs:schema>")); AssertDataSet("004", ds, "NewDataSet", 0, 0); } [Fact] public void TestSampleFileSimpleTables() { var ds = new DataSet(); ds.ReadXmlSchema(new StringReader( @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='foo' type='ct' /> <xs:complexType name='ct'> <xs:simpleContent> <xs:extension base='xs:integer'> <xs:attribute name='attr' /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:schema>")); AssertDataSet("005", ds, "NewDataSet", 1, 0); DataTable dt = ds.Tables[0]; AssertDataTable("tab", dt, "foo", 2, 0, 0, 0, 0, 0); AssertDataColumn("attr", dt.Columns[0], "attr", true, false, 0, 1, "attr", MappingType.Attribute, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); AssertDataColumn("text", dt.Columns[1], "foo_text", false, false, 0, 1, "foo_text", MappingType.SimpleContent, typeof(long), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false); ds = new DataSet(); ds.ReadXmlSchema(new StringReader( @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='foo' type='st' /> <xs:complexType name='st'> <xs:attribute name='att1' /> <xs:attribute name='att2' type='xs:int' default='2' /> </xs:complexType> </xs:schema>")); AssertDataSet("006", ds, "NewDataSet", 1, 0); dt = ds.Tables[0]; AssertDataTable("tab", dt, "foo", 2, 0, 0, 0, 0, 0); AssertDataColumn("att1", dt.Columns["att1"], "att1", true, false, 0, 1, "att1", MappingType.Attribute, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, /*0*/-1, string.Empty, false, false); AssertDataColumn("att2", dt.Columns["att2"], "att2", true, false, 0, 1, "att2", MappingType.Attribute, typeof(int), 2, string.Empty, -1, string.Empty, /*1*/-1, string.Empty, false, false); } [Fact] public void TestSampleFileComplexTables() { // Nested simple type element var ds = new DataSet(); ds.ReadXmlSchema(new StringReader( @"<!-- nested tables, root references to complex type --> <xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' targetNamespace='urn:foo' xmlns:x='urn:foo'> <xs:element name='uno' type='x:t' /> <xs:complexType name='t'> <xs:sequence> <xs:element name='des'> <xs:complexType> <xs:sequence> <xs:element name='tres' /> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:schema>")); AssertDataSet("007", ds, "NewDataSet", 2, 1); DataTable dt = ds.Tables[0]; AssertDataTable("tab1", dt, "uno", 1, 0, 0, 1, 1, 1); AssertDataColumn("id", dt.Columns[0], "uno_Id", false, true, 0, 1, "uno_Id", MappingType.Hidden, typeof(int), DBNull.Value, string.Empty, -1, "urn:foo", 0, string.Empty, false, true); dt = ds.Tables[1]; AssertDataTable("tab2", dt, "des", 2, 0, 1, 0, 1, 0); AssertDataColumn("child", dt.Columns[0], "tres", false, false, 0, 1, "tres", MappingType.Element, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); AssertDataColumn("id", dt.Columns[1], "uno_Id", true, false, 0, 1, "uno_Id", MappingType.Hidden, typeof(int), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false); // External simple type element ds = new DataSet(); ds.ReadXmlSchema(new StringReader( @"<!-- reference to external simple element --> <xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' targetNamespace='urn:foo' xmlns:x='urn:foo'> <xs:element name='uno' type='x:t' /> <xs:element name='tres' type='xs:string' /> <xs:complexType name='t'> <xs:sequence> <xs:element name='des'> <xs:complexType> <xs:sequence> <xs:element ref='x:tres' /> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:schema>")); AssertDataSet("008", ds, "NewDataSet", 2, 1); dt = ds.Tables[0]; AssertDataTable("tab1", dt, "uno", 1, 0, 0, 1, 1, 1); AssertDataColumn("id", dt.Columns[0], "uno_Id", false, true, 0, 1, "uno_Id", MappingType.Hidden, typeof(int), DBNull.Value, string.Empty, -1, "urn:foo", 0, string.Empty, false, true); dt = ds.Tables[1]; AssertDataTable("tab2", dt, "des", 2, 0, 1, 0, 1, 0); AssertDataColumn("child", dt.Columns[0], "tres", false, false, 0, 1, "tres", MappingType.Element, typeof(string), DBNull.Value, string.Empty, -1, "urn:foo", 0, string.Empty, false, false); AssertDataColumn("id", dt.Columns[1], "uno_Id", true, false, 0, 1, "uno_Id", MappingType.Hidden, typeof(int), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false); } [Fact] public void TestSampleFileComplexTables3() { var ds = new DataSet(); ds.ReadXmlSchema(new StringReader( @"<!-- Modified w3ctests attQ014.xsd --> <xsd:schema xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" targetNamespace=""http://xsdtesting"" xmlns:x=""http://xsdtesting""> <xsd:element name=""root""> <xsd:complexType> <xsd:sequence> <xsd:element name=""e""> <xsd:complexType> <xsd:simpleContent> <xsd:extension base=""xsd:decimal""> <xsd:attribute name=""a"" type=""xsd:string""/> </xsd:extension> </xsd:simpleContent> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:schema>")); AssertDataSet("013", ds, "root", 1, 0); DataTable dt = ds.Tables[0]; AssertDataTable("root", dt, "e", 2, 0, 0, 0, 0, 0); AssertDataColumn("attr", dt.Columns[0], "a", true, false, 0, 1, "a", MappingType.Attribute, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); AssertDataColumn("simple", dt.Columns[1], "e_text", false, false, 0, 1, "e_text", MappingType.SimpleContent, typeof(decimal), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false); } [Fact] public void TestSampleFileXPath() { var ds = new DataSet(); ds.ReadXmlSchema(new StringReader( @"<?xml version=""1.0"" encoding=""utf-8"" ?> <xs:schema targetNamespace=""http://neurosaudio.com/Tracks.xsd"" xmlns=""http://neurosaudio.com/Tracks.xsd"" xmlns:mstns=""http://neurosaudio.com/Tracks.xsd"" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata"" elementFormDefault=""qualified"" id=""Tracks""> <xs:element name=""Tracks""> <xs:complexType> <xs:sequence> <xs:element name=""Track"" minOccurs=""0"" maxOccurs=""unbounded""> <xs:complexType> <xs:sequence> <xs:element name=""Title"" type=""xs:string"" /> <xs:element name=""Artist"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Album"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Performer"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Sequence"" type=""xs:unsignedInt"" minOccurs=""0"" /> <xs:element name=""Genre"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Comment"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Year"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""Duration"" type=""xs:unsignedInt"" minOccurs=""0"" /> <xs:element name=""Path"" type=""xs:string"" /> <xs:element name=""DevicePath"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""FileSize"" type=""xs:unsignedInt"" minOccurs=""0"" /> <xs:element name=""Source"" type=""xs:string"" minOccurs=""0"" /> <xs:element name=""FlashStatus"" type=""xs:unsignedInt"" /> <xs:element name=""HDStatus"" type=""xs:unsignedInt"" /> </xs:sequence> <xs:attribute name=""ID"" type=""xs:unsignedInt"" msdata:AutoIncrement=""true"" msdata:AutoIncrementSeed=""1"" /> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> <xs:key name=""TrackPK"" msdata:PrimaryKey=""true""> <xs:selector xpath="".//mstns:Track"" /> <xs:field xpath=""@ID"" /> </xs:key> </xs:element> </xs:schema>")); } [Fact] public void TestAnnotatedRelation1() { var ds = new DataSet(); ds.ReadXmlSchema(new StringReader( @"<xs:schema xmlns="""" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata""> <xs:element name=""root"" msdata:IsDataSet=""true""> <xs:complexType> <xs:choice maxOccurs=""unbounded""> <xs:element name=""p""> <xs:complexType> <xs:sequence> <xs:element name=""pk"" type=""xs:string"" /> <xs:element name=""name"" type=""xs:string"" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name=""c""> <xs:complexType> <xs:sequence> <xs:element name=""fk"" type=""xs:string"" /> <xs:element name=""count"" type=""xs:int"" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> <xs:annotation> <xs:appinfo> <msdata:Relationship name=""rel"" msdata:parent=""p"" msdata:child=""c"" msdata:parentkey=""pk"" msdata:childkey=""fk""/> </xs:appinfo> </xs:annotation> </xs:schema>")); AssertDataSet("101", ds, "root", 2, 1); DataTable dt = ds.Tables[0]; AssertDataTable("parent_table", dt, "p", 2, 0, 0, 1, 0, 0); AssertDataColumn("pk", dt.Columns[0], "pk", false, false, 0, 1, "pk", MappingType.Element, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); dt = ds.Tables[1]; AssertDataTable("child_table", dt, "c", 2, 0, 1, 0, 0, 0); AssertDataColumn("fk", dt.Columns[0], "fk", false, false, 0, 1, "fk", MappingType.Element, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); AssertDataRelation("rel", ds.Relations[0], "rel", false, new string[] { "pk" }, new string[] { "fk" }, false, false); } [Fact] public void TestAnnotatedRelation2() { var ds = new DataSet(); ds.ReadXmlSchema(new StringReader( @"<xs:schema xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata""> <!-- just modified MSDN example --> <xs:element name=""ds"" msdata:IsDataSet=""true""> <xs:complexType> <xs:choice maxOccurs=""unbounded""> <xs:element name=""p""> <xs:complexType> <xs:sequence> <xs:element name=""pk"" type=""xs:string"" /> <xs:element name=""name"" type=""xs:string"" /> <xs:element name=""c""> <xs:annotation> <xs:appinfo> <msdata:Relationship name=""rel"" msdata:parent=""p"" msdata:child=""c"" msdata:parentkey=""pk"" msdata:childkey=""fk""/> </xs:appinfo> </xs:annotation> <xs:complexType> <xs:sequence> <xs:element name=""fk"" type=""xs:string"" /> <xs:element name=""count"" type=""xs:int"" /> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema>")); AssertDataSet("102", ds, "ds", 2, 1); DataTable dt = ds.Tables[0]; AssertDataTable("parent_table", dt, "p", 2, 0, 0, 1, 0, 0); AssertDataColumn("pk", dt.Columns[0], "pk", false, false, 0, 1, "pk", MappingType.Element, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); dt = ds.Tables[1]; AssertDataTable("child_table", dt, "c", 2, 0, 1, 0, 0, 0); AssertDataColumn("fk", dt.Columns[0], "fk", false, false, 0, 1, "fk", MappingType.Element, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); AssertDataRelation("rel", ds.Relations[0], "rel", true, new string[] { "pk" }, new string[] { "fk" }, false, false); } [Fact] public void RepeatableSimpleElement() { var ds = new DataSet(); ds.ReadXmlSchema(new StringReader( @"<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema'> <!-- empty --> <xs:element name='Foo' type='FooType' /> <!-- defining externally to avoid being regarded as dataset element --> <xs:complexType name='FooType'> <xs:sequence> <xs:element name='Bar' maxOccurs='2' /> </xs:sequence> </xs:complexType> </xs:schema>")); AssertDataSet("012", ds, "NewDataSet", 2, 1); DataTable dt = ds.Tables[0]; AssertDataTable("parent", dt, "Foo", 1, 0, 0, 1, 1, 1); AssertDataColumn("key", dt.Columns[0], "Foo_Id", false, true, 0, 1, "Foo_Id", MappingType.Hidden, typeof(int), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, true); dt = ds.Tables[1]; AssertDataTable("repeated", dt, "Bar", 2, 0, 1, 0, 1, 0); AssertDataColumn("data", dt.Columns[0], "Bar_Column", false, false, 0, 1, "Bar_Column", MappingType.SimpleContent, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); AssertDataColumn("refkey", dt.Columns[1], "Foo_Id", true, false, 0, 1, "Foo_Id", MappingType.Hidden, typeof(int), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false); AssertDataRelation("rel", ds.Relations[0], "Foo_Bar", true, new string[] { "Foo_Id" }, new string[] { "Foo_Id" }, true, true); } [Fact] public void TestMoreThanOneRepeatableColumns() { var ds = new DataSet(); ds.ReadXmlSchema(new StringReader( @"<xsd:schema xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> <xsd:element name=""root""> <xsd:complexType> <xsd:sequence> <xsd:element name=""x"" maxOccurs=""2"" /> <xsd:element ref=""y"" maxOccurs=""unbounded"" /> </xsd:sequence> </xsd:complexType> </xsd:element> <xsd:element name=""y"" /> </xsd:schema>")); AssertDataSet("014", ds, "NewDataSet", 3, 2); DataTable dt = ds.Tables[0]; AssertDataTable("parent", dt, "root", 1, 0, 0, 2, 1, 1); AssertDataColumn("key", dt.Columns[0], "root_Id", false, true, 0, 1, "root_Id", MappingType.Hidden, typeof(int), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, true); dt = ds.Tables[1]; AssertDataTable("repeated", dt, "x", 2, 0, 1, 0, 1, 0); AssertDataColumn("data_1", dt.Columns[0], "x_Column", false, false, 0, 1, "x_Column", MappingType.SimpleContent, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); AssertDataColumn("refkey_1", dt.Columns[1], "root_Id", true, false, 0, 1, "root_Id", MappingType.Hidden, typeof(int), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false); dt = ds.Tables[2]; AssertDataTable("repeated", dt, "y", 2, 0, 1, 0, 1, 0); AssertDataColumn("data", dt.Columns[0], "y_Column", false, false, 0, 1, "y_Column", MappingType.SimpleContent, typeof(string), DBNull.Value, string.Empty, -1, string.Empty, 0, string.Empty, false, false); AssertDataColumn("refkey", dt.Columns[1], "root_Id", true, false, 0, 1, "root_Id", MappingType.Hidden, typeof(int), DBNull.Value, string.Empty, -1, string.Empty, 1, string.Empty, false, false); AssertDataRelation("rel", ds.Relations[0], "root_x", true, new string[] { "root_Id" }, new string[] { "root_Id" }, true, true); AssertDataRelation("rel", ds.Relations[1], "root_y", true, new string[] { "root_Id" }, new string[] { "root_Id" }, true, true); } [Fact] public void AutoIncrementStep() { DataSet ds = new DataSet("testds"); DataTable tbl = ds.Tables.Add("testtbl"); DataColumn col = tbl.Columns.Add("id", typeof(int)); col.AutoIncrement = true; col.AutoIncrementSeed = -1; col.AutoIncrementStep = -1; tbl.Columns.Add("data", typeof(string)); Assert.True(ds.GetXmlSchema().IndexOf("AutoIncrementStep") > 0); } [Fact] public void ReadConstraints() { var ds = new DataSet(); ds.ReadXmlSchema(new StringReader( @"<?xml version=""1.0"" encoding=""utf-8""?> <xs:schema id=""NewDataSet"" xmlns="""" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata""> <xs:element name=""NewDataSet"" msdata:IsDataSet=""true"" msdata:Locale=""en-US""> <xs:complexType> <xs:choice maxOccurs=""unbounded""> <xs:element name=""Table1""> <xs:complexType> <xs:sequence> <xs:element name=""col1"" type=""xs:int"" minOccurs=""0"" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name=""Table2""> <xs:complexType> <xs:sequence> <xs:element name=""col1"" type=""xs:int"" minOccurs=""0"" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> <xs:unique name=""Constraint1""> <xs:selector xpath="".//Table1"" /> <xs:field xpath=""col1"" /> </xs:unique> <xs:keyref name=""fk1"" refer=""Constraint1"" msdata:ConstraintOnly=""true""> <xs:selector xpath="".//Table2"" /> <xs:field xpath=""col1"" /> </xs:keyref> </xs:element> </xs:schema>")); Assert.Equal(0, ds.Relations.Count); Assert.Equal(1, ds.Tables[0].Constraints.Count); Assert.Equal(1, ds.Tables[1].Constraints.Count); Assert.Equal("fk1", ds.Tables[1].Constraints[0].ConstraintName); } [Fact] public void ReadAnnotatedRelations_MultipleColumns() { var ds = new DataSet(); ds.ReadXmlSchema(new StringReader( @"<?xml version=""1.0"" standalone=""yes""?> <xs:schema id=""NewDataSet"" xmlns="""" xmlns:xs=""http://www.w3.org/2001/XMLSchema"" xmlns:msdata=""urn:schemas-microsoft-com:xml-msdata""> <xs:element name=""NewDataSet"" msdata:IsDataSet=""true""> <xs:complexType> <xs:choice maxOccurs=""unbounded""> <xs:element name=""Table1""> <xs:complexType> <xs:sequence> <xs:element name=""col_x0020_1"" type=""xs:int"" minOccurs=""0"" /> <xs:element name=""col2"" type=""xs:int"" minOccurs=""0"" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name=""Table2""> <xs:complexType> <xs:sequence> <xs:element name=""col1"" type=""xs:int"" minOccurs=""0"" /> <xs:element name=""col_x0020__x0020_2"" type=""xs:int"" minOccurs=""0"" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> <xs:annotation> <xs:appinfo> <msdata:Relationship name=""rel"" msdata:parent=""Table1"" msdata:child=""Table2"" msdata:parentkey=""col_x0020_1 col2"" msdata:childkey=""col1 col_x0020__x0020_2"" /> </xs:appinfo> </xs:annotation> </xs:schema>")); Assert.Equal(1, ds.Relations.Count); Assert.Equal("rel", ds.Relations[0].RelationName); Assert.Equal(2, ds.Relations[0].ParentColumns.Length); Assert.Equal(2, ds.Relations[0].ChildColumns.Length); Assert.Equal(0, ds.Tables[0].Constraints.Count); Assert.Equal(0, ds.Tables[1].Constraints.Count); AssertDataRelation("TestRel", ds.Relations[0], "rel", false, new string[] { "col 1", "col2" }, new string[] { "col1", "col 2" }, false, false); } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Text.RegularExpressions; using DotNetOpenMail; using DotNetOpenMail.SmtpAuth; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.Scripting.EmailModules { public class EmailModule : IEmailModule { // // Log // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // // Module vars // private IConfigSource m_Config; private string m_HostName = String.Empty; //private string m_RegionName = String.Empty; private string SMTP_SERVER_HOSTNAME = String.Empty; private int SMTP_SERVER_PORT = 25; private string SMTP_SERVER_LOGIN = String.Empty; private string SMTP_SERVER_PASSWORD = String.Empty; private Dictionary<UUID, DateTime> m_LastGetEmailCall = new Dictionary<UUID, DateTime>(); private TimeSpan m_QueueTimeout = new TimeSpan(2, 0, 0); // 2 hours without llGetNextEmail drops the queue private string m_InterObjectHostname = "lsl.inworldz.local"; // Scenes by Region Handle private Dictionary<ulong, Scene> m_Scenes = new Dictionary<ulong, Scene>(); private bool m_Enabled = false; public void Initialize(Scene scene, IConfigSource config) { m_Config = config; IConfig SMTPConfig; //FIXME: RegionName is correct?? //m_RegionName = scene.RegionInfo.RegionName; IConfig startupConfig = m_Config.Configs["Startup"]; m_Enabled = (startupConfig.GetString("emailmodule", "DefaultEmailModule") == "DefaultEmailModule"); //Load SMTP SERVER config try { if ((SMTPConfig = m_Config.Configs["SMTP"]) == null) { m_log.InfoFormat("[SMTP]: SMTP server not configured"); m_Enabled = false; return; } if (!SMTPConfig.GetBoolean("enabled", false)) { m_log.InfoFormat("[SMTP]: module disabled in configuration"); m_Enabled = false; return; } m_HostName = SMTPConfig.GetString("host_domain_header_from", m_HostName); m_InterObjectHostname = SMTPConfig.GetString("internal_object_host", m_InterObjectHostname); SMTP_SERVER_HOSTNAME = SMTPConfig.GetString("SMTP_SERVER_HOSTNAME", SMTP_SERVER_HOSTNAME); SMTP_SERVER_PORT = SMTPConfig.GetInt("SMTP_SERVER_PORT", SMTP_SERVER_PORT); SMTP_SERVER_LOGIN = SMTPConfig.GetString("SMTP_SERVER_LOGIN", SMTP_SERVER_LOGIN); SMTP_SERVER_PASSWORD = SMTPConfig.GetString("SMTP_SERVER_PASSWORD", SMTP_SERVER_PASSWORD); } catch (Exception e) { m_log.Error("[EMAIL]: DefaultEmailModule not configured: "+ e.Message); m_Enabled = false; return; } // It's a go! if (m_Enabled) { lock (m_Scenes) { // Claim the interface slot scene.RegisterModuleInterface<IEmailModule>(this); // Add to scene list if (m_Scenes.ContainsKey(scene.RegionInfo.RegionHandle)) { m_Scenes[scene.RegionInfo.RegionHandle] = scene; } else { m_Scenes.Add(scene.RegionInfo.RegionHandle, scene); } } m_log.Info("[EMAIL]: Activated DefaultEmailModule"); } } public void PostInitialize() { } public void Close() { } public string Name { get { return "DefaultEmailModule"; } } public bool IsSharedModule { get { return true; } } /// <summary> /// Delay function using thread in seconds /// </summary> /// <param name="seconds"></param> private void DelayInSeconds(int delay) { delay = (int)((float)delay * 1000); if (delay == 0) return; System.Threading.Thread.Sleep(delay); } // This function returns the first region name found in ObjectRegionName even if the object is not found. private SceneObjectPart findPrim(UUID objectID, out string ObjectRegionName) { ObjectRegionName = String.Empty; lock (m_Scenes) { foreach (Scene s in m_Scenes.Values) { SceneObjectPart part = s.GetSceneObjectPart(objectID); if ((part != null) || (ObjectRegionName == String.Empty)) { ObjectRegionName = s.RegionInfo.RegionName; uint localX = (s.RegionInfo.RegionLocX * 256); uint localY = (s.RegionInfo.RegionLocY * 256); ObjectRegionName = ObjectRegionName + " (" + localX + ", " + localY + ")"; if (part != null) return part; } } } return null; } private bool resolveNamePositionRegionName(UUID objectID, out string ObjectName, out string ObjectAbsolutePosition, out string ObjectRegionName) { SceneObjectPart part = findPrim(objectID, out ObjectRegionName); // ObjectRegionName is initialized by findPrim either way. if (part == null) { lock (m_Scenes) { ObjectName = "Object " + objectID.ToString(); ObjectAbsolutePosition = Vector3.Zero.ToString(); } return false; } ObjectAbsolutePosition = String.Format("({0},{1},{2})", (int)part.AbsolutePosition.X, (int)part.AbsolutePosition.Y, (int)part.AbsolutePosition.Z); ObjectName = part.Name; return true; } /// <summary> /// SendMail function utilized by llEMail /// </summary> /// <param name="objectID"></param> /// <param name="address"></param> /// <param name="subject"></param> /// <param name="body"></param> public void SendEmail(UUID objectID, string address, string subject, string body) { //Check if address is empty if (String.IsNullOrWhiteSpace(address)) return; //FIXED:Check the email is correct form in REGEX string EMailpatternStrict = @"^(([^<>()[\]\\.,;:\s@\""]+" + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@" + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+" + @"[a-zA-Z]{2,}))$"; Regex EMailreStrict = new Regex(EMailpatternStrict); bool isEMailStrictMatch = EMailreStrict.IsMatch(address); if (!isEMailStrictMatch) { m_log.Error("[EMAIL]: REGEX Problem in EMail Address: "+address); return; } string LastObjectName = String.Empty; string LastObjectPosition = String.Empty; string LastObjectRegionName = String.Empty; try { //Creation EmailMessage EmailMessage emailMessage = new EmailMessage(); //From emailMessage.FromAddress = new EmailAddress(objectID.ToString() + "@" + m_HostName); //To - Only One emailMessage.AddToAddress(new EmailAddress(address)); //Subject emailMessage.Subject = subject; //TEXT Body if (!resolveNamePositionRegionName(objectID, out LastObjectName, out LastObjectPosition, out LastObjectRegionName)) m_log.WarnFormat("[EMAIL]: Could not find sending object {0} in region.", objectID); emailMessage.BodyText = "Object-Name: " + LastObjectName + "\nRegion: " + LastObjectRegionName + "\nLocal-Position: " + LastObjectPosition + "\n\n" + body; int len = emailMessage.BodyText.Length; if ((address.Length + subject.Length + len) > 4096) { len -= address.Length; len -= subject.Length; emailMessage.BodyText = emailMessage.BodyText.Substring(0, len); } //Config SMTP Server //Set SMTP SERVER config SmtpServer smtpServer=new SmtpServer(SMTP_SERVER_HOSTNAME,SMTP_SERVER_PORT); // Add authentication only when requested // if (!(String.IsNullOrEmpty(SMTP_SERVER_LOGIN) || String.IsNullOrEmpty(SMTP_SERVER_PASSWORD))) { //Authentication smtpServer.SmtpAuthToken=new SmtpAuthToken(SMTP_SERVER_LOGIN, SMTP_SERVER_PASSWORD); } //Send Email Message emailMessage.Send(smtpServer); //Log m_log.Info("[EMAIL]: EMail sent to: " + address + " from object: " + objectID.ToString() + "@" + m_HostName); } catch (Exception e) { m_log.Error("[EMAIL]: DefaultEmailModule Exception: " + e.Message); } } } }
using EIDSS.Reports.Document.ActiveSurveillance.SessionFarmReportDataSetTableAdapters; namespace EIDSS.Reports.Document.ActiveSurveillance { partial class SessionFarmReport { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SessionFarmReport)); this.Detail = new DevExpress.XtraReports.UI.DetailBand(); this.xrTable2 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow(); this.cellNo = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell(); this.TopMargin = new DevExpress.XtraReports.UI.TopMarginBand(); this.BottomMargin = new DevExpress.XtraReports.UI.BottomMarginBand(); this.PageHeader = new DevExpress.XtraReports.UI.PageHeaderBand(); this.MainTable = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell27 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell31 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell(); this.GroupHeader1 = new DevExpress.XtraReports.UI.GroupHeaderBand(); this.xrTable1 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell(); this.cellFarm = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell(); this.m_SessionFarmReportDataSet = new EIDSS.Reports.Document.ActiveSurveillance.SessionFarmReportDataSet(); this.m_SessionFarmAdapter = new EIDSS.Reports.Document.ActiveSurveillance.SessionFarmReportDataSetTableAdapters.SessionFarmAdapter(); this.GroupFooter1 = new DevExpress.XtraReports.UI.GroupFooterBand(); this.ReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand(); this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand(); this.xrTable3 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow6 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell26 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow8 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell29 = new DevExpress.XtraReports.UI.XRTableCell(); ((System.ComponentModel.ISupportInitialize)(this.xrTable2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.MainTable)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.m_SessionFarmReportDataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable3)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); // // Detail // this.Detail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable2}); resources.ApplyResources(this.Detail, "Detail"); this.Detail.Name = "Detail"; this.Detail.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); // // xrTable2 // this.xrTable2.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.xrTable2, "xrTable2"); this.xrTable2.Name = "xrTable2"; this.xrTable2.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow3}); this.xrTable2.StylePriority.UseBorders = false; this.xrTable2.StylePriority.UseTextAlignment = false; // // xrTableRow3 // this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.cellNo, this.xrTableCell15, this.xrTableCell16, this.xrTableCell17, this.xrTableCell18, this.xrTableCell19, this.xrTableCell20, this.xrTableCell21, this.xrTableCell22, this.xrTableCell23}); this.xrTableRow3.Name = "xrTableRow3"; resources.ApplyResources(this.xrTableRow3, "xrTableRow3"); // // cellNo // this.cellNo.Multiline = true; this.cellNo.Name = "cellNo"; resources.ApplyResources(this.cellNo, "cellNo"); this.cellNo.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.cellNo_BeforePrint); // // xrTableCell15 // this.xrTableCell15.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strAnimalID")}); this.xrTableCell15.Multiline = true; this.xrTableCell15.Name = "xrTableCell15"; resources.ApplyResources(this.xrTableCell15, "xrTableCell15"); // // xrTableCell16 // this.xrTableCell16.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strSpecies")}); this.xrTableCell16.Multiline = true; this.xrTableCell16.Name = "xrTableCell16"; resources.ApplyResources(this.xrTableCell16, "xrTableCell16"); // // xrTableCell17 // this.xrTableCell17.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strAge")}); this.xrTableCell17.Multiline = true; this.xrTableCell17.Name = "xrTableCell17"; resources.ApplyResources(this.xrTableCell17, "xrTableCell17"); // // xrTableCell18 // this.xrTableCell18.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strColor")}); this.xrTableCell18.Multiline = true; this.xrTableCell18.Name = "xrTableCell18"; resources.ApplyResources(this.xrTableCell18, "xrTableCell18"); // // xrTableCell19 // this.xrTableCell19.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strName")}); this.xrTableCell19.Multiline = true; this.xrTableCell19.Name = "xrTableCell19"; resources.ApplyResources(this.xrTableCell19, "xrTableCell19"); // // xrTableCell20 // this.xrTableCell20.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strSex")}); this.xrTableCell20.Multiline = true; this.xrTableCell20.Name = "xrTableCell20"; resources.ApplyResources(this.xrTableCell20, "xrTableCell20"); // // xrTableCell21 // this.xrTableCell21.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.datCollectionDate", "{0:MM/d/yyyy}")}); this.xrTableCell21.Multiline = true; this.xrTableCell21.Name = "xrTableCell21"; resources.ApplyResources(this.xrTableCell21, "xrTableCell21"); // // xrTableCell22 // this.xrTableCell22.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strSampleID")}); this.xrTableCell22.Multiline = true; this.xrTableCell22.Name = "xrTableCell22"; resources.ApplyResources(this.xrTableCell22, "xrTableCell22"); // // xrTableCell23 // this.xrTableCell23.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strSampleType")}); this.xrTableCell23.Multiline = true; this.xrTableCell23.Name = "xrTableCell23"; resources.ApplyResources(this.xrTableCell23, "xrTableCell23"); // // TopMargin // resources.ApplyResources(this.TopMargin, "TopMargin"); this.TopMargin.Name = "TopMargin"; this.TopMargin.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); // // BottomMargin // resources.ApplyResources(this.BottomMargin, "BottomMargin"); this.BottomMargin.Name = "BottomMargin"; this.BottomMargin.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); // // PageHeader // resources.ApplyResources(this.PageHeader, "PageHeader"); this.PageHeader.Name = "PageHeader"; // // MainTable // this.MainTable.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.MainTable, "MainTable"); this.MainTable.Name = "MainTable"; this.MainTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow5, this.xrTableRow4, this.xrTableRow1}); this.MainTable.StylePriority.UseBorders = false; this.MainTable.StylePriority.UseTextAlignment = false; // // xrTableRow5 // this.xrTableRow5.Borders = DevExpress.XtraPrinting.BorderSide.None; this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell27}); this.xrTableRow5.Name = "xrTableRow5"; this.xrTableRow5.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableRow5, "xrTableRow5"); // // xrTableCell27 // resources.ApplyResources(this.xrTableCell27, "xrTableCell27"); this.xrTableCell27.Name = "xrTableCell27"; this.xrTableCell27.StylePriority.UseFont = false; this.xrTableCell27.StylePriority.UseTextAlignment = false; // // xrTableRow4 // this.xrTableRow4.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell31}); this.xrTableRow4.Name = "xrTableRow4"; resources.ApplyResources(this.xrTableRow4, "xrTableRow4"); // // xrTableCell31 // this.xrTableCell31.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Top | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell31.Name = "xrTableCell31"; this.xrTableCell31.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell31, "xrTableCell31"); // // xrTableRow1 // this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell7, this.xrTableCell4, this.xrTableCell8, this.xrTableCell1, this.xrTableCell5, this.xrTableCell9, this.xrTableCell10, this.xrTableCell11, this.xrTableCell6, this.xrTableCell3}); this.xrTableRow1.Name = "xrTableRow1"; resources.ApplyResources(this.xrTableRow1, "xrTableRow1"); // // xrTableCell7 // this.xrTableCell7.Multiline = true; this.xrTableCell7.Name = "xrTableCell7"; resources.ApplyResources(this.xrTableCell7, "xrTableCell7"); // // xrTableCell4 // this.xrTableCell4.Multiline = true; this.xrTableCell4.Name = "xrTableCell4"; resources.ApplyResources(this.xrTableCell4, "xrTableCell4"); // // xrTableCell8 // this.xrTableCell8.Multiline = true; this.xrTableCell8.Name = "xrTableCell8"; resources.ApplyResources(this.xrTableCell8, "xrTableCell8"); // // xrTableCell1 // this.xrTableCell1.Multiline = true; this.xrTableCell1.Name = "xrTableCell1"; resources.ApplyResources(this.xrTableCell1, "xrTableCell1"); // // xrTableCell5 // this.xrTableCell5.Multiline = true; this.xrTableCell5.Name = "xrTableCell5"; resources.ApplyResources(this.xrTableCell5, "xrTableCell5"); // // xrTableCell9 // this.xrTableCell9.Multiline = true; this.xrTableCell9.Name = "xrTableCell9"; resources.ApplyResources(this.xrTableCell9, "xrTableCell9"); // // xrTableCell10 // this.xrTableCell10.Multiline = true; this.xrTableCell10.Name = "xrTableCell10"; resources.ApplyResources(this.xrTableCell10, "xrTableCell10"); // // xrTableCell11 // this.xrTableCell11.Name = "xrTableCell11"; resources.ApplyResources(this.xrTableCell11, "xrTableCell11"); // // xrTableCell6 // this.xrTableCell6.Multiline = true; this.xrTableCell6.Name = "xrTableCell6"; resources.ApplyResources(this.xrTableCell6, "xrTableCell6"); // // xrTableCell3 // this.xrTableCell3.Multiline = true; this.xrTableCell3.Name = "xrTableCell3"; resources.ApplyResources(this.xrTableCell3, "xrTableCell3"); // // GroupHeader1 // this.GroupHeader1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable1}); this.GroupHeader1.GroupFields.AddRange(new DevExpress.XtraReports.UI.GroupField[] { new DevExpress.XtraReports.UI.GroupField("idfFarm", DevExpress.XtraReports.UI.XRColumnSortOrder.Ascending)}); resources.ApplyResources(this.GroupHeader1, "GroupHeader1"); this.GroupHeader1.Name = "GroupHeader1"; // // xrTable1 // resources.ApplyResources(this.xrTable1, "xrTable1"); this.xrTable1.Name = "xrTable1"; this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow2}); this.xrTable1.StylePriority.UseTextAlignment = false; // // xrTableRow2 // this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell25, this.cellFarm, this.xrTableCell12, this.xrTableCell13}); this.xrTableRow2.Name = "xrTableRow2"; resources.ApplyResources(this.xrTableRow2, "xrTableRow2"); // // xrTableCell25 // this.xrTableCell25.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell25.Name = "xrTableCell25"; this.xrTableCell25.StylePriority.UseBorders = false; this.xrTableCell25.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell25, "xrTableCell25"); // // cellFarm // this.cellFarm.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.cellFarm.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strFarmCode")}); this.cellFarm.Name = "cellFarm"; this.cellFarm.StylePriority.UseBorders = false; this.cellFarm.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.cellFarm, "cellFarm"); this.cellFarm.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.cellFarm_BeforePrint); // // xrTableCell12 // this.xrTableCell12.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell12.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strOwnerName")}); this.xrTableCell12.Name = "xrTableCell12"; this.xrTableCell12.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell12, "xrTableCell12"); // // xrTableCell13 // this.xrTableCell13.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Right | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell13.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.strFarmAddress")}); this.xrTableCell13.Name = "xrTableCell13"; this.xrTableCell13.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell13, "xrTableCell13"); // // m_SessionFarmReportDataSet // this.m_SessionFarmReportDataSet.DataSetName = "SessionFarmReportDataSet"; this.m_SessionFarmReportDataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // m_SessionFarmAdapter // this.m_SessionFarmAdapter.ClearBeforeFill = true; // // GroupFooter1 // resources.ApplyResources(this.GroupFooter1, "GroupFooter1"); this.GroupFooter1.Name = "GroupFooter1"; // // ReportHeader // this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.MainTable}); resources.ApplyResources(this.ReportHeader, "ReportHeader"); this.ReportHeader.Name = "ReportHeader"; // // ReportFooter // this.ReportFooter.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable3}); resources.ApplyResources(this.ReportFooter, "ReportFooter"); this.ReportFooter.Name = "ReportFooter"; // // xrTable3 // resources.ApplyResources(this.xrTable3, "xrTable3"); this.xrTable3.Name = "xrTable3"; this.xrTable3.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow6, this.xrTableRow8}); this.xrTable3.StylePriority.UseTextAlignment = false; // // xrTableRow6 // this.xrTableRow6.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell24, this.xrTableCell26}); this.xrTableRow6.Name = "xrTableRow6"; resources.ApplyResources(this.xrTableRow6, "xrTableRow6"); // // xrTableCell24 // this.xrTableCell24.Name = "xrTableCell24"; resources.ApplyResources(this.xrTableCell24, "xrTableCell24"); // // xrTableCell26 // this.xrTableCell26.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell26.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.intTotalAnimalSampled")}); this.xrTableCell26.Name = "xrTableCell26"; this.xrTableCell26.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell26, "xrTableCell26"); // // xrTableRow8 // this.xrTableRow8.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell14, this.xrTableCell29}); this.xrTableRow8.Name = "xrTableRow8"; resources.ApplyResources(this.xrTableRow8, "xrTableRow8"); // // xrTableCell14 // this.xrTableCell14.Name = "xrTableCell14"; resources.ApplyResources(this.xrTableCell14, "xrTableCell14"); // // xrTableCell29 // this.xrTableCell29.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell29.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "SessionFarm.intTotalSamples")}); this.xrTableCell29.Name = "xrTableCell29"; this.xrTableCell29.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell29, "xrTableCell29"); // // SessionFarmReport // this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail, this.TopMargin, this.BottomMargin, this.PageHeader, this.GroupHeader1, this.GroupFooter1, this.ReportHeader, this.ReportFooter}); this.DataAdapter = this.m_SessionFarmAdapter; this.DataMember = "SessionFarm"; this.DataSource = this.m_SessionFarmReportDataSet; resources.ApplyResources(this, "$this"); this.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F); this.Version = "14.1"; ((System.ComponentModel.ISupportInitialize)(this.xrTable2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.MainTable)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.m_SessionFarmReportDataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable3)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); } #endregion private DevExpress.XtraReports.UI.DetailBand Detail; private DevExpress.XtraReports.UI.TopMarginBand TopMargin; private DevExpress.XtraReports.UI.BottomMarginBand BottomMargin; private DevExpress.XtraReports.UI.PageHeaderBand PageHeader; private DevExpress.XtraReports.UI.XRTable MainTable; private DevExpress.XtraReports.UI.XRTableRow xrTableRow1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell3; private DevExpress.XtraReports.UI.XRTableCell xrTableCell7; private DevExpress.XtraReports.UI.XRTableCell xrTableCell4; private DevExpress.XtraReports.UI.XRTableCell xrTableCell8; private DevExpress.XtraReports.UI.XRTableCell xrTableCell5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell9; private DevExpress.XtraReports.UI.XRTableCell xrTableCell6; private DevExpress.XtraReports.UI.XRTableCell xrTableCell10; private DevExpress.XtraReports.UI.GroupHeaderBand GroupHeader1; private DevExpress.XtraReports.UI.XRTable xrTable1; private DevExpress.XtraReports.UI.XRTableRow xrTableRow2; private DevExpress.XtraReports.UI.XRTableCell cellFarm; private DevExpress.XtraReports.UI.XRTableCell xrTableCell12; private DevExpress.XtraReports.UI.XRTableCell xrTableCell13; private SessionFarmReportDataSet m_SessionFarmReportDataSet; private SessionFarmAdapter m_SessionFarmAdapter; private DevExpress.XtraReports.UI.XRTable xrTable2; private DevExpress.XtraReports.UI.XRTableRow xrTableRow3; private DevExpress.XtraReports.UI.XRTableCell cellNo; private DevExpress.XtraReports.UI.XRTableCell xrTableCell15; private DevExpress.XtraReports.UI.XRTableCell xrTableCell16; private DevExpress.XtraReports.UI.XRTableCell xrTableCell17; private DevExpress.XtraReports.UI.XRTableCell xrTableCell18; private DevExpress.XtraReports.UI.XRTableCell xrTableCell19; private DevExpress.XtraReports.UI.XRTableCell xrTableCell20; private DevExpress.XtraReports.UI.XRTableCell xrTableCell21; private DevExpress.XtraReports.UI.XRTableCell xrTableCell22; private DevExpress.XtraReports.UI.XRTableCell xrTableCell23; private DevExpress.XtraReports.UI.GroupFooterBand GroupFooter1; private DevExpress.XtraReports.UI.XRTableRow xrTableRow5; private DevExpress.XtraReports.UI.XRTableRow xrTableRow4; private DevExpress.XtraReports.UI.XRTableCell xrTableCell31; private DevExpress.XtraReports.UI.XRTableCell xrTableCell11; private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeader; private DevExpress.XtraReports.UI.ReportFooterBand ReportFooter; private DevExpress.XtraReports.UI.XRTable xrTable3; private DevExpress.XtraReports.UI.XRTableRow xrTableRow6; private DevExpress.XtraReports.UI.XRTableCell xrTableCell24; private DevExpress.XtraReports.UI.XRTableCell xrTableCell26; private DevExpress.XtraReports.UI.XRTableCell xrTableCell25; private DevExpress.XtraReports.UI.XRTableRow xrTableRow8; private DevExpress.XtraReports.UI.XRTableCell xrTableCell14; private DevExpress.XtraReports.UI.XRTableCell xrTableCell29; private DevExpress.XtraReports.UI.XRTableCell xrTableCell27; } }
// 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.IO; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Security; using Xunit; using System.Text; namespace System.IO.FileSystem.DriveInfoTests { public class DriveInfoWindowsTests { [Theory] [InlineData(":\0", "driveName")] [InlineData(":", null)] [InlineData("://", null)] [InlineData(@":\", null)] [InlineData(":/", null)] [InlineData(@":\\", null)] [InlineData("Az", null)] [InlineData("1", null)] [InlineData("a1", null)] [InlineData(@"\\share", null)] [InlineData(@"\\", null)] [InlineData("c ", null)] [InlineData("", "path")] [InlineData(" c", null)] public void Ctor_InvalidPath_ThrowsArgumentException(string driveName, string paramName) { AssertExtensions.Throws<ArgumentException>(paramName, null, () => new DriveInfo(driveName)); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void TestConstructor() { string[] variableInput = { "{0}", "{0}", "{0}:", "{0}:", @"{0}:\", @"{0}:\\", "{0}://" }; // Test Null Assert.Throws<ArgumentNullException>(() => { new DriveInfo(null); }); // Test Valid DriveLetter var validDriveLetter = GetValidDriveLettersOnMachine().First(); foreach (var input in variableInput) { string name = string.Format(input, validDriveLetter); DriveInfo dInfo = new DriveInfo(name); Assert.Equal(string.Format(@"{0}:\", validDriveLetter), dInfo.Name); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void TestGetDrives() { var validExpectedDrives = GetValidDriveLettersOnMachine(); var validActualDrives = DriveInfo.GetDrives(); // Test count Assert.Equal(validExpectedDrives.Count(), validActualDrives.Count()); for (int i = 0; i < validActualDrives.Count(); i++) { // Test if the driveletter is correct Assert.Contains(validActualDrives[i].Name[0], validExpectedDrives); } } [Fact] public void TestDriveProperties_AppContainer() { DriveInfo validDrive = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.Fixed).First(); bool isReady = validDrive.IsReady; Assert.NotNull(validDrive.Name); Assert.NotNull(validDrive.RootDirectory.Name); if (PlatformDetection.IsWinRT) { Assert.Throws<UnauthorizedAccessException>(() => validDrive.AvailableFreeSpace); Assert.Throws<UnauthorizedAccessException>(() => validDrive.DriveFormat); Assert.Throws<UnauthorizedAccessException>(() => validDrive.TotalFreeSpace); Assert.Throws<UnauthorizedAccessException>(() => validDrive.TotalSize); Assert.Throws<UnauthorizedAccessException>(() => validDrive.VolumeLabel); } else { Assert.NotNull(validDrive.DriveFormat); Assert.True(validDrive.AvailableFreeSpace > 0); Assert.True(validDrive.TotalFreeSpace > 0); Assert.True(validDrive.TotalSize > 0); Assert.NotNull(validDrive.VolumeLabel); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "Accessing drive format is not permitted inside an AppContainer.")] public void TestDriveFormat() { DriveInfo validDrive = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.Fixed).First(); const int volNameLen = 50; StringBuilder volumeName = new StringBuilder(volNameLen); const int fileSystemNameLen = 50; StringBuilder fileSystemName = new StringBuilder(fileSystemNameLen); int serialNumber, maxFileNameLen, fileSystemFlags; bool r = GetVolumeInformation(validDrive.Name, volumeName, volNameLen, out serialNumber, out maxFileNameLen, out fileSystemFlags, fileSystemName, fileSystemNameLen); var fileSystem = fileSystemName.ToString(); if (r) { Assert.Equal(fileSystem, validDrive.DriveFormat); } else { Assert.Throws<IOException>(() => validDrive.DriveFormat); } // Test Invalid drive var invalidDrive = new DriveInfo(GetInvalidDriveLettersOnMachine().First().ToString()); Assert.Throws<DriveNotFoundException>(() => invalidDrive.DriveFormat); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void TestDriveType() { var validDrive = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.Fixed).First(); var expectedDriveType = GetDriveType(validDrive.Name); Assert.Equal((DriveType)expectedDriveType, validDrive.DriveType); // Test Invalid drive var invalidDrive = new DriveInfo(GetInvalidDriveLettersOnMachine().First().ToString()); Assert.Equal(invalidDrive.DriveType, DriveType.NoRootDirectory); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "GetDiskFreeSpaceEx blocked in AC")] public void TestValidDiskSpaceProperties() { bool win32Result; long fbUser = -1; long tbUser; long fbTotal; DriveInfo drive; drive = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.Fixed).First(); if (drive.IsReady) { win32Result = GetDiskFreeSpaceEx(drive.Name, out fbUser, out tbUser, out fbTotal); Assert.True(win32Result); if (fbUser != drive.AvailableFreeSpace) Assert.True(drive.AvailableFreeSpace >= 0); // valid property getters shouldn't throw string name = drive.Name; string format = drive.DriveFormat; Assert.Equal(name, drive.ToString()); // totalsize should not change for a fixed drive. Assert.Equal(tbUser, drive.TotalSize); if (fbTotal != drive.TotalFreeSpace) Assert.True(drive.TotalFreeSpace >= 0); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void TestInvalidDiskProperties() { string invalidDriveName = GetInvalidDriveLettersOnMachine().First().ToString(); var invalidDrive = new DriveInfo(invalidDriveName); Assert.Throws<DriveNotFoundException>(() => invalidDrive.AvailableFreeSpace); Assert.Throws<DriveNotFoundException>(() => invalidDrive.DriveFormat); Assert.Equal(DriveType.NoRootDirectory, invalidDrive.DriveType); Assert.False(invalidDrive.IsReady); Assert.Equal(invalidDriveName + ":\\", invalidDrive.Name); Assert.Equal(invalidDriveName + ":\\", invalidDrive.ToString()); Assert.Equal(invalidDriveName + ":\\", invalidDrive.RootDirectory.FullName); Assert.Throws<DriveNotFoundException>(() => invalidDrive.TotalFreeSpace); Assert.Throws<DriveNotFoundException>(() => invalidDrive.TotalSize); Assert.Throws<DriveNotFoundException>(() => invalidDrive.VolumeLabel); Assert.Throws<DriveNotFoundException>(() => invalidDrive.VolumeLabel = null); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void GetVolumeLabel_Returns_CorrectLabel() { void DoDriveCheck() { // Get Volume Label - valid drive int serialNumber, maxFileNameLen, fileSystemFlags; int volNameLen = 50; int fileNameLen = 50; StringBuilder volumeName = new StringBuilder(volNameLen); StringBuilder fileSystemName = new StringBuilder(fileNameLen); DriveInfo validDrive = DriveInfo.GetDrives().First(d => d.DriveType == DriveType.Fixed); bool volumeInformationSuccess = GetVolumeInformation(validDrive.Name, volumeName, volNameLen, out serialNumber, out maxFileNameLen, out fileSystemFlags, fileSystemName, fileNameLen); if (volumeInformationSuccess) { Assert.Equal(volumeName.ToString(), validDrive.VolumeLabel); } else // if we can't compare the volumeName, we should at least check that getting it doesn't throw { var name = validDrive.VolumeLabel; } }; if (PlatformDetection.IsWinRT) { Assert.Throws<UnauthorizedAccessException>(() => DoDriveCheck()); } else { DoDriveCheck(); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void SetVolumeLabel_Roundtrips() { DriveInfo drive = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.Fixed).First(); // Inside an AppContainer access to VolumeLabel is denied. if (PlatformDetection.IsWinRT) { Assert.Throws<UnauthorizedAccessException>(() => drive.VolumeLabel); return; } string currentLabel = drive.VolumeLabel; try { drive.VolumeLabel = currentLabel; // shouldn't change the state of the drive regardless of success } catch (UnauthorizedAccessException) { } Assert.Equal(drive.VolumeLabel, currentLabel); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] public void VolumeLabelOnNetworkOrCdRom_Throws() { // Test setting the volume label on a Network or CD-ROM var noAccessDrive = DriveInfo.GetDrives().Where(d => d.DriveType == DriveType.Network || d.DriveType == DriveType.CDRom); foreach (var adrive in noAccessDrive) { if (adrive.IsReady) { Exception e = Assert.ThrowsAny<Exception>(() => { adrive.VolumeLabel = null; }); Assert.True( e is UnauthorizedAccessException || e is IOException || e is SecurityException); } } } [DllImport("kernel32.dll", SetLastError = true)] internal static extern int GetLogicalDrives(); [DllImport("kernel32.dll", EntryPoint = "GetVolumeInformationW", CharSet = CharSet.Unicode, SetLastError = true, BestFitMapping = false)] internal static extern bool GetVolumeInformation(string drive, StringBuilder volumeName, int volumeNameBufLen, out int volSerialNumber, out int maxFileNameLen, out int fileSystemFlags, StringBuilder fileSystemName, int fileSystemNameBufLen); [DllImport("kernel32.dll", SetLastError = true, EntryPoint = "GetDriveTypeW", CharSet = CharSet.Unicode)] internal static extern int GetDriveType(string drive); [DllImport("kernel32.dll", SetLastError = true)] internal static extern bool GetDiskFreeSpaceEx(string drive, out long freeBytesForUser, out long totalBytes, out long freeBytes); private IEnumerable<char> GetValidDriveLettersOnMachine() { uint mask = (uint)GetLogicalDrives(); Assert.NotEqual<uint>(mask, 0); var bits = new BitArray(new int[] { (int)mask }); for (int i = 0; i < bits.Length; i++) { var letter = (char)('A' + i); if (bits[i]) yield return letter; } } private IEnumerable<char> GetInvalidDriveLettersOnMachine() { uint mask = (uint)GetLogicalDrives(); Assert.NotEqual<uint>(mask, 0); var bits = new BitArray(new int[] { (int)mask }); for (int i = 0; i < bits.Length; i++) { var letter = (char)('A' + i); if (!bits[i]) { if (char.IsLetter(letter)) yield return letter; } } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Binary { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Common; /** * <summary>Collection of predefined handlers for various system types.</summary> */ internal static class BinarySystemHandlers { /** Write handlers. */ private static readonly CopyOnWriteConcurrentDictionary<Type, IBinarySystemWriteHandler> WriteHandlers = new CopyOnWriteConcurrentDictionary<Type, IBinarySystemWriteHandler>(); /** Read handlers. */ private static readonly IBinarySystemReader[] ReadHandlers = new IBinarySystemReader[255]; /** Type ids. */ private static readonly Dictionary<Type, byte> TypeIds = new Dictionary<Type, byte> { {typeof (bool), BinaryUtils.TypeBool}, {typeof (byte), BinaryUtils.TypeByte}, {typeof (sbyte), BinaryUtils.TypeByte}, {typeof (short), BinaryUtils.TypeShort}, {typeof (ushort), BinaryUtils.TypeShort}, {typeof (char), BinaryUtils.TypeChar}, {typeof (int), BinaryUtils.TypeInt}, {typeof (uint), BinaryUtils.TypeInt}, {typeof (long), BinaryUtils.TypeLong}, {typeof (ulong), BinaryUtils.TypeLong}, {typeof (float), BinaryUtils.TypeFloat}, {typeof (double), BinaryUtils.TypeDouble}, {typeof (string), BinaryUtils.TypeString}, {typeof (decimal), BinaryUtils.TypeDecimal}, {typeof (Guid), BinaryUtils.TypeGuid}, {typeof (Guid?), BinaryUtils.TypeGuid}, {typeof (ArrayList), BinaryUtils.TypeCollection}, {typeof (Hashtable), BinaryUtils.TypeDictionary}, {typeof (bool[]), BinaryUtils.TypeArrayBool}, {typeof (byte[]), BinaryUtils.TypeArrayByte}, {typeof (sbyte[]), BinaryUtils.TypeArrayByte}, {typeof (short[]), BinaryUtils.TypeArrayShort}, {typeof (ushort[]), BinaryUtils.TypeArrayShort}, {typeof (char[]), BinaryUtils.TypeArrayChar}, {typeof (int[]), BinaryUtils.TypeArrayInt}, {typeof (uint[]), BinaryUtils.TypeArrayInt}, {typeof (long[]), BinaryUtils.TypeArrayLong}, {typeof (ulong[]), BinaryUtils.TypeArrayLong}, {typeof (float[]), BinaryUtils.TypeArrayFloat}, {typeof (double[]), BinaryUtils.TypeArrayDouble}, {typeof (string[]), BinaryUtils.TypeArrayString}, {typeof (decimal?[]), BinaryUtils.TypeArrayDecimal}, {typeof (Guid?[]), BinaryUtils.TypeArrayGuid}, {typeof (object[]), BinaryUtils.TypeArray} }; /// <summary> /// Initializes the <see cref="BinarySystemHandlers"/> class. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Readability.")] static BinarySystemHandlers() { // 1. Primitives. ReadHandlers[BinaryUtils.TypeBool] = new BinarySystemReader<bool>(s => s.ReadBool()); ReadHandlers[BinaryUtils.TypeByte] = new BinarySystemReader<byte>(s => s.ReadByte()); ReadHandlers[BinaryUtils.TypeShort] = new BinarySystemReader<short>(s => s.ReadShort()); ReadHandlers[BinaryUtils.TypeChar] = new BinarySystemReader<char>(s => s.ReadChar()); ReadHandlers[BinaryUtils.TypeInt] = new BinarySystemReader<int>(s => s.ReadInt()); ReadHandlers[BinaryUtils.TypeLong] = new BinarySystemReader<long>(s => s.ReadLong()); ReadHandlers[BinaryUtils.TypeFloat] = new BinarySystemReader<float>(s => s.ReadFloat()); ReadHandlers[BinaryUtils.TypeDouble] = new BinarySystemReader<double>(s => s.ReadDouble()); ReadHandlers[BinaryUtils.TypeDecimal] = new BinarySystemReader<decimal?>(BinaryUtils.ReadDecimal); // 2. Date. ReadHandlers[BinaryUtils.TypeTimestamp] = new BinarySystemReader<DateTime?>(BinaryUtils.ReadTimestamp); // 3. String. ReadHandlers[BinaryUtils.TypeString] = new BinarySystemReader<string>(BinaryUtils.ReadString); // 4. Guid. ReadHandlers[BinaryUtils.TypeGuid] = new BinarySystemReader<Guid?>(s => BinaryUtils.ReadGuid(s)); // 5. Primitive arrays. ReadHandlers[BinaryUtils.TypeArrayBool] = new BinarySystemReader<bool[]>(BinaryUtils.ReadBooleanArray); ReadHandlers[BinaryUtils.TypeArrayByte] = new BinarySystemDualReader<byte[], sbyte[]>(BinaryUtils.ReadByteArray, BinaryUtils.ReadSbyteArray); ReadHandlers[BinaryUtils.TypeArrayShort] = new BinarySystemDualReader<short[], ushort[]>(BinaryUtils.ReadShortArray, BinaryUtils.ReadUshortArray); ReadHandlers[BinaryUtils.TypeArrayChar] = new BinarySystemReader<char[]>(BinaryUtils.ReadCharArray); ReadHandlers[BinaryUtils.TypeArrayInt] = new BinarySystemDualReader<int[], uint[]>(BinaryUtils.ReadIntArray, BinaryUtils.ReadUintArray); ReadHandlers[BinaryUtils.TypeArrayLong] = new BinarySystemDualReader<long[], ulong[]>(BinaryUtils.ReadLongArray, BinaryUtils.ReadUlongArray); ReadHandlers[BinaryUtils.TypeArrayFloat] = new BinarySystemReader<float[]>(BinaryUtils.ReadFloatArray); ReadHandlers[BinaryUtils.TypeArrayDouble] = new BinarySystemReader<double[]>(BinaryUtils.ReadDoubleArray); ReadHandlers[BinaryUtils.TypeArrayDecimal] = new BinarySystemReader<decimal?[]>(BinaryUtils.ReadDecimalArray); // 6. Date array. ReadHandlers[BinaryUtils.TypeArrayTimestamp] = new BinarySystemReader<DateTime?[]>(BinaryUtils.ReadTimestampArray); // 7. String array. ReadHandlers[BinaryUtils.TypeArrayString] = new BinarySystemTypedArrayReader<string>(); // 8. Guid array. ReadHandlers[BinaryUtils.TypeArrayGuid] = new BinarySystemTypedArrayReader<Guid?>(); // 9. Array. ReadHandlers[BinaryUtils.TypeArray] = new BinarySystemReader(ReadArray); // 11. Arbitrary collection. ReadHandlers[BinaryUtils.TypeCollection] = new BinarySystemReader(ReadCollection); // 13. Arbitrary dictionary. ReadHandlers[BinaryUtils.TypeDictionary] = new BinarySystemReader(ReadDictionary); // 14. Enum. ReadHandlers[BinaryUtils.TypeArrayEnum] = new BinarySystemReader(ReadEnumArray); } /// <summary> /// Try getting write handler for type. /// </summary> /// <param name="type"></param> /// <returns></returns> public static IBinarySystemWriteHandler GetWriteHandler(Type type) { return WriteHandlers.GetOrAdd(type, t => { return FindWriteHandler(t); }); } /// <summary> /// Find write handler for type. /// </summary> /// <param name="type">Type.</param> /// <returns> /// Write handler or NULL. /// </returns> private static IBinarySystemWriteHandler FindWriteHandler(Type type) { // 1. Well-known types. if (type == typeof(string)) return new BinarySystemWriteHandler<string>(WriteString, false); if (type == typeof(decimal)) return new BinarySystemWriteHandler<decimal>(WriteDecimal, false); if (type == typeof(Guid)) return new BinarySystemWriteHandler<Guid>(WriteGuid, false); if (type == typeof (BinaryObject)) return new BinarySystemWriteHandler<BinaryObject>(WriteBinary, false); if (type == typeof (BinaryEnum)) return new BinarySystemWriteHandler<BinaryEnum>(WriteBinaryEnum, false); if (type.IsEnum) { var underlyingType = Enum.GetUnderlyingType(type); if (underlyingType == typeof(int)) return new BinarySystemWriteHandler<int>((w, i) => w.WriteEnum(i, type), false); if (underlyingType == typeof(uint)) return new BinarySystemWriteHandler<uint>((w, i) => w.WriteEnum(unchecked((int) i), type), false); if (underlyingType == typeof(byte)) return new BinarySystemWriteHandler<byte>((w, i) => w.WriteEnum(i, type), false); if (underlyingType == typeof(sbyte)) return new BinarySystemWriteHandler<sbyte>((w, i) => w.WriteEnum(i, type), false); if (underlyingType == typeof(short)) return new BinarySystemWriteHandler<short>((w, i) => w.WriteEnum(i, type), false); if (underlyingType == typeof(ushort)) return new BinarySystemWriteHandler<ushort>((w, i) => w.WriteEnum(i, type), false); return null; // Other enums, such as long and ulong, can't be expressed as int. } if (type == typeof(Ignite)) return new BinarySystemWriteHandler<object>(WriteIgnite, false); // All types below can be written as handles. if (type == typeof (ArrayList)) return new BinarySystemWriteHandler<ICollection>(WriteArrayList, true); if (type == typeof (Hashtable)) return new BinarySystemWriteHandler<IDictionary>(WriteHashtable, true); if (type.IsArray) { // We know how to write any array type. Type elemType = type.GetElementType(); // Primitives. if (elemType == typeof (bool)) return new BinarySystemWriteHandler<bool[]>(WriteBoolArray, true); if (elemType == typeof(byte)) return new BinarySystemWriteHandler<byte[]>(WriteByteArray, true); if (elemType == typeof(short)) return new BinarySystemWriteHandler<short[]>(WriteShortArray, true); if (elemType == typeof(char)) return new BinarySystemWriteHandler<char[]>(WriteCharArray, true); if (elemType == typeof(int)) return new BinarySystemWriteHandler<int[]>(WriteIntArray, true); if (elemType == typeof(long)) return new BinarySystemWriteHandler<long[]>(WriteLongArray, true); if (elemType == typeof(float)) return new BinarySystemWriteHandler<float[]>(WriteFloatArray, true); if (elemType == typeof(double)) return new BinarySystemWriteHandler<double[]>(WriteDoubleArray, true); // Non-CLS primitives. if (elemType == typeof(sbyte)) return new BinarySystemWriteHandler<byte[]>(WriteByteArray, true); if (elemType == typeof(ushort)) return new BinarySystemWriteHandler<short[]>(WriteShortArray, true); if (elemType == typeof(uint)) return new BinarySystemWriteHandler<int[]>(WriteIntArray, true); if (elemType == typeof(ulong)) return new BinarySystemWriteHandler<long[]>(WriteLongArray, true); // Special types. if (elemType == typeof (decimal?)) return new BinarySystemWriteHandler<decimal?[]>(WriteDecimalArray, true); if (elemType == typeof(string)) return new BinarySystemWriteHandler<string[]>(WriteStringArray, true); if (elemType == typeof(Guid?)) return new BinarySystemWriteHandler<Guid?[]>(WriteGuidArray, true); // Enums. if (BinaryUtils.IsIgniteEnum(elemType) || elemType == typeof(BinaryEnum)) return new BinarySystemWriteHandler<object>(WriteEnumArray, true); // Object array. return new BinarySystemWriteHandler<object>(WriteArray, true); } return null; } /// <summary> /// Find write handler for type. /// </summary> /// <param name="type">Type.</param> /// <returns>Write handler or NULL.</returns> public static byte GetTypeId(Type type) { byte res; if (TypeIds.TryGetValue(type, out res)) return res; if (BinaryUtils.IsIgniteEnum(type)) return BinaryUtils.TypeEnum; if (type.IsArray && BinaryUtils.IsIgniteEnum(type.GetElementType())) return BinaryUtils.TypeArrayEnum; return BinaryUtils.TypeObject; } /// <summary> /// Reads an object of predefined type. /// </summary> public static bool TryReadSystemType<T>(byte typeId, BinaryReader ctx, out T res) { var handler = ReadHandlers[typeId]; if (handler == null) { res = default(T); return false; } res = handler.Read<T>(ctx); return true; } /// <summary> /// Write decimal. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteDecimal(BinaryWriter ctx, decimal obj) { ctx.Stream.WriteByte(BinaryUtils.TypeDecimal); BinaryUtils.WriteDecimal(obj, ctx.Stream); } /// <summary> /// Write string. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Object.</param> private static void WriteString(BinaryWriter ctx, string obj) { ctx.Stream.WriteByte(BinaryUtils.TypeString); BinaryUtils.WriteString(obj, ctx.Stream); } /// <summary> /// Write Guid. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteGuid(BinaryWriter ctx, Guid obj) { ctx.Stream.WriteByte(BinaryUtils.TypeGuid); BinaryUtils.WriteGuid(obj, ctx.Stream); } /// <summary> /// Write boolaen array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteBoolArray(BinaryWriter ctx, bool[] obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayBool); BinaryUtils.WriteBooleanArray(obj, ctx.Stream); } /// <summary> /// Write byte array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteByteArray(BinaryWriter ctx, byte[] obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayByte); BinaryUtils.WriteByteArray(obj, ctx.Stream); } /// <summary> /// Write short array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteShortArray(BinaryWriter ctx, short[] obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayShort); BinaryUtils.WriteShortArray(obj, ctx.Stream); } /// <summary> /// Write char array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteCharArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayChar); BinaryUtils.WriteCharArray((char[])obj, ctx.Stream); } /// <summary> /// Write int array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteIntArray(BinaryWriter ctx, int[] obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayInt); BinaryUtils.WriteIntArray(obj, ctx.Stream); } /// <summary> /// Write long array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteLongArray(BinaryWriter ctx, long[] obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayLong); BinaryUtils.WriteLongArray(obj, ctx.Stream); } /// <summary> /// Write float array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteFloatArray(BinaryWriter ctx, float[] obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayFloat); BinaryUtils.WriteFloatArray(obj, ctx.Stream); } /// <summary> /// Write double array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteDoubleArray(BinaryWriter ctx, double[] obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayDouble); BinaryUtils.WriteDoubleArray(obj, ctx.Stream); } /// <summary> /// Write decimal array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteDecimalArray(BinaryWriter ctx, decimal?[] obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayDecimal); BinaryUtils.WriteDecimalArray(obj, ctx.Stream); } /// <summary> /// Write string array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteStringArray(BinaryWriter ctx, string[] obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayString); BinaryUtils.WriteStringArray(obj, ctx.Stream); } /// <summary> /// Write nullable GUID array. /// </summary> /// <param name="ctx">Context.</param> /// <param name="obj">Value.</param> private static void WriteGuidArray(BinaryWriter ctx, Guid?[] obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayGuid); BinaryUtils.WriteGuidArray(obj, ctx.Stream); } /// <summary> /// Writes the enum array. /// </summary> private static void WriteEnumArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArrayEnum); BinaryUtils.WriteArray((Array) obj, ctx); } /// <summary> /// Writes the array. /// </summary> private static void WriteArray(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.TypeArray); BinaryUtils.WriteArray((Array) obj, ctx); } /** * <summary>Write ArrayList.</summary> */ private static void WriteArrayList(BinaryWriter ctx, ICollection obj) { ctx.Stream.WriteByte(BinaryUtils.TypeCollection); BinaryUtils.WriteCollection(obj, ctx, BinaryUtils.CollectionArrayList); } /** * <summary>Write Hashtable.</summary> */ private static void WriteHashtable(BinaryWriter ctx, IDictionary obj) { ctx.Stream.WriteByte(BinaryUtils.TypeDictionary); BinaryUtils.WriteDictionary(obj, ctx, BinaryUtils.MapHashMap); } /** * <summary>Write binary object.</summary> */ private static void WriteBinary(BinaryWriter ctx, BinaryObject obj) { ctx.Stream.WriteByte(BinaryUtils.TypeBinary); BinaryUtils.WriteBinary(ctx.Stream, obj); } /// <summary> /// Write enum. /// </summary> private static void WriteBinaryEnum(BinaryWriter ctx, BinaryEnum obj) { var binEnum = obj; ctx.Stream.WriteByte(BinaryUtils.TypeBinaryEnum); ctx.WriteInt(binEnum.TypeId); ctx.WriteInt(binEnum.EnumValue); } /** * <summary>Read enum array.</summary> */ private static object ReadEnumArray(BinaryReader ctx, Type type) { var elemType = type.GetElementType() ?? typeof(object); return BinaryUtils.ReadTypedArray(ctx, true, elemType); } /// <summary> /// Reads the array. /// </summary> private static object ReadArray(BinaryReader ctx, Type type) { var elemType = type.GetElementType(); if (elemType == null) { if (ctx.Mode == BinaryMode.ForceBinary) { // Forced binary mode: use object because primitives are not represented as IBinaryObject. elemType = typeof(object); } else { // Infer element type from typeId. var typeId = ctx.ReadInt(); if (typeId != BinaryUtils.ObjTypeId) { elemType = ctx.Marshaller.GetDescriptor(true, typeId, true).Type; } return BinaryUtils.ReadTypedArray(ctx, false, elemType ?? typeof(object)); } } // Element type is known, no need to check typeId. // In case of incompatible types we'll get exception either way. return BinaryUtils.ReadTypedArray(ctx, true, elemType); } /** * <summary>Read collection.</summary> */ private static object ReadCollection(BinaryReader ctx, Type type) { return BinaryUtils.ReadCollection(ctx, null, null); } /** * <summary>Read dictionary.</summary> */ private static object ReadDictionary(BinaryReader ctx, Type type) { return BinaryUtils.ReadDictionary(ctx, null); } /// <summary> /// Write Ignite. /// </summary> private static void WriteIgnite(BinaryWriter ctx, object obj) { ctx.Stream.WriteByte(BinaryUtils.HdrNull); } /** * <summary>Read delegate.</summary> * <param name="ctx">Read context.</param> * <param name="type">Type.</param> */ private delegate object BinarySystemReadDelegate(BinaryReader ctx, Type type); /// <summary> /// System type reader. /// </summary> private interface IBinarySystemReader { /// <summary> /// Reads a value of specified type from reader. /// </summary> T Read<T>(BinaryReader ctx); } /// <summary> /// System type generic reader. /// </summary> private interface IBinarySystemReader<out T> { /// <summary> /// Reads a value of specified type from reader. /// </summary> T Read(BinaryReader ctx); } /// <summary> /// Default reader with boxing. /// </summary> private class BinarySystemReader : IBinarySystemReader { /** */ private readonly BinarySystemReadDelegate _readDelegate; /// <summary> /// Initializes a new instance of the <see cref="BinarySystemReader"/> class. /// </summary> /// <param name="readDelegate">The read delegate.</param> public BinarySystemReader(BinarySystemReadDelegate readDelegate) { Debug.Assert(readDelegate != null); _readDelegate = readDelegate; } /** <inheritdoc /> */ public T Read<T>(BinaryReader ctx) { return (T)_readDelegate(ctx, typeof(T)); } } /// <summary> /// Reader without boxing. /// </summary> private class BinarySystemReader<T> : IBinarySystemReader { /** */ private readonly Func<IBinaryStream, T> _readDelegate; /// <summary> /// Initializes a new instance of the <see cref="BinarySystemReader{T}"/> class. /// </summary> /// <param name="readDelegate">The read delegate.</param> public BinarySystemReader(Func<IBinaryStream, T> readDelegate) { Debug.Assert(readDelegate != null); _readDelegate = readDelegate; } /** <inheritdoc /> */ public TResult Read<TResult>(BinaryReader ctx) { return TypeCaster<TResult>.Cast(_readDelegate(ctx.Stream)); } } /// <summary> /// Reader without boxing. /// </summary> private class BinarySystemTypedArrayReader<T> : IBinarySystemReader { public TResult Read<TResult>(BinaryReader ctx) { return TypeCaster<TResult>.Cast(BinaryUtils.ReadArray<T>(ctx, false)); } } /// <summary> /// Reader with selection based on requested type. /// </summary> private class BinarySystemDualReader<T1, T2> : IBinarySystemReader, IBinarySystemReader<T2> { /** */ private readonly Func<IBinaryStream, T1> _readDelegate1; /** */ private readonly Func<IBinaryStream, T2> _readDelegate2; /// <summary> /// Initializes a new instance of the <see cref="BinarySystemDualReader{T1,T2}"/> class. /// </summary> /// <param name="readDelegate1">The read delegate1.</param> /// <param name="readDelegate2">The read delegate2.</param> public BinarySystemDualReader(Func<IBinaryStream, T1> readDelegate1, Func<IBinaryStream, T2> readDelegate2) { Debug.Assert(readDelegate1 != null); Debug.Assert(readDelegate2 != null); _readDelegate1 = readDelegate1; _readDelegate2 = readDelegate2; } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods")] T2 IBinarySystemReader<T2>.Read(BinaryReader ctx) { return _readDelegate2(ctx.Stream); } /** <inheritdoc /> */ public T Read<T>(BinaryReader ctx) { // Can't use "as" because of variance. // For example, IBinarySystemReader<byte[]> can be cast to IBinarySystemReader<sbyte[]>, which // will cause incorrect behavior. if (typeof (T) == typeof (T2)) return ((IBinarySystemReader<T>) this).Read(ctx); return TypeCaster<T>.Cast(_readDelegate1(ctx.Stream)); } } } /// <summary> /// Write delegate + handles flag. /// </summary> internal interface IBinarySystemWriteHandler { /// <summary> /// Gets a value indicating whether this handler supports handles. /// </summary> bool SupportsHandles { get; } /// <summary> /// Writes object to a specified writer. /// </summary> /// <param name="writer">The writer.</param> /// <param name="obj">The object.</param> void Write<T>(BinaryWriter writer, T obj); } /// <summary> /// Write delegate + handles flag. /// </summary> internal class BinarySystemWriteHandler<T1> : IBinarySystemWriteHandler { /** */ private readonly Action<BinaryWriter, T1> _writeAction; /** */ private readonly bool _supportsHandles; /// <summary> /// Initializes a new instance of the <see cref="BinarySystemWriteHandler{T1}" /> class. /// </summary> /// <param name="writeAction">The write action.</param> /// <param name="supportsHandles">Handles flag.</param> public BinarySystemWriteHandler(Action<BinaryWriter, T1> writeAction, bool supportsHandles) { Debug.Assert(writeAction != null); _writeAction = writeAction; _supportsHandles = supportsHandles; } /** <inheritdoc /> */ public void Write<T>(BinaryWriter writer, T obj) { _writeAction(writer, TypeCaster<T1>.Cast(obj)); } /** <inheritdoc /> */ public bool SupportsHandles { get { return _supportsHandles; } } } }
//----------------------------------------------------------------------------- // Logicking's Game Factory // Copyright (C) Logicking.com, Inc. //----------------------------------------------------------------------------- // Test rigid bodies //--------------------------------------------------------------- function coll() { new TSStatic(coll) { canSaveDynamicFields = "1"; Enabled = "1"; position = "560.095 659.057 258.09"; rotation = "1 0 0 0"; scale = "1 1 1"; //shapeName = "art/shapes/test/LMA_LampBase.dae"; shapeName = "art/shapes/test/LMA_LampBase2.dae"; receiveSunLight = "1"; receiveLMLighting = "1"; useCustomAmbientLighting = "0"; customAmbientLighting = "0 0 0 1"; usePolysoup = "0"; allowPlayerStep = "1"; renderNormals = "0"; }; } //////////////test functions///////////////// function crai() { new RigidBody(rsh) { canSaveDynamicFields = "1"; Enabled = "1"; //position = "355 570 145"; position = $playerForAi.getPosition(); //position = "560.095 661.057 261.09"; //position = "519.416 673.461 258.4"; rotation = "1 0 0 0"; scale = "0.5 0.5 0.5"; //scale = "0.3 0.3 0.3"; dataBlock = "PhysBox"; collision = "0"; }; } function crpx() { new PxMultiActor(rsh) { canSaveDynamicFields = "1"; Enabled = "1"; position = "560.095 661.057 261.09"; rotation = "1 0 0 0"; scale = "1 1 1"; dataBlock = "pxBlackBarrel"; collision = "0"; }; } function fl() { new SoftBody(fl) { canSaveDynamicFields = "1"; Enabled = "1"; //position = "370 572 145"; position = "560 661 261"; rotation = "1 0 0 0"; scale = "1 1 1"; dataBlock = "PhysFlag"; collision = "0"; }; } function crs2() { new SoftBody(rsh2) { canSaveDynamicFields = "1"; Enabled = "1"; //position = "370 572 145"; position = "560.095 661.057 261.09"; rotation = "1 0 0 0"; scale = "0.3 0.3 0.3"; dataBlock = "PhysSoftSphere"; collision = "0"; }; } function cr() { new RigidBody(rsh) { canSaveDynamicFields = "1"; Enabled = "1"; position = "560.095 661.057 261.09"; //position = "560.095 661.057 261.09"; //position = "519.416 673.461 258.4"; rotation = "1 0 0 0"; scale = "0.5 0.5 0.5"; //scale = "0.3 0.3 0.3"; dataBlock = "PhysBox"; collision = "0"; }; } function crup() { rsh2.setPosition(VectorAdd("0 0 2",rsh2.getPosition())); } function cr2() { new RigidBody(rsh2) { canSaveDynamicFields = "1"; Enabled = "1"; //position = "355 570 145"; //position = "370 572 145"; //position = "220 506 178"; position = "560.095 661.057 261.09"; //position = "519.416 673.461 258.4"; rotation = "1 0 0 0"; scale = "0.3 0.3 0.3"; dataBlock = "PhysSphere"; collision = "0"; }; } function cr3() { new RigidBody(rsh3) { canSaveDynamicFields = "1"; Enabled = "1"; position = "355 570 142"; rotation = "1 0 0 0"; scale = "1 1 1"; dataBlock = "PhysBarrel"; collision = "0"; }; } function cr4() { new RigidBody(rsh4) { canSaveDynamicFields = "1"; Enabled = "1"; position = "355 570 142"; rotation = "1 0 0 0"; scale = "1 1 1"; dataBlock = "PhysWheel"; collision = "0"; }; } function ra() { new RagDoll(rc) { canSaveDynamicFields = "1"; Enabled = "1"; position = "560.095 661.057 257"; //position = "355 570 140.763"; rotation = "1 0 0 0"; scale = "1 1 1"; dataBlock = "SpaceOrcRagDoll"; collision = "0"; }; } function orc() { new AIBot(orc) { canSaveDynamicFields = "1"; Enabled = "1"; //position = "355 570 140.763"; position = "560.095 661.057 261.09"; rotation = "1 0 0 0"; scale = "1 1 1"; dataBlock = "SpaceOrcBotData"; collision = "0"; }; } //$nullRagDoll = 1; function ra2() { new RagDoll(rc2) { canSaveDynamicFields = "1"; Enabled = "1"; //position = "355 570 140.763"; position = "560.095 661.057 257.09"; rotation = "1 0 0 0"; scale = "1 1 1"; dataBlock = "ElfRagDoll"; collision = "0"; }; } function elf() { new AIBot(elf) { canSaveDynamicFields = "1"; Enabled = "1"; //position = "355 570 140.763"; position = "560.095 661.057 257.09"; rotation = "1 0 0 0"; scale = "1 1 1"; dataBlock = "ElfBotData"; collision = "0"; }; } function ra3() { new RagDoll(rc3) { canSaveDynamicFields = "1"; Enabled = "1"; position = "357 570 140.763"; rotation = "1 0 0 0"; scale = "1 1 1"; dataBlock = "CasualFemaleRagDoll"; collision = "0"; }; } function casual() { new AIBot(casual) { canSaveDynamicFields = "1"; Enabled = "1"; position = "357 570 140.763"; rotation = "1 0 0 0"; scale = "1 1 1"; dataBlock = "CasualFemaleBotData"; collision = "0"; }; }
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace ForieroEditor.Platforms.iOS.Xcode { internal class DeviceTypeRequirement { public static readonly string Key = "idiom"; public static readonly string Any = "universal"; public static readonly string iPhone = "iphone"; public static readonly string iPad = "ipad"; public static readonly string Mac = "mac"; public static readonly string iWatch = "watch"; } internal class MemoryRequirement { public static readonly string Key = "memory"; public static readonly string Any = ""; public static readonly string Mem1GB = "1GB"; public static readonly string Mem2GB = "2GB"; } internal class GraphicsRequirement { public static readonly string Key = "graphics-feature-set"; public static readonly string Any = ""; public static readonly string Metal1v2 = "metal1v2"; public static readonly string Metal2v2 = "metal2v2"; } // only used for image sets internal class SizeClassRequirement { public static readonly string HeightKey = "height-class"; public static readonly string WidthKey = "width-class"; public static readonly string Any = ""; public static readonly string Compact = "compact"; public static readonly string Regular = "regular"; } // only used for image sets internal class ScaleRequirement { public static readonly string Key = "scale"; public static readonly string Any = ""; // vector image public static readonly string X1 = "1x"; public static readonly string X2 = "2x"; public static readonly string X3 = "3x"; } internal class DeviceRequirement { internal Dictionary<string, string> values = new Dictionary<string, string>(); public DeviceRequirement AddDevice(string device) { AddCustom(DeviceTypeRequirement.Key, device); return this; } public DeviceRequirement AddMemory(string memory) { AddCustom(MemoryRequirement.Key, memory); return this; } public DeviceRequirement AddGraphics(string graphics) { AddCustom(GraphicsRequirement.Key, graphics); return this; } public DeviceRequirement AddWidthClass(string sizeClass) { AddCustom(SizeClassRequirement.WidthKey, sizeClass); return this; } public DeviceRequirement AddHeightClass(string sizeClass) { AddCustom(SizeClassRequirement.HeightKey, sizeClass); return this; } public DeviceRequirement AddScale(string scale) { AddCustom(ScaleRequirement.Key, scale); return this; } public DeviceRequirement AddCustom(string key, string value) { if (values.ContainsKey(key)) values.Remove(key); values.Add(key, value); return this; } public DeviceRequirement() { values.Add("idiom", DeviceTypeRequirement.Any); } } internal class AssetCatalog { AssetFolder m_Root; public string path { get { return m_Root.path; } } public AssetFolder root { get { return m_Root; } } public AssetCatalog(string path, string authorId) { if (Path.GetExtension(path) != ".xcassets") throw new Exception("Asset catalogs must have xcassets extension"); m_Root = new AssetFolder(path, null, authorId); } AssetFolder OpenFolderForResource(string relativePath) { var pathItems = PBX.Utils.SplitPath(relativePath).ToList(); // remove path filename pathItems.RemoveAt(pathItems.Count - 1); AssetFolder folder = root; foreach (var pathItem in pathItems) folder = folder.OpenFolder(pathItem); return folder; } // Checks if a dataset at the given path exists and returns it if it does. // Otherwise, creates a new dataset. Parent folders are created if needed. // Note: the path is filesystem path, not logical asset name formed // only from names of the folders that have "provides namespace" attribute. // If you want to put certain resources in folders with namespace, first // manually create the folders and then set the providesNamespace attribute. // OpenNamespacedFolder may help to do this. public AssetDataSet OpenDataSet(string relativePath) { var folder = OpenFolderForResource(relativePath); return folder.OpenDataSet(Path.GetFileName(relativePath)); } public AssetImageSet OpenImageSet(string relativePath) { var folder = OpenFolderForResource(relativePath); return folder.OpenImageSet(Path.GetFileName(relativePath)); } public AssetImageStack OpenImageStack(string relativePath) { var folder = OpenFolderForResource(relativePath); return folder.OpenImageStack(Path.GetFileName(relativePath)); } // Checks if a folder with given path exists and returns it if it does. // Otherwise, creates a new folder. Parent folders are created if needed. public AssetFolder OpenFolder(string relativePath) { if (relativePath == null) return root; var pathItems = PBX.Utils.SplitPath(relativePath); if (pathItems.Length == 0) return root; AssetFolder folder = root; foreach (var pathItem in pathItems) folder = folder.OpenFolder(pathItem); return folder; } // Creates a directory structure with "provides namespace" attribute. // First, retrieves or creates the directory at relativeBasePath, creating parent // directories if needed. Effectively calls OpenFolder(relativeBasePath). // Then, relative to this directory, creates namespacePath directories with "provides // namespace" attribute set. Fails if the attribute can't be set. public AssetFolder OpenNamespacedFolder(string relativeBasePath, string namespacePath) { var folder = OpenFolder(relativeBasePath); var pathItems = PBX.Utils.SplitPath(namespacePath); foreach (var pathItem in pathItems) { folder = folder.OpenFolder(pathItem); folder.providesNamespace = true; } return folder; } public void Write() { m_Root.Write(); } } internal abstract class AssetCatalogItem { public readonly string name; public readonly string authorId; public string path { get { return m_Path; } } protected Dictionary<string, string> m_Properties = new Dictionary<string, string>(); protected string m_Path; public AssetCatalogItem(string name, string authorId) { if (name != null && name.Contains("/")) throw new Exception("Asset catalog item must not have slashes in name"); this.name = name; this.authorId = authorId; } protected JsonElementDict WriteInfoToJson(JsonDocument doc) { var info = doc.root.CreateDict("info"); info.SetInteger("version", 1); info.SetString("author", authorId); return info; } public abstract void Write(); } internal class AssetFolder : AssetCatalogItem { List<AssetCatalogItem> m_Items = new List<AssetCatalogItem>(); bool m_ProvidesNamespace = false; public bool providesNamespace { get { return m_ProvidesNamespace; } set { if (m_Items.Count > 0 && value != m_ProvidesNamespace) throw new Exception("Asset folder namespace providing status can't be "+ "changed after items have been added"); m_ProvidesNamespace = value; } } internal AssetFolder(string parentPath, string name, string authorId) : base(name, authorId) { if (name != null) m_Path = Path.Combine(parentPath, name); else m_Path = parentPath; } // Checks if a folder with given name exists and returns it if it does. // Otherwise, creates a new folder. public AssetFolder OpenFolder(string name) { var item = GetChild(name); if (item != null) { if (item is AssetFolder) return item as AssetFolder; throw new Exception("The given path is already occupied with an asset"); } var folder = new AssetFolder(m_Path, name, authorId); m_Items.Add(folder); return folder; } T GetExistingItemWithType<T>(string name) where T : class { var item = GetChild(name); if (item != null) { if (item is T) return item as T; throw new Exception("The given path is already occupied with an asset"); } return null; } // Checks if a dataset with given name exists and returns it if it does. // Otherwise, creates a new data set. public AssetDataSet OpenDataSet(string name) { var item = GetExistingItemWithType<AssetDataSet>(name); if (item != null) return item; var dataset = new AssetDataSet(m_Path, name, authorId); m_Items.Add(dataset); return dataset; } // Checks if an imageset with given name exists and returns it if it does. // Otherwise, creates a new image set. public AssetImageSet OpenImageSet(string name) { var item = GetExistingItemWithType<AssetImageSet>(name); if (item != null) return item; var imageset = new AssetImageSet(m_Path, name, authorId); m_Items.Add(imageset); return imageset; } // Checks if a image stack with given name exists and returns it if it does. // Otherwise, creates a new image stack. public AssetImageStack OpenImageStack(string name) { var item = GetExistingItemWithType<AssetImageStack>(name); if (item != null) return item; var imageStack = new AssetImageStack(m_Path, name, authorId); m_Items.Add(imageStack); return imageStack; } // Returns the requested item or null if not found public AssetCatalogItem GetChild(string name) { foreach (var item in m_Items) { if (item.name == name) return item; } return null; } void WriteJson() { if (!providesNamespace) return; // json is optional when namespace is not provided var doc = new JsonDocument(); WriteInfoToJson(doc); var props = doc.root.CreateDict("properties"); props.SetBoolean("provides-namespace", providesNamespace); doc.WriteToFile(Path.Combine(m_Path, "Contents.json")); } public override void Write() { if (Directory.Exists(m_Path)) Directory.Delete(m_Path, true); // ensure we start from clean state Directory.CreateDirectory(m_Path); WriteJson(); foreach (var item in m_Items) item.Write(); } } abstract class AssetCatalogItemWithVariants : AssetCatalogItem { protected List<VariantData> m_Variants = new List<VariantData>(); protected List<string> m_ODRTags = new List<string>(); protected AssetCatalogItemWithVariants(string name, string authorId) : base(name, authorId) { } protected class VariantData { public DeviceRequirement requirement; public string path; public VariantData(DeviceRequirement requirement, string path) { this.requirement = requirement; this.path = path; } } public bool HasVariant(DeviceRequirement requirement) { foreach (var item in m_Variants) { if (item.requirement.values == requirement.values) return true; } return false; } public void AddOnDemandResourceTag(string tag) { if (!m_ODRTags.Contains(tag)) m_ODRTags.Add(tag); } protected void AddVariant(VariantData newItem) { foreach (var item in m_Variants) { if (item.requirement.values == newItem.requirement.values) throw new Exception("The given requirement has been already added"); if (Path.GetFileName(item.path) == Path.GetFileName(path)) throw new Exception("Two items within the same set must not have the same file name"); } if (Path.GetFileName(newItem.path) == "Contents.json") throw new Exception("The file name must not be equal to Contents.json"); m_Variants.Add(newItem); } protected void WriteODRTagsToJson(JsonElementDict info) { if (m_ODRTags.Count > 0) { var tags = info.CreateArray("on-demand-resource-tags"); foreach (var tag in m_ODRTags) tags.AddString(tag); } } protected void WriteRequirementsToJson(JsonElementDict item, DeviceRequirement req) { foreach (var kv in req.values) { if (kv.Value != null && kv.Value != "") item.SetString(kv.Key, kv.Value); } } } internal class AssetDataSet : AssetCatalogItemWithVariants { class DataSetVariant : VariantData { public string id; public DataSetVariant(DeviceRequirement requirement, string path, string id) : base(requirement, path) { this.id = id; } } internal AssetDataSet(string parentPath, string name, string authorId) : base(name, authorId) { m_Path = Path.Combine(parentPath, name + ".dataset"); } // an exception is thrown is two equivalent requirements are added. // The same asset dataset must not have paths with equivalent filenames. // The identifier allows to identify which data variant is actually loaded (use // the typeIdentifer property of the NSDataAsset that was created from the data set) public void AddVariant(DeviceRequirement requirement, string path, string typeIdentifier) { foreach (DataSetVariant item in m_Variants) { if (item.id != null && typeIdentifier != null && item.id == typeIdentifier) throw new Exception("Two items within the same dataset must not have the same id"); } AddVariant(new DataSetVariant(requirement, path, typeIdentifier)); } public override void Write() { Directory.CreateDirectory(m_Path); var doc = new JsonDocument(); var info = WriteInfoToJson(doc); WriteODRTagsToJson(info); var data = doc.root.CreateArray("data"); foreach (DataSetVariant item in m_Variants) { var filename = Path.GetFileName(item.path); File.Copy(item.path, Path.Combine(m_Path, filename)); var docItem = data.AddDict(); docItem.SetString("filename", filename); WriteRequirementsToJson(docItem, item.requirement); if (item.id != null) docItem.SetString("universal-type-identifier", item.id); } doc.WriteToFile(Path.Combine(m_Path, "Contents.json")); } } internal class ImageAlignment { public int left = 0, right = 0, top = 0, bottom = 0; } internal class ImageResizing { public enum SlicingType { Horizontal, Vertical, HorizontalAndVertical } public enum ResizeMode { Stretch, Tile } public SlicingType type = SlicingType.HorizontalAndVertical; public int left = 0; // only valid for horizontal slicing public int right = 0; // only valid for horizontal slicing public int top = 0; // only valid for vertical slicing public int bottom = 0; // only valid for vertical slicing public ResizeMode centerResizeMode = ResizeMode.Stretch; public int centerWidth = 0; // only valid for vertical slicing public int centerHeight = 0; // only valid for horizontal slicing } // TODO: rendering intent property internal class AssetImageSet : AssetCatalogItemWithVariants { internal AssetImageSet(string assetCatalogPath, string name, string authorId) : base(name, authorId) { m_Path = Path.Combine(assetCatalogPath, name + ".imageset"); } class ImageSetVariant : VariantData { public ImageAlignment alignment = null; public ImageResizing resizing = null; public ImageSetVariant(DeviceRequirement requirement, string path) : base(requirement, path) { } } public void AddVariant(DeviceRequirement requirement, string path) { AddVariant(new ImageSetVariant(requirement, path)); } public void AddVariant(DeviceRequirement requirement, string path, ImageAlignment alignment, ImageResizing resizing) { var imageset = new ImageSetVariant(requirement, path); imageset.alignment = alignment; imageset.resizing = resizing; AddVariant(imageset); } void WriteAlignmentToJson(JsonElementDict item, ImageAlignment alignment) { var docAlignment = item.CreateDict("alignment-insets"); docAlignment.SetInteger("top", alignment.top); docAlignment.SetInteger("bottom", alignment.bottom); docAlignment.SetInteger("left", alignment.left); docAlignment.SetInteger("right", alignment.right); } static string GetSlicingMode(ImageResizing.SlicingType mode) { switch (mode) { case ImageResizing.SlicingType.Horizontal: return "3-part-horizontal"; case ImageResizing.SlicingType.Vertical: return "3-part-vertical"; case ImageResizing.SlicingType.HorizontalAndVertical: return "9-part"; } return ""; } static string GetCenterResizeMode(ImageResizing.ResizeMode mode) { switch (mode) { case ImageResizing.ResizeMode.Stretch: return "stretch"; case ImageResizing.ResizeMode.Tile: return "tile"; } return ""; } void WriteResizingToJson(JsonElementDict item, ImageResizing resizing) { var docResizing = item.CreateDict("resizing"); docResizing.SetString("mode", GetSlicingMode(resizing.type)); var docCenter = docResizing.CreateDict("center"); docCenter.SetString("mode", GetCenterResizeMode(resizing.centerResizeMode)); docCenter.SetInteger("width", resizing.centerWidth); docCenter.SetInteger("height", resizing.centerHeight); var docInsets = docResizing.CreateDict("cap-insets"); docInsets.SetInteger("top", resizing.top); docInsets.SetInteger("bottom", resizing.bottom); docInsets.SetInteger("left", resizing.left); docInsets.SetInteger("right", resizing.right); } public override void Write() { Directory.CreateDirectory(m_Path); var doc = new JsonDocument(); var info = WriteInfoToJson(doc); WriteODRTagsToJson(info); var images = doc.root.CreateArray("images"); foreach (ImageSetVariant item in m_Variants) { var filename = Path.GetFileName(item.path); File.Copy(item.path, Path.Combine(m_Path, filename)); var docItem = images.AddDict(); docItem.SetString("filename", filename); WriteRequirementsToJson(docItem, item.requirement); if (item.alignment != null) WriteAlignmentToJson(docItem, item.alignment); if (item.resizing != null) WriteResizingToJson(docItem, item.resizing); } doc.WriteToFile(Path.Combine(m_Path, "Contents.json")); } } /* A stack layer may either contain an image set or reference another imageset */ class AssetImageStackLayer : AssetCatalogItem { internal AssetImageStackLayer(string assetCatalogPath, string name, string authorId) : base(name, authorId) { m_Path = Path.Combine(assetCatalogPath, name + ".imagestacklayer"); m_Imageset = new AssetImageSet(m_Path, "Content", authorId); } AssetImageSet m_Imageset = null; string m_ReferencedName = null; public void SetReference(string name) { m_Imageset = null; m_ReferencedName = name; } public string ReferencedName() { return m_ReferencedName; } public AssetImageSet GetImageSet() { return m_Imageset; } public override void Write() { Directory.CreateDirectory(m_Path); var doc = new JsonDocument(); WriteInfoToJson(doc); if (m_ReferencedName != null) { var props = doc.root.CreateDict("properties"); var reference = props.CreateDict("content-reference"); reference.SetString("type", "image-set"); reference.SetString("name", m_ReferencedName); reference.SetString("matching-style", "fully-qualified-name"); } if (m_Imageset != null) m_Imageset.Write(); doc.WriteToFile(Path.Combine(m_Path, "Contents.json")); } } class AssetImageStack : AssetCatalogItem { List<AssetImageStackLayer> m_Layers = new List<AssetImageStackLayer>(); internal AssetImageStack(string assetCatalogPath, string name, string authorId) : base(name, authorId) { m_Path = Path.Combine(assetCatalogPath, name + ".imagestack"); } public AssetImageStackLayer AddLayer(string name) { foreach (var layer in m_Layers) { if (layer.name == name) throw new Exception("A layer with given name already exists"); } var newLayer = new AssetImageStackLayer(m_Path, name, authorId); m_Layers.Add(newLayer); return newLayer; } public override void Write() { Directory.CreateDirectory(m_Path); var doc = new JsonDocument(); WriteInfoToJson(doc); var docLayers = doc.root.CreateArray("layers"); foreach (var layer in m_Layers) { layer.Write(); var docLayer = docLayers.AddDict(); docLayer.SetString("filename", Path.GetFileName(layer.path)); } doc.WriteToFile(Path.Combine(m_Path, "Contents.json")); } } } // namespace ForieroEditor.Platforms.iOS.Xcode
using Newtonsoft.Json; using NuGet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading; using System.Xml.Linq; namespace NuSave.Core { public class Downloader { const string DefaultSource = "https://packages.nuget.org/api/v2"; readonly string _source; readonly string _outputDirectory; readonly string _id; readonly string _version; readonly bool _allowPreRelease; readonly bool _allowUnlisted; readonly bool _silent; readonly bool _json; private readonly bool _useDefaultProxyConfig; List<IPackage> _toDownload = new List<IPackage>(); public Downloader( string source, string outputDirectory, string id, string version, bool allowPreRelease = false, bool allowUnlisted = false, bool silent = false, bool json = false, bool useDefaultProxyConfig = false) { _source = source; _outputDirectory = outputDirectory; _id = id; _version = version; _allowPreRelease = allowPreRelease; _allowUnlisted = allowUnlisted; _json = json; _useDefaultProxyConfig = useDefaultProxyConfig; _silent = _json ? true : silent; } public void Download() { if (!_silent) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine($"Downloading"); Console.ResetColor(); } var webClient = new WebClient(); foreach (var package in _toDownload) { if (PackageExists(package.Id, package.Version.ToString())) continue; if (!_silent) { Console.WriteLine($"{package.Id} {package.Version}"); } var dataServicePackage = (DataServicePackage) package; // We keep retrying forever until the user will press Ctrl-C // This lets the user decide when to stop retrying. // The reason for this is that building the dependencies list is expensive // on slow internet connection, when the CLI crashes because of a WebException // the user has to wait for the dependencies list to build rebuild again. while (true) { try { string nugetPackageOutputPath = GetNuGetPackagePath(package.Id, package.Version.ToString()); var downloadUrl = dataServicePackage.DownloadUrl; if (_useDefaultProxyConfig) { var proxy = webClient.Proxy; if (proxy != null) { var proxyUri = proxy.GetProxy(downloadUrl).ToString(); webClient.UseDefaultCredentials = true; webClient.Proxy = new WebProxy(proxyUri, false) {Credentials = CredentialCache.DefaultCredentials}; } } webClient.DownloadFile(downloadUrl, nugetPackageOutputPath); break; } catch (WebException e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"{e.Message}. Retrying in one second..."); Console.ResetColor(); Thread.Sleep(1000); } } } } public void ResolveDependencies(string csprojPath = null) { if (_toDownload != null && _toDownload.Count > 1) { _toDownload = new List<IPackage>(); } if (!_silent) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine($"Resolving dependencies"); Console.ResetColor(); } if (csprojPath == null) { IPackage package = string.IsNullOrWhiteSpace(_version) ? Repository.FindPackage(_id) : Repository.FindPackage(_id, SemanticVersion.Parse(_version), _allowPreRelease, _allowUnlisted); if (package == null) throw new Exception("Could not resolve package"); ResolveDependencies(package); } else { XNamespace @namespace = "http://schemas.microsoft.com/developer/msbuild/2003"; XDocument csprojDoc = XDocument.Load(csprojPath); IEnumerable<MsBuildPackageRef> references = csprojDoc .Element(@namespace + "Project") .Elements(@namespace + "ItemGroup") .Elements(@namespace + "PackageReference") .Select(e => new MsBuildPackageRef() { Include = e.Attribute("Include").Value, Version = e.Element(@namespace + "Version").Value }); ResolveDependencies(references); IEnumerable<MsBuildPackageRef> dotnetCliToolReferences = csprojDoc .Element(@namespace + "Project") .Elements(@namespace + "ItemGroup") .Elements(@namespace + "DotNetCliToolReference") .Select(e => new MsBuildPackageRef() { Include = e.Attribute("Include").Value, Version = e.Element(@namespace + "Version").Value }); ResolveDependencies(dotnetCliToolReferences); } if (_json) { Console.WriteLine(JsonConvert.SerializeObject(GetDependencies())); } } void ResolveDependencies(IEnumerable<MsBuildPackageRef> references) { foreach (var packageRef in references) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"{packageRef.Include} {packageRef.Version}"); Console.ResetColor(); ResolveDependencies(packageRef); } } string GetNuGetPackagePath(string id, string version) { return Path.Combine(_outputDirectory, $"{id}.{version}.nupkg".ToLower()); } string GetNuGetHierarchialDirPath(string id, string version) { return Path.Combine(_outputDirectory, id.ToLower(), version); } bool PackageExists(string id, string version) { string nugetPackagePath = GetNuGetPackagePath(id, version); if (File.Exists(nugetPackagePath)) return true; string nuGetHierarchialDirPath = GetNuGetHierarchialDirPath(id, version); if (Directory.Exists(nuGetHierarchialDirPath)) return true; return false; } void ResolveDependencies(MsBuildPackageRef msBuildpackageRef) { IPackage nugetPackage = Repository.FindPackage(msBuildpackageRef.Include, SemanticVersion.Parse(msBuildpackageRef.Version), true, true); ResolveDependencies(nugetPackage); } void ResolveDependencies(IPackage package) { if (PackageExists(package.Id, package.Version.ToString())) return; _toDownload.Add(package); foreach (var set in package.DependencySets) { foreach (var dependency in set.Dependencies) { if (PackageExists(dependency.Id, dependency.VersionSpec.ToString())) continue; var found = Repository.FindPackage( dependency.Id, dependency.VersionSpec, _allowPreRelease, _allowUnlisted); if (found == null) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine($"Could not resolve dependency: {dependency.Id} {dependency.VersionSpec.ToString()}"); Console.ResetColor(); } else { if (!_toDownload.Any(p => p.Title == found.Title && p.Version == found.Version)) { _toDownload.Add(found); if (!_silent) { Console.WriteLine($"{found.Id} {found.Version}"); } ResolveDependencies(found); } } } } } string GetSource() { if (_source == null) { return DefaultSource; } else { return _source; } } /// <summary> /// Convenience method that can be used in powershell in combination with Out-GridView /// </summary> /// <returns></returns> public List<SimplifiedPackageInfo> GetDependencies() { var list = new List<SimplifiedPackageInfo>(); foreach (var p in _toDownload) { list.Add(new SimplifiedPackageInfo { Id = p.Id, Version = p.Version.ToString(), Authors = string.Join(" ", p.Authors) }); } return list; } IPackageRepository _repository; IPackageRepository Repository { get { if (_repository == null) { _repository = PackageRepositoryFactory.Default.CreateRepository(GetSource()); } return _repository; } } } }
// 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.Xml.Linq; namespace System.Xml.XPath { internal class XNodeNavigator : XPathNavigator, IXmlLineInfo { internal static readonly string xmlPrefixNamespace = XNamespace.Xml.NamespaceName; internal static readonly string xmlnsPrefixNamespace = XNamespace.Xmlns.NamespaceName; const int DocumentContentMask = (1 << (int)XmlNodeType.Element) | (1 << (int)XmlNodeType.ProcessingInstruction) | (1 << (int)XmlNodeType.Comment); static readonly int[] ElementContentMasks = { 0, // Root (1 << (int)XmlNodeType.Element), // Element 0, // Attribute 0, // Namespace (1 << (int)XmlNodeType.CDATA) | (1 << (int)XmlNodeType.Text), // Text 0, // SignificantWhitespace 0, // Whitespace (1 << (int)XmlNodeType.ProcessingInstruction), // ProcessingInstruction (1 << (int)XmlNodeType.Comment), // Comment (1 << (int)XmlNodeType.Element) | (1 << (int)XmlNodeType.CDATA) | (1 << (int)XmlNodeType.Text) | (1 << (int)XmlNodeType.ProcessingInstruction) | (1 << (int)XmlNodeType.Comment) // All }; const int TextMask = (1 << (int)XmlNodeType.CDATA) | (1 << (int)XmlNodeType.Text); static XAttribute XmlNamespaceDeclaration; // The navigator position is encoded by the tuple (source, parent). // Namespace declaration uses (instance, parent element). // Common XObjects uses (instance, null). XObject source; XElement parent; XmlNameTable nameTable; public XNodeNavigator(XNode node, XmlNameTable nameTable) { this.source = node; this.nameTable = nameTable != null ? nameTable : CreateNameTable(); } public XNodeNavigator(XNodeNavigator other) { source = other.source; parent = other.parent; nameTable = other.nameTable; } public override string BaseURI { get { if (source != null) { return source.BaseUri; } if (parent != null) { return parent.BaseUri; } return string.Empty; } } public override bool HasAttributes { get { XElement element = source as XElement; if (element != null) { foreach (XAttribute attribute in element.Attributes()) { if (!attribute.IsNamespaceDeclaration) { return true; } } } return false; } } public override bool HasChildren { get { XContainer container = source as XContainer; if (container != null) { foreach (XNode node in container.Nodes()) { if (IsContent(container, node)) { return true; } } } return false; } } public override bool IsEmptyElement { get { XElement e = source as XElement; return e != null && e.IsEmpty; } } public override string LocalName { get { return nameTable.Add(GetLocalName()); } } string GetLocalName() { XElement e = source as XElement; if (e != null) { return e.Name.LocalName; } XAttribute a = source as XAttribute; if (a != null) { if (parent != null && a.Name.NamespaceName.Length == 0) { return string.Empty; // backcompat } return a.Name.LocalName; } XProcessingInstruction p = source as XProcessingInstruction; if (p != null) { return p.Target; } return string.Empty; } public override string Name { get { string prefix = GetPrefix(); if (prefix.Length == 0) { return nameTable.Add(GetLocalName()); } return nameTable.Add(string.Concat(prefix, ":", GetLocalName())); } } public override string NamespaceURI { get { return nameTable.Add(GetNamespaceURI()); } } string GetNamespaceURI() { XElement e = source as XElement; if (e != null) { return e.Name.NamespaceName; } XAttribute a = source as XAttribute; if (a != null) { if (parent != null) { return string.Empty; // backcompat } return a.Name.NamespaceName; } return string.Empty; } public override XmlNameTable NameTable { get { return nameTable; } } public override XPathNodeType NodeType { get { if (source != null) { switch (source.NodeType) { case XmlNodeType.Element: return XPathNodeType.Element; case XmlNodeType.Attribute: XAttribute attribute = (XAttribute)source; return attribute.IsNamespaceDeclaration ? XPathNodeType.Namespace : XPathNodeType.Attribute; case XmlNodeType.Document: return XPathNodeType.Root; case XmlNodeType.Comment: return XPathNodeType.Comment; case XmlNodeType.ProcessingInstruction: return XPathNodeType.ProcessingInstruction; default: return XPathNodeType.Text; } } return XPathNodeType.Text; } } public override string Prefix { get { return nameTable.Add(GetPrefix()); } } string GetPrefix() { XElement e = source as XElement; if (e != null) { string prefix = e.GetPrefixOfNamespace(e.Name.Namespace); if (prefix != null) { return prefix; } return string.Empty; } XAttribute a = source as XAttribute; if (a != null) { if (parent != null) { return string.Empty; // backcompat } string prefix = a.GetPrefixOfNamespace(a.Name.Namespace); if (prefix != null) { return prefix; } } return string.Empty; } public override object UnderlyingObject { get { return source; } } public override string Value { get { if (source != null) { switch (source.NodeType) { case XmlNodeType.Element: return ((XElement)source).Value; case XmlNodeType.Attribute: return ((XAttribute)source).Value; case XmlNodeType.Document: XElement root = ((XDocument)source).Root; return root != null ? root.Value : string.Empty; case XmlNodeType.Text: case XmlNodeType.CDATA: return CollectText((XText)source); case XmlNodeType.Comment: return ((XComment)source).Value; case XmlNodeType.ProcessingInstruction: return ((XProcessingInstruction)source).Data; default: return string.Empty; } } return string.Empty; } } public override XPathNavigator Clone() { return new XNodeNavigator(this); } public override bool IsSamePosition(XPathNavigator navigator) { XNodeNavigator other = navigator as XNodeNavigator; if (other == null) { return false; } return IsSamePosition(this, other); } public override bool MoveTo(XPathNavigator navigator) { XNodeNavigator other = navigator as XNodeNavigator; if (other != null) { source = other.source; parent = other.parent; return true; } return false; } public override bool MoveToAttribute(string localName, string namespaceName) { XElement e = source as XElement; if (e != null) { foreach (XAttribute attribute in e.Attributes()) { if (attribute.Name.LocalName == localName && attribute.Name.NamespaceName == namespaceName && !attribute.IsNamespaceDeclaration) { source = attribute; return true; } } } return false; } public override bool MoveToChild(string localName, string namespaceName) { XContainer c = source as XContainer; if (c != null) { foreach (XElement element in c.Elements()) { if (element.Name.LocalName == localName && element.Name.NamespaceName == namespaceName) { source = element; return true; } } } return false; } public override bool MoveToChild(XPathNodeType type) { XContainer c = source as XContainer; if (c != null) { int mask = GetElementContentMask(type); if ((TextMask & mask) != 0 && c.GetParent() == null && c is XDocument) { mask &= ~TextMask; } foreach (XNode node in c.Nodes()) { if (((1 << (int)node.NodeType) & mask) != 0) { source = node; return true; } } } return false; } public override bool MoveToFirstAttribute() { XElement e = source as XElement; if (e != null) { foreach (XAttribute attribute in e.Attributes()) { if (!attribute.IsNamespaceDeclaration) { source = attribute; return true; } } } return false; } public override bool MoveToFirstChild() { XContainer container = source as XContainer; if (container != null) { foreach (XNode node in container.Nodes()) { if (IsContent(container, node)) { source = node; return true; } } } return false; } public override bool MoveToFirstNamespace(XPathNamespaceScope scope) { XElement e = source as XElement; if (e != null) { XAttribute a = null; switch (scope) { case XPathNamespaceScope.Local: a = GetFirstNamespaceDeclarationLocal(e); break; case XPathNamespaceScope.ExcludeXml: a = GetFirstNamespaceDeclarationGlobal(e); while (a != null && a.Name.LocalName == "xml") { a = GetNextNamespaceDeclarationGlobal(a); } break; case XPathNamespaceScope.All: a = GetFirstNamespaceDeclarationGlobal(e); if (a == null) { a = GetXmlNamespaceDeclaration(); } break; } if (a != null) { source = a; parent = e; return true; } } return false; } public override bool MoveToId(string id) { throw new NotSupportedException(SR.NotSupported_MoveToId); } public override bool MoveToNamespace(string localName) { XElement e = source as XElement; if (e != null) { if (localName == "xmlns") { return false; // backcompat } if (localName != null && localName.Length == 0) { localName = "xmlns"; // backcompat } XAttribute a = GetFirstNamespaceDeclarationGlobal(e); while (a != null) { if (a.Name.LocalName == localName) { source = a; parent = e; return true; } a = GetNextNamespaceDeclarationGlobal(a); } if (localName == "xml") { source = GetXmlNamespaceDeclaration(); parent = e; return true; } } return false; } public override bool MoveToNext() { XNode currentNode = source as XNode; if (currentNode != null) { XContainer container = currentNode.GetParent(); if (container != null) { XNode next = null; for (XNode node = currentNode; node != null; node = next) { next = node.NextNode; if (next == null) { break; } if (IsContent(container, next) && !(node is XText && next is XText)) { source = next; return true; } } } } return false; } public override bool MoveToNext(string localName, string namespaceName) { XNode currentNode = source as XNode; if (currentNode != null) { foreach (XElement element in currentNode.ElementsAfterSelf()) { if (element.Name.LocalName == localName && element.Name.NamespaceName == namespaceName) { source = element; return true; } } } return false; } public override bool MoveToNext(XPathNodeType type) { XNode currentNode = source as XNode; if (currentNode != null) { XContainer container = currentNode.GetParent(); if (container != null) { int mask = GetElementContentMask(type); if ((TextMask & mask) != 0 && container.GetParent() == null && container is XDocument) { mask &= ~TextMask; } XNode next = null; for (XNode node = currentNode; node != null; node = next) { next = node.NextNode; if (((1 << (int)next.NodeType) & mask) != 0 && !(node is XText && next is XText)) { source = next; return true; } } } } return false; } public override bool MoveToNextAttribute() { XAttribute currentAttribute = source as XAttribute; if (currentAttribute != null && parent == null) { XElement e = (XElement)currentAttribute.GetParent(); if (e != null) { for (XAttribute attribute = currentAttribute.NextAttribute; attribute != null; attribute = attribute.NextAttribute) { if (!attribute.IsNamespaceDeclaration) { source = attribute; return true; } } } } return false; } public override bool MoveToNextNamespace(XPathNamespaceScope scope) { XAttribute a = source as XAttribute; if (a != null && parent != null && !IsXmlNamespaceDeclaration(a)) { switch (scope) { case XPathNamespaceScope.Local: if (a.GetParent() != parent) { return false; } a = GetNextNamespaceDeclarationLocal(a); break; case XPathNamespaceScope.ExcludeXml: do { a = GetNextNamespaceDeclarationGlobal(a); } while (a != null && (a.Name.LocalName == "xml" || HasNamespaceDeclarationInScope(a, parent))); break; case XPathNamespaceScope.All: do { a = GetNextNamespaceDeclarationGlobal(a); } while (a != null && HasNamespaceDeclarationInScope(a, parent)); if (a == null && !HasNamespaceDeclarationInScope(GetXmlNamespaceDeclaration(), parent)) { a = GetXmlNamespaceDeclaration(); } break; } if (a != null) { source = a; return true; } } return false; } public override bool MoveToParent() { if (parent != null) { source = parent; parent = null; return true; } XNode parentNode = source.GetParent(); if (parentNode != null) { source = parentNode; return true; } return false; } public override bool MoveToPrevious() { XNode currentNode = source as XNode; if (currentNode != null) { XContainer container = currentNode.GetParent(); if (container != null) { XNode previous = null; foreach (XNode node in container.Nodes()) { if (node == currentNode) { if (previous != null) { source = previous; return true; } return false; } if (IsContent(container, node)) { previous = node; } } } } return false; } public override XmlReader ReadSubtree() { XContainer c = source as XContainer; if (c == null) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_BadNodeType, NodeType)); return c.CreateReader(); } bool IXmlLineInfo.HasLineInfo() { IXmlLineInfo li = source as IXmlLineInfo; if (li != null) { return li.HasLineInfo(); } return false; } int IXmlLineInfo.LineNumber { get { IXmlLineInfo li = source as IXmlLineInfo; if (li != null) { return li.LineNumber; } return 0; } } int IXmlLineInfo.LinePosition { get { IXmlLineInfo li = source as IXmlLineInfo; if (li != null) { return li.LinePosition; } return 0; } } static string CollectText(XText n) { string s = n.Value; if (n.GetParent() != null) { foreach (XNode node in n.NodesAfterSelf()) { XText t = node as XText; if (t == null) break; s += t.Value; } } return s; } static XmlNameTable CreateNameTable() { XmlNameTable nameTable = new NameTable(); nameTable.Add(string.Empty); nameTable.Add(xmlnsPrefixNamespace); nameTable.Add(xmlPrefixNamespace); return nameTable; } static bool IsContent(XContainer c, XNode n) { if (c.GetParent() != null || c is XElement) { return true; } return ((1 << (int)n.NodeType) & DocumentContentMask) != 0; } static bool IsSamePosition(XNodeNavigator n1, XNodeNavigator n2) { return n1.source == n2.source && n1.source.GetParent() == n2.source.GetParent(); } static bool IsXmlNamespaceDeclaration(XAttribute a) { return (object)a == (object)GetXmlNamespaceDeclaration(); } static int GetElementContentMask(XPathNodeType type) { return ElementContentMasks[(int)type]; } static XAttribute GetFirstNamespaceDeclarationGlobal(XElement e) { do { XAttribute a = GetFirstNamespaceDeclarationLocal(e); if (a != null) { return a; } e = e.Parent; } while (e != null); return null; } static XAttribute GetFirstNamespaceDeclarationLocal(XElement e) { foreach (XAttribute attribute in e.Attributes()) { if (attribute.IsNamespaceDeclaration) { return attribute; } } return null; } static XAttribute GetNextNamespaceDeclarationGlobal(XAttribute a) { XElement e = (XElement)a.GetParent(); if (e == null) { return null; } XAttribute next = GetNextNamespaceDeclarationLocal(a); if (next != null) { return next; } e = e.Parent; if (e == null) { return null; } return GetFirstNamespaceDeclarationGlobal(e); } static XAttribute GetNextNamespaceDeclarationLocal(XAttribute a) { XElement e = a.Parent; if (e == null) { return null; } a = a.NextAttribute; while (a != null) { if (a.IsNamespaceDeclaration) { return a; } a = a.NextAttribute; } return null; } static XAttribute GetXmlNamespaceDeclaration() { if (XmlNamespaceDeclaration == null) { System.Threading.Interlocked.CompareExchange(ref XmlNamespaceDeclaration, new XAttribute(XNamespace.Xmlns.GetName("xml"), xmlPrefixNamespace), null); } return XmlNamespaceDeclaration; } static bool HasNamespaceDeclarationInScope(XAttribute a, XElement e) { XName name = a.Name; while (e != null && e != a.GetParent()) { if (e.Attribute(name) != null) { return true; } e = e.Parent; } return false; } } struct XPathEvaluator { public object Evaluate<T>(XNode node, string expression, IXmlNamespaceResolver resolver) where T : class { XPathNavigator navigator = node.CreateNavigator(); object result = navigator.Evaluate(expression, resolver); if (result is XPathNodeIterator) { return EvaluateIterator<T>((XPathNodeIterator)result); } if (!(result is T)) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedEvaluation, result.GetType())); return (T)result; } IEnumerable<T> EvaluateIterator<T>(XPathNodeIterator result) { foreach (XPathNavigator navigator in result) { object r = navigator.UnderlyingObject; if (!(r is T)) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedEvaluation, r.GetType())); yield return (T)r; XText t = r as XText; if (t != null && t.GetParent() != null) { foreach (XNode node in t.GetParent().Nodes()) { t = node as XText; if (t == null) break; yield return (T)(object)t; } } } } } /// <summary> /// Extension methods /// </summary> public static class Extensions { /// <summary> /// Creates an <see cref="XPathNavigator"/> for a given <see cref="XNode"/> /// </summary> /// <param name="node">Extension point <see cref="XNode"/></param> /// <returns>An <see cref="XPathNavigator"/></returns> public static XPathNavigator CreateNavigator(this XNode node) { return node.CreateNavigator(null); } /// <summary> /// Creates an <see cref="XPathNavigator"/> for a given <see cref="XNode"/> /// </summary> /// <param name="node">Extension point <see cref="XNode"/></param> /// <param name="nameTable">The <see cref="XmlNameTable"/> to be used by /// the <see cref="XPathNavigator"/></param> /// <returns>An <see cref="XPathNavigator"/></returns> public static XPathNavigator CreateNavigator(this XNode node, XmlNameTable nameTable) { if (node == null) throw new ArgumentNullException("node"); if (node is XDocumentType) throw new ArgumentException(SR.Format(SR.Argument_CreateNavigator, XmlNodeType.DocumentType)); XText text = node as XText; if (text != null) { if (text.GetParent() is XDocument) throw new ArgumentException(SR.Format(SR.Argument_CreateNavigator, XmlNodeType.Whitespace)); node = CalibrateText(text); } return new XNodeNavigator(node, nameTable); } /// <summary> /// Evaluates an XPath expression /// </summary> /// <param name="node">Extension point <see cref="XNode"/></param> /// <param name="expression">The XPath expression</param> /// <returns>The result of evaluating the expression which can be typed as bool, double, string or /// IEnumerable</returns> public static object XPathEvaluate(this XNode node, string expression) { return node.XPathEvaluate(expression, null); } /// <summary> /// Evaluates an XPath expression /// </summary> /// <param name="node">Extension point <see cref="XNode"/></param> /// <param name="expression">The XPath expression</param> /// <param name="resolver">A <see cref="IXmlNamespaceResolver"> for the namespace /// prefixes used in the XPath expression</see></param> /// <returns>The result of evaluating the expression which can be typed as bool, double, string or /// IEnumerable</returns> public static object XPathEvaluate(this XNode node, string expression, IXmlNamespaceResolver resolver) { if (node == null) throw new ArgumentNullException("node"); return new XPathEvaluator().Evaluate<object>(node, expression, resolver); } /// <summary> /// Select an <see cref="XElement"/> using a XPath expression /// </summary> /// <param name="node">Extension point <see cref="XNode"/></param> /// <param name="expression">The XPath expression</param> /// <returns>An <see cref="XElement"> or null</see></returns> public static XElement XPathSelectElement(this XNode node, string expression) { return node.XPathSelectElement(expression, null); } /// <summary> /// Select an <see cref="XElement"/> using a XPath expression /// </summary> /// <param name="node">Extension point <see cref="XNode"/></param> /// <param name="expression">The XPath expression</param> /// <param name="resolver">A <see cref="IXmlNamespaceResolver"/> for the namespace /// prefixes used in the XPath expression</param> /// <returns>An <see cref="XElement"> or null</see></returns> public static XElement XPathSelectElement(this XNode node, string expression, IXmlNamespaceResolver resolver) { return node.XPathSelectElements(expression, resolver).FirstOrDefault(); } /// <summary> /// Select a set of <see cref="XElement"/> using a XPath expression /// </summary> /// <param name="node">Extension point <see cref="XNode"/></param> /// <param name="expression">The XPath expression</param> /// <returns>An <see cref="IEnumerable&lt;XElement&gt;"/> corresponding to the resulting set of elements</returns> public static IEnumerable<XElement> XPathSelectElements(this XNode node, string expression) { return node.XPathSelectElements(expression, null); } /// <summary> /// Select a set of <see cref="XElement"/> using a XPath expression /// </summary> /// <param name="node">Extension point <see cref="XNode"/></param> /// <param name="expression">The XPath expression</param> /// <param name="resolver">A <see cref="IXmlNamespaceResolver"/> for the namespace /// prefixes used in the XPath expression</param> /// <returns>An <see cref="IEnumerable&lt;XElement&gt;"/> corresponding to the resulting set of elements</returns> public static IEnumerable<XElement> XPathSelectElements(this XNode node, string expression, IXmlNamespaceResolver resolver) { if (node == null) throw new ArgumentNullException("node"); return (IEnumerable<XElement>)new XPathEvaluator().Evaluate<XElement>(node, expression, resolver); } static XText CalibrateText(XText n) { XContainer parentNode = n.GetParent(); if (parentNode == null) { return n; } foreach (XNode node in parentNode.Nodes()) { XText t = node as XText; bool isTextNode = t != null; if (isTextNode && node == n) { return t; } } System.Diagnostics.Debug.Assert(false, "Parent node doesn't contain itself."); return null; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Security.Permissions { using System; #if FEATURE_CAS_POLICY using SecurityElement = System.Security.SecurityElement; #endif // FEATURE_CAS_POLICY using SiteString = System.Security.Util.SiteString; using System.Text; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.Serialization; [System.Runtime.InteropServices.ComVisible(true)] #if FEATURE_SERIALIZATION [Serializable] #endif sealed public class SiteIdentityPermission : CodeAccessPermission, IBuiltInPermission { //------------------------------------------------------ // // PRIVATE STATE DATA // //------------------------------------------------------ [OptionalField(VersionAdded = 2)] private bool m_unrestricted; [OptionalField(VersionAdded = 2)] private SiteString[] m_sites; #if FEATURE_REMOTING // This field will be populated only for non X-AD scenarios where we create a XML-ised string of the Permission [OptionalField(VersionAdded = 2)] private String m_serializedPermission; // This field is legacy info from v1.x and is never used in v2.0 and beyond: purely for serialization purposes private SiteString m_site; [OnDeserialized] private void OnDeserialized(StreamingContext ctx) { // v2.0 and beyond XML case if (m_serializedPermission != null) { FromXml(SecurityElement.FromString(m_serializedPermission)); m_serializedPermission = null; } else if (m_site != null) //v1.x case where we read the m_site value { m_unrestricted = false; m_sites = new SiteString[1]; m_sites[0] = m_site; m_site = null; } } [OnSerializing] private void OnSerializing(StreamingContext ctx) { if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) { m_serializedPermission = ToXml().ToString(); //for the v2 and beyond case if (m_sites != null && m_sites.Length == 1) // for the v1.x case m_site = m_sites[0]; } } [OnSerialized] private void OnSerialized(StreamingContext ctx) { if ((ctx.State & ~(StreamingContextStates.Clone|StreamingContextStates.CrossAppDomain)) != 0) { m_serializedPermission = null; m_site = null; } } #endif // FEATURE_REMOTING //------------------------------------------------------ // // PUBLIC CONSTRUCTORS // //------------------------------------------------------ public SiteIdentityPermission(PermissionState state) { if (state == PermissionState.Unrestricted) { m_unrestricted = true; } else if (state == PermissionState.None) { m_unrestricted = false; } else { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPermissionState")); } } public SiteIdentityPermission( String site ) { Site = site; } //------------------------------------------------------ // // PUBLIC ACCESSOR METHODS // //------------------------------------------------------ public String Site { set { m_unrestricted = false; m_sites = new SiteString[1]; m_sites[0] = new SiteString( value ); } get { if(m_sites == null) return ""; if(m_sites.Length == 1) return m_sites[0].ToString(); throw new NotSupportedException(Environment.GetResourceString("NotSupported_AmbiguousIdentity")); } } //------------------------------------------------------ // // PRIVATE AND PROTECTED HELPERS FOR ACCESSORS AND CONSTRUCTORS // //------------------------------------------------------ //------------------------------------------------------ // // CODEACCESSPERMISSION IMPLEMENTATION // //------------------------------------------------------ //------------------------------------------------------ // // IPERMISSION IMPLEMENTATION // //------------------------------------------------------ public override IPermission Copy() { SiteIdentityPermission perm = new SiteIdentityPermission( PermissionState.None ); perm.m_unrestricted = this.m_unrestricted; if (this.m_sites != null) { perm.m_sites = new SiteString[this.m_sites.Length]; int n; for(n = 0; n < this.m_sites.Length; n++) perm.m_sites[n] = (SiteString)this.m_sites[n].Copy(); } return perm; } public override bool IsSubsetOf(IPermission target) { if (target == null) { if(m_unrestricted) return false; if(m_sites == null) return true; if(m_sites.Length == 0) return true; return false; } SiteIdentityPermission that = target as SiteIdentityPermission; if(that == null) throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); if(that.m_unrestricted) return true; if(m_unrestricted) return false; if(this.m_sites != null) { foreach(SiteString ssThis in this.m_sites) { bool bOK = false; if(that.m_sites != null) { foreach(SiteString ssThat in that.m_sites) { if(ssThis.IsSubsetOf(ssThat)) { bOK = true; break; } } } if(!bOK) return false; } } return true; } public override IPermission Intersect(IPermission target) { if (target == null) return null; SiteIdentityPermission that = target as SiteIdentityPermission; if(that == null) throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); if(this.m_unrestricted && that.m_unrestricted) { SiteIdentityPermission res = new SiteIdentityPermission(PermissionState.None); res.m_unrestricted = true; return res; } if(this.m_unrestricted) return that.Copy(); if(that.m_unrestricted) return this.Copy(); if(this.m_sites == null || that.m_sites == null || this.m_sites.Length == 0 || that.m_sites.Length == 0) return null; List<SiteString> alSites = new List<SiteString>(); foreach(SiteString ssThis in this.m_sites) { foreach(SiteString ssThat in that.m_sites) { SiteString ssInt = (SiteString)ssThis.Intersect(ssThat); if(ssInt != null) alSites.Add(ssInt); } } if(alSites.Count == 0) return null; SiteIdentityPermission result = new SiteIdentityPermission(PermissionState.None); result.m_sites = alSites.ToArray(); return result; } public override IPermission Union(IPermission target) { if (target == null) { if((this.m_sites == null || this.m_sites.Length == 0) && !this.m_unrestricted) return null; return this.Copy(); } SiteIdentityPermission that = target as SiteIdentityPermission; if(that == null) throw new ArgumentException(Environment.GetResourceString("Argument_WrongType", this.GetType().FullName)); if(this.m_unrestricted || that.m_unrestricted) { SiteIdentityPermission res = new SiteIdentityPermission(PermissionState.None); res.m_unrestricted = true; return res; } if (this.m_sites == null || this.m_sites.Length == 0) { if(that.m_sites == null || that.m_sites.Length == 0) return null; return that.Copy(); } if(that.m_sites == null || that.m_sites.Length == 0) return this.Copy(); List<SiteString> alSites = new List<SiteString>(); foreach(SiteString ssThis in this.m_sites) alSites.Add(ssThis); foreach(SiteString ssThat in that.m_sites) { bool bDupe = false; foreach(SiteString ss in alSites) { if(ssThat.Equals(ss)) { bDupe = true; break; } } if(!bDupe) alSites.Add(ssThat); } SiteIdentityPermission result = new SiteIdentityPermission(PermissionState.None); result.m_sites = alSites.ToArray(); return result; } #if FEATURE_CAS_POLICY public override void FromXml(SecurityElement esd) { m_unrestricted = false; m_sites = null; CodeAccessPermission.ValidateElement( esd, this ); String unr = esd.Attribute( "Unrestricted" ); if(unr != null && String.Compare(unr, "true", StringComparison.OrdinalIgnoreCase) == 0) { m_unrestricted = true; return; } String elem = esd.Attribute( "Site" ); List<SiteString> al = new List<SiteString>(); if(elem != null) al.Add(new SiteString( elem )); ArrayList alChildren = esd.Children; if(alChildren != null) { foreach(SecurityElement child in alChildren) { elem = child.Attribute( "Site" ); if(elem != null) al.Add(new SiteString( elem )); } } if(al.Count != 0) m_sites = al.ToArray(); } public override SecurityElement ToXml() { SecurityElement esd = CodeAccessPermission.CreatePermissionElement( this, "System.Security.Permissions.SiteIdentityPermission" ); if (m_unrestricted) esd.AddAttribute( "Unrestricted", "true" ); else if (m_sites != null) { if (m_sites.Length == 1) esd.AddAttribute( "Site", m_sites[0].ToString() ); else { int n; for(n = 0; n < m_sites.Length; n++) { SecurityElement child = new SecurityElement("Site"); child.AddAttribute( "Site", m_sites[n].ToString() ); esd.AddChild(child); } } } return esd; } #endif // FEATURE_CAS_POLICY /// <internalonly/> int IBuiltInPermission.GetTokenIndex() { return SiteIdentityPermission.GetTokenIndex(); } internal static int GetTokenIndex() { return BuiltInPermissionIndex.SiteIdentityPermissionIndex; } } }
namespace FacebookSharp { using System; using System.Text; using System.Collections.Generic; public partial class Facebook { internal const string OldRestApiWarningMessage = "This method uses Old Rest api to make the request. It may be removed by facebook anytime soon."; private FacebookSettings _settings; public FacebookSettings Settings { get { return _settings; } } /// <summary> /// Initializes a new instance of the <see cref="Facebook"/> class. /// </summary> public Facebook() : this((FacebookSettings)null) { } /// <summary> /// Initializes a new instance of the <see cref="Facebook"/> class. /// </summary> /// <param name="accessToken"> /// The access token. /// </param> public Facebook(string accessToken) : this(new FacebookSettings { AccessToken = accessToken }) { } /// <summary> /// Initializes a new instance of the <see cref="Facebook"/> class. /// </summary> /// <param name="accessToken"> /// The access token. /// </param> /// <param name="expiresIn"> /// The expires in. /// </param> public Facebook(string accessToken, long expiresIn) : this(new FacebookSettings { AccessToken = accessToken, AccessExpires = expiresIn }) { } /// <summary> /// Initializes a new instance of the <see cref="Facebook"/> class. /// </summary> /// <param name="facebookSettings"> /// The facebook settings. /// </param> public Facebook(FacebookSettings facebookSettings) { _settings = facebookSettings ?? (_settings = new FacebookSettings()); } public static readonly string Token = "access_token"; public static readonly string Expires = "expires_in"; internal static readonly string DefaultUserAgent = "FacebookSharp"; #region Facebook Server endpoints. // May be modified in a subclass for testing. protected static readonly string _oauthEndpoint = "https://graph.facebook.com/oauth/authorize"; public static string OauthEndpoint { get { return _oauthEndpoint; } } protected static string _graphBaseUrl = "https://graph.facebook.com"; public static string GraphBaseUrl { get { return _graphBaseUrl; } } protected static string _apiBaseUrl = "https://api.facebook.com"; public static string ApiBaseUrl { get { return _apiBaseUrl; } } #endregion /// <summary> /// Gets the OAuth 2.0 access token for API access: treat with care. /// </summary> /// <remarks> /// Returns null if no session exists. /// </remarks> public string AccessToken { get { return Settings.AccessToken; } } /// <summary> /// Gets the current session's expiration time (in milliseconds since Unix epoch), /// or 0 if the session doen't expire or doesn't exist. /// </summary> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public long AccessExpires { get { return Settings.AccessExpires; } } /// <summary> /// Checks whether this object has an non-expired session token. /// </summary> /// <returns>Return true if session is valid otherwise false.</returns> public bool IsSessionValid() { if (string.IsNullOrEmpty(AccessToken)) return false; if (AccessExpires == 0) return true; if (DateTime.Compare(FacebookUtils.Date.FromUnixTimestamp(AccessExpires), DateTime.UtcNow) > 0) return true; return false; } /// <summary> /// Set the current session's duration (in seconds since Unix epoch). /// </summary> /// <param name="expiresIn">Duration in seconds.</param> public void SetAccessExpiresIn(string expiresIn) { // should probably remove this function entirely throw new NotImplementedException(); } /// <summary> /// Returns the url to authenticate with Facebook. /// </summary> /// <param name="facebookApplicationKey"></param> /// <param name="redirectUri"></param> /// <param name="extendedPermissions"></param> /// <returns></returns> public static string GenerateFacebookAuthorizeUrl(string facebookApplicationKey, string redirectUri, string[] extendedPermissions) { StringBuilder sb = new StringBuilder(); if (extendedPermissions != null && extendedPermissions.Length > 0) sb.Append(String.Join(",", extendedPermissions)); return GenerateFacebookAuthorizeUrl(facebookApplicationKey, redirectUri, sb.ToString()); } /// <summary> /// Returns the url to authenticate with Facebook. /// </summary> /// <param name="facebookApplicationKey"></param> /// <param name="redirectUri"></param> /// <param name="extendedPermissions"></param> /// <returns></returns> public static string GenerateFacebookAuthorizeUrl(string facebookApplicationKey, string redirectUri, string extendedPermissions) { return string.IsNullOrEmpty(extendedPermissions) ? string.Format(GraphBaseUrl + "/oauth/authorize?client_id={0}&redirect_uri={1}", facebookApplicationKey, redirectUri) : string.Format(GraphBaseUrl + "/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}", facebookApplicationKey, redirectUri, extendedPermissions); } /// <summary> /// Returns the url to login with Facebook. /// </summary> /// <param name="parameters"></param> /// <returns></returns> public static string GenerateFacebookLoginUrl(IDictionary<string, string> parameters) { return GenerateFacebookLoginUrl(parameters, new string[0]); } /// <summary> /// Returns the url to login with Facebook. /// </summary> /// <param name="parameters"></param> /// <param name="extendedPermissions"></param> /// <returns></returns> public static string GenerateFacebookLoginUrl(IDictionary<string, string> parameters, string extendedPermissions) { return GenerateFacebookLoginUrl(parameters, new string[1] { extendedPermissions }); } /// <summary> /// Returns the url to login with Facebook. /// </summary> /// <param name="parameters"></param> /// <param name="extendedPermissions"></param> /// <returns></returns> public static string GenerateFacebookLoginUrl(IDictionary<string, string> parameters, string[] extendedPermissions) { // todo: make these static somewhere else... (maybe setup defaults somewhere too) List<string> allowedParams = new List<string>(); allowedParams.Add("api_key"); allowedParams.Add("next"); allowedParams.Add("canvas"); allowedParams.Add("display"); allowedParams.Add("cancel_url"); allowedParams.Add("fbconnect"); allowedParams.Add("return_session"); allowedParams.Add("session_version"); allowedParams.Add("v"); StringBuilder loginUrl = new StringBuilder(); loginUrl.Append("http://www.facebook.com/login.php?"); List<string> paramList = new List<string>(); // todo: encode parameter values foreach (KeyValuePair<string, string> p in parameters) { if (allowedParams.Contains(p.Key)) paramList.Add(p.Key + "=" + FacebookUtils.UrlEncode(p.Value)); } if (extendedPermissions != null && extendedPermissions.Length > 0) paramList.Add("req_perms=" + String.Join(",", extendedPermissions)); loginUrl.Append(String.Join("&", paramList.ToArray())); return loginUrl.ToString(); } /// <summary> /// Returns the url to logout of Facebook. /// </summary> /// <param name="parameters"></param> /// <returns></returns> public static string GenerateFacebookLogoutUrl(IDictionary<string, string> parameters) { // todo: make these static somewhere else... (maybe setup defaults somewhere too) List<string> allowedParams = new List<string>(); allowedParams.Add("next"); allowedParams.Add("access_token"); StringBuilder logoutUrl = new StringBuilder(); logoutUrl.Append("http://www.facebook.com/logout.php?"); List<string> paramList = new List<string>(); // todo: encode parameter values foreach (KeyValuePair<string, string> p in parameters) { if (allowedParams.Contains(p.Key)) paramList.Add(p.Key + "=" + FacebookUtils.UrlEncode(p.Value)); } logoutUrl.Append(String.Join("&",paramList.ToArray())); return logoutUrl.ToString(); } /// <summary> /// Returns the url to check the login status of Facebook. /// </summary> /// <param name="parameters"></param> /// <returns></returns> public static string GenerateFacebookLoginStatusUrl(IDictionary<string, string> parameters) { // todo: make these static somewhere else... (maybe setup defaults somewhere too) List<string> allowedParams = new List<string>(); allowedParams.Add("api_key"); allowedParams.Add("ok_session"); allowedParams.Add("no_session"); allowedParams.Add("no_user"); allowedParams.Add("session_version"); // typically '3' StringBuilder statusUrl = new StringBuilder(); statusUrl.Append("http://www.facebook.com/extern/login_status.php?"); List<string> paramList = new List<string>(); // todo: encode parameter values foreach (KeyValuePair<string, string> p in parameters) { if (allowedParams.Contains(p.Key)) paramList.Add(p.Key + "=" + FacebookUtils.UrlEncode(p.Value)); } statusUrl.Append(String.Join("&",paramList.ToArray())); return statusUrl.ToString(); } } }
// Copyright (c) 2012 DotNetAnywhere // // 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. #if !LOCALTEST using System; using System.Collections.Generic; using System.Text; using System.Runtime.CompilerServices; using System.Globalization; namespace System { public struct Char : IComparable, IComparable<char>, IEquatable<char> { // Note that this array must be ordered, because binary searching is used on it. internal static readonly char[] WhiteChars = { (char) 0x9, (char) 0xA, (char) 0xB, (char) 0xC, (char) 0xD, (char) 0x85, (char) 0x1680, (char) 0x2028, (char) 0x2029, (char) 0x20, (char) 0xA0, (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 }; internal char m_value; public override string ToString() { return new string(m_value, 1); } public override bool Equals(object obj) { return (obj is char && ((char)obj).m_value == this.m_value); } public override int GetHashCode() { return (int)this.m_value; } [MethodImpl(MethodImplOptions.InternalCall)] extern static public UnicodeCategory GetUnicodeCategory(char c); public static UnicodeCategory GetUnicodeCategory(string str, int index) { if (str == null) { throw new ArgumentNullException("str"); } if (index < 0 || index >= str.Length) { throw new ArgumentOutOfRangeException("index"); } return GetUnicodeCategory(str[index]); } public static bool IsWhiteSpace(char c) { // TODO: Make this use Array.BinarySearch() when implemented for (int i = 0; i < WhiteChars.Length; i++) { if (WhiteChars[i] == c) { return true; } } return false; } public static bool IsWhiteSpace(string str, int index) { if (str == null) { throw new ArgumentNullException("str"); } if (index < 0 || index >= str.Length) { throw new ArgumentOutOfRangeException("index"); } return IsWhiteSpace(str[index]); } public static bool IsLetter(char c) { return GetUnicodeCategory(c) <= UnicodeCategory.OtherLetter; } public static bool IsLetter(string str, int index) { if (str == null) { throw new ArgumentNullException("str"); } if (index < 0 || index >= str.Length) { throw new ArgumentOutOfRangeException("index"); } return IsLetter(str[index]); } public static bool IsDigit(char c) { return GetUnicodeCategory(c) == UnicodeCategory.DecimalDigitNumber; } public static bool IsDigit(string str, int index) { if (str == null) { throw new ArgumentNullException("str"); } if (index < 0 || index >= str.Length) { throw new ArgumentOutOfRangeException("index"); } return IsDigit(str[index]); } public static bool IsLower(char c) { return GetUnicodeCategory(c) == UnicodeCategory.LowercaseLetter; } public static bool IsLower(string str, int index) { if (str == null) { throw new ArgumentNullException("str"); } if (index < 0 || index >= str.Length) { throw new ArgumentOutOfRangeException("index"); } return IsLower(str[index]); } public static bool IsUpper(char c) { return GetUnicodeCategory(c) == UnicodeCategory.UppercaseLetter; } public static bool IsUpper(string str, int index) { if (str == null) { throw new ArgumentNullException("str"); } if (index < 0 || index >= str.Length) { throw new ArgumentOutOfRangeException("index"); } return IsUpper(str[index]); } [MethodImpl(MethodImplOptions.InternalCall)] extern public static char ToLowerInvariant(char c); public static char ToLower(char c) { return ToLower(c, CultureInfo.CurrentCulture); } public static char ToLower(char c, CultureInfo culture) { if (culture == null) { throw new ArgumentNullException("culture"); } if (culture.LCID == 0x7f) { // Invariant culture return ToLowerInvariant(c); } return '?'; //return culture.TextInfo.ToUpper(c); } [MethodImpl(MethodImplOptions.InternalCall)] extern public static char ToUpperInvariant(char c); public static char ToUpper(char c) { return ToUpper(c, CultureInfo.CurrentCulture); } public static char ToUpper(char c, CultureInfo culture) { if (culture == null) { throw new ArgumentNullException("culture"); } if (culture.LCID == 0x7f) { // Invariant culture return ToUpperInvariant(c); } return '?'; //return culture.TextInfo.ToUpper(c); } #region IComparable Members public int CompareTo(object obj) { if (obj == null) { return 1; } if (!(obj is char)) { throw new ArgumentException(); } return this.CompareTo((char)obj); } #endregion #region IComparable<char> Members public int CompareTo(char x) { return (this.m_value > x) ? 1 : ((this.m_value < x) ? -1 : 0); } #endregion #region IEquatable<char> Members public bool Equals(char x) { return this.m_value == x; } #endregion } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics.CodeAnalysis; namespace System.Globalization { /*=================================TaiwanCalendar========================== ** ** Taiwan calendar is based on the Gregorian calendar. And the year is an offset to Gregorian calendar. ** That is, ** Taiwan year = Gregorian year - 1911. So 1912/01/01 A.D. is Taiwan 1/01/01 ** ** Calendar support range: ** Calendar Minimum Maximum ** ========== ========== ========== ** Gregorian 1912/01/01 9999/12/31 ** Taiwan 01/01/01 8088/12/31 ============================================================================*/ public class TaiwanCalendar : Calendar { // // The era value for the current era. // // Since // Gregorian Year = Era Year + yearOffset // When Gregorian Year 1912 is year 1, so that // 1912 = 1 + yearOffset // So yearOffset = 1911 //m_EraInfo[0] = new EraInfo(1, new DateTime(1912, 1, 1).Ticks, 1911, 1, GregorianCalendar.MaxYear - 1911); // Initialize our era info. internal static EraInfo[] taiwanEraInfo = new EraInfo[] { new EraInfo( 1, 1912, 1, 1, 1911, 1, GregorianCalendar.MaxYear - 1911) // era #, start year/month/day, yearOffset, minEraYear }; internal static volatile Calendar s_defaultInstance; internal GregorianCalendarHelper helper; /*=================================GetDefaultInstance========================== **Action: Internal method to provide a default intance of TaiwanCalendar. Used by NLS+ implementation ** and other calendars. **Returns: **Arguments: **Exceptions: ============================================================================*/ internal static Calendar GetDefaultInstance() { if (s_defaultInstance == null) { s_defaultInstance = new TaiwanCalendar(); } return (s_defaultInstance); } internal static readonly DateTime calendarMinValue = new DateTime(1912, 1, 1); public override DateTime MinSupportedDateTime { get { return (calendarMinValue); } } public override DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } public override CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.SolarCalendar; } } // Return the type of the Taiwan calendar. // public TaiwanCalendar() { try { new CultureInfo("zh-TW"); } catch (ArgumentException e) { throw new TypeInitializationException(this.GetType().ToString(), e); } helper = new GregorianCalendarHelper(this, taiwanEraInfo); } internal override CalendarId ID { get { return CalendarId.TAIWAN; } } public override DateTime AddMonths(DateTime time, int months) { return (helper.AddMonths(time, months)); } public override DateTime AddYears(DateTime time, int years) { return (helper.AddYears(time, years)); } public override int GetDaysInMonth(int year, int month, int era) { return (helper.GetDaysInMonth(year, month, era)); } public override int GetDaysInYear(int year, int era) { return (helper.GetDaysInYear(year, era)); } public override int GetDayOfMonth(DateTime time) { return (helper.GetDayOfMonth(time)); } public override DayOfWeek GetDayOfWeek(DateTime time) { return (helper.GetDayOfWeek(time)); } public override int GetDayOfYear(DateTime time) { return (helper.GetDayOfYear(time)); } public override int GetMonthsInYear(int year, int era) { return (helper.GetMonthsInYear(year, era)); } public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { return (helper.GetWeekOfYear(time, rule, firstDayOfWeek)); } public override int GetEra(DateTime time) { return (helper.GetEra(time)); } public override int GetMonth(DateTime time) { return (helper.GetMonth(time)); } public override int GetYear(DateTime time) { return (helper.GetYear(time)); } public override bool IsLeapDay(int year, int month, int day, int era) { return (helper.IsLeapDay(year, month, day, era)); } public override bool IsLeapYear(int year, int era) { return (helper.IsLeapYear(year, era)); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public override int GetLeapMonth(int year, int era) { return (helper.GetLeapMonth(year, era)); } public override bool IsLeapMonth(int year, int month, int era) { return (helper.IsLeapMonth(year, month, era)); } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return (helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era)); } public override int[] Eras { get { return (helper.Eras); } } private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 99; public override int TwoDigitYearMax { get { if (twoDigitYearMax == -1) { twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX); } return (twoDigitYearMax); } set { VerifyWritable(); if (value < 99 || value > helper.MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 99, helper.MaxYear)); } twoDigitYearMax = value; } } // For Taiwan calendar, four digit year is not used. // Therefore, for any two digit number, we just return the original number. public override int ToFourDigitYear(int year) { if (year <= 0) { throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedPosNum); } if (year > helper.MaxYear) { throw new ArgumentOutOfRangeException( nameof(year), String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, helper.MaxYear)); } return (year); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Reflection.ParameterInfo.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Reflection { public partial class ParameterInfo : System.Runtime.InteropServices._ParameterInfo, ICustomAttributeProvider, System.Runtime.Serialization.IObjectReference { #region Methods and constructors public virtual new Object[] GetCustomAttributes(bool inherit) { return default(Object[]); } public virtual new Object[] GetCustomAttributes(Type attributeType, bool inherit) { return default(Object[]); } public virtual new IList<CustomAttributeData> GetCustomAttributesData() { return default(IList<CustomAttributeData>); } public virtual new Type[] GetOptionalCustomModifiers() { return default(Type[]); } public Object GetRealObject(System.Runtime.Serialization.StreamingContext context) { return default(Object); } public virtual new Type[] GetRequiredCustomModifiers() { return default(Type[]); } public virtual new bool IsDefined(Type attributeType, bool inherit) { return default(bool); } protected ParameterInfo() { } void System.Runtime.InteropServices._ParameterInfo.GetIDsOfNames(ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { } void System.Runtime.InteropServices._ParameterInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { } void System.Runtime.InteropServices._ParameterInfo.GetTypeInfoCount(out uint pcTInfo) { pcTInfo = default(uint); } void System.Runtime.InteropServices._ParameterInfo.Invoke(uint dispIdMember, ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { } public override string ToString() { return default(string); } #endregion #region Properties and indexers public virtual new ParameterAttributes Attributes { get { return default(ParameterAttributes); } } public virtual new Object DefaultValue { get { return default(Object); } } public bool IsIn { get { Contract.Ensures(Contract.Result<bool>() == ((((this.Attributes & ((System.Reflection.ParameterAttributes)(1)))) == ((System.Reflection.ParameterAttributes)(0))) == false)); return default(bool); } } public bool IsLcid { get { Contract.Ensures(Contract.Result<bool>() == ((((this.Attributes & ((System.Reflection.ParameterAttributes)(4)))) == ((System.Reflection.ParameterAttributes)(0))) == false)); return default(bool); } } public bool IsOptional { get { Contract.Ensures(Contract.Result<bool>() == ((((this.Attributes & ((System.Reflection.ParameterAttributes)(16)))) == ((System.Reflection.ParameterAttributes)(0))) == false)); return default(bool); } } public bool IsOut { get { Contract.Ensures(Contract.Result<bool>() == ((((this.Attributes & ((System.Reflection.ParameterAttributes)(2)))) == ((System.Reflection.ParameterAttributes)(0))) == false)); return default(bool); } } public bool IsRetval { get { Contract.Ensures(Contract.Result<bool>() == ((((this.Attributes & ((System.Reflection.ParameterAttributes)(8)))) == ((System.Reflection.ParameterAttributes)(0))) == false)); return default(bool); } } public virtual new MemberInfo Member { get { return default(MemberInfo); } } public virtual new int MetadataToken { get { return default(int); } } public virtual new string Name { get { return default(string); } } public virtual new Type ParameterType { get { return default(Type); } } public virtual new int Position { get { return default(int); } } public virtual new Object RawDefaultValue { get { return default(Object); } } #endregion #region Fields protected ParameterAttributes AttrsImpl; protected Type ClassImpl; protected Object DefaultValueImpl; protected MemberInfo MemberImpl; protected string NameImpl; protected int PositionImpl; #endregion } }
using System; using System.IO; namespace Ionic.Zlib { /// <summary> /// A class for compressing and decompressing GZIP streams. /// </summary> /// <remarks> /// /// <para> /// The <c>GZipStream</c> is a <see /// href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</see> on a /// <see cref="Stream"/>. It adds GZIP compression or decompression to any /// stream. /// </para> /// /// <para> /// Like the <c>System.IO.Compression.GZipStream</c> in the .NET Base Class Library, the /// <c>Ionic.Zlib.GZipStream</c> can compress while writing, or decompress while /// reading, but not vice versa. The compression method used is GZIP, which is /// documented in <see href="http://www.ietf.org/rfc/rfc1952.txt">IETF RFC /// 1952</see>, "GZIP file format specification version 4.3".</para> /// /// <para> /// A <c>GZipStream</c> can be used to decompress data (through <c>Read()</c>) or /// to compress data (through <c>Write()</c>), but not both. /// </para> /// /// <para> /// If you wish to use the <c>GZipStream</c> to compress data, you must wrap it /// around a write-able stream. As you call <c>Write()</c> on the <c>GZipStream</c>, the /// data will be compressed into the GZIP format. If you want to decompress data, /// you must wrap the <c>GZipStream</c> around a readable stream that contains an /// IETF RFC 1952-compliant stream. The data will be decompressed as you call /// <c>Read()</c> on the <c>GZipStream</c>. /// </para> /// /// <para> /// Though the GZIP format allows data from multiple files to be concatenated /// together, this stream handles only a single segment of GZIP format, typically /// representing a single file. /// </para> /// /// <para> /// This class is similar to <see cref="ZlibStream"/> and <see cref="DeflateStream"/>. /// <c>ZlibStream</c> handles RFC1950-compliant streams. <see cref="DeflateStream"/> /// handles RFC1951-compliant streams. This class handles RFC1952-compliant streams. /// </para> /// /// </remarks> /// /// <seealso cref="DeflateStream" /> /// <seealso cref="ZlibStream" /> public class GZipStream : System.IO.Stream { // GZip format // source: http://tools.ietf.org/html/rfc1952 // // header id: 2 bytes 1F 8B // compress method 1 byte 8= DEFLATE (none other supported) // flag 1 byte bitfield (See below) // mtime 4 bytes time_t (seconds since jan 1, 1970 UTC of the file. // xflg 1 byte 2 = max compress used , 4 = max speed (can be ignored) // OS 1 byte OS for originating archive. set to 0xFF in compression. // extra field length 2 bytes optional - only if FEXTRA is set. // extra field varies // filename varies optional - if FNAME is set. zero terminated. ISO-8859-1. // file comment varies optional - if FCOMMENT is set. zero terminated. ISO-8859-1. // crc16 1 byte optional - present only if FHCRC bit is set // compressed data varies // CRC32 4 bytes // isize 4 bytes data size modulo 2^32 // // FLG (FLaGs) // bit 0 FTEXT - indicates file is ASCII text (can be safely ignored) // bit 1 FHCRC - there is a CRC16 for the header immediately following the header // bit 2 FEXTRA - extra fields are present // bit 3 FNAME - the zero-terminated filename is present. encoding; ISO-8859-1. // bit 4 FCOMMENT - a zero-terminated file comment is present. encoding: ISO-8859-1 // bit 5 reserved // bit 6 reserved // bit 7 reserved // // On consumption: // Extra field is a bunch of nonsense and can be safely ignored. // Header CRC and OS, likewise. // // on generation: // all optional fields get 0, except for the OS, which gets 255. // /// <summary> /// The comment on the GZIP stream. /// </summary> /// /// <remarks> /// <para> /// The GZIP format allows for each file to optionally have an associated /// comment stored with the file. The comment is encoded with the ISO-8859-1 /// code page. To include a comment in a GZIP stream you create, set this /// property before calling <c>Write()</c> for the first time on the /// <c>GZipStream</c>. /// </para> /// /// <para> /// When using <c>GZipStream</c> to decompress, you can retrieve this property /// after the first call to <c>Read()</c>. If no comment has been set in the /// GZIP bytestream, the Comment property will return <c>null</c> /// (<c>Nothing</c> in VB). /// </para> /// </remarks> public String Comment { get { return _Comment; } set { if (_disposed) throw new ObjectDisposedException("GZipStream"); _Comment = value; } } /// <summary> /// The FileName for the GZIP stream. /// </summary> /// /// <remarks> /// /// <para> /// The GZIP format optionally allows each file to have an associated /// filename. When compressing data (through <c>Write()</c>), set this /// FileName before calling <c>Write()</c> the first time on the <c>GZipStream</c>. /// The actual filename is encoded into the GZIP bytestream with the /// ISO-8859-1 code page, according to RFC 1952. It is the application's /// responsibility to insure that the FileName can be encoded and decoded /// correctly with this code page. /// </para> /// /// <para> /// When decompressing (through <c>Read()</c>), you can retrieve this value /// any time after the first <c>Read()</c>. In the case where there was no filename /// encoded into the GZIP bytestream, the property will return <c>null</c> (<c>Nothing</c> /// in VB). /// </para> /// </remarks> public String FileName { get { return _FileName; } set { if (_disposed) throw new ObjectDisposedException("GZipStream"); _FileName = value; if (_FileName == null) return; if (_FileName.IndexOf("/") != -1) { _FileName = _FileName.Replace("/", "\\"); } if (_FileName.EndsWith("\\")) throw new Exception("Illegal filename"); if (_FileName.IndexOf("\\") != -1) { // trim any leading path _FileName = Path.GetFileName(_FileName); } } } /// <summary> /// The last modified time for the GZIP stream. /// </summary> /// /// <remarks> /// GZIP allows the storage of a last modified time with each GZIP entry. /// When compressing data, you can set this before the first call to /// <c>Write()</c>. When decompressing, you can retrieve this value any time /// after the first call to <c>Read()</c>. /// </remarks> public DateTime? LastModified; /// <summary> /// The CRC on the GZIP stream. /// </summary> /// <remarks> /// This is used for internal error checking. You probably don't need to look at this property. /// </remarks> public int Crc32 { get { return _Crc32; } } private int _headerByteCount; internal ZlibBaseStream _baseStream; bool _disposed; bool _firstReadDone; string _FileName; string _Comment; int _Crc32; /// <summary> /// Create a <c>GZipStream</c> using the specified <c>CompressionMode</c>. /// </summary> /// <remarks> /// /// <para> /// When mode is <c>CompressionMode.Compress</c>, the <c>GZipStream</c> will use the /// default compression level. /// </para> /// /// <para> /// As noted in the class documentation, the <c>CompressionMode</c> (Compress /// or Decompress) also establishes the "direction" of the stream. A /// <c>GZipStream</c> with <c>CompressionMode.Compress</c> works only through /// <c>Write()</c>. A <c>GZipStream</c> with /// <c>CompressionMode.Decompress</c> works only through <c>Read()</c>. /// </para> /// /// </remarks> /// /// <example> /// This example shows how to use a GZipStream to compress data. /// <code> /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (var raw = System.IO.File.Create(outputFile)) /// { /// using (Stream compressor = new GZipStream(raw, CompressionMode.Compress)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n; /// while ((n= input.Read(buffer, 0, buffer.Length)) != 0) /// { /// compressor.Write(buffer, 0, n); /// } /// } /// } /// } /// </code> /// <code lang="VB"> /// Dim outputFile As String = (fileToCompress &amp; ".compressed") /// Using input As Stream = File.OpenRead(fileToCompress) /// Using raw As FileStream = File.Create(outputFile) /// Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n &lt;&gt; 0) /// If (n &gt; 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// End Using /// </code> /// </example> /// /// <example> /// This example shows how to use a GZipStream to uncompress a file. /// <code> /// private void GunZipFile(string filename) /// { /// if (!filename.EndsWith(".gz)) /// throw new ArgumentException("filename"); /// var DecompressedFile = filename.Substring(0,filename.Length-3); /// byte[] working = new byte[WORKING_BUFFER_SIZE]; /// int n= 1; /// using (System.IO.Stream input = System.IO.File.OpenRead(filename)) /// { /// using (Stream decompressor= new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true)) /// { /// using (var output = System.IO.File.Create(DecompressedFile)) /// { /// while (n !=0) /// { /// n= decompressor.Read(working, 0, working.Length); /// if (n > 0) /// { /// output.Write(working, 0, n); /// } /// } /// } /// } /// } /// } /// </code> /// /// <code lang="VB"> /// Private Sub GunZipFile(ByVal filename as String) /// If Not (filename.EndsWith(".gz)) Then /// Throw New ArgumentException("filename") /// End If /// Dim DecompressedFile as String = filename.Substring(0,filename.Length-3) /// Dim working(WORKING_BUFFER_SIZE) as Byte /// Dim n As Integer = 1 /// Using input As Stream = File.OpenRead(filename) /// Using decompressor As Stream = new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, True) /// Using output As Stream = File.Create(UncompressedFile) /// Do /// n= decompressor.Read(working, 0, working.Length) /// If n > 0 Then /// output.Write(working, 0, n) /// End IF /// Loop While (n > 0) /// End Using /// End Using /// End Using /// End Sub /// </code> /// </example> /// /// <param name="stream">The stream which will be read or written.</param> /// <param name="mode">Indicates whether the GZipStream will compress or decompress.</param> public GZipStream(Stream stream, CompressionMode mode) : this(stream, mode, CompressionLevel.Default, false) { } /// <summary> /// Create a <c>GZipStream</c> using the specified <c>CompressionMode</c> and /// the specified <c>CompressionLevel</c>. /// </summary> /// <remarks> /// /// <para> /// The <c>CompressionMode</c> (Compress or Decompress) also establishes the /// "direction" of the stream. A <c>GZipStream</c> with /// <c>CompressionMode.Compress</c> works only through <c>Write()</c>. A /// <c>GZipStream</c> with <c>CompressionMode.Decompress</c> works only /// through <c>Read()</c>. /// </para> /// /// </remarks> /// /// <example> /// /// This example shows how to use a <c>GZipStream</c> to compress a file into a .gz file. /// /// <code> /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (var raw = System.IO.File.Create(fileToCompress + ".gz")) /// { /// using (Stream compressor = new GZipStream(raw, /// CompressionMode.Compress, /// CompressionLevel.BestCompression)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n; /// while ((n= input.Read(buffer, 0, buffer.Length)) != 0) /// { /// compressor.Write(buffer, 0, n); /// } /// } /// } /// } /// </code> /// /// <code lang="VB"> /// Using input As Stream = File.OpenRead(fileToCompress) /// Using raw As FileStream = File.Create(fileToCompress &amp; ".gz") /// Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n &lt;&gt; 0) /// If (n &gt; 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// End Using /// </code> /// </example> /// <param name="stream">The stream to be read or written while deflating or inflating.</param> /// <param name="mode">Indicates whether the <c>GZipStream</c> will compress or decompress.</param> /// <param name="level">A tuning knob to trade speed for effectiveness.</param> public GZipStream(Stream stream, CompressionMode mode, CompressionLevel level) : this(stream, mode, level, false) { } /// <summary> /// Create a <c>GZipStream</c> using the specified <c>CompressionMode</c>, and /// explicitly specify whether the stream should be left open after Deflation /// or Inflation. /// </summary> /// /// <remarks> /// <para> /// This constructor allows the application to request that the captive stream /// remain open after the deflation or inflation occurs. By default, after /// <c>Close()</c> is called on the stream, the captive stream is also /// closed. In some cases this is not desired, for example if the stream is a /// memory stream that will be re-read after compressed data has been written /// to it. Specify true for the <paramref name="leaveOpen"/> parameter to leave /// the stream open. /// </para> /// /// <para> /// The <see cref="CompressionMode"/> (Compress or Decompress) also /// establishes the "direction" of the stream. A <c>GZipStream</c> with /// <c>CompressionMode.Compress</c> works only through <c>Write()</c>. A <c>GZipStream</c> /// with <c>CompressionMode.Decompress</c> works only through <c>Read()</c>. /// </para> /// /// <para> /// The <c>GZipStream</c> will use the default compression level. If you want /// to specify the compression level, see <see cref="GZipStream(Stream, /// CompressionMode, CompressionLevel, bool)"/>. /// </para> /// /// <para> /// See the other overloads of this constructor for example code. /// </para> /// /// </remarks> /// /// <param name="stream"> /// The stream which will be read or written. This is called the "captive" /// stream in other places in this documentation. /// </param> /// /// <param name="mode">Indicates whether the GZipStream will compress or decompress. /// </param> /// /// <param name="leaveOpen"> /// true if the application would like the base stream to remain open after /// inflation/deflation. /// </param> public GZipStream(Stream stream, CompressionMode mode, bool leaveOpen) : this(stream, mode, CompressionLevel.Default, leaveOpen) { } /// <summary> /// Create a <c>GZipStream</c> using the specified <c>CompressionMode</c> and the /// specified <c>CompressionLevel</c>, and explicitly specify whether the /// stream should be left open after Deflation or Inflation. /// </summary> /// /// <remarks> /// /// <para> /// This constructor allows the application to request that the captive stream /// remain open after the deflation or inflation occurs. By default, after /// <c>Close()</c> is called on the stream, the captive stream is also /// closed. In some cases this is not desired, for example if the stream is a /// memory stream that will be re-read after compressed data has been written /// to it. Specify true for the <paramref name="leaveOpen"/> parameter to /// leave the stream open. /// </para> /// /// <para> /// As noted in the class documentation, the <c>CompressionMode</c> (Compress /// or Decompress) also establishes the "direction" of the stream. A /// <c>GZipStream</c> with <c>CompressionMode.Compress</c> works only through /// <c>Write()</c>. A <c>GZipStream</c> with <c>CompressionMode.Decompress</c> works only /// through <c>Read()</c>. /// </para> /// /// </remarks> /// /// <example> /// This example shows how to use a <c>GZipStream</c> to compress data. /// <code> /// using (System.IO.Stream input = System.IO.File.OpenRead(fileToCompress)) /// { /// using (var raw = System.IO.File.Create(outputFile)) /// { /// using (Stream compressor = new GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression, true)) /// { /// byte[] buffer = new byte[WORKING_BUFFER_SIZE]; /// int n; /// while ((n= input.Read(buffer, 0, buffer.Length)) != 0) /// { /// compressor.Write(buffer, 0, n); /// } /// } /// } /// } /// </code> /// <code lang="VB"> /// Dim outputFile As String = (fileToCompress &amp; ".compressed") /// Using input As Stream = File.OpenRead(fileToCompress) /// Using raw As FileStream = File.Create(outputFile) /// Using compressor As Stream = New GZipStream(raw, CompressionMode.Compress, CompressionLevel.BestCompression, True) /// Dim buffer As Byte() = New Byte(4096) {} /// Dim n As Integer = -1 /// Do While (n &lt;&gt; 0) /// If (n &gt; 0) Then /// compressor.Write(buffer, 0, n) /// End If /// n = input.Read(buffer, 0, buffer.Length) /// Loop /// End Using /// End Using /// End Using /// </code> /// </example> /// <param name="stream">The stream which will be read or written.</param> /// <param name="mode">Indicates whether the GZipStream will compress or decompress.</param> /// <param name="leaveOpen">true if the application would like the stream to remain open after inflation/deflation.</param> /// <param name="level">A tuning knob to trade speed for effectiveness.</param> public GZipStream(Stream stream, CompressionMode mode, CompressionLevel level, bool leaveOpen) { _baseStream = new ZlibBaseStream(stream, mode, level, ZlibStreamFlavor.GZIP, leaveOpen); } #region Zlib properties /// <summary> /// This property sets the flush behavior on the stream. /// </summary> virtual public FlushType FlushMode { get { return (this._baseStream._flushMode); } set { if (_disposed) throw new ObjectDisposedException("GZipStream"); this._baseStream._flushMode = value; } } /// <summary> /// The size of the working buffer for the compression codec. /// </summary> /// /// <remarks> /// <para> /// The working buffer is used for all stream operations. The default size is /// 1024 bytes. The minimum size is 128 bytes. You may get better performance /// with a larger buffer. Then again, you might not. You would have to test /// it. /// </para> /// /// <para> /// Set this before the first call to <c>Read()</c> or <c>Write()</c> on the /// stream. If you try to set it afterwards, it will throw. /// </para> /// </remarks> public int BufferSize { get { return this._baseStream._bufferSize; } set { if (_disposed) throw new ObjectDisposedException("GZipStream"); if (this._baseStream._workingBuffer != null) throw new ZlibException("The working buffer is already set."); if (value < ZlibConstants.WorkingBufferSizeMin) throw new ZlibException(String.Format("Don't be silly. {0} bytes?? Use a bigger buffer, at least {1}.", value, ZlibConstants.WorkingBufferSizeMin)); this._baseStream._bufferSize = value; } } /// <summary> Returns the total number of bytes input so far.</summary> virtual public long TotalIn { get { return this._baseStream._z.TotalBytesIn; } } /// <summary> Returns the total number of bytes output so far.</summary> virtual public long TotalOut { get { return this._baseStream._z.TotalBytesOut; } } #endregion #region Stream methods /// <summary> /// Dispose the stream. /// </summary> /// <remarks> /// <para> /// This may or may not result in a <c>Close()</c> call on the captive /// stream. See the constructors that have a <c>leaveOpen</c> parameter /// for more information. /// </para> /// <para> /// This method may be invoked in two distinct scenarios. If disposing /// == true, the method has been called directly or indirectly by a /// user's code, for example via the public Dispose() method. In this /// case, both managed and unmanaged resources can be referenced and /// disposed. If disposing == false, the method has been called by the /// runtime from inside the object finalizer and this method should not /// reference other objects; in that case only unmanaged resources must /// be referenced or disposed. /// </para> /// </remarks> /// <param name="disposing"> /// indicates whether the Dispose method was invoked by user code. /// </param> protected override void Dispose(bool disposing) { try { if (!_disposed) { if (disposing && (this._baseStream != null)) { this._baseStream.Close(); this._Crc32 = _baseStream.Crc32; } _disposed = true; } } finally { base.Dispose(disposing); } } /// <summary> /// Indicates whether the stream can be read. /// </summary> /// <remarks> /// The return value depends on whether the captive stream supports reading. /// </remarks> public override bool CanRead { get { if (_disposed) throw new ObjectDisposedException("GZipStream"); return _baseStream._stream.CanRead; } } /// <summary> /// Indicates whether the stream supports Seek operations. /// </summary> /// <remarks> /// Always returns false. /// </remarks> public override bool CanSeek { get { return false; } } /// <summary> /// Indicates whether the stream can be written. /// </summary> /// <remarks> /// The return value depends on whether the captive stream supports writing. /// </remarks> public override bool CanWrite { get { if (_disposed) throw new ObjectDisposedException("GZipStream"); return _baseStream._stream.CanWrite; } } /// <summary> /// Flush the stream. /// </summary> public override void Flush() { if (_disposed) throw new ObjectDisposedException("GZipStream"); _baseStream.Flush(); } /// <summary> /// Reading this property always throws a <see cref="NotImplementedException"/>. /// </summary> public override long Length { get { throw new NotImplementedException(); } } /// <summary> /// The position of the stream pointer. /// </summary> /// /// <remarks> /// Setting this property always throws a <see /// cref="NotImplementedException"/>. Reading will return the total bytes /// written out, if used in writing, or the total bytes read in, if used in /// reading. The count may refer to compressed bytes or uncompressed bytes, /// depending on how you've used the stream. /// </remarks> public override long Position { get { if (this._baseStream._streamMode == Ionic.Zlib.ZlibBaseStream.StreamMode.Writer) return this._baseStream._z.TotalBytesOut + _headerByteCount; if (this._baseStream._streamMode == Ionic.Zlib.ZlibBaseStream.StreamMode.Reader) return this._baseStream._z.TotalBytesIn + this._baseStream._gzipHeaderByteCount; return 0; } set { throw new NotImplementedException(); } } /// <summary> /// Read and decompress data from the source stream. /// </summary> /// /// <remarks> /// With a <c>GZipStream</c>, decompression is done through reading. /// </remarks> /// /// <example> /// <code> /// byte[] working = new byte[WORKING_BUFFER_SIZE]; /// using (System.IO.Stream input = System.IO.File.OpenRead(_CompressedFile)) /// { /// using (Stream decompressor= new Ionic.Zlib.GZipStream(input, CompressionMode.Decompress, true)) /// { /// using (var output = System.IO.File.Create(_DecompressedFile)) /// { /// int n; /// while ((n= decompressor.Read(working, 0, working.Length)) !=0) /// { /// output.Write(working, 0, n); /// } /// } /// } /// } /// </code> /// </example> /// <param name="buffer">The buffer into which the decompressed data should be placed.</param> /// <param name="offset">the offset within that data array to put the first byte read.</param> /// <param name="count">the number of bytes to read.</param> /// <returns>the number of bytes actually read</returns> public override int Read(byte[] buffer, int offset, int count) { if (_disposed) throw new ObjectDisposedException("GZipStream"); int n = _baseStream.Read(buffer, offset, count); // Console.WriteLine("GZipStream::Read(buffer, off({0}), c({1}) = {2}", offset, count, n); // Console.WriteLine( Util.FormatByteArray(buffer, offset, n) ); if (!_firstReadDone) { _firstReadDone = true; FileName = _baseStream._GzipFileName; Comment = _baseStream._GzipComment; } return n; } /// <summary> /// Calling this method always throws a <see cref="NotImplementedException"/>. /// </summary> /// <param name="offset">irrelevant; it will always throw!</param> /// <param name="origin">irrelevant; it will always throw!</param> /// <returns>irrelevant!</returns> public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } /// <summary> /// Calling this method always throws a <see cref="NotImplementedException"/>. /// </summary> /// <param name="value">irrelevant; this method will always throw!</param> public override void SetLength(long value) { throw new NotImplementedException(); } /// <summary> /// Write data to the stream. /// </summary> /// /// <remarks> /// <para> /// If you wish to use the <c>GZipStream</c> to compress data while writing, /// you can create a <c>GZipStream</c> with <c>CompressionMode.Compress</c>, and a /// writable output stream. Then call <c>Write()</c> on that <c>GZipStream</c>, /// providing uncompressed data as input. The data sent to the output stream /// will be the compressed form of the data written. /// </para> /// /// <para> /// A <c>GZipStream</c> can be used for <c>Read()</c> or <c>Write()</c>, but not /// both. Writing implies compression. Reading implies decompression. /// </para> /// /// </remarks> /// <param name="buffer">The buffer holding data to write to the stream.</param> /// <param name="offset">the offset within that data array to find the first byte to write.</param> /// <param name="count">the number of bytes to write.</param> public override void Write(byte[] buffer, int offset, int count) { if (_disposed) throw new ObjectDisposedException("GZipStream"); if (_baseStream._streamMode == Ionic.Zlib.ZlibBaseStream.StreamMode.Undefined) { //Console.WriteLine("GZipStream: First write"); if (_baseStream._wantCompress) { // first write in compression, therefore, emit the GZIP header _headerByteCount = EmitHeader(); } else { throw new InvalidOperationException(); } } _baseStream.Write(buffer, offset, count); } #endregion internal static readonly System.DateTime _unixEpoch = new System.DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); internal static readonly System.Text.Encoding iso8859dash1 = System.Text.Encoding.GetEncoding("iso-8859-1"); private int EmitHeader() { byte[] commentBytes = (Comment == null) ? null : iso8859dash1.GetBytes(Comment); byte[] filenameBytes = (FileName == null) ? null : iso8859dash1.GetBytes(FileName); int cbLength = (Comment == null) ? 0 : commentBytes.Length + 1; int fnLength = (FileName == null) ? 0 : filenameBytes.Length + 1; int bufferLength = 10 + cbLength + fnLength; byte[] header = new byte[bufferLength]; int i = 0; // ID header[i++] = 0x1F; header[i++] = 0x8B; // compression method header[i++] = 8; byte flag = 0; if (Comment != null) flag ^= 0x10; if (FileName != null) flag ^= 0x8; // flag header[i++] = flag; // mtime if (!LastModified.HasValue) LastModified = DateTime.Now; System.TimeSpan delta = LastModified.Value - _unixEpoch; Int32 timet = (Int32)delta.TotalSeconds; Array.Copy(BitConverter.GetBytes(timet), 0, header, i, 4); i += 4; // xflg header[i++] = 0; // this field is totally useless // OS header[i++] = 0xFF; // 0xFF == unspecified // extra field length - only if FEXTRA is set, which it is not. //header[i++]= 0; //header[i++]= 0; // filename if (fnLength != 0) { Array.Copy(filenameBytes, 0, header, i, fnLength - 1); i += fnLength - 1; header[i++] = 0; // terminate } // comment if (cbLength != 0) { Array.Copy(commentBytes, 0, header, i, cbLength - 1); i += cbLength - 1; header[i++] = 0; // terminate } _baseStream._stream.Write(header, 0, header.Length); return header.Length; // bytes written } /// <summary> /// Compress a string into a byte array using GZip. /// </summary> /// /// <remarks> /// Uncompress it with <see cref="GZipStream.UncompressString(byte[])"/>. /// </remarks> /// /// <seealso cref="GZipStream.UncompressString(byte[])"/> /// <seealso cref="GZipStream.CompressBuffer(byte[])"/> /// /// <param name="s"> /// A string to compress. The string will first be encoded /// using UTF8, then compressed. /// </param> /// /// <returns>The string in compressed form</returns> public static byte[] CompressString(String s) { using (var ms = new MemoryStream()) { System.IO.Stream compressor = new GZipStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression); ZlibBaseStream.CompressString(s, compressor); return ms.ToArray(); } } /// <summary> /// Compress a byte array into a new byte array using GZip. /// </summary> /// /// <remarks> /// Uncompress it with <see cref="GZipStream.UncompressBuffer(byte[])"/>. /// </remarks> /// /// <seealso cref="GZipStream.CompressString(string)"/> /// <seealso cref="GZipStream.UncompressBuffer(byte[])"/> /// /// <param name="b"> /// A buffer to compress. /// </param> /// /// <returns>The data in compressed form</returns> public static byte[] CompressBuffer(byte[] b) { using (var ms = new MemoryStream()) { System.IO.Stream compressor = new GZipStream( ms, CompressionMode.Compress, CompressionLevel.BestCompression ); ZlibBaseStream.CompressBuffer(b, compressor); return ms.ToArray(); } } /// <summary> /// Uncompress a GZip'ed byte array into a single string. /// </summary> /// /// <seealso cref="GZipStream.CompressString(String)"/> /// <seealso cref="GZipStream.UncompressBuffer(byte[])"/> /// /// <param name="compressed"> /// A buffer containing GZIP-compressed data. /// </param> /// /// <returns>The uncompressed string</returns> public static String UncompressString(byte[] compressed) { using (var input = new MemoryStream(compressed)) { Stream decompressor = new GZipStream(input, CompressionMode.Decompress); return ZlibBaseStream.UncompressString(compressed, decompressor); } } /// <summary> /// Uncompress a GZip'ed byte array into a byte array. /// </summary> /// /// <seealso cref="GZipStream.CompressBuffer(byte[])"/> /// <seealso cref="GZipStream.UncompressString(byte[])"/> /// /// <param name="compressed"> /// A buffer containing data that has been compressed with GZip. /// </param> /// /// <returns>The data in uncompressed form</returns> public static byte[] UncompressBuffer(byte[] compressed) { using (var input = new System.IO.MemoryStream(compressed)) { System.IO.Stream decompressor = new GZipStream( input, CompressionMode.Decompress ); return ZlibBaseStream.UncompressBuffer(compressed, decompressor); } } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Collections.Generic; using System.Text; using System.Collections; using System.Windows.Forms; using Autodesk.Revit; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using Application = Autodesk.Revit.ApplicationServices.Application; namespace Revit.SDK.Samples.GridCreation.CS { /// <summary> /// Base class of all grid creation data class /// </summary> public class CreateGridsData { #region Fields /// <summary> /// The active document of Revit /// </summary> protected Autodesk.Revit.DB.Document m_revitDoc; /// <summary> /// Document Creation object to create new elements /// </summary> protected Autodesk.Revit.Creation.Document m_docCreator; /// <summary> /// Application Creation object to create new elements /// </summary> protected Autodesk.Revit.Creation.Application m_appCreator; /// <summary> /// Array list contains all grid labels in current document /// </summary> private ArrayList m_labelsList; /// <summary> /// Current display unit type /// </summary> protected DisplayUnitType m_dut; /// <summary> /// Resource manager /// </summary> protected static System.Resources.ResourceManager resManager = Properties.Resources.ResourceManager; #endregion #region Properties /// <summary> /// Current display unit type /// </summary> public DisplayUnitType Dut { get { return m_dut; } } /// <summary> /// Get array list contains all grid labels in current document /// </summary> public ArrayList LabelsList { get { return m_labelsList; } } #endregion #region Methods /// <summary> /// Constructor without display unit type /// </summary> /// <param name="application">Revit application</param> /// <param name="labels">All existing labels in Revit's document</param> public CreateGridsData(UIApplication application, ArrayList labels) { m_revitDoc = application.ActiveUIDocument.Document; m_appCreator = application.Application.Create; m_docCreator = application.ActiveUIDocument.Document.Create; m_labelsList = labels; } /// <summary> /// Constructor with display unit type /// </summary> /// <param name="application">Revit application</param> /// <param name="labels">All existing labels in Revit's document</param> /// <param name="dut">Current length display unit type</param> public CreateGridsData(UIApplication application, ArrayList labels, DisplayUnitType dut) { m_revitDoc = application.ActiveUIDocument.Document; m_appCreator = application.Application.Create; m_docCreator = application.ActiveUIDocument.Document.Create; m_labelsList = labels; m_dut = dut; } /// <summary> /// Get the line to create grid according to the specified bubble location /// </summary> /// <param name="line">The original selected line</param> /// <param name="bubLoc">bubble location</param> /// <returns>The line to create grid</returns> protected Line TransformLine(Line line, BubbleLocation bubLoc) { Line lineToCreate; // Create grid according to the bubble location if (bubLoc == BubbleLocation.StartPoint) { lineToCreate = line; } else { Autodesk.Revit.DB.XYZ startPoint = line.get_EndPoint(1); Autodesk.Revit.DB.XYZ endPoint = line.get_EndPoint(0); lineToCreate = NewLine(startPoint, endPoint); } return lineToCreate; } /// <summary> /// Get the arc to create grid according to the specified bubble location /// </summary> /// <param name="arc">The original selected line</param> /// <param name="bubLoc">bubble location</param> /// <returns>The arc to create grid</returns> protected Arc TransformArc(Arc arc, BubbleLocation bubLoc) { Arc arcToCreate; if (bubLoc == BubbleLocation.StartPoint) { arcToCreate = arc; } else { // Get start point, end point of the arc and the middle point on it Autodesk.Revit.DB.XYZ startPoint = arc.get_EndPoint(0); Autodesk.Revit.DB.XYZ endPoint = arc.get_EndPoint(1); bool clockwise = (arc.Normal.Z == -1); // Get start angel and end angel of arc double startDegree = arc.get_EndParameter(0); double endDegree = arc.get_EndParameter(1); // Handle the case that the arc is clockwise if (clockwise && startDegree > 0 && endDegree > 0) { startDegree = 2 * Values.PI - startDegree; endDegree = 2 * Values.PI - endDegree; } else if (clockwise && startDegree < 0) { double temp = endDegree; endDegree = -1 * startDegree; startDegree = -1 * temp; } double sumDegree = (startDegree + endDegree) / 2; while (sumDegree > 2 * Values.PI) { sumDegree -= 2 * Values.PI; } while (sumDegree < -2 * Values.PI) { sumDegree += 2 * Values.PI; } Autodesk.Revit.DB.XYZ midPoint = new Autodesk.Revit.DB.XYZ (arc.Center.X + arc.Radius * Math.Cos(sumDegree), arc.Center.Y + arc.Radius * Math.Sin(sumDegree), 0); arcToCreate = m_appCreator.NewArc(endPoint, startPoint, midPoint); } return arcToCreate; } /// <summary> /// Get the arc to create grid according to the specified bubble location /// </summary> /// <param name="origin">Arc grid's origin</param> /// <param name="radius">Arc grid's radius</param> /// <param name="startDegree">Arc grid's start degree</param> /// <param name="endDegree">Arc grid's end degree</param> /// <param name="bubLoc">Arc grid's Bubble location</param> /// <returns>The expected arc to create grid</returns> protected Arc TransformArc(Autodesk.Revit.DB.XYZ origin, double radius, double startDegree, double endDegree, BubbleLocation bubLoc) { Arc arcToCreate; // Get start point and end point of the arc and the middle point on the arc Autodesk.Revit.DB.XYZ startPoint = new Autodesk.Revit.DB.XYZ (origin.X + radius * Math.Cos(startDegree), origin.Y + radius * Math.Sin(startDegree), origin.Z); Autodesk.Revit.DB.XYZ midPoint = new Autodesk.Revit.DB.XYZ (origin.X + radius * Math.Cos((startDegree + endDegree) / 2), origin.Y + radius * Math.Sin((startDegree + endDegree) / 2), origin.Z); Autodesk.Revit.DB.XYZ endPoint = new Autodesk.Revit.DB.XYZ (origin.X + radius * Math.Cos(endDegree), origin.Y + radius * Math.Sin(endDegree), origin.Z); if (bubLoc == BubbleLocation.StartPoint) { arcToCreate = m_appCreator.NewArc(startPoint, endPoint, midPoint); } else { arcToCreate = m_appCreator.NewArc(endPoint, startPoint, midPoint); } return arcToCreate; } /// <summary> /// Split a circle into the upper and lower parts /// </summary> /// <param name="arc">Arc to be split</param> /// <param name="upperArc">Upper arc of the circle</param> /// <param name="lowerArc">Lower arc of the circle</param> /// <param name="bubLoc">bubble location</param> protected void TransformCircle(Arc arc, ref Arc upperArc, ref Arc lowerArc, BubbleLocation bubLoc) { Autodesk.Revit.DB.XYZ center = arc.Center; double radius = arc.Radius; Autodesk.Revit.DB.XYZ XRightPoint = new Autodesk.Revit.DB.XYZ (center.X + radius, center.Y, 0); Autodesk.Revit.DB.XYZ XLeftPoint = new Autodesk.Revit.DB.XYZ (center.X - radius, center.Y, 0); Autodesk.Revit.DB.XYZ YUpperPoint = new Autodesk.Revit.DB.XYZ (center.X, center.Y + radius, 0); Autodesk.Revit.DB.XYZ YLowerPoint = new Autodesk.Revit.DB.XYZ (center.X, center.Y - radius, 0); if (bubLoc == BubbleLocation.StartPoint) { upperArc = m_appCreator.NewArc(XRightPoint, XLeftPoint, YUpperPoint); lowerArc = m_appCreator.NewArc(XLeftPoint, XRightPoint, YLowerPoint); } else { upperArc = m_appCreator.NewArc(XLeftPoint, XRightPoint, YUpperPoint); lowerArc = m_appCreator.NewArc(XRightPoint, XLeftPoint, YLowerPoint); } } /// <summary> /// Create a new bound line /// </summary> /// <param name="start">start point of line</param> /// <param name="end">end point of line</param> /// <returns></returns> protected Line NewLine(Autodesk.Revit.DB.XYZ start, Autodesk.Revit.DB.XYZ end) { return m_appCreator.NewLineBound(start, end); } /// <summary> /// Create a grid with a line /// </summary> /// <param name="line">Line to create grid</param> /// <returns>Newly created grid</returns> protected Grid NewGrid(Line line) { return m_docCreator.NewGrid(line); } /// <summary> /// Create a grid with an arc /// </summary> /// <param name="arc">Arc to create grid</param> /// <returns>Newly created grid</returns> protected Grid NewGrid(Arc arc) { return m_docCreator.NewGrid(arc); } /// <summary> /// Create linear grid /// </summary> /// <param name="line">The linear curve to be transferred to grid</param> /// <returns>The newly created grid</returns> /// protected Grid CreateLinearGrid(Line line) { return m_docCreator.NewGrid(line); } /// <summary> /// Create batch of grids with curves /// </summary> /// <param name="curves">Curves used to create grids</param> protected void CreateGrids(CurveArray curves) { m_docCreator.NewGrids(curves); } /// <summary> /// Add curve to curve array for batch creation /// </summary> /// <param name="curves">curve array stores all curves for batch creation</param> /// <param name="curve">curve to be added</param> public static void AddCurveForBatchCreation(ref CurveArray curves, Curve curve) { curves.Append(curve); } /// <summary> /// Show a message box /// </summary> /// <param name="message">Message</param> /// <param name="caption">title of message box</param> public static void ShowMessage(String message, String caption) { MessageBox.Show(message, caption, MessageBoxButtons.OK, MessageBoxIcon.Information); } #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. /*============================================================ ** ** ** ** Purpose: The contract class allows for expressing preconditions, ** postconditions, and object invariants about methods in source ** code for runtime checking & static analysis. ** ** Two classes (Contract and ContractHelper) are split into partial classes ** in order to share the public front for multiple platforms (this file) ** while providing separate implementation details for each platform. ** ===========================================================*/ #define DEBUG // The behavior of this contract library should be consistent regardless of build type. #if SILVERLIGHT #define FEATURE_UNTRUSTED_CALLERS #elif REDHAWK_RUNTIME #elif BARTOK_RUNTIME #else // CLR #define FEATURE_UNTRUSTED_CALLERS #define FEATURE_RELIABILITY_CONTRACTS #endif using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; #if FEATURE_RELIABILITY_CONTRACTS using System.Runtime.ConstrainedExecution; #endif #if FEATURE_UNTRUSTED_CALLERS using System.Security; #endif namespace System.Diagnostics.Contracts { #region Attributes /// <summary> /// Methods and classes marked with this attribute can be used within calls to Contract methods. Such methods not make any visible state changes. /// </summary> [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event | AttributeTargets.Delegate | AttributeTargets.Class | AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] public sealed class PureAttribute : Attribute { } /// <summary> /// Types marked with this attribute specify that a separate type contains the contracts for this type. /// </summary> [Conditional("CONTRACTS_FULL")] [Conditional("DEBUG")] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] public sealed class ContractClassAttribute : Attribute { private Type _typeWithContracts; public ContractClassAttribute(Type typeContainingContracts) { _typeWithContracts = typeContainingContracts; } public Type TypeContainingContracts { get { return _typeWithContracts; } } } /// <summary> /// Types marked with this attribute specify that they are a contract for the type that is the argument of the constructor. /// </summary> [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public sealed class ContractClassForAttribute : Attribute { private Type _typeIAmAContractFor; public ContractClassForAttribute(Type typeContractsAreFor) { _typeIAmAContractFor = typeContractsAreFor; } public Type TypeContractsAreFor { get { return _typeIAmAContractFor; } } } /// <summary> /// This attribute is used to mark a method as being the invariant /// method for a class. The method can have any name, but it must /// return "void" and take no parameters. The body of the method /// must consist solely of one or more calls to the method /// Contract.Invariant. A suggested name for the method is /// "ObjectInvariant". /// </summary> [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public sealed class ContractInvariantMethodAttribute : Attribute { } /// <summary> /// Attribute that specifies that an assembly is a reference assembly with contracts. /// </summary> [AttributeUsage(AttributeTargets.Assembly)] public sealed class ContractReferenceAssemblyAttribute : Attribute { } /// <summary> /// Methods (and properties) marked with this attribute can be used within calls to Contract methods, but have no runtime behavior associated with them. /// </summary> [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class ContractRuntimeIgnoredAttribute : Attribute { } /* [Serializable] internal enum Mutability { Immutable, // read-only after construction, except for lazy initialization & caches // Do we need a "deeply immutable" value? Mutable, HasInitializationPhase, // read-only after some point. // Do we need a value for mutable types with read-only wrapper subclasses? } // Note: This hasn't been thought through in any depth yet. Consider it experimental. // We should replace this with Joe's concepts. [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)] [SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments", Justification = "Thank you very much, but we like the names we've defined for the accessors")] internal sealed class MutabilityAttribute : Attribute { private Mutability _mutabilityMarker; public MutabilityAttribute(Mutability mutabilityMarker) { _mutabilityMarker = mutabilityMarker; } public Mutability Mutability { get { return _mutabilityMarker; } } } */ /// <summary> /// Instructs downstream tools whether to assume the correctness of this assembly, type or member without performing any verification or not. /// Can use [ContractVerification(false)] to explicitly mark assembly, type or member as one to *not* have verification performed on it. /// Most specific element found (member, type, then assembly) takes precedence. /// (That is useful if downstream tools allow a user to decide which polarity is the default, unmarked case.) /// </summary> /// <remarks> /// Apply this attribute to a type to apply to all members of the type, including nested types. /// Apply this attribute to an assembly to apply to all types and members of the assembly. /// Apply this attribute to a property to apply to both the getter and setter. /// </remarks> [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Property)] public sealed class ContractVerificationAttribute : Attribute { private bool _value; public ContractVerificationAttribute(bool value) { _value = value; } public bool Value { get { return _value; } } } /// <summary> /// Allows a field f to be used in the method contracts for a method m when f has less visibility than m. /// For instance, if the method is public, but the field is private. /// </summary> [Conditional("CONTRACTS_FULL")] [AttributeUsage(AttributeTargets.Field)] [SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments", Justification = "Thank you very much, but we like the names we've defined for the accessors")] public sealed class ContractPublicPropertyNameAttribute : Attribute { private String _publicName; public ContractPublicPropertyNameAttribute(String name) { _publicName = name; } public String Name { get { return _publicName; } } } /// <summary> /// Enables factoring legacy if-then-throw into separate methods for reuse and full control over /// thrown exception and arguments /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] [Conditional("CONTRACTS_FULL")] public sealed class ContractArgumentValidatorAttribute : Attribute { } /// <summary> /// Enables writing abbreviations for contracts that get copied to other methods /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] [Conditional("CONTRACTS_FULL")] public sealed class ContractAbbreviatorAttribute : Attribute { } /// <summary> /// Allows setting contract and tool options at assembly, type, or method granularity. /// </summary> [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] [Conditional("CONTRACTS_FULL")] public sealed class ContractOptionAttribute : Attribute { private String _category; private String _setting; private bool _enabled; private String _value; public ContractOptionAttribute(String category, String setting, bool enabled) { _category = category; _setting = setting; _enabled = enabled; } public ContractOptionAttribute(String category, String setting, String value) { _category = category; _setting = setting; _value = value; } public String Category { get { return _category; } } public String Setting { get { return _setting; } } public bool Enabled { get { return _enabled; } } public String Value { get { return _value; } } } #endregion Attributes /// <summary> /// Contains static methods for representing program contracts such as preconditions, postconditions, and invariants. /// </summary> /// <remarks> /// WARNING: A binary rewriter must be used to insert runtime enforcement of these contracts. /// Otherwise some contracts like Ensures can only be checked statically and will not throw exceptions during runtime when contracts are violated. /// Please note this class uses conditional compilation to help avoid easy mistakes. Defining the preprocessor /// symbol CONTRACTS_PRECONDITIONS will include all preconditions expressed using Contract.Requires in your /// build. The symbol CONTRACTS_FULL will include postconditions and object invariants, and requires the binary rewriter. /// </remarks> public static partial class Contract { #region User Methods #region Assume /// <summary> /// Instructs code analysis tools to assume the expression <paramref name="condition"/> is true even if it can not be statically proven to always be true. /// </summary> /// <param name="condition">Expression to assume will always be true.</param> /// <remarks> /// At runtime this is equivalent to an <seealso cref="System.Diagnostics.Contracts.Debug.Assert(bool)"/>. /// </remarks> [Pure] [Conditional("DEBUG")] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS #endif public static void Assume(bool condition) { if (!condition) { ReportFailure(ContractFailureKind.Assume, null, null, null); } } /// <summary> /// Instructs code analysis tools to assume the expression <paramref name="condition"/> is true even if it can not be statically proven to always be true. /// </summary> /// <param name="condition">Expression to assume will always be true.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> /// <remarks> /// At runtime this is equivalent to an <seealso cref="System.Diagnostics.Contracts.Debug.Assert(bool)"/>. /// </remarks> [Pure] [Conditional("DEBUG")] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS #endif public static void Assume(bool condition, String userMessage) { if (!condition) { ReportFailure(ContractFailureKind.Assume, userMessage, null, null); } } #endregion Assume #region Assert /// <summary> /// In debug builds, perform a runtime check that <paramref name="condition"/> is true. /// </summary> /// <param name="condition">Expression to check to always be true.</param> [Pure] [Conditional("DEBUG")] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS #endif public static void Assert(bool condition) { if (!condition) ReportFailure(ContractFailureKind.Assert, null, null, null); } /// <summary> /// In debug builds, perform a runtime check that <paramref name="condition"/> is true. /// </summary> /// <param name="condition">Expression to check to always be true.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> [Pure] [Conditional("DEBUG")] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS #endif public static void Assert(bool condition, String userMessage) { if (!condition) ReportFailure(ContractFailureKind.Assert, userMessage, null, null); } #endregion Assert #region Requires /// <summary> /// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked. /// </summary> /// <param name="condition">Boolean expression representing the contract.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// Use this form when backward compatibility does not force you to throw a particular exception. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS #endif public static void Requires(bool condition) { AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires"); } /// <summary> /// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked. /// </summary> /// <param name="condition">Boolean expression representing the contract.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// Use this form when backward compatibility does not force you to throw a particular exception. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS #endif public static void Requires(bool condition, String userMessage) { AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires"); } /// <summary> /// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked. /// </summary> /// <param name="condition">Boolean expression representing the contract.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// Use this form when you want to throw a particular exception. /// </remarks> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "condition")] [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")] [Pure] #if FEATURE_RELIABILITY_CONTRACTS #endif public static void Requires<TException>(bool condition) where TException : Exception { AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires<TException>"); } /// <summary> /// Specifies a contract such that the expression <paramref name="condition"/> must be true before the enclosing method or property is invoked. /// </summary> /// <param name="condition">Boolean expression representing the contract.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// Use this form when you want to throw a particular exception. /// </remarks> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "userMessage")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "condition")] [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")] [Pure] #if FEATURE_RELIABILITY_CONTRACTS #endif public static void Requires<TException>(bool condition, String userMessage) where TException : Exception { AssertMustUseRewriter(ContractFailureKind.Precondition, "Requires<TException>"); } #endregion Requires #region Ensures /// <summary> /// Specifies a public contract such that the expression <paramref name="condition"/> will be true when the enclosing method or property returns normally. /// </summary> /// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this postcondition. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS #endif public static void Ensures(bool condition) { AssertMustUseRewriter(ContractFailureKind.Postcondition, "Ensures"); } /// <summary> /// Specifies a public contract such that the expression <paramref name="condition"/> will be true when the enclosing method or property returns normally. /// </summary> /// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference members at least as visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this postcondition. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS #endif public static void Ensures(bool condition, String userMessage) { AssertMustUseRewriter(ContractFailureKind.Postcondition, "Ensures"); } /// <summary> /// Specifies a contract such that if an exception of type <typeparamref name="TException"/> is thrown then the expression <paramref name="condition"/> will be true when the enclosing method or property terminates abnormally. /// </summary> /// <typeparam name="TException">Type of exception related to this postcondition.</typeparam> /// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference types and members at least as visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this postcondition. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Exception type used in tools.")] #if FEATURE_RELIABILITY_CONTRACTS #endif public static void EnsuresOnThrow<TException>(bool condition) where TException : Exception { AssertMustUseRewriter(ContractFailureKind.PostconditionOnException, "EnsuresOnThrow"); } /// <summary> /// Specifies a contract such that if an exception of type <typeparamref name="TException"/> is thrown then the expression <paramref name="condition"/> will be true when the enclosing method or property terminates abnormally. /// </summary> /// <typeparam name="TException">Type of exception related to this postcondition.</typeparam> /// <param name="condition">Boolean expression representing the contract. May include <seealso cref="OldValue"/> and <seealso cref="Result"/>.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> /// <remarks> /// This call must happen at the beginning of a method or property before any other code. /// This contract is exposed to clients so must only reference types and members at least as visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this postcondition. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Exception type used in tools.")] #if FEATURE_RELIABILITY_CONTRACTS #endif public static void EnsuresOnThrow<TException>(bool condition, String userMessage) where TException : Exception { AssertMustUseRewriter(ContractFailureKind.PostconditionOnException, "EnsuresOnThrow"); } #region Old, Result, and Out Parameters /// <summary> /// Represents the result (a.k.a. return value) of a method or property. /// </summary> /// <typeparam name="T">Type of return value of the enclosing method or property.</typeparam> /// <returns>Return value of the enclosing method or property.</returns> /// <remarks> /// This method can only be used within the argument to the <seealso cref="Ensures(bool)"/> contract. /// </remarks> [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Not intended to be called at runtime.")] [Pure] #if FEATURE_RELIABILITY_CONTRACTS #endif public static T Result<T>() { return default(T); } /// <summary> /// Represents the final (output) value of an out parameter when returning from a method. /// </summary> /// <typeparam name="T">Type of the out parameter.</typeparam> /// <param name="value">The out parameter.</param> /// <returns>The output value of the out parameter.</returns> /// <remarks> /// This method can only be used within the argument to the <seealso cref="Ensures(bool)"/> contract. /// </remarks> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#", Justification = "Not intended to be called at runtime.")] [Pure] #if FEATURE_RELIABILITY_CONTRACTS #endif public static T ValueAtReturn<T>(out T value) { value = default(T); return value; } /// <summary> /// Represents the value of <paramref name="value"/> as it was at the start of the method or property. /// </summary> /// <typeparam name="T">Type of <paramref name="value"/>. This can be inferred.</typeparam> /// <param name="value">Value to represent. This must be a field or parameter.</param> /// <returns>Value of <paramref name="value"/> at the start of the method or property.</returns> /// <remarks> /// This method can only be used within the argument to the <seealso cref="Ensures(bool)"/> contract. /// </remarks> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "value")] [Pure] #if FEATURE_RELIABILITY_CONTRACTS #endif public static T OldValue<T>(T value) { return default(T); } #endregion Old, Result, and Out Parameters #endregion Ensures #region Invariant /// <summary> /// Specifies a contract such that the expression <paramref name="condition"/> will be true after every method or property on the enclosing class. /// </summary> /// <param name="condition">Boolean expression representing the contract.</param> /// <remarks> /// This contact can only be specified in a dedicated invariant method declared on a class. /// This contract is not exposed to clients so may reference members less visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this invariant. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS #endif public static void Invariant(bool condition) { AssertMustUseRewriter(ContractFailureKind.Invariant, "Invariant"); } /// <summary> /// Specifies a contract such that the expression <paramref name="condition"/> will be true after every method or property on the enclosing class. /// </summary> /// <param name="condition">Boolean expression representing the contract.</param> /// <param name="userMessage">If it is not a constant string literal, then the contract may not be understood by tools.</param> /// <remarks> /// This contact can only be specified in a dedicated invariant method declared on a class. /// This contract is not exposed to clients so may reference members less visible as the enclosing method. /// The contract rewriter must be used for runtime enforcement of this invariant. /// </remarks> [Pure] [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS #endif public static void Invariant(bool condition, String userMessage) { AssertMustUseRewriter(ContractFailureKind.Invariant, "Invariant"); } #endregion Invariant #region Quantifiers #region ForAll /// <summary> /// Returns whether the <paramref name="predicate"/> returns <c>true</c> /// for all integers starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1. /// </summary> /// <param name="fromInclusive">First integer to pass to <paramref name="predicate"/>.</param> /// <param name="toExclusive">One greater than the last integer to pass to <paramref name="predicate"/>.</param> /// <param name="predicate">Function that is evaluated from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</param> /// <returns><c>true</c> if <paramref name="predicate"/> returns <c>true</c> for all integers /// starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</returns> /// <seealso cref="System.Collections.Generic.List&lt;T&gt;.TrueForAll"/> [Pure] #if FEATURE_RELIABILITY_CONTRACTS #endif public static bool ForAll(int fromInclusive, int toExclusive, Predicate<int> predicate) { if (fromInclusive > toExclusive) #if CORECLR throw new ArgumentException(SR.Argument_ToExclusiveLessThanFromExclusive); #else throw new ArgumentException("fromInclusive must be less than or equal to toExclusive."); #endif if (predicate == null) throw new ArgumentNullException(nameof(predicate)); Contract.EndContractBlock(); for (int i = fromInclusive; i < toExclusive; i++) if (!predicate(i)) return false; return true; } /// <summary> /// Returns whether the <paramref name="predicate"/> returns <c>true</c> /// for all elements in the <paramref name="collection"/>. /// </summary> /// <param name="collection">The collection from which elements will be drawn from to pass to <paramref name="predicate"/>.</param> /// <param name="predicate">Function that is evaluated on elements from <paramref name="collection"/>.</param> /// <returns><c>true</c> if and only if <paramref name="predicate"/> returns <c>true</c> for all elements in /// <paramref name="collection"/>.</returns> /// <seealso cref="System.Collections.Generic.List&lt;T&gt;.TrueForAll"/> [Pure] #if FEATURE_RELIABILITY_CONTRACTS #endif public static bool ForAll<T>(IEnumerable<T> collection, Predicate<T> predicate) { if (collection == null) throw new ArgumentNullException(nameof(collection)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); Contract.EndContractBlock(); foreach (T t in collection) if (!predicate(t)) return false; return true; } #endregion ForAll #region Exists /// <summary> /// Returns whether the <paramref name="predicate"/> returns <c>true</c> /// for any integer starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1. /// </summary> /// <param name="fromInclusive">First integer to pass to <paramref name="predicate"/>.</param> /// <param name="toExclusive">One greater than the last integer to pass to <paramref name="predicate"/>.</param> /// <param name="predicate">Function that is evaluated from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</param> /// <returns><c>true</c> if <paramref name="predicate"/> returns <c>true</c> for any integer /// starting from <paramref name="fromInclusive"/> to <paramref name="toExclusive"/> - 1.</returns> /// <seealso cref="System.Collections.Generic.List&lt;T&gt;.Exists"/> [Pure] #if FEATURE_RELIABILITY_CONTRACTS #endif public static bool Exists(int fromInclusive, int toExclusive, Predicate<int> predicate) { if (fromInclusive > toExclusive) #if CORECLR throw new ArgumentException(SR.Argument_ToExclusiveLessThanFromExclusive); #else throw new ArgumentException("fromInclusive must be less than or equal to toExclusive."); #endif if (predicate == null) throw new ArgumentNullException(nameof(predicate)); Contract.EndContractBlock(); for (int i = fromInclusive; i < toExclusive; i++) if (predicate(i)) return true; return false; } /// <summary> /// Returns whether the <paramref name="predicate"/> returns <c>true</c> /// for any element in the <paramref name="collection"/>. /// </summary> /// <param name="collection">The collection from which elements will be drawn from to pass to <paramref name="predicate"/>.</param> /// <param name="predicate">Function that is evaluated on elements from <paramref name="collection"/>.</param> /// <returns><c>true</c> if and only if <paramref name="predicate"/> returns <c>true</c> for an element in /// <paramref name="collection"/>.</returns> /// <seealso cref="System.Collections.Generic.List&lt;T&gt;.Exists"/> [Pure] #if FEATURE_RELIABILITY_CONTRACTS #endif public static bool Exists<T>(IEnumerable<T> collection, Predicate<T> predicate) { if (collection == null) throw new ArgumentNullException(nameof(collection)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); Contract.EndContractBlock(); foreach (T t in collection) if (predicate(t)) return true; return false; } #endregion Exists #endregion Quantifiers #region Pointers #endregion #region Misc. /// <summary> /// Marker to indicate the end of the contract section of a method. /// </summary> [Conditional("CONTRACTS_FULL")] #if FEATURE_RELIABILITY_CONTRACTS #endif public static void EndContractBlock() { } #endregion #endregion User Methods #region Failure Behavior /// <summary> /// Without contract rewriting, failing Assert/Assumes end up calling this method. /// Code going through the contract rewriter never calls this method. Instead, the rewriter produced failures call /// System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent, followed by /// System.Runtime.CompilerServices.ContractHelper.TriggerFailure. /// </summary> static partial void ReportFailure(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException); /// <summary> /// This method is used internally to trigger a failure indicating to the "programmer" that he is using the interface incorrectly. /// It is NEVER used to indicate failure of actual contracts at runtime. /// </summary> static partial void AssertMustUseRewriter(ContractFailureKind kind, String contractKind); #endregion } public enum ContractFailureKind { Precondition, [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Postcondition")] Postcondition, [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Postcondition")] PostconditionOnException, Invariant, Assert, Assume, } } // Note: In .NET FX 4.5, we duplicated the ContractHelper class in the System.Runtime.CompilerServices // namespace to remove an ugly wart of a namespace from the Windows 8 profile. But we still need the // old locations left around, so we can support rewritten .NET FX 4.0 libraries. Consider removing // these from our reference assembly in a future version. namespace System.Diagnostics.Contracts.Internal { [Obsolete("Use the ContractHelper class in the System.Runtime.CompilerServices namespace instead.")] public static class ContractHelper { #region Rewriter Failure Hooks /// <summary> /// Rewriter will call this method on a contract failure to allow listeners to be notified. /// The method should not perform any failure (assert/throw) itself. /// </summary> /// <returns>null if the event was handled and should not trigger a failure. /// Otherwise, returns the localized failure message</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS #endif public static string RaiseContractFailedEvent(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException) { return System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException); } /// <summary> /// Rewriter calls this method to get the default failure behavior. /// </summary> [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS #endif public static void TriggerFailure(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException) { System.Runtime.CompilerServices.ContractHelper.TriggerFailure(kind, displayMessage, userMessage, conditionText, innerException); } #endregion Rewriter Failure Hooks } } // namespace System.Diagnostics.Contracts.Internal namespace System.Runtime.CompilerServices { public static partial class ContractHelper { #region Rewriter Failure Hooks /// <summary> /// Rewriter will call this method on a contract failure to allow listeners to be notified. /// The method should not perform any failure (assert/throw) itself. /// </summary> /// <returns>null if the event was handled and should not trigger a failure. /// Otherwise, returns the localized failure message</returns> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS #endif public static string RaiseContractFailedEvent(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException) { var resultFailureMessage = "Contract failed"; // default in case implementation does not assign anything. RaiseContractFailedEventImplementation(failureKind, userMessage, conditionText, innerException, ref resultFailureMessage); return resultFailureMessage; } /// <summary> /// Rewriter calls this method to get the default failure behavior. /// </summary> [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS #endif public static void TriggerFailure(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException) { TriggerFailureImplementation(kind, displayMessage, userMessage, conditionText, innerException); } #endregion Rewriter Failure Hooks #region Implementation Stubs /// <summary> /// Rewriter will call this method on a contract failure to allow listeners to be notified. /// The method should not perform any failure (assert/throw) itself. /// This method has 3 functions: /// 1. Call any contract hooks (such as listeners to Contract failed events) /// 2. Determine if the listeneres deem the failure as handled (then resultFailureMessage should be set to null) /// 3. Produce a localized resultFailureMessage used in advertising the failure subsequently. /// </summary> /// <param name="resultFailureMessage">Should really be out (or the return value), but partial methods are not flexible enough. /// On exit: null if the event was handled and should not trigger a failure. /// Otherwise, returns the localized failure message</param> static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException, ref string resultFailureMessage); /// <summary> /// Implements the default failure behavior of the platform. Under the BCL, it triggers an Assert box. /// </summary> static partial void TriggerFailureImplementation(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException); #endregion Implementation Stubs } } // namespace System.Runtime.CompilerServices
// ReSharper disable once CheckNamespace namespace Fluent { using System; using System.Collections; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using Fluent.Extensions; using Fluent.Internal; using Fluent.Internal.KnownBoxes; /// <summary> /// Represents ribbon tab item /// </summary> [TemplatePart(Name = "PART_ContentContainer", Type = typeof(Border))] [ContentProperty(nameof(Groups))] [DefaultProperty(nameof(Groups))] public class RibbonTabItem : Control, IKeyTipedControl, IHeaderedControl { #region Fields // Content container private Border contentContainer; // Desired width private double desiredWidth; // Collection of ribbon groups private ObservableCollection<RibbonGroupBox> groups; // Ribbon groups container private readonly RibbonGroupsContainer groupsInnerContainer = new RibbonGroupsContainer(); // Cached width private double cachedWidth; #endregion #region Properties #region Colors/Brushes /// <summary> /// Gets or sets the <see cref="Brush"/> which is used to render the background if this <see cref="RibbonTabItem"/> is the currently active/selected one. /// </summary> public Brush ActiveTabBackground { get { return (Brush)this.GetValue(ActiveTabBackgroundProperty); } set { this.SetValue(ActiveTabBackgroundProperty, value); } } /// <summary> /// <see cref="DependencyProperty"/> for <see cref="ActiveTabBackground"/>. /// </summary> public static readonly DependencyProperty ActiveTabBackgroundProperty = DependencyProperty.Register(nameof(ActiveTabBackground), typeof(Brush), typeof(RibbonTabItem), new PropertyMetadata()); /// <summary> /// Gets or sets the <see cref="Brush"/> which is used to render the border if this <see cref="RibbonTabItem"/> is the currently active/selected one. /// </summary> public Brush ActiveTabBorderBrush { get { return (Brush)this.GetValue(ActiveTabBorderBrushProperty); } set { this.SetValue(ActiveTabBorderBrushProperty, value); } } /// <summary> /// <see cref="DependencyProperty"/> for <see cref="ActiveTabBorderBrush"/>. /// </summary> public static readonly DependencyProperty ActiveTabBorderBrushProperty = DependencyProperty.Register(nameof(ActiveTabBorderBrush), typeof(Brush), typeof(RibbonTabItem), new PropertyMetadata()); #endregion #region KeyTip /// <summary> /// Gets or sets KeyTip for element. /// </summary> public string KeyTip { get { return (string)this.GetValue(KeyTipProperty); } set { this.SetValue(KeyTipProperty, value); } } /// <summary> /// Using a DependencyProperty as the backing store for Keys. /// This enables animation, styling, binding, etc... /// </summary> public static readonly DependencyProperty KeyTipProperty = Fluent.KeyTip.KeysProperty.AddOwner(typeof(RibbonTabItem)); #endregion public static readonly DependencyProperty HeaderTooltipProperty = DependencyProperty.Register( "HeaderTooltip", typeof(string), typeof(RibbonTabItem), new PropertyMetadata(default(string))); public string HeaderTooltip { get { return (string) GetValue(HeaderTooltipProperty); } set { SetValue(HeaderTooltipProperty, value); } } /// <summary> /// Gets ribbon groups container /// </summary> public ScrollViewer GroupsContainer { get; } = new ScrollViewer(); /// <summary> /// Gets or sets whether ribbon is minimized /// </summary> public bool IsMinimized { get { return (bool)this.GetValue(IsMinimizedProperty); } set { this.SetValue(IsMinimizedProperty, value); } } /// <summary> /// Using a DependencyProperty as the backing store for IsMinimized. /// This enables animation, styling, binding, etc... /// </summary> public static readonly DependencyProperty IsMinimizedProperty = DependencyProperty.Register(nameof(IsMinimized), typeof(bool), typeof(RibbonTabItem), new PropertyMetadata(BooleanBoxes.FalseBox)); /// <summary> /// Gets or sets whether ribbon is opened /// </summary> public bool IsOpen { get { return (bool)this.GetValue(IsOpenProperty); } set { this.SetValue(IsOpenProperty, value); } } /// <summary> /// Using a DependencyProperty as the backing store for IsOpen. /// This enables animation, styling, binding, etc... /// </summary> public static readonly DependencyProperty IsOpenProperty = DependencyProperty.Register(nameof(IsOpen), typeof(bool), typeof(RibbonTabItem), new PropertyMetadata(BooleanBoxes.FalseBox)); /// <summary> /// Gets or sets reduce order /// </summary> public string ReduceOrder { get { return this.groupsInnerContainer.ReduceOrder; } set { this.groupsInnerContainer.ReduceOrder = value; } } #region IsContextual /// <summary> /// Gets or sets whether tab item is contextual /// </summary> public bool IsContextual { get { return (bool)this.GetValue(IsContextualProperty); } private set { this.SetValue(IsContextualPropertyKey, value); } } private static readonly DependencyPropertyKey IsContextualPropertyKey = DependencyProperty.RegisterReadOnly(nameof(IsContextual), typeof(bool), typeof(RibbonTabItem), new PropertyMetadata(BooleanBoxes.FalseBox)); /// <summary> /// Using a DependencyProperty as the backing store for IsContextual. /// This enables animation, styling, binding, etc... /// </summary> public static readonly DependencyProperty IsContextualProperty = IsContextualPropertyKey.DependencyProperty; /// <summary> /// Gets an enumerator for logical child elements of this element. /// </summary> protected override IEnumerator LogicalChildren { get { yield return this.GroupsContainer; } } #endregion /// <summary> /// Gets or sets whether tab item is selected /// </summary> [Bindable(true)] [Category("Appearance")] public bool IsSelected { get { return (bool)this.GetValue(IsSelectedProperty); } set { this.SetValue(IsSelectedProperty, value); } } /// <summary> /// Using a DependencyProperty as the backing store for IsSelected. /// This enables animation, styling, binding, etc... /// </summary> public static readonly DependencyProperty IsSelectedProperty = Selector.IsSelectedProperty.AddOwner(typeof(RibbonTabItem), new FrameworkPropertyMetadata(BooleanBoxes.FalseBox, FrameworkPropertyMetadataOptions.Journal | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault | FrameworkPropertyMetadataOptions.AffectsParentMeasure, OnIsSelectedChanged)); /// <summary> /// Gets ribbon tab control parent /// </summary> internal RibbonTabControl TabControlParent { get { return ItemsControl.ItemsControlFromItemContainer(this) as RibbonTabControl; } } /// <summary> /// Gets or sets indent /// </summary> public double Indent { get { return (double)this.GetValue(IndentProperty); } set { this.SetValue(IndentProperty, value); } } /// <summary> /// Using a DependencyProperty as the backing store for HeaderMargin. This enables animation, styling, binding, etc... /// </summary> public static readonly DependencyProperty IndentProperty = DependencyProperty.Register(nameof(Indent), typeof(double), typeof(RibbonTabItem), new PropertyMetadata(12.0)); /// <summary> /// Gets or sets whether separator is visible /// </summary> public bool IsSeparatorVisible { get { return (bool)this.GetValue(IsSeparatorVisibleProperty); } set { this.SetValue(IsSeparatorVisibleProperty, value); } } /// <summary> /// Using a DependencyProperty as the backing store for IsSeparatorVisible. This enables animation, styling, binding, etc... /// </summary> public static readonly DependencyProperty IsSeparatorVisibleProperty = DependencyProperty.Register(nameof(IsSeparatorVisible), typeof(bool), typeof(RibbonTabItem), new PropertyMetadata(BooleanBoxes.FalseBox)); /// <summary> /// Gets or sets ribbon contextual tab group /// </summary> public RibbonContextualTabGroup Group { get { return (RibbonContextualTabGroup)this.GetValue(GroupProperty); } set { this.SetValue(GroupProperty, value); } } /// <summary> /// Using a DependencyProperty as the backing store for Group. This enables animation, styling, binding, etc... /// </summary> public static readonly DependencyProperty GroupProperty = DependencyProperty.Register(nameof(Group), typeof(RibbonContextualTabGroup), typeof(RibbonTabItem), new PropertyMetadata(OnGroupChanged)); // handles Group property chanhged private static void OnGroupChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var tab = (RibbonTabItem)d; ((RibbonContextualTabGroup)e.OldValue)?.RemoveTabItem(tab); if (e.NewValue != null) { var tabGroup = (RibbonContextualTabGroup)e.NewValue; tabGroup.AppendTabItem(tab); tab.IsContextual = true; } else { tab.IsContextual = false; } } /// <summary> /// Gets or sets desired width of the tab item. /// </summary> /// <remarks>This is needed in case the width of <see cref="Group"/> is larger than it's tabs.</remarks> internal double DesiredWidth { get { return this.desiredWidth; } set { this.desiredWidth = value; this.InvalidateMeasure(); } } /// <summary> /// Gets or sets whether tab item has left group border /// </summary> public bool HasLeftGroupBorder { get { return (bool)this.GetValue(HasLeftGroupBorderProperty); } set { this.SetValue(HasLeftGroupBorderProperty, value); } } /// <summary> /// Using a DependencyProperty as the backing store for HaseLeftGroupBorder. This enables animation, styling, binding, etc... /// </summary> public static readonly DependencyProperty HasLeftGroupBorderProperty = DependencyProperty.Register(nameof(HasLeftGroupBorder), typeof(bool), typeof(RibbonTabItem), new PropertyMetadata(BooleanBoxes.FalseBox)); /// <summary> /// Gets or sets whether tab item has right group border /// </summary> public bool HasRightGroupBorder { get { return (bool)this.GetValue(HasRightGroupBorderProperty); } set { this.SetValue(HasRightGroupBorderProperty, value); } } /// <summary> /// Using a DependencyProperty as the backing store for HaseLeftGroupBorder. This enables animation, styling, binding, etc... /// </summary> public static readonly DependencyProperty HasRightGroupBorderProperty = DependencyProperty.Register(nameof(HasRightGroupBorder), typeof(bool), typeof(RibbonTabItem), new PropertyMetadata(BooleanBoxes.FalseBox)); /// <summary> /// get collection of ribbon groups /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public ObservableCollection<RibbonGroupBox> Groups { get { if (this.groups == null) { this.groups = new ObservableCollection<RibbonGroupBox>(); this.groups.CollectionChanged += this.OnGroupsCollectionChanged; } return this.groups; } } // handles ribbon groups collection changes private void OnGroupsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (this.groupsInnerContainer == null) { return; } switch (e.Action) { case NotifyCollectionChangedAction.Add: for (var i = 0; i < e.NewItems.Count; i++) { this.groupsInnerContainer.Children.Insert(e.NewStartingIndex + i, (UIElement)e.NewItems[i]); } break; case NotifyCollectionChangedAction.Remove: foreach (var item in e.OldItems.OfType<UIElement>()) { this.groupsInnerContainer.Children.Remove(item); } break; case NotifyCollectionChangedAction.Replace: foreach (var item in e.OldItems.OfType<UIElement>()) { this.groupsInnerContainer.Children.Remove(item); } foreach (var item in e.NewItems.OfType<UIElement>()) { this.groupsInnerContainer.Children.Add(item); } break; case NotifyCollectionChangedAction.Reset: this.groupsInnerContainer.Children.Clear(); foreach (var group in this.groups) { this.groupsInnerContainer.Children.Add(group); } break; } } #region Header Property /// <summary> /// Gets or sets header of tab item /// </summary> public object Header { get { return this.GetValue(HeaderProperty); } set { this.SetValue(HeaderProperty, value); } } /// <summary> /// DependencyProperty for <see cref="Header"/>. /// </summary> public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register(nameof(Header), typeof(object), typeof(RibbonTabItem), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsMeasure, OnHeaderChanged)); // Header changed handler private static void OnHeaderChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { } #endregion #region HeaderTemplate Property /// <summary> /// Gets or sets header template of tab item. /// </summary> public DataTemplate HeaderTemplate { get { return (DataTemplate)this.GetValue(HeaderTemplateProperty); } set { this.SetValue(HeaderTemplateProperty, value); } } /// <summary> /// DependencyProperty for <see cref="HeaderTemplate"/>. /// </summary> public static readonly DependencyProperty HeaderTemplateProperty = DependencyProperty.Register(nameof(HeaderTemplate), typeof(DataTemplate), typeof(RibbonTabItem), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsMeasure)); #endregion #region Focusable /// <summary> /// Handles Focusable changes /// </summary> private static void OnFocusableChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { } /// <summary> /// Coerces Focusable /// </summary> private static object CoerceFocusable(DependencyObject d, object basevalue) { var control = d as RibbonTabItem; var ribbon = control?.FindParentRibbon(); if (ribbon != null) { return (bool)basevalue && ribbon.Focusable; } return basevalue; } // Find parent ribbon private Ribbon FindParentRibbon() { var element = this.Parent; while (element != null) { var ribbon = element as Ribbon; if (ribbon != null) { return ribbon; } element = VisualTreeHelper.GetParent(element); } return null; } #endregion #endregion #region Initialize /// <summary> /// Static constructor /// </summary> static RibbonTabItem() { DefaultStyleKeyProperty.OverrideMetadata(typeof(RibbonTabItem), new FrameworkPropertyMetadata(typeof(RibbonTabItem))); FocusableProperty.AddOwner(typeof(RibbonTabItem), new FrameworkPropertyMetadata(OnFocusableChanged, CoerceFocusable)); VisibilityProperty.AddOwner(typeof(RibbonTabItem), new FrameworkPropertyMetadata(OnVisibilityChanged)); System.Windows.Controls.ToolTipService.InitialShowDelayProperty.OverrideMetadata(typeof(RibbonTabItem), new FrameworkPropertyMetadata(2000)); KeyboardNavigation.DirectionalNavigationProperty.OverrideMetadata(typeof(RibbonTabItem), new FrameworkPropertyMetadata(KeyboardNavigationMode.Contained)); KeyboardNavigation.TabNavigationProperty.OverrideMetadata(typeof(RibbonTabItem), new FrameworkPropertyMetadata(KeyboardNavigationMode.Local)); } // Handles visibility changes private static void OnVisibilityChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var item = d as RibbonTabItem; if (item == null) { return; } item.Group?.UpdateInnerVisiblityAndGroupBorders(); if (item.IsSelected && (Visibility)e.NewValue == Visibility.Collapsed) { if (item.TabControlParent != null) { if (item.TabControlParent.IsMinimized) { item.IsSelected = false; } else { item.TabControlParent.SelectedItem = item.TabControlParent.GetFirstVisibleAndEnabledItem(); } } } } /// <summary> /// Default constructor /// </summary> public RibbonTabItem() { this.AddLogicalChild(this.GroupsContainer); this.GroupsContainer.Content = this.groupsInnerContainer; // Force redirection of DataContext. This is needed, because we detach the container from the visual tree and attach it to a diffrent one (the popup/dropdown) when the ribbon is minimized. this.groupsInnerContainer.SetBinding(DataContextProperty, new Binding(nameof(this.DataContext)) { Source = this }); ContextMenuService.Coerce(this); this.Loaded += this.OnLoaded; this.Unloaded += this.OnUnloaded; } #endregion #region Overrides internal bool SetFocus() { if (this.SettingFocus) { return false; } var currentFocus = Keyboard.FocusedElement as RibbonTabItem; // If current focus was another TabItem in the same TabControl - dont set focus on content bool setFocusOnContent = ReferenceEquals(currentFocus, this) || currentFocus == null || ReferenceEquals(currentFocus.TabControlParent, this.TabControlParent) == false; this.SettingFocus = true; this.SetFocusOnContent = setFocusOnContent; try { return this.Focus() || setFocusOnContent; } finally { this.SettingFocus = false; this.SetFocusOnContent = false; } } private bool SetFocusOnContent { get; set; } private bool SettingFocus { get; set; } /// <summary> /// Focus event handler /// </summary> protected override void OnPreviewGotKeyboardFocus(KeyboardFocusChangedEventArgs e) { base.OnPreviewGotKeyboardFocus(e); if (e.Handled || ReferenceEquals(e.NewFocus, this) == false) { return; } if (this.IsSelected || this.TabControlParent == null) { return; } this.IsSelected = true; // If focus moved in result of selection - handle the event to prevent setting focus back on the new item if (ReferenceEquals(e.OldFocus, Keyboard.FocusedElement) == false) { e.Handled = true; } else if (this.SetFocusOnContent) { var parentTabControl = this.TabControlParent; if (parentTabControl != null) { // Save the parent and check for null to make sure that SetCurrentValue didn't have a change handler // that removed the TabItem from the tree. var selectedContentPresenter = parentTabControl.SelectedContentPresenter; if (selectedContentPresenter != null) { parentTabControl.UpdateLayout(); // Wait for layout var success = selectedContentPresenter.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)); // If we successfully move focus inside the content then don't set focus to the header if (success) { e.Handled = true; } } } } } /// <summary> /// Called to remeasure a control. /// </summary> /// <param name="constraint">The maximum size that the method can return.</param> /// <returns>The size of the control, up to the maximum specified by constraint.</returns> protected override Size MeasureOverride(Size constraint) { if (this.contentContainer == null) { return base.MeasureOverride(constraint); } if (this.IsContextual && this.Group != null && this.Group.Visibility == Visibility.Collapsed) { return Size.Empty; } this.contentContainer.Padding = new Thickness(this.Indent, this.contentContainer.Padding.Top, this.Indent, this.contentContainer.Padding.Bottom); var baseConstraint = base.MeasureOverride(constraint); var totalWidth = this.contentContainer.DesiredSize.Width - this.contentContainer.Margin.Left - this.contentContainer.Margin.Right; this.contentContainer.Child.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); var headerWidth = this.contentContainer.Child.DesiredSize.Width; if (totalWidth < headerWidth + (this.Indent * 2)) { var newPaddings = Math.Max(0, (totalWidth - headerWidth) / 2); this.contentContainer.Padding = new Thickness(newPaddings, this.contentContainer.Padding.Top, newPaddings, this.contentContainer.Padding.Bottom); } else { if (DoubleUtil.AreClose(this.desiredWidth, 0) == false) { // If header width is larger then tab increase tab width if (constraint.Width > this.desiredWidth && this.desiredWidth > totalWidth) { baseConstraint.Width = this.desiredWidth; } else { baseConstraint.Width = headerWidth + (this.Indent * 2) + this.contentContainer.Margin.Left + this.contentContainer.Margin.Right; } } } if (DoubleUtil.AreClose(this.cachedWidth, baseConstraint.Width) == false && this.IsContextual && this.Group != null) { this.cachedWidth = baseConstraint.Width; var contextualTabGroupContainer = UIHelper.GetParent<RibbonContextualGroupsContainer>(this.Group); contextualTabGroupContainer?.InvalidateMeasure(); var ribbonTitleBar = UIHelper.GetParent<RibbonTitleBar>(this.Group); ribbonTitleBar?.ForceMeasureAndArrange(); } return baseConstraint; } /// <inheritdoc /> protected override Size ArrangeOverride(Size arrangeBounds) { var result = base.ArrangeOverride(arrangeBounds); var ribbonTitleBar = UIHelper.GetParent<RibbonTitleBar>(this.Group); ribbonTitleBar?.ForceMeasureAndArrange(); return result; } /// <summary> /// On new style applying /// </summary> public override void OnApplyTemplate() { this.contentContainer = this.GetTemplateChild("PART_ContentContainer") as Border; } /// <inheritdoc /> protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) { if (ReferenceEquals(e.Source, this) && e.ClickCount == 2) { e.Handled = true; if (this.TabControlParent != null) { var canMinimize = this.TabControlParent.CanMinimize; if (canMinimize) { this.TabControlParent.IsMinimized = !this.TabControlParent.IsMinimized; } } } else if (ReferenceEquals(e.Source, this) || this.IsSelected == false) { if (this.Visibility == Visibility.Visible) { if (this.TabControlParent != null) { var newItem = this.TabControlParent.ItemContainerGenerator.ItemFromContainer(this); if (ReferenceEquals(this.TabControlParent.SelectedTabItem, newItem)) { this.TabControlParent.IsDropDownOpen = !this.TabControlParent.IsDropDownOpen; } else { this.TabControlParent.SelectedItem = newItem; } this.TabControlParent.RaiseRequestBackstageClose(); } else { this.IsSelected = true; } this.SetFocus(); e.Handled = true; } } } #endregion #region Private methods // Handles IsSelected property changes private static void OnIsSelectedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var container = (RibbonTabItem)d; var newValue = (bool)e.NewValue; if (newValue) { if (container.TabControlParent?.SelectedItem is RibbonTabItem && ReferenceEquals(container.TabControlParent.SelectedItem, container) == false) { ((RibbonTabItem)container.TabControlParent.SelectedItem).IsSelected = false; } container.OnSelected(new RoutedEventArgs(Selector.SelectedEvent, container)); } else { container.OnUnselected(new RoutedEventArgs(Selector.UnselectedEvent, container)); } } /// <summary> /// Handles selected /// </summary> /// <param name="e">The event data</param> protected virtual void OnSelected(RoutedEventArgs e) { this.HandleIsSelectedChanged(e); } /// <summary> /// handles unselected /// </summary> /// <param name="e">The event data</param> protected virtual void OnUnselected(RoutedEventArgs e) { this.HandleIsSelectedChanged(e); } #endregion #region Event handling // Handles IsSelected property changes private void HandleIsSelectedChanged(RoutedEventArgs e) { this.RaiseEvent(e); } private void OnLoaded(object sender, RoutedEventArgs e) { this.SubscribeEvents(); } private void OnUnloaded(object sender, RoutedEventArgs e) { this.UnSubscribeEvents(); } private void SubscribeEvents() { // Always unsubscribe events to ensure we don't subscribe twice this.UnSubscribeEvents(); if (this.groups != null) { this.groups.CollectionChanged += this.OnGroupsCollectionChanged; } } private void UnSubscribeEvents() { if (this.groups != null) { this.groups.CollectionChanged -= this.OnGroupsCollectionChanged; } } #endregion /// <inheritdoc /> public KeyTipPressedResult OnKeyTipPressed() { var currentSelectedItem = this.TabControlParent?.SelectedItem as RibbonTabItem; if (currentSelectedItem != null) { currentSelectedItem.IsSelected = false; } this.IsSelected = true; // This way keytips for delay loaded elements work correctly. Partially fixes #244. this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new Action(() => { })); return KeyTipPressedResult.Empty; } /// <inheritdoc /> public void OnKeyTipBack() { if (this.TabControlParent != null && this.TabControlParent.IsMinimized) { this.TabControlParent.IsDropDownOpen = false; } } } }
using UnityEditor; using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; public static class PrefabUtilityEx { public static bool HasPropertyModifications(Object obj, bool thisObjectOnly) { if(!obj) { return false; } var mods = GetPropertyModifications(obj, thisObjectOnly); var root = PrefabUtility.FindPrefabRoot(GetGameObject(obj)); if(mods==null || (root != GetGameObject(obj) && mods.Length > 0)) { return true; } var prefab = (GameObject)PrefabUtility.GetPrefabParent(root); // root prefabs tend to have overriden transform values all of the time // we should only show them if the value is changed though foreach(var i in mods) { if(i.target.GetType() != typeof(Transform)) return true; float value; if(float.TryParse(i.value, out value)) { float baseVal; if(i.propertyPath == "m_LocalPosition.x" ) baseVal = prefab.transform.localPosition.x; else if(i.propertyPath == "m_LocalPosition.y" ) baseVal = prefab.transform.localPosition.y; else if(i.propertyPath == "m_LocalPosition.z" ) baseVal = prefab.transform.localPosition.z; else if(i.propertyPath == "m_LocalRotation.x" ) baseVal = prefab.transform.localRotation.x; else if(i.propertyPath == "m_LocalRotation.y" ) baseVal = prefab.transform.localRotation.y; else if(i.propertyPath == "m_LocalRotation.z" ) baseVal = prefab.transform.localRotation.z; else if(i.propertyPath == "m_LocalRotation.w" ) baseVal = prefab.transform.localRotation.w; else if(i.propertyPath == "m_LocalScale.x" ) baseVal = prefab.transform.localScale.x; else if(i.propertyPath == "m_LocalScale.y" ) baseVal = prefab.transform.localScale.y; else if(i.propertyPath == "m_LocalScale.z" ) baseVal = prefab.transform.localScale.z; else return true; if(Mathf.Approximately(baseVal, value)) continue; } return true; } return false; } public static bool IsPrefabInstanceModified(Object obj, bool thisObjectOnly) { if(!obj) { return false; } var mods = GetPropertyModifications(obj, thisObjectOnly); bool isValueOverriden = HasPropertyModifications(obj, thisObjectOnly); bool isComponentAdded = false; var gameObj = obj as GameObject; if(gameObj && !thisObjectOnly) { Component[] components = PrefabUtility.FindPrefabRoot(gameObj).GetComponentsInChildren<Component>(); isComponentAdded = components.Any((arg) => PrefabUtility.IsComponentAddedToPrefabInstance(arg)); } else isComponentAdded = PrefabUtility.IsComponentAddedToPrefabInstance(obj); return isValueOverriden || isComponentAdded; } public static void RevertInstance(Object obj) { PrefabUtility.RevertPrefabInstance(obj as GameObject); //PrefabUtility.SetPropertyModifications(obj, new PropertyModification[0]); EditorUtility.SetDirty(obj); } public static void ApplyInstance(Object obj) { var root = PrefabUtility.FindPrefabRoot(obj as GameObject); var parent = PrefabUtility.GetPrefabParent(obj); PrefabUtility.ReplacePrefab(root, parent, ReplacePrefabOptions.ConnectToPrefab); //PrefabUtility.SetPropertyModifications(obj, new PropertyModification[0]); EditorUtility.SetDirty(parent); EditorUtility.SetDirty(obj); } public static PropertyModification[] GetPropertyModifications (Object obj, bool thisObjectOnly) { var mods = new List<PropertyModification>(); if(thisObjectOnly) { var prefab = PrefabUtility.GetPrefabParent(obj); var modsArray = PrefabUtility.GetPropertyModifications(obj); mods.AddRange(modsArray!=null ? modsArray:new PropertyModification[0]); mods.RemoveAll((i) => i.target != prefab); } else { var prefab = GetRootPrefab(obj); var modsArray = PrefabUtility.GetPropertyModifications(obj); mods.AddRange(modsArray!=null ? modsArray:new PropertyModification[0]); } return mods.ToArray(); } public static Component[] GetRemovedComponentsFromPrefab(Object obj, bool thisObjectOnly) { HashSet<Component> instanceComponents; HashSet<Component> prefabComponents; Object instance; GameObject prefab; if(thisObjectOnly) { instance = obj; prefab = (GameObject)PrefabUtility.GetPrefabParent(instance); if(instance as GameObject) instanceComponents = new HashSet<Component>((instance as GameObject).GetComponents<Component>()); else instanceComponents = new HashSet<Component>((instance as Component).GetComponents<Component>()); prefabComponents = new HashSet<Component>(prefab.GetComponents<Component>()); } else { if(obj as GameObject) { instance = PrefabUtility.FindPrefabRoot(obj as GameObject); prefab = (GameObject)PrefabUtility.GetPrefabParent(instance); instanceComponents = new HashSet<Component>((instance as GameObject).GetComponentsInChildren<Component>()); prefabComponents = new HashSet<Component>(prefab.GetComponentsInChildren<Component>()); } else { instance = PrefabUtility.FindPrefabRoot((obj as Component).gameObject); prefab = (GameObject)PrefabUtility.GetPrefabParent(instance); instanceComponents = new HashSet<Component>((instance as Component).GetComponentsInChildren<Component>()); prefabComponents = new HashSet<Component>(prefab.GetComponentsInChildren<Component>()); } } prefabComponents.RemoveWhere((i) => instanceComponents.Any((j) => PrefabUtility.GetPrefabParent(j)==i)); return prefabComponents.ToArray(); } public static string GetModificationDescription (Object obj, bool thisObjectOnly) { string output = ""; bool modified = false; var mods = PrefabUtilityEx.GetPropertyModifications(obj, thisObjectOnly); if(mods != null && mods.Length > 0) { output += "Modified values:"; foreach(var i in mods) { output += string.Concat("\n", i.target.name, ".", i.target.GetType().Name, " - ", i.propertyPath, ":", i.objectReference? i.objectReference.name:i.value); } modified = true; } if(PrefabUtility.IsComponentAddedToPrefabInstance(obj)) { output += string.Concat("Added: ",obj.GetType().Name); modified = true; } var removedChildren = GetRemovedChildrenFromPrefab(obj, thisObjectOnly); if(removedChildren.Length > 0) { output += "Removed Children: "; foreach(var i in removedChildren) { output += string.Concat("\n", i.name); } modified = true; } if(modified) return output; return "Not modified"; } static GameObject[] GetAllChildren(GameObject obj) { var children = new List<GameObject>(new GameObject[] {obj}); for(int i=0; i<obj.transform.GetChildCount(); ++i) { children.AddRange(GetAllChildren(obj.transform.GetChild(i).gameObject)); } return children.ToArray(); } public static GameObject GetGameObject(Object obj) { if(obj as GameObject) return obj as GameObject; else if(obj as Component) return (obj as Component).gameObject; else return null; } public static GameObject[] GetRemovedChildrenFromPrefab(Object instnanceObj, bool thisObjectOnly) { GameObject instance = (thisObjectOnly) ? GetGameObject(instnanceObj):PrefabUtility.FindPrefabRoot(GetGameObject(instnanceObj)); GameObject prefab = (GameObject)PrefabUtility.GetPrefabParent(instance); var prefabChildrenSet = new HashSet<GameObject>(GetAllChildren (prefab)); var instanceChildrenSet = new HashSet<GameObject>(GetAllChildren(instance).Select((arg) => GetGameObject(PrefabUtility.GetPrefabParent(arg)))); var removedChildren = new HashSet<GameObject>(prefabChildrenSet); removedChildren.ExceptWith(instanceChildrenSet); return removedChildren.ToArray(); } public static void RemoveChildrenAndReconnectToLastPrefab(GameObject instanceObj, bool thisObjectOnly) { GameObject instance = (thisObjectOnly) ? instanceObj:PrefabUtility.FindPrefabRoot(instanceObj); GameObject prefab = (GameObject)PrefabUtility.GetPrefabParent(instance); var removedChildren = GetRemovedChildrenFromPrefab(instanceObj,false); foreach(var i in removedChildren) { if(i) { GameObject.DestroyImmediate(i, true); } } EditorUtility.SetDirty(prefab); AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(prefab)); PrefabUtility.ReconnectToLastPrefab(instance); } public static bool IsPrefabRoot (Object obj) { return PrefabUtility.FindPrefabRoot(GetGameObject(PrefabUtility.GetPrefabParent(obj))) == PrefabUtility.GetPrefabParent(obj); } /* public static void ApplySpecificChanges (GameObject obj, PropertyModification[] changes) { } */ public static void RevertSpecificChanges (Object obj, PropertyModification[] changes) { var root = PrefabUtility.FindPrefabRoot(GetGameObject(obj)); var modsArray = PrefabUtility.GetPropertyModifications(root); var mods = new List<PropertyModification>(modsArray != null ? modsArray:new PropertyModification[0]); if(obj == root.transform) { var prefabTForm = (Transform)PrefabUtility.GetPrefabParent(root.transform); var baseMods = new PropertyModification[] { new PropertyModification() { propertyPath = "m_LocalPosition.x", target = prefabTForm, value=prefabTForm.localPosition.x.ToString() }, new PropertyModification() { propertyPath = "m_LocalPosition.y", target = prefabTForm, value=prefabTForm.localPosition.y.ToString() }, new PropertyModification() { propertyPath = "m_LocalPosition.z", target = prefabTForm, value=prefabTForm.localPosition.z.ToString() }, new PropertyModification() { propertyPath = "m_LocalRotation.x", target = prefabTForm, value=prefabTForm.localRotation.x.ToString() }, new PropertyModification() { propertyPath = "m_LocalRotation.y", target = prefabTForm, value=prefabTForm.localRotation.y.ToString() }, new PropertyModification() { propertyPath = "m_LocalRotation.z", target = prefabTForm, value=prefabTForm.localRotation.z.ToString() }, new PropertyModification() { propertyPath = "m_LocalRotation.w", target = prefabTForm, value=prefabTForm.localRotation.w.ToString() }, new PropertyModification() { propertyPath = "m_LocalScale.x", target = prefabTForm, value=prefabTForm.localScale.x.ToString() }, new PropertyModification() { propertyPath = "m_LocalScale.y", target = prefabTForm, value=prefabTForm.localScale.y.ToString() }, new PropertyModification() { propertyPath = "m_LocalScale.z", target = prefabTForm, value=prefabTForm.localScale.z.ToString() } }; mods = new List<PropertyModification>(baseMods); } else { foreach(var i in changes) { mods.RemoveAll((a) => ComparePropertyModifications(i,a)); } } var newChanges = mods.ToArray(); PrefabUtility.SetPropertyModifications(obj, newChanges); } static bool ComparePropertyModifications(PropertyModification a, PropertyModification b) { return a.objectReference == b.objectReference && a.propertyPath == b.propertyPath && a.target == b.target && a.value == b.value; } static Component[] GetRequiredComponents(Component obj) { var reqs = new HashSet<Component>(); foreach(RequireComponent i in obj.GetType().GetCustomAttributes(typeof(RequireComponent), true)) { reqs.Add(obj.gameObject.GetComponent(i.m_Type0)); reqs.Add(obj.gameObject.GetComponent(i.m_Type1)); reqs.Add(obj.gameObject.GetComponent(i.m_Type2)); } // things that need rigidbodies if(obj as Joint) { reqs.Add(obj.gameObject.rigidbody); } reqs.Remove(null); return reqs.ToArray(); } public static GameObject GetRootPrefab(Object obj) { if(PrefabUtility.GetPrefabType(obj)==PrefabType.None) return null; var root = PrefabUtility.FindPrefabRoot(GetGameObject(obj)); var rootPrefab = root==null?null:(GameObject)PrefabUtility.GetPrefabParent(root); return rootPrefab; } public static bool AreInsideSamePrefab(Object a, Object b) { var prefabA = GetRootPrefab(a); var prefabB = GetRootPrefab(b); return prefabA == prefabB; } public static void ApplyInstanceModificationsToPrefab(Component objInstance) { } public static bool IsInstance(Object obj) { PrefabType type = PrefabUtility.GetPrefabType(obj); return type != PrefabType.Prefab && type != PrefabType.ModelPrefab; } public static bool IsPrefabInstance(Object obj) { PrefabType type = PrefabUtility.GetPrefabType(obj); return type == PrefabType.PrefabInstance || type == PrefabType.ModelPrefabInstance || type == PrefabType.DisconnectedModelPrefabInstance || type == PrefabType.DisconnectedPrefabInstance; } public static void AddInstanceComponentToPrefab(Component obj) { var gameObject = PrefabUtility.FindPrefabRoot(GetGameObject(obj)); var prefab = (GameObject)PrefabUtility.GetPrefabParent(gameObject); foreach(var i in GetRequiredComponents(obj)) { if(i && PrefabUtility.GetPrefabParent(i) == null && prefab.GetComponent(i.GetType()) == null) AddInstanceComponentToPrefab(i); } // add the prefab to the target var prefabComp = prefab.AddComponent(obj.GetType()); if(prefabComp) { var mods = new List<PropertyModification>(PrefabUtility.GetPropertyModifications(gameObject)); // copy data EditorUtility.CopySerialized(obj, prefabComp); // fix up any references to their prefabs SerializedObject so = new SerializedObject(obj); SerializedObject prefabCompSo = new SerializedObject(prefabComp); prefabCompSo.Update(); so.Update(); var i = so.GetIterator(); while(i.Next(true)) { if(i.propertyType == SerializedPropertyType.ObjectReference) { if(i.propertyPath == "m_PrefabParentObject" || i.propertyPath == "m_PrefabInternal" || i.propertyPath == "m_GameObject" || i.propertyPath == "m_Script") continue; var prefabRef = PrefabUtility.GetPrefabParent(i.objectReferenceValue); var prefabRefRoot = PrefabUtility.GetPrefabParent(PrefabUtility.FindPrefabRoot(PrefabUtilityEx.GetGameObject(i.objectReferenceValue))); var prefabType = i.objectReferenceValue!= null ? PrefabUtility.GetPrefabType(i.objectReferenceValue):PrefabType.None; if(prefabType != PrefabType.Prefab && prefabType != PrefabType.ModelPrefab) { // link to an object in the scene. // we must add a modification for this. if(i.objectReferenceValue != null && (prefabRef == null || prefab != prefabRefRoot)) { var propertyMod = new PropertyModification(); propertyMod.objectReference = i.objectReferenceValue; propertyMod.target = prefabComp; propertyMod.propertyPath = i.propertyPath; mods.Add(propertyMod); prefabCompSo.FindProperty(i.propertyPath).objectReferenceValue = null; } else prefabCompSo.FindProperty(i.propertyPath).objectReferenceValue = prefabRef; } } } so = null; // save prefabCompSo.ApplyModifiedProperties(); EditorUtility.SetDirty(prefab); AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(prefab)); // remove the applied value from our instance. UnityEngine.GameObject.DestroyImmediate(obj); // add property mods var components = gameObject.GetComponents(prefabComp.GetType()); Component newComponent = System.Array.Find(components, ((arg) => PrefabUtility.GetPrefabParent(arg)==prefabComp)); PrefabUtility.SetPropertyModifications(newComponent, mods.ToArray()); } else EditorUtility.DisplayDialog("Error", "Can't apply this component to the prefab as it cannot own more than one prefab of this type", "Ok"); } }
using Saga.Data; using Saga.Map.Definitions.Misc; using Saga.Map.Utils.Definitions.Misc; using Saga.PrimaryTypes; using Saga.Structures; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; namespace Saga.Map { public interface IInfoProvider2 { IDataWeaponCollection createWeaponCollection(); IDataCharacter createDataCharacter(); IDataAdditionCollection createAdditionCollection(); IDataSortableItemCollection createInventoryCollection(); IDataSortableItemCollection createStorageCollection(); IDataJobinformationCollection createJobCollection(); IDataZoneInformationCollection createDataZoneCollection(); IDataEquipmentCollection createEquipmentCollection(); IDataSkillCollection createSkillCollection(); IDatabaseQuestStream createDatabaseQuestStream(); IDataSpecialSkillCollection createDatabaseSpecialSkillCollection(); IDatabaseFriendList createDatabaseFriendList(); IDatabaseBlacklist createDatabaseBlacklist(); uint OwnerId { get; set; } } public interface IDataWeaponCollection { /// <summary> /// Get's the character id of the owner /// </summary> uint CharacterId { get; } /// <summary> /// Get's or Sets a weapon at the specified index /// </summary> /// <param name="index">Zero based index where to set the weapon</param> /// <returns>Weapon</returns> Weapon this[int index] { get; set; } /// <summary> /// Get's or set's the number of unlocked weapon slots (maximum 5) /// </summary> byte UnlockedWeaponSlots { get; set; } /// <summary> /// Get's or set's the index of the primary weapon /// </summary> /// <remarks> /// Set this value to 255 to use hands. A value between 0 - 5 will /// try to get the weapon at the specified index. /// </remarks> byte PrimaryWeaponIndex { get; set; } /// <summary> /// Get's or set's the index of the seccondairy weapon /// </summary> /// <remarks> /// Set this value to 255 to use hands. A value between 0 - 5 will /// try to get the weapon at the specified index. /// </remarks> byte SeconairyWeaponIndex { get; set; } /// <summary> /// Get's or sets the active weapon index /// </summary> /// <remarks> /// Use 0 for using the left hand and 1 for using the right hand. /// </remarks> byte ActiveWeaponIndex { get; set; } } public interface IDataCharacter { /// <summary> /// Get's the character id of the owner /// </summary> uint CharacterId { get; set; } /// <summary> /// Get's or Set's the character name /// </summary> string CharacterName { get; set; } /// <summary> /// Get's or sets the characters face details /// </summary> byte[] CharacterFace { get; } /// <summary> /// Get's or set the character experience also known as base experience or cexp /// </summary> uint CharacterExperience { get; set; } /// <summary> /// Get's or set the job experience also known as jexp /// </summary> uint JobExperience { get; set; } /// <summary> /// Get's or set's the current job /// </summary> byte Job { get; set; } /// <summary> /// Get's or set's the current hp of the character /// </summary> ushort HP { get; set; } /// <summary> /// Get's or set's the current sp of the character /// </summary> ushort SP { get; set; } /// <summary> /// Get's or set's the current lp of the character /// </summary> byte LP { get; set; } /// <summary> /// Get's or set's the current breath of the character /// </summary> byte Oxygen { get; set; } /// <summary> /// Get's or set's the current strenght stat /// </summary> ushort Strength { get; set; } /// <summary> /// Get's or set's the current dexterity stat /// </summary> ushort Dexterity { get; set; } /// <summary> /// Get's or set's the current intellect stat /// </summary> ushort Intellect { get; set; } /// <summary> /// Get's or set's the current concentration stat /// </summary> ushort Concentration { get; set; } /// <summary> /// Get's or set's the current luck stat /// </summary> ushort Luck { get; set; } /// <summary> /// Get's or set's the current remainging stat points /// </summary> ushort Remaining { get; set; } /// <summary> /// Get's or set's the character amount of zeny /// </summary> uint Zeny { get; set; } WorldCoordinate Position { get; set; } WorldCoordinate SavePosition { get; set; } } public interface IDataAdditionCollection { /// <summary> /// Get's the character id of the owner /// </summary> uint CharacterId { get; } /// <summary> /// Creates a addition /// </summary> /// <param name="addition">unique id of the addition</param> /// <param name="duration">time spawn for the addition</param> /// <returns>True if the addition was loaded</returns> bool Create(uint addition, uint duration); /// <summary> /// Get's all addition /// </summary> IEnumerable<AdditionState> Additions { get; } } public interface IDataSortableItemCollection { /// <summary> /// Get's the character id of the owner /// </summary> uint CharacterId { get; } /// <summary> /// Get's or set's the sortation mode /// </summary> byte SortationMode { get; set; } /// <summary> /// Get's container for the items /// </summary> Rag2Collection Collection { get; } } public interface IDataJobinformationCollection { /// <summary> /// Get's the character id of the owner /// </summary> uint CharacterId { get; } /// <summary> /// Get's container for all the joblevels /// </summary> byte[] Joblevels { get; } } public interface IDataZoneInformationCollection { /// <summary> /// Get's the character id of the owner /// </summary> uint CharacterId { get; } /// <summary> /// Get's container for all the zone information /// </summary> byte[] ZoneInformation { get; } } public interface IDataEquipmentCollection { /// <summary> /// Get's the character id of the owner /// </summary> uint CharacterId { get; } /// <summary> /// Get's container for all the zone information /// </summary> Rag2Item[] Equipment { get; } } public interface IDataSkillCollection { /// <summary> /// Get's the character id of the owner /// </summary> uint CharacterId { get; } /// <summary> /// Get's the job id of the character /// </summary> byte Job { get; } /// <summary> /// Get's container for all the skills /// </summary> List<Skill> Skills { get; } } public interface IDataSpecialSkillCollection { /// <summary> /// Get's the character id of the owner /// </summary> uint CharacterId { get; } /// <summary> /// Get's the special skill collection (max size of 16 elements) /// </summary> Skill[] specialSkillCollection { get; } } public interface IDatabaseQuestStream { /// <summary> /// Get's the character id of the owner /// </summary> uint CharacterId { get; } /// <summary> /// Get's or set's the quest data stream /// </summary> byte[] questCollection { get; set; } } public interface IDatabaseFriendList { /// <summary> /// Get's the character id of the owner /// </summary> uint CharacterId { get; } /// <summary> /// Get's a list of friends /// </summary> List<string> friends { get; } } public interface IDatabaseBlacklist { /// <summary> /// Get's the character id of the owner /// </summary> uint CharacterId { get; } /// <summary> /// Get's a list of blacklisted people /// </summary> List<KeyValuePair<string, byte>> blacklist { get; } } public interface IDatabase { #region General /// <summary> /// Checks the server version. /// </summary> bool CheckServerVersion(); /// <summary> /// Summary on connect /// </summary> /// <param name="info">Connection info to establish the connection</param> bool Connect(ConnectionInfo info); /// <summary> /// Checks the database for missing tables and fields /// </summary> bool CheckDatabaseFields(); #endregion General #region Skills void LoadSkills(Character character, uint CharId); IEnumerable<uint> GetAllLearnedSkills(Character target); bool InsertNewSkill(uint CharId, uint SkillId, byte job); bool UpdateSkill(Character target, uint SkillId, uint Experience); bool UpgradeSkill(Character target, uint OldSkillId, uint NewSkillId, uint Experience); bool InsertNewSkill(uint CharId, uint SkillId, byte job, uint Experience); List<uint> GetJobSpeciaficSkills(Character target, byte job); #endregion Skills #region Mailbox #pragma warning disable 0436 IEnumerable<Mail> GetInboxMail(Character target); IEnumerable<Mail> GetOutboxMail(Character target); #pragma warning restore 0436 int GetInboxMailCount(string name); int GetOutboxMailCount(Character target); int GetInboxUncheckedCount(string name); bool GetItemByAuctionId(uint id, out AuctionArgument item); bool DeleteRegisteredAuctionItem(uint id); bool InsertNewMailItem(Character target, MailItem item); MailItem GetMailItemById(uint id); IEnumerable<KeyValuePair<string, uint>> GetPendingMails(); bool ClearPendingMails(string Receiptent); bool MarkAsReadMailItem(uint id); uint GetZenyAttachment(uint id); bool UpdateZenyAttachment(uint Id, uint Zeny); bool DeleteMails(uint id); bool DeleteMailFromOutbox(uint id); bool UpdateItemAttachment(uint MailId, Rag2Item Attachment); Rag2Item GetItemAttachment(uint MailId); #endregion Mailbox #region Auction /// <summary> /// Search for all market items registered in the database. /// </summary> /// <param name="Argument">Search argument</param> /// <returns>Iterable list of MarketItemArguments</returns> IEnumerable<MarketItemArgument> SearchMarket(MarketSearchArgument Argument); /// <summary> /// Search for market items registered by the specified character. /// </summary> /// <param name="target">Character who the items are from</param> /// <returns>Iterable list of MarketItemArguments</returns> IEnumerable<MarketItemArgument> SearchMarketForOwner(Character target); /// <summary> /// Registers a new marketitem on the database /// </summary> /// <param name="target">Character who the database is for.</param> /// <param name="arg">Item argument</param> /// <returns></returns> uint RegisterNewMarketItem(Character target, MarketItemArgument arg); /// <summary> /// Unregisters the selected market id. /// </summary> /// <param name="id">Id of the marketitem</param> /// <returns>Number of items registered</returns> uint UnregisterMarketItem(uint id); /// <summary> /// Find a comment by the associated itemid. /// </summary> /// <param name="id">Id of the marketitem</param> /// <returns>Display comment</returns> string FindCommentByPlayerId(uint id); /// <summary> /// Find a comment by the associated itemid. /// </summary> /// <param name="id">Id of the marketitem</param> /// <returns>Display comment</returns> string FindCommentById(uint id); /// <summary> /// Update the comment by the specified player id. /// </summary> /// <param name="id">Id of the player</param> /// <param name="message">Message to display in the future</param> /// <returns>Number of updated records</returns> uint UpdateCommentByPlayerId(uint id, string message); /// <summary> /// Gets the count of registered items by the owner character /// </summary> /// <param name="target">Character who's items to count</param> /// <returns>Number of items found</returns> int GetOwnerItemCount(Character target); #endregion Auction #region Quests IEnumerable<uint> GetAvailableQuestsByRegion(Character target, uint modelid); IEnumerable<KeyValuePair<uint, uint>> GetPersonalAvailableQuestsByRegion(Character target, byte region, uint CurrentPersonalQuest); bool QuestComplete(uint charId, uint QuestId); bool IsQuestComplete(uint charId, uint QuestId); #endregion Quests #region FriendList /// <summary> /// Delete a character on the friendlist of the user. /// </summary> /// <param name="charId">CharacterId if of the character</param> /// <param name="friend">Name of the foe</param> /// <returns></returns> bool DeleteFriend(uint charId, string friend); /// <summary> /// Delete a character on the blacklist of the user. /// </summary> /// <param name="charId">CharacterId if of the character</param> /// <param name="friend">Name of the foe</param> /// <returns></returns> bool DeleteBlacklist(uint charId, string friend); /// <summary> /// Adds the specified charactername on the friendlist /// of the character. /// </summary> /// <param name="charId">CharacterId if of the character</param> /// <param name="friend">Name of the friend</param> /// <returns></returns> bool InsertAsFriend(uint charId, string friend); /// <summary> /// Adds the specified charactername on the blacklist /// of the character. /// </summary> /// <param name="charId">CharacterId if of the character</param> /// <param name="friend">Name of the foe</param> /// <param name="reason">Reason for the ban</param> /// <returns>False on database error</returns> bool InsertAsBlacklist(uint charId, string friend, byte reason); #endregion FriendList #region Character IEnumerable<CharInfo> FindCharacters(uint PlayerId); bool FindCharacterDetails(uint CharId, out CharDetails details); bool VerifyNameExists(string name); bool DeleteCharacterById(uint id); bool GetPlayerId(string name, out uint charid); #endregion Character #region Event /// <summary> /// Retrieves a list of item rewards that were given by /// to the specified character /// </summary> /// <param name="target">Character instance to retrieve</param> /// <returns>A collection of EventItemLists</returns> Collection<EventItem> FindEventItemList(Character target); /// <summary> /// Retrieves a even item reward based on the given unqiue id, /// </summary> /// <param name="target">Owner character of the item</param> /// <param name="RewardId">Unique id of the reward</param> /// <returns>a single eventitem reward</returns> EventItem FindEventItemById(Character target, uint RewardId); /// <summary> /// Deletes a event item reward based on the given unique id. /// </summary> /// <param name="RewardId"></param> /// <returns></returns> bool DeleteEventItemId(uint RewardId); /// <summary> /// Creates an event item /// </summary> /// <returns>True if item was made</returns> bool CreateEventItem(uint charid, uint Itemid, byte stackcount); #endregion Event #region Plugin IQueryProvider GetQueryProvider(); IDataReader ExecuteDataReader(IQueryProvider query); IDataReader ExecuteDataReader(IQueryProvider query, CommandBehavior behavior); int ExecuteNonQuery(IQueryProvider query); #endregion Plugin //Third generation methods bool TransactionSave(IInfoProvider2 dbq); bool TransactionLoad(IInfoProvider2 dbq, bool continueOnError); bool TransactionRepair(IInfoProvider2 dbq); bool TransactionInsert(IInfoProvider2 dbq); bool GetCharacterId(string name, out uint charId); } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.DocumentationComments; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal static partial class ISymbolExtensions2 { public static Glyph GetGlyph(this ISymbol symbol) { Glyph publicIcon; switch (symbol.Kind) { case SymbolKind.Alias: return ((IAliasSymbol)symbol).Target.GetGlyph(); case SymbolKind.Assembly: return Glyph.Assembly; case SymbolKind.ArrayType: return ((IArrayTypeSymbol)symbol).ElementType.GetGlyph(); case SymbolKind.DynamicType: return Glyph.ClassPublic; case SymbolKind.Event: publicIcon = Glyph.EventPublic; break; case SymbolKind.Field: var containingType = symbol.ContainingType; if (containingType != null && containingType.TypeKind == TypeKind.Enum) { return Glyph.EnumMember; } publicIcon = ((IFieldSymbol)symbol).IsConst ? Glyph.ConstantPublic : Glyph.FieldPublic; break; case SymbolKind.Label: return Glyph.Label; case SymbolKind.Local: case SymbolKind.Discard: return Glyph.Local; case SymbolKind.NamedType: case SymbolKind.ErrorType: { switch (((INamedTypeSymbol)symbol).TypeKind) { case TypeKind.Class: publicIcon = Glyph.ClassPublic; break; case TypeKind.Delegate: publicIcon = Glyph.DelegatePublic; break; case TypeKind.Enum: publicIcon = Glyph.EnumPublic; break; case TypeKind.Interface: publicIcon = Glyph.InterfacePublic; break; case TypeKind.Module: publicIcon = Glyph.ModulePublic; break; case TypeKind.Struct: publicIcon = Glyph.StructurePublic; break; case TypeKind.Error: return Glyph.Error; default: throw new ArgumentException(FeaturesResources.The_symbol_does_not_have_an_icon, nameof(symbol)); } break; } case SymbolKind.Method: { var methodSymbol = (IMethodSymbol)symbol; if (methodSymbol.MethodKind == MethodKind.UserDefinedOperator || methodSymbol.MethodKind == MethodKind.Conversion) { return Glyph.Operator; } else if (methodSymbol.IsExtensionMethod || methodSymbol.MethodKind == MethodKind.ReducedExtension) { publicIcon = Glyph.ExtensionMethodPublic; } else { publicIcon = Glyph.MethodPublic; } } break; case SymbolKind.Namespace: return Glyph.Namespace; case SymbolKind.NetModule: return Glyph.Assembly; case SymbolKind.Parameter: return symbol.IsImplicitValueParameter() ? Glyph.Keyword : Glyph.Parameter; case SymbolKind.PointerType: return ((IPointerTypeSymbol)symbol).PointedAtType.GetGlyph(); case SymbolKind.Property: { var propertySymbol = (IPropertySymbol)symbol; if (propertySymbol.IsWithEvents) { publicIcon = Glyph.FieldPublic; } else { publicIcon = Glyph.PropertyPublic; } } break; case SymbolKind.RangeVariable: return Glyph.RangeVariable; case SymbolKind.TypeParameter: return Glyph.TypeParameter; default: throw new ArgumentException(FeaturesResources.The_symbol_does_not_have_an_icon, nameof(symbol)); } switch (symbol.DeclaredAccessibility) { case Accessibility.Private: publicIcon += Glyph.ClassPrivate - Glyph.ClassPublic; break; case Accessibility.Protected: case Accessibility.ProtectedAndInternal: case Accessibility.ProtectedOrInternal: publicIcon += Glyph.ClassProtected - Glyph.ClassPublic; break; case Accessibility.Internal: publicIcon += Glyph.ClassInternal - Glyph.ClassPublic; break; } return publicIcon; } public static IEnumerable<TaggedText> GetDocumentationParts(this ISymbol symbol, SemanticModel semanticModel, int position, IDocumentationCommentFormattingService formatter, CancellationToken cancellationToken) { string documentation = GetDocumentation(symbol, cancellationToken); return documentation != null ? formatter.Format(documentation, semanticModel, position, CrefFormat) : SpecializedCollections.EmptyEnumerable<TaggedText>(); } private static string GetDocumentation(ISymbol symbol, CancellationToken cancellationToken) { switch (symbol) { case IParameterSymbol parameter: return parameter.ContainingSymbol.OriginalDefinition.GetDocumentationComment(cancellationToken: cancellationToken).GetParameterText(symbol.Name); case ITypeParameterSymbol typeParam: return typeParam.ContainingSymbol.GetDocumentationComment(cancellationToken: cancellationToken).GetTypeParameterText(symbol.Name); case IMethodSymbol method: return GetMethodDocumentation(method); case IAliasSymbol alias: return alias.Target.GetDocumentationComment(cancellationToken: cancellationToken).SummaryText; default: return symbol.GetDocumentationComment(cancellationToken: cancellationToken).SummaryText; } } public static Func<CancellationToken, IEnumerable<TaggedText>> GetDocumentationPartsFactory( this ISymbol symbol, SemanticModel semanticModel, int position, IDocumentationCommentFormattingService formatter) { return c => symbol.GetDocumentationParts(semanticModel, position, formatter, cancellationToken: c); } public static readonly SymbolDisplayFormat CrefFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeExplicitInterface | SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); private static string GetMethodDocumentation(IMethodSymbol method) { switch (method.MethodKind) { case MethodKind.EventAdd: case MethodKind.EventRaise: case MethodKind.EventRemove: case MethodKind.PropertyGet: case MethodKind.PropertySet: return method.ContainingSymbol.GetDocumentationComment().SummaryText; default: return method.GetDocumentationComment().SummaryText; } } public static IList<SymbolDisplayPart> ToAwaitableParts(this ISymbol symbol, string awaitKeyword, string initializedVariableName, SemanticModel semanticModel, int position) { var spacePart = new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, " "); var parts = new List<SymbolDisplayPart>(); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Text, null, $"\r\n{WorkspacesResources.Usage_colon}\r\n ")); var returnType = symbol.InferAwaitableReturnType(semanticModel, position); returnType = returnType != null && returnType.SpecialType != SpecialType.System_Void ? returnType : null; if (returnType != null) { if (semanticModel.Language == "C#") { parts.AddRange(returnType.ToMinimalDisplayParts(semanticModel, position)); parts.Add(spacePart); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.LocalName, null, initializedVariableName)); } else { parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, "Dim")); parts.Add(spacePart); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.LocalName, null, initializedVariableName)); parts.Add(spacePart); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, "as")); parts.Add(spacePart); parts.AddRange(returnType.ToMinimalDisplayParts(semanticModel, position)); } parts.Add(spacePart); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, "=")); parts.Add(spacePart); } parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Keyword, null, awaitKeyword)); parts.Add(spacePart); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.MethodName, symbol, symbol.Name)); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, "(")); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, symbol.GetParameters().Any() ? "..." : "")); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, ")")); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, semanticModel.Language == "C#" ? ";" : "")); return parts; } public static ITypeSymbol InferAwaitableReturnType(this ISymbol symbol, SemanticModel semanticModel, int position) { var methodSymbol = symbol as IMethodSymbol; if (methodSymbol == null) { return null; } var returnType = methodSymbol.ReturnType; if (returnType == null) { return null; } var potentialGetAwaiters = semanticModel.LookupSymbols(position, container: returnType, name: WellKnownMemberNames.GetAwaiter, includeReducedExtensionMethods: true); var getAwaiters = potentialGetAwaiters.OfType<IMethodSymbol>().Where(x => !x.Parameters.Any()); if (!getAwaiters.Any()) { return null; } var getResults = getAwaiters.SelectMany(g => semanticModel.LookupSymbols(position, container: g.ReturnType, name: WellKnownMemberNames.GetResult)); var getResult = getResults.OfType<IMethodSymbol>().FirstOrDefault(g => !g.IsStatic); if (getResult == null) { return null; } return getResult.ReturnType; } } }
#if UNITY_2017_1_OR_NEWER using UnityEditor.Experimental.AssetImporters; using UnityEditor; using System.IO; using UnityEngine; using System.Collections.Generic; using System.Linq; using System; using Object = UnityEngine.Object; using System.Collections; using UnityGLTF.Loader; using GLTF.Schema; using GLTF; using System.Threading.Tasks; namespace UnityGLTF { [ScriptedImporter(1, new[] { "glb" })] public class GLTFImporter : ScriptedImporter { [SerializeField] private bool _removeEmptyRootObjects = true; [SerializeField] private float _scaleFactor = 1.0f; [SerializeField] private int _maximumLod = 300; [SerializeField] private bool _readWriteEnabled = true; [SerializeField] private bool _generateColliders = false; [SerializeField] private bool _swapUvs = false; [SerializeField] private GLTFImporterNormals _importNormals = GLTFImporterNormals.Import; [SerializeField] private bool _importMaterials = true; [SerializeField] private bool _useJpgTextures = false; public override void OnImportAsset(AssetImportContext ctx) { string sceneName = null; GameObject gltfScene = null; UnityEngine.Mesh[] meshes = null; try { sceneName = Path.GetFileNameWithoutExtension(ctx.assetPath); gltfScene = CreateGLTFScene(ctx.assetPath); // Remove empty roots if (_removeEmptyRootObjects) { var t = gltfScene.transform; while ( gltfScene.transform.childCount == 1 && gltfScene.GetComponents<Component>().Length == 1) { var parent = gltfScene; gltfScene = gltfScene.transform.GetChild(0).gameObject; t = gltfScene.transform; t.parent = null; // To keep transform information in the new parent Object.DestroyImmediate(parent); // Get rid of the parent } } // Ensure there are no hide flags present (will cause problems when saving) gltfScene.hideFlags &= ~(HideFlags.HideAndDontSave); foreach (Transform child in gltfScene.transform) { child.gameObject.hideFlags &= ~(HideFlags.HideAndDontSave); } // Zero position gltfScene.transform.position = Vector3.zero; // Get meshes var meshNames = new List<string>(); var meshHash = new HashSet<UnityEngine.Mesh>(); var meshFilters = gltfScene.GetComponentsInChildren<MeshFilter>(); var vertexBuffer = new List<Vector3>(); meshes = meshFilters.Select(mf => { var mesh = mf.sharedMesh; vertexBuffer.Clear(); mesh.GetVertices(vertexBuffer); for (var i = 0; i < vertexBuffer.Count; ++i) { vertexBuffer[i] *= _scaleFactor; } mesh.SetVertices(vertexBuffer); if (_swapUvs) { var uv = mesh.uv; var uv2 = mesh.uv2; mesh.uv = uv2; mesh.uv2 = uv2; } if (_importNormals == GLTFImporterNormals.None) { mesh.normals = new Vector3[0]; } if (_importNormals == GLTFImporterNormals.Calculate && mesh.GetTopology(0) == MeshTopology.Triangles) { mesh.RecalculateNormals(); } mesh.UploadMeshData(!_readWriteEnabled); if (_generateColliders) { var collider = mf.gameObject.AddComponent<MeshCollider>(); collider.sharedMesh = mesh; } if (meshHash.Add(mesh)) { var meshName = string.IsNullOrEmpty(mesh.name) ? mf.gameObject.name : mesh.name; mesh.name = ObjectNames.GetUniqueName(meshNames.ToArray(), meshName); meshNames.Add(mesh.name); } return mesh; }).ToArray(); var renderers = gltfScene.GetComponentsInChildren<Renderer>(); if (_importMaterials) { // Get materials var materialNames = new List<string>(); var materialHash = new HashSet<UnityEngine.Material>(); var materials = renderers.SelectMany(r => { return r.sharedMaterials.Select(mat => { if (materialHash.Add(mat)) { var matName = string.IsNullOrEmpty(mat.name) ? mat.shader.name : mat.name; if (matName == mat.shader.name) { matName = matName.Substring(Mathf.Min(matName.LastIndexOf("/") + 1, matName.Length - 1)); } // Ensure name is unique matName = string.Format("{0} {1}", sceneName, ObjectNames.NicifyVariableName(matName)); matName = ObjectNames.GetUniqueName(materialNames.ToArray(), matName); mat.name = matName; materialNames.Add(matName); } return mat; }); }).ToArray(); // Get textures var textureNames = new List<string>(); var textureHash = new HashSet<Texture2D>(); var texMaterialMap = new Dictionary<Texture2D, List<TexMaterialMap>>(); var textures = materials.SelectMany(mat => { var shader = mat.shader; if (!shader) return Enumerable.Empty<Texture2D>(); var matTextures = new List<Texture2D>(); for (var i = 0; i < ShaderUtil.GetPropertyCount(shader); ++i) { if (ShaderUtil.GetPropertyType(shader, i) == ShaderUtil.ShaderPropertyType.TexEnv) { var propertyName = ShaderUtil.GetPropertyName(shader, i); var tex = mat.GetTexture(propertyName) as Texture2D; if (tex) { if (textureHash.Add(tex)) { var texName = tex.name; if (string.IsNullOrEmpty(texName)) { if (propertyName.StartsWith("_")) texName = propertyName.Substring(Mathf.Min(1, propertyName.Length - 1)); } // Ensure name is unique texName = string.Format("{0} {1}", sceneName, ObjectNames.NicifyVariableName(texName)); texName = ObjectNames.GetUniqueName(textureNames.ToArray(), texName); tex.name = texName; textureNames.Add(texName); matTextures.Add(tex); } List<TexMaterialMap> materialMaps; if (!texMaterialMap.TryGetValue(tex, out materialMaps)) { materialMaps = new List<TexMaterialMap>(); texMaterialMap.Add(tex, materialMaps); } materialMaps.Add(new TexMaterialMap(mat, propertyName, propertyName == "_BumpMap")); } } } return matTextures; }).ToArray(); var folderName = Path.GetDirectoryName(ctx.assetPath); // Save textures as separate assets and rewrite refs // TODO: Support for other texture types if (textures.Length > 0) { var texturesRoot = string.Concat(folderName, "/", "Textures/"); Directory.CreateDirectory(texturesRoot); foreach (var tex in textures) { var ext = _useJpgTextures ? ".jpg" : ".png"; var texPath = string.Concat(texturesRoot, tex.name, ext); File.WriteAllBytes(texPath, _useJpgTextures ? tex.EncodeToJPG() : tex.EncodeToPNG()); AssetDatabase.ImportAsset(texPath); } } // Save materials as separate assets and rewrite refs if (materials.Length > 0) { var materialRoot = string.Concat(folderName, "/", "Materials/"); Directory.CreateDirectory(materialRoot); foreach (var mat in materials) { var materialPath = string.Concat(materialRoot, mat.name, ".mat"); var newMat = mat; CopyOrNew(mat, materialPath, m => { // Fix references newMat = m; foreach (var r in renderers) { var sharedMaterials = r.sharedMaterials; for (var i = 0; i < sharedMaterials.Length; ++i) { var sharedMaterial = sharedMaterials[i]; if (sharedMaterial.name == mat.name) sharedMaterials[i] = m; } sharedMaterials = sharedMaterials.Where(sm => sm).ToArray(); r.sharedMaterials = sharedMaterials; } }); // Fix textures // HACK: This needs to be a delayed call. // Unity needs a frame to kick off the texture import so we can rewrite the ref if (textures.Length > 0) { EditorApplication.delayCall += () => { for (var i = 0; i < textures.Length; ++i) { var tex = textures[i]; var texturesRoot = string.Concat(folderName, "/", "Textures/"); var ext = _useJpgTextures ? ".jpg" : ".png"; var texPath = string.Concat(texturesRoot, tex.name, ext); // Grab new imported texture var materialMaps = texMaterialMap[tex]; var importer = (TextureImporter)TextureImporter.GetAtPath(texPath); var importedTex = AssetDatabase.LoadAssetAtPath<Texture2D>(texPath); if (importer != null) { var isNormalMap = false; foreach (var materialMap in materialMaps) { if (materialMap.Material == mat) { isNormalMap |= materialMap.IsNormalMap; newMat.SetTexture(materialMap.Property, importedTex); } }; if (isNormalMap) { // Try to auto-detect normal maps importer.textureType = TextureImporterType.NormalMap; } else if (importer.textureType == TextureImporterType.Sprite) { // Force disable sprite mode, even for 2D projects importer.textureType = TextureImporterType.Default; } importer.SaveAndReimport(); } else { Debug.LogWarning("GLTFImporter: Unable to import texture from path reference"); } } }; } } } } else { var temp = GameObject.CreatePrimitive(PrimitiveType.Plane); temp.SetActive(false); var defaultMat = new[] { temp.GetComponent<Renderer>().sharedMaterial }; DestroyImmediate(temp); foreach (var rend in renderers) { rend.sharedMaterials = defaultMat; } } } catch { if (gltfScene) DestroyImmediate(gltfScene); throw; } #if UNITY_2017_3_OR_NEWER // Set main asset ctx.AddObjectToAsset("main asset", gltfScene); // Add meshes foreach (var mesh in meshes) { ctx.AddObjectToAsset("mesh " + mesh.name, mesh); } ctx.SetMainObject(gltfScene); #else // Set main asset ctx.SetMainAsset("main asset", gltfScene); // Add meshes foreach (var mesh in meshes) { ctx.AddSubAsset("mesh " + mesh.name, mesh); } #endif } private GameObject CreateGLTFScene(string projectFilePath) { var importOptions = new ImportOptions { DataLoader = new FileLoader(Path.GetDirectoryName(projectFilePath)), }; using (var stream = File.OpenRead(projectFilePath)) { GLTFRoot gLTFRoot; GLTFParser.ParseJson(stream, out gLTFRoot); stream.Position = 0; // Make sure the read position is changed back to the beginning of the file var loader = new GLTFSceneImporter(gLTFRoot, stream, importOptions); loader.MaximumLod = _maximumLod; loader.IsMultithreaded = true; loader.LoadSceneAsync().Wait(); return loader.LastLoadedScene; } } private void CopyOrNew<T>(T asset, string assetPath, Action<T> replaceReferences) where T : Object { var existingAsset = AssetDatabase.LoadAssetAtPath<T>(assetPath); if (existingAsset) { EditorUtility.CopySerialized(asset, existingAsset); replaceReferences(existingAsset); return; } AssetDatabase.CreateAsset(asset, assetPath); } private class TexMaterialMap { public UnityEngine.Material Material { get; set; } public string Property { get; set; } public bool IsNormalMap { get; set; } public TexMaterialMap(UnityEngine.Material material, string property, bool isNormalMap) { Material = material; Property = property; IsNormalMap = isNormalMap; } } } } #endif
/* Copyright(c) Microsoft Open Technologies, Inc. All rights reserved. The MIT License(MIT) 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; using System.Net.Http; using Windows.Foundation.Collections; using Windows.ApplicationModel.Background; using Windows.ApplicationModel.AppService; using Windows.System.Threading; using Windows.Networking.Sockets; using System.IO; using Windows.Storage.Streams; using System.Threading.Tasks; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; namespace WebServerTask { public sealed class WebServerBGTask : IBackgroundTask { public void Run(IBackgroundTaskInstance taskInstance) { // Associate a cancellation handler with the background task. taskInstance.Canceled += OnCanceled; // Get the deferral object from the task instance serviceDeferral = taskInstance.GetDeferral(); var appService = taskInstance.TriggerDetails as AppServiceTriggerDetails; if (appService != null && appService.Name == "App2AppComService") { appServiceConnection = appService.AppServiceConnection; appServiceConnection.RequestReceived += OnRequestReceived; } } private async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args) { var message = args.Request.Message; string command = message["Command"] as string; switch (command) { case "Initialize": { var messageDeferral = args.GetDeferral(); //Set a result to return to the caller var returnMessage = new ValueSet(); HttpServer server = new HttpServer(8000, appServiceConnection); IAsyncAction asyncAction = Windows.System.Threading.ThreadPool.RunAsync( (workItem) => { server.StartServer(); }); returnMessage.Add("Status", "Success"); var responseStatus = await args.Request.SendResponseAsync(returnMessage); messageDeferral.Complete(); break; } case "Quit": { //Service was asked to quit. Give us service deferral //so platform can terminate the background task serviceDeferral.Complete(); break; } } } private void OnCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason) { //Clean up and get ready to exit } BackgroundTaskDeferral serviceDeferral; AppServiceConnection appServiceConnection; } public sealed class HttpServer : IDisposable { string offHtmlString = "<html><head><title>Blinky App</title></head><body><form action=\"blinky.html\" method=\"GET\"><input type=\"radio\" name=\"state\" value=\"on\" onclick=\"this.form.submit()\"> On<br><input type=\"radio\" name=\"state\" value=\"off\" checked onclick=\"this.form.submit()\"> Off</form></body></html>"; string onHtmlString = "<html><head><title>Blinky App</title></head><body><form action=\"blinky.html\" method=\"GET\"><input type=\"radio\" name=\"state\" value=\"on\" checked onclick=\"this.form.submit()\"> On<br><input type=\"radio\" name=\"state\" value=\"off\" onclick=\"this.form.submit()\"> Off</form></body></html>"; private const uint BufferSize = 8192; private int port = 8000; private readonly StreamSocketListener listener; private AppServiceConnection appServiceConnection; public HttpServer(int serverPort, AppServiceConnection appServiceConnection) { listener = new StreamSocketListener(); port = serverPort; appServiceConnection = appServiceConnection; listener.ConnectionReceived += (s, e) => ProcessRequestAsync(e.Socket); } public void StartServer() { #pragma warning disable CS4014 listener.BindServiceNameAsync(port.ToString()); #pragma warning restore CS4014 } public void Dispose() { listener.Dispose(); } private async void ProcessRequestAsync(StreamSocket socket) { // this works for text only StringBuilder request = new StringBuilder(); using (IInputStream input = socket.InputStream) { byte[] data = new byte[BufferSize]; IBuffer buffer = data.AsBuffer(); uint dataRead = BufferSize; while (dataRead == BufferSize) { await input.ReadAsync(buffer, BufferSize, InputStreamOptions.Partial); request.Append(Encoding.UTF8.GetString(data, 0, data.Length)); dataRead = buffer.Length; } } using (IOutputStream output = socket.OutputStream) { string requestMethod = request.ToString().Split('\n')[0]; string[] requestParts = requestMethod.Split(' '); if (requestParts[0] == "GET") await WriteResponseAsync(requestParts[1], output); else throw new InvalidDataException("HTTP method not supported: " + requestParts[0]); } } private async Task WriteResponseAsync(string request, IOutputStream os) { // See if the request is for blinky.html, if yes get the new state string state = "Unspecified"; bool stateChanged = false; if (request.Contains("blinky.html?state=on")) { state = "On"; stateChanged = true; } else if (request.Contains("blinky.html?state=off")) { state = "Off"; stateChanged = true; } if (stateChanged) { var updateMessage = new ValueSet(); updateMessage.Add("State", state); var responseStatus = await appServiceConnection.SendMessageAsync(updateMessage); } string html = state == "On" ? onHtmlString : offHtmlString; // Show the html using (Stream resp = os.AsStreamForWrite()) { // Look in the Data subdirectory of the app package byte[] bodyArray = Encoding.UTF8.GetBytes(html); MemoryStream stream = new MemoryStream(bodyArray); string header = String.Format("HTTP/1.1 200 OK\r\n" + "Content-Length: {0}\r\n" + "Connection: close\r\n\r\n", stream.Length); byte[] headerArray = Encoding.UTF8.GetBytes(header); await resp.WriteAsync(headerArray, 0, headerArray.Length); await stream.CopyToAsync(resp); await resp.FlushAsync(); } } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if MONO namespace NLog.Internal.FileAppenders { using System; using System.Collections; using System.Collections.Specialized; using System.IO; using System.Security; using System.Text; using System.Threading; using System.Xml; using NLog; using NLog.Common; using NLog.Config; using NLog.Internal; using Mono.Unix; using Mono.Unix.Native; /// <summary> /// Provides a multiprocess-safe atomic file appends while /// keeping the files open. /// </summary> /// <remarks> /// On Unix you can get all the appends to be atomic, even when multiple /// processes are trying to write to the same file, because setting the file /// pointer to the end of the file and appending can be made one operation. /// </remarks> [SecuritySafeCritical] internal class UnixMultiProcessFileAppender : BaseMutexFileAppender { private UnixStream _file; public static readonly IFileAppenderFactory TheFactory = new Factory(); private class Factory : IFileAppenderFactory { BaseFileAppender IFileAppenderFactory.Open(string fileName, ICreateFileParameters parameters) { return new UnixMultiProcessFileAppender(fileName, parameters); } } public UnixMultiProcessFileAppender(string fileName, ICreateFileParameters parameters) : base(fileName, parameters) { UnixFileInfo fileInfo = null; bool fileExists = false; try { fileInfo = new UnixFileInfo(fileName); fileExists = fileInfo.Exists; } catch { } int fd = Syscall.open(fileName, OpenFlags.O_CREAT | OpenFlags.O_WRONLY | OpenFlags.O_APPEND, (FilePermissions)(6 | (6 << 3) | (6 << 6))); if (fd == -1) { if (Stdlib.GetLastError() == Errno.ENOENT && parameters.CreateDirs) { string dirName = Path.GetDirectoryName(fileName); if (!Directory.Exists(dirName) && parameters.CreateDirs) Directory.CreateDirectory(dirName); fd = Syscall.open(fileName, OpenFlags.O_CREAT | OpenFlags.O_WRONLY | OpenFlags.O_APPEND, (FilePermissions)(6 | (6 << 3) | (6 << 6))); } } if (fd == -1) UnixMarshal.ThrowExceptionForLastError(); try { _file = new UnixStream(fd, true); long filePosition = _file.Position; if (fileExists || filePosition > 0) { if (fileInfo != null) { CreationTimeUtc = FileInfoHelper.LookupValidFileCreationTimeUtc(fileInfo, (f) => File.GetCreationTimeUtc(f.FullName), (f) => { f.Refresh(); return f.LastStatusChangeTimeUtc; }, (f) => DateTime.UtcNow).Value; } else { CreationTimeUtc = FileInfoHelper.LookupValidFileCreationTimeUtc(fileName, (f) => File.GetCreationTimeUtc(f), (f) => DateTime.UtcNow).Value; } } else { // We actually created the file and eventually concurrent processes CreationTimeUtc = DateTime.UtcNow; File.SetCreationTimeUtc(FileName, CreationTimeUtc); } } catch { Syscall.close(fd); throw; } } /// <summary> /// Writes the specified bytes. /// </summary> /// <param name="bytes">The bytes array.</param> /// <param name="offset">The bytes array offset.</param> /// <param name="count">The number of bytes.</param> public override void Write(byte[] bytes, int offset, int count) { if (_file == null) return; _file.Write(bytes, offset, count); } /// <summary> /// Closes this instance. /// </summary> public override void Close() { if (_file == null) return; InternalLogger.Trace("Closing '{0}'", FileName); try { _file?.Close(); } catch (Exception ex) { // Swallow exception as the file-stream now is in final state (broken instead of closed) InternalLogger.Warn(ex, "Failed to close file '{0}'", FileName); System.Threading.Thread.Sleep(1); // Artificial delay to avoid hammering a bad file location } finally { _file = null; } } /// <summary> /// Gets the creation time for a file associated with the appender. The time returned is in Coordinated Universal /// Time [UTC] standard. /// </summary> /// <returns>The file creation time.</returns> public override DateTime? GetFileCreationTimeUtc() { return CreationTimeUtc; // File is kept open, so creation time is static } /// <summary> /// Gets the length in bytes of the file associated with the appender. /// </summary> /// <returns>A long value representing the length of the file in bytes.</returns> public override long? GetFileLength() { FileInfo fileInfo = new FileInfo(FileName); if (!fileInfo.Exists) return null; return fileInfo.Length; } public override void Flush() { // do nothing, the stream is always flushed } } } #endif
using System; using System.Collections.Generic; // ReSharper disable InconsistentNaming // These names are based on error codes. #pragma warning disable 1591 namespace Soothsharp.Translation { /// <summary> /// This class contains static constants that represent the various errors and warnings Sootsharp might generate. /// <para> /// Error codes 100-199 are translation errors that mean that a program cannot be translated into Silver. /// </para> /// <para> /// Error codes 200-299 are verification warnings that mean that the backend does not guarantee correctness of the code. /// </para> /// <para> /// Error codes 300-399 are internal errors of the transcompiler. /// </para> /// </summary> public class Diagnostics { // *********************************** 100 Translation Errors public static SoothsharpDiagnostic SSIL101_UnknownNode = SoothsharpDiagnostic.Create( "SSIL101", "The Soothsharp translator does not support elements of the syntax kind '{0}'.", "A syntax node of this kind cannot be translated by the Soothsharp translator because the feature it provides is unavailable in Viper, or because it is difficult to translate. If you can use a less advanced construct, please do so.", DiagnosticSeverity.Error); public static SoothsharpDiagnostic SSIL102_UnexpectedNode = SoothsharpDiagnostic.Create( "SSIL102", "An element of the syntax kind '{0}' is not expected at this code location.", "While the Soothsharp translator might otherwise be able to handle this kind of C# nodes, this is not a place where it is able to do so. There may be an error in your C# syntax (check compiler errors) or you may be using C# features that the translator does not understand.", DiagnosticSeverity.Error); public static SoothsharpDiagnostic SSIL103_ExceptionConstructingCSharp = SoothsharpDiagnostic.Create( "SSIL103", "An exception ('{0}') occured during the construction of the C# abstract syntax tree.", "While this is an internal error of the translator, it mostly occurs when there is a C# syntax or semantic error in your code. Try to fix any other compiler errors and maybe this issue will be resolved.", DiagnosticSeverity.Error); public static SoothsharpDiagnostic SSIL104_ExceptionConstructingSilver = SoothsharpDiagnostic.Create( "SSIL104", "An exception ('{0}') occured during the construction of the Viper abstract syntax tree.", "While this is an internal error of the translator, it mostly occurs when there is a C# syntax or semantic error in your code. Try to fix any other compiler errors and maybe this issue will be resolved.", DiagnosticSeverity.Error); // ReSharper disable once UnusedMember.Global - kept for compatibility and future-proofing public static SoothsharpDiagnostic SSIL105_FeatureNotYetSupported = SoothsharpDiagnostic.Create( "SSIL105", "This feature ({0}) is not yet supported.", "As the C#-to-Viper translation project is developed, we plan to allow this feature to be used in verifiable C# class files. For now, however, it is unsupported and won't work.", DiagnosticSeverity.Error); public static SoothsharpDiagnostic SSIL106_TypeNotSupported = SoothsharpDiagnostic.Create( "SSIL106", "The type {0} is not supported in Viper.", "The Viper language can only use an integer, a boolean and reference objects. Other value types besides these three cannot be translated.", DiagnosticSeverity.Error); public static SoothsharpDiagnostic SSIL107_ThisExpressionCannotBeStatement = SoothsharpDiagnostic.Create( "SSIL107", "This expression cannot form an expression statement in Viper.", "The Viper language does not support this expression as a standalone expression in a statement, even if C# supported it.", DiagnosticSeverity.Error); public static SoothsharpDiagnostic SSIL108_FeatureNotSupported = SoothsharpDiagnostic.Create( "SSIL108", "This feature ({0}) is not supported.", "This feature of C# is not supported by the translator, and will probably never be supported. Could you please try to replace it with less advanced C# features?", DiagnosticSeverity.Error); public static SoothsharpDiagnostic SSIL109_FeatureNotSupportedBecauseSilver = SoothsharpDiagnostic.Create( "SSIL109", "This feature ({0}) is not supported by Viper.", "This feature of C# cannot be meaningfully represented in Viper.", DiagnosticSeverity.Error); public static SoothsharpDiagnostic SSIL110_InvalidSyntax = SoothsharpDiagnostic.Create( "SSIL110", "Syntax is invalid ({0}).", "This feature of C# cannot be meaningfully represented in Viper.", DiagnosticSeverity.Error); // ReSharper disable once UnusedMember.Global - kept for compatibility public static SoothsharpDiagnostic SSIL111_NonStatement = SoothsharpDiagnostic.Create( "SSIL111", "\"{0}\" is not a statement silvernode.", "", DiagnosticSeverity.Error); public static SoothsharpDiagnostic SSIL112_FileNotFound = SoothsharpDiagnostic.Create( "SSIL112", "A C# file or reference could not be loaded ({0})", "", DiagnosticSeverity.Error); public static SoothsharpDiagnostic SSIL113_VerificationSettingsContradiction = SoothsharpDiagnostic.Create( "SSIL113", "This is marked both [Verified] and [Unverified]. Which do you want?", "", DiagnosticSeverity.Error); public static SoothsharpDiagnostic SSIL114_NotPureContext = SoothsharpDiagnostic.Create( "SSIL114", "This ({0}) cannot be translated into a pure assertion.", "In this context, C# code is forced to be translated into pure Viper assertions. However, this C# node cannot be translated in a pure way.", DiagnosticSeverity.Error); // This error no longer ever triggers -- all integers are now converted to Int, without regard to their size in C# public static SoothsharpDiagnostic SSIL115_ThisIntegerSizeNotSupported = SoothsharpDiagnostic.Create( "SSIL115", "[deprecated error] Use System.Int32 instead of {0}.", "[no longer true] The Viper language's integers are unbounded. To prevent confusion, use only 'System.Int32' integers, please. Your actual used type wouldn't matter anyway, since Viper does not check for overflow or underflow.", DiagnosticSeverity.Error); public static SoothsharpDiagnostic SSIL116_MethodAttributeContradiction = SoothsharpDiagnostic.Create( "SSIL116", "Constructors and predicates cannot be declared [Pure].", "The [Pure] attribute causes the C# method to be translated as a Viper function. Viper predicates can't be functions. Constructors, in the transcompiler's view, also cannot be functions.", DiagnosticSeverity.Error); public static SoothsharpDiagnostic SSIL117_ConstructorMustNotBeAbstract = SoothsharpDiagnostic.Create( "SSIL117", "Constructors cannot be declared [Abstract].", "", DiagnosticSeverity.Error); public static SoothsharpDiagnostic SSIL118_FunctionsMustHaveAReturnType = SoothsharpDiagnostic.Create( "SSIL118", "Methods declared [Pure] must have a non-void return type.", "In Viper, functions always return a value. Methods with the [Pure] attribute are translated as a functions and thus can't have the void return type. ", DiagnosticSeverity.Error); public static SoothsharpDiagnostic SSIL119_PredicateMustBeBool = SoothsharpDiagnostic.Create( "SSIL119", "Methods declared [Predicate] must have the boolean return type.", "Methods with the [Predicate] attribute are translated as Viper predicates. Predicates are either spatial or boolean - either way, the return type must be System.Boolean.", DiagnosticSeverity.Error); public static SoothsharpDiagnostic SSIL120_UndeclaredNameReferenced = SoothsharpDiagnostic.Create( "SSIL120", "Code references the name '{0}' which was not declared.", "This error would usually mean that you're using a reference that was not given to the transcompiler or that there is an error in the transcompiler.", DiagnosticSeverity.Error); public static SoothsharpDiagnostic SSIL121_FunctionsAndPredicatesCannotHaveStatements = SoothsharpDiagnostic.Create( "SSIL121", "Methods declared [Pure] or [Predicate] may only contain return statements and contracts.", "A method thus declared is translated to a Viper function or predicate. These constructs may have bodies, but these bodies must contain an assertion only, not statements. This is why only contracts (such as Contract.Ensures(...)) and a single return statement are permitted here.", DiagnosticSeverity.Error); public static SoothsharpDiagnostic SSIL122_FunctionsAndPredicatesCannotHaveMoreThanOneReturnStatement = SoothsharpDiagnostic.Create( "SSIL122", "Methods declared [Pure] or [Predicate] must have exactly one return statement.", "A method thus declared is translated to a Viper function or predicate. These constructs may have bodies, but these bodies must contain an assertion only, not statements. There can't be any statements, and the single return statement is translated as a Viper assertion. There can't be more than one.", DiagnosticSeverity.Error); public static SoothsharpDiagnostic SSIL123_ThereIsThisCSharpError = SoothsharpDiagnostic.Create( "SSIL123", "A C# compiler diagnostic prevents correct translation: {0}", "Only valid C# programs can be translated to Viper. Fix any errors offered by the C# compiler, then attempt translation again.", DiagnosticSeverity.Error); public static SoothsharpDiagnostic SSIL124_QuantifierMustGetLambda = SoothsharpDiagnostic.Create( "SSIL124", "Quantifiers must have a lambda function as an argument.", "The contents of the lambda function are converted into Viper code. You cannot use a non-lambda function here.", DiagnosticSeverity.Error); public static SoothsharpDiagnostic SSIL125_LambdasMustHaveSingleParameter = SoothsharpDiagnostic.Create( "SSIL125", "Lambda functions must have a single parameter.", "Soothsharp does not allow for lambda functions with more than one parameter.", DiagnosticSeverity.Error); public static SoothsharpDiagnostic SSIL126_LambdasMustBeExpressions = SoothsharpDiagnostic.Create( "SSIL126", "Lambda functions must have an expression body.", "Soothsharp does not allow for lambda functions with statement (full) bodies, the body of the function must an expression.", DiagnosticSeverity.Error); public static SoothsharpDiagnostic SSIL127_LambdasOnlyInContracts = SoothsharpDiagnostic.Create( "SSIL127", "Lambda functions can only occur within quantifiers.", "Soothsharp does not allow for use of arbitrary lambda functions - you may only use these within quantifiers for syntactic purposes.", DiagnosticSeverity.Error); public static SoothsharpDiagnostic SSIL128_IndexersAreOnlyForSeqsAndArrays = SoothsharpDiagnostic.Create( "SSIL128", "Element access works only for Seq types and for arrays.", "", DiagnosticSeverity.Error); public static SoothsharpDiagnostic SSIL129_MethodContractsAreOnlyForMethods = SoothsharpDiagnostic.Create( "SSIL129", "Method contracts (Requires and Ensures) must be in a method body, outside of any inner blocks or loops.", "It is an error for a Requires or Ensures call to be within a loop. Only invariants are contracts permitted within a loop.", DiagnosticSeverity.Error); public static SoothsharpDiagnostic SSIL130_InvariantsAreOnlyForLoops= SoothsharpDiagnostic.Create( "SSIL130", "Invariants must be within loops.", "It is an error for an Invariant call to be elsewhere than within the code block of a loop (for, while or do).", DiagnosticSeverity.Error); // TODO (future): Expand this diagnostic so that it triggers more consistently (not just for binary expressions, but assignments, method calls...) public static SoothsharpDiagnostic SSIL131_AssignmentsNotInsideExpressions = SoothsharpDiagnostic.Create( "SSIL131", "Assignment expressions must be outermost.", "In Viper, expressions with side-effects (such as an assignment) are statements and so can't be within other expressions.", DiagnosticSeverity.Error); // ****************************** 200 Backend Verifier Errors public static SoothsharpDiagnostic SSIL201_BackendNotFound = SoothsharpDiagnostic.Create( "SSIL201", "Back-end ({0}) not found.", "The back-end chosen to verify the translated Viper code was not found in PATH nor in the local directory and so the code was not verified.", DiagnosticSeverity.Warning); public static SoothsharpDiagnostic SSIL202_BackendUnknownLine = SoothsharpDiagnostic.Create( "SSIL202", "Backend: {0}", "This line was returned by the backend but Soothsharp does not recognize it.", DiagnosticSeverity.Warning); public static SoothsharpDiagnostic SSIL203_ParseError = SoothsharpDiagnostic.Create( "SSIL203", "Viper parse error: {0}", "This C# code was transformed into a Viper segment that does not conform to Viper grammar and therefore the code could not be verified. This should not ordinarily happen and indicates an error in the Sootsharp transcompiler.", DiagnosticSeverity.Warning); public static SoothsharpDiagnostic SSIL204_OtherLocalizedError = SoothsharpDiagnostic.Create( "SSIL204", "{0}", "", DiagnosticSeverity.Warning); public static SoothsharpDiagnostic SSIL205_NoErrorsFoundLineNotFound = SoothsharpDiagnostic.Create( "SSIL205", "Verification failed for an unknown reason.", "The verifier did not return any errors but it did not certify that the code is correct. This may happen if you don't have Java, Z3 or Boogie installed or if the verifier is set up incorrectly.", DiagnosticSeverity.Warning); // ****************************** 300 Internal Errors public static SoothsharpDiagnostic SSIL301_InternalLocalizedError = SoothsharpDiagnostic.Create( "SSIL301", "The transcompiler encountered an internal error ({0}) while parsing this.", "Try to remove the infringing C# code fragment. You may be forced to make do without that C# feature. You can also submit this as a bug report as this error should never be displayed to the user normally.", DiagnosticSeverity.Error); // ReSharper disable once UnusedMember.Global - kept for futureproofing public static SoothsharpDiagnostic SSIL302_InternalError = SoothsharpDiagnostic.Create( "SSIL302", "The transcompiler encountered an internal error ({0}).", "Try to undo your most recent change to the code as it may be triggering this error. You may be forced to make do without that C# feature. You can also submit this as a bug report as this error should never be displayed to the user normally.", DiagnosticSeverity.Error); /// <summary> /// Gets all error descriptions that might be outputted by Soothsharp. /// </summary> public static IEnumerable<SoothsharpDiagnostic> GetAllDiagnostics() { Type t = typeof(Diagnostics); var fs = t.GetFields(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public); foreach(var f in fs) { object diagnostic = f.GetValue(null); yield return diagnostic as SoothsharpDiagnostic; } } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Text; using Reporting.Rdl; namespace Reporting.RdlDesign { /// <summary> /// Summary description for DialogDataSourceRef. /// </summary> public class DialogDataSourceRef : System.Windows.Forms.Form { private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox tbPassword; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox tbFilename; private System.Windows.Forms.Button bGetFilename; private System.Windows.Forms.Label label3; private System.Windows.Forms.ComboBox cbDataProvider; private System.Windows.Forms.Label label4; private System.Windows.Forms.TextBox tbConnection; private System.Windows.Forms.CheckBox ckbIntSecurity; private System.Windows.Forms.Label label5; private System.Windows.Forms.TextBox tbPrompt; private System.Windows.Forms.Button bOK; private System.Windows.Forms.Button bCancel; private System.Windows.Forms.TextBox tbPassword2; private System.Windows.Forms.Label label6; private System.Windows.Forms.Button bTestConnection; private System.Windows.Forms.ComboBox cbOdbcNames; private System.Windows.Forms.Label lODBC; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public DialogDataSourceRef() { // // Required for Windows Form Designer support // InitializeComponent(); string[] items = RdlEngineConfig.GetProviders(); cbDataProvider.Items.AddRange(items); this.cbDataProvider.SelectedIndex = 0; this.bOK.Enabled = false; } /// <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 Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.tbPassword = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.tbFilename = new System.Windows.Forms.TextBox(); this.bGetFilename = new System.Windows.Forms.Button(); this.label3 = new System.Windows.Forms.Label(); this.cbDataProvider = new System.Windows.Forms.ComboBox(); this.label4 = new System.Windows.Forms.Label(); this.tbConnection = new System.Windows.Forms.TextBox(); this.ckbIntSecurity = new System.Windows.Forms.CheckBox(); this.label5 = new System.Windows.Forms.Label(); this.tbPrompt = new System.Windows.Forms.TextBox(); this.bOK = new System.Windows.Forms.Button(); this.bCancel = new System.Windows.Forms.Button(); this.tbPassword2 = new System.Windows.Forms.TextBox(); this.label6 = new System.Windows.Forms.Label(); this.bTestConnection = new System.Windows.Forms.Button(); this.cbOdbcNames = new System.Windows.Forms.ComboBox(); this.lODBC = new System.Windows.Forms.Label(); this.SuspendLayout(); // // label1 // this.label1.Location = new System.Drawing.Point(8, 16); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(440, 32); this.label1.TabIndex = 0; this.label1.Text = "Enter (twice) a pass phrase used to encrypt the data source reference file. You" + " should use the same password you\'ve used to create previous files, as only one " + "can be used."; // // tbPassword // this.tbPassword.Location = new System.Drawing.Point(16, 56); this.tbPassword.Name = "tbPassword"; this.tbPassword.PasswordChar = '*'; this.tbPassword.Size = new System.Drawing.Size(184, 20); this.tbPassword.TabIndex = 0; this.tbPassword.Text = ""; this.tbPassword.TextChanged += new System.EventHandler(this.validate_TextChanged); // // label2 // this.label2.Location = new System.Drawing.Point(8, 88); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(408, 16); this.label2.TabIndex = 4; this.label2.Text = "Enter the file name that will hold the encrypted data source information"; // // tbFilename // this.tbFilename.Location = new System.Drawing.Point(16, 112); this.tbFilename.Name = "tbFilename"; this.tbFilename.Size = new System.Drawing.Size(392, 20); this.tbFilename.TabIndex = 2; this.tbFilename.Text = ""; this.tbFilename.TextChanged += new System.EventHandler(this.validate_TextChanged); // // bGetFilename // this.bGetFilename.Location = new System.Drawing.Point(424, 112); this.bGetFilename.Name = "bGetFilename"; this.bGetFilename.Size = new System.Drawing.Size(24, 23); this.bGetFilename.TabIndex = 3; this.bGetFilename.Text = "..."; this.bGetFilename.Click += new System.EventHandler(this.bGetFilename_Click); // // label3 // this.label3.Location = new System.Drawing.Point(8, 152); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(80, 23); this.label3.TabIndex = 7; this.label3.Text = "Data provider"; // // cbDataProvider // this.cbDataProvider.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbDataProvider.Location = new System.Drawing.Point(80, 152); this.cbDataProvider.Name = "cbDataProvider"; this.cbDataProvider.Size = new System.Drawing.Size(104, 21); this.cbDataProvider.TabIndex = 4; this.cbDataProvider.SelectedIndexChanged += new System.EventHandler(this.cbDataProvider_SelectedIndexChanged); // // label4 // this.label4.Location = new System.Drawing.Point(8, 192); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(100, 16); this.label4.TabIndex = 10; this.label4.Text = "Connection string"; // // tbConnection // this.tbConnection.Location = new System.Drawing.Point(16, 216); this.tbConnection.Multiline = true; this.tbConnection.Name = "tbConnection"; this.tbConnection.Size = new System.Drawing.Size(424, 40); this.tbConnection.TabIndex = 7; this.tbConnection.Text = ""; this.tbConnection.TextChanged += new System.EventHandler(this.validate_TextChanged); // // ckbIntSecurity // this.ckbIntSecurity.Location = new System.Drawing.Point(296, 184); this.ckbIntSecurity.Name = "ckbIntSecurity"; this.ckbIntSecurity.Size = new System.Drawing.Size(144, 24); this.ckbIntSecurity.TabIndex = 6; this.ckbIntSecurity.Text = "Use integrated security"; // // label5 // this.label5.Location = new System.Drawing.Point(8, 272); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(432, 16); this.label5.TabIndex = 12; this.label5.Text = "(Optional) Enter the prompt displayed when asking for database credentials "; // // tbPrompt // this.tbPrompt.Location = new System.Drawing.Point(16, 296); this.tbPrompt.Name = "tbPrompt"; this.tbPrompt.Size = new System.Drawing.Size(424, 20); this.tbPrompt.TabIndex = 8; this.tbPrompt.Text = ""; // // bOK // this.bOK.Location = new System.Drawing.Point(272, 344); this.bOK.Name = "bOK"; this.bOK.TabIndex = 10; this.bOK.Text = "OK"; this.bOK.Click += new System.EventHandler(this.bOK_Click); // // bCancel // this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.bCancel.Location = new System.Drawing.Point(368, 344); this.bCancel.Name = "bCancel"; this.bCancel.TabIndex = 11; this.bCancel.Text = "Cancel"; // // tbPassword2 // this.tbPassword2.Location = new System.Drawing.Point(256, 56); this.tbPassword2.Name = "tbPassword2"; this.tbPassword2.PasswordChar = '*'; this.tbPassword2.Size = new System.Drawing.Size(184, 20); this.tbPassword2.TabIndex = 1; this.tbPassword2.Text = ""; this.tbPassword2.TextChanged += new System.EventHandler(this.validate_TextChanged); // // label6 // this.label6.Location = new System.Drawing.Point(208, 64); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(48, 23); this.label6.TabIndex = 2; this.label6.Text = "Repeat"; // // bTestConnection // this.bTestConnection.Location = new System.Drawing.Point(16, 344); this.bTestConnection.Name = "bTestConnection"; this.bTestConnection.Size = new System.Drawing.Size(96, 23); this.bTestConnection.TabIndex = 9; this.bTestConnection.Text = "Test Connection"; this.bTestConnection.Click += new System.EventHandler(this.bTestConnection_Click); // // cbOdbcNames // this.cbOdbcNames.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbOdbcNames.Location = new System.Drawing.Point(296, 152); this.cbOdbcNames.Name = "cbOdbcNames"; this.cbOdbcNames.Size = new System.Drawing.Size(152, 21); this.cbOdbcNames.Sorted = true; this.cbOdbcNames.TabIndex = 5; this.cbOdbcNames.SelectedIndexChanged += new System.EventHandler(this.cbOdbcNames_SelectedIndexChanged); // // lODBC // this.lODBC.Location = new System.Drawing.Point(184, 152); this.lODBC.Name = "lODBC"; this.lODBC.Size = new System.Drawing.Size(112, 23); this.lODBC.TabIndex = 17; this.lODBC.Text = "ODBC Data Sources"; // // DialogDataSourceRef // this.AcceptButton = this.bOK; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this.bCancel; this.ClientSize = new System.Drawing.Size(456, 374); this.Controls.Add(this.cbOdbcNames); this.Controls.Add(this.lODBC); this.Controls.Add(this.bTestConnection); this.Controls.Add(this.label6); this.Controls.Add(this.tbPassword2); this.Controls.Add(this.bCancel); this.Controls.Add(this.bOK); this.Controls.Add(this.tbPrompt); this.Controls.Add(this.label5); this.Controls.Add(this.ckbIntSecurity); this.Controls.Add(this.tbConnection); this.Controls.Add(this.label4); this.Controls.Add(this.cbDataProvider); this.Controls.Add(this.label3); this.Controls.Add(this.bGetFilename); this.Controls.Add(this.tbFilename); this.Controls.Add(this.label2); this.Controls.Add(this.tbPassword); this.Controls.Add(this.label1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "DialogDataSourceRef"; this.ShowInTaskbar = false; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Create Data Source Reference File"; this.ResumeLayout(false); } #endregion private void bGetFilename_Click(object sender, System.EventArgs e) { SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "Data source reference files (*.dsr)|*.dsr" + "|All files (*.*)|*.*"; sfd.FilterIndex = 1; if (tbFilename.Text.Length > 0) sfd.FileName = tbFilename.Text; else sfd.FileName = "*.dsr"; sfd.Title = "Specify Data Source Reference File Name"; sfd.OverwritePrompt = true; sfd.DefaultExt = "dsr"; sfd.AddExtension = true; try { if (sfd.ShowDialog() == DialogResult.OK) tbFilename.Text = sfd.FileName; } finally { sfd.Dispose(); } } private void validate_TextChanged(object sender, System.EventArgs e) { if (this.tbFilename.Text.Length > 0 && this.tbPassword.Text.Length > 0 && this.tbPassword.Text == this.tbPassword2.Text && this.tbConnection.Text.Length > 0) bOK.Enabled = true; else bOK.Enabled = false; return; } private void bOK_Click(object sender, System.EventArgs e) { // Build the ConnectionProperties XML StringBuilder sb = new StringBuilder(); sb.Append("<ConnectionProperties>"); sb.AppendFormat("<DataProvider>{0}</DataProvider>", this.cbDataProvider.Text); sb.AppendFormat("<ConnectString>{0}</ConnectString>", this.tbConnection.Text.Replace("<", "&lt;")); sb.AppendFormat("<IntegratedSecurity>{0}</IntegratedSecurity>", this.ckbIntSecurity.Checked? "true": "false"); if (this.tbPrompt.Text.Length > 0) sb.AppendFormat("<Prompt>{0}</Prompt>", this.tbPrompt.Text.Replace("<", "&lt;")); sb.Append("</ConnectionProperties>"); try { Rdl.DataSourceReference.Create(tbFilename.Text, sb.ToString(), tbPassword.Text); } catch (Exception ex) { MessageBox.Show(ex.Message, "Unable to create data source reference file"); return; } DialogResult = DialogResult.OK; } private void bTestConnection_Click(object sender, System.EventArgs e) { if (DesignerUtility.TestConnection(this.cbDataProvider.Text, tbConnection.Text)) MessageBox.Show("Connection succeeded!", "Test Connection"); } private void cbDataProvider_SelectedIndexChanged(object sender, System.EventArgs e) { if (cbDataProvider.Text == "ODBC") { lODBC.Visible = cbOdbcNames.Visible = true; DesignerUtility.FillOdbcNames(cbOdbcNames); } else { lODBC.Visible = cbOdbcNames.Visible = false; } } private void cbOdbcNames_SelectedIndexChanged(object sender, System.EventArgs e) { tbConnection.Text = "dsn=" + cbOdbcNames.Text + ";"; } } }
using System.Collections; using Gnu.MP.BrickCoinProtocol.BouncyCastle.Asn1.X9; using Gnu.MP.BrickCoinProtocol.BouncyCastle.Math; using Gnu.MP.BrickCoinProtocol.BouncyCastle.Math.EC; using Gnu.MP.BrickCoinProtocol.BouncyCastle.Math.EC.Endo; using Gnu.MP.BrickCoinProtocol.BouncyCastle.Utilities; using Gnu.MP.BrickCoinProtocol.BouncyCastle.Utilities.Encoders; namespace Gnu.MP.BrickCoinProtocol.BouncyCastle.Asn1.Sec { internal sealed class SecNamedCurves { private SecNamedCurves() { } private static ECCurve ConfigureCurve(ECCurve curve) { return curve; } private static ECCurve ConfigureCurveGlv(ECCurve c, GlvTypeBParameters p) { return c.Configure().SetEndomorphism(new GlvTypeBEndomorphism(c, p)).Create(); } private static BigInteger FromHex(string hex) { return new BigInteger(1, Hex.Decode(hex)); } /* * secp112r1 */ internal class Secp112r1Holder : X9ECParametersHolder { private Secp112r1Holder() { } internal static readonly X9ECParametersHolder Instance = new Secp112r1Holder(); protected override X9ECParameters CreateParameters() { // p = (2^128 - 3) / 76439 BigInteger p = FromHex("DB7C2ABF62E35E668076BEAD208B"); BigInteger a = FromHex("DB7C2ABF62E35E668076BEAD2088"); BigInteger b = FromHex("659EF8BA043916EEDE8911702B22"); byte[] S = Hex.Decode("00F50B028E4D696E676875615175290472783FB1"); BigInteger n = FromHex("DB7C2ABF62E35E7628DFAC6561C5"); BigInteger h = BigInteger.One; ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h)); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "09487239995A5EE76B55F9C2F098" + "A89CE5AF8724C0A23E0E0FF77500")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp112r2 */ internal class Secp112r2Holder : X9ECParametersHolder { private Secp112r2Holder() { } internal static readonly X9ECParametersHolder Instance = new Secp112r2Holder(); protected override X9ECParameters CreateParameters() { // p = (2^128 - 3) / 76439 BigInteger p = FromHex("DB7C2ABF62E35E668076BEAD208B"); BigInteger a = FromHex("6127C24C05F38A0AAAF65C0EF02C"); BigInteger b = FromHex("51DEF1815DB5ED74FCC34C85D709"); byte[] S = Hex.Decode("002757A1114D696E6768756151755316C05E0BD4"); BigInteger n = FromHex("36DF0AAFD8B8D7597CA10520D04B"); BigInteger h = BigInteger.ValueOf(4); ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h)); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "4BA30AB5E892B4E1649DD0928643" + "ADCD46F5882E3747DEF36E956E97")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp128r1 */ internal class Secp128r1Holder : X9ECParametersHolder { private Secp128r1Holder() { } internal static readonly X9ECParametersHolder Instance = new Secp128r1Holder(); protected override X9ECParameters CreateParameters() { // p = 2^128 - 2^97 - 1 BigInteger p = FromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF"); BigInteger a = FromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC"); BigInteger b = FromHex("E87579C11079F43DD824993C2CEE5ED3"); byte[] S = Hex.Decode("000E0D4D696E6768756151750CC03A4473D03679"); BigInteger n = FromHex("FFFFFFFE0000000075A30D1B9038A115"); BigInteger h = BigInteger.One; ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h)); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "161FF7528B899B2D0C28607CA52C5B86" + "CF5AC8395BAFEB13C02DA292DDED7A83")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp128r2 */ internal class Secp128r2Holder : X9ECParametersHolder { private Secp128r2Holder() { } internal static readonly X9ECParametersHolder Instance = new Secp128r2Holder(); protected override X9ECParameters CreateParameters() { // p = 2^128 - 2^97 - 1 BigInteger p = FromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF"); BigInteger a = FromHex("D6031998D1B3BBFEBF59CC9BBFF9AEE1"); BigInteger b = FromHex("5EEEFCA380D02919DC2C6558BB6D8A5D"); byte[] S = Hex.Decode("004D696E67687561517512D8F03431FCE63B88F4"); BigInteger n = FromHex("3FFFFFFF7FFFFFFFBE0024720613B5A3"); BigInteger h = BigInteger.ValueOf(4); ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h)); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "7B6AA5D85E572983E6FB32A7CDEBC140" + "27B6916A894D3AEE7106FE805FC34B44")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp160k1 */ internal class Secp160k1Holder : X9ECParametersHolder { private Secp160k1Holder() { } internal static readonly X9ECParametersHolder Instance = new Secp160k1Holder(); protected override X9ECParameters CreateParameters() { // p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73"); BigInteger a = BigInteger.Zero; BigInteger b = BigInteger.ValueOf(7); byte[] S = null; BigInteger n = FromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3"); BigInteger h = BigInteger.One; GlvTypeBParameters glv = new GlvTypeBParameters( new BigInteger("9ba48cba5ebcb9b6bd33b92830b2a2e0e192f10a", 16), new BigInteger("c39c6c3b3a36d7701b9c71a1f5804ae5d0003f4", 16), new BigInteger[]{ new BigInteger("9162fbe73984472a0a9e", 16), new BigInteger("-96341f1138933bc2f505", 16) }, new BigInteger[]{ new BigInteger("127971af8721782ecffa3", 16), new BigInteger("9162fbe73984472a0a9e", 16) }, new BigInteger("9162fbe73984472a0a9d0590", 16), new BigInteger("96341f1138933bc2f503fd44", 16), 176); ECCurve curve = ConfigureCurveGlv(new FpCurve(p, a, b, n, h), glv); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB" + "938CF935318FDCED6BC28286531733C3F03C4FEE")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp160r1 */ internal class Secp160r1Holder : X9ECParametersHolder { private Secp160r1Holder() { } internal static readonly X9ECParametersHolder Instance = new Secp160r1Holder(); protected override X9ECParameters CreateParameters() { // p = 2^160 - 2^31 - 1 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF"); BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC"); BigInteger b = FromHex("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45"); byte[] S = Hex.Decode("1053CDE42C14D696E67687561517533BF3F83345"); BigInteger n = FromHex("0100000000000000000001F4C8F927AED3CA752257"); BigInteger h = BigInteger.One; ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h)); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "4A96B5688EF573284664698968C38BB913CBFC82" + "23A628553168947D59DCC912042351377AC5FB32")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp160r2 */ internal class Secp160r2Holder : X9ECParametersHolder { private Secp160r2Holder() { } internal static readonly X9ECParametersHolder Instance = new Secp160r2Holder(); protected override X9ECParameters CreateParameters() { // p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73"); BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC70"); BigInteger b = FromHex("B4E134D3FB59EB8BAB57274904664D5AF50388BA"); byte[] S = Hex.Decode("B99B99B099B323E02709A4D696E6768756151751"); BigInteger n = FromHex("0100000000000000000000351EE786A818F3A1A16B"); BigInteger h = BigInteger.One; ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h)); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "52DCB034293A117E1F4FF11B30F7199D3144CE6D" + "FEAFFEF2E331F296E071FA0DF9982CFEA7D43F2E")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp192k1 */ internal class Secp192k1Holder : X9ECParametersHolder { private Secp192k1Holder() { } internal static readonly X9ECParametersHolder Instance = new Secp192k1Holder(); protected override X9ECParameters CreateParameters() { // p = 2^192 - 2^32 - 2^12 - 2^8 - 2^7 - 2^6 - 2^3 - 1 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37"); BigInteger a = BigInteger.Zero; BigInteger b = BigInteger.ValueOf(3); byte[] S = null; BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D"); BigInteger h = BigInteger.One; GlvTypeBParameters glv = new GlvTypeBParameters( new BigInteger("bb85691939b869c1d087f601554b96b80cb4f55b35f433c2", 16), new BigInteger("3d84f26c12238d7b4f3d516613c1759033b1a5800175d0b1", 16), new BigInteger[]{ new BigInteger("71169be7330b3038edb025f1", 16), new BigInteger("-b3fb3400dec5c4adceb8655c", 16) }, new BigInteger[]{ new BigInteger("12511cfe811d0f4e6bc688b4d", 16), new BigInteger("71169be7330b3038edb025f1", 16) }, new BigInteger("71169be7330b3038edb025f1d0f9", 16), new BigInteger("b3fb3400dec5c4adceb8655d4c94", 16), 208); ECCurve curve = ConfigureCurveGlv(new FpCurve(p, a, b, n, h), glv); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D" + "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp192r1 */ internal class Secp192r1Holder : X9ECParametersHolder { private Secp192r1Holder() { } internal static readonly X9ECParametersHolder Instance = new Secp192r1Holder(); protected override X9ECParameters CreateParameters() { // p = 2^192 - 2^64 - 1 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF"); BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC"); BigInteger b = FromHex("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1"); byte[] S = Hex.Decode("3045AE6FC8422F64ED579528D38120EAE12196D5"); BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831"); BigInteger h = BigInteger.One; ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h)); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012" + "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp224k1 */ internal class Secp224k1Holder : X9ECParametersHolder { private Secp224k1Holder() { } internal static readonly X9ECParametersHolder Instance = new Secp224k1Holder(); protected override X9ECParameters CreateParameters() { // p = 2^224 - 2^32 - 2^12 - 2^11 - 2^9 - 2^7 - 2^4 - 2 - 1 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFE56D"); BigInteger a = BigInteger.Zero; BigInteger b = BigInteger.ValueOf(5); byte[] S = null; BigInteger n = FromHex("010000000000000000000000000001DCE8D2EC6184CAF0A971769FB1F7"); BigInteger h = BigInteger.One; GlvTypeBParameters glv = new GlvTypeBParameters( new BigInteger("fe0e87005b4e83761908c5131d552a850b3f58b749c37cf5b84d6768", 16), new BigInteger("60dcd2104c4cbc0be6eeefc2bdd610739ec34e317f9b33046c9e4788", 16), new BigInteger[]{ new BigInteger("6b8cf07d4ca75c88957d9d670591", 16), new BigInteger("-b8adf1378a6eb73409fa6c9c637d", 16) }, new BigInteger[]{ new BigInteger("1243ae1b4d71613bc9f780a03690e", 16), new BigInteger("6b8cf07d4ca75c88957d9d670591", 16) }, new BigInteger("6b8cf07d4ca75c88957d9d67059037a4", 16), new BigInteger("b8adf1378a6eb73409fa6c9c637ba7f5", 16), 240); ECCurve curve = ConfigureCurveGlv(new FpCurve(p, a, b, n, h), glv); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "A1455B334DF099DF30FC28A169A467E9E47075A90F7E650EB6B7A45C" + "7E089FED7FBA344282CAFBD6F7E319F7C0B0BD59E2CA4BDB556D61A5")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp224r1 */ internal class Secp224r1Holder : X9ECParametersHolder { private Secp224r1Holder() { } internal static readonly X9ECParametersHolder Instance = new Secp224r1Holder(); protected override X9ECParameters CreateParameters() { // p = 2^224 - 2^96 + 1 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001"); BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE"); BigInteger b = FromHex("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4"); byte[] S = Hex.Decode("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5"); BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D"); BigInteger h = BigInteger.One; ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h)); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21" + "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp256k1 */ internal class Secp256k1Holder : X9ECParametersHolder { private Secp256k1Holder() { } internal static readonly X9ECParametersHolder Instance = new Secp256k1Holder(); protected override X9ECParameters CreateParameters() { // p = 2^256 - 2^32 - 2^9 - 2^8 - 2^7 - 2^6 - 2^4 - 1 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"); BigInteger a = BigInteger.Zero; BigInteger b = BigInteger.ValueOf(7); byte[] S = null; BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"); BigInteger h = BigInteger.One; GlvTypeBParameters glv = new GlvTypeBParameters( new BigInteger("7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee", 16), new BigInteger("5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72", 16), new BigInteger[]{ new BigInteger("3086d221a7d46bcde86c90e49284eb15", 16), new BigInteger("-e4437ed6010e88286f547fa90abfe4c3", 16) }, new BigInteger[]{ new BigInteger("114ca50f7a8e2f3f657c1108d9d44cfd8", 16), new BigInteger("3086d221a7d46bcde86c90e49284eb15", 16) }, new BigInteger("3086d221a7d46bcde86c90e49284eb153dab", 16), new BigInteger("e4437ed6010e88286f547fa90abfe4c42212", 16), 272); ECCurve curve = ConfigureCurveGlv(new FpCurve(p, a, b, n, h), glv); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798" + "483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp256r1 */ internal class Secp256r1Holder : X9ECParametersHolder { private Secp256r1Holder() { } internal static readonly X9ECParametersHolder Instance = new Secp256r1Holder(); protected override X9ECParameters CreateParameters() { // p = 2^224 (2^32 - 1) + 2^192 + 2^96 - 1 BigInteger p = FromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF"); BigInteger a = FromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC"); BigInteger b = FromHex("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B"); byte[] S = Hex.Decode("C49D360886E704936A6678E1139D26B7819F7E90"); BigInteger n = FromHex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"); BigInteger h = BigInteger.One; ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h)); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296" + "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp384r1 */ internal class Secp384r1Holder : X9ECParametersHolder { private Secp384r1Holder() { } internal static readonly X9ECParametersHolder Instance = new Secp384r1Holder(); protected override X9ECParameters CreateParameters() { // p = 2^384 - 2^128 - 2^96 + 2^32 - 1 BigInteger p = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF"); BigInteger a = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC"); BigInteger b = FromHex("B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF"); byte[] S = Hex.Decode("A335926AA319A27A1D00896A6773A4827ACDAC73"); BigInteger n = FromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973"); BigInteger h = BigInteger.One; ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h)); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7" + "3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F")); return new X9ECParameters(curve, G, n, h, S); } } /* * secp521r1 */ internal class Secp521r1Holder : X9ECParametersHolder { private Secp521r1Holder() { } internal static readonly X9ECParametersHolder Instance = new Secp521r1Holder(); protected override X9ECParameters CreateParameters() { // p = 2^521 - 1 BigInteger p = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"); BigInteger a = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC"); BigInteger b = FromHex("0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00"); byte[] S = Hex.Decode("D09E8800291CB85396CC6717393284AAA0DA64BA"); BigInteger n = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409"); BigInteger h = BigInteger.One; ECCurve curve = ConfigureCurve(new FpCurve(p, a, b, n, h)); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66" + "011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect113r1 */ internal class Sect113r1Holder : X9ECParametersHolder { private Sect113r1Holder() { } internal static readonly X9ECParametersHolder Instance = new Sect113r1Holder(); private const int m = 113; private const int k = 9; protected override X9ECParameters CreateParameters() { BigInteger a = FromHex("003088250CA6E7C7FE649CE85820F7"); BigInteger b = FromHex("00E8BEE4D3E2260744188BE0E9C723"); byte[] S = Hex.Decode("10E723AB14D696E6768756151756FEBF8FCB49A9"); BigInteger n = FromHex("0100000000000000D9CCEC8A39E56F"); BigInteger h = BigInteger.ValueOf(2); ECCurve curve = new F2mCurve(m, k, a, b, n, h); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "009D73616F35F4AB1407D73562C10F" + "00A52830277958EE84D1315ED31886")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect113r2 */ internal class Sect113r2Holder : X9ECParametersHolder { private Sect113r2Holder() { } internal static readonly X9ECParametersHolder Instance = new Sect113r2Holder(); private const int m = 113; private const int k = 9; protected override X9ECParameters CreateParameters() { BigInteger a = FromHex("00689918DBEC7E5A0DD6DFC0AA55C7"); BigInteger b = FromHex("0095E9A9EC9B297BD4BF36E059184F"); byte[] S = Hex.Decode("10C0FB15760860DEF1EEF4D696E676875615175D"); BigInteger n = FromHex("010000000000000108789B2496AF93"); BigInteger h = BigInteger.ValueOf(2); ECCurve curve = new F2mCurve(m, k, a, b, n, h); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "01A57A6A7B26CA5EF52FCDB8164797" + "00B3ADC94ED1FE674C06E695BABA1D")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect131r1 */ internal class Sect131r1Holder : X9ECParametersHolder { private Sect131r1Holder() { } internal static readonly X9ECParametersHolder Instance = new Sect131r1Holder(); private const int m = 131; private const int k1 = 2; private const int k2 = 3; private const int k3 = 8; protected override X9ECParameters CreateParameters() { BigInteger a = FromHex("07A11B09A76B562144418FF3FF8C2570B8"); BigInteger b = FromHex("0217C05610884B63B9C6C7291678F9D341"); byte[] S = Hex.Decode("4D696E676875615175985BD3ADBADA21B43A97E2"); BigInteger n = FromHex("0400000000000000023123953A9464B54D"); BigInteger h = BigInteger.ValueOf(2); ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "0081BAF91FDF9833C40F9C181343638399" + "078C6E7EA38C001F73C8134B1B4EF9E150")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect131r2 */ internal class Sect131r2Holder : X9ECParametersHolder { private Sect131r2Holder() { } internal static readonly X9ECParametersHolder Instance = new Sect131r2Holder(); private const int m = 131; private const int k1 = 2; private const int k2 = 3; private const int k3 = 8; protected override X9ECParameters CreateParameters() { BigInteger a = FromHex("03E5A88919D7CAFCBF415F07C2176573B2"); BigInteger b = FromHex("04B8266A46C55657AC734CE38F018F2192"); byte[] S = Hex.Decode("985BD3ADBAD4D696E676875615175A21B43A97E3"); BigInteger n = FromHex("0400000000000000016954A233049BA98F"); BigInteger h = BigInteger.ValueOf(2); ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "0356DCD8F2F95031AD652D23951BB366A8" + "0648F06D867940A5366D9E265DE9EB240F")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect163k1 */ internal class Sect163k1Holder : X9ECParametersHolder { private Sect163k1Holder() { } internal static readonly X9ECParametersHolder Instance = new Sect163k1Holder(); private const int m = 163; private const int k1 = 3; private const int k2 = 6; private const int k3 = 7; protected override X9ECParameters CreateParameters() { BigInteger a = BigInteger.One; BigInteger b = BigInteger.One; byte[] S = null; BigInteger n = FromHex("04000000000000000000020108A2E0CC0D99F8A5EF"); BigInteger h = BigInteger.ValueOf(2); ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "02FE13C0537BBC11ACAA07D793DE4E6D5E5C94EEE8" + "0289070FB05D38FF58321F2E800536D538CCDAA3D9")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect163r1 */ internal class Sect163r1Holder : X9ECParametersHolder { private Sect163r1Holder() { } internal static readonly X9ECParametersHolder Instance = new Sect163r1Holder(); private const int m = 163; private const int k1 = 3; private const int k2 = 6; private const int k3 = 7; protected override X9ECParameters CreateParameters() { BigInteger a = FromHex("07B6882CAAEFA84F9554FF8428BD88E246D2782AE2"); BigInteger b = FromHex("0713612DCDDCB40AAB946BDA29CA91F73AF958AFD9"); byte[] S = Hex.Decode("24B7B137C8A14D696E6768756151756FD0DA2E5C"); BigInteger n = FromHex("03FFFFFFFFFFFFFFFFFFFF48AAB689C29CA710279B"); BigInteger h = BigInteger.ValueOf(2); ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "0369979697AB43897789566789567F787A7876A654" + "00435EDB42EFAFB2989D51FEFCE3C80988F41FF883")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect163r2 */ internal class Sect163r2Holder : X9ECParametersHolder { private Sect163r2Holder() { } internal static readonly X9ECParametersHolder Instance = new Sect163r2Holder(); private const int m = 163; private const int k1 = 3; private const int k2 = 6; private const int k3 = 7; protected override X9ECParameters CreateParameters() { BigInteger a = BigInteger.One; BigInteger b = FromHex("020A601907B8C953CA1481EB10512F78744A3205FD"); byte[] S = Hex.Decode("85E25BFE5C86226CDB12016F7553F9D0E693A268"); BigInteger n = FromHex("040000000000000000000292FE77E70C12A4234C33"); BigInteger h = BigInteger.ValueOf(2); ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "03F0EBA16286A2D57EA0991168D4994637E8343E36" + "00D51FBC6C71A0094FA2CDD545B11C5C0C797324F1")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect193r1 */ internal class Sect193r1Holder : X9ECParametersHolder { private Sect193r1Holder() { } internal static readonly X9ECParametersHolder Instance = new Sect193r1Holder(); private const int m = 193; private const int k = 15; protected override X9ECParameters CreateParameters() { BigInteger a = FromHex("0017858FEB7A98975169E171F77B4087DE098AC8A911DF7B01"); BigInteger b = FromHex("00FDFB49BFE6C3A89FACADAA7A1E5BBC7CC1C2E5D831478814"); byte[] S = Hex.Decode("103FAEC74D696E676875615175777FC5B191EF30"); BigInteger n = FromHex("01000000000000000000000000C7F34A778F443ACC920EBA49"); BigInteger h = BigInteger.ValueOf(2); ECCurve curve = new F2mCurve(m, k, a, b, n, h); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "01F481BC5F0FF84A74AD6CDF6FDEF4BF6179625372D8C0C5E1" + "0025E399F2903712CCF3EA9E3A1AD17FB0B3201B6AF7CE1B05")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect193r2 */ internal class Sect193r2Holder : X9ECParametersHolder { private Sect193r2Holder() { } internal static readonly X9ECParametersHolder Instance = new Sect193r2Holder(); private const int m = 193; private const int k = 15; protected override X9ECParameters CreateParameters() { BigInteger a = FromHex("0163F35A5137C2CE3EA6ED8667190B0BC43ECD69977702709B"); BigInteger b = FromHex("00C9BB9E8927D4D64C377E2AB2856A5B16E3EFB7F61D4316AE"); byte[] S = Hex.Decode("10B7B4D696E676875615175137C8A16FD0DA2211"); BigInteger n = FromHex("010000000000000000000000015AAB561B005413CCD4EE99D5"); BigInteger h = BigInteger.ValueOf(2); ECCurve curve = new F2mCurve(m, k, a, b, n, h); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "00D9B67D192E0367C803F39E1A7E82CA14A651350AAE617E8F" + "01CE94335607C304AC29E7DEFBD9CA01F596F927224CDECF6C")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect233k1 */ internal class Sect233k1Holder : X9ECParametersHolder { private Sect233k1Holder() { } internal static readonly X9ECParametersHolder Instance = new Sect233k1Holder(); private const int m = 233; private const int k = 74; protected override X9ECParameters CreateParameters() { BigInteger a = BigInteger.Zero; BigInteger b = BigInteger.One; byte[] S = null; BigInteger n = FromHex("8000000000000000000000000000069D5BB915BCD46EFB1AD5F173ABDF"); BigInteger h = BigInteger.ValueOf(4); ECCurve curve = new F2mCurve(m, k, a, b, n, h); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "017232BA853A7E731AF129F22FF4149563A419C26BF50A4C9D6EEFAD6126" + "01DB537DECE819B7F70F555A67C427A8CD9BF18AEB9B56E0C11056FAE6A3")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect233r1 */ internal class Sect233r1Holder : X9ECParametersHolder { private Sect233r1Holder() { } internal static readonly X9ECParametersHolder Instance = new Sect233r1Holder(); private const int m = 233; private const int k = 74; protected override X9ECParameters CreateParameters() { BigInteger a = BigInteger.One; BigInteger b = FromHex("0066647EDE6C332C7F8C0923BB58213B333B20E9CE4281FE115F7D8F90AD"); byte[] S = Hex.Decode("74D59FF07F6B413D0EA14B344B20A2DB049B50C3"); BigInteger n = FromHex("01000000000000000000000000000013E974E72F8A6922031D2603CFE0D7"); BigInteger h = BigInteger.ValueOf(2); ECCurve curve = new F2mCurve(m, k, a, b, n, h); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "00FAC9DFCBAC8313BB2139F1BB755FEF65BC391F8B36F8F8EB7371FD558B" + "01006A08A41903350678E58528BEBF8A0BEFF867A7CA36716F7E01F81052")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect239k1 */ internal class Sect239k1Holder : X9ECParametersHolder { private Sect239k1Holder() { } internal static readonly X9ECParametersHolder Instance = new Sect239k1Holder(); private const int m = 239; private const int k = 158; protected override X9ECParameters CreateParameters() { BigInteger a = BigInteger.Zero; BigInteger b = BigInteger.One; byte[] S = null; BigInteger n = FromHex("2000000000000000000000000000005A79FEC67CB6E91F1C1DA800E478A5"); BigInteger h = BigInteger.ValueOf(4); ECCurve curve = new F2mCurve(m, k, a, b, n, h); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "29A0B6A887A983E9730988A68727A8B2D126C44CC2CC7B2A6555193035DC" + "76310804F12E549BDB011C103089E73510ACB275FC312A5DC6B76553F0CA")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect283k1 */ internal class Sect283k1Holder : X9ECParametersHolder { private Sect283k1Holder() { } internal static readonly X9ECParametersHolder Instance = new Sect283k1Holder(); private const int m = 283; private const int k1 = 5; private const int k2 = 7; private const int k3 = 12; protected override X9ECParameters CreateParameters() { BigInteger a = BigInteger.Zero; BigInteger b = BigInteger.One; byte[] S = null; BigInteger n = FromHex("01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE9AE2ED07577265DFF7F94451E061E163C61"); BigInteger h = BigInteger.ValueOf(4); ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "0503213F78CA44883F1A3B8162F188E553CD265F23C1567A16876913B0C2AC2458492836" + "01CCDA380F1C9E318D90F95D07E5426FE87E45C0E8184698E45962364E34116177DD2259")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect283r1 */ internal class Sect283r1Holder : X9ECParametersHolder { private Sect283r1Holder() { } internal static readonly X9ECParametersHolder Instance = new Sect283r1Holder(); private const int m = 283; private const int k1 = 5; private const int k2 = 7; private const int k3 = 12; protected override X9ECParameters CreateParameters() { BigInteger a = BigInteger.One; BigInteger b = FromHex("027B680AC8B8596DA5A4AF8A19A0303FCA97FD7645309FA2A581485AF6263E313B79A2F5"); byte[] S = Hex.Decode("77E2B07370EB0F832A6DD5B62DFC88CD06BB84BE"); BigInteger n = FromHex("03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEF90399660FC938A90165B042A7CEFADB307"); BigInteger h = BigInteger.ValueOf(2); ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "05F939258DB7DD90E1934F8C70B0DFEC2EED25B8557EAC9C80E2E198F8CDBECD86B12053" + "03676854FE24141CB98FE6D4B20D02B4516FF702350EDDB0826779C813F0DF45BE8112F4")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect409k1 */ internal class Sect409k1Holder : X9ECParametersHolder { private Sect409k1Holder() { } internal static readonly X9ECParametersHolder Instance = new Sect409k1Holder(); private const int m = 409; private const int k = 87; protected override X9ECParameters CreateParameters() { BigInteger a = BigInteger.Zero; BigInteger b = BigInteger.One; byte[] S = null; BigInteger n = FromHex("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE5F83B2D4EA20400EC4557D5ED3E3E7CA5B4B5C83B8E01E5FCF"); BigInteger h = BigInteger.ValueOf(4); ECCurve curve = new F2mCurve(m, k, a, b, n, h); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "0060F05F658F49C1AD3AB1890F7184210EFD0987E307C84C27ACCFB8F9F67CC2C460189EB5AAAA62EE222EB1B35540CFE9023746" + "01E369050B7C4E42ACBA1DACBF04299C3460782F918EA427E6325165E9EA10E3DA5F6C42E9C55215AA9CA27A5863EC48D8E0286B")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect409r1 */ internal class Sect409r1Holder : X9ECParametersHolder { private Sect409r1Holder() { } internal static readonly X9ECParametersHolder Instance = new Sect409r1Holder(); private const int m = 409; private const int k = 87; protected override X9ECParameters CreateParameters() { BigInteger a = BigInteger.One; BigInteger b = FromHex("0021A5C2C8EE9FEB5C4B9A753B7B476B7FD6422EF1F3DD674761FA99D6AC27C8A9A197B272822F6CD57A55AA4F50AE317B13545F"); byte[] S = Hex.Decode("4099B5A457F9D69F79213D094C4BCD4D4262210B"); BigInteger n = FromHex("010000000000000000000000000000000000000000000000000001E2AAD6A612F33307BE5FA47C3C9E052F838164CD37D9A21173"); BigInteger h = BigInteger.ValueOf(2); ECCurve curve = new F2mCurve(m, k, a, b, n, h); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "015D4860D088DDB3496B0C6064756260441CDE4AF1771D4DB01FFE5B34E59703DC255A868A1180515603AEAB60794E54BB7996A7" + "0061B1CFAB6BE5F32BBFA78324ED106A7636B9C5A7BD198D0158AA4F5488D08F38514F1FDF4B4F40D2181B3681C364BA0273C706")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect571k1 */ internal class Sect571k1Holder : X9ECParametersHolder { private Sect571k1Holder() { } internal static readonly X9ECParametersHolder Instance = new Sect571k1Holder(); private const int m = 571; private const int k1 = 2; private const int k2 = 5; private const int k3 = 10; protected override X9ECParameters CreateParameters() { BigInteger a = BigInteger.Zero; BigInteger b = BigInteger.One; byte[] S = null; BigInteger n = FromHex("020000000000000000000000000000000000000000000000000000000000000000000000131850E1F19A63E4B391A8DB917F4138B630D84BE5D639381E91DEB45CFE778F637C1001"); BigInteger h = BigInteger.ValueOf(4); ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "026EB7A859923FBC82189631F8103FE4AC9CA2970012D5D46024804801841CA44370958493B205E647DA304DB4CEB08CBBD1BA39494776FB988B47174DCA88C7E2945283A01C8972" + "0349DC807F4FBF374F4AEADE3BCA95314DD58CEC9F307A54FFC61EFC006D8A2C9D4979C0AC44AEA74FBEBBB9F772AEDCB620B01A7BA7AF1B320430C8591984F601CD4C143EF1C7A3")); return new X9ECParameters(curve, G, n, h, S); } } /* * sect571r1 */ internal class Sect571r1Holder : X9ECParametersHolder { private Sect571r1Holder() { } internal static readonly X9ECParametersHolder Instance = new Sect571r1Holder(); private const int m = 571; private const int k1 = 2; private const int k2 = 5; private const int k3 = 10; protected override X9ECParameters CreateParameters() { BigInteger a = BigInteger.One; BigInteger b = FromHex("02F40E7E2221F295DE297117B7F3D62F5C6A97FFCB8CEFF1CD6BA8CE4A9A18AD84FFABBD8EFA59332BE7AD6756A66E294AFD185A78FF12AA520E4DE739BACA0C7FFEFF7F2955727A"); byte[] S = Hex.Decode("2AA058F73A0E33AB486B0F610410C53A7F132310"); BigInteger n = FromHex("03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE661CE18FF55987308059B186823851EC7DD9CA1161DE93D5174D66E8382E9BB2FE84E47"); BigInteger h = BigInteger.ValueOf(2); ECCurve curve = new F2mCurve(m, k1, k2, k3, a, b, n, h); X9ECPoint G = new X9ECPoint(curve, Hex.Decode("04" + "0303001D34B856296C16C0D40D3CD7750A93D1D2955FA80AA5F40FC8DB7B2ABDBDE53950F4C0D293CDD711A35B67FB1499AE60038614F1394ABFA3B4C850D927E1E7769C8EEC2D19" + "037BF27342DA639B6DCCFFFEB73D69D78C6C27A6009CBBCA1980F8533921E8A684423E43BAB08A576291AF8F461BB2A8B3531D2F0485C19B16E2F1516E23DD3C1A4827AF1B8AC15B")); return new X9ECParameters(curve, G, n, h, S); } } private static readonly IDictionary objIds = Platform.CreateHashtable(); private static readonly IDictionary curves = Platform.CreateHashtable(); private static readonly IDictionary names = Platform.CreateHashtable(); private static void DefineCurve( string name, DerObjectIdentifier oid, X9ECParametersHolder holder) { objIds.Add(Platform.ToUpperInvariant(name), oid); names.Add(oid, name); curves.Add(oid, holder); } static SecNamedCurves() { DefineCurve("secp112r1", SecObjectIdentifiers.SecP112r1, Secp112r1Holder.Instance); DefineCurve("secp112r2", SecObjectIdentifiers.SecP112r2, Secp112r2Holder.Instance); DefineCurve("secp128r1", SecObjectIdentifiers.SecP128r1, Secp128r1Holder.Instance); DefineCurve("secp128r2", SecObjectIdentifiers.SecP128r2, Secp128r2Holder.Instance); DefineCurve("secp160k1", SecObjectIdentifiers.SecP160k1, Secp160k1Holder.Instance); DefineCurve("secp160r1", SecObjectIdentifiers.SecP160r1, Secp160r1Holder.Instance); DefineCurve("secp160r2", SecObjectIdentifiers.SecP160r2, Secp160r2Holder.Instance); DefineCurve("secp192k1", SecObjectIdentifiers.SecP192k1, Secp192k1Holder.Instance); DefineCurve("secp192r1", SecObjectIdentifiers.SecP192r1, Secp192r1Holder.Instance); DefineCurve("secp224k1", SecObjectIdentifiers.SecP224k1, Secp224k1Holder.Instance); DefineCurve("secp224r1", SecObjectIdentifiers.SecP224r1, Secp224r1Holder.Instance); DefineCurve("secp256k1", SecObjectIdentifiers.SecP256k1, Secp256k1Holder.Instance); DefineCurve("secp256r1", SecObjectIdentifiers.SecP256r1, Secp256r1Holder.Instance); DefineCurve("secp384r1", SecObjectIdentifiers.SecP384r1, Secp384r1Holder.Instance); DefineCurve("secp521r1", SecObjectIdentifiers.SecP521r1, Secp521r1Holder.Instance); DefineCurve("sect113r1", SecObjectIdentifiers.SecT113r1, Sect113r1Holder.Instance); DefineCurve("sect113r2", SecObjectIdentifiers.SecT113r2, Sect113r2Holder.Instance); DefineCurve("sect131r1", SecObjectIdentifiers.SecT131r1, Sect131r1Holder.Instance); DefineCurve("sect131r2", SecObjectIdentifiers.SecT131r2, Sect131r2Holder.Instance); DefineCurve("sect163k1", SecObjectIdentifiers.SecT163k1, Sect163k1Holder.Instance); DefineCurve("sect163r1", SecObjectIdentifiers.SecT163r1, Sect163r1Holder.Instance); DefineCurve("sect163r2", SecObjectIdentifiers.SecT163r2, Sect163r2Holder.Instance); DefineCurve("sect193r1", SecObjectIdentifiers.SecT193r1, Sect193r1Holder.Instance); DefineCurve("sect193r2", SecObjectIdentifiers.SecT193r2, Sect193r2Holder.Instance); DefineCurve("sect233k1", SecObjectIdentifiers.SecT233k1, Sect233k1Holder.Instance); DefineCurve("sect233r1", SecObjectIdentifiers.SecT233r1, Sect233r1Holder.Instance); DefineCurve("sect239k1", SecObjectIdentifiers.SecT239k1, Sect239k1Holder.Instance); DefineCurve("sect283k1", SecObjectIdentifiers.SecT283k1, Sect283k1Holder.Instance); DefineCurve("sect283r1", SecObjectIdentifiers.SecT283r1, Sect283r1Holder.Instance); DefineCurve("sect409k1", SecObjectIdentifiers.SecT409k1, Sect409k1Holder.Instance); DefineCurve("sect409r1", SecObjectIdentifiers.SecT409r1, Sect409r1Holder.Instance); DefineCurve("sect571k1", SecObjectIdentifiers.SecT571k1, Sect571k1Holder.Instance); DefineCurve("sect571r1", SecObjectIdentifiers.SecT571r1, Sect571r1Holder.Instance); } public static X9ECParameters GetByName( string name) { DerObjectIdentifier oid = GetOid(name); return oid == null ? null : GetByOid(oid); } /** * return the X9ECParameters object for the named curve represented by * the passed in object identifier. Null if the curve isn't present. * * @param oid an object identifier representing a named curve, if present. */ public static X9ECParameters GetByOid( DerObjectIdentifier oid) { X9ECParametersHolder holder = (X9ECParametersHolder)curves[oid]; return holder == null ? null : holder.Parameters; } /** * return the object identifier signified by the passed in name. Null * if there is no object identifier associated with name. * * @return the object identifier associated with name, if present. */ public static DerObjectIdentifier GetOid( string name) { return (DerObjectIdentifier)objIds[Platform.ToUpperInvariant(name)]; } /** * return the named curve name represented by the given object identifier. */ public static string GetName( DerObjectIdentifier oid) { return (string)names[oid]; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System.Threading.Tasks; namespace System.Collections.Tests { public class Hashtable_SynchronizedTests { private Hashtable _hsh2; private int _iNumberOfElements = 20; [Fact] [OuterLoop] public void TestSynchronizedBasic() { Hashtable hsh1; string strValue; Task[] workers; Action ts1; int iNumberOfWorkers = 3; DictionaryEntry[] strValueArr; string[] strKeyArr; Hashtable hsh3; Hashtable hsh4; IDictionaryEnumerator idic; object oValue; //[]Vanila - Syncronized returns a wrapped HT. We must make sure that all the methods //are accounted for here for the wrapper hsh1 = new Hashtable(); for (int i = 0; i < _iNumberOfElements; i++) { hsh1.Add("Key_" + i, "Value_" + i); } _hsh2 = Hashtable.Synchronized(hsh1); //Count Assert.Equal(_hsh2.Count, hsh1.Count); //get/set item for (int i = 0; i < _iNumberOfElements; i++) { Assert.True(((string)_hsh2["Key_" + i]).Equals("Value_" + i)); } Assert.Throws<ArgumentNullException>(() => { oValue = _hsh2[null]; }); _hsh2.Clear(); for (int i = 0; i < _iNumberOfElements; i++) { _hsh2["Key_" + i] = "Value_" + i; } strValueArr = new DictionaryEntry[_hsh2.Count]; _hsh2.CopyTo(strValueArr, 0); //ContainsXXX hsh3 = new Hashtable(); for (int i = 0; i < _iNumberOfElements; i++) { Assert.True(_hsh2.Contains("Key_" + i)); Assert.True(_hsh2.ContainsKey("Key_" + i)); Assert.True(_hsh2.ContainsValue("Value_" + i)); //we still need a way to make sure that there are all these unique values here -see below code for that Assert.True(hsh1.ContainsValue(((DictionaryEntry)strValueArr[i]).Value)); hsh3.Add(strValueArr[i], null); } hsh4 = (Hashtable)_hsh2.Clone(); Assert.Equal(hsh4.Count, hsh1.Count); strValueArr = new DictionaryEntry[hsh4.Count]; hsh4.CopyTo(strValueArr, 0); //ContainsXXX hsh3 = new Hashtable(); for (int i = 0; i < _iNumberOfElements; i++) { Assert.True(hsh4.Contains("Key_" + i)); Assert.True(hsh4.ContainsKey("Key_" + i)); Assert.True(hsh4.ContainsValue("Value_" + i)); //we still need a way to make sure that there are all these unique values here -see below code for that Assert.True(hsh1.ContainsValue(((DictionaryEntry)strValueArr[i]).Value)); hsh3.Add(((DictionaryEntry)strValueArr[i]).Value, null); } Assert.False(hsh4.IsReadOnly); Assert.True(hsh4.IsSynchronized); //Phew, back to other methods idic = _hsh2.GetEnumerator(); hsh3 = new Hashtable(); hsh4 = new Hashtable(); while (idic.MoveNext()) { Assert.True(_hsh2.ContainsKey(idic.Key)); Assert.True(_hsh2.ContainsValue(idic.Value)); hsh3.Add(idic.Key, null); hsh4.Add(idic.Value, null); } hsh4 = (Hashtable)_hsh2.Clone(); strValueArr = new DictionaryEntry[hsh4.Count]; hsh4.CopyTo(strValueArr, 0); hsh3 = new Hashtable(); for (int i = 0; i < _iNumberOfElements; i++) { Assert.True(hsh4.Contains("Key_" + i)); Assert.True(hsh4.ContainsKey("Key_" + i)); Assert.True(hsh4.ContainsValue("Value_" + i)); //we still need a way to make sure that there are all these unique values here -see below code for that Assert.True(hsh1.ContainsValue(((DictionaryEntry)strValueArr[i]).Value)); hsh3.Add(((DictionaryEntry)strValueArr[i]).Value, null); } Assert.False(hsh4.IsReadOnly); Assert.True(hsh4.IsSynchronized); //Properties Assert.False(_hsh2.IsReadOnly); Assert.True(_hsh2.IsSynchronized); Assert.Equal(_hsh2.SyncRoot, hsh1.SyncRoot); //we will test the Keys & Values string[] strValueArr11 = new string[hsh1.Count]; strKeyArr = new string[hsh1.Count]; _hsh2.Keys.CopyTo(strKeyArr, 0); _hsh2.Values.CopyTo(strValueArr11, 0); hsh3 = new Hashtable(); hsh4 = new Hashtable(); for (int i = 0; i < _iNumberOfElements; i++) { Assert.True(_hsh2.ContainsKey(strKeyArr[i])); Assert.True(_hsh2.ContainsValue(strValueArr11[i])); hsh3.Add(strKeyArr[i], null); hsh4.Add(strValueArr11[i], null); } //now we test the modifying methods _hsh2.Remove("Key_1"); Assert.False(_hsh2.ContainsKey("Key_1")); Assert.False(_hsh2.ContainsValue("Value_1")); _hsh2.Add("Key_1", "Value_1"); Assert.True(_hsh2.ContainsKey("Key_1")); Assert.True(_hsh2.ContainsValue("Value_1")); _hsh2["Key_1"] = "Value_Modified_1"; Assert.True(_hsh2.ContainsKey("Key_1")); Assert.False(_hsh2.ContainsValue("Value_1")); /////////////////////////// Assert.True(_hsh2.ContainsValue("Value_Modified_1")); hsh3 = Hashtable.Synchronized(_hsh2); //we are not going through all of the above again:) we will just make sure that this syncrnized and that //values are there Assert.Equal(hsh3.Count, hsh1.Count); Assert.True(hsh3.IsSynchronized); _hsh2.Clear(); Assert.Equal(_hsh2.Count, 0); //[] Synchronized returns a HT that is thread safe // We will try to test this by getting a number of threads to write some items // to a synchronized IList hsh1 = new Hashtable(); _hsh2 = Hashtable.Synchronized(hsh1); workers = new Task[iNumberOfWorkers]; for (int i = 0; i < workers.Length; i++) { var name = "Thread worker " + i; ts1 = new Action(() => AddElements(name)); workers[i] = Task.Run(ts1); } Task.WaitAll(workers); //checking time Assert.Equal(_hsh2.Count, _iNumberOfElements * iNumberOfWorkers); for (int i = 0; i < iNumberOfWorkers; i++) { for (int j = 0; j < _iNumberOfElements; j++) { strValue = "Thread worker " + i + "_" + j; Assert.True(_hsh2.Contains(strValue)); } } //I dont think that we can make an assumption on the order of these items though //now we are going to remove all of these workers = new Task[iNumberOfWorkers]; for (int i = 0; i < workers.Length; i++) { var name = "Thread worker " + i; ts1 = new Action(() => RemoveElements(name)); workers[i] = Task.Run(ts1); } Task.WaitAll(workers); Assert.Equal(_hsh2.Count, 0); Assert.False(hsh1.IsSynchronized); Assert.True(_hsh2.IsSynchronized); //[] Tyr calling Synchronized with null Assert.Throws<ArgumentNullException>(() => { Hashtable.Synchronized(null); } ); } void AddElements(string strName) { for (int i = 0; i < _iNumberOfElements; i++) { _hsh2.Add(strName + "_" + i, "string_" + i); } } void RemoveElements(string strName) { for (int i = 0; i < _iNumberOfElements; i++) { _hsh2.Remove(strName + "_" + i); } } } }
//------------------------------------------------------------------------------ // <copyright file="TagPrefixInfo.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.Configuration { using System; using System.Xml; using System.Configuration; using System.Collections.Specialized; using System.Collections; using System.IO; using System.Text; using System.Web.Util; using System.Web.UI; using System.Web.Compilation; using System.Threading; using System.Web.Configuration; using System.Security.Permissions; public sealed class TagPrefixInfo : ConfigurationElement { private static readonly ConfigurationElementProperty s_elemProperty = new ConfigurationElementProperty(new CallbackValidator(typeof(TagPrefixInfo), Validate)); private static ConfigurationPropertyCollection _properties; private static readonly ConfigurationProperty _propTagPrefix = new ConfigurationProperty("tagPrefix", typeof(string), "/", null, StdValidatorsAndConverters.NonEmptyStringValidator, ConfigurationPropertyOptions.IsRequired); private static readonly ConfigurationProperty _propTagName = new ConfigurationProperty("tagName", typeof(string), String.Empty, null, null, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propNamespace = new ConfigurationProperty("namespace", typeof(string), String.Empty, null, null, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty _propAssembly = new ConfigurationProperty("assembly", typeof(string), String.Empty, null, null, ConfigurationPropertyOptions.IsAssemblyStringTransformationRequired); private static readonly ConfigurationProperty _propSource = new ConfigurationProperty("src", typeof(string), String.Empty, null, null, ConfigurationPropertyOptions.None); static TagPrefixInfo() { _properties = new ConfigurationPropertyCollection(); _properties.Add(_propTagPrefix); _properties.Add(_propTagName); _properties.Add(_propNamespace); _properties.Add(_propAssembly); _properties.Add(_propSource); } internal TagPrefixInfo() { } public TagPrefixInfo(String tagPrefix, String nameSpace, String assembly, String tagName, String source) : this() { TagPrefix = tagPrefix; Namespace = nameSpace; Assembly = assembly; TagName = tagName; Source = source; } public override bool Equals(object prefix) { TagPrefixInfo ns = prefix as TagPrefixInfo; return StringUtil.Equals(TagPrefix, ns.TagPrefix) && StringUtil.Equals(TagName, ns.TagName) && StringUtil.Equals(Namespace, ns.Namespace) && StringUtil.Equals(Assembly, ns.Assembly) && StringUtil.Equals(Source, ns.Source); } public override int GetHashCode() { return TagPrefix.GetHashCode() ^ TagName.GetHashCode() ^ Namespace.GetHashCode() ^ Assembly.GetHashCode() ^ Source.GetHashCode(); } protected override ConfigurationPropertyCollection Properties { get { return _properties; } } [ConfigurationProperty("tagPrefix", IsRequired = true, DefaultValue = "/")] [StringValidator(MinLength = 1)] public string TagPrefix { get { return (string)base[_propTagPrefix]; } set { base[_propTagPrefix] = value; } } [ConfigurationProperty("tagName")] public string TagName { get { return (string)base[_propTagName]; } set { base[_propTagName] = value; } } [ConfigurationProperty("namespace")] public string Namespace { get { return (string)base[_propNamespace]; } set { base[_propNamespace] = value; } } [ConfigurationProperty("assembly")] public string Assembly { get { return (string)base[_propAssembly]; } set { base[_propAssembly] = value; } } [ConfigurationProperty("src")] public string Source { get { return (string)base[_propSource]; } set { if (!String.IsNullOrEmpty(value)) { base[_propSource] = value; } else { base[_propSource] = null; } } } protected override ConfigurationElementProperty ElementProperty { get { return s_elemProperty; } } private static void Validate(object value) { if (value == null) { throw new ArgumentNullException("control"); } TagPrefixInfo elem = (TagPrefixInfo)value; if (System.Web.UI.Util.ContainsWhiteSpace(elem.TagPrefix)) { throw new ConfigurationErrorsException( SR.GetString(SR.Space_attribute, "tagPrefix")); } bool invalid = false; if (!String.IsNullOrEmpty(elem.Namespace)) { // It is a custom control if (!(String.IsNullOrEmpty(elem.TagName) && String.IsNullOrEmpty(elem.Source))) { invalid = true; } } else if (!String.IsNullOrEmpty(elem.TagName)) { // It is a user control if (!(String.IsNullOrEmpty(elem.Namespace) && String.IsNullOrEmpty(elem.Assembly) && !String.IsNullOrEmpty(elem.Source))) { invalid = true; } } else { invalid = true; } if (invalid) { throw new ConfigurationErrorsException( SR.GetString(SR.Invalid_tagprefix_entry)); } } } }
// TarBuffer.cs // Copyright (C) 2001 Mike Krueger // // 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; using System.IO; namespace ICSharpCode.SharpZipLib.Silverlight.Tar { /// <summary> /// The TarBuffer class implements the tar archive concept /// of a buffered input stream. This concept goes back to the /// days of blocked tape drives and special io devices. In the /// C# universe, the only real function that this class /// performs is to ensure that files have the correct "record" /// size, or other tars will complain. /// <p> /// You should never have a need to access this class directly. /// TarBuffers are created by Tar IO Streams. /// </p> /// </summary> public class TarBuffer { #region Constants /// <summary> /// The size of a block in a tar archive in bytes. /// </summary> /// <remarks>This is 512 bytes.</remarks> public const int BlockSize = 512; /// <summary> /// The number of blocks in a default record. /// </summary> /// <remarks> /// The default value is 20 blocks per record. /// </remarks> public const int DefaultBlockFactor = 20; /// <summary> /// The size in bytes of a default record. /// </summary> /// <remarks> /// The default size is 10KB. /// </remarks> public const int DefaultRecordSize = BlockSize*DefaultBlockFactor; #endregion /* A quote from GNU tar man file on blocking and records A `tar' archive file contains a series of blocks. Each block contains `BLOCKSIZE' bytes. Although this format may be thought of as being on magnetic tape, other media are often used. Each file archived is represented by a header block which describes the file, followed by zero or more blocks which give the contents of the file. At the end of the archive file there may be a block filled with binary zeros as an end-of-file marker. A reasonable system should write a block of zeros at the end, but must not assume that such a block exists when reading an archive. The blocks may be "blocked" for physical I/O operations. Each record of N blocks is written with a single 'write ()' operation. On magnetic tapes, the result of such a write is a single record. When writing an archive, the last record of blocks should be written at the full size, with blocks after the zero block containing all zeros. When reading an archive, a reasonable system should properly handle an archive whose last record is shorter than the rest, or which contains garbage records after a zero block. */ /// <summary> /// Construct a default TarBuffer /// </summary> protected TarBuffer() { } /// <summary> /// Get the record size for this buffer /// </summary> /// <value>The record size in bytes. /// This is equal to the <see cref="BlockFactor"/> multiplied by the <see cref="BlockSize"/></value> public int RecordSize { get { return recordSize; } } /// <summary> /// Get the Blocking factor for the buffer /// </summary> /// <value>This is the number of block in each record.</value> public int BlockFactor { get { return _blockFactor; } } /// <summary> /// Get the current block number, within the current record, zero based. /// </summary> public int CurrentBlock { get { return currentBlockIndex; } } /// <summary> /// Get the current record number. /// </summary> /// <returns> /// The current zero based record number. /// </returns> public int CurrentRecord { get { return currentRecordIndex; } } /// <summary> /// Get the TAR Buffer's record size. /// </summary> /// <returns>The record size in bytes. /// This is equal to the <see cref="BlockFactor"/> multiplied by the <see cref="BlockSize"/></returns> [Obsolete("Use RecordSize property instead")] public int GetRecordSize() { return recordSize; } /// <summary> /// Get the TAR Buffer's block factor /// </summary> /// <returns>The block factor; the number of blocks per record.</returns> [Obsolete("Use BlockFactor property instead")] public int GetBlockFactor() { return _blockFactor; } /// <summary> /// Create TarBuffer for reading with default BlockFactor /// </summary> /// <param name="inputStream">Stream to buffer</param> /// <returns>A new <see cref="TarBuffer"/> suitable for input.</returns> public static TarBuffer CreateInputTarBuffer(Stream inputStream) { if (inputStream == null) { throw new ArgumentNullException("inputStream"); } return CreateInputTarBuffer(inputStream, DefaultBlockFactor); } /// <summary> /// Construct TarBuffer for reading inputStream setting BlockFactor /// </summary> /// <param name="inputStream">Stream to buffer</param> /// <param name="blockFactor">Blocking factor to apply</param> /// <returns>A new <see cref="TarBuffer"/> suitable for input.</returns> public static TarBuffer CreateInputTarBuffer(Stream inputStream, int blockFactor) { if (inputStream == null) { throw new ArgumentNullException("inputStream"); } if (blockFactor <= 0) { throw new ArgumentOutOfRangeException("blockFactor", "Factor cannot be negative"); } var tarBuffer = new TarBuffer{inputStream = inputStream, outputStream = null}; tarBuffer.Initialize(blockFactor); return tarBuffer; } /// <summary> /// Construct TarBuffer for writing with default BlockFactor /// </summary> /// <param name="outputStream">output stream for buffer</param> /// <returns>A new <see cref="TarBuffer"/> suitable for output.</returns> public static TarBuffer CreateOutputTarBuffer(Stream outputStream) { if (outputStream == null) { throw new ArgumentNullException("outputStream"); } return CreateOutputTarBuffer(outputStream, DefaultBlockFactor); } /// <summary> /// Construct TarBuffer for writing Tar output to streams. /// </summary> /// <param name="outputStream">Output stream to write to.</param> /// <param name="blockFactor">Blocking factor to apply</param> /// <returns>A new <see cref="TarBuffer"/> suitable for output.</returns> public static TarBuffer CreateOutputTarBuffer(Stream outputStream, int blockFactor) { if (outputStream == null) { throw new ArgumentNullException("outputStream"); } if (blockFactor <= 0) { throw new ArgumentOutOfRangeException("blockFactor", "Factor cannot be negative"); } var tarBuffer = new TarBuffer{inputStream = null, outputStream = outputStream}; tarBuffer.Initialize(blockFactor); return tarBuffer; } /// <summary> /// Initialization common to all constructors. /// </summary> private void Initialize(int blockFactor) { _blockFactor = blockFactor; recordSize = blockFactor*BlockSize; recordBuffer = new byte[RecordSize]; if (inputStream != null) { currentRecordIndex = -1; currentBlockIndex = BlockFactor; } else { currentRecordIndex = 0; currentBlockIndex = 0; } } // TODO: IsEOFBlock could/should be static but this is a breaking change. /// <summary> /// Determine if an archive block indicates End of Archive. End of /// archive is indicated by a block that consists entirely of null bytes. /// All remaining blocks for the record should also be null's /// However some older tars only do a couple of null blocks (Old GNU tar for one) /// and also partial records /// </summary> /// <param name = "block">The data block to check.</param> /// <returns>Returns true if the block is an EOF block; false otherwise.</returns> public bool IsEOFBlock(byte[] block) { if (block == null) { throw new ArgumentNullException("block"); } if (block.Length != BlockSize) { throw new ArgumentException("block length is invalid"); } for (var i = 0; i < BlockSize; ++i) { if (block[i] != 0) { return false; } } return true; } /// <summary> /// Skip over a block on the input stream. /// </summary> public void SkipBlock() { if (inputStream == null) { throw new TarException("no input stream defined"); } if (currentBlockIndex >= BlockFactor) { if (!ReadRecord()) { throw new TarException("Failed to read a record"); } } currentBlockIndex++; } /// <summary> /// Read a block from the input stream. /// </summary> /// <returns> /// The block of data read. /// </returns> public byte[] ReadBlock() { if (inputStream == null) { throw new TarException("TarBuffer.ReadBlock - no input stream defined"); } if (currentBlockIndex >= BlockFactor) { if (!ReadRecord()) { throw new TarException("Failed to read a record"); } } var result = new byte[BlockSize]; Array.Copy(recordBuffer, (currentBlockIndex*BlockSize), result, 0, BlockSize); currentBlockIndex++; return result; } /// <summary> /// Read a record from data stream. /// </summary> /// <returns> /// false if End-Of-File, else true. /// </returns> private bool ReadRecord() { if (inputStream == null) { throw new TarException("no input stream stream defined"); } currentBlockIndex = 0; var offset = 0; var bytesNeeded = RecordSize; while (bytesNeeded > 0) { long numBytes = inputStream.Read(recordBuffer, offset, bytesNeeded); // // NOTE // We have found EOF, and the record is not full! // // This is a broken archive. It does not follow the standard // blocking algorithm. However, because we are generous, and // it requires little effort, we will simply ignore the error // and continue as if the entire record were read. This does // not appear to break anything upstream. We used to return // false in this case. // // Thanks to '[email protected]' for this fix. // if (numBytes <= 0) { break; } offset += (int) numBytes; bytesNeeded -= (int) numBytes; } currentRecordIndex++; return true; } /// <summary> /// Get the current block number, within the current record, zero based. /// </summary> /// <returns> /// The current zero based block number. /// </returns> /// <remarks> /// The absolute block number = (<see cref="GetCurrentRecordNum">record number</see> * <see cref="BlockFactor">block factor</see>) + <see cref="GetCurrentBlockNum">block number</see>. /// </remarks> [Obsolete("Use CurrentBlock property instead")] public int GetCurrentBlockNum() { return currentBlockIndex; } /// <summary> /// Get the current record number. /// </summary> /// <returns> /// The current zero based record number. /// </returns> [Obsolete("Use CurrentRecord property instead")] public int GetCurrentRecordNum() { return currentRecordIndex; } /// <summary> /// Write a block of data to the archive. /// </summary> /// <param name="block"> /// The data to write to the archive. /// </param> public void WriteBlock(byte[] block) { if (block == null) { throw new ArgumentNullException("block"); } if (outputStream == null) { throw new TarException("TarBuffer.WriteBlock - no output stream defined"); } if (block.Length != BlockSize) { var errorText = string.Format( "TarBuffer.WriteBlock - block to write has length '{0}' which is not the block size of '{1}'", block.Length, BlockSize); throw new TarException(errorText); } if (currentBlockIndex >= BlockFactor) { WriteRecord(); } Array.Copy(block, 0, recordBuffer, (currentBlockIndex*BlockSize), BlockSize); currentBlockIndex++; } /// <summary> /// Write an archive record to the archive, where the record may be /// inside of a larger array buffer. The buffer must be "offset plus /// record size" long. /// </summary> /// <param name="buffer"> /// The buffer containing the record data to write. /// </param> /// <param name="offset"> /// The offset of the record data within buffer. /// </param> public void WriteBlock(byte[] buffer, int offset) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (outputStream == null) { throw new TarException("TarBuffer.WriteBlock - no output stream stream defined"); } if ((offset < 0) || (offset >= buffer.Length)) { throw new ArgumentOutOfRangeException("offset"); } if ((offset + BlockSize) > buffer.Length) { var errorText = string.Format( "TarBuffer.WriteBlock - record has length '{0}' with offset '{1}' which is less than the record size of '{2}'", buffer.Length, offset, recordSize); throw new TarException(errorText); } if (currentBlockIndex >= BlockFactor) { WriteRecord(); } Array.Copy(buffer, offset, recordBuffer, (currentBlockIndex*BlockSize), BlockSize); currentBlockIndex++; } /// <summary> /// Write a TarBuffer record to the archive. /// </summary> private void WriteRecord() { if (outputStream == null) { throw new TarException("TarBuffer.WriteRecord no output stream defined"); } outputStream.Write(recordBuffer, 0, RecordSize); outputStream.Flush(); currentBlockIndex = 0; currentRecordIndex++; } /// <summary> /// Flush the current record if it has any data in it. /// </summary> private void Flush() { if (outputStream == null) { throw new TarException("TarBuffer.Flush no output stream defined"); } if (currentBlockIndex > 0) { var dataBytes = currentBlockIndex*BlockSize; Array.Clear(recordBuffer, dataBytes, RecordSize - dataBytes); WriteRecord(); } outputStream.Flush(); } /// <summary> /// Close the TarBuffer. If this is an output buffer, also flush the /// current block before closing. /// </summary> public void Close() { if (outputStream != null) { Flush(); outputStream.Close(); outputStream = null; } else if (inputStream != null) { inputStream.Close(); inputStream = null; } } #region Instance Fields private int _blockFactor = DefaultBlockFactor; private int currentBlockIndex; private int currentRecordIndex; private Stream inputStream; private Stream outputStream; private byte[] recordBuffer; private int recordSize = DefaultRecordSize; #endregion } } /* The original Java file had this header: * ** Authored by Timothy Gerard Endres ** <mailto:[email protected]> <http://www.trustice.com> ** ** This work has been placed into the public domain. ** You may use this work in any way and for any purpose you wish. ** ** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND, ** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR ** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY ** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR ** REDISTRIBUTION OF THIS SOFTWARE. ** */
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Msagl.Core.DataStructures; using Microsoft.Msagl.Core.GraphAlgorithms; using Microsoft.Msagl.Core.Layout; using Microsoft.Msagl.Core.ProjectionSolver; namespace Microsoft.Msagl.Layout.Layered { internal class ConstrainedOrdering { readonly GeometryGraph geometryGraph; readonly BasicGraph<Node, IntEdge> intGraph; internal ProperLayeredGraph ProperLayeredGraph; readonly int[] initialLayering; LayerInfo[] layerInfos; internal LayerArrays LayerArrays; readonly HorizontalConstraintsForSugiyama horizontalConstraints; int numberOfNodesOfProperGraph; readonly Database database; double[][] xPositions; int[][] yetBestLayers; readonly List<IntEdge> verticalEdges = new List<IntEdge>(); readonly AdjacentSwapsWithConstraints adjSwapper; SugiyamaLayoutSettings settings; int numberOfLayers = -1; int noGainSteps; const int MaxNumberOfNoGainSteps=5; int NumberOfLayers { get { if (numberOfLayers > 0) return numberOfLayers; return numberOfLayers = initialLayering.Max(i => i + 1); } } double NodeSeparation() { return settings.NodeSeparation; } internal ConstrainedOrdering( GeometryGraph geomGraph, BasicGraph<Node, IntEdge> basicIntGraph, int[] layering, Dictionary<Node, int> nodeIdToIndex, Database database, SugiyamaLayoutSettings settings) { this.settings = settings; horizontalConstraints = settings.HorizontalConstraints; horizontalConstraints.PrepareForOrdering(nodeIdToIndex, layering); geometryGraph = geomGraph; this.database = database; intGraph = basicIntGraph; initialLayering = layering; //this has to be changed only to insert layers that are needed if (NeedToInsertLayers(layering)) { for (int i = 0; i < layering.Length; i++) layering[i] *= 2; LayersAreDoubled = true; numberOfLayers = -1; } PrepareProperLayeredGraphAndFillLayerInfos(); adjSwapper = new AdjacentSwapsWithConstraints( LayerArrays, HasCrossWeights(), ProperLayeredGraph, layerInfos); } bool LayersAreDoubled { get; set; } bool NeedToInsertLayers(int[] layering) { return ExistsShortLabeledEdge(layering, intGraph.Edges) || ExistsShortMultiEdge(layering, database.Multiedges); } static bool ExistsShortMultiEdge(int[] layering, Dictionary<IntPair, List<IntEdge>> multiedges) { return multiedges.Any(multiedge => multiedge.Value.Count > 2 && layering[multiedge.Key.x] == 1 + layering[multiedge.Key.y]); } internal void Calculate() { AllocateXPositions(); var originalGraph = intGraph.Nodes[0].GeometryParent as GeometryGraph; LayeredLayoutEngine.CalculateAnchorSizes(database, out database.anchors, ProperLayeredGraph, originalGraph, intGraph, settings); LayeredLayoutEngine.CalcInitialYAnchorLocations(LayerArrays, 500, geometryGraph, database, intGraph, settings, LayersAreDoubled); Order(); } ConstrainedOrderMeasure CreateMeasure() { return new ConstrainedOrderMeasure(Ordering.GetCrossingsTotal(ProperLayeredGraph, LayerArrays)); } bool HasCrossWeights() { return ProperLayeredGraph.Edges.Any(le => le.CrossingWeight != 1); } static bool ExistsShortLabeledEdge(int[] layering, IEnumerable<IntEdge> edges) { return edges.Any(edge => layering[edge.Source] == layering[edge.Target] + 1 && edge.Edge.Label != null); } void AllocateXPositions() { xPositions = new double[NumberOfLayers][]; for (int i = 0; i < NumberOfLayers; i++) xPositions[i] = new double[LayerArrays.Layers[i].Length]; } void Order() { CreateInitialOrderInLayers(); TryPushingOutStrangersFromHorizontalBlocks(); int n = 5; ConstrainedOrderMeasure measure = null; while (n-- > 0 && noGainSteps <= MaxNumberOfNoGainSteps) { SetXPositions(); ConstrainedOrderMeasure newMeasure = CreateMeasure(); if (measure == null || newMeasure < measure) { noGainSteps = 0; Ordering.CloneLayers(LayerArrays.Layers, ref yetBestLayers); measure = newMeasure; } else { noGainSteps++; RestoreState(); } } #region old code /* int noGainSteps = 0; for (int i = 0; i < NumberOfSweeps && noGainSteps <= MaxNumberOfNoGainSteps && !measure.Perfect(); i++) { SweepDown(false); SweepUp(false); ConstrainedOrderMeasure newMeasure = CreateMeasure(); if (newMeasure < measure) { noGainSteps = 0; Ordering.CloneLayers(LayerArrays.Layers, ref yetBestLayers); measure = newMeasure; } else { noGainSteps++; RestoreState(); } } SwitchXPositions(); SweepUpWithoutChangingLayerOrder(true); SwitchXPositions(); SweepDownWithoutChangingLayerOrder(true); AverageXPositions(); */ #endregion } void SetXPositions() { ISolverShell solver = InitSolverWithoutOrder(); ImproveWithAdjacentSwaps(); PutLayerNodeSeparationsIntoSolver(solver); solver.Solve(); SortLayers(solver); for (int i = 0; i < LayerArrays.Y.Length; i++) database.Anchors[i].X = solver.GetVariableResolvedPosition(i); } ISolverShell InitSolverWithoutOrder() { ISolverShell solver=CreateSolver(); InitSolverVars(solver); PutLeftRightConstraintsIntoSolver(solver); PutVerticalConstraintsIntoSolver(solver); AddGoalsToKeepProperEdgesShort(solver); AddGoalsToKeepFlatEdgesShort(solver); return solver; } void SortLayers(ISolverShell solver) { for (int i = 0; i < LayerArrays.Layers.Length; i++) SortLayerBasedOnSolution(LayerArrays.Layers[i], solver); } void AddGoalsToKeepFlatEdgesShort(ISolverShell solver) { foreach (var layerInfo in layerInfos) AddGoalToKeepFlatEdgesShortOnBlockLevel(layerInfo, solver); } void InitSolverVars(ISolverShell solver) { for (int i = 0; i < LayerArrays.Y.Length; i++) solver.AddVariableWithIdealPosition(i, 0); } void AddGoalsToKeepProperEdgesShort(ISolverShell solver) { foreach (var edge in ProperLayeredGraph.Edges) solver.AddGoalTwoVariablesAreClose(edge.Source, edge.Target, PositionOverBaricenterWeight); } void PutVerticalConstraintsIntoSolver(ISolverShell solver) { foreach (var pair in horizontalConstraints.VerticalInts) { solver.AddGoalTwoVariablesAreClose(pair.Item1, pair.Item2, ConstrainedVarWeight); } } void PutLeftRightConstraintsIntoSolver(ISolverShell solver) { foreach (var pair in horizontalConstraints.LeftRighInts) { solver.AddLeftRightSeparationConstraint(pair.Item1, pair.Item2, SimpleGapBetweenTwoNodes(pair.Item1, pair.Item2)); } } void PutLayerNodeSeparationsIntoSolver(ISolverShell solver) { foreach (var layer in LayerArrays.Layers) { for (int i = 0; i < layer.Length - 1; i++) { int l = layer[i]; int r = layer[i + 1]; solver.AddLeftRightSeparationConstraint(l, r, SimpleGapBetweenTwoNodes(l, r)); } } } void ImproveWithAdjacentSwaps() { adjSwapper.DoSwaps(); } void TryPushingOutStrangersFromHorizontalBlocks() { } void CreateInitialOrderInLayers() { //the idea is to topologically ordering all nodes horizontally, by using vertical components, then fill the layers according to this order Dictionary<int, int> nodesToVerticalComponentsRoots = CreateVerticalComponents(); IEnumerable<IntPair> liftedLeftRightRelations = LiftLeftRightRelationsToComponentRoots(nodesToVerticalComponentsRoots).ToArray(); int[] orderOfVerticalComponentRoots = TopologicalSort.GetOrderOnEdges(liftedLeftRightRelations); FillLayersWithVerticalComponentsOrder(orderOfVerticalComponentRoots, nodesToVerticalComponentsRoots); LayerArrays.UpdateXFromLayers(); } void FillLayersWithVerticalComponentsOrder(int[] order, Dictionary<int, int> nodesToVerticalComponentsRoots) { Dictionary<int, List<int>> componentRootsToComponents = CreateComponentRootsToComponentsMap(nodesToVerticalComponentsRoots); var alreadyInLayers = new bool[LayerArrays.Y.Length]; var runninglayerCounts = new int[LayerArrays.Layers.Length]; foreach (var vertCompRoot in order) PutVerticalComponentIntoLayers(EnumerateVertComponent(componentRootsToComponents, vertCompRoot), runninglayerCounts, alreadyInLayers); for (int i = 0; i < ProperLayeredGraph.NodeCount; i++) if (alreadyInLayers[i] == false) AddVertToLayers(i, runninglayerCounts, alreadyInLayers); } IEnumerable<int> EnumerateVertComponent(Dictionary<int, List<int>> componentRootsToComponents, int vertCompRoot) { List<int> compList; if (componentRootsToComponents.TryGetValue(vertCompRoot, out compList)) { foreach (var i in compList) yield return i; } else yield return vertCompRoot; } void PutVerticalComponentIntoLayers(IEnumerable<int> vertComponent, int[] runningLayerCounts, bool[] alreadyInLayers) { foreach (var i in vertComponent) AddVertToLayers(i, runningLayerCounts, alreadyInLayers); } void AddVertToLayers(int i, int[] runningLayerCounts, bool[] alreadyInLayers) { if (alreadyInLayers[i]) return; int layerIndex = LayerArrays.Y[i]; int xIndex = runningLayerCounts[layerIndex]; var layer = LayerArrays.Layers[layerIndex]; layer[xIndex++] = i; alreadyInLayers[i] = true; List<int> block; if (horizontalConstraints.BlockRootToBlock.TryGetValue(i, out block)) foreach (var v in block) { if (alreadyInLayers[v]) continue; layer[xIndex++] = v; alreadyInLayers[v] = true; } runningLayerCounts[layerIndex] = xIndex; } static Dictionary<int, List<int>> CreateComponentRootsToComponentsMap(Dictionary<int, int> nodesToVerticalComponentsRoots) { var d = new Dictionary<int, List<int>>(); foreach (var kv in nodesToVerticalComponentsRoots) { int i = kv.Key; var root = kv.Value; List<int> component; if (!d.TryGetValue(root, out component)) { d[root] = component = new List<int>(); } component.Add(i); } return d; } IEnumerable<IntPair> LiftLeftRightRelationsToComponentRoots(Dictionary<int, int> nodesToVerticalComponentsRoots) { foreach (var pair in horizontalConstraints.LeftRighInts) yield return new IntPair(GetFromDictionaryOrIdentical(nodesToVerticalComponentsRoots, pair.Item1), GetFromDictionaryOrIdentical(nodesToVerticalComponentsRoots, pair.Item2)); foreach (var pair in horizontalConstraints.LeftRightIntNeibs) yield return new IntPair(GetFromDictionaryOrIdentical(nodesToVerticalComponentsRoots, pair.Item1), GetFromDictionaryOrIdentical(nodesToVerticalComponentsRoots, pair.Item2)); } static int GetFromDictionaryOrIdentical(Dictionary<int, int> d, int key) { int i; if (d.TryGetValue(key, out i)) return i; return key; } /// <summary> /// These blocks are connected components in the vertical constraints. They don't necesserely span consequent layers. /// </summary> /// <returns></returns> Dictionary<int, int> CreateVerticalComponents() { var vertGraph = new BasicGraph<IntEdge>(from pair in horizontalConstraints.VerticalInts select new IntEdge(pair.Item1, pair.Item2)); var verticalComponents = ConnectedComponentCalculator<IntEdge>.GetComponents(vertGraph); var nodesToComponentRoots = new Dictionary<int, int>(); foreach (var component in verticalComponents) { var ca = component.ToArray(); if (ca.Length == 1) continue; int componentRoot = -1; foreach (var j in component) { if (componentRoot == -1) componentRoot = j; nodesToComponentRoots[j] = componentRoot; } } return nodesToComponentRoots; } void RestoreState() { LayerArrays.UpdateLayers(yetBestLayers); } #if TEST_MSAGL [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledCode")] void Show() { SugiyamaLayoutSettings.ShowDatabase(database); } #endif #if TEST_MSAGL [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Console.Write(System.String)"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledCode")] static void PrintPositions(double[] positions) { for (int j = 0; j < positions.Length; j++) Console.Write(" " + positions[j]); Console.WriteLine(); } #endif void SortLayerBasedOnSolution(int[] layer, ISolverShell solver) { int length = layer.Length; var positions = new double[length]; int k = 0; foreach (int v in layer) positions[k++] = solver.GetVariableResolvedPosition(v); Array.Sort(positions, layer); int i = 0; foreach (int v in layer) LayerArrays.X[v] = i++; } const double ConstrainedVarWeight = 10e6; const double PositionOverBaricenterWeight = 5; static int NodeToBlockRootSoftOnLayerInfo(LayerInfo layerInfo, int node) { int root; return layerInfo.nodeToBlockRoot.TryGetValue(node, out root) ? root : node; } static void AddGoalToKeepFlatEdgesShortOnBlockLevel(LayerInfo layerInfo, ISolverShell solver) { if (layerInfo != null) foreach (var couple in layerInfo.flatEdges) { int sourceBlockRoot = NodeToBlockRootSoftOnLayerInfo(layerInfo, couple.Item1); int targetBlockRoot = NodeToBlockRootSoftOnLayerInfo(layerInfo, couple.Item2); if (sourceBlockRoot != targetBlockRoot) solver.AddGoalTwoVariablesAreClose(sourceBlockRoot, targetBlockRoot); } } static bool NodeIsConstrainedBelow(int v, LayerInfo layerInfo) { if (layerInfo == null) return false; return layerInfo.constrainedFromBelow.ContainsKey(v); } static bool NodeIsConstrainedAbove(int v, LayerInfo layerInfo) { if (layerInfo == null) return false; return layerInfo.constrainedFromAbove.ContainsKey(v); } internal static bool BelongsToNeighbBlock(int p, LayerInfo layerInfo) { return layerInfo != null && (layerInfo.nodeToBlockRoot.ContainsKey(p) || layerInfo.neigBlocks.ContainsKey(p)); //p is a root of the block } static bool NodesAreConstrainedBelow(int leftNode, int rightNode, LayerInfo layerInfo) { return NodeIsConstrainedBelow(leftNode, layerInfo) && NodeIsConstrainedBelow(rightNode, layerInfo); } static bool NodesAreConstrainedAbove(int leftNode, int rightNode, LayerInfo layerInfo) { return NodeIsConstrainedAbove(leftNode, layerInfo) && NodeIsConstrainedAbove(rightNode, layerInfo); } double GetGapFromNodeNodesConstrainedBelow(int leftNode, int rightNode, LayerInfo layerInfo, int layerIndex) { double gap = SimpleGapBetweenTwoNodes(leftNode, rightNode); leftNode = layerInfo.constrainedFromBelow[leftNode]; rightNode = layerInfo.constrainedFromBelow[rightNode]; layerIndex--; layerInfo = layerInfos[layerIndex]; if (layerIndex > 0 && NodesAreConstrainedBelow(leftNode, rightNode, layerInfo)) return Math.Max(gap, GetGapFromNodeNodesConstrainedBelow(leftNode, rightNode, layerInfo, layerIndex)); return Math.Max(gap, SimpleGapBetweenTwoNodes(leftNode, rightNode)); } double GetGapFromNodeNodesConstrainedAbove(int leftNode, int rightNode, LayerInfo layerInfo, int layerIndex) { double gap = SimpleGapBetweenTwoNodes(leftNode, rightNode); leftNode = layerInfo.constrainedFromAbove[leftNode]; rightNode = layerInfo.constrainedFromAbove[rightNode]; layerIndex++; layerInfo = layerInfos[layerIndex]; if (layerIndex < LayerArrays.Layers.Length - 1 && NodesAreConstrainedAbove(leftNode, rightNode, layerInfo)) return Math.Max(gap, GetGapFromNodeNodesConstrainedAbove(leftNode, rightNode, layerInfo, layerIndex)); return Math.Max(gap, SimpleGapBetweenTwoNodes(leftNode, rightNode)); } double SimpleGapBetweenTwoNodes(int leftNode, int rightNode) { return database.anchors[leftNode].RightAnchor + NodeSeparation() + database.anchors[rightNode].LeftAnchor; } internal static ISolverShell CreateSolver() { return new SolverShell(); } void PrepareProperLayeredGraphAndFillLayerInfos() { layerInfos = new LayerInfo[NumberOfLayers]; CreateProperLayeredGraph(); CreateExtendedLayerArrays(); FillBlockRootToBlock(); FillLeftRightPairs(); FillFlatEdges(); FillAboveBelow(); FillBlockRootToVertConstrainedNode(); } void FillBlockRootToVertConstrainedNode() { foreach (LayerInfo layerInfo in layerInfos) foreach (int v in VertConstrainedNodesOfLayer(layerInfo)) { int blockRoot; if (TryGetBlockRoot(v, out blockRoot, layerInfo)) layerInfo.blockRootToVertConstrainedNodeOfBlock[blockRoot] = v; } } static bool TryGetBlockRoot(int v, out int blockRoot, LayerInfo layerInfo) { if (layerInfo.nodeToBlockRoot.TryGetValue(v, out blockRoot)) return true; if (layerInfo.neigBlocks.ContainsKey(v)) { blockRoot = v; return true; } return false; } static IEnumerable<int> VertConstrainedNodesOfLayer(LayerInfo layerInfo) { if (layerInfo != null) { foreach (int v in layerInfo.constrainedFromAbove.Keys) yield return v; foreach (int v in layerInfo.constrainedFromBelow.Keys) yield return v; } } void CreateExtendedLayerArrays() { var layeringExt = new int[numberOfNodesOfProperGraph]; Array.Copy(initialLayering, layeringExt, initialLayering.Length); foreach (IntEdge edge in ProperLayeredGraph.BaseGraph.Edges) { var ledges = (LayerEdge[])edge.LayerEdges; if (ledges != null && ledges.Length > 1) { int layerIndex = initialLayering[edge.Source] - 1; for (int i = 0; i < ledges.Length - 1; i++) layeringExt[ledges[i].Target] = layerIndex--; } } LayerArrays = new LayerArrays(layeringExt); } void CreateProperLayeredGraph() { IEnumerable<IntEdge> edges = CreatePathEdgesOnIntGraph(); var nodeCount = Math.Max(intGraph.NodeCount, BasicGraph<Node, IntEdge>.VertexCount(edges)); var baseGraph = new BasicGraph<Node, IntEdge>(edges, nodeCount) { Nodes = intGraph.Nodes }; ProperLayeredGraph = new ProperLayeredGraph(baseGraph); } IEnumerable<IntEdge> CreatePathEdgesOnIntGraph() { numberOfNodesOfProperGraph = intGraph.NodeCount; var ret = new List<IntEdge>(); foreach (IntEdge ie in intGraph.Edges) { if (initialLayering[ie.Source] > initialLayering[ie.Target]) { CreateLayerEdgesUnderIntEdge(ie); ret.Add(ie); if (horizontalConstraints.VerticalInts.Contains(new Tuple<int, int>(ie.Source, ie.Target))) verticalEdges.Add(ie); } } return ret; } void CreateLayerEdgesUnderIntEdge(IntEdge ie) { int source = ie.Source; int target = ie.Target; int span = LayeredLayoutEngine.EdgeSpan(initialLayering, ie); ie.LayerEdges = new LayerEdge[span]; Debug.Assert(span > 0); if (span == 1) ie.LayerEdges[0] = new LayerEdge(ie.Source, ie.Target, ie.CrossingWeight); else { ie.LayerEdges[0] = new LayerEdge(source, numberOfNodesOfProperGraph, ie.CrossingWeight); for (int i = 0; i < span - 2; i++) ie.LayerEdges[i + 1] = new LayerEdge(numberOfNodesOfProperGraph++, numberOfNodesOfProperGraph, ie.CrossingWeight); ie.LayerEdges[span - 1] = new LayerEdge(numberOfNodesOfProperGraph++, target, ie.CrossingWeight); } } void FillAboveBelow() { foreach (IntEdge ie in verticalEdges) { foreach (LayerEdge le in ie.LayerEdges) { int upper = le.Source; int lower = le.Target; RegisterAboveBelowOnConstrainedUpperLower(upper, lower); } } foreach (var p in horizontalConstraints.VerticalInts) RegisterAboveBelowOnConstrainedUpperLower(p.Item1, p.Item2); } void RegisterAboveBelowOnConstrainedUpperLower(int upper, int lower) { LayerInfo topLayerInfo = GetOrCreateLayerInfo(LayerArrays.Y[upper]); LayerInfo bottomLayerInfo = GetOrCreateLayerInfo(LayerArrays.Y[lower]); topLayerInfo.constrainedFromBelow[upper] = lower; bottomLayerInfo.constrainedFromAbove[lower] = upper; } void FillFlatEdges() { foreach (IntEdge edge in intGraph.Edges) { int l = initialLayering[edge.Source]; if (l == initialLayering[edge.Target]) { GetOrCreateLayerInfo(l).flatEdges.Insert(new Tuple<int, int>(edge.Source, edge.Target)); } } } void FillLeftRightPairs() { foreach (var p in horizontalConstraints.LeftRighInts) { LayerInfo layerInfo = GetOrCreateLayerInfo(initialLayering[p.Item1]); layerInfo.leftRight.Insert(p); } } /// <summary> /// when we call this function we know that a LayerInfo is needed /// </summary> /// <param name="layerNumber"></param> /// <returns></returns> LayerInfo GetOrCreateLayerInfo(int layerNumber) { LayerInfo layerInfo = layerInfos[layerNumber] ?? (layerInfos[layerNumber] = new LayerInfo()); return layerInfo; } void FillBlockRootToBlock() { foreach (var p in horizontalConstraints.BlockRootToBlock) { LayerInfo layerInfo = GetOrCreateLayerInfo(initialLayering[p.Key]); layerInfo.neigBlocks[p.Key] = p.Value; foreach (int i in p.Value) layerInfo.nodeToBlockRoot[i] = p.Key; } } } }
namespace Orleans.CodeGenerator { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Orleans.CodeGeneration; using Orleans.CodeGenerator.Utilities; using Orleans.Concurrency; using Orleans.Runtime; using GrainInterfaceUtils = Orleans.CodeGeneration.GrainInterfaceUtils; using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory; /// <summary> /// Code generator which generates <see cref="GrainReference"/>s for grains. /// </summary> internal static class GrainReferenceGenerator { /// <summary> /// The suffix appended to the name of generated classes. /// </summary> private const string ClassSuffix = "Reference"; /// <summary> /// A reference to the CheckGrainObserverParamInternal method. /// </summary> private static readonly Expression<Action> CheckGrainObserverParamInternalExpression = () => GrainFactoryBase.CheckGrainObserverParamInternal(null); /// <summary> /// Returns the name of the generated class for the provided type. /// </summary> /// <param name="type">The type.</param> /// <returns>The name of the generated class for the provided type.</returns> internal static string GetGeneratedClassName(Type type) => CodeGeneratorCommon.ClassPrefix + TypeUtils.GetSuitableClassName(type) + ClassSuffix; /// <summary> /// Generates the class for the provided grain types. /// </summary> /// <param name="grainType"> /// The grain interface type. /// </param> /// <param name="generatedTypeName">Name of the generated type.</param> /// <param name="onEncounteredType">The callback which is invoked when a type is encountered.</param> /// <returns> /// The generated class. /// </returns> internal static TypeDeclarationSyntax GenerateClass(Type grainType, string generatedTypeName, Action<Type> onEncounteredType) { var grainTypeInfo = grainType.GetTypeInfo(); var genericTypes = grainTypeInfo.IsGenericTypeDefinition ? grainTypeInfo.GetGenericArguments() .Select(_ => SF.TypeParameter(_.ToString())) .ToArray() : new TypeParameterSyntax[0]; // Create the special marker attribute. var markerAttribute = SF.Attribute(typeof(GrainReferenceAttribute).GetNameSyntax()) .AddArgumentListArguments( SF.AttributeArgument( SF.TypeOfExpression(grainType.GetTypeSyntax(includeGenericParameters: false)))); var attributes = SF.AttributeList() .AddAttributes( CodeGeneratorCommon.GetGeneratedCodeAttributeSyntax(), SF.Attribute(typeof(SerializableAttribute).GetNameSyntax()), SF.Attribute(typeof(ExcludeFromCodeCoverageAttribute).GetNameSyntax()), markerAttribute); var classDeclaration = SF.ClassDeclaration(generatedTypeName) .AddModifiers(SF.Token(SyntaxKind.InternalKeyword)) .AddBaseListTypes( SF.SimpleBaseType(typeof(GrainReference).GetTypeSyntax()), SF.SimpleBaseType(grainType.GetTypeSyntax())) .AddConstraintClauses(grainType.GetTypeConstraintSyntax()) .AddMembers(GenerateConstructors(generatedTypeName)) .AddMembers( GenerateInterfaceIdProperty(grainType), GenerateInterfaceVersionProperty(grainType), GenerateInterfaceNameProperty(grainType), GenerateIsCompatibleMethod(grainType), GenerateGetMethodNameMethod(grainType)) .AddMembers(GenerateInvokeMethods(grainType, onEncounteredType)) .AddAttributeLists(attributes); if (genericTypes.Length > 0) { classDeclaration = classDeclaration.AddTypeParameterListParameters(genericTypes); } return classDeclaration; } /// <summary> /// Generates constructors. /// </summary> /// <param name="className">The class name.</param> /// <returns>Constructor syntax for the provided class name.</returns> private static MemberDeclarationSyntax[] GenerateConstructors(string className) { var baseConstructors = typeof(GrainReference).GetTypeInfo().GetConstructors( BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance).Where(_ => !_.IsPrivate); var constructors = new List<MemberDeclarationSyntax>(); foreach (var baseConstructor in baseConstructors) { var args = baseConstructor.GetParameters() .Select(arg => SF.Argument(arg.Name.ToIdentifierName())) .ToArray(); var declaration = baseConstructor.GetDeclarationSyntax(className) .WithInitializer( SF.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer) .AddArgumentListArguments(args)) .AddBodyStatements(); constructors.Add(declaration); } return constructors.ToArray(); } /// <summary> /// Generates invoker methods. /// </summary> /// <param name="grainType">The grain type.</param> /// <param name="onEncounteredType"> /// The callback which is invoked when a type is encountered. /// </param> /// <returns>Invoker methods for the provided grain type.</returns> private static MemberDeclarationSyntax[] GenerateInvokeMethods(Type grainType, Action<Type> onEncounteredType) { var baseReference = SF.BaseExpression(); var methods = GrainInterfaceUtils.GetMethods(grainType); var members = new List<MemberDeclarationSyntax>(); foreach (var method in methods) { onEncounteredType(method.ReturnType); var methodId = GrainInterfaceUtils.ComputeMethodId(method); var methodIdArgument = SF.Argument(SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(methodId))); // Construct a new object array from all method arguments. var parameters = method.GetParameters(); var body = new List<StatementSyntax>(); foreach (var parameter in parameters) { onEncounteredType(parameter.ParameterType); if (typeof(IGrainObserver).GetTypeInfo().IsAssignableFrom(parameter.ParameterType)) { body.Add( SF.ExpressionStatement( CheckGrainObserverParamInternalExpression.Invoke() .AddArgumentListArguments(SF.Argument(parameter.Name.ToIdentifierName())))); } } // Get the parameters argument value. ExpressionSyntax args; if (method.IsGenericMethodDefinition) { // Create an arguments array which includes the method's type parameters followed by the method's parameter list. var allParameters = new List<ExpressionSyntax>(); foreach (var typeParameter in method.GetGenericArguments()) { allParameters.Add(SF.TypeOfExpression(typeParameter.GetTypeSyntax())); } allParameters.AddRange(parameters.Select(GetParameterForInvocation)); args = SF.ArrayCreationExpression(typeof(object).GetArrayTypeSyntax()) .WithInitializer( SF.InitializerExpression(SyntaxKind.ArrayInitializerExpression) .AddExpressions(allParameters.ToArray())); } else if (parameters.Length == 0) { args = SF.LiteralExpression(SyntaxKind.NullLiteralExpression); } else { args = SF.ArrayCreationExpression(typeof(object).GetArrayTypeSyntax()) .WithInitializer( SF.InitializerExpression(SyntaxKind.ArrayInitializerExpression) .AddExpressions(parameters.Select(GetParameterForInvocation).ToArray())); } var options = GetInvokeOptions(method); // Construct the invocation call. var isOneWayTask = method.GetCustomAttribute<OneWayAttribute>() != null; if (method.ReturnType == typeof(void) || isOneWayTask) { var invocation = SF.InvocationExpression(baseReference.Member("InvokeOneWayMethod")) .AddArgumentListArguments(methodIdArgument) .AddArgumentListArguments(SF.Argument(args)); if (options != null) { invocation = invocation.AddArgumentListArguments(options); } body.Add(SF.ExpressionStatement(invocation)); if (isOneWayTask) { if (method.ReturnType != typeof(Task)) { throw new CodeGenerationException( $"Method {grainType.GetParseableName()}.{method.Name} is marked with [{nameof(OneWayAttribute)}], " + $"but has a return type which is not assignable from {typeof(Task)}"); } var done = typeof(Task).GetNameSyntax(true).Member((object _) => Task.CompletedTask); body.Add(SF.ReturnStatement(done)); } } else { var returnType = method.ReturnType == typeof(Task) ? typeof(object) : method.ReturnType.GenericTypeArguments[0]; var invocation = SF.InvocationExpression(baseReference.Member("InvokeMethodAsync", returnType)) .AddArgumentListArguments(methodIdArgument) .AddArgumentListArguments(SF.Argument(args)); if (options != null) { invocation = invocation.AddArgumentListArguments(options); } ExpressionSyntax returnContent = invocation; if (method.ReturnType.IsGenericType && method.ReturnType.GetGenericTypeDefinition().FullName == "System.Threading.Tasks.ValueTask`1") { // Wrapping invocation expression with initialization of ValueTask (e.g. new ValueTask<int>(base.InvokeMethod())) returnContent = SF.ObjectCreationExpression(method.ReturnType.GetTypeSyntax()) .AddArgumentListArguments(SF.Argument(SF.ExpressionStatement(invocation).Expression)); } body.Add(SF.ReturnStatement(returnContent)); } members.Add(method.GetDeclarationSyntax().AddBodyStatements(body.ToArray())); } return members.ToArray(); } /// <summary> /// Returns syntax for the options argument to <see cref="GrainReference.InvokeMethodAsync{T}"/> and <see cref="GrainReference.InvokeOneWayMethod"/>. /// </summary> /// <param name="method">The method which an invoke call is being generated for.</param> /// <returns> /// Argument syntax for the options argument to <see cref="GrainReference.InvokeMethodAsync{T}"/> and /// <see cref="GrainReference.InvokeOneWayMethod"/>, or <see langword="null"/> if no options are to be specified. /// </returns> private static ArgumentSyntax GetInvokeOptions(MethodInfo method) { var options = new List<ExpressionSyntax>(); if (GrainInterfaceUtils.IsReadOnly(method)) { options.Add(typeof(InvokeMethodOptions).GetNameSyntax().Member(InvokeMethodOptions.ReadOnly.ToString())); } if (GrainInterfaceUtils.IsUnordered(method)) { options.Add(typeof(InvokeMethodOptions).GetNameSyntax().Member(InvokeMethodOptions.Unordered.ToString())); } if (GrainInterfaceUtils.IsAlwaysInterleave(method)) { options.Add(typeof(InvokeMethodOptions).GetNameSyntax().Member(InvokeMethodOptions.AlwaysInterleave.ToString())); } if (GrainInterfaceUtils.TryGetTransactionOption(method, out TransactionOption option)) { switch (option) { case TransactionOption.Suppress: options.Add(typeof(InvokeMethodOptions).GetNameSyntax().Member(InvokeMethodOptions.TransactionSuppress.ToString())); break; case TransactionOption.CreateOrJoin: options.Add(typeof(InvokeMethodOptions).GetNameSyntax().Member(InvokeMethodOptions.TransactionCreateOrJoin.ToString())); break; case TransactionOption.Create: options.Add(typeof(InvokeMethodOptions).GetNameSyntax().Member(InvokeMethodOptions.TransactionCreate.ToString())); break; case TransactionOption.Join: options.Add(typeof(InvokeMethodOptions).GetNameSyntax().Member(InvokeMethodOptions.TransactionJoin.ToString())); break; case TransactionOption.Supported: options.Add(typeof(InvokeMethodOptions).GetNameSyntax().Member(InvokeMethodOptions.TransactionSupported.ToString())); break; case TransactionOption.NotAllowed: options.Add(typeof(InvokeMethodOptions).GetNameSyntax().Member(InvokeMethodOptions.TransactionNotAllowed.ToString())); break; default: throw new NotSupportedException($"Transaction option {options} is not supported."); } } ExpressionSyntax allOptions; if (options.Count <= 1) { allOptions = options.FirstOrDefault(); } else { allOptions = options.Aggregate((a, b) => SF.BinaryExpression(SyntaxKind.BitwiseOrExpression, a, b)); } if (allOptions == null) { return null; } return SF.Argument(SF.NameColon("options"), SF.Token(SyntaxKind.None), allOptions); } private static ExpressionSyntax GetParameterForInvocation(ParameterInfo arg, int argIndex) { var argIdentifier = arg.GetOrCreateName(argIndex).ToIdentifierName(); // Addressable arguments must be converted to references before passing. if (typeof(IAddressable).GetTypeInfo().IsAssignableFrom(arg.ParameterType) && arg.ParameterType.GetTypeInfo().IsInterface) { return SF.ConditionalExpression( SF.BinaryExpression(SyntaxKind.IsExpression, argIdentifier, typeof(Grain).GetTypeSyntax()), SF.InvocationExpression(argIdentifier.Member("AsReference", arg.ParameterType)), argIdentifier); } return argIdentifier; } private static MemberDeclarationSyntax GenerateInterfaceIdProperty(Type grainType) { var property = TypeUtils.Member((GrainReference _) => _.InterfaceId); var returnValue = SF.LiteralExpression( SyntaxKind.NumericLiteralExpression, SF.Literal(GrainInterfaceUtils.GetGrainInterfaceId(grainType))); return SF.PropertyDeclaration(typeof(int).GetTypeSyntax(), property.Name) .AddAccessorListAccessors( SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .AddBodyStatements(SF.ReturnStatement(returnValue))) .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.OverrideKeyword)); } private static MemberDeclarationSyntax GenerateInterfaceVersionProperty(Type grainType) { var property = TypeUtils.Member((GrainReference _) => _.InterfaceVersion); var returnValue = SF.LiteralExpression( SyntaxKind.NumericLiteralExpression, SF.Literal(GrainInterfaceUtils.GetGrainInterfaceVersion(grainType))); return SF.PropertyDeclaration(typeof(ushort).GetTypeSyntax(), property.Name) .AddAccessorListAccessors( SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .AddBodyStatements(SF.ReturnStatement(returnValue))) .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.OverrideKeyword)); } private static MemberDeclarationSyntax GenerateIsCompatibleMethod(Type grainType) { var method = TypeUtils.Method((GrainReference _) => _.IsCompatible(default(int))); var methodDeclaration = method.GetDeclarationSyntax(); var interfaceIdParameter = method.GetParameters()[0].Name.ToIdentifierName(); var interfaceIds = new HashSet<int>( new[] { GrainInterfaceUtils.GetGrainInterfaceId(grainType) }.Concat( GrainInterfaceUtils.GetRemoteInterfaces(grainType).Keys)); var returnValue = default(BinaryExpressionSyntax); foreach (var interfaceId in interfaceIds) { var check = SF.BinaryExpression( SyntaxKind.EqualsExpression, interfaceIdParameter, SF.LiteralExpression(SyntaxKind.NumericLiteralExpression, SF.Literal(interfaceId))); // If this is the first check, assign it, otherwise OR this check with the previous checks. returnValue = returnValue == null ? check : SF.BinaryExpression(SyntaxKind.LogicalOrExpression, returnValue, check); } return methodDeclaration.AddBodyStatements(SF.ReturnStatement(returnValue)) .AddModifiers(SF.Token(SyntaxKind.OverrideKeyword)); } private static MemberDeclarationSyntax GenerateInterfaceNameProperty(Type grainType) { var propertyName = TypeUtils.Member((GrainReference _) => _.InterfaceName); var returnValue = grainType.GetParseableName().GetLiteralExpression(); return SF.PropertyDeclaration(typeof(string).GetTypeSyntax(), propertyName.Name) .AddAccessorListAccessors( SF.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration) .AddBodyStatements(SF.ReturnStatement(returnValue))) .AddModifiers(SF.Token(SyntaxKind.PublicKeyword), SF.Token(SyntaxKind.OverrideKeyword)); } private static MethodDeclarationSyntax GenerateGetMethodNameMethod(Type grainType) { var method = TypeUtils.Method((GrainReference _) => _.GetMethodName(default(int), default(int))); var methodDeclaration = method.GetDeclarationSyntax() .AddModifiers(SF.Token(SyntaxKind.OverrideKeyword)); var parameters = method.GetParameters(); var interfaceIdArgument = parameters[0].Name.ToIdentifierName(); var methodIdArgument = parameters[1].Name.ToIdentifierName(); var interfaceCases = CodeGeneratorCommon.GenerateGrainInterfaceAndMethodSwitch( grainType, methodIdArgument, methodType => new StatementSyntax[] { SF.ReturnStatement(methodType.Name.GetLiteralExpression()) }); // Generate the default case, which will throw a NotImplementedException. var errorMessage = SF.BinaryExpression( SyntaxKind.AddExpression, "interfaceId=".GetLiteralExpression(), interfaceIdArgument); var throwStatement = SF.ThrowStatement( SF.ObjectCreationExpression(typeof(NotImplementedException).GetTypeSyntax()) .AddArgumentListArguments(SF.Argument(errorMessage))); var defaultCase = SF.SwitchSection().AddLabels(SF.DefaultSwitchLabel()).AddStatements(throwStatement); var interfaceIdSwitch = SF.SwitchStatement(interfaceIdArgument).AddSections(interfaceCases.ToArray()).AddSections(defaultCase); return methodDeclaration.AddBodyStatements(interfaceIdSwitch); } } }
// 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; /// <summary> /// Char.Equals(Object) /// Note: This method is new in the .NET Framework version 2.0. /// Returns a value indicating whether this instance is equal to the specified Char object. /// </summary> public class CharEquals { public static int Main() { CharEquals testObj = new CharEquals(); TestLibrary.TestFramework.BeginTestCase("for method: Char.Equals(Object)"); if(testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; const string c_TEST_ID = "P001"; const string c_TEST_DESC = @"PosTest1: char.MaxValue vs '\uFFFF'"; string errorDesc; const char c_MAX_CHAR = '\uFFFF'; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { char actualChar = char.MaxValue; object obj = c_MAX_CHAR; bool result = actualChar.Equals(obj); if (!result) { errorDesc = "Char.MaxValue is not " + c_MAX_CHAR + " as expected: Actual(" + actualChar + ")"; TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_ID = "P002"; const string c_TEST_DESC = @"PosTest2: char.MinValue vs '\u0000'"; string errorDesc; const char c_MIN_CHAR = '\u0000'; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { char actualChar = char.MinValue; object obj = c_MIN_CHAR; bool result = actualChar.Equals(obj); if (!result) { errorDesc = "char.MinValue is not " + c_MIN_CHAR + " as expected: Actual(" + actualChar + ")"; TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; const string c_TEST_ID = "P003"; const string c_TEST_DESC = "PosTest3: char.MaxValue vs char.MinValue"; string errorDesc; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { bool expectedValue = false; object obj = char.MinValue; bool actualValue = char.MaxValue.Equals(obj); if (actualValue != expectedValue) { errorDesc = @"char.MaxValue('\uFFFF') does not equal char.MinValue('\u0000')"; TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; const string c_TEST_ID = "P004"; const string c_TEST_DESC = "PosTest4: equality of two random charaters"; string errorDesc; char chA, chB; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { chA = TestLibrary.Generator.GetChar(-55); chB = TestLibrary.Generator.GetChar(-55); object obj = chB; bool expectedValue = (int)chA == (int)chB; bool actualValue = chA.Equals(obj); if (actualValue != expectedValue) { errorDesc = string.Format("The equality of character \'\\u{0:x}\' against character \'\\u{1:x}\' is not {2} as expected: Actual({3})", (int)chA, (int)chB, expectedValue, actualValue); TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; const string c_TEST_ID = "P004"; const string c_TEST_DESC = "PosTest4: char vs 32-bit integer value"; string errorDesc; char chA; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { chA = TestLibrary.Generator.GetChar(-55); object obj = (int)chA; bool expectedValue = false; bool actualValue = chA.Equals(obj); if (actualValue != expectedValue) { errorDesc = string.Format("The equality of character \'\\u{0:x}\' against 32-bit integer {1:x} is not {2} as expected: Actual({3})", (int)chA, (int)obj, expectedValue, actualValue); TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpected exception: " + e; TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } return retVal; } #endregion }
// // Copyright (C) 2010 Jackson Harper ([email protected]) // // 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.Concurrent; using System.Collections.Generic; using System.Runtime.InteropServices; using Manos.IO; using Manos.Http; using Manos.Caching; using Manos.Logging; using Libev; using Manos.Threading; namespace Manos { /// <summary> /// The app runner. This is where the magic happens. /// </summary> public static class AppHost { private static ManosApp app; private static bool started; private static List<IPEndPoint> listenEndPoints = new List<IPEndPoint> (); private static Dictionary<IPEndPoint, Tuple<string, string>> secureListenEndPoints = new Dictionary<IPEndPoint, Tuple<string, string>> (); private static List<HttpServer> servers = new List<HttpServer> (); private static IManosCache cache; private static IManosLogger log; private static List<IManosPipe> pipes; private static Context context; static AppHost () { context = Context.Create (); } public static ManosApp App { get { return app; } } public static IManosCache Cache { get { if (cache == null) cache = new ManosInProcCache (); return cache; } } public static IManosLogger Log { get { if (log == null) log = new Manos.Logging.ManosConsoleLogger ("manos", LogLevel.Debug); return log; } } public static Context Context { get { return context; } } public static IList<IManosPipe> Pipes { get { return pipes; } } public static ICollection<IPEndPoint> ListenEndPoints { get { return listenEndPoints.AsReadOnly (); } } public static void ListenAt (IPEndPoint endPoint) { if (endPoint == null) throw new ArgumentNullException ("endPoint"); if (listenEndPoints.Contains (endPoint) || secureListenEndPoints.ContainsKey (endPoint)) throw new InvalidOperationException ("Endpoint already registered"); listenEndPoints.Add (endPoint); } public static void SecureListenAt (IPEndPoint endPoint, string cert, string key) { if (endPoint == null) throw new ArgumentNullException ("endPoint"); if (cert == null) throw new ArgumentNullException ("cert"); if (key == null) throw new ArgumentNullException ("key"); if (secureListenEndPoints.ContainsKey (endPoint) || listenEndPoints.Contains (endPoint)) throw new InvalidOperationException ("Endpoint already registered"); secureListenEndPoints.Add (endPoint, Tuple.Create (cert, key)); } public static void InitializeTLS (string priorities) { #if !DISABLETLS manos_tls_global_init (priorities); RegenerateDHParams (1024); #endif } public static void RegenerateDHParams (int bits) { #if !DISABLETLS manos_tls_regenerate_dhparams (bits); #endif } #if !DISABLETLS [DllImport ("libmanos", CallingConvention = CallingConvention.Cdecl)] private static extern int manos_tls_global_init (string priorities); [DllImport ("libmanos", CallingConvention = CallingConvention.Cdecl)] private static extern int manos_tls_regenerate_dhparams (int bits); #endif public static void Start (ManosApp application) { if (application == null) throw new ArgumentNullException ("application"); app = application; app.StartInternal (); started = true; foreach (var ep in listenEndPoints) { var server = new HttpServer (Context, HandleTransaction, Context.CreateTcpServerSocket (ep.AddressFamily)); server.Listen (ep.Address.ToString (), ep.Port); servers.Add (server); } foreach (var ep in secureListenEndPoints.Keys) { // var keypair = secureListenEndPoints [ep]; // var socket = Context.CreateSecureSocket (keypair.Item1, keypair.Item2); // var server = new HttpServer (context, HandleTransaction, socket); // server.Listen (ep.Address.ToString (), ep.Port); // // servers.Add (server); } context.Start (); } public static void Stop () { context.Stop (); } public static void HandleTransaction (IHttpTransaction con) { app.HandleTransaction (app, con); } public static void AddPipe (IManosPipe pipe) { if (pipes == null) pipes = new List<IManosPipe> (); pipes.Add (pipe); } public static Timeout AddTimeout (TimeSpan timespan, IRepeatBehavior repeat, object data, TimeoutCallback callback) { return AddTimeout (timespan, timespan, repeat, data, callback); } public static Timeout AddTimeout (TimeSpan begin, TimeSpan timespan, IRepeatBehavior repeat, object data, TimeoutCallback callback) { Timeout t = new Timeout (begin, timespan, repeat, data, callback); ITimerWatcher timer = null; timer = context.CreateTimerWatcher (begin, timespan, delegate { t.Run (app); if (!t.ShouldContinueToRepeat ()) { t.Stop (); timer.Dispose (); } }); timer.Start (); return t; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Xml; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.MultiCluster; using Orleans.Runtime.MembershipService; using Orleans.Runtime.MultiClusterNetwork; using Orleans.Versions; using Orleans.Versions.Compatibility; using Orleans.Versions.Selector; namespace Orleans.Runtime.Management { /// <summary> /// Implementation class for the Orleans management grain. /// </summary> [OneInstancePerCluster] internal class ManagementGrain : Grain, IManagementGrain { private readonly MultiClusterOptions multiClusterOptions; private readonly IMultiClusterOracle multiClusterOracle; private readonly IInternalGrainFactory internalGrainFactory; private readonly ISiloStatusOracle siloStatusOracle; private readonly GrainTypeManager grainTypeManager; private readonly IVersionStore versionStore; private ILogger logger; private IMembershipTable membershipTable; public ManagementGrain( IOptions<MultiClusterOptions> multiClusterOptions, IMultiClusterOracle multiClusterOracle, IInternalGrainFactory internalGrainFactory, ISiloStatusOracle siloStatusOracle, IMembershipTable membershipTable, GrainTypeManager grainTypeManager, IVersionStore versionStore, ILogger<ManagementGrain> logger) { this.multiClusterOptions = multiClusterOptions.Value; this.multiClusterOracle = multiClusterOracle; this.internalGrainFactory = internalGrainFactory; this.membershipTable = membershipTable; this.siloStatusOracle = siloStatusOracle; this.grainTypeManager = grainTypeManager; this.versionStore = versionStore; this.logger = logger; } public async Task<Dictionary<SiloAddress, SiloStatus>> GetHosts(bool onlyActive = false) { // If the status oracle isn't MembershipOracle, then it is assumed that it does not use IMembershipTable. // In that event, return the approximate silo statuses from the status oracle. if (!(this.siloStatusOracle is MembershipOracle)) return this.siloStatusOracle.GetApproximateSiloStatuses(onlyActive); // Explicitly read the membership table and return the results. var table = await GetMembershipTable(); var members = await table.ReadAll(); var results = onlyActive ? members.Members.Where(item => item.Item1.Status == SiloStatus.Active) : members.Members; return results.ToDictionary(item => item.Item1.SiloAddress, item => item.Item1.Status); } public async Task<MembershipEntry[]> GetDetailedHosts(bool onlyActive = false) { logger.Info("GetDetailedHosts onlyActive={0}", onlyActive); var mTable = await GetMembershipTable(); var table = await mTable.ReadAll(); if (onlyActive) { return table.Members .Where(item => item.Item1.Status == SiloStatus.Active) .Select(x => x.Item1) .ToArray(); } return table.Members .Select(x => x.Item1) .ToArray(); } public Task ForceGarbageCollection(SiloAddress[] siloAddresses) { var silos = GetSiloAddresses(siloAddresses); logger.Info("Forcing garbage collection on {0}", Utils.EnumerableToString(silos)); List<Task> actionPromises = PerformPerSiloAction(silos, s => GetSiloControlReference(s).ForceGarbageCollection()); return Task.WhenAll(actionPromises); } public Task ForceActivationCollection(SiloAddress[] siloAddresses, TimeSpan ageLimit) { var silos = GetSiloAddresses(siloAddresses); return Task.WhenAll(GetSiloAddresses(silos).Select(s => GetSiloControlReference(s).ForceActivationCollection(ageLimit))); } public async Task ForceActivationCollection(TimeSpan ageLimit) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); SiloAddress[] silos = hosts.Keys.ToArray(); await ForceActivationCollection(silos, ageLimit); } public Task ForceRuntimeStatisticsCollection(SiloAddress[] siloAddresses) { var silos = GetSiloAddresses(siloAddresses); logger.Info("Forcing runtime statistics collection on {0}", Utils.EnumerableToString(silos)); List<Task> actionPromises = PerformPerSiloAction( silos, s => GetSiloControlReference(s).ForceRuntimeStatisticsCollection()); return Task.WhenAll(actionPromises); } public Task<SiloRuntimeStatistics[]> GetRuntimeStatistics(SiloAddress[] siloAddresses) { var silos = GetSiloAddresses(siloAddresses); if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("GetRuntimeStatistics on {0}", Utils.EnumerableToString(silos)); var promises = new List<Task<SiloRuntimeStatistics>>(); foreach (SiloAddress siloAddress in silos) promises.Add(GetSiloControlReference(siloAddress).GetRuntimeStatistics()); return Task.WhenAll(promises); } public async Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics(SiloAddress[] hostsIds) { var all = GetSiloAddresses(hostsIds).Select(s => GetSiloControlReference(s).GetSimpleGrainStatistics()).ToList(); await Task.WhenAll(all); return all.SelectMany(s => s.Result).ToArray(); } public async Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics() { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); SiloAddress[] silos = hosts.Keys.ToArray(); return await GetSimpleGrainStatistics(silos); } public async Task<DetailedGrainStatistic[]> GetDetailedGrainStatistics(string[] types = null, SiloAddress[] hostsIds = null) { if (hostsIds == null) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); hostsIds = hosts.Keys.ToArray(); } var all = GetSiloAddresses(hostsIds).Select(s => GetSiloControlReference(s).GetDetailedGrainStatistics(types)).ToList(); await Task.WhenAll(all); return all.SelectMany(s => s.Result).ToArray(); } public async Task<int> GetGrainActivationCount(GrainReference grainReference) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); List<SiloAddress> hostsIds = hosts.Keys.ToList(); var tasks = new List<Task<DetailedGrainReport>>(); foreach (var silo in hostsIds) tasks.Add(GetSiloControlReference(silo).GetDetailedGrainReport(grainReference.GrainId)); await Task.WhenAll(tasks); return tasks.Select(s => s.Result).Select(r => r.LocalActivations.Count).Sum(); } public async Task<string[]> GetActiveGrainTypes(SiloAddress[] hostsIds=null) { if (hostsIds == null) { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); SiloAddress[] silos = hosts.Keys.ToArray(); } var all = GetSiloAddresses(hostsIds).Select(s => GetSiloControlReference(s).GetGrainTypeList()).ToArray(); await Task.WhenAll(all); return all.SelectMany(s => s.Result).Distinct().ToArray(); } public async Task SetCompatibilityStrategy(CompatibilityStrategy strategy) { await SetStrategy( store => store.SetCompatibilityStrategy(strategy), siloControl => siloControl.SetCompatibilityStrategy(strategy)); } public async Task SetSelectorStrategy(VersionSelectorStrategy strategy) { await SetStrategy( store => store.SetSelectorStrategy(strategy), siloControl => siloControl.SetSelectorStrategy(strategy)); } public async Task SetCompatibilityStrategy(int interfaceId, CompatibilityStrategy strategy) { CheckIfIsExistingInterface(interfaceId); await SetStrategy( store => store.SetCompatibilityStrategy(interfaceId, strategy), siloControl => siloControl.SetCompatibilityStrategy(interfaceId, strategy)); } public async Task SetSelectorStrategy(int interfaceId, VersionSelectorStrategy strategy) { CheckIfIsExistingInterface(interfaceId); await SetStrategy( store => store.SetSelectorStrategy(interfaceId, strategy), siloControl => siloControl.SetSelectorStrategy(interfaceId, strategy)); } public async Task<int> GetTotalActivationCount() { Dictionary<SiloAddress, SiloStatus> hosts = await GetHosts(true); List<SiloAddress> silos = hosts.Keys.ToList(); var tasks = new List<Task<int>>(); foreach (var silo in silos) tasks.Add(GetSiloControlReference(silo).GetActivationCount()); await Task.WhenAll(tasks); int sum = 0; foreach (Task<int> task in tasks) sum += task.Result; return sum; } public Task<object[]> SendControlCommandToProvider(string providerTypeFullName, string providerName, int command, object arg) { return ExecutePerSiloCall(isc => isc.SendControlCommandToProvider(providerTypeFullName, providerName, command, arg), String.Format("SendControlCommandToProvider of type {0} and name {1} command {2}.", providerTypeFullName, providerName, command)); } private void CheckIfIsExistingInterface(int interfaceId) { Type unused; var interfaceMap = this.grainTypeManager.ClusterGrainInterfaceMap; if (!interfaceMap.TryGetServiceInterface(interfaceId, out unused)) { throw new ArgumentException($"Interface code '{interfaceId} not found", nameof(interfaceId)); } } private async Task SetStrategy(Func<IVersionStore, Task> storeFunc, Func<ISiloControl, Task> applyFunc) { await storeFunc(versionStore); var silos = GetSiloAddresses(null); var actionPromises = PerformPerSiloAction( silos, s => applyFunc(GetSiloControlReference(s))); try { await Task.WhenAll(actionPromises); } catch (Exception) { // ignored: silos that failed to set the new strategy will reload it from the storage // in the future. } } private async Task<object[]> ExecutePerSiloCall(Func<ISiloControl, Task<object>> action, string actionToLog) { var silos = await GetHosts(true); if(logger.IsEnabled(LogLevel.Debug)) { logger.Debug("Executing {0} against {1}", actionToLog, Utils.EnumerableToString(silos.Keys)); } var actionPromises = new List<Task<object>>(); foreach (SiloAddress siloAddress in silos.Keys.ToArray()) actionPromises.Add(action(GetSiloControlReference(siloAddress))); return await Task.WhenAll(actionPromises); } private Task<IMembershipTable> GetMembershipTable() { if (!(this.siloStatusOracle is MembershipOracle)) throw new InvalidOperationException("The current membership oracle does not support detailed silo status reporting."); return Task.FromResult(this.membershipTable); } private SiloAddress[] GetSiloAddresses(SiloAddress[] silos) { if (silos != null && silos.Length > 0) return silos; return this.siloStatusOracle .GetApproximateSiloStatuses(true).Select(s => s.Key).ToArray(); } /// <summary> /// Perform an action for each silo. /// </summary> /// <remarks> /// Because SiloControl contains a reference to a system target, each method call using that reference /// will get routed either locally or remotely to the appropriate silo instance auto-magically. /// </remarks> /// <param name="siloAddresses">List of silos to perform the action for</param> /// <param name="perSiloAction">The action function to be performed for each silo</param> /// <returns>Array containing one Task for each silo the action was performed for</returns> private List<Task> PerformPerSiloAction(SiloAddress[] siloAddresses, Func<SiloAddress, Task> perSiloAction) { var requestsToSilos = new List<Task>(); foreach (SiloAddress siloAddress in siloAddresses) requestsToSilos.Add( perSiloAction(siloAddress) ); return requestsToSilos; } private static XmlDocument XPathValuesToXml(Dictionary<string,string> values) { var doc = new XmlDocument(); if (values == null) return doc; foreach (var p in values) { var path = p.Key.Split('/').ToList(); if (path[0] == "") path.RemoveAt(0); if (path[0] != "OrleansConfiguration") path.Insert(0, "OrleansConfiguration"); if (!path[path.Count - 1].StartsWith("@")) throw new ArgumentException("XPath " + p.Key + " must end with @attribute"); AddXPathValue(doc, path, p.Value); } return doc; } private static void AddXPathValue(XmlNode xml, IEnumerable<string> path, string value) { if (path == null) return; var first = path.FirstOrDefault(); if (first == null) return; if (first.StartsWith("@")) { first = first.Substring(1); if (path.Count() != 1) throw new ArgumentException("Attribute " + first + " must be last in path"); var e = xml as XmlElement; if (e == null) throw new ArgumentException("Attribute " + first + " must be on XML element"); e.SetAttribute(first, value); return; } foreach (var child in xml.ChildNodes) { var e = child as XmlElement; if (e != null && e.LocalName == first) { AddXPathValue(e, path.Skip(1), value); return; } } var empty = (xml as XmlDocument ?? xml.OwnerDocument).CreateElement(first); xml.AppendChild(empty); AddXPathValue(empty, path.Skip(1), value); } private ISiloControl GetSiloControlReference(SiloAddress silo) { return this.internalGrainFactory.GetSystemTarget<ISiloControl>(Constants.SiloControlId, silo); } private IMultiClusterOracle GetMultiClusterOracle() { if (!this.multiClusterOptions.HasMultiClusterNetwork) throw new OrleansException("No multicluster network configured"); return this.multiClusterOracle; } public Task<List<IMultiClusterGatewayInfo>> GetMultiClusterGateways() { return Task.FromResult(GetMultiClusterOracle().GetGateways().Cast<IMultiClusterGatewayInfo>().ToList()); } public Task<MultiClusterConfiguration> GetMultiClusterConfiguration() { return Task.FromResult(GetMultiClusterOracle().GetMultiClusterConfiguration()); } public async Task<MultiClusterConfiguration> InjectMultiClusterConfiguration(IEnumerable<string> clusters, string comment = "", bool checkForLaggingSilosFirst = true) { var multiClusterOracle = GetMultiClusterOracle(); var configuration = new MultiClusterConfiguration(DateTime.UtcNow, clusters.ToList(), comment); if (!MultiClusterConfiguration.OlderThan(multiClusterOracle.GetMultiClusterConfiguration(), configuration)) throw new OrleansException("Could not inject multi-cluster configuration: current configuration is newer than clock"); if (checkForLaggingSilosFirst) { try { var laggingSilos = await multiClusterOracle.FindLaggingSilos(multiClusterOracle.GetMultiClusterConfiguration()); if (laggingSilos.Count > 0) { var msg = string.Format("Found unstable silos {0}", string.Join(",", laggingSilos)); throw new OrleansException(msg); } } catch (Exception e) { throw new OrleansException("Could not inject multi-cluster configuration: stability check failed", e); } } await multiClusterOracle.InjectMultiClusterConfiguration(configuration); return configuration; } public Task<List<SiloAddress>> FindLaggingSilos() { var multiClusterOracle = GetMultiClusterOracle(); var expected = multiClusterOracle.GetMultiClusterConfiguration(); return multiClusterOracle.FindLaggingSilos(expected); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.TeamFoundation.Build.WebApi; using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.VisualStudio.Services.Common; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.Services.WebApi; namespace Microsoft.VisualStudio.Services.Agent.Worker.Build { public sealed class ArtifactCommandExtension: BaseWorkerCommandExtension { public ArtifactCommandExtension() { CommandArea = "artifact"; SupportedHostTypes = HostTypes.Build | HostTypes.Release; InstallWorkerCommand(new ArtifactAssociateCommand()); InstallWorkerCommand(new ArtifactUploadCommand()); } } public sealed class ArtifactAssociateCommand: IWorkerCommand { public string Name => "associate"; public List<string> Aliases => null; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA2000:Dispose objects before losing scope", MessageId = "WorkerUtilities")] public void Execute(IExecutionContext context, Command command) { ArgUtil.NotNull(context, nameof(context)); ArgUtil.NotNull(context.Endpoints, nameof(context.Endpoints)); ArgUtil.NotNull(command, nameof(command)); var eventProperties = command.Properties; var data = command.Data; ServiceEndpoint systemConnection = context.Endpoints.FirstOrDefault(e => string.Equals(e.Name, WellKnownServiceEndpointNames.SystemVssConnection, StringComparison.OrdinalIgnoreCase)); ArgUtil.NotNull(systemConnection, nameof(systemConnection)); ArgUtil.NotNull(systemConnection.Url, nameof(systemConnection.Url)); Uri projectUrl = systemConnection.Url; VssCredentials projectCredential = VssUtil.GetVssCredential(systemConnection); Guid projectId = context.Variables.System_TeamProjectId ?? Guid.Empty; ArgUtil.NotEmpty(projectId, nameof(projectId)); int? buildId = context.Variables.Build_BuildId; ArgUtil.NotNull(buildId, nameof(buildId)); string artifactName; if (!eventProperties.TryGetValue(ArtifactAssociateEventProperties.ArtifactName, out artifactName) || string.IsNullOrEmpty(artifactName)) { throw new Exception(StringUtil.Loc("ArtifactNameRequired")); } string artifactType; if (!eventProperties.TryGetValue(ArtifactAssociateEventProperties.ArtifactType, out artifactType)) { artifactType = ArtifactCommandExtensionUtil.InferArtifactResourceType(context, data); } if (string.IsNullOrEmpty(artifactType)) { throw new Exception(StringUtil.Loc("ArtifactTypeRequired")); } else if ((artifactType.Equals(ArtifactResourceTypes.Container, StringComparison.OrdinalIgnoreCase) || artifactType.Equals(ArtifactResourceTypes.FilePath, StringComparison.OrdinalIgnoreCase) || artifactType.Equals(ArtifactResourceTypes.VersionControl, StringComparison.OrdinalIgnoreCase)) && string.IsNullOrEmpty(data)) { throw new Exception(StringUtil.Loc("ArtifactLocationRequired")); } if (!artifactType.Equals(ArtifactResourceTypes.FilePath, StringComparison.OrdinalIgnoreCase) && context.Variables.System_HostType != HostTypes.Build) { throw new Exception(StringUtil.Loc("AssociateArtifactCommandNotSupported", context.Variables.System_HostType)); } var propertyDictionary = ArtifactCommandExtensionUtil.ExtractArtifactProperties(eventProperties); string artifactData = ""; if (ArtifactCommandExtensionUtil.IsContainerPath(data) || ArtifactCommandExtensionUtil.IsValidServerPath(data)) { //if data is a file container path or a tfvc server path artifactData = data; } else if (ArtifactCommandExtensionUtil.IsUncSharePath(context, data)) { //if data is a UNC share path artifactData = new Uri(data).LocalPath; } else { artifactData = data ?? string.Empty; } // queue async command task to associate artifact. context.Debug($"Associate artifact: {artifactName} with build: {buildId.Value} at backend."); var commandContext = context.GetHostContext().CreateService<IAsyncCommandContext>(); commandContext.InitializeCommandContext(context, StringUtil.Loc("AssociateArtifact")); commandContext.Task = ArtifactCommandExtensionUtil.AssociateArtifactAsync(commandContext, WorkerUtilities.GetVssConnection(context), projectId, buildId.Value, artifactName, context.Variables.System_JobId, artifactType, artifactData, propertyDictionary, context.CancellationToken); context.AsyncCommands.Add(commandContext); } } public sealed class ArtifactUploadCommand: IWorkerCommand { public string Name => "upload"; public List<string> Aliases => null; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA2000:Dispose objects before losing scope", MessageId = "WorkerUtilities")] public void Execute(IExecutionContext context, Command command) { ArgUtil.NotNull(context, nameof(context)); ArgUtil.NotNull(context.Endpoints, nameof(context.Endpoints)); ArgUtil.NotNull(command, nameof(command)); var eventProperties = command.Properties; var data = command.Data; Guid projectId = context.Variables.System_TeamProjectId ?? Guid.Empty; ArgUtil.NotEmpty(projectId, nameof(projectId)); int? buildId = context.Variables.Build_BuildId; ArgUtil.NotNull(buildId, nameof(buildId)); long? containerId = context.Variables.Build_ContainerId; ArgUtil.NotNull(containerId, nameof(containerId)); string artifactName; if (!eventProperties.TryGetValue(ArtifactUploadEventProperties.ArtifactName, out artifactName) || string.IsNullOrEmpty(artifactName)) { throw new Exception(StringUtil.Loc("ArtifactNameRequired")); } string containerFolder; if (!eventProperties.TryGetValue(ArtifactUploadEventProperties.ContainerFolder, out containerFolder) || string.IsNullOrEmpty(containerFolder)) { containerFolder = artifactName; } var propertyDictionary = ArtifactCommandExtensionUtil.ExtractArtifactProperties(eventProperties); // Translate file path back from container path string localPath = context.TranslateToHostPath(data); if (string.IsNullOrEmpty(localPath)) { throw new Exception(StringUtil.Loc("ArtifactLocationRequired")); } if (!ArtifactCommandExtensionUtil.IsUncSharePath(context, localPath) && (context.Variables.System_HostType != HostTypes.Build)) { throw new Exception(StringUtil.Loc("UploadArtifactCommandNotSupported", context.Variables.System_HostType)); } string fullPath = Path.GetFullPath(localPath); if (!File.Exists(fullPath) && !Directory.Exists(fullPath)) { // if localPath is not a file or folder on disk throw new FileNotFoundException(StringUtil.Loc("PathDoesNotExist", localPath)); } else if (Directory.Exists(fullPath) && Directory.EnumerateFiles(fullPath, "*", SearchOption.AllDirectories).FirstOrDefault() == null) { // if localPath is a folder but the folder contains nothing context.Warning(StringUtil.Loc("DirectoryIsEmptyForArtifact", fullPath, artifactName)); return; } // queue async command task to associate artifact. context.Debug($"Upload artifact: {fullPath} to server for build: {buildId.Value} at backend."); var commandContext = context.GetHostContext().CreateService<IAsyncCommandContext>(); commandContext.InitializeCommandContext(context, StringUtil.Loc("UploadArtifact")); commandContext.Task = ArtifactCommandExtensionUtil.UploadArtifactAsync(commandContext, WorkerUtilities.GetVssConnection(context), projectId, containerId.Value, containerFolder, buildId.Value, artifactName, context.Variables.System_JobId, propertyDictionary, fullPath, context.CancellationToken); context.AsyncCommands.Add(commandContext); } } internal static class ArtifactCommandExtensionUtil { public static async Task AssociateArtifactAsync( IAsyncCommandContext context, VssConnection connection, Guid projectId, int buildId, string name, string jobId, string type, string data, Dictionary<string, string> propertiesDictionary, CancellationToken cancellationToken) { var buildHelper = context.GetHostContext().GetService<IBuildServer>(); await buildHelper.ConnectAsync(connection); var artifact = await buildHelper.AssociateArtifactAsync(buildId, projectId, name, jobId, type, data, propertiesDictionary, cancellationToken); context.Output(StringUtil.Loc("AssociateArtifactWithBuild", artifact.Id, buildId)); } public static async Task UploadArtifactAsync( IAsyncCommandContext context, VssConnection connection, Guid projectId, long containerId, string containerPath, int buildId, string name, string jobId, Dictionary<string, string> propertiesDictionary, string source, CancellationToken cancellationToken) { var fileContainerHelper = new FileContainerServer(connection, projectId, containerId, containerPath); var size = await fileContainerHelper.CopyToContainerAsync(context, source, cancellationToken); propertiesDictionary.Add(ArtifactUploadEventProperties.ArtifactSize, size.ToString()); var fileContainerFullPath = StringUtil.Format($"#/{containerId}/{containerPath}"); context.Output(StringUtil.Loc("UploadToFileContainer", source, fileContainerFullPath)); var buildHelper = context.GetHostContext().GetService<IBuildServer>(); await buildHelper.ConnectAsync(connection); var artifact = await buildHelper.AssociateArtifactAsync(buildId, projectId, name, jobId, ArtifactResourceTypes.Container, fileContainerFullPath, propertiesDictionary, cancellationToken); context.Output(StringUtil.Loc("AssociateArtifactWithBuild", artifact.Id, buildId)); } public static Boolean IsContainerPath(string path) { return !string.IsNullOrEmpty(path) && path.StartsWith("#", StringComparison.OrdinalIgnoreCase); } public static Boolean IsValidServerPath(string path) { return !string.IsNullOrEmpty(path) && path.Length >= 2 && path[0] == '$' && (path[1] == '/' || path[1] == '\\'); } public static Boolean IsUncSharePath(IExecutionContext context, string path) { if (string.IsNullOrEmpty(path)) { return false; } Uri uri; // Add try catch to avoid unexpected throw from Uri.Property. try { if (Uri.TryCreate(path, UriKind.RelativeOrAbsolute, out uri)) { if (uri.IsAbsoluteUri && uri.IsUnc) { return true; } } } catch (Exception ex) { context.Debug($"Can't determine path: {path} is UNC or not."); context.Debug(ex.ToString()); return false; } return false; } public static string InferArtifactResourceType(IExecutionContext context, string artifactLocation) { string type = ""; if (!string.IsNullOrEmpty(artifactLocation)) { // Prioritize UNC first as leading double-backslash can also match Tfvc VC paths (multiple slashes in a row are ignored) if (IsUncSharePath(context, artifactLocation)) { type = ArtifactResourceTypes.FilePath; } else if (IsValidServerPath(artifactLocation)) { // TFVC artifact type = ArtifactResourceTypes.VersionControl; } else if (IsContainerPath(artifactLocation)) { // file container artifact type = ArtifactResourceTypes.Container; } } if (string.IsNullOrEmpty(type)) { throw new Exception(StringUtil.Loc("UnableResolveArtifactType", artifactLocation ?? string.Empty)); } return type; } public static Dictionary<string, string> ExtractArtifactProperties(Dictionary<string, string> eventProperties) { return eventProperties.Where(pair => !(string.Compare(pair.Key, ArtifactUploadEventProperties.ContainerFolder, StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(pair.Key, ArtifactUploadEventProperties.ArtifactName, StringComparison.OrdinalIgnoreCase) == 0 || string.Compare(pair.Key, ArtifactUploadEventProperties.ArtifactType, StringComparison.OrdinalIgnoreCase) == 0)).ToDictionary(pair => pair.Key, pair => pair.Value); } } internal static class ArtifactAssociateEventProperties { public static readonly string ArtifactName = "artifactname"; public static readonly string ArtifactType = "artifacttype"; public static readonly string Browsable = "Browsable"; } internal static class ArtifactUploadEventProperties { public static readonly string ContainerFolder = "containerfolder"; public static readonly string ArtifactName = "artifactname"; public static readonly string ArtifactSize = "artifactsize"; public static readonly string ArtifactType = "artifacttype"; public static readonly string Browsable = "Browsable"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Android.App; using Android.Bluetooth; using Android.Bluetooth.LE; using Android.OS; using Java.Util; using Plugin.BLE.Abstractions; using Plugin.BLE.Abstractions.Contracts; using Object = Java.Lang.Object; using Trace = Plugin.BLE.Abstractions.Trace; namespace Plugin.BLE.Android { public class Adapter : AdapterBase { private readonly BluetoothManager _bluetoothManager; private readonly BluetoothAdapter _bluetoothAdapter; private readonly Api18BleScanCallback _api18ScanCallback; private readonly Api21BleScanCallback _api21ScanCallback; private readonly GattCallback _gattCallback; public override IList<IDevice> ConnectedDevices => ConnectedDeviceRegistry.Values.ToList(); /// <summary> /// Used to store all connected devices /// </summary> public Dictionary<string, IDevice> ConnectedDeviceRegistry { get; } /// <summary> /// Registry used to store device instances for pending operations : connect /// </summary> public Dictionary<string, IDevice> DeviceOperationRegistry { get; } public Adapter(BluetoothManager bluetoothManager) { _bluetoothManager = bluetoothManager; _bluetoothAdapter = bluetoothManager.Adapter; DeviceOperationRegistry = new Dictionary<string, IDevice>(); ConnectedDeviceRegistry = new Dictionary<string, IDevice>(); // TODO: bonding //var bondStatusBroadcastReceiver = new BondStatusBroadcastReceiver(); //Application.Context.RegisterReceiver(bondStatusBroadcastReceiver, // new IntentFilter(BluetoothDevice.ActionBondStateChanged)); ////forward events from broadcast receiver //bondStatusBroadcastReceiver.BondStateChanged += (s, args) => //{ // //DeviceBondStateChanged(this, args); //}; if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop) { _api21ScanCallback = new Api21BleScanCallback(this); } else { _api18ScanCallback = new Api18BleScanCallback(this); } _gattCallback = new GattCallback(this); } protected override Task StartScanningForDevicesNativeAsync(Guid[] serviceUuids, bool allowDuplicatesKey, CancellationToken scanCancellationToken) { // clear out the list DiscoveredDevices.Clear(); if (serviceUuids == null || !serviceUuids.Any()) { if (Build.VERSION.SdkInt < BuildVersionCodes.Lollipop) { Trace.Message("Adapter < 21: Starting a scan for devices."); //without filter #pragma warning disable 618 _bluetoothAdapter.StartLeScan(_api18ScanCallback); #pragma warning restore 618 } else { Trace.Message("Adapter >= 21: Starting a scan for devices."); if (_bluetoothAdapter.BluetoothLeScanner != null) { _bluetoothAdapter.BluetoothLeScanner.StartScan(_api21ScanCallback); } else { Trace.Message("Adapter >= 21: Scan failed. Bluetooth is probably off"); } } } else { if (Build.VERSION.SdkInt < BuildVersionCodes.Lollipop) { var uuids = serviceUuids.Select(u => UUID.FromString(u.ToString())).ToArray(); Trace.Message("Adapter < 21: Starting a scan for devices."); #pragma warning disable 618 _bluetoothAdapter.StartLeScan(uuids, _api18ScanCallback); #pragma warning restore 618 } else { Trace.Message("Adapter >=21: Starting a scan for devices with service Id {0}.", serviceUuids.First()); var scanFilters = new List<ScanFilter>(); foreach (var serviceUuid in serviceUuids) { var sfb = new ScanFilter.Builder(); sfb.SetServiceUuid(ParcelUuid.FromString(serviceUuid.ToString())); scanFilters.Add(sfb.Build()); } var ssb = new ScanSettings.Builder(); //ssb.SetCallbackType(ScanCallbackType.AllMatches); if (_bluetoothAdapter.BluetoothLeScanner != null) { _bluetoothAdapter.BluetoothLeScanner.StartScan(scanFilters, ssb.Build(), _api21ScanCallback); } else { Trace.Message("Adapter >= 21: Scan failed. Bluetooth is probably off"); } } } return Task.FromResult(true); } protected override void StopScanNative() { if (Build.VERSION.SdkInt < BuildVersionCodes.Lollipop) { Trace.Message("Adapter < 21: Stopping the scan for devices."); #pragma warning disable 618 _bluetoothAdapter.StopLeScan(_api18ScanCallback); #pragma warning restore 618 } else { Trace.Message("Adapter >= 21: Stopping the scan for devices."); _bluetoothAdapter.BluetoothLeScanner?.StopScan(_api21ScanCallback); } } protected override Task ConnectToDeviceNativeAsync(IDevice device, bool autoconnect, CancellationToken cancellationToken) { AddToDeviceOperationRegistry(device); ((BluetoothDevice)device.NativeDevice).ConnectGatt(Application.Context, autoconnect, _gattCallback); return Task.FromResult(true); } protected override void DisconnectDeviceNative(IDevice device) { //make sure everything is disconnected AddToDeviceOperationRegistry(device); ((Device)device).Disconnect(); } public override async Task<IDevice> ConnectToKnownDeviceAsync(Guid deviceGuid, CancellationToken cancellationToken = default(CancellationToken)) { var macBytes = deviceGuid.ToByteArray().Skip(10).Take(6).ToArray(); var nativeDevice = _bluetoothAdapter.GetRemoteDevice(macBytes); var device = new Device(this, nativeDevice, null, null, 0, new byte[] { }); await ConnectToDeviceAsync(device, false, cancellationToken); return device; } public override List<IDevice> GetSystemConnectedOrPairedDevices(Guid[] services = null) { if (services != null) { Trace.Message("Caution: GetSystemConnectedDevices does not take into account the 'services' parameter on Android."); } var connectedDevices = _bluetoothManager.GetConnectedDevices(ProfileType.Gatt).Where(d => d.Type == BluetoothDeviceType.Le); var bondedDevices = _bluetoothAdapter.BondedDevices.Where(d => d.Type == BluetoothDeviceType.Le); return connectedDevices.Union(bondedDevices, new DeviceComparer()).Select(d => new Device(this, d, null, null, 0)).Cast<IDevice>().ToList(); } private class DeviceComparer : IEqualityComparer<BluetoothDevice> { public bool Equals(BluetoothDevice x, BluetoothDevice y) { return x.Address == y.Address; } public int GetHashCode(BluetoothDevice obj) { return obj.GetHashCode(); } } private void AddToDeviceOperationRegistry(IDevice device) { var nativeDevice = ((BluetoothDevice)device.NativeDevice); DeviceOperationRegistry[nativeDevice.Address] = device; } public class Api18BleScanCallback : Object, BluetoothAdapter.ILeScanCallback { private readonly Adapter _adapter; public Api18BleScanCallback(Adapter adapter) { _adapter = adapter; } public void OnLeScan(BluetoothDevice bleDevice, int rssi, byte[] scanRecord) { Trace.Message("Adapter.LeScanCallback: " + bleDevice.Name); _adapter.HandleDiscoveredDevice(new Device(_adapter, bleDevice, null, null, rssi, scanRecord)); } } public class Api21BleScanCallback : ScanCallback { private readonly Adapter _adapter; public Api21BleScanCallback(Adapter adapter) { _adapter = adapter; } public override void OnScanFailed(ScanFailure errorCode) { Trace.Message("Adapter: Scan failed with code {0}", errorCode); base.OnScanFailed(errorCode); } public override void OnScanResult(ScanCallbackType callbackType, ScanResult result) { base.OnScanResult(callbackType, result); /* Might want to transition to parsing the API21+ ScanResult, but sort of a pain for now List<AdvertisementRecord> records = new List<AdvertisementRecord>(); records.Add(new AdvertisementRecord(AdvertisementRecordType.Flags, BitConverter.GetBytes(result.ScanRecord.AdvertiseFlags))); if (!string.IsNullOrEmpty(result.ScanRecord.DeviceName)) { records.Add(new AdvertisementRecord(AdvertisementRecordType.CompleteLocalName, Encoding.UTF8.GetBytes(result.ScanRecord.DeviceName))); } for (int i = 0; i < result.ScanRecord.ManufacturerSpecificData.Size(); i++) { int key = result.ScanRecord.ManufacturerSpecificData.KeyAt(i); var arr = result.ScanRecord.GetManufacturerSpecificData(key); byte[] data = new byte[arr.Length + 2]; BitConverter.GetBytes((ushort)key).CopyTo(data,0); arr.CopyTo(data, 2); records.Add(new AdvertisementRecord(AdvertisementRecordType.ManufacturerSpecificData, data)); } foreach(var uuid in result.ScanRecord.ServiceUuids) { records.Add(new AdvertisementRecord(AdvertisementRecordType.UuidsIncomplete128Bit, uuid.Uuid.)); } foreach(var key in result.ScanRecord.ServiceData.Keys) { records.Add(new AdvertisementRecord(AdvertisementRecordType.ServiceData, result.ScanRecord.ServiceData)); }*/ var device = new Device(_adapter, result.Device, null, null, result.Rssi, result.ScanRecord.GetBytes()); //Device device; //if (result.ScanRecord.ManufacturerSpecificData.Size() > 0) //{ // int key = result.ScanRecord.ManufacturerSpecificData.KeyAt(0); // byte[] mdata = result.ScanRecord.GetManufacturerSpecificData(key); // byte[] mdataWithKey = new byte[mdata.Length + 2]; // BitConverter.GetBytes((ushort)key).CopyTo(mdataWithKey, 0); // mdata.CopyTo(mdataWithKey, 2); // device = new Device(result.Device, null, null, result.Rssi, mdataWithKey); //} //else //{ // device = new Device(result.Device, null, null, result.Rssi, new byte[0]); //} _adapter.HandleDiscoveredDevice(device); } } } }
// // RectilinearEdgeRouter.cs // MSAGL main class for Rectilinear Edge Routing.Routing. // // Copyright Microsoft Corporation. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Microsoft.Msagl.Core.DataStructures; using Microsoft.Msagl.Core.Geometry; using Microsoft.Msagl.Core.Geometry.Curves; using Microsoft.Msagl.Core.Layout; using Microsoft.Msagl.Core.Routing; using Microsoft.Msagl.DebugHelpers; using Microsoft.Msagl.Routing.Rectilinear.Nudging; using Microsoft.Msagl.Routing.Spline.Bundling; using Microsoft.Msagl.Routing.Visibility; using Microsoft.Msagl.Core; namespace Microsoft.Msagl.Routing.Rectilinear { /// <summary> /// Provides rectilinear edge routing functionality /// </summary> public class RectilinearEdgeRouter : AlgorithmBase { /// <summary> /// If an edge does not connect to an obstacle it should stay away from it at least at the padding distance /// </summary> public double Padding { get; set; } /// <summary> /// The radius of the arc inscribed into the path corners. /// </summary> public double CornerFitRadius { get; set; } /// <summary> /// The relative penalty of a bend, representated as a percentage of the Manhattan distance between /// two ports being connected. /// </summary> public double BendPenaltyAsAPercentageOfDistance { get; set; } /// <summary> /// If true, route to obstacle centers. Initially false for greater accuracy with the current /// MultiSourceMultiTarget approach. /// </summary> public bool RouteToCenterOfObstacles { get { return PortManager.RouteToCenterOfObstacles; } set { PortManager.RouteToCenterOfObstacles = value; } } /// <summary> /// If true, limits the extension of port visibility splices into the visibility graph to the rectangle defined by /// the path endpoints. /// </summary> public bool LimitPortVisibilitySpliceToEndpointBoundingBox { get { return this.PortManager.LimitPortVisibilitySpliceToEndpointBoundingBox; } set { this.PortManager.LimitPortVisibilitySpliceToEndpointBoundingBox = value; } } /// <summary> /// Add an EdgeGeometry to route /// </summary> /// <param name="edgeGeometry"></param> public void AddEdgeGeometryToRoute(EdgeGeometry edgeGeometry) { ValidateArg.IsNotNull(edgeGeometry, "edgeGeometry"); // The Port.Location values are not necessarily rounded by the caller. The values // will be rounded upon acquisition in PortManager.cs. PointComparer.Equal expects // all values to be rounded. if (!PointComparer.Equal(ApproximateComparer.Round(edgeGeometry.SourcePort.Location) , ApproximateComparer.Round(edgeGeometry.TargetPort.Location))) { EdgeGeometries.Add(edgeGeometry); } else { selfEdges.Add(edgeGeometry); } } /// <summary> /// Remove a routing specification for an EdgeGeometry. /// </summary> /// <param name="edgeGeometry"></param> public void RemoveEdgeGeometryToRoute(EdgeGeometry edgeGeometry) { EdgeGeometries.Remove(edgeGeometry); } /// <summary> /// List all edge routing specifications that are currently active. We want to hide access to the /// List itself so people don't add or remove items directly. /// </summary> public IEnumerable<EdgeGeometry> EdgeGeometriesToRoute { get { return EdgeGeometries; } } /// <summary> /// Remove all EdgeGeometries to route /// </summary> public void RemoveAllEdgeGeometriesToRoute() { // Don't call RemoveEdgeGeometryToRoute as it will interrupt the EdgeGeometries enumerator. EdgeGeometries.Clear(); } /// <summary> /// If true, this router uses a sparse visibility graph, which saves memory for large graphs but /// may choose suboptimal paths. Set on constructor. /// </summary> public bool UseSparseVisibilityGraph { get { return GraphGenerator is SparseVisibilityGraphGenerator; } } /// <summary> /// If true, this router uses obstacle bounding box rectangles in the visibility graph. /// Set on constructor. /// </summary> public bool UseObstacleRectangles { get; private set; } #region Obstacle API /// <summary> /// The collection of input shapes to route around. Contains all source and target shapes. /// as well as any intervening obstacles. /// </summary> public IEnumerable<Shape> Obstacles { get { return ShapeToObstacleMap.Values.Select(obs => obs.InputShape); } } /// <summary> /// The collection of padded obstacle boundary polylines around the input shapes to route around. /// </summary> internal IEnumerable<Polyline> PaddedObstacles { get { return ShapeToObstacleMap.Values.Select(obs => obs.PaddedPolyline); } } /// <summary> /// Add obstacles to the router. /// </summary> /// <param name="obstacles"></param> public void AddObstacles(IEnumerable<Shape> obstacles) { ValidateArg.IsNotNull(obstacles, "obstacles"); AddShapes(obstacles); RebuildTreeAndGraph(); } private void AddShapes(IEnumerable<Shape> obstacles) { foreach (var shape in obstacles) { this.AddObstacleWithoutRebuild(shape); } } /// <summary> /// Add a single obstacle to the router. /// </summary> /// <param name="shape"></param> public void AddObstacle(Shape shape) { AddObstacleWithoutRebuild(shape); RebuildTreeAndGraph(); } /// <summary> /// For each Shapes, update its position and reroute as necessary. /// </summary> /// <param name="obstacles"></param> public void UpdateObstacles(IEnumerable<Shape> obstacles) { ValidateArg.IsNotNull(obstacles, "obstacles"); foreach (var shape in obstacles) { UpdateObstacleWithoutRebuild(shape); } RebuildTreeAndGraph(); } /// <summary> /// For each Shapes, update its position and reroute as necessary. /// </summary> /// <param name="obstacle"></param> public void UpdateObstacle(Shape obstacle) { UpdateObstacleWithoutRebuild(obstacle); RebuildTreeAndGraph(); } /// <summary> /// Remove obstacles from the router. /// </summary> /// <param name="obstacles"></param> public void RemoveObstacles(IEnumerable<Shape> obstacles) { ValidateArg.IsNotNull(obstacles, "obstacles"); foreach (var shape in obstacles) { RemoveObstacleWithoutRebuild(shape); } RebuildTreeAndGraph(); } /// <summary> /// Removes an obstacle from the router. /// </summary> /// <param name="obstacle"></param> /// <returns>All EdgeGeometries affected by the re-routing and re-nudging in order to avoid the new obstacle.</returns> public void RemoveObstacle(Shape obstacle) { RemoveObstacleWithoutRebuild(obstacle); RebuildTreeAndGraph(); } // utilities [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "BoundaryCurve")] void AddObstacleWithoutRebuild(Shape shape) { ValidateArg.IsNotNull(shape, "shape"); if (null == shape.BoundaryCurve) { throw new InvalidOperationException( #if DEBUG "Shape must have a BoundaryCurve" #endif // DEBUG ); } this.CreatePaddedObstacle(shape); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "BoundaryCurve")] void UpdateObstacleWithoutRebuild(Shape shape) { ValidateArg.IsNotNull(shape, "shape"); if (null == shape.BoundaryCurve) { throw new InvalidOperationException( #if DEBUG "Shape must have a BoundaryCurve" #endif // DEBUG ); } // Always do all of this even if the Shape objects are the same, because the BoundaryCurve probably changed. PortManager.RemoveObstaclePorts(ShapeToObstacleMap[shape]); CreatePaddedObstacle(shape); } private void CreatePaddedObstacle(Shape shape) { var obstacle = new Obstacle(shape, this.UseObstacleRectangles, this.Padding); this.ShapeToObstacleMap[shape] = obstacle; this.PortManager.CreateObstaclePorts(obstacle); } void RemoveObstacleWithoutRebuild(Shape shape) { ValidateArg.IsNotNull(shape, "shape"); Obstacle obstacle = ShapeToObstacleMap[shape]; ShapeToObstacleMap.Remove(shape); PortManager.RemoveObstaclePorts(obstacle); } /// <summary> /// Remove all obstacles from the graph. /// </summary> public void RemoveAllObstacles() { InternalClear(retainObstacles: false); } #endregion // Obstacle API void RebuildTreeAndGraph() { bool hadTree = (null != this.ObstacleTree.Root); bool hadVg = (null != GraphGenerator.VisibilityGraph); InternalClear(retainObstacles: true); if (hadTree) { GenerateObstacleTree(); } if (hadVg) { GenerateVisibilityGraph(); } } /// <summary> /// The visibility graph generated by GenerateVisibilityGraph. /// </summary> internal VisibilityGraph VisibilityGraph { get { GenerateVisibilityGraph(); return GraphGenerator.VisibilityGraph; } } /// <summary> /// Clears all data set into the router. /// </summary> public void Clear() { InternalClear(retainObstacles: false); } #region Private data /// <summary> /// Generates the visibility graph. /// </summary> internal readonly VisibilityGraphGenerator GraphGenerator; /// <summary> /// To support dynamic obstacles, we index obstacles by their Shape, which is /// the unpadded inner obstacle boundary and contains a unique ID so we can /// handle overlap due to dragging. /// </summary> internal readonly Dictionary<Shape, Obstacle> ShapeToObstacleMap = new Dictionary<Shape, Obstacle>(); ///<summary> /// The list of EdgeGeometries to route ///</summary> internal readonly List<EdgeGeometry> EdgeGeometries = new List<EdgeGeometry>(); ///<summary> /// Manages the mapping between App-level Ports, their locations, and their containing EdgeGeometries. ///</summary> internal readonly PortManager PortManager; internal Dictionary<Shape, Set<Shape>> AncestorsSets { get; private set; } #endregion // Private data /// <summary> /// Default constructor. /// </summary> public RectilinearEdgeRouter() : this(null) { // pass-through default arguments to parameterized ctor } /// <summary> /// The padding from an obstacle's curve to its enclosing polyline. /// </summary> public const double DefaultPadding = 1.0; /// <summary> /// The default radius of the arc inscribed into path corners. /// </summary> public const double DefaultCornerFitRadius = 3.0; /// <summary> /// Constructor that takes the obstacles but uses defaults for other arguments. /// </summary> /// <param name="obstacles">The collection of shapes to route around. Contains all source and target shapes /// as well as any intervening obstacles.</param> public RectilinearEdgeRouter(IEnumerable<Shape> obstacles) : this(obstacles, DefaultPadding, DefaultCornerFitRadius, useSparseVisibilityGraph:false, useObstacleRectangles:false) { } /// <summary> /// Constructor for a router that does not use obstacle rectangles in the visibility graph. /// </summary> /// <param name="obstacles">The collection of shapes to route around. Contains all source and target shapes /// as well as any intervening obstacles.</param> /// <param name="padding">The minimum padding from an obstacle's curve to its enclosing polyline.</param> /// <param name="cornerFitRadius">The radius of the arc inscribed into path corners</param> /// <param name="useSparseVisibilityGraph">If true, use a sparse visibility graph, which saves memory for large graphs /// but may select suboptimal paths</param> public RectilinearEdgeRouter(IEnumerable<Shape> obstacles, double padding, double cornerFitRadius, bool useSparseVisibilityGraph) : this(obstacles, padding, cornerFitRadius, useSparseVisibilityGraph, useObstacleRectangles: false) { } /// <summary> /// Constructor specifying graph and shape information. /// </summary> /// <param name="obstacles">The collection of shapes to route around. Contains all source and target shapes /// as well as any intervening obstacles.</param> /// <param name="padding">The minimum padding from an obstacle's curve to its enclosing polyline.</param> /// <param name="cornerFitRadius">The radius of the arc inscribed into path corners</param> /// <param name="useSparseVisibilityGraph">If true, use a sparse visibility graph, which saves memory for large graphs /// but may select suboptimal paths</param> /// <param name="useObstacleRectangles">Use obstacle bounding boxes in visibility graph</param> public RectilinearEdgeRouter(IEnumerable<Shape> obstacles, double padding, double cornerFitRadius, bool useSparseVisibilityGraph, bool useObstacleRectangles) { Padding = padding; CornerFitRadius = cornerFitRadius; BendPenaltyAsAPercentageOfDistance = SsstRectilinearPath.DefaultBendPenaltyAsAPercentageOfDistance; if (useSparseVisibilityGraph) { this.GraphGenerator = new SparseVisibilityGraphGenerator(); } else { this.GraphGenerator = new FullVisibilityGraphGenerator(); } this.UseObstacleRectangles = useObstacleRectangles; PortManager = new PortManager(GraphGenerator); AddShapes(obstacles); } /// <summary> /// Constructor specifying graph information. /// </summary> /// <param name="graph">The graph whose edges are being routed.</param> /// <param name="padding">The minimum padding from an obstacle's curve to its enclosing polyline.</param> /// <param name="cornerFitRadius">The radius of the arc inscribed into path corners</param> /// <param name="useSparseVisibilityGraph">If true, use a sparse visibility graph, which saves memory for large graphs /// but may select suboptimal paths</param> public RectilinearEdgeRouter(GeometryGraph graph, double padding, double cornerFitRadius, bool useSparseVisibilityGraph) : this(graph, padding, cornerFitRadius, useSparseVisibilityGraph, useObstacleRectangles:false) { } /// <summary> /// Constructor specifying graph information. /// </summary> /// <param name="graph">The graph whose edges are being routed.</param> /// <param name="padding">The minimum padding from an obstacle's curve to its enclosing polyline.</param> /// <param name="cornerFitRadius">The radius of the arc inscribed into path corners</param> /// <param name="useSparseVisibilityGraph">If true, use a sparse visibility graph, which saves memory for large graphs /// but may select suboptimal paths</param> /// <param name="useObstacleRectangles">If true, use obstacle bounding boxes in visibility graph</param> public RectilinearEdgeRouter(GeometryGraph graph, double padding, double cornerFitRadius, bool useSparseVisibilityGraph, bool useObstacleRectangles) : this(ShapeCreator.GetShapes(graph), padding, cornerFitRadius, useSparseVisibilityGraph, useObstacleRectangles) { ValidateArg.IsNotNull(graph, "graph"); foreach (var edge in graph.Edges) { this.AddEdgeGeometryToRoute(edge.EdgeGeometry); } } /// <summary> /// Executes the algorithm. /// </summary> protected override void RunInternal() { RouteEdges(); } internal Dictionary<EdgeGeometry, IEnumerable<Path>> edgeGeomsToSplittedEdgePaths; /// <summary> /// Calculates the routed edges geometry, optionally forcing re-routing for existing paths. /// </summary> /// <returns></returns> private void RouteEdges() { // Create visibility graph if not already done. GenerateVisibilityGraph(); GeneratePaths(); } internal virtual void GeneratePaths() { // Split EdgeGeometries with waypoints into a separate Path (containing a separate EdgeGeometry) for each stage. this.edgeGeomsToSplittedEdgePaths = SplitEdgeGeomsWithWaypoints(this.EdgeGeometries); // Create a Path for each EdgeGeometry. GeneratePaths will map from a Path wrapping an EdgeGeometry with waypoints // to the list of split Paths. Wrapping the EdgeGeometries that do have waypoints with a Path is just to make // GeneratePath easier; those Paths are not used because we must do nudging on each stage, otherwise it will // nudge the path off the waypoints. var edgePathsForGeomsWithNoWaypoints = new List<Path>(this.EdgeGeometries.Where(eg => !eg.HasWaypoints).Select(eg => new Path(eg))); var edgePathsForGeomsWithWaypoints = new List<Path>(this.edgeGeomsToSplittedEdgePaths.Keys.Select(eg => new Path(eg))); this.FillEdgePathsWithShortestPaths(edgePathsForGeomsWithNoWaypoints.Concat(edgePathsForGeomsWithWaypoints)); this.NudgePaths(edgePathsForGeomsWithNoWaypoints.Concat(this.edgeGeomsToSplittedEdgePaths.Values.SelectMany(path => path))); this.UniteEdgeCurvesBetweenWaypoints(); this.RouteSelfEdges(); this.FinaliseEdgeGeometries(); } void RouteSelfEdges() { foreach (var edge in selfEdges) { SmoothedPolyline sp; edge.Curve = Edge.RouteSelfEdge(edge.SourcePort.Curve, Math.Max(Padding, 2*edge.GetMaxArrowheadLength()), out sp); } } internal virtual void UniteEdgeCurvesBetweenWaypoints() { foreach (var pair in this.edgeGeomsToSplittedEdgePaths) { EdgeGeometry edgeGeom = pair.Key; IEnumerable<Path> splittedPieces = pair.Value; var polyline = new Polyline(splittedPieces.First().EdgeGeometry.Curve as Polyline); foreach (EdgeGeometry piece in splittedPieces.Skip(1).Select(path => path.EdgeGeometry)) { polyline.AddRangeOfPoints((piece.Curve as Polyline).Skip(1)); } edgeGeom.Curve = polyline; } } #if TEST_MSAGL private IEnumerable<DebugCurve> GetGraphDebugCurves() { List<DebugCurve> l = VisibilityGraph.Edges.Select(e => new DebugCurve(50, 0.1, "blue", new LineSegment(e.SourcePoint, e.TargetPoint))).ToList(); l.AddRange(Obstacles.Select(o => new DebugCurve(1, "green", o.BoundaryCurve))); return l; } #endif private static Dictionary<EdgeGeometry, IEnumerable<Path>> SplitEdgeGeomsWithWaypoints(IEnumerable<EdgeGeometry> edgeGeometries) { var ret = new Dictionary<EdgeGeometry, IEnumerable<Path>>(); foreach (EdgeGeometry edgeGeometry in edgeGeometries.Where(eg => eg.HasWaypoints)) { ret[edgeGeometry] = SplitEdgeGeomWithWaypoints(edgeGeometry, edgeGeometry.Waypoints); } return ret; } private static IEnumerable<Path> SplitEdgeGeomWithWaypoints(EdgeGeometry edgeGeom, IEnumerable<Point> waypoints) { var ret = new List<Path>(); IEnumerator<Point> wp0 = waypoints.GetEnumerator(); wp0.MoveNext(); ret.Add(new Path(new EdgeGeometry(edgeGeom.SourcePort, new WaypointPort(wp0.Current)))); IEnumerator<Point> wp1 = waypoints.GetEnumerator(); wp1.MoveNext(); while (wp1.MoveNext()) { ret.Add(new Path(new EdgeGeometry(new WaypointPort(wp0.Current), new WaypointPort(wp1.Current)))); wp0.MoveNext(); } ret.Add(new Path(new EdgeGeometry(new WaypointPort(wp0.Current), edgeGeom.TargetPort))); return ret; } private void FillEdgePathsWithShortestPaths(IEnumerable<Path> edgePaths) { this.PortManager.BeginRouteEdges(); var shortestPathRouter = new MsmtRectilinearPath(this.BendPenaltyAsAPercentageOfDistance); foreach (Path edgePath in edgePaths) { this.ProgressStep(); AddControlPointsAndGeneratePath(shortestPathRouter, edgePath); } this.PortManager.EndRouteEdges(); } private void AddControlPointsAndGeneratePath(MsmtRectilinearPath shortestPathRouter, Path edgePath) { if (!edgePath.EdgeGeometry.HasWaypoints) { Point[] intersectPoints = PortManager.GetPortVisibilityIntersection(edgePath.EdgeGeometry); if (intersectPoints != null) { GeneratePathThroughVisibilityIntersection(edgePath, intersectPoints); return; } } this.SpliceVisibilityAndGeneratePath(shortestPathRouter, edgePath); } internal virtual void GeneratePathThroughVisibilityIntersection(Path edgePath, Point[] intersectPoints) { edgePath.PathPoints = intersectPoints; } internal virtual void SpliceVisibilityAndGeneratePath(MsmtRectilinearPath shortestPathRouter, Path edgePath) { this.PortManager.AddControlPointsToGraph(edgePath.EdgeGeometry, this.ShapeToObstacleMap); this.PortManager.TransUtil.DevTrace_VerifyAllVertices(this.VisibilityGraph); this.PortManager.TransUtil.DevTrace_VerifyAllEdgeIntersections(this.VisibilityGraph); if (!this.GeneratePath(shortestPathRouter, edgePath)) { this.RetryPathsWithAdditionalGroupsEnabled(shortestPathRouter, edgePath); } this.PortManager.RemoveControlPointsFromGraph(); } #if TEST_MSAGL // ReSharper disable UnusedMember.Local [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private void ShowEdgePath(Path path) { // ReSharper restore UnusedMember.Local List<DebugCurve> dd = Nudger.GetObstacleBoundaries(PaddedObstacles, "black"); dd.AddRange(Nudger.PathDebugCurvesFromPoint(path)); dd.AddRange(VisibilityGraph.Edges.Select(e => new DebugCurve(0.5, "blue", new LineSegment(e.SourcePoint, e.TargetPoint)))); LayoutAlgorithmSettings.ShowDebugCurvesEnumeration(dd); } #endif internal virtual bool GeneratePath(MsmtRectilinearPath shortestPathRouter, Path edgePath, bool lastChance = false) { var sourceVertices = PortManager.FindVertices(edgePath.EdgeGeometry.SourcePort); var targetVertices = PortManager.FindVertices(edgePath.EdgeGeometry.TargetPort); return edgePath.EdgeGeometry.HasWaypoints ? this.GetMultiStagePath(edgePath, shortestPathRouter, sourceVertices, targetVertices, lastChance) : GetSingleStagePath(edgePath, shortestPathRouter, sourceVertices, targetVertices, lastChance); } private static bool GetSingleStagePath(Path edgePath, MsmtRectilinearPath shortestPathRouter, List<VisibilityVertex> sourceVertices, List<VisibilityVertex> targetVertices, bool lastChance) { edgePath.PathPoints = shortestPathRouter.GetPath(sourceVertices, targetVertices); if (lastChance) { EnsureNonNullPath(edgePath); } return (edgePath.PathPoints != null); } private bool GetMultiStagePath(Path edgePath, MsmtRectilinearPath shortestPathRouter, List<VisibilityVertex> sourceVertices, List<VisibilityVertex> targetVertices, bool lastChance) { var waypointVertices = PortManager.FindWaypointVertices(edgePath.EdgeGeometry.Waypoints); var paths = shortestPathRouter.GetPath(sourceVertices, waypointVertices, targetVertices); if (paths == null) { if (!lastChance) { return false; } // Get each stage individually. They won't necessarily be ideal but this should be very rare and // with at least one stage being "forced" through obstacles, the path is not good anyway. foreach (var stagePath in this.edgeGeomsToSplittedEdgePaths[edgePath.EdgeGeometry]) { var stageGeom = stagePath.EdgeGeometry; GetSingleStagePath(stagePath, shortestPathRouter, this.PortManager.FindVertices(stageGeom.SourcePort), this.PortManager.FindVertices(stageGeom.TargetPort), lastChance:true); } return true; } // Record the path for each state. var pathsEnum = paths.GetEnumerator(); foreach (var stagePath in this.edgeGeomsToSplittedEdgePaths[edgePath.EdgeGeometry]) { pathsEnum.MoveNext(); stagePath.PathPoints = pathsEnum.Current; } return true; } private static void EnsureNonNullPath(Path edgePath) { if (null == edgePath.PathPoints) { // Probably a fully-landlocked obstacle such as RectilinearTests.Route_Between_Two_Separately_Landlocked_Obstacles // or disconnected subcomponents due to excessive overlaps, such as Rectilinear(File)Tests.*Disconnected*. In this // case, just put the single-bend path in there, even though it most likely cuts across unrelated obstacles. if (PointComparer.IsPureDirection(edgePath.EdgeGeometry.SourcePort.Location, edgePath.EdgeGeometry.TargetPort.Location)) { edgePath.PathPoints = new[] { edgePath.EdgeGeometry.SourcePort.Location, edgePath.EdgeGeometry.TargetPort.Location }; return; } edgePath.PathPoints = new[] { edgePath.EdgeGeometry.SourcePort.Location, new Point(edgePath.EdgeGeometry.SourcePort.Location.X, edgePath.EdgeGeometry.TargetPort.Location.Y), edgePath.EdgeGeometry.TargetPort.Location }; } } internal virtual void RetryPathsWithAdditionalGroupsEnabled(MsmtRectilinearPath shortestPathRouter, Path edgePath) { // Insert any spatial parent groups that are not in our hierarchical parent tree and retry, // if we haven't already done this. if (!PortManager.SetAllAncestorsActive(edgePath.EdgeGeometry, ShapeToObstacleMap) || !GeneratePath(shortestPathRouter, edgePath)) { // Last chance: enable all groups (if we have any). Only do this on a per-path basis so a single degenerate // path won't make the entire graph look bad. PortManager.SetAllGroupsActive(); GeneratePath(shortestPathRouter, edgePath, lastChance:true); } } #if TEST_MSAGL && !SILVERLIGHT [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Console.WriteLine(System.String)")] internal static void ShowPointEnum(IEnumerable<Point> p) { // ReSharper disable InconsistentNaming const double w0 = 0.1; const int w1 = 3; Point[] arr = p.ToArray(); double d = (w1 - w0)/(arr.Length - 1); var l = new List<DebugCurve>(); for (int i = 0; i < arr.Length - 1; i++) { Console.WriteLine(arr[i]); l.Add(new DebugCurve(100, w0 + i*d, "blue", new LineSegment(arr[i], arr[i + 1]))); } Console.WriteLine(arr.Last()); Console.WriteLine("================"); LayoutAlgorithmSettings.ShowDebugCurvesEnumeration(l); // ReSharper restore InconsistentNaming } #endif internal virtual void NudgePaths(IEnumerable<Path> edgePaths) { // If we adjusted for spatial ancestors, this nudging can get very weird, so refetch in that case. var ancestorSets = this.ObstacleTree.SpatialAncestorsAdjusted ? SplineRouter.GetAncestorSetsMap(Obstacles) : this.AncestorsSets; // Using VisibilityPolyline retains any reflection/staircases on the convex hull borders; using // PaddedPolyline removes them. Nudger.NudgePaths(edgePaths, CornerFitRadius, PaddedObstacles, ancestorSets, RemoveStaircases); //Nudger.NudgePaths(edgePaths, CornerFitRadius, this.ObstacleTree.GetAllPrimaryObstacles().Select(obs => obs.VisibilityPolyline), ancestorSets, RemoveStaircases); } /* MetroGraphData CreateMetroData() { return new MetroGraphData(EdgeGeometries.ToArray(),BuildLooseTree(), BuildTightTree(), GetRoutingWithGroups() , EdgeLooseEnterable(), EdgeTightEnterable()); } Dictionary<EdgeGeometry, Set<Polyline>> EdgeLooseEnterable() { var ret = new Dictionary<EdgeGeometry, Set<Polyline>>(); foreach (var edgeGeometry in EdgeGeometries) { ret[edgeGeometry] = GetEdgeEnterableLoosePolylines(edgeGeometry); } return ret; } Set<Polyline> GetEdgeEnterableLoosePolylines(EdgeGeometry edgeGeometry) { return PortEnterableLoose(edgeGeometry.SourcePort) + PortEnterableLoose(edgeGeometry.TargetPort); } Set<Polyline> PortEnterableLoose(Port port) { var obstPort = PortManager.FindObstaclePort(port); var obst = obstPort.Obstacle; var ret = new Set<Polyline>(); ret.Insert(obst.PaddedPolyline); ret.InsertRange(AncestorsSets[obst.InputShape].Select(sh=>ShapeToObstacleMap[sh].LooseVisibilityPolyline)); return ret; } Set<Polyline> PortEnterableTight(Port port) { var obstPort = PortManager.FindObstaclePort(port); var obst = obstPort.Obstacle; var ret = new Set<Polyline>(); ret.Insert(obst.PaddedPolyline); ret.InsertRange(AncestorsSets[obst.InputShape].Select(sh => ShapeToObstacleMap[sh].PaddedPolyline)); return ret; } Dictionary<EdgeGeometry, Set<Polyline>> EdgeTightEnterable() { var ret = new Dictionary<EdgeGeometry, Set<Polyline>>(); foreach (var edgeGeometry in EdgeGeometries) { ret[edgeGeometry] = GetEdgeEnterableTightPolylines(edgeGeometry); } return ret; } Set<Polyline> GetEdgeEnterableTightPolylines(EdgeGeometry edgeGeometry) { return PortEnterableTight(edgeGeometry.SourcePort) + PortEnterableTight(edgeGeometry.TargetPort); } bool GetRoutingWithGroups() { throw new NotImplementedException(); } RectangleNode<Polyline> BuildTightTree() { throw new NotImplementedException(); } RectangleNode<Polyline> BuildLooseTree() { throw new NotImplementedException(); } */ private bool removeStaircases = true; readonly List<EdgeGeometry> selfEdges = new List<EdgeGeometry>(); ///<summary> ///</summary> public bool RemoveStaircases { get { return removeStaircases; } set { removeStaircases = value; } } internal virtual void FinaliseEdgeGeometries() { foreach (EdgeGeometry edgeGeom in EdgeGeometries.Concat(selfEdges)) { if (null == edgeGeom.Curve) { continue; } var poly = (edgeGeom.Curve as Polyline); if (poly != null) { edgeGeom.Curve = FitArcsIntoCorners(CornerFitRadius, poly.ToArray()); } CalculateArrowheads(edgeGeom); } } internal virtual void CreateVisibilityGraph() { GraphGenerator.Clear(); InitObstacleTree(); GraphGenerator.GenerateVisibilityGraph(); } private static void CalculateArrowheads(EdgeGeometry edgeGeom) { Arrowheads.TrimSplineAndCalculateArrowheads(edgeGeom, edgeGeom.SourcePort.Curve, edgeGeom.TargetPort.Curve, edgeGeom.Curve, true, false); } #region Private functions private ObstacleTree ObstacleTree { get { return this.GraphGenerator.ObstacleTree; } } private void GenerateObstacleTree() { if ((null == Obstacles) || !Obstacles.Any()) { throw new InvalidOperationException( #if TEST_MSAGL "No obstacles have been added" #endif // TEST ); } if (null == this.ObstacleTree.Root) { InitObstacleTree(); } } internal virtual void InitObstacleTree() { AncestorsSets = SplineRouter.GetAncestorSetsMap(Obstacles); this.ObstacleTree.Init(ShapeToObstacleMap.Values, AncestorsSets, ShapeToObstacleMap); } private void InternalClear(bool retainObstacles) { GraphGenerator.Clear(); ClearShortestPaths(); if (retainObstacles) { // Remove precalculated visibility, since we're likely revising obstacle positions. PortManager.ClearVisibility(); } else { PortManager.Clear(); ShapeToObstacleMap.Clear(); EdgeGeometries.Clear(); } } private void ClearShortestPaths() { foreach (EdgeGeometry edgeGeom in EdgeGeometries) { edgeGeom.Curve = null; } } #endregion Private functions /// <summary> /// Generates the visibility graph if it hasn't already been done. /// </summary> internal void GenerateVisibilityGraph() { if ((null == Obstacles) || !Obstacles.Any()) { throw new InvalidOperationException( #if TEST_MSAGL "No obstacles have been set" #endif ); } // Must test GraphGenerator.VisibilityGraph because this.VisibilityGraph calls back to // this function to ensure the graph is present. if (GraphGenerator.VisibilityGraph == null) { CreateVisibilityGraph(); } } #if TEST_MSAGL internal void ShowPathWithTakenEdgesAndGraph(IEnumerable<VisibilityVertex> path, Set<VisibilityEdge> takenEdges){ var list = new List<VisibilityVertex>(path); var lines = new List<LineSegment>(); for (int i = 0; i < list.Count - 1; i++) lines.Add(new LineSegment(list[i].Point, list[i + 1].Point)); // ReSharper disable InconsistentNaming double w0 = 4; const double w1 = 8; double delta = (w1 - w0)/(list.Count - 1); var dc = new List<DebugCurve>(); foreach (LineSegment line in lines) { dc.Add(new DebugCurve(50, w0, "red", line)); w0 += delta; } dc.AddRange(takenEdges.Select(edge => new DebugCurve(50, 2, "black", new LineSegment(edge.SourcePoint, edge.TargetPoint)))); IEnumerable<DebugCurve> k = GetGraphDebugCurves(); dc.AddRange(k); LayoutAlgorithmSettings.ShowDebugCurvesEnumeration(dc); // ReSharper restore InconsistentNaming } #endif internal static ICurve FitArcsIntoCorners(double radius, Point[] polyline) { IEnumerable<Ellipse> ellipses = GetFittedArcSegs(radius, polyline); var curve = new Curve(polyline.Length); Ellipse prevEllipse = null; foreach (Ellipse ellipse in ellipses) { bool ellipseIsAlmostCurve = EllipseIsAlmostLineSegment(ellipse); if (prevEllipse != null) { if (ellipseIsAlmostCurve) Curve.ContinueWithLineSegment(curve, CornerPoint(ellipse)); else { Curve.ContinueWithLineSegment(curve, ellipse.Start); curve.AddSegment(ellipse); } } else { if (ellipseIsAlmostCurve) Curve.AddLineSegment(curve, polyline[0], CornerPoint(ellipse)); else { Curve.AddLineSegment(curve, polyline[0], ellipse.Start); curve.AddSegment(ellipse); } } prevEllipse = ellipse; } if (curve.Segments.Count > 0) Curve.ContinueWithLineSegment(curve, polyline[polyline.Length - 1]); else Curve.AddLineSegment(curve, polyline[0], polyline[polyline.Length - 1]); return curve; } static Point CornerPoint(Ellipse ellipse) { return ellipse.Center + ellipse.AxisA + ellipse.AxisB; } private static bool EllipseIsAlmostLineSegment(Ellipse ellipse) { return ellipse.AxisA.LengthSquared < 0.0001 || ellipse.AxisB.LengthSquared<0.0001; } private static IEnumerable<Ellipse> GetFittedArcSegs(double radius, Point[] polyline) { Point leg = polyline[1] - polyline[0]; Point dir = leg.Normalize(); double rad0 = Math.Min(radius, leg.Length/2); for (int i = 1; i < polyline.Length - 1; i++) { Ellipse ret = null; leg = polyline[i + 1] - polyline[i]; double legLength = leg.Length; if (legLength < ApproximateComparer.IntersectionEpsilon) ret = new Ellipse(0, 0, polyline[i]); Point ndir = leg/legLength; if (Math.Abs(ndir*dir) > 0.9) //the polyline does't make a 90 degrees turn ret = new Ellipse(0, 0, polyline[i]); double nrad0 = Math.Min(radius, leg.Length/2); Point axis0 = -nrad0*ndir; Point axis1 = rad0*dir; yield return ret ?? (new Ellipse(0, Math.PI/2, axis0, axis1, polyline[i] - axis1 - axis0)); dir = ndir; rad0 = nrad0; } } } }
using UnityEngine; using UnityEditor; using System.IO; public class RagePixelSpriteSheetGUI { public Color backgroundColor = (PlayerSettings.advancedLicense) ? new Color(0.2f, 0.2f, 0.2f, 1f) : new Color(0.4f, 0.4f, 0.4f, 1f); public bool animStripIsDirty = false; public bool isDirty = false; public int dragTargetIndex = -1; public int positionX; public int positionY; public Rect bounds { get { return new Rect(positionX, positionY, pixelWidth, pixelHeight); } } private RagePixelSpriteSheet _spriteSheet; public RagePixelSpriteSheet spriteSheet { get { return _spriteSheet; } set { if (value != _spriteSheet) { isDirty = true; _spriteSheet = value; } } } private int _maxWidth = 128; public int maxWidth { get { return _maxWidth; } set { if (Mathf.FloorToInt((float)value / (float)thumbnailSize) != tableWidth) { isDirty = true; } _maxWidth = value; } } private Texture2D _spriteSheetTexture; public Texture2D spriteSheetTexture { get { if (_spriteSheetTexture == null || isDirty) { CreateTextureInstance(); Refresh(); animStripIsDirty = true; isDirty = false; } return _spriteSheetTexture; } } private int _currentRowKey; public int currentRowKey { get { return _currentRowKey; } set { if (_currentRowKey != value) { isDirty = true; _currentRowKey = value; } } } private int thumbnailSize { get { if (spriteSheet != null) { return spriteSheet.thumbnailSize; } else { return 40; } } } public int tableWidth { get { return Mathf.FloorToInt((float)maxWidth / (float)thumbnailSize); } } public int tableHeight { get { if (spriteSheet != null) { return Mathf.Max(Mathf.CeilToInt((float)spriteSheet.rows.Length / (float)tableWidth), 1); } else { return 1; } } } private int _pixelWidth; public int pixelWidth { get { return _pixelWidth; } set { _pixelWidth = value; } } private int _pixelHeight; public int pixelHeight { get { return _pixelHeight; } set { _pixelHeight = value; } } public bool sizeIsDirty(int width) { if (spriteSheet != null) { return Mathf.FloorToInt((float)width / (float)spriteSheet.thumbnailSize) != tableWidth || Mathf.Max(Mathf.CeilToInt((float)spriteSheet.GetRow(currentRowKey).cells.Length / Mathf.FloorToInt((float)width / (float)spriteSheet.thumbnailSize)), 1) != tableHeight; } else { return true; } } public void CreateTextureInstance() { if (_spriteSheetTexture == null) { _spriteSheetTexture = new Texture2D( tableWidth * thumbnailSize + 2, tableHeight * thumbnailSize + 2 ); pixelWidth = tableWidth * thumbnailSize + 2; pixelHeight = tableHeight * thumbnailSize + 2; _spriteSheetTexture.hideFlags = HideFlags.HideAndDontSave; _spriteSheetTexture.filterMode = FilterMode.Point; } else { if (_spriteSheetTexture.width != tableWidth * thumbnailSize + 2 || _spriteSheetTexture.height != tableHeight * thumbnailSize + 2) { Object.DestroyImmediate(_spriteSheetTexture, false); _spriteSheetTexture = new Texture2D( tableWidth * thumbnailSize + 2, tableHeight * thumbnailSize + 2 ); pixelWidth = tableWidth * thumbnailSize + 2; pixelHeight = tableHeight * thumbnailSize + 2; _spriteSheetTexture.hideFlags = HideFlags.HideAndDontSave; _spriteSheetTexture.filterMode = FilterMode.Point; } } } public void Refresh() { if (spriteSheet != null) { Color[] backgroundPixels = new Color[_spriteSheetTexture.width * _spriteSheetTexture.height]; for (int i = 0; i < backgroundPixels.Length; i++) backgroundPixels[i] = backgroundColor; _spriteSheetTexture.SetPixels(backgroundPixels); int y = _spriteSheetTexture.height - thumbnailSize - 1; int x = 1; int currentIndex = spriteSheet.GetIndex(currentRowKey); for (int rowIndex = 0; rowIndex < spriteSheet.rows.Length; rowIndex++) { int showIndex = rowIndex; Color borderColor = Color.white; if (dragTargetIndex >= 0) { if (dragTargetIndex == rowIndex && dragTargetIndex != currentIndex) { showIndex = currentIndex; borderColor = new Color(0.8f, 0.8f, 0f, 1f); } else if (rowIndex < currentIndex && rowIndex < dragTargetIndex || rowIndex > currentIndex && rowIndex > dragTargetIndex) { //noop } else if (rowIndex >= currentIndex && rowIndex < dragTargetIndex) { showIndex = rowIndex + 1; } else if (rowIndex <= currentIndex && rowIndex > dragTargetIndex) { showIndex = rowIndex - 1; } } showIndex = Mathf.Clamp(showIndex, 0, spriteSheet.rows.Length - 1); Color[] thumbnail = spriteSheet.getPreviewImage( showIndex, 0, thumbnailSize - 2, thumbnailSize - 2, spriteSheet.GetKey(showIndex) == currentRowKey, borderColor ); _spriteSheetTexture.SetPixels(x + 1, y + 1, thumbnailSize - 2, thumbnailSize - 2, thumbnail); x += thumbnailSize; if (x + thumbnailSize > _spriteSheetTexture.width - 1) { x = 1; y -= thumbnailSize; } } Color emptySpriteBackgroundColor = (PlayerSettings.advancedLicense) ? new Color(0.22f, 0.22f, 0.22f, 1f) : new Color(0.53f, 0.53f, 0.53f, 1f); Color[] emptySprite = new Color[(thumbnailSize - 2) * (thumbnailSize - 2)]; for (int i = 0; i < emptySprite.Length; i++) emptySprite[i] = emptySpriteBackgroundColor; if (x > 1) { while (x < pixelWidth - thumbnailSize) { _spriteSheetTexture.SetPixels(x + 1, y + 1, thumbnailSize - 2, thumbnailSize - 2, emptySprite); x += thumbnailSize; } } RagePixelUtil.drawPixelBorder(_spriteSheetTexture, new Color(0.1f, 0.1f, 0.1f, 1f)); _spriteSheetTexture.Apply(); } } public int GetRowIndex(int localX, int localY) { int x = localX / thumbnailSize; int y = localY / thumbnailSize; int index = y * tableWidth + x; return index; } public bool HandleGUIEvent(Event ev) { int localX = (int)ev.mousePosition.x - positionX; int localY = (int)ev.mousePosition.y - positionY; if (localX >= 0 && localX <= pixelWidth && localY >= 0 && localY <= pixelHeight) { int index = GetRowIndex(localX, localY); switch (ev.type) { case (EventType.mouseDown): if (index >= 0 && index < spriteSheet.rows.Length && localY >= 0 && localX >= 0) { currentRowKey = spriteSheet.GetKey(index); return true; } else { return false; } case (EventType.mouseUp): if (dragTargetIndex >= 0 && dragTargetIndex != spriteSheet.GetIndex(currentRowKey)) { dragTargetIndex = index; int fromIndex = spriteSheet.GetIndex(currentRowKey); spriteSheet.MoveRow(fromIndex, dragTargetIndex); RagePixelUtil.RebuildAtlas(spriteSheet, false, "MoveRow"); dragTargetIndex = -1; isDirty = true; return true; } else { dragTargetIndex = -1; isDirty = true; return true; } case (EventType.mouseDrag): int newdragTargetIndex = GetRowIndex(localX, localY); if (newdragTargetIndex >= 0 && newdragTargetIndex < spriteSheet.rows.Length) { if (newdragTargetIndex != dragTargetIndex) { dragTargetIndex = newdragTargetIndex; isDirty = true; } } return false; } } return false; } public void CleanExit() { Object.DestroyImmediate(_spriteSheetTexture, false); } }
// 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. // $Id: Protocol.java,v 1.18 2004/07/05 14:17:33 belaban Exp $ using System; using System.Threading; using System.Collections; using Alachisoft.NGroups; using Alachisoft.NGroups.Util; using Alachisoft.NCache.Common.Util; namespace Alachisoft.NGroups.Stack { /// <summary> The Protocol class provides a set of common services for protocol layers. Each layer has to /// be a subclass of Protocol and override a number of methods (typically just <code>up()</code>, /// <code>Down</code> and <code>getName</code>. Layers are stacked in a certain order to form /// a protocol stack. <a href=org.jgroups.Event.html>Events</a> are passed from lower /// layers to upper ones and vice versa. E.g. a Message received by the UDP layer at the bottom /// will be passed to its higher layer as an Event. That layer will in turn pass the Event to /// its layer and so on, until a layer handles the Message and sends a response or discards it, /// the former resulting in another Event being passed down the stack.<p> /// Each layer has 2 FIFO queues, one for up Events and one for down Events. When an Event is /// received by a layer (calling the internal upcall <code>ReceiveUpEvent</code>), it is placed /// in the up-queue where it will be retrieved by the up-handler thread which will invoke method /// <code>Up</code> of the layer. The same applies for Events traveling down the stack. Handling /// of the up-handler and down-handler threads and the 2 FIFO queues is donw by the Protocol /// class, subclasses will almost never have to override this behavior.<p> /// The important thing to bear in mind is that Events have to passed on between layers in FIFO /// order which is guaranteed by the Protocol implementation and must be guranteed by subclasses /// implementing their on Event queuing.<p> /// <b>Note that each class implementing interface Protocol MUST provide an empty, public /// constructor !</b> /// </summary> internal abstract class Protocol { internal class UpHandler:ThreadClass { private Alachisoft.NCache.Common.DataStructures.Queue mq; private Protocol handler; int id; DateTime time; TimeSpan worsTime = new TimeSpan(0,0,0); public UpHandler(Alachisoft.NCache.Common.DataStructures.Queue mq, Protocol handler) { this.mq = mq; this.handler = handler; if (handler != null) { Name = "UpHandler (" + handler.Name + ')'; } else { Name = "UpHandler"; } IsBackground = true; } public UpHandler(Alachisoft.NCache.Common.DataStructures.Queue mq, Protocol handler, string name, int id) { this.mq = mq; this.handler = handler; if(name != null) Name = name; IsBackground = true; this.id = id; } /// <summary>Removes events from mq and calls handler.up(evt) </summary> override public void Run() { if (handler.Stack.NCacheLog.IsInfoEnabled) handler.Stack.NCacheLog.Info(Name, "---> Started!"); try { while (!mq.Closed) { try { Event evt = (Event) mq.remove(); if (evt == null) { handler.Stack.NCacheLog.Warn("Protocol", "removed null event"); continue; } if (handler.enableMonitoring) { handler.PublishUpQueueStats(mq.Count,id); } time = DateTime.Now; handler.up(evt); DateTime now = DateTime.Now; TimeSpan ts = now - time; if (ts.TotalMilliseconds > worsTime.TotalMilliseconds) worsTime = ts; } catch (QueueClosedException e) { handler.Stack.NCacheLog.Error(Name, e.ToString()); break; } catch (ThreadInterruptedException ex) { handler.Stack.NCacheLog.Error(Name, ex.ToString()); break; } catch (System.Exception e) { handler.Stack.NCacheLog.Error(Name, " exception: " + e.ToString()); } } } catch (ThreadInterruptedException ex) { handler.Stack.NCacheLog.Error(Name, ex.ToString()); } if (handler.Stack.NCacheLog.IsInfoEnabled) handler.Stack.NCacheLog.Info(Name + " ---> Stopped!"); } } internal class DownHandler:ThreadClass { private Alachisoft.NCache.Common.DataStructures.Queue mq; private Protocol handler; int id; public DownHandler(Alachisoft.NCache.Common.DataStructures.Queue mq, Protocol handler) { this.mq = mq; this.handler = handler; string name = null; if (handler != null) { Name = "DownHandler (" + handler.Name + ')'; } else { Name = "DownHandler"; } IsBackground = true; } public DownHandler(Alachisoft.NCache.Common.DataStructures.Queue mq, Protocol handler, string name, int id) { this.mq = mq; this.handler = handler; Name = name; IsBackground = true; this.id = id; } /// <summary>Removes events from mq and calls handler.down(evt) </summary> override public void Run() { try { while (!mq.Closed) { try { Event evt = (Event) mq.remove(); if (evt == null) { handler.Stack.NCacheLog.Warn("Protocol", "removed null event"); continue; } int type = evt.Type; if (type == Event.ACK || type == Event.START || type == Event.STOP) { if (handler.handleSpecialDownEvent(evt) == false) continue; } if (handler.enableMonitoring) { handler.PublishDownQueueStats(mq.Count,id); } handler.down(evt); } catch (QueueClosedException e) { handler.Stack.NCacheLog.Error(Name, e.ToString()); break; } catch (ThreadInterruptedException e) { handler.Stack.NCacheLog.Error(Name, e.ToString()); break; } catch (System.Exception e) { handler.Stack.NCacheLog.Warn(Name, " exception is " + e.ToString()); } } } catch (ThreadInterruptedException e) { handler.Stack.NCacheLog.Error("DownHandler.Run():3", "exception=" + e.ToString()); } } } public abstract string Name{get;} public Alachisoft.NCache.Common.DataStructures.Queue UpQueue { get { return up_queue; } } public Alachisoft.NCache.Common.DataStructures.Queue DownQueue { get { return down_queue; } } public ProtocolStack Stack { get { return this.stack; } set { this.stack = value; } } public Protocol UpProtocol { get { return up_prot; } set { this.up_prot = value; } } public Protocol DownProtocol { get { return down_prot; } set { this.down_prot = value; } } protected long THREAD_JOIN_TIMEOUT = 1000; protected Hashtable props = new Hashtable(); protected Protocol up_prot, down_prot; protected ProtocolStack stack; protected Alachisoft.NCache.Common.DataStructures.Queue up_queue, down_queue; protected int up_thread_prio = - 1; protected int down_thread_prio = - 1; protected bool down_thread = false; // determines whether the down_handler thread should be started protected bool up_thread = true; // determines whether the up_handler thread should be started protected UpHandler up_handler; protected DownHandler down_handler; protected bool _printMsgHdrs = false; internal bool enableMonitoring; protected bool useAvgStats = false; /// <summary> Configures the protocol initially. A configuration string consists of name=value /// items, separated by a ';' (semicolon), e.g.:<pre> /// "loopback=false;unicast_inport=4444" /// </pre> /// </summary> public virtual bool setProperties(Hashtable props) { if (props != null) this.props = (Hashtable)props.Clone(); return true; } /// <summary>Called by Configurator. Removes 2 properties which are used by the Protocol directly and then /// calls setProperties(), which might invoke the setProperties() method of the actual protocol instance. /// </summary> public virtual bool setPropertiesInternal(Hashtable props) { this.props = (Hashtable)props.Clone(); if (props.Contains("down_thread")) { down_thread = Convert.ToBoolean(props["down_thread"]); props.Remove("down_thread"); } if (props.Contains("down_thread_prio")) { down_thread_prio = Convert.ToInt32(props["down_thread_prio"]); props.Remove("down_thread_prio"); } if (props.Contains("up_thread")) { up_thread = Convert.ToBoolean(props["up_thread"]); props.Remove("up_thread"); } if (props.Contains("up_thread_prio")) { up_thread_prio = Convert.ToInt32(props["up_thread_prio"]); props.Remove("up_thread_prio"); } if (System.Configuration.ConfigurationSettings.AppSettings["NCacheServer.EnableDebuggingCounters"] != null) { enableMonitoring = Convert.ToBoolean(System.Configuration.ConfigurationSettings.AppSettings["NCacheServer.EnableDebuggingCounters"]); } if (System.Configuration.ConfigurationSettings.AppSettings["useAvgStats"] != null) { useAvgStats = Convert.ToBoolean(System.Configuration.ConfigurationSettings.AppSettings["useAvgStats"]); } return setProperties(props); } public virtual Hashtable getProperties() { return props; } public virtual void PublishUpQueueStats(long count,int queueId) { } public virtual void PublishDownQueueStats(long count,int queueId) { } /// <summary> Called after instance has been created (null constructor) and before protocol is started. /// Properties are already set. Other protocols are not yet connected and events cannot yet be sent. /// </summary> /// <exception cref=""> Exception Thrown if protocol cannot be initialized successfully. This will cause the /// ProtocolStack to fail, so the channel constructor will throw an exception /// </exception> public virtual void init() { } /// <summary> This method is called on a {@link org.jgroups.Channel#connect(String)}. Starts work. /// Protocols are connected and queues are ready to receive events. /// Will be called <em>from bottom to top</em>. This call will replace /// the <b>START</b> and <b>START_OK</b> events. /// </summary> /// <exception cref=""> Exception Thrown if protocol cannot be started successfully. This will cause the ProtocolStack /// to fail, so {@link org.jgroups.Channel#connect(String)} will throw an exception /// </exception> public virtual void start() { } /// <summary> This method is called on a {@link org.jgroups.Channel#disconnect()}. Stops work (e.g. by closing multicast socket). /// Will be called <em>from top to bottom</em>. This means that at the time of the method invocation the /// neighbor protocol below is still working. This method will replace the /// <b>STOP</b>, <b>STOP_OK</b>, <b>CLEANUP</b> and <b>CLEANUP_OK</b> events. The ProtocolStack guarantees that /// when this method is called all messages in the down queue will have been flushed /// </summary> public virtual void stop() { } /// <summary> This method is called on a {@link org.jgroups.Channel#close()}. /// Does some cleanup; after the call the VM will terminate /// </summary> public virtual void destroy() { } /// <summary>List of events that are required to be answered by some layer above.</summary> /// <returns> Vector (of Integers) /// </returns> public virtual ArrayList requiredUpServices() { return null; } /// <summary>List of events that are required to be answered by some layer below.</summary> /// <returns> Vector (of Integers) /// </returns> public virtual ArrayList requiredDownServices() { return null; } /// <summary>List of events that are provided to layers above (they will be handled when sent down from /// above). /// </summary> /// <returns> Vector (of Integers) /// </returns> public virtual ArrayList providedUpServices() { return null; } /// <summary>List of events that are provided to layers below (they will be handled when sent down from /// below). /// </summary> /// <returns> Vector (of Integers) /// </returns> public virtual ArrayList providedDownServices() { return null; } /// <summary>Used internally. If overridden, call this method first. Only creates the up_handler thread /// if down_thread is true /// </summary> public virtual void startUpHandler() { if (up_thread) { if (up_handler == null) { up_queue = new Alachisoft.NCache.Common.DataStructures.Queue(); up_handler = new UpHandler(up_queue, this); up_handler.Start(); } } } /// <summary>Used internally. If overridden, call this method first. Only creates the down_handler thread /// if down_thread is true /// </summary> public virtual void startDownHandler() { if (down_thread) { if (down_handler == null) { down_queue = new Alachisoft.NCache.Common.DataStructures.Queue(); down_handler = new DownHandler(down_queue, this); down_handler.Start(); } } } /// <summary>Used internally. If overridden, call parent's method first </summary> public virtual void stopInternal() { if(up_queue != null) up_queue.close(false); // this should terminate up_handler thread if (up_handler != null && up_handler.IsAlive) { try { up_handler.Join(THREAD_JOIN_TIMEOUT); } catch (System.Exception e) { stack.NCacheLog.Error("Protocol.stopInternal()", "up_handler.Join " + e.Message); } if (up_handler != null && up_handler.IsAlive) { up_handler.Interrupt(); // still alive ? let's just kill it without mercy... try { up_handler.Join(THREAD_JOIN_TIMEOUT); } catch (System.Exception e) { stack.NCacheLog.Error("Protocol.stopInternal()", "up_handler.Join " + e.Message); } if (up_handler != null && up_handler.IsAlive) stack.NCacheLog.Error("Protocol", "up_handler thread for " + Name + " was interrupted (in order to be terminated), but is still alive"); } } up_handler = null; if(down_queue != null) down_queue.close(false); // this should terminate down_handler thread if (down_handler != null && down_handler.IsAlive) { try { down_handler.Join(THREAD_JOIN_TIMEOUT); } catch (System.Exception e) { stack.NCacheLog.Error("Protocol.stopInternal()", "down_handler.Join " + e.Message); } if (down_handler != null && down_handler.IsAlive) { down_handler.Interrupt(); // still alive ? let's just kill it without mercy... try { down_handler.Join(THREAD_JOIN_TIMEOUT); } catch (System.Exception e) { stack.NCacheLog.Error("Protocol.stopInternal()", "down_handler.Join " + e.Message); } if (down_handler != null && down_handler.IsAlive) stack.NCacheLog.Error("Protocol", "down_handler thread for " + Name + " was interrupted (in order to be terminated), but is is still alive"); } } down_handler = null; } /// <summary> Internal method, should not be called by clients. Used by ProtocolStack. I would have /// used the 'friends' modifier, but this is available only in C++ ... If the up_handler thread /// is not available (down_thread == false), then directly call the up() method: we will run on the /// caller's thread (e.g. the protocol layer below us). /// </summary> public virtual void receiveUpEvent(Event evt) { int type = evt.Type; if (_printMsgHdrs && type == Event.MSG) printMsgHeaders(evt,"up()"); if (up_handler == null) { up(evt); return ; } try { if (stack.NCacheLog.IsInfoEnabled) stack.NCacheLog.Info(Name + ".receiveUpEvent()", "RentId :" + evt.RentId + "up queue count : " + up_queue.Count); up_queue.add(evt, evt.Priority); } catch (System.Exception e) { stack.NCacheLog.Warn("Protocol.receiveUpEvent()", e.ToString()); } } /// <summary> /// Prints the header of a message. Used for debugging purpose. /// </summary> /// <param name="evt"></param> protected void printMsgHeaders(Event evt,string extra) { Message m = (Message)evt.Arg; try { if(m != null) { if (stack.NCacheLog.IsInfoEnabled) stack.NCacheLog.Info(this.Name + "." + extra + ".printMsgHeaders()", Global.CollectionToString(m.Headers)); } } catch(Exception e) { stack.NCacheLog.Error(this.Name + ".printMsgHeaders()", e.ToString()); } } /// <summary> Internal method, should not be called by clients. Used by ProtocolStack. I would have /// used the 'friends' modifier, but this is available only in C++ ... If the down_handler thread /// is not available (down_thread == false), then directly call the down() method: we will run on the /// caller's thread (e.g. the protocol layer above us). /// </summary> public virtual void receiveDownEvent(Event evt) { int type = evt.Type; if (down_handler == null) { if (type == Event.ACK || type == Event.START || type == Event.STOP) { if (handleSpecialDownEvent(evt) == false) return ; } if (_printMsgHdrs && type == Event.MSG) printMsgHeaders(evt,"down()"); down(evt); return ; } try { if (type == Event.STOP || type == Event.VIEW_BCAST_MSG) { if (handleSpecialDownEvent(evt) == false) return ; if (down_prot != null) { down_prot.receiveDownEvent(evt); } return; } down_queue.add(evt, evt.Priority); } catch (System.Exception e) { stack.NCacheLog.Warn("Protocol.receiveDownEvent():2", e.ToString()); } } /// <summary> Causes the event to be forwarded to the next layer up in the hierarchy. Typically called /// by the implementation of <code>Up</code> (when done). /// </summary> public virtual void passUp(Event evt) { if (up_prot != null) { up_prot.receiveUpEvent(evt); } else stack.NCacheLog.Error("Protocol", "no upper layer available"); } /// <summary> Causes the event to be forwarded to the next layer down in the hierarchy.Typically called /// by the implementation of <code>Down</code> (when done). /// </summary> public virtual void passDown(Event evt) { if (down_prot != null) { down_prot.receiveDownEvent(evt); } else stack.NCacheLog.Error("Protocol", "no lower layer available"); } /// <summary> An event was received from the layer below. Usually the current layer will want to examine /// the event type and - depending on its type - perform some computation /// (e.g. removing headers from a MSG event type, or updating the internal membership list /// when receiving a VIEW_CHANGE event). /// Finally the event is either a) discarded, or b) an event is sent down /// the stack using <code>passDown()</code> or c) the event (or another event) is sent up /// the stack using <code>passUp()</code>. /// </summary> public virtual void up(Event evt) { passUp(evt); } /// <summary> An event is to be sent down the stack. The layer may want to examine its type and perform /// some action on it, depending on the event's type. If the event is a message MSG, then /// the layer may need to add a header to it (or do nothing at all) before sending it down /// the stack using <code>passDown()</code>. In case of a GET_ADDRESS event (which tries to /// retrieve the stack's address from one of the bottom layers), the layer may need to send /// a new response event back up the stack using <code>passUp()</code>. /// </summary> public virtual void down(Event evt) { passDown(evt); } /// <summary>These are special internal events that should not be handled by protocols</summary> /// <returns> boolean True: the event should be passed further down the stack. False: the event should /// be discarded (not passed down the stack) /// </returns> protected virtual bool handleSpecialDownEvent(Event evt) { switch (evt.Type) { case Event.ACK: if (down_prot == null) { passUp(new Event(Event.ACK_OK)); return false; // don't pass down the stack } goto case Event.START; case Event.START: try { start(); // if we're the transport protocol, reply with a START_OK up the stack if (down_prot == null) { passUp(new Event(Event.START_OK, (object) true)); return false; // don't pass down the stack } return true; // pass down the stack } catch (System.Exception e) { stack.NCacheLog.Error("Protocol.handleSpecialDownEvent", e.ToString()); passUp(new Event(Event.START_OK, new System.Exception(e.Message,e))); } return false; case Event.STOP: try { stop(); } catch (System.Exception e) { stack.NCacheLog.Error("Protocol.handleSpecialDownEvent()", e.ToString()); } if (down_prot == null) { passUp(new Event(Event.STOP_OK, (object) true)); return false; // don't pass down the stack } return true; // pass down the stack default: return true; // pass down by default } } } }
// // ApplicationTrustTest.cs - NUnit tests for ApplicationTrust // // Author: // Sebastien Pouliot <[email protected]> // // Copyright (C) 2005 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #if NET_2_0 using NUnit.Framework; using System; using System.Runtime.Serialization; using System.Security; using System.Security.Permissions; using System.Security.Policy; namespace MonoTests.System.Security.Policy { [TestFixture] public class ApplicationTrustTest { private string AdjustLineEnds (string s) { return s.Replace ("\r\n", "\n"); } [Test] public void Constructor_Empty () { ApplicationTrust at = new ApplicationTrust (); Assert.IsNull (at.ApplicationIdentity, "ApplicationIdentity"); Assert.AreEqual (PolicyStatementAttribute.Nothing, at.DefaultGrantSet.Attributes, "DefaultGrantSet.Attributes"); Assert.AreEqual (String.Empty, at.DefaultGrantSet.AttributeString, "DefaultGrantSet.AttributeString"); Assert.IsTrue (at.DefaultGrantSet.PermissionSet.IsEmpty (), "DefaultGrantSet.PermissionSet.IsEmpty"); Assert.IsFalse (at.DefaultGrantSet.PermissionSet.IsUnrestricted (), "DefaultGrantSet.PermissionSet.IsUnrestricted"); Assert.IsNull (at.ExtraInfo, "ExtraInfo"); Assert.IsFalse (at.IsApplicationTrustedToRun, "IsApplicationTrustedToRun"); Assert.IsFalse (at.Persist, "Persist"); string expected = AdjustLineEnds ("<ApplicationTrust version=\"1\">\r\n<DefaultGrant>\r\n<PolicyStatement version=\"1\">\r\n<PermissionSet class=\"System.Security.PermissionSet\"\r\nversion=\"1\"/>\r\n</PolicyStatement>\r\n</DefaultGrant>\r\n</ApplicationTrust>\r\n"); Assert.AreEqual (expected, AdjustLineEnds (at.ToXml ().ToString ()), "XML"); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void Constructor_Null () { ApplicationTrust at = new ApplicationTrust (null); } [Test] public void ApplicationIdentity () { ApplicationTrust at = new ApplicationTrust (); at.ApplicationIdentity = new ApplicationIdentity ("Mono Unit Test"); Assert.IsNotNull (at.ApplicationIdentity, "not null"); string expected = AdjustLineEnds ("<ApplicationTrust version=\"1\"\r\nFullName=\"Mono Unit Test, Culture=neutral\">\r\n<DefaultGrant>\r\n<PolicyStatement version=\"1\">\r\n<PermissionSet class=\"System.Security.PermissionSet\"\r\nversion=\"1\"/>\r\n</PolicyStatement>\r\n</DefaultGrant>\r\n</ApplicationTrust>\r\n"); Assert.AreEqual (expected, AdjustLineEnds (at.ToXml ().ToString ()), "XML"); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void ApplicationIdentity_Null () { ApplicationTrust at = new ApplicationTrust (); at.ApplicationIdentity = new ApplicationIdentity ("Mono Unit Test"); // once set it cannot be "unset" ... at.ApplicationIdentity = null; } [Test] public void ApplicationIdentity_Change () { ApplicationTrust at = new ApplicationTrust (); at.ApplicationIdentity = new ApplicationIdentity ("Mono Unit Test"); // ... but it can be changed at.ApplicationIdentity = new ApplicationIdentity ("Mono Unit Test Too"); } [Test] public void DefaultGrantSet () { ApplicationTrust at = new ApplicationTrust (); at.DefaultGrantSet = new PolicyStatement (new PermissionSet (PermissionState.Unrestricted)); Assert.IsNotNull (at.DefaultGrantSet, "not null"); string expected = AdjustLineEnds ("<ApplicationTrust version=\"1\">\r\n<DefaultGrant>\r\n<PolicyStatement version=\"1\">\r\n<PermissionSet class=\"System.Security.PermissionSet\"\r\nversion=\"1\"\r\nUnrestricted=\"true\"/>\r\n</PolicyStatement>\r\n</DefaultGrant>\r\n</ApplicationTrust>\r\n"); Assert.AreEqual (expected, AdjustLineEnds (at.ToXml ().ToString ()), "XML"); at.DefaultGrantSet = null; // returns to defaults Assert.IsNotNull (at.DefaultGrantSet, "null"); Assert.AreEqual (PolicyStatementAttribute.Nothing, at.DefaultGrantSet.Attributes, "DefaultGrantSet.Attributes"); Assert.AreEqual (String.Empty, at.DefaultGrantSet.AttributeString, "DefaultGrantSet.AttributeString"); Assert.IsTrue (at.DefaultGrantSet.PermissionSet.IsEmpty (), "DefaultGrantSet.PermissionSet.IsEmpty"); Assert.IsFalse (at.DefaultGrantSet.PermissionSet.IsUnrestricted (), "DefaultGrantSet.PermissionSet.IsUnrestricted"); } [Test] public void ExtraInfo () { ApplicationTrust at = new ApplicationTrust (); at.ExtraInfo = "Mono"; Assert.IsNotNull (at.ExtraInfo, "not null"); string expected = AdjustLineEnds ("<ApplicationTrust version=\"1\">\r\n<DefaultGrant>\r\n<PolicyStatement version=\"1\">\r\n<PermissionSet class=\"System.Security.PermissionSet\"\r\nversion=\"1\"/>\r\n</PolicyStatement>\r\n</DefaultGrant>\r\n<ExtraInfo Data=\"0001000000FFFFFFFF01000000000000000601000000044D6F6E6F0B\"/>\r\n</ApplicationTrust>\r\n"); Assert.AreEqual (expected, AdjustLineEnds (at.ToXml ().ToString ()), "XML"); at.ExtraInfo = null; Assert.IsNull (at.ExtraInfo, "null"); } [Test] [ExpectedException (typeof (SerializationException))] public void ExtraInfo_NotSerializable () { ApplicationTrust at = new ApplicationTrust (); at.ExtraInfo = this; SecurityElement se = at.ToXml (); } [Test] public void IsApplicationTrustedToRun () { ApplicationTrust at = new ApplicationTrust (); at.IsApplicationTrustedToRun = true; Assert.IsTrue (at.IsApplicationTrustedToRun); string expected = AdjustLineEnds ("<ApplicationTrust version=\"1\"\r\nTrustedToRun=\"true\">\r\n<DefaultGrant>\r\n<PolicyStatement version=\"1\">\r\n<PermissionSet class=\"System.Security.PermissionSet\"\r\nversion=\"1\"/>\r\n</PolicyStatement>\r\n</DefaultGrant>\r\n</ApplicationTrust>\r\n"); Assert.AreEqual (expected, AdjustLineEnds (at.ToXml ().ToString ()), "XML"); at.IsApplicationTrustedToRun = false; Assert.IsFalse (at.IsApplicationTrustedToRun); } [Test] public void Persist () { ApplicationTrust at = new ApplicationTrust (); at.Persist = true; Assert.IsTrue (at.Persist, "true"); string expected = AdjustLineEnds ("<ApplicationTrust version=\"1\"\r\nPersist=\"true\">\r\n<DefaultGrant>\r\n<PolicyStatement version=\"1\">\r\n<PermissionSet class=\"System.Security.PermissionSet\"\r\nversion=\"1\"/>\r\n</PolicyStatement>\r\n</DefaultGrant>\r\n</ApplicationTrust>\r\n"); Assert.AreEqual (expected, AdjustLineEnds (at.ToXml ().ToString ()), "XML"); at.Persist = false; Assert.IsFalse (at.Persist, "false"); } [Test] public void ToFromXmlRoundtrip () { ApplicationTrust at = new ApplicationTrust (); at.ApplicationIdentity = new ApplicationIdentity ("Mono Unit Test"); at.DefaultGrantSet = new PolicyStatement (new PermissionSet (PermissionState.Unrestricted)); at.ExtraInfo = "Mono"; at.IsApplicationTrustedToRun = true; at.Persist = true; SecurityElement se = at.ToXml (); string expected = AdjustLineEnds ("<ApplicationTrust version=\"1\"\r\nFullName=\"Mono Unit Test, Culture=neutral\"\r\nTrustedToRun=\"true\"\r\nPersist=\"true\">\r\n<DefaultGrant>\r\n<PolicyStatement version=\"1\">\r\n<PermissionSet class=\"System.Security.PermissionSet\"\r\nversion=\"1\"\r\nUnrestricted=\"true\"/>\r\n</PolicyStatement>\r\n</DefaultGrant>\r\n<ExtraInfo Data=\"0001000000FFFFFFFF01000000000000000601000000044D6F6E6F0B\"/>\r\n</ApplicationTrust>\r\n"); Assert.AreEqual (expected, AdjustLineEnds (at.ToXml ().ToString ()), "XML"); ApplicationTrust copy = new ApplicationTrust (); copy.FromXml (se); se = copy.ToXml (); Assert.AreEqual (expected, AdjustLineEnds (at.ToXml ().ToString ()), "Copy"); } [Test] [ExpectedException (typeof (ArgumentNullException))] public void FromXml_Null () { ApplicationTrust at = new ApplicationTrust (); at.FromXml (null); } [Test] [ExpectedException (typeof (ArgumentException))] public void FromXml_InvalidTag () { ApplicationTrust at = new ApplicationTrust (); SecurityElement se = at.ToXml (); se.Tag = "MonoTrust"; at.FromXml (se); } [Test] public void FromXml_InvalidVersion () { ApplicationTrust at = new ApplicationTrust (); SecurityElement se = at.ToXml (); SecurityElement w = new SecurityElement (se.Tag); w.AddAttribute ("version", "2"); foreach (SecurityElement child in se.Children) w.AddChild (child); at.FromXml (w); } [Test] public void FromXml_NoVersion () { ApplicationTrust at = new ApplicationTrust (); SecurityElement se = at.ToXml (); SecurityElement w = new SecurityElement (se.Tag); foreach (SecurityElement child in se.Children) w.AddChild (child); at.FromXml (w); } [Test] public void FromXml_NoChild () { ApplicationTrust at = new ApplicationTrust (); SecurityElement se = at.ToXml (); SecurityElement w = new SecurityElement (se.Tag); w.AddAttribute ("version", "1"); at.FromXml (w); Assert.IsNull (at.ApplicationIdentity, "ApplicationIdentity"); Assert.AreEqual (PolicyStatementAttribute.Nothing, at.DefaultGrantSet.Attributes, "DefaultGrantSet.Attributes"); Assert.AreEqual (String.Empty, at.DefaultGrantSet.AttributeString, "DefaultGrantSet.AttributeString"); Assert.IsTrue (at.DefaultGrantSet.PermissionSet.IsEmpty (), "DefaultGrantSet.PermissionSet.IsEmpty"); Assert.IsFalse (at.DefaultGrantSet.PermissionSet.IsUnrestricted (), "DefaultGrantSet.PermissionSet.IsUnrestricted"); Assert.IsNull (at.ExtraInfo, "ExtraInfo"); Assert.IsFalse (at.IsApplicationTrustedToRun, "IsApplicationTrustedToRun"); Assert.IsFalse (at.Persist, "Persist"); } } } #endif
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System.Globalization; using ModularityWithUnity.Desktop.Properties; namespace ModularityWithUnity.Desktop { using Microsoft.Practices.Prism.Logging; using Microsoft.Practices.Prism.Modularity; using ModuleTracking; using System; /// <summary> /// Provides tracking of modules for the quickstart. /// </summary> /// <remarks> /// This class is for demonstration purposes for the quickstart and not expected to be used in a real world application. /// This class exports the interface for modules and the concrete type for the shell. /// </remarks> public class ModuleTracker : IModuleTracker { private readonly ModuleTrackingState moduleATrackingState; private readonly ModuleTrackingState moduleBTrackingState; private readonly ModuleTrackingState moduleCTrackingState; private readonly ModuleTrackingState moduleDTrackingState; private readonly ModuleTrackingState moduleETrackingState; private readonly ModuleTrackingState moduleFTrackingState; private ILoggerFacade logger; /// <summary> /// Initializes a new instance of the <see cref="ModuleTracker"/> class. /// </summary> public ModuleTracker(ILoggerFacade logger) { if (logger == null) { throw new ArgumentNullException("logger"); } this.logger = logger; // These states are defined specifically for the desktop version of the quickstart. this.moduleATrackingState = new ModuleTrackingState { ModuleName = WellKnownModuleNames.ModuleA, ExpectedDiscoveryMethod = DiscoveryMethod.ApplicationReference, ExpectedInitializationMode = InitializationMode.WhenAvailable, ExpectedDownloadTiming = DownloadTiming.WithApplication, ConfiguredDependencies = WellKnownModuleNames.ModuleD, }; this.moduleBTrackingState = new ModuleTrackingState { ModuleName = WellKnownModuleNames.ModuleB, ExpectedDiscoveryMethod = DiscoveryMethod.DirectorySweep, ExpectedInitializationMode = InitializationMode.OnDemand, ExpectedDownloadTiming = DownloadTiming.InBackground, }; this.moduleCTrackingState = new ModuleTrackingState { ModuleName = WellKnownModuleNames.ModuleC, ExpectedDiscoveryMethod = DiscoveryMethod.ApplicationReference, ExpectedInitializationMode = InitializationMode.OnDemand, ExpectedDownloadTiming = DownloadTiming.WithApplication, }; this.moduleDTrackingState = new ModuleTrackingState { ModuleName = WellKnownModuleNames.ModuleD, ExpectedDiscoveryMethod = DiscoveryMethod.DirectorySweep, ExpectedInitializationMode = InitializationMode.WhenAvailable, ExpectedDownloadTiming = DownloadTiming.InBackground, }; this.moduleETrackingState = new ModuleTrackingState { ModuleName = WellKnownModuleNames.ModuleE, ExpectedDiscoveryMethod = DiscoveryMethod.ConfigurationManifest, ExpectedInitializationMode = InitializationMode.OnDemand, ExpectedDownloadTiming = DownloadTiming.InBackground, }; this.moduleFTrackingState = new ModuleTrackingState { ModuleName = WellKnownModuleNames.ModuleF, ExpectedDiscoveryMethod = DiscoveryMethod.ConfigurationManifest, ExpectedInitializationMode = InitializationMode.OnDemand, ExpectedDownloadTiming = DownloadTiming.InBackground, ConfiguredDependencies = WellKnownModuleNames.ModuleE, }; } /// <summary> /// Gets the tracking state of module A. /// </summary> /// <value>A ModuleTrackingState.</value> /// <remarks> /// This is exposed as a specific property for data-binding purposes in the quickstart UI. /// </remarks> public ModuleTrackingState ModuleATrackingState { get { return this.moduleATrackingState; } } /// <summary> /// Gets the tracking state of module B. /// </summary> /// <value>A ModuleTrackingState.</value> /// <remarks> /// This is exposed as a specific property for data-binding purposes in the quickstart UI. /// </remarks> public ModuleTrackingState ModuleBTrackingState { get { return this.moduleBTrackingState; } } /// <summary> /// Gets the tracking state of module C. /// </summary> /// <value>A ModuleTrackingState.</value> /// <remarks> /// This is exposed as a specific property for data-binding purposes in the quickstart UI. /// </remarks> public ModuleTrackingState ModuleCTrackingState { get { return this.moduleCTrackingState; } } /// <summary> /// Gets the tracking state of module D. /// </summary> /// <value>A ModuleTrackingState.</value> /// <remarks> /// This is exposed as a specific property for data-binding purposes in the quickstart UI. /// </remarks> public ModuleTrackingState ModuleDTrackingState { get { return this.moduleDTrackingState; } } /// <summary> /// Gets the tracking state of module E. /// </summary> /// <value>A ModuleTrackingState.</value> /// <remarks> /// This is exposed as a specific property for data-binding purposes in the quickstart UI. /// </remarks> public ModuleTrackingState ModuleETrackingState { get { return this.moduleETrackingState; } } /// <summary> /// Gets the tracking state of module F. /// </summary> /// <value>A ModuleTrackingState.</value> /// <remarks> /// This is exposed as a specific property for data-binding purposes in the quickstart UI. /// </remarks> public ModuleTrackingState ModuleFTrackingState { get { return this.moduleFTrackingState; } } /// <summary> /// Records the module is loading. /// </summary> /// <param name="moduleName">The <see cref="WellKnownModuleNames">well-known name</see> of the module.</param> /// <param name="bytesReceived">The number of bytes downloaded.</param> /// <param name="totalBytesToReceive">The total number of bytes received.</param> public void RecordModuleDownloading(string moduleName, long bytesReceived, long totalBytesToReceive) { ModuleTrackingState moduleTrackingState = this.GetModuleTrackingState(moduleName); if (moduleTrackingState != null) { moduleTrackingState.BytesReceived = bytesReceived; moduleTrackingState.TotalBytesToReceive = totalBytesToReceive; if (bytesReceived < totalBytesToReceive) { moduleTrackingState.ModuleInitializationStatus = ModuleInitializationStatus.Downloading; } else { moduleTrackingState.ModuleInitializationStatus = ModuleInitializationStatus.Downloaded; } } this.logger.Log(string.Format(CultureInfo.CurrentCulture, Resources.ModuleIsLoadingProgress, moduleName, bytesReceived, totalBytesToReceive), Category.Debug, Priority.Low); } /// <summary> /// Records the module has been constructed. /// </summary> /// <param name="moduleName">The <see cref="WellKnownModuleNames">well-known name</see> of the module.</param> public void RecordModuleConstructed(string moduleName) { ModuleTrackingState moduleTrackingState = this.GetModuleTrackingState(moduleName); if (moduleTrackingState != null) { moduleTrackingState.ModuleInitializationStatus = ModuleInitializationStatus.Constructed; } this.logger.Log(string.Format(CultureInfo.CurrentCulture, Resources.ModuleConstructed, moduleName), Category.Debug, Priority.Low); } /// <summary> /// Records the module has been initialized. /// </summary> /// <param name="moduleName">The <see cref="WellKnownModuleNames">well-known name</see> of the module.</param> public void RecordModuleInitialized(string moduleName) { ModuleTrackingState moduleTrackingState = this.GetModuleTrackingState(moduleName); if (moduleTrackingState != null) { moduleTrackingState.ModuleInitializationStatus = ModuleInitializationStatus.Initialized; } this.logger.Log(string.Format(CultureInfo.CurrentCulture, Resources.ModuleIsInitialized, moduleName), Category.Debug, Priority.Low); } /// <summary> /// Records the module is loaded. /// </summary> /// <param name="moduleName">The <see cref="WellKnownModuleNames">well-known name</see> of the module.</param> public void RecordModuleLoaded(string moduleName) { this.logger.Log(string.Format(CultureInfo.CurrentCulture, Resources.ModuleLoaded, moduleName), Category.Debug, Priority.Low); } // A helper to make updating specific property instances by name easier. private ModuleTrackingState GetModuleTrackingState(string moduleName) { switch (moduleName) { case WellKnownModuleNames.ModuleA: return this.ModuleATrackingState; case WellKnownModuleNames.ModuleB: return this.ModuleBTrackingState; case WellKnownModuleNames.ModuleC: return this.ModuleCTrackingState; case WellKnownModuleNames.ModuleD: return this.ModuleDTrackingState; case WellKnownModuleNames.ModuleE: return this.ModuleETrackingState; case WellKnownModuleNames.ModuleF: return this.ModuleFTrackingState; default: return null; } } } }
using System; using System.Collections.Generic; using System.Linq; using Sandbox.Game.Entities; using Sandbox.ModAPI; using VRage; using VRage.Game; using VRage.ModAPI; using VRageMath; using Ingame = Sandbox.ModAPI.Ingame; using VRage.Game.ModAPI; using Sandbox.Definitions; using Sandbox.Common.ObjectBuilders; using NaniteConstructionSystem.Particles; using NaniteConstructionSystem.Extensions; using NaniteConstructionSystem.Entities.Beacons; namespace NaniteConstructionSystem.Entities.Targets { public class NaniteProjectionTarget { public int ParticleCount { get; set; } public int StartTime { get; set; } public bool CheckInventory { get; set; } } public class NaniteProjectionTargets : NaniteTargetBlocksBase { public override string TargetName { get { return "Projection"; } } private Dictionary<IMySlimBlock, NaniteProjectionTarget> m_targetBlocks; private float m_orientationAngle = 0.0f; private Vector3 m_dirUp = new Vector3(1.0f, 0.0f, 0.0f); private Vector3 m_dirForward = new Vector3(0.0f, 1.0f, 0.0f); private int m_count; private float m_maxDistance = 300f; //private NaniteConstructionBlock m_constructionBlock; public NaniteProjectionTargets(NaniteConstructionBlock constructionBlock) : base(constructionBlock) { m_count = 0; m_targetBlocks = new Dictionary<IMySlimBlock, NaniteProjectionTarget>(); m_maxDistance = NaniteConstructionManager.Settings.ProjectionMaxBeaconDistance; } public override int GetMaximumTargets() { MyCubeBlock block = (MyCubeBlock)m_constructionBlock.ConstructionBlock; return (int)Math.Min(NaniteConstructionManager.Settings.ProjectionNanitesNoUpgrade + (block.UpgradeValues["ProjectionNanites"] * NaniteConstructionManager.Settings.ProjectionNanitesPerUpgrade), NaniteConstructionManager.Settings.ProjectionMaxStreams); } public override float GetPowerUsage() { MyCubeBlock block = (MyCubeBlock)m_constructionBlock.ConstructionBlock; return Math.Max(1, NaniteConstructionManager.Settings.ProjectionPowerPerStream - (int)(block.UpgradeValues["PowerNanites"] * NaniteConstructionManager.Settings.PowerDecreasePerUpgrade)); } public override float GetMinTravelTime() { MyCubeBlock block = (MyCubeBlock)m_constructionBlock.ConstructionBlock; return Math.Max(1f, NaniteConstructionManager.Settings.ProjectionMinTravelTime - (block.UpgradeValues["SpeedNanites"] * NaniteConstructionManager.Settings.MinTravelTimeReductionPerUpgrade)); } public override float GetSpeed() { MyCubeBlock block = (MyCubeBlock)m_constructionBlock.ConstructionBlock; return NaniteConstructionManager.Settings.ProjectionDistanceDivisor + (block.UpgradeValues["SpeedNanites"] * (float)NaniteConstructionManager.Settings.SpeedIncreasePerUpgrade); } public override bool IsEnabled() { bool result = true; if (!((IMyFunctionalBlock)m_constructionBlock.ConstructionBlock).Enabled || !((IMyFunctionalBlock)m_constructionBlock.ConstructionBlock).IsFunctional || m_constructionBlock.ConstructionBlock.CustomName.ToLower().Contains("NoProjection".ToLower())) result = false; if (NaniteConstructionManager.TerminalSettings.ContainsKey(m_constructionBlock.ConstructionBlock.EntityId)) { if (!NaniteConstructionManager.TerminalSettings[m_constructionBlock.ConstructionBlock.EntityId].AllowProjection) return false; } return result; } public override void FindTargets(ref Dictionary<string, int> available) { ComponentsRequired.Clear(); if (!IsEnabled()) return; if (TargetList.Count >= GetMaximumTargets()) { if(PotentialTargetList.Count > 0) m_lastInvalidTargetReason = "Maximum targets reached. Add more upgrades!"; return; } NaniteConstructionInventory inventoryManager = m_constructionBlock.InventoryManager; Vector3D sourcePosition = m_constructionBlock.ConstructionBlock.GetPosition(); Dictionary<string, int> missing = new Dictionary<string, int>(); using (m_lock.AcquireExclusiveUsing()) { foreach (var item in PotentialTargetList.OrderBy(x => Vector3D.Distance(sourcePosition, EntityHelper.GetBlockPosition((IMySlimBlock)x)))) { if (m_constructionBlock.IsUserDefinedLimitReached()) { m_lastInvalidTargetReason = "User defined maximum nanite limit reached"; return; } if (TargetList.Contains(item)) continue; missing = inventoryManager.GetProjectionComponents((IMySlimBlock)item); bool haveComponents = inventoryManager.CheckComponentsAvailable(ref missing, ref available); if (haveComponents && NaniteConstructionPower.HasRequiredPowerForNewTarget((IMyFunctionalBlock)m_constructionBlock.ConstructionBlock, this)) { if (((IMySlimBlock)item).CubeGrid.GetPosition() == Vector3D.Zero) { m_lastInvalidTargetReason = "Target blocks grid is in an invalid position (Vector3D.Zero, this shouldn't happen!)"; continue; } var blockList = NaniteConstructionManager.GetConstructionBlocks((IMyCubeGrid)m_constructionBlock.ConstructionBlock.CubeGrid); bool found = false; foreach (var block in blockList) { if(block.GetTarget<NaniteProjectionTargets>().TargetList.Contains(item)) { found = true; break; } } if (found) { m_lastInvalidTargetReason = "Another factory has this block as a target"; continue; } TargetList.Add(item); IMySlimBlock slimBlock = (IMySlimBlock)item; var def = slimBlock.BlockDefinition as MyCubeBlockDefinition; Logging.Instance.WriteLine(string.Format("ADDING Projection Target: conid={0} subtypeid={1} entityID={2} position={3}", m_constructionBlock.ConstructionBlock.EntityId, def.Id.SubtypeId, slimBlock.FatBlock != null ? slimBlock.FatBlock.EntityId : 0, slimBlock.Position)); if (TargetList.Count >= GetMaximumTargets()) break; } else if(!haveComponents) { m_lastInvalidTargetReason = "Missing components to start projected block"; } else if(!NaniteConstructionPower.HasRequiredPowerForNewTarget((IMyFunctionalBlock)m_constructionBlock.ConstructionBlock, this)) { m_lastInvalidTargetReason = "Insufficient power for another target."; } } } } public override void Update() { foreach (var item in m_targetList.ToList()) { var block = item as IMySlimBlock; if (block != null) ProcessProjectedItem(block); } } private void ProcessProjectedItem(IMySlimBlock target) { if (Sync.IsServer) { if (target.CubeGrid.GetPosition() == Vector3D.Zero) { Logging.Instance.WriteLine("CANCELLING Projection Target due to invalid position"); CancelTarget(target); return; } if (!IsEnabled()) { Logging.Instance.WriteLine("CANCELLING Projection Target due to being disabled"); CancelTarget(target); return; } if (!NaniteConstructionPower.HasRequiredPowerForCurrentTarget((IMyFunctionalBlock)m_constructionBlock.ConstructionBlock)) { Logging.Instance.WriteLine("CANCELLING Projection Target due to power shortage"); CancelTarget(target); return; } if (m_constructionBlock.FactoryState != NaniteConstructionBlock.FactoryStates.Active) return; double distance = EntityHelper.GetDistanceBetweenBlockAndSlimblock((IMyCubeBlock)m_constructionBlock.ConstructionBlock, target); int time = (int)Math.Max(GetMinTravelTime() * 1000f, (distance / GetSpeed()) * 1000f); if (!m_targetBlocks.ContainsKey(target)) { NaniteProjectionTarget projectionTarget = new NaniteProjectionTarget(); projectionTarget.ParticleCount = 0; projectionTarget.StartTime = (int)MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds; m_targetBlocks.Add(target, projectionTarget); m_constructionBlock.SendAddTarget(target, TargetTypes.Projection, GetProjectorByBlock(target)); } if (MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds - m_targetBlocks[target].StartTime >= time / 2.5 && !m_targetBlocks[target].CheckInventory) { m_targetBlocks[target].CheckInventory = true; if (!m_constructionBlock.InventoryManager.ProcessMissingComponents(target)) { Logging.Instance.WriteLine("CANCELLING Projection Target due to missing components"); CancelTarget(target); return; } } if (MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds - m_targetBlocks[target].StartTime >= time / 2) { //BuildBlock(target, (MyCubeBlock)m_constructionBlock.ConstructionBlock); ProcessBuildBlock(target); CompleteTarget(target); return; } if (!m_potentialTargetList.Contains(target)) { Logging.Instance.WriteLine("COMPLETING Projection Target since potential target is missing"); CompleteTarget(target); return; } } CreateProjectionParticle(target); } public void CancelTarget(IMySlimBlock target) { Logging.Instance.WriteLine(string.Format("CANCELLING Projection Target: {0} - {1} (EntityID={2},Position={3})", m_constructionBlock.ConstructionBlock.EntityId, target.GetType().Name, target.FatBlock != null ? target.FatBlock.EntityId : 0, target.Position)); if (Sync.IsServer) m_constructionBlock.SendCancelTarget(target, TargetTypes.Projection, GetProjectorByBlock(target)); m_constructionBlock.ParticleManager.CancelTarget(target); m_constructionBlock.ToolManager.Remove(target); Remove(target); m_targetBlocks.Remove(target); } public override void CancelTarget(object obj) { var target = obj as IMySlimBlock; if (target == null) return; CancelTarget(target); } public override void CompleteTarget(object obj) { var target = obj as IMySlimBlock; if (target == null) return; CompleteTarget(target); } public void CompleteTarget(IMySlimBlock target) { Logging.Instance.WriteLine(string.Format("COMPLETING Projection Target: {0} - {1} (EntityID={2},Position={3})", m_constructionBlock.ConstructionBlock.EntityId, target.GetType().Name, target.FatBlock != null ? target.FatBlock.EntityId : 0, target.Position)); if (Sync.IsServer) m_constructionBlock.SendCompleteTarget(target, TargetTypes.Projection, GetProjectorByBlock(target)); m_constructionBlock.ParticleManager.CompleteTarget(target); m_constructionBlock.ToolManager.Remove(target); Remove(target); m_targetBlocks.Remove(target); } private void CreateProjectionParticle(IMySlimBlock target) { if (!m_targetBlocks.ContainsKey(target)) { Logging.Instance.WriteLine($"ADD ProjectionParticle Target: {target.Position}"); NaniteProjectionTarget projectionTarget = new NaniteProjectionTarget(); projectionTarget.ParticleCount = 0; projectionTarget.StartTime = (int)MyAPIGateway.Session.ElapsedPlayTime.TotalMilliseconds; m_targetBlocks.Add(target, projectionTarget); } if (NaniteParticleManager.TotalParticleCount > NaniteParticleManager.MaxTotalParticles) return; m_targetBlocks[target].ParticleCount++; int size = (int)Math.Max(60f, NaniteParticleManager.TotalParticleCount); if ((float)m_targetBlocks[target].ParticleCount / size < 1f) return; m_targetBlocks[target].ParticleCount = 0; Vector4 startColor = new Vector4(0.95f, 0.0f, 0.95f, 0.75f); Vector4 endColor = new Vector4(0.035f, 0.0f, 0.35f, 0.75f); m_constructionBlock.ParticleManager.AddParticle(startColor, endColor, GetMinTravelTime() * 1000f, GetSpeed(), target); } public override void ParallelUpdate(List<IMyCubeGrid> gridList, List<IMySlimBlock> blocks) { if (!IsEnabled()) return; if (m_count % 4 == 0) ScanProjection(blocks); m_count++; } private void ScanProjection(List<IMySlimBlock> blocks) { using (m_lock.AcquireExclusiveUsing()) { TargetList.Clear(); PotentialTargetList.Clear(); } HashSet<IMyEntity> entities = new HashSet<IMyEntity>(); MyAPIGateway.Entities.GetEntities(entities, x => x is IMyCubeGrid && x.Physics == null); foreach(var item in blocks) { CheckBlockProjection(item); } foreach (var beaconBlock in NaniteConstructionManager.BeaconList.Where(x => x is NaniteBeaconProjection && Vector3D.DistanceSquared(m_constructionBlock.ConstructionBlock.GetPosition(), x.BeaconBlock.GetPosition()) < m_maxDistance * m_maxDistance)) { IMyCubeBlock item = (IMyCubeBlock)beaconBlock.BeaconBlock; MyRelationsBetweenPlayerAndBlock relation = item.GetUserRelationToOwner(m_constructionBlock.ConstructionBlock.OwnerId); if (!(relation == MyRelationsBetweenPlayerAndBlock.Owner || relation == MyRelationsBetweenPlayerAndBlock.FactionShare || (MyAPIGateway.Session.CreativeMode && relation == MyRelationsBetweenPlayerAndBlock.NoOwnership))) continue; if (!((IMyFunctionalBlock)item).Enabled) continue; List<IMyCubeGrid> beaconGridList = GridHelper.GetGridGroup((IMyCubeGrid)item.CubeGrid); List<IMySlimBlock> beaconBlocks = new List<IMySlimBlock>(); foreach (var grid in beaconGridList) { grid.GetBlocks(beaconBlocks); } foreach (var block in beaconBlocks) { CheckBlockProjection(block); } } CheckAreaBeacons(); } public static long GetProjectorByBlock(IMySlimBlock block) { foreach(var item in NaniteConstructionManager.ProjectorBlocks) { var projector = item.Value as IMyProjector; if(projector.ProjectedGrid != null && projector.ProjectedGrid.EntityId == block.CubeGrid.EntityId) { return projector.EntityId; } } return 0; } private void CheckAreaBeacons() { foreach (var beaconBlock in NaniteConstructionManager.BeaconList.Where(x => x is NaniteAreaBeacon)) { IMyCubeBlock cubeBlock = beaconBlock.BeaconBlock; if (!((IMyFunctionalBlock)cubeBlock).Enabled) continue; var item = beaconBlock as NaniteAreaBeacon; if (!item.Settings.AllowProjection) continue; HashSet<IMyEntity> entities = new HashSet<IMyEntity>(); MyAPIGateway.Entities.GetEntities(entities); foreach (var entity in entities) { var grid = entity as IMyCubeGrid; if (grid == null) continue; if ((grid.GetPosition() - cubeBlock.GetPosition()).LengthSquared() < m_maxDistance * m_maxDistance) { foreach (IMySlimBlock block in ((MyCubeGrid)grid).GetBlocks()) { BoundingBoxD blockbb; block.GetWorldBoundingBox(out blockbb, true); if (item.IsInsideBox(blockbb)) CheckBlockProjection(block); } } } } } private void CheckBlockProjection(IMySlimBlock item) { if (item.FatBlock == null) return; if (!(item.FatBlock is IMyProjector)) return; IMyProjector projector = item.FatBlock as IMyProjector; if (!projector.Enabled) return; if (projector.ProjectedGrid == null) return; //Logging.Instance.WriteLine(string.Format("Projector: {0} - BuildableBlocksCount: {1}", projector.CustomName, projector.BuildableBlocksCount)); if (projector.BuildableBlocksCount > 0) { ProcessProjector(projector); } } private void ProcessProjector(IMyProjector projector) { MyCubeGrid grid = (MyCubeGrid)projector.ProjectedGrid; foreach(IMySlimBlock block in grid.GetBlocks()) { if(projector.CanBuild(block, false) == BuildCheckResult.OK) { using (Lock.AcquireExclusiveUsing()) { if(!PotentialTargetList.Contains(block)) PotentialTargetList.Add(block); } } } } private void ProcessBuildBlock(IMySlimBlock block) { foreach(var item in NaniteConstructionManager.ProjectorBlocks) { var projector = item.Value as IMyProjector; if (projector == null) continue; if(projector.ProjectedGrid == block.CubeGrid) { projector.Build(block, 0, m_constructionBlock.ConstructionBlock.EntityId, false); break; } } } private bool UpdateProjection(MyCubeBlock projector, MyCubeGrid projectedGrid, MyObjectBuilder_ProjectorBase projectorBuilder) { // god fucking damnit object builders MyCubeGrid cubeGrid = projector.CubeGrid; MyObjectBuilder_CubeGrid gridBuilder = (MyObjectBuilder_CubeGrid)projectedGrid.GetObjectBuilder(); bool found = false; foreach (MyObjectBuilder_CubeBlock blockBuilder in gridBuilder.CubeBlocks) { Vector3 worldPosition = projectedGrid.GridIntegerToWorld(blockBuilder.Min); Vector3I realPosition = cubeGrid.WorldToGridInteger(worldPosition); var realBlock = (IMySlimBlock)cubeGrid.GetCubeBlock(realPosition); MyCubeBlockDefinition blockDefinition; MyDefinitionManager.Static.TryGetCubeBlockDefinition(blockBuilder.GetId(), out blockDefinition); if (realBlock != null) // && blockDefinition.Id == new MyDefinitionId(realBlock.GetType())) { //Logging.Instance.WriteLine(string.Format("Found overlap - {0} {1}", blockBuilder.GetId(), realBlock.GetObjectBuilder().GetId())); } else { //Logging.Instance.WriteLine(string.Format("No block at position: {0}", blockBuilder.GetId())); if (CanBuildBlock(blockBuilder, projectedGrid, projector, cubeGrid, projectorBuilder)) { //Logging.Instance.WriteLine(string.Format("No block at position: {0}", blockBuilder.GetId())); var slimBlock = (IMySlimBlock)projectedGrid.GetCubeBlock(blockBuilder.Min); if (slimBlock != null && slimBlock.CubeGrid.GetPosition() != Vector3D.Zero) { //Logging.Instance.WriteLine(string.Format("Adding block: {0}", blockBuilder.GetId())); PotentialTargetList.Add(slimBlock); found = true; } } else { using (m_lock.AcquireExclusiveUsing()) { foreach (var item in blockDefinition.Components) { if (!ComponentsRequired.ContainsKey(item.Definition.Id.SubtypeName)) ComponentsRequired.Add(item.Definition.Id.SubtypeName, item.Count); else ComponentsRequired[item.Definition.Id.SubtypeName] += item.Count; } } } } } return found; } private bool CanBuildBlock(MyObjectBuilder_CubeBlock block, MyCubeGrid blockGrid, MyCubeBlock projector, MyCubeGrid projectorGrid, MyObjectBuilder_ProjectorBase projectorBuilder) { MyBlockOrientation blockOrientation = block.BlockOrientation; Matrix local; blockOrientation.GetMatrix(out local); var gridOrientation = GetGridOrientation(projectorBuilder); if (gridOrientation != Matrix.Identity) { var afterRotation = Matrix.Multiply(local, gridOrientation); blockOrientation = new MyBlockOrientation(ref afterRotation); } Quaternion blockOrientationQuat; blockOrientation.GetQuaternion(out blockOrientationQuat); Quaternion projQuat = Quaternion.Identity; projector.Orientation.GetQuaternion(out projQuat); blockOrientationQuat = Quaternion.Multiply(projQuat, blockOrientationQuat); MyCubeBlockDefinition blockDefinition; MyDefinitionManager.Static.TryGetCubeBlockDefinition(block.GetId(), out blockDefinition); // Get real block max Vector3I blockMax = Vector3I.Zero; Vector3I blockMin = block.Min; ComputeMax(blockDefinition, block.BlockOrientation, ref blockMin, out blockMax); var position = ComputePositionInGrid(new MatrixI(block.BlockOrientation), blockDefinition, blockMin); Vector3I projectedMin = projectorGrid.WorldToGridInteger(blockGrid.GridIntegerToWorld(block.Min)); Vector3I projectedMax = projectorGrid.WorldToGridInteger(blockGrid.GridIntegerToWorld(blockMax)); Vector3I blockPos = projectorGrid.WorldToGridInteger(blockGrid.GridIntegerToWorld(position)); Vector3I min = new Vector3I(Math.Min(projectedMin.X, projectedMax.X), Math.Min(projectedMin.Y, projectedMax.Y), Math.Min(projectedMin.Z, projectedMax.Z)); Vector3I max = new Vector3I(Math.Max(projectedMin.X, projectedMax.X), Math.Max(projectedMin.Y, projectedMax.Y), Math.Max(projectedMin.Z, projectedMax.Z)); projectedMin = min; projectedMax = max; if (!projectorGrid.CanAddCubes(projectedMin, projectedMax)) { IMySlimBlock slimBlock = (IMySlimBlock)blockGrid.GetCubeBlock(block.Min); if (slimBlock == null || slimBlock.FatBlock == null) return false; Logging.Instance.WriteLine(string.Format("Can not add block: {0}: {1} - {2} {3} {4} {5}", slimBlock.FatBlock.EntityId, blockDefinition.Id, projectedMin, projectedMax, blockMin, blockMax)); //, slimBlock.FatBlock.EntityId)); return false; } var mountPoints = blockDefinition.GetBuildProgressModelMountPoints(1.0f); bool isConnected = MyCubeGrid.CheckConnectivity(projectorGrid, blockDefinition, mountPoints, ref blockOrientationQuat, ref blockPos); if (isConnected) { if (projectorGrid.GetCubeBlock(blockPos) == null) { return true; } else { return false; } } else { return false; } } private void BuildBlock(IMySlimBlock block, MyCubeBlock constructionBlock) { MyObjectBuilder_CubeBlock cubeBlock = block.GetObjectBuilder(); MyObjectBuilder_ProjectorBase projectorBuilder = null;// = (MyObjectBuilder_ProjectorBase)constructionBlock.GetObjectBuilderCubeBlock(); MyCubeGrid projectorGrid = null; MyCubeGrid blockGrid = (MyCubeGrid)block.CubeGrid; MyCubeBlock projector = null; foreach(var item in NaniteConstructionManager.ProjectorBlocks) { var projectorTest = item.Value as IMyProjector; if (projectorTest == null) continue; if (projectorTest.ProjectedGrid == null) continue; if(projectorTest.ProjectedGrid == block.CubeGrid) { projector = (MyCubeBlock)projectorTest; projectorGrid = projector.CubeGrid; projectorBuilder = (MyObjectBuilder_ProjectorBase)projector.GetObjectBuilderCubeBlock(); break; } } /* Ingame.IMyGridTerminalSystem system = MyAPIGateway.TerminalActionsHelper.GetTerminalSystemForGrid((IMyCubeGrid)m_constructionBlock.ConstructionBlock.CubeGrid); List<Ingame.IMyTerminalBlock> terminalBlocks = new List<Ingame.IMyTerminalBlock>(); system.GetBlocks(terminalBlocks); foreach(var item in terminalBlocks) { if (!(item is IMyFunctionalBlock) || !((IMyFunctionalBlock)item).Enabled) continue; if (!(item is Ingame.IMyProjector)) continue; var cube = (MyCubeBlock)item; MyObjectBuilder_ProjectorBase testBuilder = (MyObjectBuilder_ProjectorBase)cube.GetObjectBuilderCubeBlock(); if (testBuilder.ProjectedGrid == null) continue; if(testBuilder.ProjectedGrid.DisplayName == blockGrid.DisplayName) { projector = cube; projectorGrid = cube.CubeGrid; projectorBuilder = testBuilder; break; } } */ if(projectorBuilder == null) { Logging.Instance.WriteLine("PROBLEM Can not locate projector that is projecting target!"); return; } Quaternion quat = Quaternion.Identity; var orientation = block.Orientation; Matrix local; orientation.GetMatrix(out local); var gridOrientation = GetGridOrientation(projectorBuilder); if (gridOrientation != Matrix.Identity) { var afterRotation = Matrix.Multiply(local, gridOrientation); orientation = new MyBlockOrientation(ref afterRotation); } Quaternion projQuat = Quaternion.Identity; projector.Orientation.GetQuaternion(out projQuat); orientation.GetQuaternion(out quat); quat = Quaternion.Multiply(projQuat, quat); // Get real block max MyCubeBlockDefinition blockDefinition = (MyCubeBlockDefinition)block.BlockDefinition; Vector3I blockMax = block.Max; Vector3I blockMin = cubeBlock.Min; Vector3I position = block.Position; Vector3I min = projectorGrid.WorldToGridInteger(blockGrid.GridIntegerToWorld(blockMin)); Vector3I max = projectorGrid.WorldToGridInteger(blockGrid.GridIntegerToWorld(blockMax)); Vector3I pos = projectorGrid.WorldToGridInteger(blockGrid.GridIntegerToWorld(block.Position)); Vector3I projectedMin = new Vector3I(Math.Min(min.X, max.X), Math.Min(min.Y, max.Y), Math.Min(min.Z, max.Z)); Vector3I projectedMax = new Vector3I(Math.Max(min.X, max.X), Math.Max(min.Y, max.Y), Math.Max(min.Z, max.Z)); MyCubeGrid.MyBlockLocation location = new MyCubeGrid.MyBlockLocation(blockDefinition.Id, projectedMin, projectedMax, pos, quat, 0, constructionBlock.OwnerId); /* MyObjectBuilder_CubeGrid originalGridBuilder = (MyObjectBuilder_CubeGrid)blockGrid.GetObjectBuilder(); MyObjectBuilder_CubeBlock objectBuilder = null; //Find original grid builder foreach (var blockBuilder in originalGridBuilder.CubeBlocks) { if (blockBuilder.GetId() == blockDefinition.Id) { if ((Vector3I)blockBuilder.Min == blockMin) { objectBuilder = (MyObjectBuilder_CubeBlock)blockBuilder.Clone(); objectBuilder.SetupForProjector(); } } } */ MyObjectBuilder_CubeBlock objectBuilder = cubeBlock; objectBuilder.SetupForProjector(); var functionalBuilder = objectBuilder as MyObjectBuilder_FunctionalBlock; if (functionalBuilder != null && !functionalBuilder.Enabled) functionalBuilder.Enabled = true; var terminalBuilder = objectBuilder as MyObjectBuilder_TerminalBlock; if (terminalBuilder != null) terminalBuilder.Owner = constructionBlock.OwnerId; var shipConnector = objectBuilder as MyObjectBuilder_ShipConnector; if(shipConnector != null) { shipConnector.Connected = false; shipConnector.ConnectedEntityId = 0; shipConnector.MasterToSlaveGrid = null; shipConnector.MasterToSlaveTransform = null; } //if (objectBuilder == null) // objectBuilder = cubeBlock; location.EntityId = 0; // MyEntityIdentifier.AllocateId(); objectBuilder.EntityId = 0; objectBuilder.ConstructionInventory = null; projector.CubeGrid.BuildBlockRequest(block.GetColorMask().PackHSVToUint(), location, objectBuilder, constructionBlock.EntityId, false, constructionBlock.OwnerId); } private void ComputeMax(MyCubeBlockDefinition definition, MyBlockOrientation orientation, ref Vector3I min, out Vector3I max) { Vector3I size = definition.Size - 1; MatrixI localMatrix = new MatrixI(orientation); Vector3I.TransformNormal(ref size, ref localMatrix, out size); Vector3I.Abs(ref size, out size); max = min + size; } private Vector3I ComputePositionInGrid(MatrixI localMatrix, MyCubeBlockDefinition blockDefinition, Vector3I min) { var center = blockDefinition.Center; var sizeMinusOne = blockDefinition.Size - 1; Vector3I rotatedBlockSize; Vector3I rotatedCenter; Vector3I.TransformNormal(ref sizeMinusOne, ref localMatrix, out rotatedBlockSize); Vector3I.TransformNormal(ref center, ref localMatrix, out rotatedCenter); var trueSize = Vector3I.Abs(rotatedBlockSize); var offsetCenter = rotatedCenter + min; if (rotatedBlockSize.X != trueSize.X) offsetCenter.X += trueSize.X; if (rotatedBlockSize.Y != trueSize.Y) offsetCenter.Y += trueSize.Y; if (rotatedBlockSize.Z != trueSize.Z) offsetCenter.Z += trueSize.Z; return offsetCenter; } private Matrix GetGridOrientation(MyObjectBuilder_ProjectorBase projectorBuilder) { m_dirForward = Vector3.Forward; m_dirUp = Vector3.Up; m_orientationAngle = 0f; RotateAroundAxis(0, Math.Sign(projectorBuilder.ProjectionRotation.X), Math.Abs(projectorBuilder.ProjectionRotation.X * MathHelper.PiOver2)); RotateAroundAxis(1, Math.Sign(projectorBuilder.ProjectionRotation.Y), Math.Abs(projectorBuilder.ProjectionRotation.Y * MathHelper.PiOver2)); RotateAroundAxis(2, Math.Sign(projectorBuilder.ProjectionRotation.Z), Math.Abs(projectorBuilder.ProjectionRotation.Z * MathHelper.PiOver2)); return Matrix.CreateWorld(Vector3.Zero, m_dirForward, m_dirUp) * Matrix.CreateFromAxisAngle(m_dirUp, m_orientationAngle); } private void RotateAroundAxis(int axisIndex, int sign, float angleDelta) { switch (axisIndex) { case 0: if (sign < 0) UpMinus(angleDelta); else UpPlus(angleDelta); break; case 1: if (sign < 0) AngleMinus(angleDelta); else AnglePlus(angleDelta); break; case 2: if (sign < 0) RightPlus(angleDelta); else RightMinus(angleDelta); break; } } private void AnglePlus(float angle) { m_orientationAngle += angle; if (m_orientationAngle >= (float)Math.PI * 2.0f) { m_orientationAngle -= (float)Math.PI * 2.0f; } } private void AngleMinus(float angle) { m_orientationAngle -= angle; if (m_orientationAngle < 0.0f) { m_orientationAngle += (float)Math.PI * 2.0f; } } private void UpPlus(float angle) { ApplyOrientationAngle(); Vector3 right = Vector3.Cross(m_dirForward, m_dirUp); float cos = (float)Math.Cos(angle); float sin = (float)Math.Sin(angle); Vector3 up = m_dirUp * cos - m_dirForward * sin; m_dirForward = m_dirUp * sin + m_dirForward * cos; m_dirUp = up; } private void UpMinus(float angle) { UpPlus(-angle); } private void RightPlus(float angle) { ApplyOrientationAngle(); Vector3 right = Vector3.Cross(m_dirForward, m_dirUp); float cos = (float)Math.Cos(angle); float sin = (float)Math.Sin(angle); m_dirUp = m_dirUp * cos + right * sin; } private void RightMinus(float angle) { RightPlus(-angle); } private void ApplyOrientationAngle() { m_dirForward = Vector3.Normalize(m_dirForward); m_dirUp = Vector3.Normalize(m_dirUp); Vector3 right = Vector3.Cross(m_dirForward, m_dirUp); float cos = (float)Math.Cos(m_orientationAngle); float sin = (float)Math.Sin(m_orientationAngle); m_dirForward = m_dirForward * cos - right * sin; m_orientationAngle = 0.0f; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace Microsoft.Protocols.TestTools.StackSdk.Security.KerberosLib { /// <summary> /// Define const values used in this project. /// </summary> public static class KerberosConstValue { #region transport /// <summary> /// The default transport buffer size. /// </summary> public const int TRANSPORT_BUFFER_SIZE = 1500; /// <summary> /// The timeout exception. /// </summary> public const string TIMEOUT_EXCEPTION = "It has been timeout when receiving packets."; /// <summary> /// Default value for max connections set on server. /// </summary> public const int MAX_CONNECTIONS = 10; /// <summary> /// Default value for kdc port. /// </summary> public const int KDC_PORT = 88; /// <summary> /// Default value for Kpassword port /// </summary> public const int KPASSWORD_PORT = 464; #endregion transport #region AS request /// <summary> /// The version number of KerberosV5. /// </summary> public const int KERBEROSV5 = 5; /// <summary> /// The till time in AS request. /// </summary> public const string TGT_TILL_TIME = "20370913024805Z"; /// <summary> /// The rtime in AS request. /// </summary> public const string TGT_RTIME = "20370913024805Z"; /// <summary> /// The service principle name of Kerberos. /// </summary> public const string KERBEROS_SNAME = "krbtgt"; /// <summary> /// The service principle name of Kerberos for Password change. /// </summary> public const string KERBEROS_KADMIN_SNAME = "kadmin/changepw"; /// <summary> /// The default timeout value. /// </summary> public static readonly TimeSpan TIMEOUT_DEFAULT = new TimeSpan(0, 0, 2); /// <summary> /// Timeout in seconds for SMB2 connection over transport /// </summary> public static readonly TimeSpan TIMEOUT_FOR_SMB2AP = new TimeSpan(0, 2, 0); #endregion AS request #region AP request /// <summary> /// The key length of AES256_CTS_HMAC_SHA1_96. /// </summary> public const int AES_KEY_LENGTH = 32; /// <summary> /// The version number of KerberosV5. /// </summary> public const int AUTHENTICATOR_CHECKSUM_LENGTH = 16; /// <summary> /// The default size of AuthCheckSum. /// </summary> public const int AUTH_CHECKSUM_SIZE = 24; /// <summary> /// The default value of sequence number. /// </summary> public const int SEQUENCE_NUMBER_DEFAULT = 0x123; /// <summary> /// The Authorization Data Type AD-AUTH-DATA-AP-OPTIONS has an ad-type of 143 /// and ad-data of KERB_AP_OPTIONS_CBT (0x4000). /// </summary> public const int KERB_AP_OPTIONS_CBT = 0x4000; #endregion AP request #region token /// <summary> /// Filler field in wrap token for [rfc4121]. /// </summary> public const int TOKEN_FILLER_1_BYTE = 0xFF; /// <summary> /// Filler field in wrap token for [rfc1964]. /// </summary> public const int TOKEN_FILLER_2_BYTE = 0xFFFF; /// <summary> /// The size of confounder in wrap token for [rfc1964] and [rfc4757]. /// </summary> public const int CONFOUNDER_SIZE = 8; /// <summary> /// The size of checksum in wrap and mic token for [rfc4757]. /// </summary> public const int CHECKSUM_SIZE_RFC1964 = 8; /// <summary> /// The size of sequence number in wrap and mic token for [rfc4757]. /// </summary> public const int SEQUENCE_NUMBER_SIZE = 8; /// <summary> /// The first 8 byte-size of header in wrap and mic token for [rfc4757]. /// </summary> public const int HEADER_FIRST_8_BYTE_SIZE = 8; /// <summary> /// The signature key in wrap and mic token for [rfc4757]. /// </summary> public const string SIGNATURE_KEY = "signaturekey\0"; /// <summary> /// The fortybits in wrap and mic token for [rfc4757]. /// </summary> public const string FORTY_BITS = "fortybits\0"; /// <summary> /// The tag of kerberos. /// </summary> public const byte KERBEROS_TAG = 0x60; /// <summary> /// Default max token size /// </summary> public const ushort MAX_TOKEN_SIZE = 12288; /// <summary> /// Default max signature size /// </summary> public const byte MAX_SIGNATURE_SIZE = 50; /// <summary> /// Default max signature size /// </summary> public const byte SECURITY_TRAILER_SIZE = 76; /// <summary> /// Integral size of the messages /// </summary> public const byte BLOCK_SIZE = 8; /// <summary> /// The kerberos oid (1.2.840.113554.1.2.2). /// </summary> public static byte[] GetKerberosOid() { return (byte[])KerberosOid.Clone(); } public static int[] GetKerberosOidInt() { return (int[])KerberosOidInt.Clone(); } private readonly static byte[] KerberosOid = new byte[] { 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x01, 0x02, 0x02 }; private readonly static int[] KerberosOidInt = { 1, 2, 840, 113554, 1, 2, 2 }; /// <summary> /// The kerberos oid (1.2.840.48018.1.2.2). /// </summary> public static byte[] GetMsKerberosOid() { return (byte[])MsKerberosOid.Clone(); } public static int[] GetMsKerberosOidInt() { return (int[])MsKerberosOidInt.Clone(); } private readonly static byte[] MsKerberosOid = new byte[] { 0x06, 0x09, 0x2a, 0x86, 0x48, 0x82, 0xf7, 0x12, 0x01, 0x02, 0x02 }; private readonly static int[] MsKerberosOidInt = { 1, 2, 840, 48018, 1, 2, 2 }; /// <summary> /// This bytes is encoded ASN.1 value of the corresponding OID. /// </summary> public static byte[] GetSpnegoOidPkt() { return (byte[])SpnegoOidPkt.Clone(); } public static int[] GetSpngOidInt() { return (int[])SpngOidInt.Clone(); } private readonly static byte[] SpnegoOidPkt = new byte[] { 0x06, 0x06, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x02 }; private readonly static int[] SpngOidInt = { 1, 3, 6, 1, 5, 5, 2 }; public enum OidPkt { MSKerberosToken, KerberosToken } public enum GSSToken { GSSAPI, GSSSPNG } #endregion token #region encryption and decryption /// <summary> /// (8 bits) The length of byte in bits /// </summary> public const int BYTE_SIZE = 8; /// <summary> /// (8 bytes = 64 bits) Size of DES encryption block /// </summary> public const int DES_BLOCK_SIZE = 8; #endregion encryption and decryption } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Reflection; using System.Collections; using System.IO; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, System.Runtime.Serialization.DataContract>; namespace System.Runtime.Serialization.Json { #if NET_NATIVE public class XmlObjectSerializerWriteContextComplexJson : XmlObjectSerializerWriteContextComplex #else internal class XmlObjectSerializerWriteContextComplexJson : XmlObjectSerializerWriteContext #endif { private DataContractJsonSerializer _jsonSerializer; #if !NET_NATIVE private bool _isSerializerKnownDataContractsSetExplicit; #endif #if NET_NATIVE private EmitTypeInformation _emitXsiType; private bool _perCallXsiTypeAlreadyEmitted; private bool _useSimpleDictionaryFormat; #endif public XmlObjectSerializerWriteContextComplexJson(DataContractJsonSerializer serializer, DataContract rootTypeDataContract) : base(null, int.MaxValue, new StreamingContext(), true) { _jsonSerializer = serializer; this.rootTypeDataContract = rootTypeDataContract; this.serializerKnownTypeList = serializer.knownTypeList; } internal static XmlObjectSerializerWriteContextComplexJson CreateContext(DataContractJsonSerializer serializer, DataContract rootTypeDataContract) { return new XmlObjectSerializerWriteContextComplexJson(serializer, rootTypeDataContract); } #if NET_NATIVE internal static XmlObjectSerializerWriteContextComplexJson CreateContext(DataContractJsonSerializerImpl serializer, DataContract rootTypeDataContract) { return new XmlObjectSerializerWriteContextComplexJson(serializer, rootTypeDataContract); } internal XmlObjectSerializerWriteContextComplexJson(DataContractJsonSerializerImpl serializer, DataContract rootTypeDataContract) : base(serializer, serializer.MaxItemsInObjectGraph, new StreamingContext(), false) { _emitXsiType = serializer.EmitTypeInformation; this.rootTypeDataContract = rootTypeDataContract; this.serializerKnownTypeList = serializer.knownTypeList; this.serializeReadOnlyTypes = serializer.SerializeReadOnlyTypes; _useSimpleDictionaryFormat = serializer.UseSimpleDictionaryFormat; } #endif #if !NET_NATIVE internal override DataContractDictionary SerializerKnownDataContracts { get { // This field must be initialized during construction by serializers using data contracts. if (!_isSerializerKnownDataContractsSetExplicit) { this.serializerKnownDataContracts = _jsonSerializer.KnownDataContracts; _isSerializerKnownDataContractsSetExplicit = true; } return this.serializerKnownDataContracts; } } #endif internal IList<Type> SerializerKnownTypeList { get { return this.serializerKnownTypeList; } } #if NET_NATIVE public bool UseSimpleDictionaryFormat { get { return _useSimpleDictionaryFormat; } } #endif internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, string clrTypeName, string clrAssemblyName) { return false; } internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, DataContract dataContract) { return false; } internal override void WriteArraySize(XmlWriterDelegator xmlWriter, int size) { //Noop } #if NET_NATIVE protected override void WriteTypeInfo(XmlWriterDelegator writer, string dataContractName, string dataContractNamespace) { if (_emitXsiType != EmitTypeInformation.Never) { if (string.IsNullOrEmpty(dataContractNamespace)) { WriteTypeInfo(writer, dataContractName); } else { WriteTypeInfo(writer, string.Concat(dataContractName, JsonGlobals.NameValueSeparatorString, TruncateDefaultDataContractNamespace(dataContractNamespace))); } } } #endif internal static string TruncateDefaultDataContractNamespace(string dataContractNamespace) { if (!string.IsNullOrEmpty(dataContractNamespace)) { if (dataContractNamespace[0] == '#') { return string.Concat("\\", dataContractNamespace); } else if (dataContractNamespace[0] == '\\') { return string.Concat("\\", dataContractNamespace); } else if (dataContractNamespace.StartsWith(Globals.DataContractXsdBaseNamespace, StringComparison.Ordinal)) { return string.Concat("#", dataContractNamespace.Substring(JsonGlobals.DataContractXsdBaseNamespaceLength)); } } return dataContractNamespace; } protected override bool WriteTypeInfo(XmlWriterDelegator writer, DataContract contract, DataContract declaredContract) { if (!((object.ReferenceEquals(contract.Name, declaredContract.Name) && object.ReferenceEquals(contract.Namespace, declaredContract.Namespace)) || (contract.Name.Value == declaredContract.Name.Value && contract.Namespace.Value == declaredContract.Namespace.Value)) && (contract.UnderlyingType != Globals.TypeOfObjectArray) #if NET_NATIVE && (_emitXsiType != EmitTypeInformation.Never) #endif ) { // We always deserialize collections assigned to System.Object as object[] // Because of its common and JSON-specific nature, // we don't want to validate known type information for object[] #if NET_NATIVE // Don't validate known type information when emitXsiType == Never because // known types are not used without type information in the JSON if (RequiresJsonTypeInfo(contract)) { _perCallXsiTypeAlreadyEmitted = true; WriteTypeInfo(writer, contract.Name.Value, contract.Namespace.Value); } else { // check if the declared type is System.Enum and throw because // __type information cannot be written for enums since it results in invalid JSON. // Without __type, the resulting JSON cannot be deserialized since a number cannot be directly assigned to System.Enum. if (declaredContract.UnderlyingType == typeof(Enum)) { throw new SerializationException(SR.Format(SR.EnumTypeNotSupportedByDataContractJsonSerializer, declaredContract.UnderlyingType)); } } #endif // Return true regardless of whether we actually wrote __type information // E.g. We don't write __type information for enums, but we still want verifyKnownType // to be true for them. return true; } return false; } #if NET_NATIVE private static bool RequiresJsonTypeInfo(DataContract contract) { return (contract is ClassDataContract); } private void WriteTypeInfo(XmlWriterDelegator writer, string typeInformation) { writer.WriteAttributeString(null, JsonGlobals.serverTypeString, null, typeInformation); } #endif protected override void WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle declaredTypeHandle) { #if NET_NATIVE JsonDataContract jsonDataContract = JsonDataContract.GetJsonDataContract(dataContract); if (_emitXsiType == EmitTypeInformation.Always && !_perCallXsiTypeAlreadyEmitted && RequiresJsonTypeInfo(dataContract)) { WriteTypeInfo(xmlWriter, jsonDataContract.TypeName); } _perCallXsiTypeAlreadyEmitted = false; DataContractJsonSerializerImpl.WriteJsonValue(jsonDataContract, xmlWriter, obj, this, declaredTypeHandle); #else _jsonSerializer.WriteObjectInternal(obj, dataContract, this, WriteTypeInfo(null, dataContract, DataContract.GetDataContract(declaredTypeHandle, obj.GetType())), declaredTypeHandle); #endif } protected override void WriteNull(XmlWriterDelegator xmlWriter) { #if NET_NATIVE DataContractJsonSerializerImpl.WriteJsonNull(xmlWriter); #endif } #if NET_NATIVE internal XmlDictionaryString CollectionItemName { get { return JsonGlobals.itemDictionaryString; } } protected override void SerializeWithXsiType(XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType) { DataContract dataContract; bool verifyKnownType = false; bool isDeclaredTypeInterface = declaredType.GetTypeInfo().IsInterface; if (isDeclaredTypeInterface && CollectionDataContract.IsCollectionInterface(declaredType)) { dataContract = GetDataContract(declaredTypeHandle, declaredType); } else if (declaredType.IsArray) // If declared type is array do not write __serverType. Instead write__serverType for each item { dataContract = GetDataContract(declaredTypeHandle, declaredType); } else { dataContract = GetDataContract(objectTypeHandle, objectType); DataContract declaredTypeContract = (declaredTypeID >= 0) ? GetDataContract(declaredTypeID, declaredTypeHandle) : GetDataContract(declaredTypeHandle, declaredType); verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, declaredTypeContract); HandleCollectionAssignedToObject(declaredType, ref dataContract, ref obj, ref verifyKnownType); } if (isDeclaredTypeInterface) { VerifyObjectCompatibilityWithInterface(dataContract, obj, declaredType); } SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, declaredType.TypeHandle, declaredType); } private void HandleCollectionAssignedToObject(Type declaredType, ref DataContract dataContract, ref object obj, ref bool verifyKnownType) { if ((declaredType != dataContract.UnderlyingType) && (dataContract is CollectionDataContract)) { if (verifyKnownType) { VerifyType(dataContract, declaredType); verifyKnownType = false; } if (((CollectionDataContract)dataContract).Kind == CollectionKind.Dictionary) { // Convert non-generic dictionary to generic dictionary IDictionary dictionaryObj = obj as IDictionary; Dictionary<object, object> genericDictionaryObj = new Dictionary<object, object>(); foreach (DictionaryEntry entry in dictionaryObj) { genericDictionaryObj.Add(entry.Key, entry.Value); } obj = genericDictionaryObj; } dataContract = GetDataContract(Globals.TypeOfIEnumerable); } } internal override void SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType) { bool verifyKnownType = false; Type declaredType = rootTypeDataContract.UnderlyingType; bool isDeclaredTypeInterface = declaredType.GetTypeInfo().IsInterface; if (!(isDeclaredTypeInterface && CollectionDataContract.IsCollectionInterface(declaredType)) && !declaredType.IsArray)//Array covariance is not supported in XSD. If declared type is array do not write xsi:type. Instead write xsi:type for each item { verifyKnownType = WriteTypeInfo(xmlWriter, dataContract, rootTypeDataContract); HandleCollectionAssignedToObject(declaredType, ref dataContract, ref obj, ref verifyKnownType); } if (isDeclaredTypeInterface) { VerifyObjectCompatibilityWithInterface(dataContract, obj, declaredType); } SerializeAndVerifyType(dataContract, xmlWriter, obj, verifyKnownType, declaredType.TypeHandle, declaredType); } private void VerifyType(DataContract dataContract, Type declaredType) { bool knownTypesAddedInCurrentScope = false; if (dataContract.KnownDataContracts != null) { scopedKnownTypes.Push(dataContract.KnownDataContracts); knownTypesAddedInCurrentScope = true; } if (!IsKnownType(dataContract, declaredType)) { throw XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace)); } if (knownTypesAddedInCurrentScope) { scopedKnownTypes.Pop(); } } #endif internal static void VerifyObjectCompatibilityWithInterface(DataContract contract, object graph, Type declaredType) { Type contractType = contract.GetType(); if ((contractType == typeof(XmlDataContract)) && !Globals.TypeOfIXmlSerializable.IsAssignableFrom(declaredType)) { throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.XmlObjectAssignedToIncompatibleInterface, graph.GetType(), declaredType))); } if ((contractType == typeof(CollectionDataContract)) && !CollectionDataContract.IsCollectionInterface(declaredType)) { throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CollectionAssignedToIncompatibleInterface, graph.GetType(), declaredType))); } } internal void CheckIfTypeNeedsVerifcation(DataContract declaredContract, DataContract runtimeContract) { if (WriteTypeInfo(null, runtimeContract, declaredContract)) { VerifyType(runtimeContract); } } internal void VerifyType(DataContract dataContract) { bool knownTypesAddedInCurrentScope = false; if (dataContract.KnownDataContracts != null) { scopedKnownTypes.Push(dataContract.KnownDataContracts); knownTypesAddedInCurrentScope = true; } DataContract knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/); if (knownContract == null || knownContract.UnderlyingType != dataContract.UnderlyingType) { throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DcTypeNotFoundOnSerialize, DataContract.GetClrTypeFullName(dataContract.UnderlyingType), dataContract.StableName.Name, dataContract.StableName.Namespace))); } if (knownTypesAddedInCurrentScope) { scopedKnownTypes.Pop(); } } #if !NET_NATIVE private ObjectReferenceStack _byValObjectsInScope = new ObjectReferenceStack(); internal override bool OnHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference) { if (obj.GetType().GetTypeInfo().IsValueType) { return false; } if (_byValObjectsInScope.Contains(obj)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.CannotSerializeObjectWithCycles, DataContract.GetClrTypeFullName(obj.GetType())))); } _byValObjectsInScope.Push(obj); return false; } internal override void OnEndHandleReference(XmlWriterDelegator xmlWriter, object obj, bool canContainCyclicReference) { if (!obj.GetType().GetTypeInfo().IsValueType) _byValObjectsInScope.Pop(obj); } #endif internal static DataContract GetRevisedItemContract(DataContract oldItemContract) { if ((oldItemContract != null) && oldItemContract.UnderlyingType.GetTypeInfo().IsGenericType && (oldItemContract.UnderlyingType.GetGenericTypeDefinition() == Globals.TypeOfKeyValue)) { return ClassDataContract.CreateClassDataContractForKeyValue(oldItemContract.UnderlyingType, oldItemContract.Namespace, new string[] { JsonGlobals.KeyString, JsonGlobals.ValueString }); } return oldItemContract; } internal override DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type) { DataContract dataContract = base.GetDataContract(typeHandle, type); DataContractJsonSerializer.CheckIfTypeIsReference(dataContract); return dataContract; } internal override DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type type) { DataContract dataContract = base.GetDataContractSkipValidation(typeId, typeHandle, type); DataContractJsonSerializer.CheckIfTypeIsReference(dataContract); return dataContract; } internal override DataContract GetDataContract(int id, RuntimeTypeHandle typeHandle) { DataContract dataContract = base.GetDataContract(id, typeHandle); DataContractJsonSerializer.CheckIfTypeIsReference(dataContract); return dataContract; } } }
//--------------------------------------------------------------------- // File: ReceiveBatch.cs // // Summary: Implementation of an adapter framework sample adapter. // This class constitutes one of the BaseAdapter classes, which, are // a set of generic re-usable set of classes to help adapter writers. // // Sample: Base Adapter Class Library v1.0.2 // // Description: Batching logic intended for Receive side adapters - supports submitting messages // //--------------------------------------------------------------------- // This file is part of the Microsoft BizTalk Server SDK // // Copyright (c) Microsoft Corporation. All rights reserved. // // This source code is intended only as a supplement to Microsoft BizTalk // Server release and/or on-line documentation. See these other // materials for detailed information regarding Microsoft code samples. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR // PURPOSE. //--------------------------------------------------------------------- using System; using System.IO; using System.Threading; using System.Runtime.InteropServices; using System.Diagnostics; using Microsoft.BizTalk.TransportProxy.Interop; using Microsoft.BizTalk.Message.Interop; using System.Collections; namespace inSyca.foundation.integration.biztalk.adapter.common { public delegate void ReceiveBatchCompleteHandler(bool overallStatus); public class ReceiveBatch : Batch { public ReceiveBatch(IBTTransportProxy transportProxy, ControlledTermination control, ManualResetEvent orderedEvent, int depth) : base(transportProxy, true) { this.control = control; this.orderedEvent = orderedEvent; this.innerBatch = null; this.depth = depth; } public ReceiveBatch(IBTTransportProxy transportProxy, ControlledTermination control, ReceiveBatchCompleteHandler callback, int depth) : base(transportProxy, true) { this.control = control; if (callback != null) { this.ReceiveBatchComplete += callback; } this.innerBatch = null; this.depth = depth; } protected override void StartProcessFailures() { // Keep a recusive batch depth so we stop trying at some point. if (!this.OverallSuccess && this.depth > 0) { // we don't at this point care about ordering with respect to failures if (orderedEvent != null) { this.innerBatch = new ReceiveBatch(this.TransportProxy, this.control, this.orderedEvent, this.depth - 1); this.innerBatch.ReceiveBatchComplete = this.ReceiveBatchComplete; } else { this.innerBatch = new ReceiveBatch(this.TransportProxy, this.control, this.ReceiveBatchComplete, this.depth - 1); } this.innerBatchCount = 0; } } protected override void EndProcessFailures() { if (this.innerBatch != null && this.innerBatchCount > 0) { try { this.innerBatch.Done(null); this.needToLeave = false; } catch (Exception e) { Trace.WriteLine("ReceiveBatch.EndProcessFailures Exception: {0}", e.Message); this.innerBatch = null; } } } protected override void EndBatchComplete() { if (this.needToLeave) this.control.Leave(); // if there is no pending work and we have been given an event to set then set it! if (this.innerBatch == null) { // Theoretically, suspend should never fail unless DB is down/not-reachable // or the stream is not seekable. In such cases, there is a chance of duplicates // but that's safer than deleting messages that are not in the DB. if (this.ReceiveBatchComplete != null) this.ReceiveBatchComplete(this.OverallSuccess && !this.suspendFailed); if (this.orderedEvent != null) this.orderedEvent.Set(); } } protected override void SubmitFailure(IBaseMessage message, Int32 hrStatus, object userData) { failedMessages.Add(new FailedMessage(message, hrStatus)); Stream originalStream = message.BodyPart.GetOriginalDataStream(); if (this.innerBatch != null) { try { originalStream.Seek(0, SeekOrigin.Begin); message.BodyPart.Data = originalStream; this.innerBatch.MoveToSuspendQ(message, userData); this.innerBatchCount++; } catch (Exception e) { Trace.WriteLine("ReceiveBatch.SubmitFailure Exception: {0}", e.Message); this.innerBatch = null; } } } protected override void SubmitSuccess(IBaseMessage message, Int32 hrStatus, object userData) { Stream originalStream = message.BodyPart.GetOriginalDataStream(); if (this.innerBatch != null) { failedMessages.Add(new FailedMessage(message, hrStatus)); // this good message was caught up with some bad ones - it needs to be submitted again try { originalStream.Seek(0, SeekOrigin.Begin); message.BodyPart.Data = originalStream; this.innerBatch.SubmitMessage(message, userData); this.innerBatchCount++; } catch (Exception e) { Trace.WriteLine("ReceiveBatch.SubmitSuccess Exception: {0}", e.Message); this.innerBatch = null; } } else { originalStream.Close(); } } protected override void SubmitRequestFailure(IBaseMessage message, int hrStatus, object userData) { failedMessages.Add(new FailedMessage(message, hrStatus)); Stream originalStream = message.BodyPart.GetOriginalDataStream(); if (this.innerBatch != null) { try { originalStream.Seek(0, SeekOrigin.Begin); message.BodyPart.Data = originalStream; this.innerBatch.MoveToSuspendQ(message, userData); this.innerBatchCount++; } catch (Exception e) { Trace.WriteLine("ReceiveBatch.SubmitFailure Exception: {0}", e.Message); this.innerBatch = null; } } } protected override void SubmitRequestSuccess(IBaseMessage message, int hrStatus, object userData) { Stream originalStream = message.BodyPart.GetOriginalDataStream(); if (this.innerBatch != null) { failedMessages.Add(new FailedMessage(message, hrStatus)); try { originalStream.Seek(0, SeekOrigin.Begin); message.BodyPart.Data = originalStream; this.innerBatch.SubmitMessage(message, userData); this.innerBatchCount++; } catch (Exception e) { Trace.WriteLine("ReceiveBatch.SubmitSuccess Exception: {0}", e.Message); this.innerBatch = null; } } else { originalStream.Close(); } } protected override void MoveToSuspendQFailure(IBaseMessage message, Int32 hrStatus, object userData) { suspendFailed = true; Stream originalStream = message.BodyPart.GetOriginalDataStream(); originalStream.Close(); } protected override void MoveToSuspendQSuccess(IBaseMessage message, Int32 hrStatus, object userData) { Stream originalStream = message.BodyPart.GetOriginalDataStream(); // We may not be done: so if we have successful suspends from last time then suspend them again if (this.innerBatch != null) { try { originalStream.Seek(0, SeekOrigin.Begin); message.BodyPart.Data = originalStream; this.innerBatch.MoveToSuspendQ(message, userData); this.innerBatchCount++; } catch (Exception e) { Trace.WriteLine("ReceiveBatch.MoveToSuspendQSuccess Exception: {0}", e.Message); this.innerBatch = null; } } else { originalStream.Close(); } } private bool needToLeave = true; private ControlledTermination control; private ReceiveBatch innerBatch; private int innerBatchCount; private ManualResetEvent orderedEvent; private int depth; private bool suspendFailed = false; private ArrayList failedMessages = new ArrayList(); public ArrayList FailedMessages { get { return failedMessages; } set { failedMessages = value; } } public event ReceiveBatchCompleteHandler ReceiveBatchComplete; } public class FailedMessage { private IBaseMessage message; private int status; public IBaseMessage Message { get { return message; } set { message = value; } } public int Status { get { return status; } set { status = value; } } public FailedMessage(IBaseMessage message, int status) { this.message = message; this.status = status; } } }
using System.Collections; namespace NetDimension.NanUI; public class ServiceContainer : IServiceProvider { private static readonly TypeInfo DelegateType = typeof(Delegate).GetTypeInfo(); private static readonly TypeInfo EnumerableType = typeof(IEnumerable).GetTypeInfo(); private readonly List<ContainerEntry> _entries; /// <summary> /// Initializes a new instance of the <see cref="ServiceContainer" /> class. /// </summary> public ServiceContainer() { _entries = new List<ContainerEntry>(); RegisterPerRequest(c => c); RegisterPerRequest<IServiceProvider>(c => c); } private ServiceContainer(IEnumerable<ContainerEntry> entries) { _entries = new List<ContainerEntry>(entries); } /// <summary> /// Creates a child container. /// </summary> /// <returns>A new container.</returns> public ServiceContainer CreateChildContainer() { return new ServiceContainer(_entries); } /// <summary> /// Determines if a handler for the service/key has previously been registered. /// </summary> /// <param name="service">The service.</param> /// <param name="key">The key.</param> /// <returns>True if a handler is registered; false otherwise.</returns> public bool IsRegistered(Type service, string key = null) { if (service is null) throw new ArgumentNullException(nameof(service)); return _entries.Any(x => x.Service == service && x.Key == key); } /// <summary> /// Determines if a handler for the service/key has previously been registered. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="key">The key.</param> /// <returns>True if a handler is registered; false otherwise.</returns> public bool IsRegistered<TService>(string key = null) { return IsRegistered(typeof(TService), key); } /// <summary> /// Registers the class so that it is created once, on first request, and the same instance is returned to all requestors thereafter. /// </summary> /// <param name="service">The service.</param> /// <param name="implementation">The implementation.</param> /// <param name="key">The key.</param> public void RegisterSingleton(Type service, Type implementation, string key = null) { if (service is null) throw new ArgumentNullException(nameof(service)); if (implementation is null) throw new ArgumentNullException(nameof(implementation)); object singleton = null; GetOrCreateEntry(service, key).Add(c => singleton ?? (singleton = c.BuildInstance(implementation))); } /// <summary> /// Registers the class so that it is created once, on first request, and the same instance is returned to all requestors thereafter. /// </summary> /// <typeparam name="TImplementation">The type of the implementation.</typeparam> /// <param name="key">The key.</param> public void RegisterSingleton<TImplementation>(string key = null) { RegisterSingleton(typeof(TImplementation), typeof(TImplementation), key); } /// <summary> /// Registers the class so that it is created once, on first request, and the same instance is returned to all requestors thereafter. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <typeparam name="TImplementation">The type of the implementation.</typeparam> /// <param name="key">The key.</param> public void RegisterSingleton<TService, TImplementation>(string key = null) where TImplementation : TService { RegisterSingleton(typeof(TService), typeof(TImplementation), key); } /// <summary> /// Registers the class so that it is created once, on first request, and the same instance is returned to all requestors thereafter. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="handler">The handler.</param> /// <param name="key">The key.</param> public void RegisterSingleton<TService>(Func<ServiceContainer, TService> handler, string key = null) { if (handler is null) throw new ArgumentNullException(nameof(handler)); object singleton = null; GetOrCreateEntry(typeof(TService), key).Add(c => singleton ?? (singleton = handler(c))); } /// <summary> /// Registers an instance with the container. /// </summary> /// <param name="service">The service.</param> /// <param name="instance">The instance.</param> /// <param name="key">The key.</param> public void RegisterInstance(Type service, object instance, string key = null) { if (service is null) throw new ArgumentNullException(nameof(service)); GetOrCreateEntry(service, key).Add(_ => instance); } /// <summary> /// Registers an instance with the container. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="instance">The instance.</param> /// <param name="key">The key.</param> public void RegisterInstance<TService>(TService instance, string key = null) { RegisterInstance(typeof(TService), instance, key); } /// <summary> /// Registers the class so that a new instance is created on each request. /// </summary> /// <param name="service">The service.</param> /// <param name="implementation">The implementation.</param> /// <param name="key">The key.</param> public void RegisterPerRequest(Type service, Type implementation, string key = null) { if (service is null) throw new ArgumentNullException(nameof(service)); if (implementation is null) throw new ArgumentNullException(nameof(implementation)); GetOrCreateEntry(service, key).Add(c => c.BuildInstance(implementation)); } /// <summary> /// Registers the class so that a new instance is created on each request. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="key">The key.</param> public void RegisterPerRequest<TService>(string key = null) { RegisterPerRequest<TService, TService>(key); } /// <summary> /// Registers the class so that a new instance is created on each request. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <typeparam name="TImplementation">The type of the implementation.</typeparam> /// <param name="key">The key.</param> public void RegisterPerRequest<TService, TImplementation>(string key = null) where TImplementation : TService { RegisterPerRequest(typeof(TService), typeof(TImplementation), key); } /// <summary> /// Registers a custom handler for serving requests from the container. /// </summary> /// <param name="service">The service.</param> /// <param name="handler">The handler.</param> /// <param name="key">The key.</param> public void RegisterPerRequest(Type service, Func<ServiceContainer, object> handler, string key = null) { if (service is null) throw new ArgumentNullException(nameof(service)); if (handler is null) throw new ArgumentNullException(nameof(handler)); GetOrCreateEntry(service, key).Add(handler); } /// <summary> /// Registers a custom handler for serving requests from the container. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="handler">The handler.</param> /// <param name="key">The key.</param> public void RegisterPerRequest<TService>(Func<ServiceContainer, TService> handler, string key = null) { if (handler is null) throw new ArgumentNullException(nameof(handler)); GetOrCreateEntry(typeof(TService), key).Add(c => handler(c)); } /// <summary> /// Unregisters any handlers for the service/key that have previously been registered. /// </summary> /// <param name="service">The service.</param> /// <param name="key">The key.</param> /// <returns>true if handler is successfully removed; otherwise, false.</returns> public bool UnregisterHandler(Type service, string key = null) { if (service is null) throw new ArgumentNullException(nameof(service)); var entry = _entries.Find(x => x.Service == service && x.Key == key); if (entry is null) return false; return _entries.Remove(entry); } /// <summary> /// Unregisters any handlers for the service/key that have previously been registered. /// </summary> /// <typeparam name="TService">The of the service.</typeparam> /// <param name="key">The key.</param> /// <returns>true if handler is successfully removed; otherwise, false.</returns> public bool UnregisterHandler<TService>(string key = null) { return UnregisterHandler(typeof(TService), key); } object IServiceProvider.GetService(Type serviceType) { return GetInstance(serviceType, null); } /// <summary> /// Requests an instance. /// </summary> /// <typeparam name="TService">The type of the service.</typeparam> /// <param name="key">The key.</param> /// <returns>The instance.</returns> public TService GetInstance<TService>(string key = null) { return (TService)GetInstance(typeof(TService), key); } /// <summary> /// Requests an instance. /// </summary> /// <param name="service">The service.</param> /// <param name="key">The key.</param> /// <returns>The instance.</returns> public object GetInstance(Type service, string key = null) { if (service is null) throw new ArgumentNullException(nameof(service)); var entry = _entries.Find(x => x.Service == service && x.Key == key) ?? _entries.Find(x => x.Service == service); if (entry is object) { if (entry.Count != 1) throw new InvalidOperationException(string.Format("Found multiple registrations for type '{0}' and key {1}.", service, key)); return entry[0](this); } var serviceType = service.GetTypeInfo(); if (serviceType.IsGenericType && DelegateType.IsAssignableFrom(serviceType)) { var typeToCreate = service.GenericTypeArguments[0]; var factoryFactoryType = typeof(FactoryFactory<>).MakeGenericType(typeToCreate); var factoryFactoryHost = Activator.CreateInstance(factoryFactoryType); var factoryFactoryMethod = factoryFactoryType.GetRuntimeMethod("Create", new[] { typeof(ServiceContainer), typeof(string) }); return factoryFactoryMethod.Invoke(factoryFactoryHost, new object[] { this, key }); } if (serviceType.IsGenericType && EnumerableType.IsAssignableFrom(serviceType)) { if (key is object) throw new InvalidOperationException(string.Format("Requesting type '{0}' with key {1} is not supported.", service, key)); var listType = service.GenericTypeArguments[0]; var instances = GetAllInstances(listType); var array = Array.CreateInstance(listType, instances.Length); for (var i = 0; i < array.Length; i++) { array.SetValue(instances[i], i); } return array; } return (serviceType.IsValueType) ? Activator.CreateInstance(service) : null; } /// <summary> /// Gets all instances of a particular type. /// </summary> /// <typeparam name="TService">The type to resolve.</typeparam> /// <returns>The resolved instances.</returns> public TService[] GetAllInstances<TService>() { var service = typeof(TService); var instances = _entries .Where(x => x.Service == service) .SelectMany(e => e.Select(x => (TService)x(this))) .ToArray(); return instances; } /// <summary> /// Requests all instances of a given type. /// </summary> /// <param name="service">The service.</param> /// <returns>All the instances or an empty enumerable if none are found.</returns> public object[] GetAllInstances(Type service) { if (service is null) throw new ArgumentNullException(nameof(service)); var instances = _entries .Where(x => x.Service == service) .SelectMany(e => e.Select(x => x(this))) .ToArray(); return instances; } private ContainerEntry GetOrCreateEntry(Type service, string key) { var entry = _entries.Find(x => x.Service == service && x.Key == key); if (entry is null) { entry = new ContainerEntry { Service = service, Key = key }; _entries.Add(entry); } return entry; } /// <summary> /// Actually does the work of creating the instance and satisfying it's constructor dependencies. /// </summary> /// <param name="type">The type.</param> /// <returns>The build instance.</returns> protected object BuildInstance(Type type) { var constructor = type.GetTypeInfo().DeclaredConstructors .OrderByDescending(c => c.GetParameters().Length) .FirstOrDefault(c => c.IsPublic); if (constructor is null) throw new InvalidOperationException(string.Format("Type '{0}' has no public constructor.", type)); var args = constructor.GetParameters() .Select(info => GetInstance(info.ParameterType, null)) .ToArray(); return ActivateInstance(type, args); } /// <summary> /// Creates an instance of the type with the specified constructor arguments. /// </summary> /// <param name="type">The type.</param> /// <param name="args">The constructor arguments.</param> /// <returns>The created instance.</returns> protected virtual object ActivateInstance(Type type, object[] args) { return (args.Length > 0) ? Activator.CreateInstance(type, args) : Activator.CreateInstance(type); } private sealed class ContainerEntry : List<Func<ServiceContainer, object>> { public string Key; public Type Service; } private sealed class FactoryFactory<T> { public Func<T> Create(ServiceContainer container, string key) { return () => (T)container.GetInstance(typeof(T), key); } } }
/* Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft 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 C5; using NUnit.Framework; using SCG = System.Collections.Generic; namespace C5UnitTests { class SC : SCG.IComparer<string> { public int Compare(string a, string b) { return a.CompareTo(b); } public void appl(String s) { System.Console.WriteLine("--{0}", s); } } class TenEqualityComparer : SCG.IEqualityComparer<int>, SCG.IComparer<int> { TenEqualityComparer() { } public static TenEqualityComparer Default { get { return new TenEqualityComparer(); } } public int GetHashCode(int item) { return (item / 10).GetHashCode(); } public bool Equals(int item1, int item2) { return item1 / 10 == item2 / 10; } public int Compare(int a, int b) { return (a / 10).CompareTo(b / 10); } } class IC : SCG.IComparer<int>, IComparable<int>, SCG.IComparer<IC>, IComparable<IC> { public int Compare(int a, int b) { return a > b ? 1 : a < b ? -1 : 0; } public int Compare(IC a, IC b) { return a._i > b._i ? 1 : a._i < b._i ? -1 : 0; } private int _i; public int i { get { return _i; } set { _i = value; } } public IC() { } public IC(int i) { _i = i; } public int CompareTo(int that) { return _i > that ? 1 : _i < that ? -1 : 0; } public bool Equals(int that) { return _i == that; } public int CompareTo(IC that) { return _i > that._i ? 1 : _i < that._i ? -1 : 0; } public bool Equals(IC that) { return _i == that._i; } public static bool eq(SCG.IEnumerable<int> me, params int[] that) { int i = 0, maxind = that.Length - 1; foreach (int item in me) if (i > maxind || item != that[i++]) return false; return i == maxind + 1; } public static bool seteq(ICollectionValue<int> me, params int[] that) { int[] me2 = me.ToArray(); Array.Sort(me2); int i = 0, maxind = that.Length - 1; foreach (int item in me2) if (i > maxind || item != that[i++]) return false; return i == maxind + 1; } public static bool seteq(ICollectionValue<KeyValuePair<int, int>> me, params int[] that) { ArrayList<KeyValuePair<int, int>> first = new ArrayList<KeyValuePair<int, int>>(); first.AddAll(me); ArrayList<KeyValuePair<int, int>> other = new ArrayList<KeyValuePair<int, int>>(); for (int i = 0; i < that.Length; i += 2) { other.Add(new KeyValuePair<int, int>(that[i], that[i + 1])); } return other.UnsequencedEquals(first); } } class RevIC : SCG.IComparer<int> { public int Compare(int a, int b) { return a > b ? -1 : a < b ? 1 : 0; } } public class FunEnumerable : SCG.IEnumerable<int> { int size; Func<int, int> f; public FunEnumerable(int size, Func<int, int> f) { this.size = size; this.f = f; } public SCG.IEnumerator<int> GetEnumerator() { for (int i = 0; i < size; i++) yield return f(i); } #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new NotImplementedException(); } #endregion } public class BadEnumerableException : Exception { } public class BadEnumerable<T> : CollectionValueBase<T>, ICollectionValue<T> { T[] contents; Exception exception; public BadEnumerable(Exception exception, params T[] contents) { this.contents = (T[])contents.Clone(); this.exception = exception; } public override SCG.IEnumerator<T> GetEnumerator() { for (int i = 0; i < contents.Length; i++) yield return contents[i]; throw exception; } public override bool IsEmpty { get { return false; } } public override int Count { get { return contents.Length + 1; } } public override Speed CountSpeed { get { return Speed.Constant; } } public override T Choose() { throw exception; } } public class CollectionEventList<T> { ArrayList<CollectionEvent<T>> happened; EventTypeEnum listenTo; SCG.IEqualityComparer<T> itemequalityComparer; public CollectionEventList(SCG.IEqualityComparer<T> itemequalityComparer) { happened = new ArrayList<CollectionEvent<T>>(); this.itemequalityComparer = itemequalityComparer; } public void Listen(ICollectionValue<T> list, EventTypeEnum listenTo) { this.listenTo = listenTo; if ((listenTo & EventTypeEnum.Changed) != 0) list.CollectionChanged += new CollectionChangedHandler<T>(changed); if ((listenTo & EventTypeEnum.Cleared) != 0) list.CollectionCleared += new CollectionClearedHandler<T>(cleared); if ((listenTo & EventTypeEnum.Removed) != 0) list.ItemsRemoved += new ItemsRemovedHandler<T>(removed); if ((listenTo & EventTypeEnum.Added) != 0) list.ItemsAdded += new ItemsAddedHandler<T>(added); if ((listenTo & EventTypeEnum.Inserted) != 0) list.ItemInserted += new ItemInsertedHandler<T>(inserted); if ((listenTo & EventTypeEnum.RemovedAt) != 0) list.ItemRemovedAt += new ItemRemovedAtHandler<T>(removedAt); } public void Add(CollectionEvent<T> e) { happened.Add(e); } /// <summary> /// Check that we have seen exactly the events in expected that match listenTo. /// </summary> /// <param name="expected"></param> public void Check(SCG.IEnumerable<CollectionEvent<T>> expected) { int i = 0; foreach (CollectionEvent<T> expectedEvent in expected) { if ((expectedEvent.Act & listenTo) == 0) continue; if (i >= happened.Count) Assert.Fail(string.Format("Event number {0} did not happen:\n expected {1}", i, expectedEvent)); if (!expectedEvent.Equals(happened[i], itemequalityComparer)) Assert.Fail(string.Format("Event number {0}:\n expected {1}\n but saw {2}", i, expectedEvent, happened[i])); i++; } if (i < happened.Count) Assert.Fail(string.Format("Event number {0} seen but no event expected:\n {1}", i, happened[i])); happened.Clear(); } public void Clear() { happened.Clear(); } public void Print(System.IO.TextWriter writer) { happened.Apply(delegate(CollectionEvent<T> e) { writer.WriteLine(e); }); } void changed(object sender) { happened.Add(new CollectionEvent<T>(EventTypeEnum.Changed, new EventArgs(), sender)); } void cleared(object sender, ClearedEventArgs eventArgs) { happened.Add(new CollectionEvent<T>(EventTypeEnum.Cleared, eventArgs, sender)); } void added(object sender, ItemCountEventArgs<T> eventArgs) { happened.Add(new CollectionEvent<T>(EventTypeEnum.Added, eventArgs, sender)); } void removed(object sender, ItemCountEventArgs<T> eventArgs) { happened.Add(new CollectionEvent<T>(EventTypeEnum.Removed, eventArgs, sender)); } void inserted(object sender, ItemAtEventArgs<T> eventArgs) { happened.Add(new CollectionEvent<T>(EventTypeEnum.Inserted, eventArgs, sender)); } void removedAt(object sender, ItemAtEventArgs<T> eventArgs) { happened.Add(new CollectionEvent<T>(EventTypeEnum.RemovedAt, eventArgs, sender)); } } public sealed class CollectionEvent<T> { public readonly EventTypeEnum Act; public readonly EventArgs Args; public readonly object Sender; public CollectionEvent(EventTypeEnum act, EventArgs args, object sender) { this.Act = act; this.Args = args; this.Sender = sender; } public bool Equals(CollectionEvent<T> otherEvent, SCG.IEqualityComparer<T> itemequalityComparer) { if (otherEvent == null || Act != otherEvent.Act || !object.ReferenceEquals(Sender, otherEvent.Sender)) return false; switch (Act) { case EventTypeEnum.None: break; case EventTypeEnum.Changed: return true; case EventTypeEnum.Cleared: if (Args is ClearedRangeEventArgs) { ClearedRangeEventArgs a = Args as ClearedRangeEventArgs, o = otherEvent.Args as ClearedRangeEventArgs; if (o == null) return false; return a.Full == o.Full && a.Start == o.Start && a.Count == o.Count; } else { if (otherEvent.Args is ClearedRangeEventArgs) return false; ClearedEventArgs a = Args as ClearedEventArgs, o = otherEvent.Args as ClearedEventArgs; return a.Full == o.Full && a.Count == o.Count; } case EventTypeEnum.Added: { ItemCountEventArgs<T> a = Args as ItemCountEventArgs<T>, o = otherEvent.Args as ItemCountEventArgs<T>; return itemequalityComparer.Equals(a.Item, o.Item) && a.Count == o.Count; } case EventTypeEnum.Removed: { ItemCountEventArgs<T> a = Args as ItemCountEventArgs<T>, o = otherEvent.Args as ItemCountEventArgs<T>; return itemequalityComparer.Equals(a.Item, o.Item) && a.Count == o.Count; } case EventTypeEnum.Inserted: { ItemAtEventArgs<T> a = Args as ItemAtEventArgs<T>, o = otherEvent.Args as ItemAtEventArgs<T>; return a.Index == o.Index && itemequalityComparer.Equals(a.Item, o.Item); } case EventTypeEnum.RemovedAt: { ItemAtEventArgs<T> a = Args as ItemAtEventArgs<T>, o = otherEvent.Args as ItemAtEventArgs<T>; return a.Index == o.Index && itemequalityComparer.Equals(a.Item, o.Item); } } throw new ApplicationException("Illegal Action: " + Act); } public override string ToString() { return string.Format("Action: {0}, Args : {1}, Source : {2}", Act, Args, Sender); } } public class CHC { static public int unsequencedhashcode(params int[] a) { int h = 0; foreach (int i in a) { h += (int)(((uint)i * 1529784657 + 1) ^ ((uint)i * 2912831877) ^ ((uint)i * 1118771817 + 2)); } return h; } static public int sequencedhashcode(params int[] a) { int h = 0; foreach (int i in a) { h = h * 31 + i; } return h; } } //This class is a modified sample from VS2005 beta1 documentation public class RadixFormatProvider : IFormatProvider { RadixFormatter _radixformatter; public RadixFormatProvider(int radix) { if (radix < 2 || radix > 36) throw new ArgumentException(string.Format( "The radix \"{0}\" is not in the range 2..36.", radix)); _radixformatter = new RadixFormatter(radix); } public object GetFormat(Type argType) { if (argType == typeof(ICustomFormatter)) return _radixformatter; else return null; } } //This class is a modified sample from VS2005 beta1 documentation public class RadixFormatter : ICustomFormatter { int radix; public RadixFormatter(int radix) { if (radix < 2 || radix > 36) throw new ArgumentException(string.Format( "The radix \"{0}\" is not in the range 2..36.", radix)); this.radix = radix; } // The value to be formatted is returned as a signed string // of digits from the rDigits array. private static char[] rDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' }; public string Format(string formatString, object argToBeFormatted, IFormatProvider provider) { /*switch (Type.GetTypeCode(argToBeFormatted.GetType())) { case TypeCode.Boolean: break; case TypeCode.Byte: break; case TypeCode.Char: break; case TypeCode.DBNull: break; case TypeCode.DateTime: break; case TypeCode.Decimal: break; case TypeCode.Double: break; case TypeCode.Empty: break; case TypeCode.Int16: break; case TypeCode.Int32: break; case TypeCode.Int64: break; case TypeCode.Object: break; case TypeCode.SByte: break; case TypeCode.Single: break; case TypeCode.String: break; case TypeCode.UInt16: break; case TypeCode.UInt32: break; case TypeCode.UInt64: break; }*/ int intToBeFormatted; try { intToBeFormatted = (int)argToBeFormatted; } catch (Exception) { if (argToBeFormatted is IFormattable) return ((IFormattable)argToBeFormatted). ToString(formatString, provider); else return argToBeFormatted.ToString(); } return formatInt(intToBeFormatted); } private string formatInt(int intToBeFormatted) { // The formatting is handled here. if (intToBeFormatted == 0) return "0"; int digitIndex = 0; int intPositive; char[] outDigits = new char[31]; // Verify that the argument can be converted to a int integer. // Extract the magnitude for conversion. intPositive = Math.Abs(intToBeFormatted); // Convert the magnitude to a digit string. for (digitIndex = 0; digitIndex <= 32; digitIndex++) { if (intPositive == 0) break; outDigits[outDigits.Length - digitIndex - 1] = rDigits[intPositive % radix]; intPositive /= radix; } // Add a minus sign if the argument is negative. if (intToBeFormatted < 0) outDigits[outDigits.Length - digitIndex++ - 1] = '-'; return new string(outDigits, outDigits.Length - digitIndex, digitIndex); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Security.Claims; using System.Text; using System.Threading; using KERB_LOGON_SUBMIT_TYPE = Interop.SspiCli.KERB_LOGON_SUBMIT_TYPE; using KERB_S4U_LOGON = Interop.SspiCli.KERB_S4U_LOGON; using KerbS4uLogonFlags = Interop.SspiCli.KerbS4uLogonFlags; using LUID = Interop.LUID; using LSA_STRING = Interop.SspiCli.LSA_STRING; using QUOTA_LIMITS = Interop.SspiCli.QUOTA_LIMITS; using SECURITY_LOGON_TYPE = Interop.SspiCli.SECURITY_LOGON_TYPE; using TOKEN_SOURCE = Interop.SspiCli.TOKEN_SOURCE; using System.Runtime.Serialization; namespace System.Security.Principal { [Serializable] public class WindowsIdentity : ClaimsIdentity, IDisposable, ISerializable, IDeserializationCallback { private string _name = null; private SecurityIdentifier _owner = null; private SecurityIdentifier _user = null; private IdentityReferenceCollection _groups = null; private SafeAccessTokenHandle _safeTokenHandle = SafeAccessTokenHandle.InvalidHandle; private string _authType = null; private int _isAuthenticated = -1; private volatile TokenImpersonationLevel _impersonationLevel; private volatile bool _impersonationLevelInitialized; public new const string DefaultIssuer = @"AD AUTHORITY"; [NonSerialized] private string _issuerName = DefaultIssuer; [NonSerialized] private object _claimsIntiailizedLock = new object(); [NonSerialized] private volatile bool _claimsInitialized; [NonSerialized] private List<Claim> _deviceClaims; [NonSerialized] private List<Claim> _userClaims; // // Constructors. // private WindowsIdentity() : base(null, null, null, ClaimTypes.Name, ClaimTypes.GroupSid) { } /// <summary> /// Initializes a new instance of the WindowsIdentity class for the user represented by the specified User Principal Name (UPN). /// </summary> /// <remarks> /// Unlike the desktop version, we connect to Lsa only as an untrusted caller. We do not attempt to explot Tcb privilege or adjust the current /// thread privilege to include Tcb. /// </remarks> public WindowsIdentity(string sUserPrincipalName) : base(null, null, null, ClaimTypes.Name, ClaimTypes.GroupSid) { // Desktop compat: See comments below for why we don't validate sUserPrincipalName. using (SafeLsaHandle lsaHandle = ConnectToLsa()) { int packageId = LookupAuthenticationPackage(lsaHandle, Interop.SspiCli.AuthenticationPackageNames.MICROSOFT_KERBEROS_NAME_A); // 8 byte or less name that indicates the source of the access token. This choice of name is visible to callers through the native GetTokenInformation() api // so we'll use the same name the CLR used even though we're not actually the "CLR." byte[] sourceName = { (byte)'C', (byte)'L', (byte)'R', (byte)0 }; TOKEN_SOURCE sourceContext; if (!Interop.Advapi32.AllocateLocallyUniqueId(out sourceContext.SourceIdentifier)) throw new SecurityException(new Win32Exception().Message); sourceContext.SourceName = new byte[TOKEN_SOURCE.TOKEN_SOURCE_LENGTH]; Buffer.BlockCopy(sourceName, 0, sourceContext.SourceName, 0, sourceName.Length); // Desktop compat: Desktop never null-checks sUserPrincipalName. Actual behavior is that the null makes it down to Encoding.Unicode.GetBytes() which then throws // the ArgumentNullException (provided that the prior LSA calls didn't fail first.) To make this compat decision explicit, we'll null check ourselves // and simulate the exception from Encoding.Unicode.GetBytes(). if (sUserPrincipalName == null) throw new ArgumentNullException("s"); byte[] upnBytes = Encoding.Unicode.GetBytes(sUserPrincipalName); if (upnBytes.Length > ushort.MaxValue) { // Desktop compat: LSA only allocates 16 bits to hold the UPN size. We should throw an exception here but unfortunately, the desktop did an unchecked cast to ushort, // effectively truncating upnBytes to the first (N % 64K) bytes. We'll simulate the same behavior here (albeit in a way that makes it look less accidental.) Array.Resize(ref upnBytes, upnBytes.Length & ushort.MaxValue); } unsafe { // // Build the KERB_S4U_LOGON structure. Note that the LSA expects this entire // structure to be contained within the same block of memory, so we need to allocate // enough room for both the structure itself and the UPN string in a single buffer // and do the marshalling into this buffer by hand. // int authenticationInfoLength = checked(sizeof(KERB_S4U_LOGON) + upnBytes.Length); using (SafeLocalAllocHandle authenticationInfo = Interop.Kernel32.LocalAlloc(0, new UIntPtr(checked((uint)authenticationInfoLength)))) { if (authenticationInfo.IsInvalid) throw new OutOfMemoryException(); KERB_S4U_LOGON* pKerbS4uLogin = (KERB_S4U_LOGON*)(authenticationInfo.DangerousGetHandle()); pKerbS4uLogin->MessageType = KERB_LOGON_SUBMIT_TYPE.KerbS4ULogon; pKerbS4uLogin->Flags = KerbS4uLogonFlags.None; pKerbS4uLogin->ClientUpn.Length = pKerbS4uLogin->ClientUpn.MaximumLength = checked((ushort)upnBytes.Length); IntPtr pUpnOffset = (IntPtr)(pKerbS4uLogin + 1); pKerbS4uLogin->ClientUpn.Buffer = pUpnOffset; Marshal.Copy(upnBytes, 0, pKerbS4uLogin->ClientUpn.Buffer, upnBytes.Length); pKerbS4uLogin->ClientRealm.Length = pKerbS4uLogin->ClientRealm.MaximumLength = 0; pKerbS4uLogin->ClientRealm.Buffer = IntPtr.Zero; ushort sourceNameLength = checked((ushort)(sourceName.Length)); using (SafeLocalAllocHandle sourceNameBuffer = Interop.Kernel32.LocalAlloc(0, new UIntPtr(sourceNameLength))) { if (sourceNameBuffer.IsInvalid) throw new OutOfMemoryException(); Marshal.Copy(sourceName, 0, sourceNameBuffer.DangerousGetHandle(), sourceName.Length); LSA_STRING lsaOriginName = new LSA_STRING(sourceNameBuffer.DangerousGetHandle(), sourceNameLength); SafeLsaReturnBufferHandle profileBuffer; int profileBufferLength; LUID logonId; SafeAccessTokenHandle accessTokenHandle; QUOTA_LIMITS quota; int subStatus; int ntStatus = Interop.SspiCli.LsaLogonUser( lsaHandle, ref lsaOriginName, SECURITY_LOGON_TYPE.Network, packageId, authenticationInfo.DangerousGetHandle(), authenticationInfoLength, IntPtr.Zero, ref sourceContext, out profileBuffer, out profileBufferLength, out logonId, out accessTokenHandle, out quota, out subStatus); if (ntStatus == unchecked((int)Interop.StatusOptions.STATUS_ACCOUNT_RESTRICTION) && subStatus < 0) ntStatus = subStatus; if (ntStatus < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(ntStatus); if (subStatus < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(subStatus); if (profileBuffer != null) profileBuffer.Dispose(); _safeTokenHandle = accessTokenHandle; } } } } } private static SafeLsaHandle ConnectToLsa() { SafeLsaHandle lsaHandle; int ntStatus = Interop.SspiCli.LsaConnectUntrusted(out lsaHandle); if (ntStatus < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(ntStatus); return lsaHandle; } private static int LookupAuthenticationPackage(SafeLsaHandle lsaHandle, string packageName) { Debug.Assert(!string.IsNullOrEmpty(packageName)); unsafe { int packageId; byte[] asciiPackageName = Encoding.ASCII.GetBytes(packageName); fixed (byte* pAsciiPackageName = &asciiPackageName[0]) { LSA_STRING lsaPackageName = new LSA_STRING((IntPtr)pAsciiPackageName, checked((ushort)(asciiPackageName.Length))); int ntStatus = Interop.SspiCli.LsaLookupAuthenticationPackage(lsaHandle, ref lsaPackageName, out packageId); if (ntStatus < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(ntStatus); } return packageId; } } public WindowsIdentity(IntPtr userToken) : this(userToken, null, -1) { } public WindowsIdentity(IntPtr userToken, string type) : this(userToken, type, -1) { } private WindowsIdentity(IntPtr userToken, string authType, int isAuthenticated) : base(null, null, null, ClaimTypes.Name, ClaimTypes.GroupSid) { CreateFromToken(userToken); _authType = authType; _isAuthenticated = isAuthenticated; } private void CreateFromToken(IntPtr userToken) { if (userToken == IntPtr.Zero) throw new ArgumentException(SR.Argument_TokenZero); Contract.EndContractBlock(); // Find out if the specified token is a valid. uint dwLength = (uint)sizeof(uint); bool result = Interop.Advapi32.GetTokenInformation(userToken, (uint)TokenInformationClass.TokenType, SafeLocalAllocHandle.InvalidHandle, 0, out dwLength); if (Marshal.GetLastWin32Error() == Interop.Errors.ERROR_INVALID_HANDLE) throw new ArgumentException(SR.Argument_InvalidImpersonationToken); if (!Interop.Kernel32.DuplicateHandle(Interop.Kernel32.GetCurrentProcess(), userToken, Interop.Kernel32.GetCurrentProcess(), ref _safeTokenHandle, 0, true, Interop.DuplicateHandleOptions.DUPLICATE_SAME_ACCESS)) throw new SecurityException(new Win32Exception().Message); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2229", Justification = "Public API has already shipped.")] public WindowsIdentity(SerializationInfo info, StreamingContext context) { _claimsInitialized = false; IntPtr userToken = (IntPtr)info.GetValue("m_userToken", typeof(IntPtr)); if (userToken != IntPtr.Zero) { CreateFromToken(userToken); } } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { // TODO: Add back when ClaimsIdentity is serializable // base.GetObjectData(info, context); info.AddValue("m_userToken", _safeTokenHandle.DangerousGetHandle()); } void IDeserializationCallback.OnDeserialization(object sender) { } // // Factory methods. // public static WindowsIdentity GetCurrent() { return GetCurrentInternal(TokenAccessLevels.MaximumAllowed, false); } public static WindowsIdentity GetCurrent(bool ifImpersonating) { return GetCurrentInternal(TokenAccessLevels.MaximumAllowed, ifImpersonating); } public static WindowsIdentity GetCurrent(TokenAccessLevels desiredAccess) { return GetCurrentInternal(desiredAccess, false); } // GetAnonymous() is used heavily in ASP.NET requests as a dummy identity to indicate // the request is anonymous. It does not represent a real process or thread token so // it cannot impersonate or do anything useful. Note this identity does not represent the // usual concept of an anonymous token, and the name is simply misleading but we cannot change it now. public static WindowsIdentity GetAnonymous() { return new WindowsIdentity(); } // // Properties. // // this is defined 'override sealed' for back compat. Il generated is 'virtual final' and this needs to be the same. public override sealed string AuthenticationType { get { // If this is an anonymous identity, return an empty string if (_safeTokenHandle.IsInvalid) return String.Empty; if (_authType == null) { Interop.LUID authId = GetLogonAuthId(_safeTokenHandle); if (authId.LowPart == Interop.LuidOptions.ANONYMOUS_LOGON_LUID) return String.Empty; // no authentication, just return an empty string SafeLsaReturnBufferHandle pLogonSessionData = SafeLsaReturnBufferHandle.InvalidHandle; try { int status = Interop.SspiCli.LsaGetLogonSessionData(ref authId, ref pLogonSessionData); if (status < 0) // non-negative numbers indicate success throw GetExceptionFromNtStatus(status); pLogonSessionData.Initialize((uint)Marshal.SizeOf<Interop.SECURITY_LOGON_SESSION_DATA>()); Interop.SECURITY_LOGON_SESSION_DATA logonSessionData = pLogonSessionData.Read<Interop.SECURITY_LOGON_SESSION_DATA>(0); return Marshal.PtrToStringUni(logonSessionData.AuthenticationPackage.Buffer); } finally { if (!pLogonSessionData.IsInvalid) pLogonSessionData.Dispose(); } } return _authType; } } public TokenImpersonationLevel ImpersonationLevel { get { // In case of a race condition here here, both threads will set m_impersonationLevel to the same value, // which is ok. if (!_impersonationLevelInitialized) { TokenImpersonationLevel impersonationLevel = TokenImpersonationLevel.None; // If this is an anonymous identity if (_safeTokenHandle.IsInvalid) { impersonationLevel = TokenImpersonationLevel.Anonymous; } else { TokenType tokenType = (TokenType)GetTokenInformation<int>(TokenInformationClass.TokenType); if (tokenType == TokenType.TokenPrimary) { impersonationLevel = TokenImpersonationLevel.None; // primary token; } else { /// This is an impersonation token, get the impersonation level int level = GetTokenInformation<int>(TokenInformationClass.TokenImpersonationLevel); impersonationLevel = (TokenImpersonationLevel)level + 1; } } _impersonationLevel = impersonationLevel; _impersonationLevelInitialized = true; } return _impersonationLevel; } } public override bool IsAuthenticated { get { if (_isAuthenticated == -1) { // This approach will not work correctly for domain guests (will return false // instead of true). This is a corner-case that is not very interesting. _isAuthenticated = CheckNtTokenForSid(new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[] { Interop.SecurityIdentifier.SECURITY_AUTHENTICATED_USER_RID })) ? 1 : 0; } return _isAuthenticated == 1; } } private bool CheckNtTokenForSid(SecurityIdentifier sid) { Contract.EndContractBlock(); // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return false; // CheckTokenMembership expects an impersonation token SafeAccessTokenHandle token = SafeAccessTokenHandle.InvalidHandle; TokenImpersonationLevel til = ImpersonationLevel; bool isMember = false; try { if (til == TokenImpersonationLevel.None) { if (!Interop.Advapi32.DuplicateTokenEx(_safeTokenHandle, (uint)TokenAccessLevels.Query, IntPtr.Zero, (uint)TokenImpersonationLevel.Identification, (uint)TokenType.TokenImpersonation, ref token)) throw new SecurityException(new Win32Exception().Message); } // CheckTokenMembership will check if the SID is both present and enabled in the access token. if (!Interop.Advapi32.CheckTokenMembership((til != TokenImpersonationLevel.None ? _safeTokenHandle : token), sid.BinaryForm, ref isMember)) throw new SecurityException(new Win32Exception().Message); } finally { if (token != SafeAccessTokenHandle.InvalidHandle) { token.Dispose(); } } return isMember; } // // IsGuest, IsSystem and IsAnonymous are maintained for compatibility reasons. It is always // possible to extract this same information from the User SID property and the new // (and more general) methods defined in the SID class (IsWellKnown, etc...). // public virtual bool IsGuest { get { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return false; return CheckNtTokenForSid(new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[] { Interop.SecurityIdentifier.SECURITY_BUILTIN_DOMAIN_RID, (int)WindowsBuiltInRole.Guest })); } } public virtual bool IsSystem { get { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return false; SecurityIdentifier sid = new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[] { Interop.SecurityIdentifier.SECURITY_LOCAL_SYSTEM_RID }); return (this.User == sid); } } public virtual bool IsAnonymous { get { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return true; SecurityIdentifier sid = new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[] { Interop.SecurityIdentifier.SECURITY_ANONYMOUS_LOGON_RID }); return (this.User == sid); } } public override string Name { get { return GetName(); } } internal String GetName() { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return String.Empty; if (_name == null) { // revert thread impersonation for the duration of the call to get the name. RunImpersonated(SafeAccessTokenHandle.InvalidHandle, delegate { NTAccount ntAccount = this.User.Translate(typeof(NTAccount)) as NTAccount; _name = ntAccount.ToString(); }); } return _name; } public SecurityIdentifier Owner { get { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return null; if (_owner == null) { using (SafeLocalAllocHandle tokenOwner = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenOwner)) { _owner = new SecurityIdentifier(tokenOwner.Read<IntPtr>(0), true); } } return _owner; } } public SecurityIdentifier User { get { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return null; if (_user == null) { using (SafeLocalAllocHandle tokenUser = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenUser)) { _user = new SecurityIdentifier(tokenUser.Read<IntPtr>(0), true); } } return _user; } } public IdentityReferenceCollection Groups { get { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return null; if (_groups == null) { IdentityReferenceCollection groups = new IdentityReferenceCollection(); using (SafeLocalAllocHandle pGroups = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenGroups)) { uint groupCount = pGroups.Read<uint>(0); Interop.TOKEN_GROUPS tokenGroups = pGroups.Read<Interop.TOKEN_GROUPS>(0); Interop.SID_AND_ATTRIBUTES[] groupDetails = new Interop.SID_AND_ATTRIBUTES[tokenGroups.GroupCount]; pGroups.ReadArray((uint)Marshal.OffsetOf<Interop.TOKEN_GROUPS>("Groups").ToInt32(), groupDetails, 0, groupDetails.Length); foreach (Interop.SID_AND_ATTRIBUTES group in groupDetails) { // Ignore disabled, logon ID, and deny-only groups. uint mask = Interop.SecurityGroups.SE_GROUP_ENABLED | Interop.SecurityGroups.SE_GROUP_LOGON_ID | Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY; if ((group.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_ENABLED) { groups.Add(new SecurityIdentifier(group.Sid, true)); } } } Interlocked.CompareExchange(ref _groups, groups, null); } return _groups; } } public SafeAccessTokenHandle AccessToken { get { return _safeTokenHandle; } } public virtual IntPtr Token { get { return _safeTokenHandle.DangerousGetHandle(); } } // // Public methods. // public static void RunImpersonated(SafeAccessTokenHandle safeAccessTokenHandle, Action action) { if (action == null) throw new ArgumentNullException(nameof(action)); RunImpersonatedInternal(safeAccessTokenHandle, action); } public static T RunImpersonated<T>(SafeAccessTokenHandle safeAccessTokenHandle, Func<T> func) { if (func == null) throw new ArgumentNullException(nameof(func)); T result = default(T); RunImpersonatedInternal(safeAccessTokenHandle, () => result = func()); return result; } protected virtual void Dispose(bool disposing) { if (disposing) { if (_safeTokenHandle != null && !_safeTokenHandle.IsClosed) _safeTokenHandle.Dispose(); } _name = null; _owner = null; _user = null; } public void Dispose() { Dispose(true); } // // internal. // private static AsyncLocal<SafeAccessTokenHandle> s_currentImpersonatedToken = new AsyncLocal<SafeAccessTokenHandle>(CurrentImpersonatedTokenChanged); private static void RunImpersonatedInternal(SafeAccessTokenHandle token, Action action) { bool isImpersonating; int hr; SafeAccessTokenHandle previousToken = GetCurrentToken(TokenAccessLevels.MaximumAllowed, false, out isImpersonating, out hr); if (previousToken == null || previousToken.IsInvalid) throw new SecurityException(new Win32Exception(hr).Message); s_currentImpersonatedToken.Value = isImpersonating ? previousToken : null; ExecutionContext currentContext = ExecutionContext.Capture(); // Run everything else inside of ExecutionContext.Run, so that any EC changes will be undone // on the way out. ExecutionContext.Run( currentContext, delegate { if (!Interop.Advapi32.RevertToSelf()) Environment.FailFast(new Win32Exception().Message); s_currentImpersonatedToken.Value = null; if (!token.IsInvalid && !Interop.Advapi32.ImpersonateLoggedOnUser(token)) throw new SecurityException(SR.Argument_ImpersonateUser); s_currentImpersonatedToken.Value = token; action(); }, null); } private static void CurrentImpersonatedTokenChanged(AsyncLocalValueChangedArgs<SafeAccessTokenHandle> args) { if (!args.ThreadContextChanged) return; // we handle explicit Value property changes elsewhere. if (!Interop.Advapi32.RevertToSelf()) Environment.FailFast(new Win32Exception().Message); if (args.CurrentValue != null && !args.CurrentValue.IsInvalid) { if (!Interop.Advapi32.ImpersonateLoggedOnUser(args.CurrentValue)) Environment.FailFast(new Win32Exception().Message); } } internal static WindowsIdentity GetCurrentInternal(TokenAccessLevels desiredAccess, bool threadOnly) { int hr = 0; bool isImpersonating; SafeAccessTokenHandle safeTokenHandle = GetCurrentToken(desiredAccess, threadOnly, out isImpersonating, out hr); if (safeTokenHandle == null || safeTokenHandle.IsInvalid) { // either we wanted only ThreadToken - return null if (threadOnly && !isImpersonating) return null; // or there was an error throw new SecurityException(new Win32Exception(hr).Message); } WindowsIdentity wi = new WindowsIdentity(); wi._safeTokenHandle.Dispose(); wi._safeTokenHandle = safeTokenHandle; return wi; } // // private. // private static int GetHRForWin32Error(int dwLastError) { if ((dwLastError & 0x80000000) == 0x80000000) return dwLastError; else return (dwLastError & 0x0000FFFF) | unchecked((int)0x80070000); } private static Exception GetExceptionFromNtStatus(int status) { if ((uint)status == Interop.StatusOptions.STATUS_ACCESS_DENIED) return new UnauthorizedAccessException(); if ((uint)status == Interop.StatusOptions.STATUS_INSUFFICIENT_RESOURCES || (uint)status == Interop.StatusOptions.STATUS_NO_MEMORY) return new OutOfMemoryException(); int win32ErrorCode = Interop.NtDll.RtlNtStatusToDosError(status); return new SecurityException(new Win32Exception(win32ErrorCode).Message); } private static SafeAccessTokenHandle GetCurrentToken(TokenAccessLevels desiredAccess, bool threadOnly, out bool isImpersonating, out int hr) { isImpersonating = true; SafeAccessTokenHandle safeTokenHandle; hr = 0; bool success = Interop.Advapi32.OpenThreadToken(desiredAccess, WinSecurityContext.Both, out safeTokenHandle); if (!success) hr = Marshal.GetHRForLastWin32Error(); if (!success && hr == GetHRForWin32Error(Interop.Errors.ERROR_NO_TOKEN)) { // No impersonation isImpersonating = false; if (!threadOnly) safeTokenHandle = GetCurrentProcessToken(desiredAccess, out hr); } return safeTokenHandle; } private static SafeAccessTokenHandle GetCurrentProcessToken(TokenAccessLevels desiredAccess, out int hr) { hr = 0; SafeAccessTokenHandle safeTokenHandle; if (!Interop.Advapi32.OpenProcessToken(Interop.Kernel32.GetCurrentProcess(), desiredAccess, out safeTokenHandle)) hr = GetHRForWin32Error(Marshal.GetLastWin32Error()); return safeTokenHandle; } /// <summary> /// Get a property from the current token /// </summary> private T GetTokenInformation<T>(TokenInformationClass tokenInformationClass) where T : struct { Debug.Assert(!_safeTokenHandle.IsInvalid && !_safeTokenHandle.IsClosed, "!m_safeTokenHandle.IsInvalid && !m_safeTokenHandle.IsClosed"); using (SafeLocalAllocHandle information = GetTokenInformation(_safeTokenHandle, tokenInformationClass)) { Debug.Assert(information.ByteLength >= (ulong)Marshal.SizeOf<T>(), "information.ByteLength >= (ulong)Marshal.SizeOf(typeof(T))"); return information.Read<T>(0); } } // // QueryImpersonation used to test if the current thread is impersonated. // This method doesn't return the thread token (WindowsIdentity). // Note GetCurrentInternal can be used to perform the same test, but // QueryImpersonation is optimized for performance // internal static ImpersonationQueryResult QueryImpersonation() { SafeAccessTokenHandle safeTokenHandle = null; bool success = Interop.Advapi32.OpenThreadToken(TokenAccessLevels.Query, WinSecurityContext.Thread, out safeTokenHandle); if (safeTokenHandle != null) { Debug.Assert(success, "[WindowsIdentity..QueryImpersonation] - success"); safeTokenHandle.Dispose(); return ImpersonationQueryResult.Impersonated; } int lastError = Marshal.GetLastWin32Error(); if (lastError == Interop.Errors.ERROR_ACCESS_DENIED) { // thread is impersonated because the thread was there (and we failed to open it). return ImpersonationQueryResult.Impersonated; } if (lastError == Interop.Errors.ERROR_NO_TOKEN) { // definitely not impersonating return ImpersonationQueryResult.NotImpersonated; } // Unexpected failure. return ImpersonationQueryResult.Failed; } private static Interop.LUID GetLogonAuthId(SafeAccessTokenHandle safeTokenHandle) { using (SafeLocalAllocHandle pStatistics = GetTokenInformation(safeTokenHandle, TokenInformationClass.TokenStatistics)) { Interop.TOKEN_STATISTICS statistics = pStatistics.Read<Interop.TOKEN_STATISTICS>(0); return statistics.AuthenticationId; } } private static SafeLocalAllocHandle GetTokenInformation(SafeAccessTokenHandle tokenHandle, TokenInformationClass tokenInformationClass) { SafeLocalAllocHandle safeLocalAllocHandle = SafeLocalAllocHandle.InvalidHandle; uint dwLength = (uint)sizeof(uint); bool result = Interop.Advapi32.GetTokenInformation(tokenHandle, (uint)tokenInformationClass, safeLocalAllocHandle, 0, out dwLength); int dwErrorCode = Marshal.GetLastWin32Error(); switch (dwErrorCode) { case Interop.Errors.ERROR_BAD_LENGTH: // special case for TokenSessionId. Falling through case Interop.Errors.ERROR_INSUFFICIENT_BUFFER: // ptrLength is an [In] param to LocalAlloc UIntPtr ptrLength = new UIntPtr(dwLength); safeLocalAllocHandle.Dispose(); safeLocalAllocHandle = Interop.Kernel32.LocalAlloc(0, ptrLength); if (safeLocalAllocHandle == null || safeLocalAllocHandle.IsInvalid) throw new OutOfMemoryException(); safeLocalAllocHandle.Initialize(dwLength); result = Interop.Advapi32.GetTokenInformation(tokenHandle, (uint)tokenInformationClass, safeLocalAllocHandle, dwLength, out dwLength); if (!result) throw new SecurityException(new Win32Exception().Message); break; case Interop.Errors.ERROR_INVALID_HANDLE: throw new ArgumentException(SR.Argument_InvalidImpersonationToken); default: throw new SecurityException(new Win32Exception(dwErrorCode).Message); } return safeLocalAllocHandle; } protected WindowsIdentity(WindowsIdentity identity) : base(identity, null, GetAuthType(identity), null, null) { bool mustDecrement = false; try { if (!identity._safeTokenHandle.IsInvalid && identity._safeTokenHandle != SafeAccessTokenHandle.InvalidHandle && identity._safeTokenHandle.DangerousGetHandle() != IntPtr.Zero) { identity._safeTokenHandle.DangerousAddRef(ref mustDecrement); if (!identity._safeTokenHandle.IsInvalid && identity._safeTokenHandle.DangerousGetHandle() != IntPtr.Zero) CreateFromToken(identity._safeTokenHandle.DangerousGetHandle()); _authType = identity._authType; _isAuthenticated = identity._isAuthenticated; } } finally { if (mustDecrement) identity._safeTokenHandle.DangerousRelease(); } } private static string GetAuthType(WindowsIdentity identity) { if (identity == null) { throw new ArgumentNullException(nameof(identity)); } return identity._authType; } internal IntPtr GetTokenInternal() { return _safeTokenHandle.DangerousGetHandle(); } internal WindowsIdentity(ClaimsIdentity claimsIdentity, IntPtr userToken) : base(claimsIdentity) { if (userToken != IntPtr.Zero && userToken.ToInt64() > 0) { CreateFromToken(userToken); } } /// <summary> /// Returns a new instance of the base, used when serializing the WindowsIdentity. /// </summary> internal ClaimsIdentity CloneAsBase() { return base.Clone(); } /// <summary> /// Returns a new instance of <see cref="WindowsIdentity"/> with values copied from this object. /// </summary> public override ClaimsIdentity Clone() { return new WindowsIdentity(this); } /// <summary> /// Gets the 'User Claims' from the NTToken that represents this identity /// </summary> public virtual IEnumerable<Claim> UserClaims { get { InitializeClaims(); return _userClaims.ToArray(); } } /// <summary> /// Gets the 'Device Claims' from the NTToken that represents the device the identity is using /// </summary> public virtual IEnumerable<Claim> DeviceClaims { get { InitializeClaims(); return _deviceClaims.ToArray(); } } /// <summary> /// Gets the claims as <see cref="IEnumerable{Claim}"/>, associated with this <see cref="WindowsIdentity"/>. /// Includes UserClaims and DeviceClaims. /// </summary> public override IEnumerable<Claim> Claims { get { if (!_claimsInitialized) { InitializeClaims(); } foreach (Claim claim in base.Claims) yield return claim; foreach (Claim claim in _userClaims) yield return claim; foreach (Claim claim in _deviceClaims) yield return claim; } } /// <summary> /// Intenal method to initialize the claim collection. /// Lazy init is used so claims are not initialzed until needed /// </summary> private void InitializeClaims() { if (!_claimsInitialized) { lock (_claimsIntiailizedLock) { if (!_claimsInitialized) { _userClaims = new List<Claim>(); _deviceClaims = new List<Claim>(); if (!String.IsNullOrEmpty(Name)) { // // Add the name claim only if the WindowsIdentity.Name is populated // WindowsIdentity.Name will be null when it is the fake anonymous user // with a token value of IntPtr.Zero // _userClaims.Add(new Claim(NameClaimType, Name, ClaimValueTypes.String, _issuerName, _issuerName, this)); } // primary sid AddPrimarySidClaim(_userClaims); // group sids AddGroupSidClaims(_userClaims); _claimsInitialized = true; } } } } /// <summary> /// Creates a collection of SID claims that represent the users groups. /// </summary> private void AddGroupSidClaims(List<Claim> instanceClaims) { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return; SafeLocalAllocHandle safeAllocHandle = SafeLocalAllocHandle.InvalidHandle; SafeLocalAllocHandle safeAllocHandlePrimaryGroup = SafeLocalAllocHandle.InvalidHandle; try { // Retrieve the primary group sid safeAllocHandlePrimaryGroup = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenPrimaryGroup); Interop.TOKEN_PRIMARY_GROUP primaryGroup = (Interop.TOKEN_PRIMARY_GROUP)Marshal.PtrToStructure<Interop.TOKEN_PRIMARY_GROUP>(safeAllocHandlePrimaryGroup.DangerousGetHandle()); SecurityIdentifier primaryGroupSid = new SecurityIdentifier(primaryGroup.PrimaryGroup, true); // only add one primary group sid bool foundPrimaryGroupSid = false; // Retrieve all group sids, primary group sid is one of them safeAllocHandle = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenGroups); int count = Marshal.ReadInt32(safeAllocHandle.DangerousGetHandle()); IntPtr pSidAndAttributes = new IntPtr((long)safeAllocHandle.DangerousGetHandle() + (long)Marshal.OffsetOf<Interop.TOKEN_GROUPS>("Groups")); Claim claim; for (int i = 0; i < count; ++i) { Interop.SID_AND_ATTRIBUTES group = (Interop.SID_AND_ATTRIBUTES)Marshal.PtrToStructure<Interop.SID_AND_ATTRIBUTES>(pSidAndAttributes); uint mask = Interop.SecurityGroups.SE_GROUP_ENABLED | Interop.SecurityGroups.SE_GROUP_LOGON_ID | Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY; SecurityIdentifier groupSid = new SecurityIdentifier(group.Sid, true); if ((group.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_ENABLED) { if (!foundPrimaryGroupSid && StringComparer.Ordinal.Equals(groupSid.Value, primaryGroupSid.Value)) { claim = new Claim(ClaimTypes.PrimaryGroupSid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this); claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString()); instanceClaims.Add(claim); foundPrimaryGroupSid = true; } //Primary group sid generates both regular groupsid claim and primary groupsid claim claim = new Claim(ClaimTypes.GroupSid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this); claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString()); instanceClaims.Add(claim); } else if ((group.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY) { if (!foundPrimaryGroupSid && StringComparer.Ordinal.Equals(groupSid.Value, primaryGroupSid.Value)) { claim = new Claim(ClaimTypes.DenyOnlyPrimaryGroupSid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this); claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString()); instanceClaims.Add(claim); foundPrimaryGroupSid = true; } //Primary group sid generates both regular groupsid claim and primary groupsid claim claim = new Claim(ClaimTypes.DenyOnlySid, groupSid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this); claim.Properties.Add(ClaimTypes.WindowsSubAuthority, groupSid.IdentifierAuthority.ToString()); instanceClaims.Add(claim); } pSidAndAttributes = new IntPtr((long)pSidAndAttributes + Marshal.SizeOf<Interop.SID_AND_ATTRIBUTES>()); } } finally { safeAllocHandle.Dispose(); safeAllocHandlePrimaryGroup.Dispose(); } } /// <summary> /// Creates a Windows SID Claim and adds to collection of claims. /// </summary> private void AddPrimarySidClaim(List<Claim> instanceClaims) { // special case the anonymous identity. if (_safeTokenHandle.IsInvalid) return; SafeLocalAllocHandle safeAllocHandle = SafeLocalAllocHandle.InvalidHandle; try { safeAllocHandle = GetTokenInformation(_safeTokenHandle, TokenInformationClass.TokenUser); Interop.SID_AND_ATTRIBUTES user = (Interop.SID_AND_ATTRIBUTES)Marshal.PtrToStructure<Interop.SID_AND_ATTRIBUTES>(safeAllocHandle.DangerousGetHandle()); uint mask = Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY; SecurityIdentifier sid = new SecurityIdentifier(user.Sid, true); Claim claim; if (user.Attributes == 0) { claim = new Claim(ClaimTypes.PrimarySid, sid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this); claim.Properties.Add(ClaimTypes.WindowsSubAuthority, sid.IdentifierAuthority.ToString()); instanceClaims.Add(claim); } else if ((user.Attributes & mask) == Interop.SecurityGroups.SE_GROUP_USE_FOR_DENY_ONLY) { claim = new Claim(ClaimTypes.DenyOnlyPrimarySid, sid.Value, ClaimValueTypes.String, _issuerName, _issuerName, this); claim.Properties.Add(ClaimTypes.WindowsSubAuthority, sid.IdentifierAuthority.ToString()); instanceClaims.Add(claim); } } finally { safeAllocHandle.Dispose(); } } } internal enum WinSecurityContext { Thread = 1, // OpenAsSelf = false Process = 2, // OpenAsSelf = true Both = 3 // OpenAsSelf = true, then OpenAsSelf = false } internal enum ImpersonationQueryResult { Impersonated = 0, // current thread is impersonated NotImpersonated = 1, // current thread is not impersonated Failed = 2 // failed to query } [Serializable] internal enum TokenType : int { TokenPrimary = 1, TokenImpersonation } [Serializable] internal enum TokenInformationClass : int { TokenUser = 1, TokenGroups, TokenPrivileges, TokenOwner, TokenPrimaryGroup, TokenDefaultDacl, TokenSource, TokenType, TokenImpersonationLevel, TokenStatistics, TokenRestrictedSids, TokenSessionId, TokenGroupsAndPrivileges, TokenSessionReference, TokenSandBoxInert, TokenAuditPolicy, TokenOrigin, TokenElevationType, TokenLinkedToken, TokenElevation, TokenHasRestrictions, TokenAccessInformation, TokenVirtualizationAllowed, TokenVirtualizationEnabled, TokenIntegrityLevel, TokenUIAccess, TokenMandatoryPolicy, TokenLogonSid, TokenIsAppContainer, TokenCapabilities, TokenAppContainerSid, TokenAppContainerNumber, TokenUserClaimAttributes, TokenDeviceClaimAttributes, TokenRestrictedUserClaimAttributes, TokenRestrictedDeviceClaimAttributes, TokenDeviceGroups, TokenRestrictedDeviceGroups, MaxTokenInfoClass // MaxTokenInfoClass should always be the last enum } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using Orleans.CodeGeneration; using Orleans.Runtime; namespace Orleans.Serialization { internal static class BinaryTokenStreamWriterExtensions { internal static void Write<TWriter>(this TWriter @this, SerializationTokenType t) where TWriter : IBinaryTokenStreamWriter { @this.Write((byte)t); } /// <summary> Write a <c>CorrelationId</c> value to the stream. </summary> internal static void Write<TWriter>(this TWriter @this, CorrelationId id) where TWriter : IBinaryTokenStreamWriter { @this.Write(id.ToInt64()); } /// <summary> Write a <c>ActivationAddress</c> value to the stream. </summary> internal static void Write<TWriter>(this TWriter @this, ActivationAddress addr) where TWriter : IBinaryTokenStreamWriter { @this.Write(addr.Silo ?? SiloAddress.Zero); // GrainId must not be null @this.Write(addr.Grain); @this.Write(addr.Activation ?? ActivationId.Zero); } internal static void Write<TWriter>(this TWriter @this, UniqueKey key) where TWriter : IBinaryTokenStreamWriter { @this.Write(key.N0); @this.Write(key.N1); @this.Write(key.TypeCodeData); @this.Write(key.KeyExt); } /// <summary> Write a <c>ActivationId</c> value to the stream. </summary> internal static void Write<TWriter>(this TWriter @this, ActivationId id) where TWriter : IBinaryTokenStreamWriter { @this.Write(id.Key); } /// <summary> Write a <c>GrainId</c> value to the stream. </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] internal static void Write<TWriter>(this TWriter @this, GrainId id) where TWriter : IBinaryTokenStreamWriter { @this.Write(id.Key); } /// <summary> /// Write header for an <c>Array</c> to the output stream. /// </summary> /// <param name="this">The IBinaryTokenStreamReader to read from</param> /// <param name="a">Data object for which header should be written.</param> /// <param name="expected">The most recent Expected Type currently active for this stream.</param> internal static void WriteArrayHeader<TWriter>(this TWriter @this, Array a, Type expected = null) where TWriter : IBinaryTokenStreamWriter { @this.WriteTypeHeader(a.GetType(), expected); for (var i = 0; i < a.Rank; i++) { @this.Write(a.GetLength(i)); } } // Back-references internal static void WriteReference<TWriter>(this TWriter @this, int offset) where TWriter : IBinaryTokenStreamWriter { @this.Write((byte)SerializationTokenType.Reference); @this.Write(offset); } } /// <summary> /// Writer for Orleans binary token streams /// </summary> public class BinaryTokenStreamWriter : IBinaryTokenStreamWriter { private readonly ByteArrayBuilder ab; private static readonly Dictionary<RuntimeTypeHandle, SerializationTokenType> typeTokens; private static readonly Dictionary<RuntimeTypeHandle, Action<BinaryTokenStreamWriter, object>> writers; static BinaryTokenStreamWriter() { typeTokens = new Dictionary<RuntimeTypeHandle, SerializationTokenType>(RuntimeTypeHandlerEqualityComparer.Instance); typeTokens[typeof(bool).TypeHandle] = SerializationTokenType.Boolean; typeTokens[typeof(int).TypeHandle] = SerializationTokenType.Int; typeTokens[typeof(uint).TypeHandle] = SerializationTokenType.Uint; typeTokens[typeof(short).TypeHandle] = SerializationTokenType.Short; typeTokens[typeof(ushort).TypeHandle] = SerializationTokenType.Ushort; typeTokens[typeof(long).TypeHandle] = SerializationTokenType.Long; typeTokens[typeof(ulong).TypeHandle] = SerializationTokenType.Ulong; typeTokens[typeof(byte).TypeHandle] = SerializationTokenType.Byte; typeTokens[typeof(sbyte).TypeHandle] = SerializationTokenType.Sbyte; typeTokens[typeof(float).TypeHandle] = SerializationTokenType.Float; typeTokens[typeof(double).TypeHandle] = SerializationTokenType.Double; typeTokens[typeof(decimal).TypeHandle] = SerializationTokenType.Decimal; typeTokens[typeof(string).TypeHandle] = SerializationTokenType.String; typeTokens[typeof(char).TypeHandle] = SerializationTokenType.Character; typeTokens[typeof(Guid).TypeHandle] = SerializationTokenType.Guid; typeTokens[typeof(DateTime).TypeHandle] = SerializationTokenType.Date; typeTokens[typeof(TimeSpan).TypeHandle] = SerializationTokenType.TimeSpan; typeTokens[typeof(GrainId).TypeHandle] = SerializationTokenType.GrainId; typeTokens[typeof(ActivationId).TypeHandle] = SerializationTokenType.ActivationId; typeTokens[typeof(SiloAddress).TypeHandle] = SerializationTokenType.SiloAddress; typeTokens[typeof(ActivationAddress).TypeHandle] = SerializationTokenType.ActivationAddress; typeTokens[typeof(IPAddress).TypeHandle] = SerializationTokenType.IpAddress; typeTokens[typeof(IPEndPoint).TypeHandle] = SerializationTokenType.IpEndPoint; typeTokens[typeof(CorrelationId).TypeHandle] = SerializationTokenType.CorrelationId; typeTokens[typeof(InvokeMethodRequest).TypeHandle] = SerializationTokenType.Request; typeTokens[typeof(Response).TypeHandle] = SerializationTokenType.Response; typeTokens[typeof(Dictionary<string, object>).TypeHandle] = SerializationTokenType.StringObjDict; typeTokens[typeof(Object).TypeHandle] = SerializationTokenType.Object; typeTokens[typeof(List<>).TypeHandle] = SerializationTokenType.List; typeTokens[typeof(SortedList<,>).TypeHandle] = SerializationTokenType.SortedList; typeTokens[typeof(Dictionary<,>).TypeHandle] = SerializationTokenType.Dictionary; typeTokens[typeof(HashSet<>).TypeHandle] = SerializationTokenType.Set; typeTokens[typeof(SortedSet<>).TypeHandle] = SerializationTokenType.SortedSet; typeTokens[typeof(KeyValuePair<,>).TypeHandle] = SerializationTokenType.KeyValuePair; typeTokens[typeof(LinkedList<>).TypeHandle] = SerializationTokenType.LinkedList; typeTokens[typeof(Stack<>).TypeHandle] = SerializationTokenType.Stack; typeTokens[typeof(Queue<>).TypeHandle] = SerializationTokenType.Queue; typeTokens[typeof(Tuple<>).TypeHandle] = SerializationTokenType.Tuple + 1; typeTokens[typeof(Tuple<,>).TypeHandle] = SerializationTokenType.Tuple + 2; typeTokens[typeof(Tuple<,,>).TypeHandle] = SerializationTokenType.Tuple + 3; typeTokens[typeof(Tuple<,,,>).TypeHandle] = SerializationTokenType.Tuple + 4; typeTokens[typeof(Tuple<,,,,>).TypeHandle] = SerializationTokenType.Tuple + 5; typeTokens[typeof(Tuple<,,,,,>).TypeHandle] = SerializationTokenType.Tuple + 6; typeTokens[typeof(Tuple<,,,,,,>).TypeHandle] = SerializationTokenType.Tuple + 7; writers = new Dictionary<RuntimeTypeHandle, Action<BinaryTokenStreamWriter, object>>(RuntimeTypeHandlerEqualityComparer.Instance); writers[typeof(bool).TypeHandle] = (stream, obj) => stream.Write((bool) obj); writers[typeof(int).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Int); stream.Write((int) obj); }; writers[typeof(uint).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Uint); stream.Write((uint) obj); }; writers[typeof(short).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Short); stream.Write((short) obj); }; writers[typeof(ushort).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Ushort); stream.Write((ushort) obj); }; writers[typeof(long).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Long); stream.Write((long) obj); }; writers[typeof(ulong).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Ulong); stream.Write((ulong) obj); }; writers[typeof(byte).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Byte); stream.Write((byte) obj); }; writers[typeof(sbyte).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Sbyte); stream.Write((sbyte) obj); }; writers[typeof(float).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Float); stream.Write((float) obj); }; writers[typeof(double).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Double); stream.Write((double) obj); }; writers[typeof(decimal).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Decimal); stream.Write((decimal)obj); }; writers[typeof(string).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.String); stream.Write((string)obj); }; writers[typeof(char).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Character); stream.Write((char) obj); }; writers[typeof(Guid).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Guid); stream.Write((Guid) obj); }; writers[typeof(DateTime).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.Date); stream.Write((DateTime) obj); }; writers[typeof(TimeSpan).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.TimeSpan); stream.Write((TimeSpan) obj); }; writers[typeof(GrainId).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.GrainId); stream.Write((GrainId) obj); }; writers[typeof(ActivationId).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.ActivationId); stream.Write((ActivationId) obj); }; writers[typeof(SiloAddress).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.SiloAddress); stream.Write((SiloAddress) obj); }; writers[typeof(ActivationAddress).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.ActivationAddress); stream.Write((ActivationAddress) obj); }; writers[typeof(IPAddress).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.IpAddress); stream.Write((IPAddress) obj); }; writers[typeof(IPEndPoint).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.IpEndPoint); stream.Write((IPEndPoint) obj); }; writers[typeof(CorrelationId).TypeHandle] = (stream, obj) => { stream.Write(SerializationTokenType.CorrelationId); stream.Write((CorrelationId) obj); }; } /// <summary> Default constructor. </summary> public BinaryTokenStreamWriter() { ab = new ByteArrayBuilder(); Trace("Starting new binary token stream"); } /// <summary> Return the output stream as a set of <c>ArraySegment</c>. </summary> /// <returns>Data from this stream, converted to output type.</returns> public List<ArraySegment<byte>> ToBytes() { return ab.ToBytes(); } /// <summary> Return the output stream as a <c>byte[]</c>. </summary> /// <returns>Data from this stream, converted to output type.</returns> public byte[] ToByteArray() { return ab.ToByteArray(); } /// <summary> Release any serialization buffers being used by this stream. </summary> public void ReleaseBuffers() { ab.ReleaseBuffers(); } /// <summary> Current write position in the stream. </summary> public int CurrentOffset { get { return ab.Length; } } // Numbers /// <summary> Write an <c>Int32</c> value to the stream. </summary> public void Write(int i) { Trace("--Wrote integer {0}", i); ab.Append(i); } /// <summary> Write an <c>Int16</c> value to the stream. </summary> public void Write(short s) { Trace("--Wrote short {0}", s); ab.Append(s); } /// <summary> Write an <c>Int64</c> value to the stream. </summary> public void Write(long l) { Trace("--Wrote long {0}", l); ab.Append(l); } /// <summary> Write a <c>sbyte</c> value to the stream. </summary> public void Write(sbyte b) { Trace("--Wrote sbyte {0}", b); ab.Append(b); } /// <summary> Write a <c>UInt32</c> value to the stream. </summary> public void Write(uint u) { Trace("--Wrote uint {0}", u); ab.Append(u); } /// <summary> Write a <c>UInt16</c> value to the stream. </summary> public void Write(ushort u) { Trace("--Wrote ushort {0}", u); ab.Append(u); } /// <summary> Write a <c>UInt64</c> value to the stream. </summary> public void Write(ulong u) { Trace("--Wrote ulong {0}", u); ab.Append(u); } /// <summary> Write a <c>byte</c> value to the stream. </summary> public void Write(byte b) { Trace("--Wrote byte {0}", b); ab.Append(b); } /// <summary> Write a <c>float</c> value to the stream. </summary> public void Write(float f) { Trace("--Wrote float {0}", f); ab.Append(f); } /// <summary> Write a <c>double</c> value to the stream. </summary> public void Write(double d) { Trace("--Wrote double {0}", d); ab.Append(d); } /// <summary> Write a <c>decimal</c> value to the stream. </summary> public void Write(decimal d) { Trace("--Wrote decimal {0}", d); ab.Append(Decimal.GetBits(d)); } // Text /// <summary> Write a <c>string</c> value to the stream. </summary> public void Write(string s) { Trace("--Wrote string '{0}'", s); if (null == s) { ab.Append(-1); } else { var bytes = Encoding.UTF8.GetBytes(s); ab.Append(bytes.Length); ab.Append(bytes); } } /// <summary> Write a <c>char</c> value to the stream. </summary> public void Write(char c) { Trace("--Wrote char {0}", c); ab.Append(Convert.ToInt16(c)); } // Other primitives /// <summary> Write a <c>bool</c> value to the stream. </summary> public void Write(bool b) { Trace("--Wrote Boolean {0}", b); ab.Append((byte)(b ? SerializationTokenType.True : SerializationTokenType.False)); } /// <summary> Write a <c>null</c> value to the stream. </summary> public void WriteNull() { Trace("--Wrote null"); ab.Append((byte)SerializationTokenType.Null); } // Types /// <summary> Write a type header for the specified Type to the stream. </summary> /// <param name="t">Type to write header for.</param> /// <param name="expected">Currently expected Type for this stream.</param> public void WriteTypeHeader(Type t, Type expected = null) { Trace("-Writing type header for type {0}, expected {1}", t, expected); if (t == expected) { ab.Append((byte)SerializationTokenType.ExpectedType); return; } ab.Append((byte) SerializationTokenType.SpecifiedType); if (t.IsArray) { ab.Append((byte)(SerializationTokenType.Array + (byte)t.GetArrayRank())); WriteTypeHeader(t.GetElementType()); return; } SerializationTokenType token; if (typeTokens.TryGetValue(t.TypeHandle, out token)) { ab.Append((byte) token); return; } if (t.IsGenericType) { if (typeTokens.TryGetValue(t.GetGenericTypeDefinition().TypeHandle, out token)) { ab.Append((byte)token); foreach (var tp in t.GetGenericArguments()) { WriteTypeHeader(tp); } return; } } ab.Append((byte)SerializationTokenType.NamedType); var typeKey = t.OrleansTypeKey(); ab.Append(typeKey.Length); ab.Append(typeKey); } // Primitive arrays /// <summary> Write a <c>byte[]</c> value to the stream. </summary> public void Write(byte[] b) { Trace("--Wrote byte array of length {0}", b.Length); ab.Append(b); } /// <summary> Write a list of byte array segments to the stream. </summary> public void Write(List<ArraySegment<byte>> bytes) { ab.Append(bytes); } /// <summary> Write the specified number of bytes to the stream, starting at the specified offset in the input <c>byte[]</c>. </summary> /// <param name="b">The input data to be written.</param> /// <param name="offset">The offset into the inout byte[] to start writing bytes from.</param> /// <param name="count">The number of bytes to be written.</param> public void Write(byte[] b, int offset, int count) { if (count <= 0) { return; } Trace("--Wrote byte array of length {0}", count); if ((offset == 0) && (count == b.Length)) { Write(b); } else { var temp = new byte[count]; Buffer.BlockCopy(b, offset, temp, 0, count); Write(temp); } } /// <summary> Write a <c>Int16[]</c> value to the stream. </summary> public void Write(short[] i) { Trace("--Wrote short array of length {0}", i.Length); ab.Append(i); } /// <summary> Write a <c>Int32[]</c> value to the stream. </summary> public void Write(int[] i) { Trace("--Wrote short array of length {0}", i.Length); ab.Append(i); } /// <summary> Write a <c>Int64[]</c> value to the stream. </summary> public void Write(long[] l) { Trace("--Wrote long array of length {0}", l.Length); ab.Append(l); } /// <summary> Write a <c>UInt16[]</c> value to the stream. </summary> public void Write(ushort[] i) { Trace("--Wrote ushort array of length {0}", i.Length); ab.Append(i); } /// <summary> Write a <c>UInt32[]</c> value to the stream. </summary> public void Write(uint[] i) { Trace("--Wrote uint array of length {0}", i.Length); ab.Append(i); } /// <summary> Write a <c>UInt64[]</c> value to the stream. </summary> public void Write(ulong[] l) { Trace("--Wrote ulong array of length {0}", l.Length); ab.Append(l); } /// <summary> Write a <c>sbyte[]</c> value to the stream. </summary> public void Write(sbyte[] l) { Trace("--Wrote sbyte array of length {0}", l.Length); ab.Append(l); } /// <summary> Write a <c>char[]</c> value to the stream. </summary> public void Write(char[] l) { Trace("--Wrote char array of length {0}", l.Length); ab.Append(l); } /// <summary> Write a <c>bool[]</c> value to the stream. </summary> public void Write(bool[] l) { Trace("--Wrote bool array of length {0}", l.Length); ab.Append(l); } /// <summary> Write a <c>double[]</c> value to the stream. </summary> public void Write(double[] d) { Trace("--Wrote double array of length {0}", d.Length); ab.Append(d); } /// <summary> Write a <c>float[]</c> value to the stream. </summary> public void Write(float[] f) { Trace("--Wrote float array of length {0}", f.Length); ab.Append(f); } // Other simple types /// <summary> Write a <c>IPEndPoint</c> value to the stream. </summary> public void Write(IPEndPoint ep) { Write(ep.Address); Write(ep.Port); } /// <summary> Write a <c>IPAddress</c> value to the stream. </summary> public void Write(IPAddress ip) { if (ip.AddressFamily == AddressFamily.InterNetwork) { for (var i = 0; i < 12; i++) { Write((byte)0); } Write(ip.GetAddressBytes()); // IPv4 -- 4 bytes } else { Write(ip.GetAddressBytes()); // IPv6 -- 16 bytes } } /// <summary> Write a <c>SiloAddress</c> value to the stream. </summary> public void Write(SiloAddress addr) { Write(addr.Endpoint); Write(addr.Generation); } /// <summary> Write a <c>TimeSpan</c> value to the stream. </summary> public void Write(TimeSpan ts) { Write(ts.Ticks); } /// <summary> Write a <c>DataTime</c> value to the stream. </summary> public void Write(DateTime dt) { Write(dt.ToBinary()); } /// <summary> Write a <c>Guid</c> value to the stream. </summary> public void Write(Guid id) { Write(id.ToByteArray()); } /// <summary> /// Try to write a simple type (non-array) value to the stream. /// </summary> /// <param name="obj">Input object to be written to the output stream.</param> /// <returns>Returns <c>true</c> if the value was successfully written to the output stream.</returns> public bool TryWriteSimpleObject(object obj) { if (obj == null) { WriteNull(); return true; } Action<BinaryTokenStreamWriter, object> writer; if (writers.TryGetValue(obj.GetType().TypeHandle, out writer)) { writer(this, obj); return true; } return false; } // General containers private StreamWriter trace; [Conditional("TRACE_SERIALIZATION")] private void Trace(string format, params object[] args) { if (trace == null) { var path = String.Format("d:\\Trace-{0}.{1}.{2}.txt", DateTime.UtcNow.Hour, DateTime.UtcNow.Minute, DateTime.UtcNow.Ticks); Console.WriteLine("Opening trace file at '{0}'", path); trace = File.CreateText(path); } trace.Write(format, args); trace.WriteLine(" at offset {0}", CurrentOffset); trace.Flush(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System; using System.Linq; using System.Runtime.CompilerServices; using System.Security.Claims; using System.Security.Principal; using System.Threading; using System.Threading.Tasks; using System.Threading.Tests; using Xunit; public class WindowsIdentityTests { private const string authenticationType = "WindowsAuthentication"; [Fact] public static void GetAnonymousUserTest() { WindowsIdentity windowsIdentity = WindowsIdentity.GetAnonymous(); Assert.True(windowsIdentity.IsAnonymous); Assert.False(windowsIdentity.IsAuthenticated); CheckDispose(windowsIdentity, true); } [Fact] public static void ConstructorsAndProperties() { TestUsingAccessToken((logonToken) => { // Construct a WindowsIdentity object using the input account token. var windowsIdentity = new WindowsIdentity(logonToken); CheckDispose(windowsIdentity); var windowsIdentity2 = new WindowsIdentity(logonToken, authenticationType); Assert.True(windowsIdentity2.IsAuthenticated); Assert.Equal(authenticationType, windowsIdentity2.AuthenticationType); CheckDispose(windowsIdentity2); }); } [Theory] [InlineData(true)] [InlineData(false)] public static void AuthenticationCtor(bool authentication) { TestUsingAccessToken((logonToken) => { var windowsIdentity = new WindowsIdentity(logonToken, authenticationType, WindowsAccountType.Normal, isAuthenticated: authentication); Assert.Equal(authentication, windowsIdentity.IsAuthenticated); Assert.Equal(authenticationType, windowsIdentity.AuthenticationType); CheckDispose(windowsIdentity); }); } [Fact] public static void WindowsAccountTypeCtor() { TestUsingAccessToken((logonToken) => { var windowsIdentity = new WindowsIdentity(logonToken, authenticationType, WindowsAccountType.Normal); Assert.True(windowsIdentity.IsAuthenticated); Assert.Equal(authenticationType, windowsIdentity.AuthenticationType); CheckDispose(windowsIdentity); }); } [Fact] public static void CloneAndProperties() { TestUsingAccessToken((logonToken) => { var winId = new WindowsIdentity(logonToken); WindowsIdentity cloneWinId = winId.Clone() as WindowsIdentity; Assert.NotNull(cloneWinId); Assert.Equal(winId.IsSystem, cloneWinId.IsSystem); Assert.Equal(winId.IsGuest, cloneWinId.IsGuest); Assert.Equal(winId.ImpersonationLevel, cloneWinId.ImpersonationLevel); Assert.Equal(winId.Name, cloneWinId.Name); Assert.Equal(winId.Owner, cloneWinId.Owner); IdentityReferenceCollection irc1 = winId.Groups; IdentityReferenceCollection irc2 = cloneWinId.Groups; Assert.Equal(irc1.Count, irc2.Count); CheckDispose(winId); CheckDispose(cloneWinId); }); } [Fact] public static void GetTokenHandle() { WindowsIdentity id = WindowsIdentity.GetCurrent(); Assert.Equal(id.AccessToken.DangerousGetHandle(), id.Token); } [Fact] public static void CheckDeviceClaims() { using (WindowsIdentity id = WindowsIdentity.GetCurrent()) { int manualCount = id.Claims.Count(c => c.Properties.ContainsKey(ClaimTypes.WindowsDeviceClaim)); int autoCount = id.DeviceClaims.Count(); Assert.Equal(manualCount, autoCount); } } [Fact] public static void CheckUserClaims() { using (WindowsIdentity id = WindowsIdentity.GetCurrent()) { Claim[] allClaims = id.Claims.ToArray(); int deviceCount = allClaims.Count(c => c.Properties.ContainsKey(ClaimTypes.WindowsDeviceClaim)); int manualCount = allClaims.Length - deviceCount; int autoCount = id.UserClaims.Count(); Assert.Equal(manualCount, autoCount); } } [Fact] public static void RunImpersonatedTest_InvalidHandle() { using (var mutex = new Mutex()) { SafeAccessTokenHandle handle = null; try { handle = new SafeAccessTokenHandle(mutex.SafeWaitHandle.DangerousGetHandle()); Assert.Throws<ArgumentException>(() => WindowsIdentity.RunImpersonated(handle, () => { })); } finally { handle?.SetHandleAsInvalid(); } } } [Fact] public static void RunImpersonatedAsyncTest() { var testData = new RunImpersonatedAsyncTestInfo(); BeginTask(testData); // Wait for the SafeHandle that was disposed in BeginTask() to actually be closed GC.Collect(); GC.WaitForPendingFinalizers(); GC.WaitForPendingFinalizers(); testData.continueTask.Release(); testData.task.CheckedWait(); if (testData.exception != null) { throw new AggregateException(testData.exception); } } [MethodImpl(MethodImplOptions.NoInlining)] private static void BeginTask(RunImpersonatedAsyncTestInfo testInfo) { testInfo.continueTask = new SemaphoreSlim(0, 1); using (SafeAccessTokenHandle token = WindowsIdentity.GetCurrent().AccessToken) { WindowsIdentity.RunImpersonated(token, () => { testInfo.task = Task.Run(async () => { try { Task<bool> task = testInfo.continueTask.WaitAsync(ThreadTestHelpers.UnexpectedTimeoutMilliseconds); Assert.True(await task.ConfigureAwait(false)); } catch (Exception ex) { testInfo.exception = ex; } }); }); } } private class RunImpersonatedAsyncTestInfo { public Task task; public SemaphoreSlim continueTask; public Exception exception; } private static void CheckDispose(WindowsIdentity identity, bool anonymous = false) { Assert.False(identity.AccessToken.IsClosed); try { identity.Dispose(); } catch { } Assert.True(identity.AccessToken.IsClosed); if (!anonymous) { Assert.Throws<ObjectDisposedException>(() => identity.Name); Assert.Throws<ObjectDisposedException>(() => identity.Owner); Assert.Throws<ObjectDisposedException>(() => identity.User); } } private static void TestUsingAccessToken(Action<IntPtr> ctorOrPropertyTest) { // Retrieve the Windows account token for the current user. SafeAccessTokenHandle token = WindowsIdentity.GetCurrent().AccessToken; bool gotRef = false; try { token.DangerousAddRef(ref gotRef); IntPtr logonToken = token.DangerousGetHandle(); ctorOrPropertyTest(logonToken); } finally { if (gotRef) token.DangerousRelease(); } } }
/////////////////////////////////////////////////////////////////////////////////////////////// // // This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler // // Copyright (c) 2005-2008, Jim Heising // 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 Jim Heising nor the names of its contributors may be // used to endorse or promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // /////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; using System.Collections; namespace WOSI.Utilities { public class FifoStream : Stream { private const int BlockSize = 65536; private const int MaxBlocksInCache = (3 * 1024 * 1024) / BlockSize; private int m_Size; private int m_RPos; private int m_WPos; private Stack m_UsedBlocks = new Stack(); private ArrayList m_Blocks = new ArrayList(); private byte[] AllocBlock() { byte[] Result = null; Result = m_UsedBlocks.Count > 0 ? (byte[])m_UsedBlocks.Pop() : new byte[BlockSize]; return Result; } private void FreeBlock(byte[] block) { if (m_UsedBlocks.Count < MaxBlocksInCache) m_UsedBlocks.Push(block); } private byte[] GetWBlock() { byte[] Result = null; if (m_WPos < BlockSize && m_Blocks.Count > 0) Result = (byte[])m_Blocks[m_Blocks.Count - 1]; else { Result = AllocBlock(); m_Blocks.Add(Result); m_WPos = 0; } return Result; } // Stream members public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return true; } } public override long Length { get { lock (this) return m_Size; } } public override long Position { get { throw new InvalidOperationException(); } set { throw new InvalidOperationException(); } } public override void Close() { Flush(); } public override void Flush() { lock (this) { foreach (byte[] block in m_Blocks) FreeBlock(block); m_Blocks.Clear(); m_RPos = 0; m_WPos = 0; m_Size = 0; } } public override void SetLength(long len) { throw new InvalidOperationException(); } public override long Seek(long pos, SeekOrigin o) { throw new InvalidOperationException(); } public override int Read(byte[] buf, int ofs, int count) { lock (this) { int Result = Peek(buf, ofs, count); Advance(Result); return Result; } } public override void Write(byte[] buf, int ofs, int count) { lock (this) { int Left = count; while (Left > 0) { int ToWrite = Math.Min(BlockSize - m_WPos, Left); Array.Copy(buf, ofs + count - Left, GetWBlock(), m_WPos, ToWrite); m_WPos += ToWrite; Left -= ToWrite; } m_Size += count; } } // extra stuff public int Advance(int count) { lock (this) { int SizeLeft = count; while (SizeLeft > 0 && m_Size > 0) { if (m_RPos == BlockSize) { m_RPos = 0; FreeBlock((byte[])m_Blocks[0]); m_Blocks.RemoveAt(0); } int ToFeed = m_Blocks.Count == 1 ? Math.Min(m_WPos - m_RPos, SizeLeft) : Math.Min(BlockSize - m_RPos, SizeLeft); m_RPos += ToFeed; SizeLeft -= ToFeed; m_Size -= ToFeed; } return count - SizeLeft; } } public int Peek(byte[] buf, int ofs, int count) { lock (this) { int SizeLeft = count; int TempBlockPos = m_RPos; int TempSize = m_Size; int CurrentBlock = 0; while (SizeLeft > 0 && TempSize > 0) { if (TempBlockPos == BlockSize) { TempBlockPos = 0; CurrentBlock++; } int Upper = CurrentBlock < m_Blocks.Count - 1 ? BlockSize : m_WPos; int ToFeed = Math.Min(Upper - TempBlockPos, SizeLeft); Array.Copy((byte[])m_Blocks[CurrentBlock], TempBlockPos, buf, ofs + count - SizeLeft, ToFeed); SizeLeft -= ToFeed; TempBlockPos += ToFeed; TempSize -= ToFeed; } return count - SizeLeft; } } } }
namespace Microsoft.Msagl.Core.Geometry.Curves { /// <summary> /// The interface for curves: instances of ICurve inside of GLEE /// are BSpline,Curve,LineSeg, Ellipse,CubicBezierSeg and ArrowTipCurve. /// </summary> public interface ICurve { /// <summary> /// Returns the point on the curve corresponding to parameter t /// </summary> /// <param name="t"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1043:UseIntegralOrStringArgumentForIndexers")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "t")] Point this[double t] { get; } /// <summary> /// first derivative at t /// </summary> /// <param name="t">the parameter where the derivative is calculated</param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "t")] Point Derivative(double t); /// <summary> /// second derivative /// </summary> /// <param name="t"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "t")] Point SecondDerivative(double t); /// <summary> /// third derivative /// </summary> /// <param name="t">the parameter of the derivative</param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "t")] Point ThirdDerivative(double t); /// <summary> /// A tree of ParallelogramNodes covering the curve. /// This tree is used in curve intersections routines. /// </summary> /// <value></value> ParallelogramNodeOverICurve ParallelogramNodeOverICurve { get; } /// <summary> /// XY bounding box of the curve /// </summary> Rectangle BoundingBox { get;} /// <summary> /// the start of the parameter domain /// </summary> double ParStart { get;} /// <summary> /// the end of the parameter domain /// </summary> double ParEnd { get;} /// <summary> /// Returns the trim curve between start and end, without wrap /// </summary> /// <param name="start"></param> /// <param name="end"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "End")] ICurve Trim(double start, double end); /// <summary> /// Returns the trim curve between start and end, with wrap, if supported by the implementing class. /// </summary> /// <param name="start"></param> /// <param name="end"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "End")] ICurve TrimWithWrap(double start, double end); /// <summary> /// Moves the curve by the delta. /// </summary> void Translate(Point delta); /// <summary> /// Returns the curved with all points scaled from the original by x and y /// </summary> /// <returns></returns> ICurve ScaleFromOrigin(double xScale, double yScale); /// <summary> /// this[ParStart] /// </summary> Point Start { get;} /// <summary> /// this[ParEnd] /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "End")] Point End { get; } /// <summary> /// this[Reverse[t]]=this[ParEnd+ParStart-t] /// </summary> /// <returns></returns> ICurve Reverse(); /// <summary> /// Offsets the curve in the direction of dir /// </summary> /// <param name="offset"></param> /// <param name="dir"></param> /// <returns></returns> ICurve OffsetCurve(double offset, Point dir); /// <summary> /// return length of the curve segment [start,end] /// </summary> /// <param name="start"></param> /// <param name="end"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "End")] double LengthPartial(double start, double end); /// <summary> /// Get the length of the curve /// </summary> double Length { get;} /// <summary> /// gets the parameter at a specific length from the start along the curve /// </summary> /// <param name="length"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "t")] double GetParameterAtLength(double length); /// <summary> /// Return the transformed curve /// </summary> /// <param name="transformation"></param> /// <returns>the transformed curve</returns> ICurve Transform(PlaneTransformation transformation); /// <summary> /// returns a parameter t such that the distance between curve[t] and targetPoint is minimal /// and t belongs to the closed segment [low,high] /// </summary> /// <param name="targetPoint">the point to find the closest point</param> /// <param name="high">the upper bound of the parameter</param> /// <param name="low">the low bound of the parameter</param> /// <returns></returns> double ClosestParameterWithinBounds(Point targetPoint, double low, double high); /// <summary> /// returns a parameter t such that the distance between curve[t] and a is minimal /// </summary> /// <param name="targetPoint"></param> /// <returns></returns> double ClosestParameter(Point targetPoint); /// <summary> /// clones the curve. /// </summary> /// <returns>the cloned curve</returns> ICurve Clone(); /// <summary> /// The left derivative at t. /// </summary> /// <param name="t">the parameter where the derivative is calculated</param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "t")] Point LeftDerivative(double t); /// <summary> /// the right derivative at t /// </summary> /// <param name="t">the parameter where the derivative is calculated</param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "t")] Point RightDerivative(double t); /// <summary> /// the signed curvature of the segment at t /// </summary> /// <param name="t"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "t")] double Curvature(double t); /// <summary> /// the derivative of the curvature at t /// </summary> /// <param name="t"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "t")] double CurvatureDerivative(double t); /// <summary> /// the derivative of CurvatureDerivative /// </summary> /// <param name="t"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "t")] double CurvatureSecondDerivative(double t); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.noaccessibility004.noaccessibility004 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.noaccessibility004.noaccessibility004; // <Title>Call methods that have different accessibility</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public class Foo { protected internal int this[int x] { set { Test.Status = 0; } } } public class Test { public static int Status = -1; public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Foo f = new Foo(); dynamic d = 3; f[d] = -1; return Status; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.errorverifier.errorverifier { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.errorverifier.errorverifier; using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.param012.param012; using System; using System.Collections; using System.IO; using System.Globalization; using System.Reflection; using System.Resources; using Microsoft.CSharp.RuntimeBinder; public enum ErrorElementId { None, SK_METHOD, // method SK_CLASS, // type SK_NAMESPACE, // namespace SK_FIELD, // field SK_PROPERTY, // property SK_UNKNOWN, // element SK_VARIABLE, // variable SK_EVENT, // event SK_TYVAR, // type parameter SK_ALIAS, // using alias ERRORSYM, // <error> NULL, // <null> GlobalNamespace, // <global namespace> MethodGroup, // method group AnonMethod, // anonymous method Lambda, // lambda expression AnonymousType, // anonymous type } public enum ErrorMessageId { None, BadBinaryOps, // Operator '{0}' cannot be applied to operands of type '{1}' and '{2}' IntDivByZero, // Division by constant zero BadIndexLHS, // Cannot apply indexing with [] to an expression of type '{0}' BadIndexCount, // Wrong number of indices inside []; expected '{0}' BadUnaryOp, // Operator '{0}' cannot be applied to operand of type '{1}' NoImplicitConv, // Cannot implicitly convert type '{0}' to '{1}' NoExplicitConv, // Cannot convert type '{0}' to '{1}' ConstOutOfRange, // Constant value '{0}' cannot be converted to a '{1}' AmbigBinaryOps, // Operator '{0}' is ambiguous on operands of type '{1}' and '{2}' AmbigUnaryOp, // Operator '{0}' is ambiguous on an operand of type '{1}' ValueCantBeNull, // Cannot convert null to '{0}' because it is a non-nullable value type WrongNestedThis, // Cannot access a non-static member of outer type '{0}' via nested type '{1}' NoSuchMember, // '{0}' does not contain a definition for '{1}' ObjectRequired, // An object reference is required for the non-static field, method, or property '{0}' AmbigCall, // The call is ambiguous between the following methods or properties: '{0}' and '{1}' BadAccess, // '{0}' is inaccessible due to its protection level MethDelegateMismatch, // No overload for '{0}' matches delegate '{1}' AssgLvalueExpected, // The left-hand side of an assignment must be a variable, property or indexer NoConstructors, // The type '{0}' has no constructors defined BadDelegateConstructor, // The delegate '{0}' does not have a valid constructor PropertyLacksGet, // The property or indexer '{0}' cannot be used in this context because it lacks the get accessor ObjectProhibited, // Member '{0}' cannot be accessed with an instance reference; qualify it with a type name instead AssgReadonly, // A readonly field cannot be assigned to (except in a constructor or a variable initializer) RefReadonly, // A readonly field cannot be passed ref or out (except in a constructor) AssgReadonlyStatic, // A static readonly field cannot be assigned to (except in a static constructor or a variable initializer) RefReadonlyStatic, // A static readonly field cannot be passed ref or out (except in a static constructor) AssgReadonlyProp, // Property or indexer '{0}' cannot be assigned to -- it is read only AbstractBaseCall, // Cannot call an abstract base member: '{0}' RefProperty, // A property or indexer may not be passed as an out or ref parameter ManagedAddr, // Cannot take the address of, get the size of, or declare a pointer to a managed type ('{0}') FixedNotNeeded, // You cannot use the fixed statement to take the address of an already fixed expression UnsafeNeeded, // Dynamic calls cannot be used in conjunction with pointers BadBoolOp, // In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') must have the same return type as the type of its 2 parameters MustHaveOpTF, // The type ('{0}') must contain declarations of operator true and operator false CheckedOverflow, // The operation overflows at compile time in checked mode ConstOutOfRangeChecked, // Constant value '{0}' cannot be converted to a '{1}' (use 'unchecked' syntax to override) AmbigMember, // Ambiguity between '{0}' and '{1}' SizeofUnsafe, // '{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf) FieldInitRefNonstatic, // A field initializer cannot reference the non-static field, method, or property '{0}' CallingFinalizeDepracated, // Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available. CallingBaseFinalizeDeprecated, // Do not directly call your base class Finalize method. It is called automatically from your destructor. BadCastInFixed, // The right hand side of a fixed statement assignment may not be a cast expression NoImplicitConvCast, // Cannot implicitly convert type '{0}' to '{1}'. An explicit conversion exists (are you missing a cast?) InaccessibleGetter, // The property or indexer '{0}' cannot be used in this context because the get accessor is inaccessible InaccessibleSetter, // The property or indexer '{0}' cannot be used in this context because the set accessor is inaccessible BadArity, // Using the generic {1} '{0}' requires '{2}' type arguments BadTypeArgument, // The type '{0}' may not be used as a type argument TypeArgsNotAllowed, // The {1} '{0}' cannot be used with type arguments HasNoTypeVars, // The non-generic {1} '{0}' cannot be used with type arguments NewConstraintNotSatisfied, // '{2}' must be a non-abstract type with a public parameterless constructor in order to use it as parameter '{1}' in the generic type or method '{0}' GenericConstraintNotSatisfiedRefType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no implicit reference conversion from '{3}' to '{1}'. GenericConstraintNotSatisfiedNullableEnum, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'. GenericConstraintNotSatisfiedNullableInterface, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'. Nullable types can not satisfy any interface constraints. GenericConstraintNotSatisfiedTyVar, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion or type parameter conversion from '{3}' to '{1}'. GenericConstraintNotSatisfiedValType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion from '{3}' to '{1}'. TypeVarCantBeNull, // Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead. BadRetType, // '{1} {0}' has the wrong return type CantInferMethTypeArgs, // The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly. MethGrpToNonDel, // Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method? RefConstraintNotSatisfied, // The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}' ValConstraintNotSatisfied, // The type '{2}' must be a non-nullable value type in order to use it as parameter '{1}' in the generic type or method '{0}' CircularConstraint, // Circular constraint dependency involving '{0}' and '{1}' BaseConstraintConflict, // Type parameter '{0}' inherits conflicting constraints '{1}' and '{2}' ConWithValCon, // Type parameter '{1}' has the 'struct' constraint so '{1}' cannot be used as a constraint for '{0}' AmbigUDConv, // Ambiguous user defined conversions '{0}' and '{1}' when converting from '{2}' to '{3}' PredefinedTypeNotFound, // Predefined type '{0}' is not defined or imported PredefinedTypeBadType, // Predefined type '{0}' is declared incorrectly BindToBogus, // '{0}' is not supported by the language CantCallSpecialMethod, // '{0}': cannot explicitly call operator or accessor BogusType, // '{0}' is a type not supported by the language MissingPredefinedMember, // Missing compiler required member '{0}.{1}' LiteralDoubleCast, // Literal of type double cannot be implicitly converted to type '{1}'; use an '{0}' suffix to create a literal of this type UnifyingInterfaceInstantiations, // '{0}' cannot implement both '{1}' and '{2}' because they may unify for some type parameter substitutions ConvertToStaticClass, // Cannot convert to static type '{0}' GenericArgIsStaticClass, // '{0}': static types cannot be used as type arguments PartialMethodToDelegate, // Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration IncrementLvalueExpected, // The operand of an increment or decrement operator must be a variable, property or indexer NoSuchMemberOrExtension, // '{0}' does not contain a definition for '{1}' and no extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive or an assembly reference?) ValueTypeExtDelegate, // Extension methods '{0}' defined on value type '{1}' cannot be used to create delegates BadArgCount, // No overload for method '{0}' takes '{1}' arguments BadArgTypes, // The best overloaded method match for '{0}' has some invalid arguments BadArgType, // Argument '{0}': cannot convert from '{1}' to '{2}' RefLvalueExpected, // A ref or out argument must be an assignable variable BadProtectedAccess, // Cannot access protected member '{0}' via a qualifier of type '{1}'; the qualifier must be of type '{2}' (or derived from it) BindToBogusProp2, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor methods '{1}' or '{2}' BindToBogusProp1, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor method '{1}' BadDelArgCount, // Delegate '{0}' does not take '{1}' arguments BadDelArgTypes, // Delegate '{0}' has some invalid arguments AssgReadonlyLocal, // Cannot assign to '{0}' because it is read-only RefReadonlyLocal, // Cannot pass '{0}' as a ref or out argument because it is read-only ReturnNotLValue, // Cannot modify the return value of '{0}' because it is not a variable BadArgExtraRef, // Argument '{0}' should not be passed with the '{1}' keyword // DelegateOnConditional, // Cannot create delegate with '{0}' because it has a Conditional attribute (REMOVED) BadArgRef, // Argument '{0}' must be passed with the '{1}' keyword AssgReadonly2, // Members of readonly field '{0}' cannot be modified (except in a constructor or a variable initializer) RefReadonly2, // Members of readonly field '{0}' cannot be passed ref or out (except in a constructor) AssgReadonlyStatic2, // Fields of static readonly field '{0}' cannot be assigned to (except in a static constructor or a variable initializer) RefReadonlyStatic2, // Fields of static readonly field '{0}' cannot be passed ref or out (except in a static constructor) AssgReadonlyLocalCause, // Cannot assign to '{0}' because it is a '{1}' RefReadonlyLocalCause, // Cannot pass '{0}' as a ref or out argument because it is a '{1}' ThisStructNotInAnonMeth, // Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead. DelegateOnNullable, // Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<T>' BadCtorArgCount, // '{0}' does not contain a constructor that takes '{1}' arguments BadExtensionArgTypes, // '{0}' does not contain a definition for '{1}' and the best extension method overload '{2}' has some invalid arguments BadInstanceArgType, // Instance argument: cannot convert from '{0}' to '{1}' BadArgTypesForCollectionAdd, // The best overloaded Add method '{0}' for the collection initializer has some invalid arguments InitializerAddHasParamModifiers, // The best overloaded method match '{0}' for the collection initializer element cannot be used. Collection initializer 'Add' methods cannot have ref or out parameters. NonInvocableMemberCalled, // Non-invocable member '{0}' cannot be used like a method. NamedArgumentSpecificationBeforeFixedArgument, // Named argument specifications must appear after all fixed arguments have been specified BadNamedArgument, // The best overload for '{0}' does not have a parameter named '{1}' BadNamedArgumentForDelegateInvoke, // The delegate '{0}' does not have a parameter named '{1}' DuplicateNamedArgument, // Named argument '{0}' cannot be specified multiple times NamedArgumentUsedInPositional, // Named argument '{0}' specifies a parameter for which a positional argument has already been given } public enum RuntimeErrorId { None, // RuntimeBinderInternalCompilerException InternalCompilerError, // An unexpected exception occurred while binding a dynamic operation // ArgumentException BindRequireArguments, // Cannot bind call with no calling object // RuntimeBinderException BindCallFailedOverloadResolution, // Overload resolution failed // ArgumentException BindBinaryOperatorRequireTwoArguments, // Binary operators must be invoked with two arguments // ArgumentException BindUnaryOperatorRequireOneArgument, // Unary operators must be invoked with one argument // RuntimeBinderException BindPropertyFailedMethodGroup, // The name '{0}' is bound to a method and cannot be used like a property // RuntimeBinderException BindPropertyFailedEvent, // The event '{0}' can only appear on the left hand side of += or -= // RuntimeBinderException BindInvokeFailedNonDelegate, // Cannot invoke a non-delegate type // ArgumentException BindImplicitConversionRequireOneArgument, // Implicit conversion takes exactly one argument // ArgumentException BindExplicitConversionRequireOneArgument, // Explicit conversion takes exactly one argument // ArgumentException BindBinaryAssignmentRequireTwoArguments, // Binary operators cannot be invoked with one argument // RuntimeBinderException BindBinaryAssignmentFailedNullReference, // Cannot perform member assignment on a null reference // RuntimeBinderException NullReferenceOnMemberException, // Cannot perform runtime binding on a null reference // RuntimeBinderException BindCallToConditionalMethod, // Cannot dynamically invoke method '{0}' because it has a Conditional attribute // RuntimeBinderException BindToVoidMethodButExpectResult, // Cannot implicitly convert type 'void' to 'object' // EE? EmptyDynamicView, // No further information on this object could be discovered // MissingMemberException GetValueonWriteOnlyProperty, // Write Only properties are not supported } public class ErrorVerifier { private static Assembly s_asm; private static ResourceManager s_rm1; private static ResourceManager s_rm2; public static string GetErrorElement(ErrorElementId id) { return string.Empty; } public static bool Verify(ErrorMessageId id, string actualError, params string[] args) { return true; } public static bool Verify(RuntimeErrorId id, string actualError, params string[] args) { return true; } private static bool CompareMessages(ResourceManager rm, string id, string actualError, params string[] args) { // should not happen if (null == rm) return false; if (String.IsNullOrEmpty(id) || String.IsNullOrEmpty(actualError)) { System.Console.WriteLine("Empty error id or actual message"); return false; } string message = rm.GetString(id, null); if ((null != args) && (0 < args.Length)) { message = String.Format(CultureInfo.InvariantCulture, message, args); } bool ret = 0 == String.CompareOrdinal(message, actualError); // debug if (!ret) { System.Console.WriteLine("*** Expected= {0}\r\n*** Actual= {1}", message, actualError); } return ret; } } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.param012.param012 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.errorverifier.errorverifier; using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.param012.param012; // <Title>Call methods that have different parameter modifiers with dynamic</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> //<Expects Status=warning>\(23,23\).*CS0649</Expects> public struct myStruct { public int Field; } public class Foo { public int this[params int[] x] { set { } } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Foo f = new Foo(); dynamic d = "foo"; try { f[d] = 1; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "Foo.this[params int[]]")) return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.param014.param014 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.errorverifier.errorverifier; using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.setter.Oneclass.Oneparam.param014.param014; // <Title>Call methods that have different parameter modifiers with dynamic</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public struct myStruct { public int Field; } public class Foo { public int this[params int[] x] { set { } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Foo f = new Foo(); dynamic d = "foo"; dynamic d2 = 3; try { f[d2, d] = 3; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "Foo.this[params int[]]")) return 0; } return 1; } } // </Code> }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using Google.Api; using Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.Cloud.Monitoring.V3; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Google.Cloud.Monitoring.V3.Snippets { /// <summary>Generated snippets</summary> public class GeneratedMetricServiceClientSnippets { /// <summary>Snippet for ListMonitoredResourceDescriptorsAsync</summary> public async Task ListMonitoredResourceDescriptorsAsync() { // Snippet: ListMonitoredResourceDescriptorsAsync(ProjectName,string,int?,CallSettings) // Create client MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync(); // Initialize request argument(s) ProjectName name = new ProjectName("[PROJECT]"); // Make the request PagedAsyncEnumerable<ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor> response = metricServiceClient.ListMonitoredResourceDescriptorsAsync(name); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((MonitoredResourceDescriptor 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((ListMonitoredResourceDescriptorsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (MonitoredResourceDescriptor item in page) { 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<MonitoredResourceDescriptor> 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 (MonitoredResourceDescriptor item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListMonitoredResourceDescriptors</summary> public void ListMonitoredResourceDescriptors() { // Snippet: ListMonitoredResourceDescriptors(ProjectName,string,int?,CallSettings) // Create client MetricServiceClient metricServiceClient = MetricServiceClient.Create(); // Initialize request argument(s) ProjectName name = new ProjectName("[PROJECT]"); // Make the request PagedEnumerable<ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor> response = metricServiceClient.ListMonitoredResourceDescriptors(name); // Iterate over all response items, lazily performing RPCs as required foreach (MonitoredResourceDescriptor 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 (ListMonitoredResourceDescriptorsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (MonitoredResourceDescriptor item in page) { 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<MonitoredResourceDescriptor> 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 (MonitoredResourceDescriptor item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListMonitoredResourceDescriptorsAsync</summary> public async Task ListMonitoredResourceDescriptorsAsync_RequestObject() { // Snippet: ListMonitoredResourceDescriptorsAsync(ListMonitoredResourceDescriptorsRequest,CallSettings) // Create client MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync(); // Initialize request argument(s) ListMonitoredResourceDescriptorsRequest request = new ListMonitoredResourceDescriptorsRequest { ProjectName = new ProjectName("[PROJECT]"), }; // Make the request PagedAsyncEnumerable<ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor> response = metricServiceClient.ListMonitoredResourceDescriptorsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((MonitoredResourceDescriptor 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((ListMonitoredResourceDescriptorsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (MonitoredResourceDescriptor item in page) { 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<MonitoredResourceDescriptor> 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 (MonitoredResourceDescriptor item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListMonitoredResourceDescriptors</summary> public void ListMonitoredResourceDescriptors_RequestObject() { // Snippet: ListMonitoredResourceDescriptors(ListMonitoredResourceDescriptorsRequest,CallSettings) // Create client MetricServiceClient metricServiceClient = MetricServiceClient.Create(); // Initialize request argument(s) ListMonitoredResourceDescriptorsRequest request = new ListMonitoredResourceDescriptorsRequest { ProjectName = new ProjectName("[PROJECT]"), }; // Make the request PagedEnumerable<ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor> response = metricServiceClient.ListMonitoredResourceDescriptors(request); // Iterate over all response items, lazily performing RPCs as required foreach (MonitoredResourceDescriptor 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 (ListMonitoredResourceDescriptorsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (MonitoredResourceDescriptor item in page) { 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<MonitoredResourceDescriptor> 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 (MonitoredResourceDescriptor item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetMonitoredResourceDescriptorAsync</summary> public async Task GetMonitoredResourceDescriptorAsync() { // Snippet: GetMonitoredResourceDescriptorAsync(MonitoredResourceDescriptorName,CallSettings) // Additional: GetMonitoredResourceDescriptorAsync(MonitoredResourceDescriptorName,CancellationToken) // Create client MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync(); // Initialize request argument(s) MonitoredResourceDescriptorName name = new MonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"); // Make the request MonitoredResourceDescriptor response = await metricServiceClient.GetMonitoredResourceDescriptorAsync(name); // End snippet } /// <summary>Snippet for GetMonitoredResourceDescriptor</summary> public void GetMonitoredResourceDescriptor() { // Snippet: GetMonitoredResourceDescriptor(MonitoredResourceDescriptorName,CallSettings) // Create client MetricServiceClient metricServiceClient = MetricServiceClient.Create(); // Initialize request argument(s) MonitoredResourceDescriptorName name = new MonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"); // Make the request MonitoredResourceDescriptor response = metricServiceClient.GetMonitoredResourceDescriptor(name); // End snippet } /// <summary>Snippet for GetMonitoredResourceDescriptorAsync</summary> public async Task GetMonitoredResourceDescriptorAsync_RequestObject() { // Snippet: GetMonitoredResourceDescriptorAsync(GetMonitoredResourceDescriptorRequest,CallSettings) // Create client MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync(); // Initialize request argument(s) GetMonitoredResourceDescriptorRequest request = new GetMonitoredResourceDescriptorRequest { MonitoredResourceDescriptorName = new MonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"), }; // Make the request MonitoredResourceDescriptor response = await metricServiceClient.GetMonitoredResourceDescriptorAsync(request); // End snippet } /// <summary>Snippet for GetMonitoredResourceDescriptor</summary> public void GetMonitoredResourceDescriptor_RequestObject() { // Snippet: GetMonitoredResourceDescriptor(GetMonitoredResourceDescriptorRequest,CallSettings) // Create client MetricServiceClient metricServiceClient = MetricServiceClient.Create(); // Initialize request argument(s) GetMonitoredResourceDescriptorRequest request = new GetMonitoredResourceDescriptorRequest { MonitoredResourceDescriptorName = new MonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]"), }; // Make the request MonitoredResourceDescriptor response = metricServiceClient.GetMonitoredResourceDescriptor(request); // End snippet } /// <summary>Snippet for ListMetricDescriptorsAsync</summary> public async Task ListMetricDescriptorsAsync() { // Snippet: ListMetricDescriptorsAsync(ProjectName,string,int?,CallSettings) // Create client MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync(); // Initialize request argument(s) ProjectName name = new ProjectName("[PROJECT]"); // Make the request PagedAsyncEnumerable<ListMetricDescriptorsResponse, MetricDescriptor> response = metricServiceClient.ListMetricDescriptorsAsync(name); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((MetricDescriptor 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((ListMetricDescriptorsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (MetricDescriptor item in page) { 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<MetricDescriptor> 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 (MetricDescriptor item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListMetricDescriptors</summary> public void ListMetricDescriptors() { // Snippet: ListMetricDescriptors(ProjectName,string,int?,CallSettings) // Create client MetricServiceClient metricServiceClient = MetricServiceClient.Create(); // Initialize request argument(s) ProjectName name = new ProjectName("[PROJECT]"); // Make the request PagedEnumerable<ListMetricDescriptorsResponse, MetricDescriptor> response = metricServiceClient.ListMetricDescriptors(name); // Iterate over all response items, lazily performing RPCs as required foreach (MetricDescriptor 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 (ListMetricDescriptorsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (MetricDescriptor item in page) { 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<MetricDescriptor> 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 (MetricDescriptor item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListMetricDescriptorsAsync</summary> public async Task ListMetricDescriptorsAsync_RequestObject() { // Snippet: ListMetricDescriptorsAsync(ListMetricDescriptorsRequest,CallSettings) // Create client MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync(); // Initialize request argument(s) ListMetricDescriptorsRequest request = new ListMetricDescriptorsRequest { ProjectName = new ProjectName("[PROJECT]"), }; // Make the request PagedAsyncEnumerable<ListMetricDescriptorsResponse, MetricDescriptor> response = metricServiceClient.ListMetricDescriptorsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((MetricDescriptor 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((ListMetricDescriptorsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (MetricDescriptor item in page) { 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<MetricDescriptor> 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 (MetricDescriptor item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListMetricDescriptors</summary> public void ListMetricDescriptors_RequestObject() { // Snippet: ListMetricDescriptors(ListMetricDescriptorsRequest,CallSettings) // Create client MetricServiceClient metricServiceClient = MetricServiceClient.Create(); // Initialize request argument(s) ListMetricDescriptorsRequest request = new ListMetricDescriptorsRequest { ProjectName = new ProjectName("[PROJECT]"), }; // Make the request PagedEnumerable<ListMetricDescriptorsResponse, MetricDescriptor> response = metricServiceClient.ListMetricDescriptors(request); // Iterate over all response items, lazily performing RPCs as required foreach (MetricDescriptor 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 (ListMetricDescriptorsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (MetricDescriptor item in page) { 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<MetricDescriptor> 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 (MetricDescriptor item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetMetricDescriptorAsync</summary> public async Task GetMetricDescriptorAsync() { // Snippet: GetMetricDescriptorAsync(MetricDescriptorName,CallSettings) // Additional: GetMetricDescriptorAsync(MetricDescriptorName,CancellationToken) // Create client MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync(); // Initialize request argument(s) MetricDescriptorName name = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"); // Make the request MetricDescriptor response = await metricServiceClient.GetMetricDescriptorAsync(name); // End snippet } /// <summary>Snippet for GetMetricDescriptor</summary> public void GetMetricDescriptor() { // Snippet: GetMetricDescriptor(MetricDescriptorName,CallSettings) // Create client MetricServiceClient metricServiceClient = MetricServiceClient.Create(); // Initialize request argument(s) MetricDescriptorName name = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"); // Make the request MetricDescriptor response = metricServiceClient.GetMetricDescriptor(name); // End snippet } /// <summary>Snippet for GetMetricDescriptorAsync</summary> public async Task GetMetricDescriptorAsync_RequestObject() { // Snippet: GetMetricDescriptorAsync(GetMetricDescriptorRequest,CallSettings) // Create client MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync(); // Initialize request argument(s) GetMetricDescriptorRequest request = new GetMetricDescriptorRequest { MetricDescriptorName = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; // Make the request MetricDescriptor response = await metricServiceClient.GetMetricDescriptorAsync(request); // End snippet } /// <summary>Snippet for GetMetricDescriptor</summary> public void GetMetricDescriptor_RequestObject() { // Snippet: GetMetricDescriptor(GetMetricDescriptorRequest,CallSettings) // Create client MetricServiceClient metricServiceClient = MetricServiceClient.Create(); // Initialize request argument(s) GetMetricDescriptorRequest request = new GetMetricDescriptorRequest { MetricDescriptorName = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; // Make the request MetricDescriptor response = metricServiceClient.GetMetricDescriptor(request); // End snippet } /// <summary>Snippet for CreateMetricDescriptorAsync</summary> public async Task CreateMetricDescriptorAsync() { // Snippet: CreateMetricDescriptorAsync(ProjectName,MetricDescriptor,CallSettings) // Additional: CreateMetricDescriptorAsync(ProjectName,MetricDescriptor,CancellationToken) // Create client MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync(); // Initialize request argument(s) ProjectName name = new ProjectName("[PROJECT]"); MetricDescriptor metricDescriptor = new MetricDescriptor(); // Make the request MetricDescriptor response = await metricServiceClient.CreateMetricDescriptorAsync(name, metricDescriptor); // End snippet } /// <summary>Snippet for CreateMetricDescriptor</summary> public void CreateMetricDescriptor() { // Snippet: CreateMetricDescriptor(ProjectName,MetricDescriptor,CallSettings) // Create client MetricServiceClient metricServiceClient = MetricServiceClient.Create(); // Initialize request argument(s) ProjectName name = new ProjectName("[PROJECT]"); MetricDescriptor metricDescriptor = new MetricDescriptor(); // Make the request MetricDescriptor response = metricServiceClient.CreateMetricDescriptor(name, metricDescriptor); // End snippet } /// <summary>Snippet for CreateMetricDescriptorAsync</summary> public async Task CreateMetricDescriptorAsync_RequestObject() { // Snippet: CreateMetricDescriptorAsync(CreateMetricDescriptorRequest,CallSettings) // Create client MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync(); // Initialize request argument(s) CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest { ProjectName = new ProjectName("[PROJECT]"), MetricDescriptor = new MetricDescriptor(), }; // Make the request MetricDescriptor response = await metricServiceClient.CreateMetricDescriptorAsync(request); // End snippet } /// <summary>Snippet for CreateMetricDescriptor</summary> public void CreateMetricDescriptor_RequestObject() { // Snippet: CreateMetricDescriptor(CreateMetricDescriptorRequest,CallSettings) // Create client MetricServiceClient metricServiceClient = MetricServiceClient.Create(); // Initialize request argument(s) CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest { ProjectName = new ProjectName("[PROJECT]"), MetricDescriptor = new MetricDescriptor(), }; // Make the request MetricDescriptor response = metricServiceClient.CreateMetricDescriptor(request); // End snippet } /// <summary>Snippet for DeleteMetricDescriptorAsync</summary> public async Task DeleteMetricDescriptorAsync() { // Snippet: DeleteMetricDescriptorAsync(MetricDescriptorName,CallSettings) // Additional: DeleteMetricDescriptorAsync(MetricDescriptorName,CancellationToken) // Create client MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync(); // Initialize request argument(s) MetricDescriptorName name = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"); // Make the request await metricServiceClient.DeleteMetricDescriptorAsync(name); // End snippet } /// <summary>Snippet for DeleteMetricDescriptor</summary> public void DeleteMetricDescriptor() { // Snippet: DeleteMetricDescriptor(MetricDescriptorName,CallSettings) // Create client MetricServiceClient metricServiceClient = MetricServiceClient.Create(); // Initialize request argument(s) MetricDescriptorName name = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"); // Make the request metricServiceClient.DeleteMetricDescriptor(name); // End snippet } /// <summary>Snippet for DeleteMetricDescriptorAsync</summary> public async Task DeleteMetricDescriptorAsync_RequestObject() { // Snippet: DeleteMetricDescriptorAsync(DeleteMetricDescriptorRequest,CallSettings) // Create client MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync(); // Initialize request argument(s) DeleteMetricDescriptorRequest request = new DeleteMetricDescriptorRequest { MetricDescriptorName = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; // Make the request await metricServiceClient.DeleteMetricDescriptorAsync(request); // End snippet } /// <summary>Snippet for DeleteMetricDescriptor</summary> public void DeleteMetricDescriptor_RequestObject() { // Snippet: DeleteMetricDescriptor(DeleteMetricDescriptorRequest,CallSettings) // Create client MetricServiceClient metricServiceClient = MetricServiceClient.Create(); // Initialize request argument(s) DeleteMetricDescriptorRequest request = new DeleteMetricDescriptorRequest { MetricDescriptorName = new MetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"), }; // Make the request metricServiceClient.DeleteMetricDescriptor(request); // End snippet } /// <summary>Snippet for ListTimeSeriesAsync</summary> public async Task ListTimeSeriesAsync() { // Snippet: ListTimeSeriesAsync(ProjectName,string,TimeInterval,ListTimeSeriesRequest.Types.TimeSeriesView,string,int?,CallSettings) // Create client MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync(); // Initialize request argument(s) ProjectName name = new ProjectName("[PROJECT]"); string filter = ""; TimeInterval interval = new TimeInterval(); ListTimeSeriesRequest.Types.TimeSeriesView view = ListTimeSeriesRequest.Types.TimeSeriesView.Full; // Make the request PagedAsyncEnumerable<ListTimeSeriesResponse, TimeSeries> response = metricServiceClient.ListTimeSeriesAsync(name, filter, interval, view); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((TimeSeries 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((ListTimeSeriesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TimeSeries item in page) { 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<TimeSeries> 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 (TimeSeries item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListTimeSeries</summary> public void ListTimeSeries() { // Snippet: ListTimeSeries(ProjectName,string,TimeInterval,ListTimeSeriesRequest.Types.TimeSeriesView,string,int?,CallSettings) // Create client MetricServiceClient metricServiceClient = MetricServiceClient.Create(); // Initialize request argument(s) ProjectName name = new ProjectName("[PROJECT]"); string filter = ""; TimeInterval interval = new TimeInterval(); ListTimeSeriesRequest.Types.TimeSeriesView view = ListTimeSeriesRequest.Types.TimeSeriesView.Full; // Make the request PagedEnumerable<ListTimeSeriesResponse, TimeSeries> response = metricServiceClient.ListTimeSeries(name, filter, interval, view); // Iterate over all response items, lazily performing RPCs as required foreach (TimeSeries 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 (ListTimeSeriesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TimeSeries item in page) { 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<TimeSeries> 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 (TimeSeries item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListTimeSeriesAsync</summary> public async Task ListTimeSeriesAsync_RequestObject() { // Snippet: ListTimeSeriesAsync(ListTimeSeriesRequest,CallSettings) // Create client MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync(); // Initialize request argument(s) ListTimeSeriesRequest request = new ListTimeSeriesRequest { ProjectName = new ProjectName("[PROJECT]"), Filter = "", Interval = new TimeInterval(), View = ListTimeSeriesRequest.Types.TimeSeriesView.Full, }; // Make the request PagedAsyncEnumerable<ListTimeSeriesResponse, TimeSeries> response = metricServiceClient.ListTimeSeriesAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((TimeSeries 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((ListTimeSeriesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TimeSeries item in page) { 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<TimeSeries> 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 (TimeSeries item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListTimeSeries</summary> public void ListTimeSeries_RequestObject() { // Snippet: ListTimeSeries(ListTimeSeriesRequest,CallSettings) // Create client MetricServiceClient metricServiceClient = MetricServiceClient.Create(); // Initialize request argument(s) ListTimeSeriesRequest request = new ListTimeSeriesRequest { ProjectName = new ProjectName("[PROJECT]"), Filter = "", Interval = new TimeInterval(), View = ListTimeSeriesRequest.Types.TimeSeriesView.Full, }; // Make the request PagedEnumerable<ListTimeSeriesResponse, TimeSeries> response = metricServiceClient.ListTimeSeries(request); // Iterate over all response items, lazily performing RPCs as required foreach (TimeSeries 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 (ListTimeSeriesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TimeSeries item in page) { 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<TimeSeries> 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 (TimeSeries item in singlePage) { Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for CreateTimeSeriesAsync</summary> public async Task CreateTimeSeriesAsync() { // Snippet: CreateTimeSeriesAsync(ProjectName,IEnumerable<TimeSeries>,CallSettings) // Additional: CreateTimeSeriesAsync(ProjectName,IEnumerable<TimeSeries>,CancellationToken) // Create client MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync(); // Initialize request argument(s) ProjectName name = new ProjectName("[PROJECT]"); IEnumerable<TimeSeries> timeSeries = new List<TimeSeries>(); // Make the request await metricServiceClient.CreateTimeSeriesAsync(name, timeSeries); // End snippet } /// <summary>Snippet for CreateTimeSeries</summary> public void CreateTimeSeries() { // Snippet: CreateTimeSeries(ProjectName,IEnumerable<TimeSeries>,CallSettings) // Create client MetricServiceClient metricServiceClient = MetricServiceClient.Create(); // Initialize request argument(s) ProjectName name = new ProjectName("[PROJECT]"); IEnumerable<TimeSeries> timeSeries = new List<TimeSeries>(); // Make the request metricServiceClient.CreateTimeSeries(name, timeSeries); // End snippet } /// <summary>Snippet for CreateTimeSeriesAsync</summary> public async Task CreateTimeSeriesAsync_RequestObject() { // Snippet: CreateTimeSeriesAsync(CreateTimeSeriesRequest,CallSettings) // Create client MetricServiceClient metricServiceClient = await MetricServiceClient.CreateAsync(); // Initialize request argument(s) CreateTimeSeriesRequest request = new CreateTimeSeriesRequest { ProjectName = new ProjectName("[PROJECT]"), TimeSeries = { }, }; // Make the request await metricServiceClient.CreateTimeSeriesAsync(request); // End snippet } /// <summary>Snippet for CreateTimeSeries</summary> public void CreateTimeSeries_RequestObject() { // Snippet: CreateTimeSeries(CreateTimeSeriesRequest,CallSettings) // Create client MetricServiceClient metricServiceClient = MetricServiceClient.Create(); // Initialize request argument(s) CreateTimeSeriesRequest request = new CreateTimeSeriesRequest { ProjectName = new ProjectName("[PROJECT]"), TimeSeries = { }, }; // Make the request metricServiceClient.CreateTimeSeries(request); // End snippet } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.AIPlatform.V1 { /// <summary>Settings for <see cref="FeaturestoreOnlineServingServiceClient"/> instances.</summary> public sealed partial class FeaturestoreOnlineServingServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="FeaturestoreOnlineServingServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="FeaturestoreOnlineServingServiceSettings"/>.</returns> public static FeaturestoreOnlineServingServiceSettings GetDefault() => new FeaturestoreOnlineServingServiceSettings(); /// <summary> /// Constructs a new <see cref="FeaturestoreOnlineServingServiceSettings"/> object with default settings. /// </summary> public FeaturestoreOnlineServingServiceSettings() { } private FeaturestoreOnlineServingServiceSettings(FeaturestoreOnlineServingServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); ReadFeatureValuesSettings = existing.ReadFeatureValuesSettings; StreamingReadFeatureValuesSettings = existing.StreamingReadFeatureValuesSettings; OnCopy(existing); } partial void OnCopy(FeaturestoreOnlineServingServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>FeaturestoreOnlineServingServiceClient.ReadFeatureValues</c> and /// <c>FeaturestoreOnlineServingServiceClient.ReadFeatureValuesAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ReadFeatureValuesSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>FeaturestoreOnlineServingServiceClient.StreamingReadFeatureValues</c> and /// <c>FeaturestoreOnlineServingServiceClient.StreamingReadFeatureValuesAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings StreamingReadFeatureValuesSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="FeaturestoreOnlineServingServiceSettings"/> object.</returns> public FeaturestoreOnlineServingServiceSettings Clone() => new FeaturestoreOnlineServingServiceSettings(this); } /// <summary> /// Builder class for <see cref="FeaturestoreOnlineServingServiceClient"/> to provide simple configuration of /// credentials, endpoint etc. /// </summary> public sealed partial class FeaturestoreOnlineServingServiceClientBuilder : gaxgrpc::ClientBuilderBase<FeaturestoreOnlineServingServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public FeaturestoreOnlineServingServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public FeaturestoreOnlineServingServiceClientBuilder() { UseJwtAccessWithScopes = FeaturestoreOnlineServingServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref FeaturestoreOnlineServingServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<FeaturestoreOnlineServingServiceClient> task); /// <summary>Builds the resulting client.</summary> public override FeaturestoreOnlineServingServiceClient Build() { FeaturestoreOnlineServingServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<FeaturestoreOnlineServingServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<FeaturestoreOnlineServingServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private FeaturestoreOnlineServingServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return FeaturestoreOnlineServingServiceClient.Create(callInvoker, Settings); } private async stt::Task<FeaturestoreOnlineServingServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return FeaturestoreOnlineServingServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => FeaturestoreOnlineServingServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => FeaturestoreOnlineServingServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => FeaturestoreOnlineServingServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>FeaturestoreOnlineServingService client wrapper, for convenient use.</summary> /// <remarks> /// A service for serving online feature values. /// </remarks> public abstract partial class FeaturestoreOnlineServingServiceClient { /// <summary> /// The default endpoint for the FeaturestoreOnlineServingService service, which is a host of /// "aiplatform.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "aiplatform.googleapis.com:443"; /// <summary>The default FeaturestoreOnlineServingService scopes.</summary> /// <remarks> /// The default FeaturestoreOnlineServingService scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="FeaturestoreOnlineServingServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="FeaturestoreOnlineServingServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="FeaturestoreOnlineServingServiceClient"/>.</returns> public static stt::Task<FeaturestoreOnlineServingServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new FeaturestoreOnlineServingServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="FeaturestoreOnlineServingServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="FeaturestoreOnlineServingServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="FeaturestoreOnlineServingServiceClient"/>.</returns> public static FeaturestoreOnlineServingServiceClient Create() => new FeaturestoreOnlineServingServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="FeaturestoreOnlineServingServiceClient"/> which uses the specified call invoker for /// remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="FeaturestoreOnlineServingServiceSettings"/>.</param> /// <returns>The created <see cref="FeaturestoreOnlineServingServiceClient"/>.</returns> internal static FeaturestoreOnlineServingServiceClient Create(grpccore::CallInvoker callInvoker, FeaturestoreOnlineServingServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } FeaturestoreOnlineServingService.FeaturestoreOnlineServingServiceClient grpcClient = new FeaturestoreOnlineServingService.FeaturestoreOnlineServingServiceClient(callInvoker); return new FeaturestoreOnlineServingServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC FeaturestoreOnlineServingService client</summary> public virtual FeaturestoreOnlineServingService.FeaturestoreOnlineServingServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Reads Feature values of a specific entity of an EntityType. For reading /// feature values of multiple entities of an EntityType, please use /// StreamingReadFeatureValues. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual ReadFeatureValuesResponse ReadFeatureValues(ReadFeatureValuesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Reads Feature values of a specific entity of an EntityType. For reading /// feature values of multiple entities of an EntityType, please use /// StreamingReadFeatureValues. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ReadFeatureValuesResponse> ReadFeatureValuesAsync(ReadFeatureValuesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Reads Feature values of a specific entity of an EntityType. For reading /// feature values of multiple entities of an EntityType, please use /// StreamingReadFeatureValues. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ReadFeatureValuesResponse> ReadFeatureValuesAsync(ReadFeatureValuesRequest request, st::CancellationToken cancellationToken) => ReadFeatureValuesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Reads Feature values of a specific entity of an EntityType. For reading /// feature values of multiple entities of an EntityType, please use /// StreamingReadFeatureValues. /// </summary> /// <param name="entityType"> /// Required. The resource name of the EntityType for the entity being read. /// Value format: /// `projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entityType}`. /// For example, for a machine learning model predicting user clicks on a /// website, an EntityType ID could be `user`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual ReadFeatureValuesResponse ReadFeatureValues(string entityType, gaxgrpc::CallSettings callSettings = null) => ReadFeatureValues(new ReadFeatureValuesRequest { EntityType = gax::GaxPreconditions.CheckNotNullOrEmpty(entityType, nameof(entityType)), }, callSettings); /// <summary> /// Reads Feature values of a specific entity of an EntityType. For reading /// feature values of multiple entities of an EntityType, please use /// StreamingReadFeatureValues. /// </summary> /// <param name="entityType"> /// Required. The resource name of the EntityType for the entity being read. /// Value format: /// `projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entityType}`. /// For example, for a machine learning model predicting user clicks on a /// website, an EntityType ID could be `user`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ReadFeatureValuesResponse> ReadFeatureValuesAsync(string entityType, gaxgrpc::CallSettings callSettings = null) => ReadFeatureValuesAsync(new ReadFeatureValuesRequest { EntityType = gax::GaxPreconditions.CheckNotNullOrEmpty(entityType, nameof(entityType)), }, callSettings); /// <summary> /// Reads Feature values of a specific entity of an EntityType. For reading /// feature values of multiple entities of an EntityType, please use /// StreamingReadFeatureValues. /// </summary> /// <param name="entityType"> /// Required. The resource name of the EntityType for the entity being read. /// Value format: /// `projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entityType}`. /// For example, for a machine learning model predicting user clicks on a /// website, an EntityType ID could be `user`. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ReadFeatureValuesResponse> ReadFeatureValuesAsync(string entityType, st::CancellationToken cancellationToken) => ReadFeatureValuesAsync(entityType, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Reads Feature values of a specific entity of an EntityType. For reading /// feature values of multiple entities of an EntityType, please use /// StreamingReadFeatureValues. /// </summary> /// <param name="entityType"> /// Required. The resource name of the EntityType for the entity being read. /// Value format: /// `projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entityType}`. /// For example, for a machine learning model predicting user clicks on a /// website, an EntityType ID could be `user`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual ReadFeatureValuesResponse ReadFeatureValues(EntityTypeName entityType, gaxgrpc::CallSettings callSettings = null) => ReadFeatureValues(new ReadFeatureValuesRequest { EntityTypeAsEntityTypeName = gax::GaxPreconditions.CheckNotNull(entityType, nameof(entityType)), }, callSettings); /// <summary> /// Reads Feature values of a specific entity of an EntityType. For reading /// feature values of multiple entities of an EntityType, please use /// StreamingReadFeatureValues. /// </summary> /// <param name="entityType"> /// Required. The resource name of the EntityType for the entity being read. /// Value format: /// `projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entityType}`. /// For example, for a machine learning model predicting user clicks on a /// website, an EntityType ID could be `user`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ReadFeatureValuesResponse> ReadFeatureValuesAsync(EntityTypeName entityType, gaxgrpc::CallSettings callSettings = null) => ReadFeatureValuesAsync(new ReadFeatureValuesRequest { EntityTypeAsEntityTypeName = gax::GaxPreconditions.CheckNotNull(entityType, nameof(entityType)), }, callSettings); /// <summary> /// Reads Feature values of a specific entity of an EntityType. For reading /// feature values of multiple entities of an EntityType, please use /// StreamingReadFeatureValues. /// </summary> /// <param name="entityType"> /// Required. The resource name of the EntityType for the entity being read. /// Value format: /// `projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entityType}`. /// For example, for a machine learning model predicting user clicks on a /// website, an EntityType ID could be `user`. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ReadFeatureValuesResponse> ReadFeatureValuesAsync(EntityTypeName entityType, st::CancellationToken cancellationToken) => ReadFeatureValuesAsync(entityType, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Server streaming methods for /// <see cref="StreamingReadFeatureValues(StreamingReadFeatureValuesRequest,gaxgrpc::CallSettings)"/>. /// </summary> public abstract partial class StreamingReadFeatureValuesStream : gaxgrpc::ServerStreamingBase<ReadFeatureValuesResponse> { } /// <summary> /// Reads Feature values for multiple entities. Depending on their size, data /// for different entities may be broken /// up across multiple responses. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The server stream.</returns> public virtual StreamingReadFeatureValuesStream StreamingReadFeatureValues(StreamingReadFeatureValuesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Reads Feature values for multiple entities. Depending on their size, data /// for different entities may be broken /// up across multiple responses. /// </summary> /// <param name="entityType"> /// Required. The resource name of the entities' type. /// Value format: /// `projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entityType}`. /// For example, /// for a machine learning model predicting user clicks on a website, an /// EntityType ID could be `user`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The server stream.</returns> public virtual StreamingReadFeatureValuesStream StreamingReadFeatureValues(string entityType, gaxgrpc::CallSettings callSettings = null) => StreamingReadFeatureValues(new StreamingReadFeatureValuesRequest { EntityType = gax::GaxPreconditions.CheckNotNullOrEmpty(entityType, nameof(entityType)), }, callSettings); /// <summary> /// Reads Feature values for multiple entities. Depending on their size, data /// for different entities may be broken /// up across multiple responses. /// </summary> /// <param name="entityType"> /// Required. The resource name of the entities' type. /// Value format: /// `projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entityType}`. /// For example, /// for a machine learning model predicting user clicks on a website, an /// EntityType ID could be `user`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The server stream.</returns> public virtual StreamingReadFeatureValuesStream StreamingReadFeatureValues(EntityTypeName entityType, gaxgrpc::CallSettings callSettings = null) => StreamingReadFeatureValues(new StreamingReadFeatureValuesRequest { EntityTypeAsEntityTypeName = gax::GaxPreconditions.CheckNotNull(entityType, nameof(entityType)), }, callSettings); } /// <summary>FeaturestoreOnlineServingService client wrapper implementation, for convenient use.</summary> /// <remarks> /// A service for serving online feature values. /// </remarks> public sealed partial class FeaturestoreOnlineServingServiceClientImpl : FeaturestoreOnlineServingServiceClient { private readonly gaxgrpc::ApiCall<ReadFeatureValuesRequest, ReadFeatureValuesResponse> _callReadFeatureValues; private readonly gaxgrpc::ApiServerStreamingCall<StreamingReadFeatureValuesRequest, ReadFeatureValuesResponse> _callStreamingReadFeatureValues; /// <summary> /// Constructs a client wrapper for the FeaturestoreOnlineServingService service, with the specified gRPC client /// and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="FeaturestoreOnlineServingServiceSettings"/> used within this client. /// </param> public FeaturestoreOnlineServingServiceClientImpl(FeaturestoreOnlineServingService.FeaturestoreOnlineServingServiceClient grpcClient, FeaturestoreOnlineServingServiceSettings settings) { GrpcClient = grpcClient; FeaturestoreOnlineServingServiceSettings effectiveSettings = settings ?? FeaturestoreOnlineServingServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callReadFeatureValues = clientHelper.BuildApiCall<ReadFeatureValuesRequest, ReadFeatureValuesResponse>(grpcClient.ReadFeatureValuesAsync, grpcClient.ReadFeatureValues, effectiveSettings.ReadFeatureValuesSettings).WithGoogleRequestParam("entity_type", request => request.EntityType); Modify_ApiCall(ref _callReadFeatureValues); Modify_ReadFeatureValuesApiCall(ref _callReadFeatureValues); _callStreamingReadFeatureValues = clientHelper.BuildApiCall<StreamingReadFeatureValuesRequest, ReadFeatureValuesResponse>(grpcClient.StreamingReadFeatureValues, effectiveSettings.StreamingReadFeatureValuesSettings).WithGoogleRequestParam("entity_type", request => request.EntityType); Modify_ApiCall(ref _callStreamingReadFeatureValues); Modify_StreamingReadFeatureValuesApiCall(ref _callStreamingReadFeatureValues); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiServerStreamingCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_ReadFeatureValuesApiCall(ref gaxgrpc::ApiCall<ReadFeatureValuesRequest, ReadFeatureValuesResponse> call); partial void Modify_StreamingReadFeatureValuesApiCall(ref gaxgrpc::ApiServerStreamingCall<StreamingReadFeatureValuesRequest, ReadFeatureValuesResponse> call); partial void OnConstruction(FeaturestoreOnlineServingService.FeaturestoreOnlineServingServiceClient grpcClient, FeaturestoreOnlineServingServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC FeaturestoreOnlineServingService client</summary> public override FeaturestoreOnlineServingService.FeaturestoreOnlineServingServiceClient GrpcClient { get; } partial void Modify_ReadFeatureValuesRequest(ref ReadFeatureValuesRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_StreamingReadFeatureValuesRequest(ref StreamingReadFeatureValuesRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Reads Feature values of a specific entity of an EntityType. For reading /// feature values of multiple entities of an EntityType, please use /// StreamingReadFeatureValues. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override ReadFeatureValuesResponse ReadFeatureValues(ReadFeatureValuesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ReadFeatureValuesRequest(ref request, ref callSettings); return _callReadFeatureValues.Sync(request, callSettings); } /// <summary> /// Reads Feature values of a specific entity of an EntityType. For reading /// feature values of multiple entities of an EntityType, please use /// StreamingReadFeatureValues. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<ReadFeatureValuesResponse> ReadFeatureValuesAsync(ReadFeatureValuesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ReadFeatureValuesRequest(ref request, ref callSettings); return _callReadFeatureValues.Async(request, callSettings); } internal sealed partial class StreamingReadFeatureValuesStreamImpl : StreamingReadFeatureValuesStream { /// <summary>Construct the server streaming method for <c>StreamingReadFeatureValues</c>.</summary> /// <param name="call">The underlying gRPC server streaming call.</param> public StreamingReadFeatureValuesStreamImpl(grpccore::AsyncServerStreamingCall<ReadFeatureValuesResponse> call) => GrpcCall = call; public override grpccore::AsyncServerStreamingCall<ReadFeatureValuesResponse> GrpcCall { get; } } /// <summary> /// Reads Feature values for multiple entities. Depending on their size, data /// for different entities may be broken /// up across multiple responses. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The server stream.</returns> public override FeaturestoreOnlineServingServiceClient.StreamingReadFeatureValuesStream StreamingReadFeatureValues(StreamingReadFeatureValuesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_StreamingReadFeatureValuesRequest(ref request, ref callSettings); return new StreamingReadFeatureValuesStreamImpl(_callStreamingReadFeatureValues.Call(request, callSettings)); } } }
//--------------------------------------------------------------------------- // // <copyright file="NotifyCollectionChangedEventArgs.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: NotifyCollectionChanged event arguments // // Specs: http://avalon/connecteddata/Specs/INotifyCollectionChanged.mht // //--------------------------------------------------------------------------- using System; using System.Collections; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; namespace System.Collections.Specialized { /// <summary> /// This enum describes the action that caused a CollectionChanged event. /// </summary> //[TypeForwardedFrom("WindowsBase, Version=3.0.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35")] public enum NotifyCollectionChangedAction { /// <summary> One or more items were added to the collection. </summary> Add, /// <summary> One or more items were removed from the collection. </summary> Remove, /// <summary> One or more items were replaced in the collection. </summary> Replace, /// <summary> One or more items were moved within the collection. </summary> Move, /// <summary> The contents of the collection changed dramatically. </summary> Reset, } /// <summary> /// Arguments for the CollectionChanged event. /// A collection that supports INotifyCollectionChangedThis raises this event /// whenever an item is added or removed, or when the contents of the collection /// changes dramatically. /// </summary> //[TypeForwardedFrom("WindowsBase, Version=3.0.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35")] public class NotifyCollectionChangedEventArgs : EventArgs { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a reset change. /// </summary> /// <param name="action">The action that caused the event (must be Reset).</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action) { if (action != NotifyCollectionChangedAction.Reset) throw new ArgumentException(SR.GetString(SR.WrongActionForCtor, NotifyCollectionChangedAction.Reset), "action"); InitializeAdd(action, null, -1); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item change. /// </summary> /// <param name="action">The action that caused the event; can only be Reset, Add or Remove action.</param> /// <param name="changedItem">The item affected by the change.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object changedItem) { if ((action != NotifyCollectionChangedAction.Add) && (action != NotifyCollectionChangedAction.Remove) && (action != NotifyCollectionChangedAction.Reset)) throw new ArgumentException(SR.GetString(SR.MustBeResetAddOrRemoveActionForCtor), "action"); if (action == NotifyCollectionChangedAction.Reset) { if (changedItem != null) throw new ArgumentException(SR.GetString(SR.ResetActionRequiresNullItem), "action"); InitializeAdd(action, null, -1); } else { InitializeAddOrRemove(action, new object[]{changedItem}, -1); } } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item change. /// </summary> /// <param name="action">The action that caused the event.</param> /// <param name="changedItem">The item affected by the change.</param> /// <param name="index">The index where the change occurred.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object changedItem, int index) { if ((action != NotifyCollectionChangedAction.Add) && (action != NotifyCollectionChangedAction.Remove) && (action != NotifyCollectionChangedAction.Reset)) throw new ArgumentException(SR.GetString(SR.MustBeResetAddOrRemoveActionForCtor), "action"); if (action == NotifyCollectionChangedAction.Reset) { if (changedItem != null) throw new ArgumentException(SR.GetString(SR.ResetActionRequiresNullItem), "action"); if (index != -1) throw new ArgumentException(SR.GetString(SR.ResetActionRequiresIndexMinus1), "action"); InitializeAdd(action, null, -1); } else { InitializeAddOrRemove(action, new object[]{changedItem}, index); } } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item change. /// </summary> /// <param name="action">The action that caused the event.</param> /// <param name="changedItems">The items affected by the change.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList changedItems) { if ((action != NotifyCollectionChangedAction.Add) && (action != NotifyCollectionChangedAction.Remove) && (action != NotifyCollectionChangedAction.Reset)) throw new ArgumentException(SR.GetString(SR.MustBeResetAddOrRemoveActionForCtor), "action"); if (action == NotifyCollectionChangedAction.Reset) { if (changedItems != null) throw new ArgumentException(SR.GetString(SR.ResetActionRequiresNullItem), "action"); InitializeAdd(action, null, -1); } else { if (changedItems == null) throw new ArgumentNullException("changedItems"); InitializeAddOrRemove(action, changedItems, -1); } } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item change (or a reset). /// </summary> /// <param name="action">The action that caused the event.</param> /// <param name="changedItems">The items affected by the change.</param> /// <param name="startingIndex">The index where the change occurred.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList changedItems, int startingIndex) { if ((action != NotifyCollectionChangedAction.Add) && (action != NotifyCollectionChangedAction.Remove) && (action != NotifyCollectionChangedAction.Reset)) throw new ArgumentException(SR.GetString(SR.MustBeResetAddOrRemoveActionForCtor), "action"); if (action == NotifyCollectionChangedAction.Reset) { if (changedItems != null) throw new ArgumentException(SR.GetString(SR.ResetActionRequiresNullItem), "action"); if (startingIndex != -1) throw new ArgumentException(SR.GetString(SR.ResetActionRequiresIndexMinus1), "action"); InitializeAdd(action, null, -1); } else { if (changedItems == null) throw new ArgumentNullException("changedItems"); if (startingIndex < -1) throw new ArgumentException(SR.GetString(SR.IndexCannotBeNegative), "startingIndex"); InitializeAddOrRemove(action, changedItems, startingIndex); } } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item Replace event. /// </summary> /// <param name="action">Can only be a Replace action.</param> /// <param name="newItem">The new item replacing the original item.</param> /// <param name="oldItem">The original item that is replaced.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object newItem, object oldItem) { if (action != NotifyCollectionChangedAction.Replace) throw new ArgumentException(SR.GetString(SR.WrongActionForCtor, NotifyCollectionChangedAction.Replace), "action"); InitializeMoveOrReplace(action, new object[]{newItem}, new object[]{oldItem}, -1, -1); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item Replace event. /// </summary> /// <param name="action">Can only be a Replace action.</param> /// <param name="newItem">The new item replacing the original item.</param> /// <param name="oldItem">The original item that is replaced.</param> /// <param name="index">The index of the item being replaced.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object newItem, object oldItem, int index) { if (action != NotifyCollectionChangedAction.Replace) throw new ArgumentException(SR.GetString(SR.WrongActionForCtor, NotifyCollectionChangedAction.Replace), "action"); int oldStartingIndex = index; #if FEATURE_LEGACYNETCF if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { // Dev11 444113 quirk: // This is a "Replace" so the old and new index should both be set to the index passed in however // NetCF on Mango incorrectly leaves OldStartingIndex at -1 and Mango apps depend on this behavior. oldStartingIndex = -1; } #endif InitializeMoveOrReplace(action, new object[]{newItem}, new object[]{oldItem}, index, oldStartingIndex); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item Replace event. /// </summary> /// <param name="action">Can only be a Replace action.</param> /// <param name="newItems">The new items replacing the original items.</param> /// <param name="oldItems">The original items that are replaced.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList newItems, IList oldItems) { if (action != NotifyCollectionChangedAction.Replace) throw new ArgumentException(SR.GetString(SR.WrongActionForCtor, NotifyCollectionChangedAction.Replace), "action"); if (newItems == null) throw new ArgumentNullException("newItems"); if (oldItems == null) throw new ArgumentNullException("oldItems"); InitializeMoveOrReplace(action, newItems, oldItems, -1, -1); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item Replace event. /// </summary> /// <param name="action">Can only be a Replace action.</param> /// <param name="newItems">The new items replacing the original items.</param> /// <param name="oldItems">The original items that are replaced.</param> /// <param name="startingIndex">The starting index of the items being replaced.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList newItems, IList oldItems, int startingIndex) { if (action != NotifyCollectionChangedAction.Replace) throw new ArgumentException(SR.GetString(SR.WrongActionForCtor, NotifyCollectionChangedAction.Replace), "action"); if (newItems == null) throw new ArgumentNullException("newItems"); if (oldItems == null) throw new ArgumentNullException("oldItems"); InitializeMoveOrReplace(action, newItems, oldItems, startingIndex, startingIndex); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item Move event. /// </summary> /// <param name="action">Can only be a Move action.</param> /// <param name="changedItem">The item affected by the change.</param> /// <param name="index">The new index for the changed item.</param> /// <param name="oldIndex">The old index for the changed item.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object changedItem, int index, int oldIndex) { if (action != NotifyCollectionChangedAction.Move) throw new ArgumentException(SR.GetString(SR.WrongActionForCtor, NotifyCollectionChangedAction.Move), "action"); if (index < 0) throw new ArgumentException(SR.GetString(SR.IndexCannotBeNegative), "index"); object[] changedItems= new object[] {changedItem}; InitializeMoveOrReplace(action, changedItems, changedItems, index, oldIndex); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item Move event. /// </summary> /// <param name="action">The action that caused the event.</param> /// <param name="changedItems">The items affected by the change.</param> /// <param name="index">The new index for the changed items.</param> /// <param name="oldIndex">The old index for the changed items.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList changedItems, int index, int oldIndex) { if (action != NotifyCollectionChangedAction.Move) throw new ArgumentException(SR.GetString(SR.WrongActionForCtor, NotifyCollectionChangedAction.Move), "action"); if (index < 0) throw new ArgumentException(SR.GetString(SR.IndexCannotBeNegative), "index"); InitializeMoveOrReplace(action, changedItems, changedItems, index, oldIndex); } /// <summary> /// Construct a NotifyCollectionChangedEventArgs with given fields (no validation). Used by WinRT marshaling. /// </summary> internal NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList newItems, IList oldItems, int newIndex, int oldIndex) { _action = action; #if FEATURE_LEGACYNETCF if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { _newItems = newItems; } else #endif { _newItems = (newItems == null) ? null : ArrayList.ReadOnly(newItems); } _oldItems = (oldItems == null) ? null : ArrayList.ReadOnly(oldItems); _newStartingIndex = newIndex; _oldStartingIndex = oldIndex; } private void InitializeAddOrRemove(NotifyCollectionChangedAction action, IList changedItems, int startingIndex) { if (action == NotifyCollectionChangedAction.Add) InitializeAdd(action, changedItems, startingIndex); else if (action == NotifyCollectionChangedAction.Remove) InitializeRemove(action, changedItems, startingIndex); else Contract.Assert(false, String.Format("Unsupported action: {0}", action.ToString())); } private void InitializeAdd(NotifyCollectionChangedAction action, IList newItems, int newStartingIndex) { _action = action; #if FEATURE_LEGACYNETCF if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8) { _newItems = newItems; } else #endif // !FEATURE_LEGACYNETCF { _newItems = (newItems == null) ? null : ArrayList.ReadOnly(newItems); } _newStartingIndex = newStartingIndex; } private void InitializeRemove(NotifyCollectionChangedAction action, IList oldItems, int oldStartingIndex) { _action = action; _oldItems = (oldItems == null) ? null : ArrayList.ReadOnly(oldItems); _oldStartingIndex= oldStartingIndex; } private void InitializeMoveOrReplace(NotifyCollectionChangedAction action, IList newItems, IList oldItems, int startingIndex, int oldStartingIndex) { InitializeAdd(action, newItems, startingIndex); InitializeRemove(action, oldItems, oldStartingIndex); } //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ /// <summary> /// The action that caused the event. /// </summary> public NotifyCollectionChangedAction Action { get { return _action; } } /// <summary> /// The items affected by the change. /// </summary> public IList NewItems { get { return _newItems; } } /// <summary> /// The old items affected by the change (for Replace events). /// </summary> public IList OldItems { get { return _oldItems; } } /// <summary> /// The index where the change occurred. /// </summary> public int NewStartingIndex { get { return _newStartingIndex; } } /// <summary> /// The old index where the change occurred (for Move events). /// </summary> public int OldStartingIndex { get { return _oldStartingIndex; } } //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ private NotifyCollectionChangedAction _action; private IList _newItems, _oldItems; private int _newStartingIndex = -1; private int _oldStartingIndex = -1; } /// <summary> /// The delegate to use for handlers that receive the CollectionChanged event. /// </summary> //[TypeForwardedFrom("WindowsBase, Version=3.0.0.0, Culture=Neutral, PublicKeyToken=31bf3856ad364e35")] public delegate void NotifyCollectionChangedEventHandler(object sender, NotifyCollectionChangedEventArgs e); }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace WebApiDocumentation.HelpPage.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Internal.Cryptography; using Internal.Cryptography.Pal; using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Globalization; using System.Runtime.Serialization; using System.Text; namespace System.Security.Cryptography.X509Certificates { [Serializable] public class X509Certificate : IDisposable, IDeserializationCallback, ISerializable { private volatile byte[] _lazyCertHash; private volatile string _lazyIssuer; private volatile string _lazySubject; private volatile byte[] _lazySerialNumber; private volatile string _lazyKeyAlgorithm; private volatile byte[] _lazyKeyAlgorithmParameters; private volatile byte[] _lazyPublicKey; private DateTime _lazyNotBefore = DateTime.MinValue; private DateTime _lazyNotAfter = DateTime.MinValue; public virtual void Reset() { _lazyCertHash = null; _lazyIssuer = null; _lazySubject = null; _lazySerialNumber = null; _lazyKeyAlgorithm = null; _lazyKeyAlgorithmParameters = null; _lazyPublicKey = null; _lazyNotBefore = DateTime.MinValue; _lazyNotAfter = DateTime.MinValue; ICertificatePal pal = Pal; Pal = null; if (pal != null) pal.Dispose(); } public X509Certificate() { } public X509Certificate(byte[] data) { if (data != null && data.Length != 0) { // For compat reasons, this constructor treats passing a null or empty data set as the same as calling the nullary constructor. using (var safePasswordHandle = new SafePasswordHandle((string)null)) { Pal = CertificatePal.FromBlob(data, safePasswordHandle, X509KeyStorageFlags.DefaultKeySet); } } } public X509Certificate(byte[] rawData, string password) : this(rawData, password, X509KeyStorageFlags.DefaultKeySet) { } [System.CLSCompliantAttribute(false)] public X509Certificate(byte[] rawData, SecureString password) : this(rawData, password, X509KeyStorageFlags.DefaultKeySet) { } public X509Certificate(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) { if (rawData == null || rawData.Length == 0) throw new ArgumentException(SR.Arg_EmptyOrNullArray, nameof(rawData)); ValidateKeyStorageFlags(keyStorageFlags); using (var safePasswordHandle = new SafePasswordHandle(password)) { Pal = CertificatePal.FromBlob(rawData, safePasswordHandle, keyStorageFlags); } } [System.CLSCompliantAttribute(false)] public X509Certificate(byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags) { if (rawData == null || rawData.Length == 0) throw new ArgumentException(SR.Arg_EmptyOrNullArray, nameof(rawData)); ValidateKeyStorageFlags(keyStorageFlags); using (var safePasswordHandle = new SafePasswordHandle(password)) { Pal = CertificatePal.FromBlob(rawData, safePasswordHandle, keyStorageFlags); } } public X509Certificate(IntPtr handle) { Pal = CertificatePal.FromHandle(handle); } internal X509Certificate(ICertificatePal pal) { Debug.Assert(pal != null); Pal = pal; } public X509Certificate(string fileName) : this(fileName, (string)null, X509KeyStorageFlags.DefaultKeySet) { } public X509Certificate(string fileName, string password) : this(fileName, password, X509KeyStorageFlags.DefaultKeySet) { } [System.CLSCompliantAttribute(false)] public X509Certificate(string fileName, SecureString password) : this(fileName, password, X509KeyStorageFlags.DefaultKeySet) { } public X509Certificate(string fileName, string password, X509KeyStorageFlags keyStorageFlags) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); ValidateKeyStorageFlags(keyStorageFlags); using (var safePasswordHandle = new SafePasswordHandle(password)) { Pal = CertificatePal.FromFile(fileName, safePasswordHandle, keyStorageFlags); } } [System.CLSCompliantAttribute(false)] public X509Certificate(string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags) : this() { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); ValidateKeyStorageFlags(keyStorageFlags); using (var safePasswordHandle = new SafePasswordHandle(password)) { Pal = CertificatePal.FromFile(fileName, safePasswordHandle, keyStorageFlags); } } public X509Certificate(X509Certificate cert) { if (cert == null) throw new ArgumentNullException(nameof(cert)); if (cert.Pal != null) { Pal = CertificatePal.FromOtherCert(cert); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2229", Justification = "Public API has already shipped.")] public X509Certificate(SerializationInfo info, StreamingContext context) : this() { byte[] rawData = (byte[])info.GetValue("RawData", typeof(byte[])); if (rawData != null) { using (var safePasswordHandle = new SafePasswordHandle((string)null)) { Pal = CertificatePal.FromBlob(rawData, safePasswordHandle, X509KeyStorageFlags.DefaultKeySet); } } } public static X509Certificate CreateFromCertFile(string filename) { return new X509Certificate(filename); } public static X509Certificate CreateFromSignedFile(string filename) { return new X509Certificate(filename); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("RawData", Pal?.RawData); } void IDeserializationCallback.OnDeserialization(object sender) { } public IntPtr Handle { get { if (Pal == null) return IntPtr.Zero; else return Pal.Handle; } } public string Issuer { get { ThrowIfInvalid(); string issuer = _lazyIssuer; if (issuer == null) issuer = _lazyIssuer = Pal.Issuer; return issuer; } } public string Subject { get { ThrowIfInvalid(); string subject = _lazySubject; if (subject == null) subject = _lazySubject = Pal.Subject; return subject; } } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { Reset(); } } public override bool Equals(object obj) { X509Certificate other = obj as X509Certificate; if (other == null) return false; return Equals(other); } public virtual bool Equals(X509Certificate other) { if (other == null) return false; if (Pal == null) return other.Pal == null; if (!Issuer.Equals(other.Issuer)) return false; byte[] thisSerialNumber = GetRawSerialNumber(); byte[] otherSerialNumber = other.GetRawSerialNumber(); if (thisSerialNumber.Length != otherSerialNumber.Length) return false; for (int i = 0; i < thisSerialNumber.Length; i++) { if (thisSerialNumber[i] != otherSerialNumber[i]) return false; } return true; } public virtual byte[] Export(X509ContentType contentType) { return Export(contentType, (string)null); } public virtual byte[] Export(X509ContentType contentType, string password) { VerifyContentType(contentType); if (Pal == null) throw new CryptographicException(ErrorCode.E_POINTER); // Not the greatest error, but needed for backward compat. using (var safePasswordHandle = new SafePasswordHandle(password)) using (IExportPal storePal = StorePal.FromCertificate(Pal)) { return storePal.Export(contentType, safePasswordHandle); } } [System.CLSCompliantAttribute(false)] public virtual byte[] Export(X509ContentType contentType, SecureString password) { VerifyContentType(contentType); if (Pal == null) throw new CryptographicException(ErrorCode.E_POINTER); // Not the greatest error, but needed for backward compat. using (var safePasswordHandle = new SafePasswordHandle(password)) using (IExportPal storePal = StorePal.FromCertificate(Pal)) { return storePal.Export(contentType, safePasswordHandle); } } public virtual string GetRawCertDataString() { ThrowIfInvalid(); return GetRawCertData().ToHexStringUpper(); } public virtual byte[] GetCertHash() { ThrowIfInvalid(); return GetRawCertHash().CloneByteArray(); } public virtual string GetCertHashString() { ThrowIfInvalid(); return GetRawCertHash().ToHexStringUpper(); } // Only use for internal purposes when the returned byte[] will not be mutated private byte[] GetRawCertHash() { return _lazyCertHash ?? (_lazyCertHash = Pal.Thumbprint); } public virtual string GetEffectiveDateString() { return GetNotBefore().ToString(); } public virtual string GetExpirationDateString() { return GetNotAfter().ToString(); } public virtual string GetFormat() { return "X509"; } public virtual string GetPublicKeyString() { return GetPublicKey().ToHexStringUpper(); } public virtual byte[] GetRawCertData() { ThrowIfInvalid(); return Pal.RawData.CloneByteArray(); } public override int GetHashCode() { if (Pal == null) return 0; byte[] thumbPrint = GetRawCertHash(); int value = 0; for (int i = 0; i < thumbPrint.Length && i < 4; ++i) { value = value << 8 | thumbPrint[i]; } return value; } public virtual string GetKeyAlgorithm() { ThrowIfInvalid(); string keyAlgorithm = _lazyKeyAlgorithm; if (keyAlgorithm == null) keyAlgorithm = _lazyKeyAlgorithm = Pal.KeyAlgorithm; return keyAlgorithm; } public virtual byte[] GetKeyAlgorithmParameters() { ThrowIfInvalid(); byte[] keyAlgorithmParameters = _lazyKeyAlgorithmParameters; if (keyAlgorithmParameters == null) keyAlgorithmParameters = _lazyKeyAlgorithmParameters = Pal.KeyAlgorithmParameters; return keyAlgorithmParameters.CloneByteArray(); } public virtual string GetKeyAlgorithmParametersString() { ThrowIfInvalid(); byte[] keyAlgorithmParameters = GetKeyAlgorithmParameters(); return keyAlgorithmParameters.ToHexStringUpper(); } public virtual byte[] GetPublicKey() { ThrowIfInvalid(); byte[] publicKey = _lazyPublicKey; if (publicKey == null) publicKey = _lazyPublicKey = Pal.PublicKeyValue; return publicKey.CloneByteArray(); } public virtual byte[] GetSerialNumber() { ThrowIfInvalid(); return GetRawSerialNumber().CloneByteArray(); } public virtual string GetSerialNumberString() { ThrowIfInvalid(); return GetRawSerialNumber().ToHexStringUpper(); } // Only use for internal purposes when the returned byte[] will not be mutated private byte[] GetRawSerialNumber() { return _lazySerialNumber ?? (_lazySerialNumber = Pal.SerialNumber); } [Obsolete("This method has been deprecated. Please use the Subject property instead. http://go.microsoft.com/fwlink/?linkid=14202")] public virtual string GetName() { return Subject; } [Obsolete("This method has been deprecated. Please use the Issuer property instead. http://go.microsoft.com/fwlink/?linkid=14202")] public virtual string GetIssuerName() { return Issuer; } public override string ToString() { return ToString(fVerbose: false); } public virtual string ToString(bool fVerbose) { if (fVerbose == false || Pal == null) return GetType().ToString(); StringBuilder sb = new StringBuilder(); // Subject sb.AppendLine("[Subject]"); sb.Append(" "); sb.AppendLine(Subject); // Issuer sb.AppendLine(); sb.AppendLine("[Issuer]"); sb.Append(" "); sb.AppendLine(Issuer); // Serial Number sb.AppendLine(); sb.AppendLine("[Serial Number]"); sb.Append(" "); byte[] serialNumber = GetSerialNumber(); Array.Reverse(serialNumber); sb.Append(serialNumber.ToHexArrayUpper()); sb.AppendLine(); // NotBefore sb.AppendLine(); sb.AppendLine("[Not Before]"); sb.Append(" "); sb.AppendLine(FormatDate(GetNotBefore())); // NotAfter sb.AppendLine(); sb.AppendLine("[Not After]"); sb.Append(" "); sb.AppendLine(FormatDate(GetNotAfter())); // Thumbprint sb.AppendLine(); sb.AppendLine("[Thumbprint]"); sb.Append(" "); sb.Append(GetRawCertHash().ToHexArrayUpper()); sb.AppendLine(); return sb.ToString(); } public virtual void Import(byte[] rawData) { throw new PlatformNotSupportedException(SR.NotSupported_ImmutableX509Certificate); } public virtual void Import(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags) { throw new PlatformNotSupportedException(SR.NotSupported_ImmutableX509Certificate); } [System.CLSCompliantAttribute(false)] public virtual void Import(byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags) { throw new PlatformNotSupportedException(SR.NotSupported_ImmutableX509Certificate); } public virtual void Import(string fileName) { throw new PlatformNotSupportedException(SR.NotSupported_ImmutableX509Certificate); } public virtual void Import(string fileName, string password, X509KeyStorageFlags keyStorageFlags) { throw new PlatformNotSupportedException(SR.NotSupported_ImmutableX509Certificate); } [System.CLSCompliantAttribute(false)] public virtual void Import(string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags) { throw new PlatformNotSupportedException(SR.NotSupported_ImmutableX509Certificate); } internal ICertificatePal Pal { get; private set; } internal DateTime GetNotAfter() { ThrowIfInvalid(); DateTime notAfter = _lazyNotAfter; if (notAfter == DateTime.MinValue) notAfter = _lazyNotAfter = Pal.NotAfter; return notAfter; } internal DateTime GetNotBefore() { ThrowIfInvalid(); DateTime notBefore = _lazyNotBefore; if (notBefore == DateTime.MinValue) notBefore = _lazyNotBefore = Pal.NotBefore; return notBefore; } internal void ThrowIfInvalid() { if (Pal == null) throw new CryptographicException(SR.Format(SR.Cryptography_InvalidHandle, "m_safeCertContext")); // Keeping "m_safeCertContext" string for backward compat sake. } /// <summary> /// Convert a date to a string. /// /// Some cultures, specifically using the Um-AlQura calendar cannot convert dates far into /// the future into strings. If the expiration date of an X.509 certificate is beyond the range /// of one of these cases, we need to fall back to a calendar which can express the dates /// </summary> protected static string FormatDate(DateTime date) { CultureInfo culture = CultureInfo.CurrentCulture; if (!culture.DateTimeFormat.Calendar.IsValidDay(date.Year, date.Month, date.Day, 0)) { // The most common case of culture failing to work is in the Um-AlQuara calendar. In this case, // we can fall back to the Hijri calendar, otherwise fall back to the invariant culture. if (culture.DateTimeFormat.Calendar is UmAlQuraCalendar) { culture = culture.Clone() as CultureInfo; culture.DateTimeFormat.Calendar = new HijriCalendar(); } else { culture = CultureInfo.InvariantCulture; } } return date.ToString(culture); } internal static void ValidateKeyStorageFlags(X509KeyStorageFlags keyStorageFlags) { if ((keyStorageFlags & ~KeyStorageFlagsAll) != 0) throw new ArgumentException(SR.Argument_InvalidFlag, nameof(keyStorageFlags)); const X509KeyStorageFlags EphemeralPersist = X509KeyStorageFlags.EphemeralKeySet | X509KeyStorageFlags.PersistKeySet; X509KeyStorageFlags persistenceFlags = keyStorageFlags & EphemeralPersist; if (persistenceFlags == EphemeralPersist) { throw new ArgumentException( SR.Format(SR.Cryptography_X509_InvalidFlagCombination, persistenceFlags), nameof(keyStorageFlags)); } } private void VerifyContentType(X509ContentType contentType) { if (!(contentType == X509ContentType.Cert || contentType == X509ContentType.SerializedCert || contentType == X509ContentType.Pkcs12)) throw new CryptographicException(SR.Cryptography_X509_InvalidContentType); } internal const X509KeyStorageFlags KeyStorageFlagsAll = X509KeyStorageFlags.UserKeySet | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable | X509KeyStorageFlags.UserProtected | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.EphemeralKeySet; } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Web.UI.WebControls.WebParts.DeclarativeCatalogPart.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web.UI.WebControls.WebParts { sealed public partial class DeclarativeCatalogPart : CatalogPart { #region Methods and constructors public DeclarativeCatalogPart() { } public override WebPartDescriptionCollection GetAvailableWebPartDescriptions() { return default(WebPartDescriptionCollection); } public override WebPart GetWebPart(WebPartDescription description) { return default(WebPart); } protected internal override void Render(System.Web.UI.HtmlTextWriter writer) { } #endregion #region Properties and indexers public override string AccessKey { get { return default(string); } set { } } public override System.Drawing.Color BackColor { get { return default(System.Drawing.Color); } set { } } public override string BackImageUrl { get { return default(string); } set { } } public override System.Drawing.Color BorderColor { get { return default(System.Drawing.Color); } set { } } public override System.Web.UI.WebControls.BorderStyle BorderStyle { get { return default(System.Web.UI.WebControls.BorderStyle); } set { } } public override System.Web.UI.WebControls.Unit BorderWidth { get { return default(System.Web.UI.WebControls.Unit); } set { } } public override string CssClass { get { return default(string); } set { } } public override string DefaultButton { get { return default(string); } set { } } public override System.Web.UI.WebControls.ContentDirection Direction { get { return default(System.Web.UI.WebControls.ContentDirection); } set { } } public override bool Enabled { get { return default(bool); } set { } } public override bool EnableTheming { get { return default(bool); } set { } } public override System.Web.UI.WebControls.FontInfo Font { get { return default(System.Web.UI.WebControls.FontInfo); } } public override System.Drawing.Color ForeColor { get { return default(System.Drawing.Color); } set { } } public override string GroupingText { get { return default(string); } set { } } public override System.Web.UI.WebControls.Unit Height { get { return default(System.Web.UI.WebControls.Unit); } set { } } public override System.Web.UI.WebControls.HorizontalAlign HorizontalAlign { get { return default(System.Web.UI.WebControls.HorizontalAlign); } set { } } public override System.Web.UI.WebControls.ScrollBars ScrollBars { get { return default(System.Web.UI.WebControls.ScrollBars); } set { } } public override string SkinID { get { return default(string); } set { } } public override short TabIndex { get { return default(short); } set { } } public override string Title { get { return default(string); } set { } } public override string ToolTip { get { return default(string); } set { } } public override bool Visible { get { return default(bool); } set { } } public string WebPartsListUserControlPath { get { return default(string); } set { } } public System.Web.UI.ITemplate WebPartsTemplate { get { return default(System.Web.UI.ITemplate); } set { } } public override System.Web.UI.WebControls.Unit Width { get { return default(System.Web.UI.WebControls.Unit); } set { } } public override bool Wrap { get { return default(bool); } set { } } #endregion } }
using System; using System.ComponentModel; using System.Linq; using System.Reactive.Disposables; using Avalonia.Controls.Mixins; using Avalonia.Controls.Diagnostics; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives.PopupPositioning; using Avalonia.Input; using Avalonia.Input.Raw; using Avalonia.Layout; using Avalonia.LogicalTree; using Avalonia.Metadata; using Avalonia.Platform; using Avalonia.VisualTree; #nullable enable namespace Avalonia.Controls.Primitives { /// <summary> /// Displays a popup window. /// </summary> #pragma warning disable CS0612 // Type or member is obsolete public class Popup : Control, IVisualTreeHost, IPopupHostProvider #pragma warning restore CS0612 // Type or member is obsolete { public static readonly StyledProperty<bool> WindowManagerAddShadowHintProperty = AvaloniaProperty.Register<PopupRoot, bool>(nameof(WindowManagerAddShadowHint), false); /// <summary> /// Defines the <see cref="Child"/> property. /// </summary> public static readonly StyledProperty<Control?> ChildProperty = AvaloniaProperty.Register<Popup, Control?>(nameof(Child)); /// <summary> /// Defines the <see cref="IsOpen"/> property. /// </summary> public static readonly DirectProperty<Popup, bool> IsOpenProperty = AvaloniaProperty.RegisterDirect<Popup, bool>( nameof(IsOpen), o => o.IsOpen, (o, v) => o.IsOpen = v); /// <summary> /// Defines the <see cref="PlacementAnchor"/> property. /// </summary> public static readonly StyledProperty<PopupAnchor> PlacementAnchorProperty = AvaloniaProperty.Register<Popup, PopupAnchor>(nameof(PlacementAnchor)); /// <summary> /// Defines the <see cref="PlacementConstraintAdjustment"/> property. /// </summary> public static readonly StyledProperty<PopupPositionerConstraintAdjustment> PlacementConstraintAdjustmentProperty = AvaloniaProperty.Register<Popup, PopupPositionerConstraintAdjustment>( nameof(PlacementConstraintAdjustment), PopupPositionerConstraintAdjustment.FlipX | PopupPositionerConstraintAdjustment.FlipY | PopupPositionerConstraintAdjustment.SlideX | PopupPositionerConstraintAdjustment.SlideY | PopupPositionerConstraintAdjustment.ResizeX | PopupPositionerConstraintAdjustment.ResizeY); /// <summary> /// Defines the <see cref="PlacementGravity"/> property. /// </summary> public static readonly StyledProperty<PopupGravity> PlacementGravityProperty = AvaloniaProperty.Register<Popup, PopupGravity>(nameof(PlacementGravity)); /// <summary> /// Defines the <see cref="PlacementMode"/> property. /// </summary> public static readonly StyledProperty<PlacementMode> PlacementModeProperty = AvaloniaProperty.Register<Popup, PlacementMode>(nameof(PlacementMode), defaultValue: PlacementMode.Bottom); /// <summary> /// Defines the <see cref="PlacementRect"/> property. /// </summary> public static readonly StyledProperty<Rect?> PlacementRectProperty = AvaloniaProperty.Register<Popup, Rect?>(nameof(PlacementRect)); /// <summary> /// Defines the <see cref="PlacementTarget"/> property. /// </summary> public static readonly StyledProperty<Control?> PlacementTargetProperty = AvaloniaProperty.Register<Popup, Control?>(nameof(PlacementTarget)); #pragma warning disable 618 /// <summary> /// Defines the <see cref="ObeyScreenEdges"/> property. /// </summary> public static readonly StyledProperty<bool> ObeyScreenEdgesProperty = AvaloniaProperty.Register<Popup, bool>(nameof(ObeyScreenEdges), true); #pragma warning restore 618 public static readonly StyledProperty<bool> OverlayDismissEventPassThroughProperty = AvaloniaProperty.Register<Popup, bool>(nameof(OverlayDismissEventPassThrough)); public static readonly DirectProperty<Popup, IInputElement?> OverlayInputPassThroughElementProperty = AvaloniaProperty.RegisterDirect<Popup, IInputElement?>( nameof(OverlayInputPassThroughElement), o => o.OverlayInputPassThroughElement, (o, v) => o.OverlayInputPassThroughElement = v); /// <summary> /// Defines the <see cref="HorizontalOffset"/> property. /// </summary> public static readonly StyledProperty<double> HorizontalOffsetProperty = AvaloniaProperty.Register<Popup, double>(nameof(HorizontalOffset)); /// <summary> /// Defines the <see cref="IsLightDismissEnabled"/> property. /// </summary> public static readonly StyledProperty<bool> IsLightDismissEnabledProperty = AvaloniaProperty.Register<Popup, bool>(nameof(IsLightDismissEnabled)); /// <summary> /// Defines the <see cref="VerticalOffset"/> property. /// </summary> public static readonly StyledProperty<double> VerticalOffsetProperty = AvaloniaProperty.Register<Popup, double>(nameof(VerticalOffset)); /// <summary> /// Defines the <see cref="StaysOpen"/> property. /// </summary> [Obsolete("Use IsLightDismissEnabledProperty")] public static readonly DirectProperty<Popup, bool> StaysOpenProperty = AvaloniaProperty.RegisterDirect<Popup, bool>( nameof(StaysOpen), o => o.StaysOpen, (o, v) => o.StaysOpen = v, true); /// <summary> /// Defines the <see cref="Topmost"/> property. /// </summary> public static readonly StyledProperty<bool> TopmostProperty = AvaloniaProperty.Register<Popup, bool>(nameof(Topmost)); private bool _isOpenRequested = false; private bool _isOpen; private bool _ignoreIsOpenChanged; private PopupOpenState? _openState; private IInputElement? _overlayInputPassThroughElement; private Action<IPopupHost?>? _popupHostChangedHandler; /// <summary> /// Initializes static members of the <see cref="Popup"/> class. /// </summary> static Popup() { IsHitTestVisibleProperty.OverrideDefaultValue<Popup>(false); ChildProperty.Changed.AddClassHandler<Popup>((x, e) => x.ChildChanged(e)); IsOpenProperty.Changed.AddClassHandler<Popup>((x, e) => x.IsOpenChanged((AvaloniaPropertyChangedEventArgs<bool>)e)); VerticalOffsetProperty.Changed.AddClassHandler<Popup>((x, _) => x.HandlePositionChange()); HorizontalOffsetProperty.Changed.AddClassHandler<Popup>((x, _) => x.HandlePositionChange()); } /// <summary> /// Raised when the popup closes. /// </summary> public event EventHandler<EventArgs>? Closed; /// <summary> /// Raised when the popup opens. /// </summary> public event EventHandler? Opened; internal event EventHandler<CancelEventArgs>? Closing; public IPopupHost? Host => _openState?.PopupHost; public bool WindowManagerAddShadowHint { get { return GetValue(WindowManagerAddShadowHintProperty); } set { SetValue(WindowManagerAddShadowHintProperty, value); } } /// <summary> /// Gets or sets the control to display in the popup. /// </summary> [Content] public Control? Child { get { return GetValue(ChildProperty); } set { SetValue(ChildProperty, value); } } /// <summary> /// Gets or sets a dependency resolver for the <see cref="PopupRoot"/>. /// </summary> /// <remarks> /// This property allows a client to customize the behaviour of the popup by injecting /// a specialized dependency resolver into the <see cref="PopupRoot"/>'s constructor. /// </remarks> public IAvaloniaDependencyResolver? DependencyResolver { get; set; } /// <summary> /// Gets or sets a value that determines how the <see cref="Popup"/> can be dismissed. /// </summary> /// <remarks> /// Light dismiss is when the user taps on any area other than the popup. /// </remarks> public bool IsLightDismissEnabled { get => GetValue(IsLightDismissEnabledProperty); set => SetValue(IsLightDismissEnabledProperty, value); } /// <summary> /// Gets or sets a value indicating whether the popup is currently open. /// </summary> public bool IsOpen { get { return _isOpen; } set { SetAndRaise(IsOpenProperty, ref _isOpen, value); } } /// <summary> /// Gets or sets the anchor point on the <see cref="PlacementRect"/> when <see cref="PlacementMode"/> /// is <see cref="PlacementMode.AnchorAndGravity"/>. /// </summary> public PopupAnchor PlacementAnchor { get { return GetValue(PlacementAnchorProperty); } set { SetValue(PlacementAnchorProperty, value); } } /// <summary> /// Gets or sets a value describing how the popup position will be adjusted if the /// unadjusted position would result in the popup being partly constrained. /// </summary> public PopupPositionerConstraintAdjustment PlacementConstraintAdjustment { get { return GetValue(PlacementConstraintAdjustmentProperty); } set { SetValue(PlacementConstraintAdjustmentProperty, value); } } /// <summary> /// Gets or sets a value which defines in what direction the popup should open /// when <see cref="PlacementMode"/> is <see cref="PlacementMode.AnchorAndGravity"/>. /// </summary> public PopupGravity PlacementGravity { get { return GetValue(PlacementGravityProperty); } set { SetValue(PlacementGravityProperty, value); } } /// <summary> /// Gets or sets the placement mode of the popup in relation to the <see cref="PlacementTarget"/>. /// </summary> public PlacementMode PlacementMode { get { return GetValue(PlacementModeProperty); } set { SetValue(PlacementModeProperty, value); } } /// <summary> /// Gets or sets the the anchor rectangle within the parent that the popup will be placed /// relative to when <see cref="PlacementMode"/> is <see cref="PlacementMode.AnchorAndGravity"/>. /// </summary> /// <remarks> /// The placement rect defines a rectangle relative to <see cref="PlacementTarget"/> around /// which the popup will be opened, with <see cref="PlacementAnchor"/> determining which edge /// of the placement target is used. /// /// If unset, the anchor rectangle will be the bounds of the <see cref="PlacementTarget"/>. /// </remarks> public Rect? PlacementRect { get { return GetValue(PlacementRectProperty); } set { SetValue(PlacementRectProperty, value); } } /// <summary> /// Gets or sets the control that is used to determine the popup's position. /// </summary> [ResolveByName] public Control? PlacementTarget { get { return GetValue(PlacementTargetProperty); } set { SetValue(PlacementTargetProperty, value); } } [Obsolete("This property has no effect")] public bool ObeyScreenEdges { get => GetValue(ObeyScreenEdgesProperty); set => SetValue(ObeyScreenEdgesProperty, value); } /// <summary> /// Gets or sets a value indicating whether the event that closes the popup is passed /// through to the parent window. /// </summary> /// <remarks> /// When <see cref="IsLightDismissEnabled"/> is set to true, clicks outside the the popup /// cause the popup to close. When <see cref="OverlayDismissEventPassThrough"/> is set to /// false, these clicks will be handled by the popup and not be registered by the parent /// window. When set to true, the events will be passed through to the parent window. /// </remarks> public bool OverlayDismissEventPassThrough { get => GetValue(OverlayDismissEventPassThroughProperty); set => SetValue(OverlayDismissEventPassThroughProperty, value); } /// <summary> /// Gets or sets an element that should receive pointer input events even when underneath /// the popup's overlay. /// </summary> public IInputElement? OverlayInputPassThroughElement { get => _overlayInputPassThroughElement; set => SetAndRaise(OverlayInputPassThroughElementProperty, ref _overlayInputPassThroughElement, value); } /// <summary> /// Gets or sets the Horizontal offset of the popup in relation to the <see cref="PlacementTarget"/>. /// </summary> public double HorizontalOffset { get { return GetValue(HorizontalOffsetProperty); } set { SetValue(HorizontalOffsetProperty, value); } } /// <summary> /// Gets or sets the Vertical offset of the popup in relation to the <see cref="PlacementTarget"/>. /// </summary> public double VerticalOffset { get { return GetValue(VerticalOffsetProperty); } set { SetValue(VerticalOffsetProperty, value); } } /// <summary> /// Gets or sets a value indicating whether the popup should stay open when the popup is /// pressed or loses focus. /// </summary> [Obsolete("Use IsLightDismissEnabled")] public bool StaysOpen { get => !IsLightDismissEnabled; set => IsLightDismissEnabled = !value; } /// <summary> /// Gets or sets whether this popup appears on top of all other windows /// </summary> public bool Topmost { get { return GetValue(TopmostProperty); } set { SetValue(TopmostProperty, value); } } /// <summary> /// Gets the root of the popup window. /// </summary> IVisual? IVisualTreeHost.Root => _openState?.PopupHost.HostedVisualTreeRoot; IPopupHost? IPopupHostProvider.PopupHost => Host; event Action<IPopupHost?>? IPopupHostProvider.PopupHostChanged { add => _popupHostChangedHandler += value; remove => _popupHostChangedHandler -= value; } /// <summary> /// Opens the popup. /// </summary> public void Open() { // Popup is currently open if (_openState != null) { return; } var placementTarget = PlacementTarget ?? this.FindLogicalAncestorOfType<IControl>(); if (placementTarget == null) { _isOpenRequested = true; return; } var topLevel = placementTarget.VisualRoot as TopLevel; if (topLevel == null) { _isOpenRequested = true; return; } _isOpenRequested = false; var popupHost = OverlayPopupHost.CreatePopupHost(placementTarget, DependencyResolver); var handlerCleanup = new CompositeDisposable(7); popupHost.BindConstraints(this, WidthProperty, MinWidthProperty, MaxWidthProperty, HeightProperty, MinHeightProperty, MaxHeightProperty, TopmostProperty).DisposeWith(handlerCleanup); popupHost.SetChild(Child); ((ISetLogicalParent)popupHost).SetParent(this); popupHost.ConfigurePosition( placementTarget, PlacementMode, new Point(HorizontalOffset, VerticalOffset), PlacementAnchor, PlacementGravity, PlacementConstraintAdjustment, PlacementRect); SubscribeToEventHandler<IPopupHost, EventHandler<TemplateAppliedEventArgs>>(popupHost, RootTemplateApplied, (x, handler) => x.TemplateApplied += handler, (x, handler) => x.TemplateApplied -= handler).DisposeWith(handlerCleanup); if (topLevel is Window window) { SubscribeToEventHandler<Window, EventHandler>(window, WindowDeactivated, (x, handler) => x.Deactivated += handler, (x, handler) => x.Deactivated -= handler).DisposeWith(handlerCleanup); SubscribeToEventHandler<IWindowImpl, Action>(window.PlatformImpl, WindowLostFocus, (x, handler) => x.LostFocus += handler, (x, handler) => x.LostFocus -= handler).DisposeWith(handlerCleanup); SubscribeToEventHandler<IWindowImpl, Action<PixelPoint>>(window.PlatformImpl, WindowPositionChanged, (x, handler) => x.PositionChanged += handler, (x, handler) => x.PositionChanged -= handler).DisposeWith(handlerCleanup); if (placementTarget is Layoutable layoutTarget) { // If the placement target is moved, update the popup position SubscribeToEventHandler<Layoutable, EventHandler>(layoutTarget, PlacementTargetLayoutUpdated, (x, handler) => x.LayoutUpdated += handler, (x, handler) => x.LayoutUpdated -= handler).DisposeWith(handlerCleanup); } } else if (topLevel is PopupRoot parentPopupRoot) { SubscribeToEventHandler<PopupRoot, EventHandler<PixelPointEventArgs>>(parentPopupRoot, ParentPopupPositionChanged, (x, handler) => x.PositionChanged += handler, (x, handler) => x.PositionChanged -= handler).DisposeWith(handlerCleanup); if (parentPopupRoot.Parent is Popup popup) { SubscribeToEventHandler<Popup, EventHandler<EventArgs>>(popup, ParentClosed, (x, handler) => x.Closed += handler, (x, handler) => x.Closed -= handler).DisposeWith(handlerCleanup); } } InputManager.Instance?.Process.Subscribe(ListenForNonClientClick).DisposeWith(handlerCleanup); var cleanupPopup = Disposable.Create((popupHost, handlerCleanup), state => { state.handlerCleanup.Dispose(); state.popupHost.SetChild(null); state.popupHost.Hide(); ((ISetLogicalParent)state.popupHost).SetParent(null); state.popupHost.Dispose(); }); if (IsLightDismissEnabled) { var dismissLayer = LightDismissOverlayLayer.GetLightDismissOverlayLayer(placementTarget); if (dismissLayer != null) { dismissLayer.IsVisible = true; dismissLayer.InputPassThroughElement = _overlayInputPassThroughElement; Disposable.Create(() => { dismissLayer.IsVisible = false; dismissLayer.InputPassThroughElement = null; }).DisposeWith(handlerCleanup); SubscribeToEventHandler<LightDismissOverlayLayer, EventHandler<PointerPressedEventArgs>>( dismissLayer, PointerPressedDismissOverlay, (x, handler) => x.PointerPressed += handler, (x, handler) => x.PointerPressed -= handler).DisposeWith(handlerCleanup); } } _openState = new PopupOpenState(topLevel, popupHost, cleanupPopup); WindowManagerAddShadowHintChanged(popupHost, WindowManagerAddShadowHint); popupHost.Show(); using (BeginIgnoringIsOpen()) { IsOpen = true; } Opened?.Invoke(this, EventArgs.Empty); _popupHostChangedHandler?.Invoke(Host); } /// <summary> /// Closes the popup. /// </summary> public void Close() => CloseCore(); /// <summary> /// Measures the control. /// </summary> /// <param name="availableSize">The available size for the control.</param> /// <returns>A size of 0,0 as Popup itself takes up no space.</returns> protected override Size MeasureCore(Size availableSize) { return new Size(); } /// <inheritdoc/> protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e) { base.OnAttachedToVisualTree(e); if (_isOpenRequested) { Open(); } } /// <inheritdoc/> protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); Close(); } private void HandlePositionChange() { if (_openState != null) { var placementTarget = PlacementTarget ?? this.FindLogicalAncestorOfType<IControl>(); if (placementTarget == null) return; _openState.PopupHost.ConfigurePosition( placementTarget, PlacementMode, new Point(HorizontalOffset, VerticalOffset), PlacementAnchor, PlacementGravity, PlacementConstraintAdjustment, PlacementRect); } } private static IDisposable SubscribeToEventHandler<T, TEventHandler>(T target, TEventHandler handler, Action<T, TEventHandler> subscribe, Action<T, TEventHandler> unsubscribe) { subscribe(target, handler); return Disposable.Create((unsubscribe, target, handler), state => state.unsubscribe(state.target, state.handler)); } private void WindowManagerAddShadowHintChanged(IPopupHost host, bool hint) { if(host is PopupRoot pr) { pr.PlatformImpl.SetWindowManagerAddShadowHint(hint); } } /// <summary> /// Called when the <see cref="IsOpen"/> property changes. /// </summary> /// <param name="e">The event args.</param> private void IsOpenChanged(AvaloniaPropertyChangedEventArgs<bool> e) { if (!_ignoreIsOpenChanged) { if (e.NewValue.Value) { Open(); } else { Close(); } } } /// <summary> /// Called when the <see cref="Child"/> property changes. /// </summary> /// <param name="e">The event args.</param> private void ChildChanged(AvaloniaPropertyChangedEventArgs e) { LogicalChildren.Clear(); ((ISetLogicalParent?)e.OldValue)?.SetParent(null); if (e.NewValue != null) { ((ISetLogicalParent)e.NewValue).SetParent(this); LogicalChildren.Add((ILogical)e.NewValue); } } private void CloseCore() { var closingArgs = new CancelEventArgs(); Closing?.Invoke(this, closingArgs); if (closingArgs.Cancel) { return; } _isOpenRequested = false; if (_openState is null) { using (BeginIgnoringIsOpen()) { IsOpen = false; } return; } _openState.Dispose(); _openState = null; _popupHostChangedHandler?.Invoke(null); using (BeginIgnoringIsOpen()) { IsOpen = false; } Closed?.Invoke(this, EventArgs.Empty); var focusCheck = FocusManager.Instance?.Current; // Focus is set to null as part of popup closing, so we only want to // set focus to PlacementTarget if this is the case if (focusCheck == null) { if (PlacementTarget != null) { FocusManager.Instance?.Focus(PlacementTarget); } else { var anc = this.FindLogicalAncestorOfType<IControl>(); if (anc != null) { FocusManager.Instance?.Focus(anc); } } } } private void ListenForNonClientClick(RawInputEventArgs e) { var mouse = e as RawPointerEventArgs; if (IsLightDismissEnabled && mouse?.Type == RawPointerEventType.NonClientLeftButtonDown) { CloseCore(); } } private void PointerPressedDismissOverlay(object sender, PointerPressedEventArgs e) { if (IsLightDismissEnabled && e.Source is IVisual v && !IsChildOrThis(v)) { CloseCore(); if (OverlayDismissEventPassThrough) { PassThroughEvent(e); } } } private void PassThroughEvent(PointerPressedEventArgs e) { if (e.Source is LightDismissOverlayLayer layer && layer.GetVisualRoot() is IInputElement root) { var p = e.GetCurrentPoint(root); var hit = root.InputHitTest(p.Position, x => x != layer); if (hit != null) { e.Pointer.Capture(hit); hit.RaiseEvent(e); e.Handled = true; } } } private void RootTemplateApplied(object sender, TemplateAppliedEventArgs e) { if (_openState is null) { return; } var popupHost = _openState.PopupHost; popupHost.TemplateApplied -= RootTemplateApplied; _openState.SetPresenterSubscription(null); // If the Popup appears in a control template, then the child controls // that appear in the popup host need to have their TemplatedParent // properties set. if (TemplatedParent != null && popupHost.Presenter != null) { popupHost.Presenter.ApplyTemplate(); var presenterSubscription = popupHost.Presenter.GetObservable(ContentPresenter.ChildProperty) .Subscribe(SetTemplatedParentAndApplyChildTemplates); _openState.SetPresenterSubscription(presenterSubscription); } } private void SetTemplatedParentAndApplyChildTemplates(IControl control) { if (control != null) { var templatedParent = TemplatedParent; if (control.TemplatedParent == null) { control.SetValue(TemplatedParentProperty, templatedParent); } control.ApplyTemplate(); if (!(control is IPresenter) && control.TemplatedParent == templatedParent) { foreach (IControl child in control.VisualChildren) { SetTemplatedParentAndApplyChildTemplates(child); } } } } private bool IsChildOrThis(IVisual child) { if (_openState is null) { return false; } var popupHost = _openState.PopupHost; IVisual? root = child.VisualRoot; while (root is IHostedVisualTreeRoot hostedRoot) { if (root == popupHost) { return true; } root = hostedRoot.Host?.VisualRoot; } return false; } public bool IsInsidePopup(IVisual visual) { if (_openState is null) { return false; } var popupHost = _openState.PopupHost; return popupHost != null && ((IVisual)popupHost).IsVisualAncestorOf(visual); } public bool IsPointerOverPopup => ((IInputElement?)_openState?.PopupHost)?.IsPointerOver ?? false; private void WindowDeactivated(object sender, EventArgs e) { if (IsLightDismissEnabled) { Close(); } } private void ParentClosed(object sender, EventArgs e) { if (IsLightDismissEnabled) { Close(); } } private void WindowLostFocus() { if (IsLightDismissEnabled) Close(); } private void WindowPositionChanged(PixelPoint pp) => HandlePositionChange(); private void PlacementTargetLayoutUpdated(object src, EventArgs e) => HandlePositionChange(); private void ParentPopupPositionChanged(object src, PixelPointEventArgs e) => HandlePositionChange(); private IgnoreIsOpenScope BeginIgnoringIsOpen() { return new IgnoreIsOpenScope(this); } private readonly struct IgnoreIsOpenScope : IDisposable { private readonly Popup _owner; public IgnoreIsOpenScope(Popup owner) { _owner = owner; _owner._ignoreIsOpenChanged = true; } public void Dispose() { _owner._ignoreIsOpenChanged = false; } } private class PopupOpenState : IDisposable { private readonly IDisposable _cleanup; private IDisposable? _presenterCleanup; public PopupOpenState(TopLevel topLevel, IPopupHost popupHost, IDisposable cleanup) { TopLevel = topLevel; PopupHost = popupHost; _cleanup = cleanup; } public TopLevel TopLevel { get; } public IPopupHost PopupHost { get; } public void SetPresenterSubscription(IDisposable? presenterCleanup) { _presenterCleanup?.Dispose(); _presenterCleanup = presenterCleanup; } public void Dispose() { _presenterCleanup?.Dispose(); _cleanup.Dispose(); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace OnlineExamPrep.WebAPI.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); } } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using Microsoft.PackageManagement.Internal.Utility.Platform; namespace Microsoft.PackageManagement.MetaProvider.PowerShell.Internal { using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Threading; using Microsoft.PackageManagement.Internal.Utility.Extensions; using Microsoft.PackageManagement.Internal.Utility.Platform; using Messages = Microsoft.PackageManagement.MetaProvider.PowerShell.Resources.Messages; using System.Collections.Concurrent; public class PowerShellProviderBase : IDisposable { private object _lock = new Object(); protected PSModuleInfo _module; private PowerShell _powershell; private ManualResetEvent _reentrancyLock = new ManualResetEvent(true); private readonly Dictionary<string, CommandInfo> _allCommands = new Dictionary<string, CommandInfo>(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<string, CommandInfo> _methods = new Dictionary<string, CommandInfo>(StringComparer.OrdinalIgnoreCase); public PowerShellProviderBase(PowerShell ps, PSModuleInfo module) { if (module == null) { throw new ArgumentNullException("module"); } _powershell = ps; _module = module; // combine all the cmdinfos we care about // but normalize the keys as we go (remove any '-' '_' chars) foreach (var k in _module.ExportedAliases.Keys) { _allCommands.AddOrSet(k.Replace("-", "").Replace("_", ""), _module.ExportedAliases[k]); } foreach (var k in _module.ExportedCmdlets.Keys) { _allCommands.AddOrSet(k.Replace("-", "").Replace("_", ""), _module.ExportedCmdlets[k]); } foreach (var k in _module.ExportedFunctions.Keys) { _allCommands.AddOrSet(k.Replace("-", "").Replace("_", ""), _module.ExportedFunctions[k]); } } public string ModulePath { get { return _module.Path; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { if (_powershell != null) { _powershell.Dispose(); _powershell = null; } if (_reentrancyLock != null) { _reentrancyLock.Dispose(); _reentrancyLock = null; } _module = null; } } internal CommandInfo GetMethod(string methodName) { return _methods.GetOrAdd(methodName, () => { if (_allCommands.ContainsKey(methodName)) { return _allCommands[methodName]; } // try simple plurals to single if (methodName.EndsWith("s", StringComparison.OrdinalIgnoreCase)) { var meth = methodName.Substring(0, methodName.Length - 1); if (_allCommands.ContainsKey(meth)) { return _allCommands[meth]; } } // try words like Dependencies to Dependency if (methodName.EndsWith("cies", StringComparison.OrdinalIgnoreCase)) { var meth = methodName.Substring(0, methodName.Length - 4) + "cy"; if (_allCommands.ContainsKey(meth)) { return _allCommands[meth]; } } // try IsFoo to Test-IsFoo if (methodName.IndexOf("Is", StringComparison.OrdinalIgnoreCase) == 0) { var meth = "test" + methodName; if (_allCommands.ContainsKey(meth)) { return _allCommands[meth]; } } if (methodName.IndexOf("add", StringComparison.OrdinalIgnoreCase) == 0) { // try it with 'register' instead var result = GetMethod("register" + methodName.Substring(3)); if (result != null) { return result; } } if (methodName.IndexOf("remove", StringComparison.OrdinalIgnoreCase) == 0) { // try it with 'register' instead var result = GetMethod("unregister" + methodName.Substring(6)); if (result != null) { return result; } } // can't find one, return null. return null; }); // hmm, it is possible to get the parameter types to match better when binding. // module.ExportedFunctions.FirstOrDefault().Value.Parameters.Values.First().ParameterType } internal object CallPowerShellWithoutRequest(string method, params object[] args) { var cmdInfo = GetMethod(method); if (cmdInfo == null) { return null; } var result = _powershell.InvokeFunction<object>(cmdInfo.Name, null, null, args); if (result == null) { // failure! throw new Exception(Messages.PowershellScriptFunctionReturnsNull.format(_module.Name, method)); } return result; } // lock is on this instance only internal void ReportErrors(PsRequest request, IEnumerable<ErrorRecord> errors) { foreach (var error in errors) { request.Error(error.FullyQualifiedErrorId, error.CategoryInfo.Category.ToString(), error.TargetObject == null ? null : error.TargetObject.ToString(), error.ErrorDetails == null ? error.Exception.Message : error.ErrorDetails.Message); if (!string.IsNullOrWhiteSpace(error.Exception.StackTrace)) { // give a debug hint if we have a script stack trace. How nice of us. // the exception stack trace gives better stack than the script stack trace request.Debug(Constants.ScriptStackTrace, error.Exception.StackTrace); } } } private IAsyncResult _stopResult; private object _stopLock = new object(); internal void CancelRequest() { if (!_reentrancyLock.WaitOne(0)) { // it's running right now. #if DEBUG NativeMethods.OutputDebugString("[Cmdlet:debugging] -- Stopping powershell script."); #endif lock (_stopLock) { if (_stopResult == null) { _stopResult = _powershell.BeginStop(ar => { }, null); } } } } internal object CallPowerShell(PsRequest request, params object[] args) { // the lock ensures that we're not re-entrant into the same powershell runspace lock (_lock) { if (!_reentrancyLock.WaitOne(0)) { // this lock is set to false, meaning we're still in a call **ON THIS THREAD** // this is bad karma -- powershell won't let us call into the runspace again // we're going to throw an error here because this indicates that the currently // running powershell call is calling back into PM, and it has called back // into this provider. That's just bad bad bad. throw new Exception("Re-entrancy Violation in powershell module"); } try { // otherwise, this is the first time we've been here during this call. _reentrancyLock.Reset(); _powershell.SetVariable("request", request); _powershell.Streams.ClearStreams(); object finalValue = null; ConcurrentBag<ErrorRecord> errors = new ConcurrentBag<ErrorRecord>(); request.Debug("INVOKING PowerShell Fn {0} with args {1} that has length {2}", request.CommandInfo.Name, String.Join(", ", args), args.Length); var result = _powershell.InvokeFunction<object>(request.CommandInfo.Name, (sender, e) => output_DataAdded(sender, e, request, ref finalValue), (sender, e) => error_DataAdded(sender, e, request, errors), args); if (result == null) { // result is null but it does not mean that the call fails because the command may return nothing request.Debug(Messages.PowershellScriptFunctionReturnsNull.format(_module.Name, request.CommandInfo.Name)); } if (errors.Count > 0) { // report the error if there are any ReportErrors(request, errors); _powershell.Streams.Error.Clear(); } return finalValue; } catch (CmdletInvocationException cie) { var error = cie.ErrorRecord; request.Error(error.FullyQualifiedErrorId, error.CategoryInfo.Category.ToString(), error.TargetObject == null ? null : error.TargetObject.ToString(), error.ErrorDetails == null ? error.Exception.Message : error.ErrorDetails.Message); } finally { lock (_stopLock) { if (_stopResult != null){ _powershell.EndStop(_stopResult); _stopResult = null; } } _powershell.Clear(); _powershell.SetVariable("request", null); // it's ok if someone else calls into this module now. request.Debug("Done calling powershell", request.CommandInfo.Name, _module.Name); _reentrancyLock.Set(); } return null; } } private void error_DataAdded(object sender, DataAddedEventArgs e, PsRequest request, ConcurrentBag<ErrorRecord> errors) { PSDataCollection<ErrorRecord> errorStream = sender as PSDataCollection<ErrorRecord>; if (errorStream == null) { return; } var error = errorStream[e.Index]; if (error != null) { // add the error so we can report them later errors.Add(error); } } private void output_DataAdded(object sender, DataAddedEventArgs e, PsRequest request, ref object finalValue) { PSDataCollection<PSObject> outputstream = sender as PSDataCollection<PSObject>; if (outputstream == null) { return; } PSObject psObject = outputstream[e.Index]; if (psObject != null) { var value = psObject.ImmediateBaseObject; var y = value as Yieldable; if (y != null) { // yield it to stream the result gradually y.YieldResult(request); } else { finalValue = value; return; } } } } }
/******************************************************************************************** Copyright (c) Microsoft Corporation All rights reserved. Microsoft Public License: This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 1. Definitions The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. 2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 3. Conditions and Limitations (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. ********************************************************************************************/ using System; using System.IO; using System.Reflection; using System.Runtime.Versioning; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VsSDK.UnitTestLibrary; using MSBuild = Microsoft.Build.BuildEngine; using OleServiceProvider = Microsoft.VsSDK.UnitTestLibrary.OleServiceProvider; namespace Microsoft.VisualStudio.Project.Samples.NestedProject.UnitTests { /// <summary> ///This is a test class for VisualStudio.Project.Samples.NestedProject.GeneralPropertyPage and is intended ///to contain all VisualStudio.Project.Samples.NestedProject.GeneralPropertyPage Unit Tests ///</summary> [TestClass()] public class GeneralPropertyPageTest : BaseTest { #region Fields private string testString; VisualStudio_Project_Samples_GeneralPropertyPageAccessor gppAccessor; #endregion Fields #region Initialization && Cleanup /// <summary> /// Runs before the test to allocate and configure resources needed /// by all tests in the test class. /// </summary> [TestInitialize()] public void GeneralPropertyPageTestInitialize() { base.Initialize(); testString = "This is a test string"; // Initialize GeneralPropertyPage instance gppAccessor = new VisualStudio_Project_Samples_GeneralPropertyPageAccessor(generalPropertyPage); } [ClassInitialize] public static void TestClassInitialize(TestContext context) { fullPathToProjectFile = Path.Combine(context.TestDeploymentDir, fullPathToProjectFile); } #endregion Initialization && Cleanup #region Test methods /// <summary> /// The test for ApplicationIcon. /// AppIcon must be internally assigned and isDirty flag switched on. ///</summary> [TestMethod()] public void ApplicationIconTest() { GeneralPropertyPage target = generalPropertyPage; target.ApplicationIcon = testString; Assert.AreEqual(testString, gppAccessor.applicationIcon, target.ApplicationIcon, "ApplicationIcon value was not initialized by expected value."); Assert.IsTrue((VSConstants.S_OK == target.IsPageDirty()), "IsDirty status was unexpected after changing of the property of the tested object."); } /// <summary> /// The test for ApplyChanges() in scenario when ProjectMgr is uninitialized. ///</summary> [TestMethod()] public void ApplyChangesNullableProjectMgrTest() { GeneralPropertyPage target = generalPropertyPage; // sets indirectly projectMgr to null target.SetObjects(0, null); int actual = gppAccessor.ApplyChanges(); Assert.IsNull(target.ProjectMgr, "ProjectMgr instance was not initialized to null as it expected."); Assert.AreEqual(VSConstants.E_INVALIDARG, actual, "Method ApplyChanges() was returned unexpected value in case of uninitialized project instance."); } /// <summary> /// The test for AssemblyName property. ///</summary> [TestMethod()] public void AssemblyNameTest() { GeneralPropertyPage target = generalPropertyPage; target.AssemblyName = testString; Assert.AreEqual(testString, gppAccessor.assemblyName, target.ApplicationIcon, "AssemblyName property value was not initialized by expected value."); Assert.IsTrue((VSConstants.S_OK == target.IsPageDirty()), "IsDirty status was unexpected after changing of the property of the tested object."); } /// <summary> /// The test for GeneralPropertyPage default constructor. ///</summary> [TestMethod()] public void ConstructorTest() { GeneralPropertyPage target = generalPropertyPage; target.Name = testString; Assert.AreEqual(testString, target.Name, target.ApplicationIcon, "Name property value was not initialized by expected value in GeneralPropertyPage() constructor."); } /// <summary> /// The test for DefaultNamespace property. ///</summary> [TestMethod()] public void DefaultNamespaceTest() { GeneralPropertyPage target = generalPropertyPage; target.DefaultNamespace = testString; Assert.AreEqual(testString, target.DefaultNamespace, "DefaultNamespace property value was not initialized by expected value;"); Assert.IsTrue((VSConstants.S_OK == target.IsPageDirty()), "IsDirty status was unexpected after changing of the property of the tested object."); } /// <summary> /// The test for GetClassName() method. ///</summary> [TestMethod()] public void GetClassNameTest() { GeneralPropertyPage target = generalPropertyPage; string expectedClassName = "Microsoft.VisualStudio.Project.Samples.NestedProject.GeneralPropertyPage"; string actualClassName = target.GetClassName(); Assert.AreEqual(expectedClassName, actualClassName, "GetClassName() method was returned unexpected Type FullName value."); } /// <summary> /// The test for OutputFile in case of OutputType.Exe file type. ///</summary> [TestMethod()] public void OutputFileWithExeTypeTest() { GeneralPropertyPage target = generalPropertyPage; gppAccessor.outputType = OutputType.Exe; string expectedValue = target.AssemblyName + ".exe"; Assert.AreEqual(expectedValue, target.OutputFile, "OutputFile name was initialized by unexpected value for EXE OutputType."); } /// <summary> /// The test for OutputFile property in case of using of OutputType.WinExe file type. ///</summary> [TestMethod()] public void OutputFileWithWinExeTypeTest() { GeneralPropertyPage target = generalPropertyPage; gppAccessor.outputType = OutputType.WinExe; string expectedValue = target.AssemblyName + ".exe"; Assert.AreEqual(expectedValue, target.OutputFile, "OutputFile name was initialized by unexpected value for WINEXE OutputType."); } /// <summary> /// The test for OutputFile in case of using of OutputType.Library file type. ///</summary> [TestMethod()] public void OutputFileWithLibraryTypeTest() { GeneralPropertyPage target = generalPropertyPage; gppAccessor.outputType = OutputType.Library; string expectedValue = target.AssemblyName + ".dll"; Assert.AreEqual(expectedValue, target.OutputFile, "OutputFile name was initialized by unexpected value for Library OutputType."); } /// <summary> /// The test for OutputType property. ///</summary> [TestMethod()] public void OutputTypeTest() { GeneralPropertyPage target = generalPropertyPage; OutputType expectedOutType = OutputType.Library; target.OutputType = expectedOutType; Assert.AreEqual(expectedOutType, target.OutputType, "OutputType property value was initialized by unexpected value."); Assert.IsTrue((VSConstants.S_OK == target.IsPageDirty()), "IsDirty status was unexpected after changing of the property of the tested object."); } /// <summary> /// The test for StartupObject property. ///</summary> [TestMethod()] public void StartupObjectTest() { GeneralPropertyPage target = generalPropertyPage; target.StartupObject = testString; Assert.AreEqual(testString, gppAccessor.startupObject, target.StartupObject, "StartupObject property value was not initialized by expected value."); Assert.IsTrue((VSConstants.S_OK == target.IsPageDirty()), "IsDirty status was unexpected after changing of the property of the tested object."); } /// <summary> /// The test for TargetPlatform property. ///</summary> [TestMethod()] public void TargetFrameworkMonikerTest() { var fx4 = new FrameworkName(".NETFramework", new Version(4, 1)); generalPropertyPage.TargetFrameworkMoniker = fx4; FrameworkName expected = fx4; FrameworkName actual = generalPropertyPage.TargetFrameworkMoniker; Assert.AreEqual(expected, actual, "TargetFrameworkMoniker value was not initialized to expected value."); Assert.IsTrue((VSConstants.S_OK == generalPropertyPage.IsPageDirty()), "IsDirty status was unexpected after changing of the property of the tested object."); } /// <summary> /// The test for BindProperties() method. ///</summary> [TestMethod()] public void BindPropertiesTest() { PrepareProjectConfig(); gppAccessor.defaultNamespace = null; gppAccessor.startupObject = null; gppAccessor.applicationIcon = null; gppAccessor.assemblyName = null; gppAccessor.targetFrameworkMoniker = null; // NOTE: For the best test result we must tests all shown below fields: // For this we must Load project with specified property values. //gppAccessor.targetPlatform //gppAccessor.targetPlatformLocation //gppAccessor.defaultNamespace //gppAccessor.startupObject //gppAccessor.applicationIcon gppAccessor.BindProperties(); Assert.IsNotNull(gppAccessor.assemblyName, "The AssemblyName was not properly initialized."); } /// <summary> /// The test for BindProperties() method in scenario when ProjectMgr is not initialized. ///</summary> [TestMethod()] public void BindPropertiesWithNullableProjectMgrTest() { gppAccessor.BindProperties(); Assert.IsNull(gppAccessor.assemblyName, "The AssemblyName was initialized in scenario when ProjectMgr is invalid."); } /// <summary> /// The test for ProjectFile property. ///</summary> [TestMethod()] public void ProjectFileTest() { PrepareProjectConfig(); GeneralPropertyPage target = generalPropertyPage; // Project File Name must be equivalent with name of the currently loaded project Assert.AreEqual(Path.GetFileName(fullPathToProjectFile), target.ProjectFile, "ProjectFile property value was initialized by unexpected path value."); } /// <summary> ///The test for ProjectFolder property. ///</summary> [TestMethod()] public void ProjectFolderTest() { PrepareProjectConfig(); GeneralPropertyPage target = generalPropertyPage; string expectedProjectFolderPath = Path.GetDirectoryName(fullPathToProjectFile); expectedProjectFolderPath = Path.GetDirectoryName(expectedProjectFolderPath); // Project Folder path must be equivalent with path of the currently loaded project Assert.AreEqual(expectedProjectFolderPath, target.ProjectFolder, "ProjectFolder property value was initialized by unexpected path value."); } /// <summary> /// The test for ApplyChanges() in scenario when ProjectMgr is initialized. ///</summary> [TestMethod()] public void ApplyChangesTest() { PrepareProjectConfig(); int actual = gppAccessor.ApplyChanges(); Assert.AreEqual(VSConstants.S_OK, actual, "Method ApplyChanges() was returned unexpected value in case of initialized project instance."); } #endregion Completed test methods #region Service functions /// <summary> /// Initialize ProjectConfig and internal projectMgr objects. /// </summary> /// <remarks>Service function. Before calling this function projectNode must be /// initialized by valid project data.</remarks> protected void PrepareProjectConfig() { object[] ppUnk = new object[2]; ProjectConfig pjc = new ProjectConfig(projectNode, "manualSetConfigArgument"); ppUnk[0] = pjc; generalPropertyPage.SetObjects(1, ppUnk); } #endregion Service functions } }
using UnityEngine; using UnityEngine.Networking; using UnityEngine.UI; using System.Collections; using System.Collections.Generic; using System.Linq; public enum GameState { Offline, Connecting, Lobby, Countdown, WaitingForRolls, Scoring, GameOver } public class ExampleGameSession : NetworkBehaviour { public Text gameStateField; public Text gameRulesField; public static ExampleGameSession instance; ExampleListener networkListener; List<ExamplePlayerScript> players; string specialMessage = ""; [SyncVar] public GameState gameState; [SyncVar] public string message = ""; public void OnDestroy() { if (gameStateField != null) { gameStateField.text = ""; gameStateField.gameObject.SetActive(false); } if (gameRulesField != null) { gameRulesField.gameObject.SetActive(false); } } [Server] public override void OnStartServer() { networkListener = FindObjectOfType<ExampleListener>(); gameState = GameState.Connecting; } [Server] public void OnStartGame(List<CaptainsMessPlayer> aStartingPlayers) { players = aStartingPlayers.Select(p => p as ExamplePlayerScript).ToList(); RpcOnStartedGame(); foreach (ExamplePlayerScript p in players) { p.RpcOnStartedGame(); } StartCoroutine(RunGame()); } [Server] public void OnAbortGame() { RpcOnAbortedGame(); } [Client] public override void OnStartClient() { if (instance) { Debug.LogError("ERROR: Another GameSession!"); } instance = this; networkListener = FindObjectOfType<ExampleListener>(); networkListener.gameSession = this; if (gameState != GameState.Lobby) { gameState = GameState.Lobby; } } public void OnJoinedLobby() { gameState = GameState.Lobby; } public void OnLeftLobby() { gameState = GameState.Offline; } public void OnCountdownStarted() { gameState = GameState.Countdown; } public void OnCountdownCancelled() { gameState = GameState.Lobby; } [Server] IEnumerator RunGame() { // Reset game foreach (ExamplePlayerScript p in players) { p.totalPoints = 0; } while (MaxScore() < 3) { // Reset rolls foreach (ExamplePlayerScript p in players) { p.rollResult = 0; } // Wait for all players to roll gameState = GameState.WaitingForRolls; while (!AllPlayersHaveRolled()) { yield return null; } // Award point to winner gameState = GameState.Scoring; List<ExamplePlayerScript> scoringPlayers = PlayersWithHighestRoll(); if (scoringPlayers.Count == 1) { scoringPlayers[0].totalPoints += 1; specialMessage = scoringPlayers[0].deviceName + " scores 1 point!"; } else { specialMessage = "TIE! No points awarded."; } yield return new WaitForSeconds(2); specialMessage = ""; } // Declare winner! specialMessage = PlayerWithHighestScore().deviceName + " WINS!"; yield return new WaitForSeconds(3); specialMessage = ""; // Game over gameState = GameState.GameOver; } [Server] bool AllPlayersHaveRolled() { return players.All(p => p.rollResult > 0); } [Server] List<ExamplePlayerScript> PlayersWithHighestRoll() { int highestRoll = players.Max(p => p.rollResult); return players.Where(p => p.rollResult == highestRoll).ToList(); } [Server] int MaxScore() { return players.Max(p => p.totalPoints); } [Server] ExamplePlayerScript PlayerWithHighestScore() { int highestScore = players.Max(p => p.totalPoints); return players.Where(p => p.totalPoints == highestScore).First(); } [Server] public void PlayAgain() { StartCoroutine(RunGame()); } void Update() { if (isServer) { if (gameState == GameState.Countdown) { message = "Game Starting in " + Mathf.Ceil(networkListener.mess.CountdownTimer()) + "..."; } else if (specialMessage != "") { message = specialMessage; } else { message = gameState.ToString(); } } gameStateField.text = message; } // Client RPCs [ClientRpc] public void RpcOnStartedGame() { gameRulesField.gameObject.SetActive(true); } [ClientRpc] public void RpcOnAbortedGame() { gameRulesField.gameObject.SetActive(false); } }