context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using QuantConnect.Configuration; using QuantConnect.Interfaces; using QuantConnect.Logging; using QuantConnect.ToolBox.AlgoSeekFuturesConverter; using QuantConnect.ToolBox.AlgoSeekOptionsConverter; using QuantConnect.ToolBox.AlphaVantageDownloader; using QuantConnect.ToolBox.BitfinexDownloader; using QuantConnect.ToolBox.CoarseUniverseGenerator; using QuantConnect.ToolBox.CoinApiDataConverter; using QuantConnect.ToolBox.CryptoiqDownloader; using QuantConnect.ToolBox.DukascopyDownloader; using QuantConnect.ToolBox.GDAXDownloader; using QuantConnect.ToolBox.IBDownloader; using QuantConnect.ToolBox.IEX; using QuantConnect.ToolBox.IQFeedDownloader; using QuantConnect.ToolBox.IVolatilityEquityConverter; using QuantConnect.ToolBox.KaikoDataConverter; using QuantConnect.ToolBox.KrakenDownloader; using QuantConnect.ToolBox.NseMarketDataConverter; using QuantConnect.ToolBox.OandaDownloader; using QuantConnect.ToolBox.Polygon; using QuantConnect.ToolBox.QuantQuoteConverter; using QuantConnect.ToolBox.RandomDataGenerator; using QuantConnect.ToolBox.YahooDownloader; using QuantConnect.Util; using System; using System.IO; using static QuantConnect.Configuration.ApplicationParser; namespace QuantConnect.ToolBox { public class Program { public static void Main(string[] args) { Log.DebuggingEnabled = Config.GetBool("debug-mode"); var destinationDir = Config.Get("results-destination-folder"); if (!string.IsNullOrEmpty(destinationDir)) { Directory.CreateDirectory(destinationDir); Log.FilePath = Path.Combine(destinationDir, "log.txt"); } Log.LogHandler = Composer.Instance.GetExportedValueByTypeName<ILogHandler>(Config.Get("log-handler", "CompositeLogHandler")); var optionsObject = ToolboxArgumentParser.ParseArguments(args); if (optionsObject.Count == 0) { PrintMessageAndExit(); } var dataProvider = Composer.Instance.GetExportedValueByTypeName<IDataProvider>(Config.Get("data-provider", "DefaultDataProvider")); var mapFileProvider = Composer.Instance.GetExportedValueByTypeName<IMapFileProvider>(Config.Get("map-file-provider", "LocalDiskMapFileProvider")); var factorFileProvider = Composer.Instance.GetExportedValueByTypeName<IFactorFileProvider>(Config.Get("factor-file-provider", "LocalDiskFactorFileProvider")); mapFileProvider.Initialize(dataProvider); factorFileProvider.Initialize(mapFileProvider, dataProvider); var targetApp = GetParameterOrExit(optionsObject, "app").ToLowerInvariant(); if (targetApp.Contains("download") || targetApp.EndsWith("dl")) { var fromDate = Parse.DateTimeExact(GetParameterOrExit(optionsObject, "from-date"), "yyyyMMdd-HH:mm:ss"); var resolution = optionsObject.ContainsKey("resolution") ? optionsObject["resolution"].ToString() : ""; var market = optionsObject.ContainsKey("market") ? optionsObject["market"].ToString() : ""; var securityType = optionsObject.ContainsKey("security-type") ? optionsObject["security-type"].ToString() : ""; var tickers = ToolboxArgumentParser.GetTickers(optionsObject); var toDate = optionsObject.ContainsKey("to-date") ? Parse.DateTimeExact(optionsObject["to-date"].ToString(), "yyyyMMdd-HH:mm:ss") : DateTime.UtcNow; switch (targetApp) { case "gdaxdl": case "gdaxdownloader": GDAXDownloaderProgram.GDAXDownloader(tickers, resolution, fromDate, toDate); break; case "cdl": case "cryptoiqdownloader": CryptoiqDownloaderProgram.CryptoiqDownloader(tickers, GetParameterOrExit(optionsObject, "exchange"), fromDate, toDate); break; case "ddl": case "dukascopydownloader": DukascopyDownloaderProgram.DukascopyDownloader(tickers, resolution, fromDate, toDate); break; case "ibdl": case "ibdownloader": IBDownloaderProgram.IBDownloader(tickers, resolution, fromDate, toDate); break; case "iexdl": case "iexdownloader": IEXDownloaderProgram.IEXDownloader(tickers, resolution, fromDate, toDate); break; case "iqfdl": case "iqfeeddownloader": IQFeedDownloaderProgram.IQFeedDownloader(tickers, resolution, fromDate, toDate); break; case "kdl": case "krakendownloader": KrakenDownloaderProgram.KrakenDownloader(tickers, resolution, fromDate, toDate); break; case "odl": case "oandadownloader": OandaDownloaderProgram.OandaDownloader(tickers, resolution, fromDate, toDate); break; case "qbdl": case "ydl": case "yahoodownloader": YahooDownloaderProgram.YahooDownloader(tickers, resolution, fromDate, toDate); break; case "bfxdl": case "bitfinexdownloader": BitfinexDownloaderProgram.BitfinexDownloader(tickers, resolution, fromDate, toDate); break; case "pdl": case "polygondownloader": PolygonDownloaderProgram.PolygonDownloader( tickers, GetParameterOrExit(optionsObject, "security-type"), GetParameterOrExit(optionsObject, "market"), resolution, fromDate, toDate); break; case "avdl": case "alphavantagedownloader": AlphaVantageDownloaderProgram.AlphaVantageDownloader( tickers, resolution, fromDate, toDate, GetParameterOrExit(optionsObject, "api-key") ); break; default: PrintMessageAndExit(1, "ERROR: Unrecognized --app value"); break; } } else if (targetApp.Contains("updater") || targetApp.EndsWith("spu")) { switch (targetApp) { case "gdaxspu": case "gdaxsymbolpropertiesupdater": GDAXDownloaderProgram.ExchangeInfoDownloader(); break; case "bfxspu": case "bitfinexsymbolpropertiesupdater": BitfinexDownloaderProgram.ExchangeInfoDownloader(); break; default: PrintMessageAndExit(1, "ERROR: Unrecognized --app value"); break; } } else { switch (targetApp) { case "asfc": case "algoseekfuturesconverter": AlgoSeekFuturesProgram.AlgoSeekFuturesConverter(GetParameterOrExit(optionsObject, "date")); break; case "asoc": case "algoseekoptionsconverter": AlgoSeekOptionsConverterProgram.AlgoSeekOptionsConverter(GetParameterOrExit(optionsObject, "date")); break; case "ivec": case "ivolatilityequityconverter": IVolatilityEquityConverterProgram.IVolatilityEquityConverter(GetParameterOrExit(optionsObject, "source-dir"), GetParameterOrExit(optionsObject, "source-meta-dir"), GetParameterOrExit(optionsObject, "destination-dir"), GetParameterOrExit(optionsObject, "resolution")); break; case "kdc": case "kaikodataconverter": KaikoDataConverterProgram.KaikoDataConverter(GetParameterOrExit(optionsObject, "source-dir"), GetParameterOrExit(optionsObject, "date"), GetParameterOrDefault(optionsObject, "exchange", string.Empty)); break; case "cadc": case "coinapidataconverter": CoinApiDataConverterProgram.CoinApiDataProgram( GetParameterOrExit(optionsObject, "date"), GetParameterOrExit(optionsObject, "source-dir"), GetParameterOrExit(optionsObject, "destination-dir"), GetParameterOrDefault(optionsObject, "market", null)); break; case "nmdc": case "nsemarketdataconverter": NseMarketDataConverterProgram.NseMarketDataConverter(GetParameterOrExit(optionsObject, "source-dir"), GetParameterOrExit(optionsObject, "destination-dir")); break; case "qqc": case "quantquoteconverter": QuantQuoteConverterProgram.QuantQuoteConverter(GetParameterOrExit(optionsObject, "destination-dir"), GetParameterOrExit(optionsObject, "source-dir"), GetParameterOrExit(optionsObject, "resolution")); break; case "cug": case "coarseuniversegenerator": CoarseUniverseGeneratorProgram.CoarseUniverseGenerator(); break; case "rdg": case "randomdatagenerator": var tickers = ToolboxArgumentParser.GetTickers(optionsObject); RandomDataGeneratorProgram.RandomDataGenerator( GetParameterOrExit(optionsObject, "start"), GetParameterOrExit(optionsObject, "end"), GetParameterOrExit(optionsObject, "symbol-count"), GetParameterOrDefault(optionsObject, "market", null), GetParameterOrDefault(optionsObject, "security-type", "Equity"), GetParameterOrDefault(optionsObject, "resolution", "Minute"), GetParameterOrDefault(optionsObject, "data-density", "Dense"), GetParameterOrDefault(optionsObject, "include-coarse", "true"), GetParameterOrDefault(optionsObject, "quote-trade-ratio", "1"), GetParameterOrDefault(optionsObject, "random-seed", null), GetParameterOrDefault(optionsObject, "ipo-percentage", "5.0"), GetParameterOrDefault(optionsObject, "rename-percentage", "30.0"), GetParameterOrDefault(optionsObject, "splits-percentage", "15.0"), GetParameterOrDefault(optionsObject, "dividends-percentage", "60.0"), GetParameterOrDefault(optionsObject, "dividend-every-quarter-percentage", "30.0"), GetParameterOrDefault(optionsObject, "option-price-engine", "BaroneAdesiWhaleyApproximationEngine"), GetParameterOrDefault(optionsObject, "volatility-model-resolution", "Daily"), GetParameterOrDefault(optionsObject, "chain-symbol-count", "1"), tickers ); break; default: PrintMessageAndExit(1, "ERROR: Unrecognized --app value"); break; } } } } }
namespace BaseType.Migrations { using System; using System.Data.Entity.Migrations; public partial class baseInstall : DbMigration { public override void Up() { CreateTable( "dbo.AppJurnals", c => new { IdEntry = c.Guid(nullable: false), IdTask = c.Guid(nullable: false), DateEntry = c.DateTime(nullable: false), Message = c.String(nullable: false), MessageType = c.Int(nullable: false), MessageCode = c.Int(nullable: false), }) .PrimaryKey(t => t.IdEntry); CreateTable( "dbo.AspNetUserLogins", c => new { LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 200), UserId = c.Guid(nullable: false), }) .PrimaryKey(t => new { t.LoginProvider, t.ProviderKey, t.UserId }) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.Notivications", c => new { IdNotivication = c.Guid(nullable: false), Description = c.String(nullable: false, maxLength: 350), DateCreate = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"), TimeSend = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"), IdTask = c.Guid(nullable: false), IdUserFrom = c.Guid(), IdUserTo = c.Guid(), NotivicationStatus = c.Int(nullable: false), }) .PrimaryKey(t => t.IdNotivication) .ForeignKey("dbo.AspNetUsers", t => t.IdUserFrom) .ForeignKey("dbo.Tasks", t => t.IdTask, cascadeDelete: true) .ForeignKey("dbo.AspNetUsers", t => t.IdUserTo) .Index(t => t.IdTask) .Index(t => t.IdUserFrom) .Index(t => t.IdUserTo); CreateTable( "dbo.AspNetUsers", c => new { Id = c.Guid(nullable: false), Email = c.String(nullable: false, maxLength: 256), Surname = c.String(nullable: false, maxLength: 30), Name = c.String(nullable: false, maxLength: 25), MiddleName = c.String(maxLength: 30), BirthDate = c.DateTime(precision: 7, storeType: "datetime2"), PhoneNumber = c.String(maxLength: 20), IsWork = c.Boolean(nullable: false), Comment = c.String(maxLength: 250), Post = c.String(maxLength: 60), LockoutEndDateUtc = c.DateTime(precision: 7, storeType: "datetime2"), PasswordHash = c.String(maxLength: 800), SecurityStamp = c.String(maxLength: 200), EmailConfirmed = c.Boolean(nullable: false), PhoneNumberConfirmed = c.Boolean(nullable: false), TwoFactorEnabled = c.Boolean(nullable: false), LockoutEnabled = c.Boolean(nullable: false), AccessFailedCount = c.Int(nullable: false), UserName = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.Email, unique: true, name: "UK_Email") .Index(t => t.UserName, unique: true, name: "UserNameIndex"); CreateTable( "dbo.AspNetUserClaims", c => new { Id = c.Int(nullable: false, identity: true), UserId = c.Guid(nullable: false), ClaimType = c.String(), ClaimValue = c.String(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.Members", c => new { IdProject = c.Guid(nullable: false), IdUser = c.Guid(nullable: false), Role = c.Int(nullable: false), Comment = c.String(maxLength: 120), }) .PrimaryKey(t => new { t.IdProject, t.IdUser }) .ForeignKey("dbo.Projects", t => t.IdProject, cascadeDelete: true) .ForeignKey("dbo.AspNetUsers", t => t.IdUser, cascadeDelete: true) .Index(t => t.IdProject) .Index(t => t.IdUser); CreateTable( "dbo.Projects", c => new { IdProject = c.Guid(nullable: false), Name = c.String(maxLength: 70), Comment = c.String(maxLength: 90), Purpose = c.String(maxLength: 600), Status = c.Int(nullable: false), DateCreate = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"), DateUpdate = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"), TypeProject = c.Int(nullable: false), Author_Id = c.Guid(), }) .PrimaryKey(t => t.IdProject) .ForeignKey("dbo.AspNetUsers", t => t.Author_Id) .Index(t => t.Name, unique: true, name: "UK_ProjectName") .Index(t => t.Author_Id); CreateTable( "dbo.Tasks", c => new { IdTask = c.Guid(nullable: false), Author = c.Guid(nullable: false), Project = c.Guid(nullable: false), DateCreate = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"), DateFinish = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"), DateUpdate = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"), DateClose = c.DateTime(precision: 7, storeType: "datetime2"), TaskRating = c.Int(nullable: false), NameTask = c.String(nullable: false, maxLength: 160), Result = c.String(maxLength: 300), Description = c.String(maxLength: 700), Comment = c.String(maxLength: 600), ParentTask = c.Guid(nullable: false), Status = c.Int(nullable: false), Project_IdProject = c.Guid(), }) .PrimaryKey(t => t.IdTask) .ForeignKey("dbo.Projects", t => t.Project_IdProject) .Index(t => t.Project_IdProject); CreateTable( "dbo.WorkFiles", c => new { FileId = c.Guid(nullable: false), FileName = c.String(nullable: false, maxLength: 254), Comment = c.String(maxLength: 60), DateCreate = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"), Size = c.Int(nullable: false), Author_Id = c.Guid(), Catalog_IdTask = c.Guid(), }) .PrimaryKey(t => t.FileId) .ForeignKey("dbo.AspNetUsers", t => t.Author_Id) .ForeignKey("dbo.Tasks", t => t.Catalog_IdTask) .Index(t => t.Author_Id) .Index(t => t.Catalog_IdTask); Sql("alter table [dbo].[WorkFiles] ALTER COLUMN [FileId] add rowguidcol "); Sql("alter table [dbo].[WorkFiles] ADD [Data] varbinary(max) FILESTREAM NOT NULL"); CreateTable( "dbo.TaskComments", c => new { TaskCommentId = c.Guid(nullable: false), Message = c.String(nullable: false), DateMessage = c.DateTime(nullable: false, precision: 7, storeType: "datetime2"), Author_Id = c.Guid(nullable: false), Task_IdTask = c.Guid(nullable: false), }) .PrimaryKey(t => t.TaskCommentId) .ForeignKey("dbo.AspNetUsers", t => t.Author_Id, cascadeDelete: true) .ForeignKey("dbo.Tasks", t => t.Task_IdTask, cascadeDelete: true) .Index(t => t.Author_Id) .Index(t => t.Task_IdTask); CreateTable( "dbo.TaskMembers", c => new { IdTask = c.Guid(nullable: false), IdUser = c.Guid(nullable: false), Participation = c.Int(nullable: false), LevelNotivication = c.Int(nullable: false), TaskRole = c.Int(nullable: false), Comment = c.String(maxLength: 80), }) .PrimaryKey(t => new { t.IdTask, t.IdUser }) .ForeignKey("dbo.Tasks", t => t.IdTask, cascadeDelete: true) .ForeignKey("dbo.AspNetUsers", t => t.IdUser, cascadeDelete: true) .Index(t => t.IdTask) .Index(t => t.IdUser); CreateTable( "dbo.AspNetUserRoles", c => new { UserId = c.Guid(nullable: false), RoleId = c.Guid(nullable: false), }) .PrimaryKey(t => new { t.UserId, t.RoleId }) .ForeignKey("dbo.AspNetUsers", t => t.UserId, cascadeDelete: true) .ForeignKey("dbo.AspNetRoles", t => t.RoleId, cascadeDelete: true) .Index(t => t.UserId) .Index(t => t.RoleId); CreateTable( "dbo.AspNetRoles", c => new { Id = c.Guid(nullable: false), Name = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .Index(t => t.Name, unique: true, name: "RoleNameIndex"); } public override void Down() { DropForeignKey("dbo.AspNetUserRoles", "RoleId", "dbo.AspNetRoles"); DropForeignKey("dbo.Notivications", "IdUserTo", "dbo.AspNetUsers"); DropForeignKey("dbo.Notivications", "IdTask", "dbo.Tasks"); DropForeignKey("dbo.Notivications", "IdUserFrom", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserRoles", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.Members", "IdUser", "dbo.AspNetUsers"); DropForeignKey("dbo.Members", "IdProject", "dbo.Projects"); DropForeignKey("dbo.Tasks", "Project_IdProject", "dbo.Projects"); DropForeignKey("dbo.TaskMembers", "IdUser", "dbo.AspNetUsers"); DropForeignKey("dbo.TaskMembers", "IdTask", "dbo.Tasks"); DropForeignKey("dbo.TaskComments", "Task_IdTask", "dbo.Tasks"); DropForeignKey("dbo.TaskComments", "Author_Id", "dbo.AspNetUsers"); DropForeignKey("dbo.WorkFiles", "Catalog_IdTask", "dbo.Tasks"); DropForeignKey("dbo.WorkFiles", "Author_Id", "dbo.AspNetUsers"); DropForeignKey("dbo.Projects", "Author_Id", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserLogins", "UserId", "dbo.AspNetUsers"); DropForeignKey("dbo.AspNetUserClaims", "UserId", "dbo.AspNetUsers"); DropIndex("dbo.AspNetRoles", "RoleNameIndex"); DropIndex("dbo.AspNetUserRoles", new[] { "RoleId" }); DropIndex("dbo.AspNetUserRoles", new[] { "UserId" }); DropIndex("dbo.TaskMembers", new[] { "IdUser" }); DropIndex("dbo.TaskMembers", new[] { "IdTask" }); DropIndex("dbo.TaskComments", new[] { "Task_IdTask" }); DropIndex("dbo.TaskComments", new[] { "Author_Id" }); DropIndex("dbo.WorkFiles", new[] { "Catalog_IdTask" }); DropIndex("dbo.WorkFiles", new[] { "Author_Id" }); DropIndex("dbo.Tasks", new[] { "Project_IdProject" }); DropIndex("dbo.Projects", new[] { "Author_Id" }); DropIndex("dbo.Projects", "UK_ProjectName"); DropIndex("dbo.Members", new[] { "IdUser" }); DropIndex("dbo.Members", new[] { "IdProject" }); DropIndex("dbo.AspNetUserClaims", new[] { "UserId" }); DropIndex("dbo.AspNetUsers", "UserNameIndex"); DropIndex("dbo.AspNetUsers", "UK_Email"); DropIndex("dbo.Notivications", new[] { "IdUserTo" }); DropIndex("dbo.Notivications", new[] { "IdUserFrom" }); DropIndex("dbo.Notivications", new[] { "IdTask" }); DropIndex("dbo.AspNetUserLogins", new[] { "UserId" }); DropTable("dbo.AspNetRoles"); DropTable("dbo.AspNetUserRoles"); DropTable("dbo.TaskMembers"); DropTable("dbo.TaskComments"); DropTable("dbo.WorkFiles"); DropTable("dbo.Tasks"); DropTable("dbo.Projects"); DropTable("dbo.Members"); DropTable("dbo.AspNetUserClaims"); DropTable("dbo.AspNetUsers"); DropTable("dbo.Notivications"); DropTable("dbo.AspNetUserLogins"); DropTable("dbo.AppJurnals"); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Sitecore.Data.Managers; using Sitecore.Data.Templates; namespace Sitecore.DataBlaster { public class BulkItem { private string _itemPath; private readonly Dictionary<BulkFieldKey, BulkField> _fields = new Dictionary<BulkFieldKey, BulkField>(); /// <summary> /// Item id. /// </summary> public Guid Id { get; private set; } /// <summary> /// Item name /// </summary> public string Name { get; private set; } public Guid TemplateId { get; private set; } public Guid MasterId { get; private set; } public Guid ParentId { get; set; } /// <summary> /// Sitecore path of the item. /// </summary> /// <remarks>Could be null.</remarks> public string ItemPath { get { return _itemPath; } set { if (value == null) throw new ArgumentNullException(nameof(value)); _itemPath = value; this.Name = _itemPath.Split('/').Last(); } } public IEnumerable<BulkField> Fields => _fields.Values; public int FieldCount => _fields.Count; public BulkItem(Guid id, Guid templateId, Guid masterId, Guid parentId, string itemPath) { if (id == Guid.Empty) throw new ArgumentException("Id of item should not be an empty Guid.", nameof(id)); if (string.IsNullOrWhiteSpace(itemPath)) throw new ArgumentNullException(nameof(itemPath)); this.Id = id; this.TemplateId = templateId; this.MasterId = masterId; this.ParentId = parentId; this.ItemPath = itemPath; } protected BulkItem(BulkItem toCopy) { if (toCopy == null) throw new ArgumentNullException(nameof(toCopy)); this.Id = toCopy.Id; this.TemplateId = toCopy.TemplateId; this.MasterId = toCopy.MasterId; this.ParentId = toCopy.ParentId; this.ItemPath = toCopy.ItemPath; _fields = toCopy._fields.ToDictionary(x => x.Key, x => x.Value.CopyTo(this)); } private void AddField(BulkFieldKey key, string value, Func<Stream> blob = null, bool isBlob = false, string name = null, Action<BulkField> postProcessor = null) { if (value == null && !isBlob) return; BulkField field = null; if (key.Language == null && !key.Version.HasValue) { field = new SharedBulkField(this, key.FieldId, value, blob, isBlob, name); _fields.Add(key, field); } else if (key.Language != null && !key.Version.HasValue) { field = new UnversionedBulkField(this, key.FieldId, key.Language, value, blob, isBlob, name); _fields.Add(key, field); } else if (key.Language == null && key.Version.HasValue) { throw new ArgumentException("You cannot add a language specific field without a version."); } else { field = new VersionedBulkField(this, key.FieldId, key.Language, key.Version.Value, value, blob, isBlob, name); _fields.Add(key, field); } postProcessor?.Invoke(field); } /// <summary> /// Tries to add the field, returns false if the field with name and version already exists. /// </summary> public bool TryAddField(Guid id, string value, Func<Stream> blob = null, bool isBlob = false, string language = null, int? version = null, string name = null, Action<BulkField> postProcessor = null) { if (string.IsNullOrWhiteSpace(language)) language = null; var key = new BulkFieldKey(id, language, version); if (_fields.ContainsKey(key)) return false; AddField(key, value, blob, isBlob, name, postProcessor); return true; } public BulkItem AddField(Guid id, string value, Func<Stream> blob = null, bool isBlob = false, string language = null, int? version = null, string name = null, Action<BulkField> postProcessor = null) { if (value == null && !isBlob) return this; if (string.IsNullOrWhiteSpace(language)) language = null; AddField(new BulkFieldKey(id, language, version), value, blob, isBlob, name, postProcessor); return this; } public BulkItem AddField(TemplateField field, string value, Func<Stream> blob = null, bool isBlob = false, string language = null, int? version = null, Action<BulkField> postProcessor = null) { return AddField(field.ID.Guid, value, blob, isBlob, language, version, field.Name, postProcessor); } public BulkItem AddSharedField(Guid id, string value, Func<Stream> blob = null, bool isBlob = false, string name = null, Action<BulkField> postProcessor = null) { return AddField(id, value, blob, isBlob, null, null, name, postProcessor); } public BulkItem AddUnversionedField(Guid id, string language, string value, Func<Stream> blob = null, bool isBlob = false, string name = null, Action<BulkField> postProcessor = null) { return AddField(id, value, blob, isBlob, language, null, name, postProcessor); } public BulkItem AddVersionedField(Guid id, string language, int version, string value, Func<Stream> blob = null, bool isBlob = false, string name = null, Action<BulkField> postProcessor = null) { return AddField(id, value, blob, isBlob, language, version, name, postProcessor); } public BulkField GetField(Guid id, string language, int? version) { BulkField field; return _fields.TryGetValue(new BulkFieldKey(id, language, version), out field) ? field : null; } /// <summary> /// Statistics fields are necessary for correct working of Sitecore versions. /// If not correctly configured, publish might e.g not work. /// </summary> /// <param name="defaultLanguage">Default language will be added when no language version is present.</param> /// <param name="mandatoryLanguages">Language for which a version must be present.</param> /// <param name="timestampsOnly">Whether to only ensure created and updated fields.</param> /// <param name="forceUpdate">Forces modification date to always be set, not only when data is changed.</param> public void EnsureLanguageVersions(string defaultLanguage = null, IEnumerable<string> mandatoryLanguages = null, bool timestampsOnly = false, bool forceUpdate = false) { var user = Sitecore.Context.User.Name; var now = DateUtil.IsoNow; var versionsByLanguage = new Dictionary<string, HashSet<int>>(StringComparer.OrdinalIgnoreCase); // Detect versions by language from fields. foreach (var field in Fields.OfType<UnversionedBulkField>()) { var versioned = field as VersionedBulkField; var version = versioned?.Version ?? 1; HashSet<int> versions; if (versionsByLanguage.TryGetValue(field.Language, out versions)) versions.Add(version); else versionsByLanguage[field.Language] = new HashSet<int> { version }; } // Ensure mandatory languages. foreach (var language in mandatoryLanguages ?? Enumerable.Empty<string>()) { HashSet<int> versions; if (!versionsByLanguage.TryGetValue(language, out versions)) versionsByLanguage[language] = new HashSet<int> { 1 }; } // Add default version when no version is present. if (versionsByLanguage.Count == 0) versionsByLanguage[defaultLanguage ?? LanguageManager.DefaultLanguage.Name] = new HashSet<int> { 1 }; foreach (var languageVersion in versionsByLanguage .SelectMany(pair => pair.Value.Select(x => new { Language = pair.Key, Version = x }))) { TryAddField(FieldIDs.Created.Guid, now, language: languageVersion.Language, version: languageVersion.Version, name: "__Created", postProcessor: x => x.DependsOnCreate = true); TryAddField(FieldIDs.Updated.Guid, now, language: languageVersion.Language, version: languageVersion.Version, name: "__Updated", postProcessor: x => { if (!forceUpdate) x.DependsOnCreate = x.DependsOnUpdate = true; }); if (!timestampsOnly) { TryAddField(FieldIDs.CreatedBy.Guid, user, language: languageVersion.Language, version: languageVersion.Version, name: "__Created by", postProcessor: x => x.DependsOnCreate = true); TryAddField(FieldIDs.UpdatedBy.Guid, user, language: languageVersion.Language, version: languageVersion.Version, name: "__Updated by", postProcessor: x => x.DependsOnCreate = x.DependsOnUpdate = true); TryAddField(FieldIDs.Revision.Guid, Guid.NewGuid().ToString("D"), language: languageVersion.Language, version: languageVersion.Version, name: "__Revision", postProcessor: x => x.DependsOnCreate = x.DependsOnUpdate = true); } } } public string[] GetLanguages() { return Fields.OfType<UnversionedBulkField>().Select(x => x.Language).Distinct().ToArray(); } public string GetParentPath() { if (string.IsNullOrWhiteSpace(ItemPath)) return null; var idx = ItemPath.LastIndexOf("/", StringComparison.OrdinalIgnoreCase); if (idx < 0 || ItemPath.Length == idx + 1) return null; return ItemPath.Substring(0, idx); } private class BulkFieldKey { public Guid FieldId { get; private set; } public string Language { get; private set; } public int? Version { get; private set; } public BulkFieldKey(Guid fieldId, string language, int? version) { FieldId = fieldId; Language = language; Version = version; } public override string ToString() { return $"{FieldId} ({Language}#{Version})"; } private bool Equals(BulkFieldKey other) { return FieldId.Equals(other.FieldId) && string.Equals(Language, other.Language, StringComparison.OrdinalIgnoreCase) && Version == other.Version; } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((BulkFieldKey)obj); } public override int GetHashCode() { unchecked { return (FieldId.GetHashCode() * 397) ^ (Language == null ? 0 : StringComparer.OrdinalIgnoreCase.GetHashCode(Language)) ^ Version.GetHashCode(); } } } } }
// 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 Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Scripting; using Microsoft.CodeAnalysis.Scripting.CSharp; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Scripting.CSharp.Test { public class ScriptTests : CSharpTestBase { [Fact] public void TestCreateScript() { var script = CSharpScript.Create("1 + 2"); Assert.Equal("1 + 2", script.Code); } [Fact] public void TestGetCompilation() { var script = CSharpScript.Create("1 + 2"); var compilation = script.GetCompilation(); Assert.Equal(script.Code, compilation.SyntaxTrees.First().GetText().ToString()); } [Fact] public void TestCreateScriptDelegate() { // create a delegate for the entire script var script = CSharpScript.Create("1 + 2"); var fn = script.CreateDelegate(); var value = fn(); Assert.Equal(3, value); } [Fact] public void TestRunScript() { var result = CSharpScript.Run("1 + 2"); Assert.Equal(3, result.ReturnValue); } [Fact] public void TestCreateAndRunScript() { var script = CSharpScript.Create("1 + 2"); var result = script.Run(); Assert.Same(script, result.Script); Assert.Equal(3, result.ReturnValue); } [Fact] public void TestEvalScript() { var value = CSharpScript.Eval("1 + 2"); Assert.Equal(3, value); } [Fact] public void TestRunScriptWithSpecifiedReturnType() { var result = CSharpScript.Create("1 + 2").WithReturnType(typeof(int)).Run(); Assert.Equal(3, result.ReturnValue); } [Fact] public void TestRunVoidScript() { var result = CSharpScript.Run("Console.WriteLine(0);"); } [Fact(Skip = "Bug 170")] public void TestRunDynamicVoidScriptWithTerminatingSemicolon() { var result = CSharpScript.Run(@" class SomeClass { public void Do() { } } dynamic d = new SomeClass(); d.Do();" , ScriptOptions.Default.WithReferences(MscorlibRef, SystemRef, SystemCoreRef, CSharpRef)); } [Fact(Skip = "Bug 170")] public void TestRunDynamicVoidScriptWithoutTerminatingSemicolon() { var result = CSharpScript.Run(@" class SomeClass { public void Do() { } } dynamic d = new SomeClass(); d.Do()" , ScriptOptions.Default.WithReferences(MscorlibRef, SystemRef, SystemCoreRef, CSharpRef)); } public class Globals { public int X; public int Y; } [Fact] public void TestRunScriptWithGlobals() { var result = CSharpScript.Run("X + Y", new Globals { X = 1, Y = 2 }); Assert.Equal(3, result.ReturnValue); } [Fact] public void TestRunCreatedScriptWithExpectedGlobals() { var script = CSharpScript.Create("X + Y").WithGlobalsType(typeof(Globals)); var result = script.Run(new Globals { X = 1, Y = 2 }); Assert.Equal(3, result.ReturnValue); Assert.Same(script, result.Script); } [Fact] public void TestRunCreatedScriptWithUnexpectedGlobals() { var script = CSharpScript.Create("X + Y"); var result = script.Run(new Globals { X = 1, Y = 2 }); Assert.Equal(3, result.ReturnValue); // the end state of running the script should be based on a different script instance because of the globals // not matching the original script definition. Assert.NotSame(script, result.Script); } [Fact] public void TestRunScriptWithScriptState() { // run a script using another scripts end state as the starting state (globals) var result = CSharpScript.Run("int X = 100;"); var result2 = CSharpScript.Run("X + X", result); Assert.Equal(200, result2.ReturnValue); } [Fact] public void TestRepl() { string[] submissions = new[] { "int x = 100;", "int y = x * x;", "x + y" }; object input = null; ScriptState result = null; foreach (var submission in submissions) { result = CSharpScript.Run(submission, input); input = result; } Assert.Equal(10100, result.ReturnValue); } #if TODO // https://github.com/dotnet/roslyn/issues/3720 [Fact] public void TestCreateMethodDelegate() { // create a delegate to a method declared in the script var state = CSharpScript.Run("int Times(int x) { return x * x; }"); var fn = state.CreateDelegate<Func<int, int>>("Times"); var result = fn(5); Assert.Equal(25, result); } #endif [Fact] public void TestGetScriptVariableAfterRunningScript() { var result = CSharpScript.Run("int x = 100;"); var globals = result.Variables.Names.ToList(); Assert.Equal(1, globals.Count); Assert.Equal(true, globals.Contains("x")); Assert.Equal(true, result.Variables.ContainsVariable("x")); Assert.Equal(100, (int)result.Variables["x"].Value); } [Fact] public void TestBranchingSubscripts() { // run script to create declaration of M var result1 = CSharpScript.Run("int M(int x) { return x + x; }"); // run second script starting from first script's end state // this script's new declaration should hide the old declaration var result2 = CSharpScript.Run("int M(int x) { return x * x; } M(5)", result1); Assert.Equal(25, result2.ReturnValue); // run third script also starting from first script's end state // it should not see any declarations made by the second script. var result3 = CSharpScript.Run("M(5)", result1); Assert.Equal(10, result3.ReturnValue); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace System.ComponentModel { public class BackgroundWorker : Component { // Private instance members private bool _canCancelWorker = false; private bool _workerReportsProgress = false; private bool _cancellationPending = false; private bool _isRunning = false; private AsyncOperation _asyncOperation = null; private readonly SendOrPostCallback _operationCompleted; private readonly SendOrPostCallback _progressReporter; public BackgroundWorker() { _operationCompleted = new SendOrPostCallback(AsyncOperationCompleted); _progressReporter = new SendOrPostCallback(ProgressReporter); } private void AsyncOperationCompleted(object arg) { _isRunning = false; _cancellationPending = false; OnRunWorkerCompleted((RunWorkerCompletedEventArgs)arg); } public bool CancellationPending { get { return _cancellationPending; } } public void CancelAsync() { if (!WorkerSupportsCancellation) { throw new InvalidOperationException(SR.BackgroundWorker_WorkerDoesntSupportCancellation); } _cancellationPending = true; } public event DoWorkEventHandler DoWork; public bool IsBusy { get { return _isRunning; } } protected virtual void OnDoWork(DoWorkEventArgs e) { DoWorkEventHandler handler = DoWork; if (handler != null) { handler(this, e); } } protected virtual void OnRunWorkerCompleted(RunWorkerCompletedEventArgs e) { RunWorkerCompletedEventHandler handler = RunWorkerCompleted; if (handler != null) { handler(this, e); } } protected virtual void OnProgressChanged(ProgressChangedEventArgs e) { ProgressChangedEventHandler handler = ProgressChanged; if (handler != null) { handler(this, e); } } public event ProgressChangedEventHandler ProgressChanged; // Gets invoked through the AsyncOperation on the proper thread. private void ProgressReporter(object arg) { OnProgressChanged((ProgressChangedEventArgs)arg); } // Cause progress update to be posted through current AsyncOperation. public void ReportProgress(int percentProgress) { ReportProgress(percentProgress, null); } // Cause progress update to be posted through current AsyncOperation. public void ReportProgress(int percentProgress, object userState) { if (!WorkerReportsProgress) { throw new InvalidOperationException(SR.BackgroundWorker_WorkerDoesntReportProgress); } ProgressChangedEventArgs args = new ProgressChangedEventArgs(percentProgress, userState); if (_asyncOperation != null) { _asyncOperation.Post(_progressReporter, args); } else { _progressReporter(args); } } public void RunWorkerAsync() { RunWorkerAsync(null); } public void RunWorkerAsync(object argument) { if (_isRunning) { throw new InvalidOperationException(SR.BackgroundWorker_WorkerAlreadyRunning); } _isRunning = true; _cancellationPending = false; _asyncOperation = AsyncOperationManager.CreateOperation(null); Task.Factory.StartNew( (arg) => WorkerThreadStart(arg), argument, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default ); } public event RunWorkerCompletedEventHandler RunWorkerCompleted; public bool WorkerReportsProgress { get { return _workerReportsProgress; } set { _workerReportsProgress = value; } } public bool WorkerSupportsCancellation { get { return _canCancelWorker; } set { _canCancelWorker = value; } } private void WorkerThreadStart(object argument) { Debug.Assert(_asyncOperation != null, "_asyncOperation not initialized"); object workerResult = null; Exception error = null; bool cancelled = false; try { DoWorkEventArgs doWorkArgs = new DoWorkEventArgs(argument); OnDoWork(doWorkArgs); if (doWorkArgs.Cancel) { cancelled = true; } else { workerResult = doWorkArgs.Result; } } catch (Exception exception) { error = exception; } var e = new RunWorkerCompletedEventArgs(workerResult, error, cancelled); _asyncOperation.PostOperationCompleted(_operationCompleted, e); } protected override void Dispose(bool disposing) { } } }
/* * C# port of Mozilla Character Set Detector * https://code.google.com/p/chardetsharp/ * * Original Mozilla License Block follows * */ #region License Block // Version: MPL 1.1/GPL 2.0/LGPL 2.1 // // The contents of this file are subject to the Mozilla Public License Version // 1.1 (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.mozilla.org/MPL/ // // Software distributed under the License is distributed on an "AS IS" basis, // WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License // for the specific language governing rights and limitations under the // License. // // The Original Code is Mozilla Universal charset detector code. // // The Initial Developer of the Original Code is // Netscape Communications Corporation. // Portions created by the Initial Developer are Copyright (C) 2001 // the Initial Developer. All Rights Reserved. // // Contributor(s): // // Alternatively, the contents of this file may be used under the terms of // either the GNU General Public License Version 2 or later (the "GPL"), or // the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), // in which case the provisions of the GPL or the LGPL are applicable instead // of those above. If you wish to allow use of your version of this file only // under the terms of either the GPL or the LGPL, and not to allow others to // use your version of this file under the terms of the MPL, indicate your // decision by deleting the provisions above and replace them with the notice // and other provisions required by the GPL or the LGPL. If you do not delete // the provisions above, a recipient may use your version of this file under // the terms of any one of the MPL, the GPL or the LGPL. #endregion namespace Cloney.Core.CharsetDetection { internal partial class EUCKRDistributionAnalysis : CharDistributionAnalysis { //Sampling from about 20M text materials include literature and computer technology /****************************************************************************** * 128 --> 0.79 * 256 --> 0.92 * 512 --> 0.986 * 1024 --> 0.99944 * 2048 --> 0.99999 * * Idea Distribution Ratio = 0.98653 / (1-0.98653) = 73.24 * Random Distribution Ration = 512 / (2350-512) = 0.279. * * Typical Distribution Ratio *****************************************************************************/ const float EUCKR_TYPICAL_DISTRIBUTION_RATIO = 6.0f; //Char to FreqOrder table , static readonly int[] EUCKRCharToFreqOrder = new int[] { 13, 130, 120,1396, 481,1719,1720, 328, 609, 212,1721, 707, 400, 299,1722, 87, 1397,1723, 104, 536,1117,1203,1724,1267, 685,1268, 508,1725,1726,1727,1728,1398, 1399,1729,1730,1731, 141, 621, 326,1057, 368,1732, 267, 488, 20,1733,1269,1734, 945,1400,1735, 47, 904,1270,1736,1737, 773, 248,1738, 409, 313, 786, 429,1739, 116, 987, 813,1401, 683, 75,1204, 145,1740,1741,1742,1743, 16, 847, 667, 622, 708,1744,1745,1746, 966, 787, 304, 129,1747, 60, 820, 123, 676,1748,1749,1750, 1751, 617,1752, 626,1753,1754,1755,1756, 653,1757,1758,1759,1760,1761,1762, 856, 344,1763,1764,1765,1766, 89, 401, 418, 806, 905, 848,1767,1768,1769, 946,1205, 709,1770,1118,1771, 241,1772,1773,1774,1271,1775, 569,1776, 999,1777,1778,1779, 1780, 337, 751,1058, 28, 628, 254,1781, 177, 906, 270, 349, 891,1079,1782, 19, 1783, 379,1784, 315,1785, 629, 754,1402, 559,1786, 636, 203,1206,1787, 710, 567, 1788, 935, 814,1789,1790,1207, 766, 528,1791,1792,1208,1793,1794,1795,1796,1797, 1403,1798,1799, 533,1059,1404,1405,1156,1406, 936, 884,1080,1800, 351,1801,1802, 1803,1804,1805, 801,1806,1807,1808,1119,1809,1157, 714, 474,1407,1810, 298, 899, 885,1811,1120, 802,1158,1812, 892,1813,1814,1408, 659,1815,1816,1121,1817,1818, 1819,1820,1821,1822, 319,1823, 594, 545,1824, 815, 937,1209,1825,1826, 573,1409, 1022,1827,1210,1828,1829,1830,1831,1832,1833, 556, 722, 807,1122,1060,1834, 697, 1835, 900, 557, 715,1836,1410, 540,1411, 752,1159, 294, 597,1211, 976, 803, 770, 1412,1837,1838, 39, 794,1413, 358,1839, 371, 925,1840, 453, 661, 788, 531, 723, 544,1023,1081, 869, 91,1841, 392, 430, 790, 602,1414, 677,1082, 457,1415,1416, 1842,1843, 475, 327,1024,1417, 795, 121,1844, 733, 403,1418,1845,1846,1847, 300, 119, 711,1212, 627,1848,1272, 207,1849,1850, 796,1213, 382,1851, 519,1852,1083, 893,1853,1854,1855, 367, 809, 487, 671,1856, 663,1857,1858, 956, 471, 306, 857, 1859,1860,1160,1084,1861,1862,1863,1864,1865,1061,1866,1867,1868,1869,1870,1871, 282, 96, 574,1872, 502,1085,1873,1214,1874, 907,1875,1876, 827, 977,1419,1420, 1421, 268,1877,1422,1878,1879,1880, 308,1881, 2, 537,1882,1883,1215,1884,1885, 127, 791,1886,1273,1423,1887, 34, 336, 404, 643,1888, 571, 654, 894, 840,1889, 0, 886,1274, 122, 575, 260, 908, 938,1890,1275, 410, 316,1891,1892, 100,1893, 1894,1123, 48,1161,1124,1025,1895, 633, 901,1276,1896,1897, 115, 816,1898, 317, 1899, 694,1900, 909, 734,1424, 572, 866,1425, 691, 85, 524,1010, 543, 394, 841, 1901,1902,1903,1026,1904,1905,1906,1907,1908,1909, 30, 451, 651, 988, 310,1910, 1911,1426, 810,1216, 93,1912,1913,1277,1217,1914, 858, 759, 45, 58, 181, 610, 269,1915,1916, 131,1062, 551, 443,1000, 821,1427, 957, 895,1086,1917,1918, 375, 1919, 359,1920, 687,1921, 822,1922, 293,1923,1924, 40, 662, 118, 692, 29, 939, 887, 640, 482, 174,1925, 69,1162, 728,1428, 910,1926,1278,1218,1279, 386, 870, 217, 854,1163, 823,1927,1928,1929,1930, 834,1931, 78,1932, 859,1933,1063,1934, 1935,1936,1937, 438,1164, 208, 595,1938,1939,1940,1941,1219,1125,1942, 280, 888, 1429,1430,1220,1431,1943,1944,1945,1946,1947,1280, 150, 510,1432,1948,1949,1950, 1951,1952,1953,1954,1011,1087,1955,1433,1043,1956, 881,1957, 614, 958,1064,1065, 1221,1958, 638,1001, 860, 967, 896,1434, 989, 492, 553,1281,1165,1959,1282,1002, 1283,1222,1960,1961,1962,1963, 36, 383, 228, 753, 247, 454,1964, 876, 678,1965, 1966,1284, 126, 464, 490, 835, 136, 672, 529, 940,1088,1435, 473,1967,1968, 467, 50, 390, 227, 587, 279, 378, 598, 792, 968, 240, 151, 160, 849, 882,1126,1285, 639,1044, 133, 140, 288, 360, 811, 563,1027, 561, 142, 523,1969,1970,1971, 7, 103, 296, 439, 407, 506, 634, 990,1972,1973,1974,1975, 645,1976,1977,1978,1979, 1980,1981, 236,1982,1436,1983,1984,1089, 192, 828, 618, 518,1166, 333,1127,1985, 818,1223,1986,1987,1988,1989,1990,1991,1992,1993, 342,1128,1286, 746, 842,1994, 1995, 560, 223,1287, 98, 8, 189, 650, 978,1288,1996,1437,1997, 17, 345, 250, 423, 277, 234, 512, 226, 97, 289, 42, 167,1998, 201,1999,2000, 843, 836, 824, 532, 338, 783,1090, 182, 576, 436,1438,1439, 527, 500,2001, 947, 889,2002,2003, 2004,2005, 262, 600, 314, 447,2006, 547,2007, 693, 738,1129,2008, 71,1440, 745, 619, 688,2009, 829,2010,2011, 147,2012, 33, 948,2013,2014, 74, 224,2015, 61, 191, 918, 399, 637,2016,1028,1130, 257, 902,2017,2018,2019,2020,2021,2022,2023, 2024,2025,2026, 837,2027,2028,2029,2030, 179, 874, 591, 52, 724, 246,2031,2032, 2033,2034,1167, 969,2035,1289, 630, 605, 911,1091,1168,2036,2037,2038,1441, 912, 2039, 623,2040,2041, 253,1169,1290,2042,1442, 146, 620, 611, 577, 433,2043,1224, 719,1170, 959, 440, 437, 534, 84, 388, 480,1131, 159, 220, 198, 679,2044,1012, 819,1066,1443, 113,1225, 194, 318,1003,1029,2045,2046,2047,2048,1067,2049,2050, 2051,2052,2053, 59, 913, 112,2054, 632,2055, 455, 144, 739,1291,2056, 273, 681, 499,2057, 448,2058,2059, 760,2060,2061, 970, 384, 169, 245,1132,2062,2063, 414, 1444,2064,2065, 41, 235,2066, 157, 252, 877, 568, 919, 789, 580,2067, 725,2068, 2069,1292,2070,2071,1445,2072,1446,2073,2074, 55, 588, 66,1447, 271,1092,2075, 1226,2076, 960,1013, 372,2077,2078,2079,2080,2081,1293,2082,2083,2084,2085, 850, 2086,2087,2088,2089,2090, 186,2091,1068, 180,2092,2093,2094, 109,1227, 522, 606, 2095, 867,1448,1093, 991,1171, 926, 353,1133,2096, 581,2097,2098,2099,1294,1449, 1450,2100, 596,1172,1014,1228,2101,1451,1295,1173,1229,2102,2103,1296,1134,1452, 949,1135,2104,2105,1094,1453,1454,1455,2106,1095,2107,2108,2109,2110,2111,2112, 2113,2114,2115,2116,2117, 804,2118,2119,1230,1231, 805,1456, 405,1136,2120,2121, 2122,2123,2124, 720, 701,1297, 992,1457, 927,1004,2125,2126,2127,2128,2129,2130, 22, 417,2131, 303,2132, 385,2133, 971, 520, 513,2134,1174, 73,1096, 231, 274, 962,1458, 673,2135,1459,2136, 152,1137,2137,2138,2139,2140,1005,1138,1460,1139, 2141,2142,2143,2144, 11, 374, 844,2145, 154,1232, 46,1461,2146, 838, 830, 721, 1233, 106,2147, 90, 428, 462, 578, 566,1175, 352,2148,2149, 538,1234, 124,1298, 2150,1462, 761, 565,2151, 686,2152, 649,2153, 72, 173,2154, 460, 415,2155,1463, 2156,1235, 305,2157,2158,2159,2160,2161,2162, 579,2163,2164,2165,2166,2167, 747, 2168,2169,2170,2171,1464, 669,2172,2173,2174,2175,2176,1465,2177, 23, 530, 285, 2178, 335, 729,2179, 397,2180,2181,2182,1030,2183,2184, 698,2185,2186, 325,2187, 2188, 369,2189, 799,1097,1015, 348,2190,1069, 680,2191, 851,1466,2192,2193, 10, 2194, 613, 424,2195, 979, 108, 449, 589, 27, 172, 81,1031, 80, 774, 281, 350, 1032, 525, 301, 582,1176,2196, 674,1045,2197,2198,1467, 730, 762,2199,2200,2201, 2202,1468,2203, 993,2204,2205, 266,1070, 963,1140,2206,2207,2208, 664,1098, 972, 2209,2210,2211,1177,1469,1470, 871,2212,2213,2214,2215,2216,1471,2217,2218,2219, 2220,2221,2222,2223,2224,2225,2226,2227,1472,1236,2228,2229,2230,2231,2232,2233, 2234,2235,1299,2236,2237, 200,2238, 477, 373,2239,2240, 731, 825, 777,2241,2242, 2243, 521, 486, 548,2244,2245,2246,1473,1300, 53, 549, 137, 875, 76, 158,2247, 1301,1474, 469, 396,1016, 278, 712,2248, 321, 442, 503, 767, 744, 941,1237,1178, 1475,2249, 82, 178,1141,1179, 973,2250,1302,2251, 297,2252,2253, 570,2254,2255, 2256, 18, 450, 206,2257, 290, 292,1142,2258, 511, 162, 99, 346, 164, 735,2259, 1476,1477, 4, 554, 343, 798,1099,2260,1100,2261, 43, 171,1303, 139, 215,2262, 2263, 717, 775,2264,1033, 322, 216,2265, 831,2266, 149,2267,1304,2268,2269, 702, 1238, 135, 845, 347, 309,2270, 484,2271, 878, 655, 238,1006,1478,2272, 67,2273, 295,2274,2275, 461,2276, 478, 942, 412,2277,1034,2278,2279,2280, 265,2281, 541, 2282,2283,2284,2285,2286, 70, 852,1071,2287,2288,2289,2290, 21, 56, 509, 117, 432,2291,2292, 331, 980, 552,1101, 148, 284, 105, 393,1180,1239, 755,2293, 187, 2294,1046,1479,2295, 340,2296, 63,1047, 230,2297,2298,1305, 763,1306, 101, 800, 808, 494,2299,2300,2301, 903,2302, 37,1072, 14, 5,2303, 79, 675,2304, 312, 2305,2306,2307,2308,2309,1480, 6,1307,2310,2311,2312, 1, 470, 35, 24, 229, 2313, 695, 210, 86, 778, 15, 784, 592, 779, 32, 77, 855, 964,2314, 259,2315, 501, 380,2316,2317, 83, 981, 153, 689,1308,1481,1482,1483,2318,2319, 716,1484, 2320,2321,2322,2323,2324,2325,1485,2326,2327, 128, 57, 68, 261,1048, 211, 170, 1240, 31,2328, 51, 435, 742,2329,2330,2331, 635,2332, 264, 456,2333,2334,2335, 425,2336,1486, 143, 507, 263, 943,2337, 363, 920,1487, 256,1488,1102, 243, 601, 1489,2338,2339,2340,2341,2342,2343,2344, 861,2345,2346,2347,2348,2349,2350, 395, 2351,1490,1491, 62, 535, 166, 225,2352,2353, 668, 419,1241, 138, 604, 928,2354, 1181,2355,1492,1493,2356,2357,2358,1143,2359, 696,2360, 387, 307,1309, 682, 476, 2361,2362, 332, 12, 222, 156,2363, 232,2364, 641, 276, 656, 517,1494,1495,1035, 416, 736,1496,2365,1017, 586,2366,2367,2368,1497,2369, 242,2370,2371,2372,1498, 2373, 965, 713,2374,2375,2376,2377, 740, 982,1499, 944,1500,1007,2378,2379,1310, 1501,2380,2381,2382, 785, 329,2383,2384,1502,2385,2386,2387, 932,2388,1503,2389, 2390,2391,2392,1242,2393,2394,2395,2396,2397, 994, 950,2398,2399,2400,2401,1504, 1311,2402,2403,2404,2405,1049, 749,2406,2407, 853, 718,1144,1312,2408,1182,1505, 2409,2410, 255, 516, 479, 564, 550, 214,1506,1507,1313, 413, 239, 444, 339,1145, 1036,1508,1509,1314,1037,1510,1315,2411,1511,2412,2413,2414, 176, 703, 497, 624, 593, 921, 302,2415, 341, 165,1103,1512,2416,1513,2417,2418,2419, 376,2420, 700, 2421,2422,2423, 258, 768,1316,2424,1183,2425, 995, 608,2426,2427,2428,2429, 221, 2430,2431,2432,2433,2434,2435,2436,2437, 195, 323, 726, 188, 897, 983,1317, 377, 644,1050, 879,2438, 452,2439,2440,2441,2442,2443,2444, 914,2445,2446,2447,2448, 915, 489,2449,1514,1184,2450,2451, 515, 64, 427, 495,2452, 583,2453, 483, 485, 1038, 562, 213,1515, 748, 666,2454,2455,2456,2457, 334,2458, 780, 996,1008, 705, 1243,2459,2460,2461,2462,2463, 114,2464, 493,1146, 366, 163,1516, 961,1104,2465, 291,2466,1318,1105,2467,1517, 365,2468, 355, 951,1244,2469,1319,2470, 631,2471, 2472, 218,1320, 364, 320, 756,1518,1519,1321,1520,1322,2473,2474,2475,2476, 997, 2477,2478,2479,2480, 665,1185,2481, 916,1521,2482,2483,2484, 584, 684,2485,2486, 797,2487,1051,1186,2488,2489,2490,1522,2491,2492, 370,2493,1039,1187, 65,2494, 434, 205, 463,1188,2495, 125, 812, 391, 402, 826, 699, 286, 398, 155, 781, 771, 585,2496, 590, 505,1073,2497, 599, 244, 219, 917,1018, 952, 646,1523,2498,1323, 2499,2500, 49, 984, 354, 741,2501, 625,2502,1324,2503,1019, 190, 357, 757, 491, 95, 782, 868,2504,2505,2506,2507,2508,2509, 134,1524,1074, 422,1525, 898,2510, 161,2511,2512,2513,2514, 769,2515,1526,2516,2517, 411,1325,2518, 472,1527,2519, 2520,2521,2522,2523,2524, 985,2525,2526,2527,2528,2529,2530, 764,2531,1245,2532, 2533, 25, 204, 311,2534, 496,2535,1052,2536,2537,2538,2539,2540,2541,2542, 199, 704, 504, 468, 758, 657,1528, 196, 44, 839,1246, 272, 750,2543, 765, 862,2544, 2545,1326,2546, 132, 615, 933,2547, 732,2548,2549,2550,1189,1529,2551, 283,1247, 1053, 607, 929,2552,2553,2554, 930, 183, 872, 616,1040,1147,2555,1148,1020, 441, 249,1075,2556,2557,2558, 466, 743,2559,2560,2561, 92, 514, 426, 420, 526,2562, 2563,2564,2565,2566,2567,2568, 185,2569,2570,2571,2572, 776,1530, 658,2573, 362, 2574, 361, 922,1076, 793,2575,2576,2577,2578,2579,2580,1531, 251,2581,2582,2583, 2584,1532, 54, 612, 237,1327,2585,2586, 275, 408, 647, 111,2587,1533,1106, 465, 3, 458, 9, 38,2588, 107, 110, 890, 209, 26, 737, 498,2589,1534,2590, 431, 202, 88,1535, 356, 287,1107, 660,1149,2591, 381,1536, 986,1150, 445,1248,1151, 974,2592,2593, 846,2594, 446, 953, 184,1249,1250, 727,2595, 923, 193, 883,2596, 2597,2598, 102, 324, 539, 817,2599, 421,1041,2600, 832,2601, 94, 175, 197, 406, 2602, 459,2603,2604,2605,2606,2607, 330, 555,2608,2609,2610, 706,1108, 389,2611, 2612,2613,2614, 233,2615, 833, 558, 931, 954,1251,2616,2617,1537, 546,2618,2619, 1009,2620,2621,2622,1538, 690,1328,2623, 955,2624,1539,2625,2626, 772,2627,2628, 2629,2630,2631, 924, 648, 863, 603,2632,2633, 934,1540, 864, 865,2634, 642,1042, 670,1190,2635,2636,2637,2638, 168,2639, 652, 873, 542,1054,1541,2640,2641,2642, //512, 256 /*************************************************************************************** *Everything below is of no interest for detection purpose * *************************************************************************************** 2643,2644,2645,2646,2647,2648,2649,2650,2651,2652,2653,2654,2655,2656,2657,2658, 2659,2660,2661,2662,2663,2664,2665,2666,2667,2668,2669,2670,2671,2672,2673,2674, 2675,2676,2677,2678,2679,2680,2681,2682,2683,2684,2685,2686,2687,2688,2689,2690, 2691,2692,2693,2694,2695,2696,2697,2698,2699,1542, 880,2700,2701,2702,2703,2704, 2705,2706,2707,2708,2709,2710,2711,2712,2713,2714,2715,2716,2717,2718,2719,2720, 2721,2722,2723,2724,2725,1543,2726,2727,2728,2729,2730,2731,2732,1544,2733,2734, 2735,2736,2737,2738,2739,2740,2741,2742,2743,2744,2745,2746,2747,2748,2749,2750, 2751,2752,2753,2754,1545,2755,2756,2757,2758,2759,2760,2761,2762,2763,2764,2765, 2766,1546,2767,1547,2768,2769,2770,2771,2772,2773,2774,2775,2776,2777,2778,2779, 2780,2781,2782,2783,2784,2785,2786,1548,2787,2788,2789,1109,2790,2791,2792,2793, 2794,2795,2796,2797,2798,2799,2800,2801,2802,2803,2804,2805,2806,2807,2808,2809, 2810,2811,2812,1329,2813,2814,2815,2816,2817,2818,2819,2820,2821,2822,2823,2824, 2825,2826,2827,2828,2829,2830,2831,2832,2833,2834,2835,2836,2837,2838,2839,2840, 2841,2842,2843,2844,2845,2846,2847,2848,2849,2850,2851,2852,2853,2854,2855,2856, 1549,2857,2858,2859,2860,1550,2861,2862,1551,2863,2864,2865,2866,2867,2868,2869, 2870,2871,2872,2873,2874,1110,1330,2875,2876,2877,2878,2879,2880,2881,2882,2883, 2884,2885,2886,2887,2888,2889,2890,2891,2892,2893,2894,2895,2896,2897,2898,2899, 2900,2901,2902,2903,2904,2905,2906,2907,2908,2909,2910,2911,2912,2913,2914,2915, 2916,2917,2918,2919,2920,2921,2922,2923,2924,2925,2926,2927,2928,2929,2930,1331, 2931,2932,2933,2934,2935,2936,2937,2938,2939,2940,2941,2942,2943,1552,2944,2945, 2946,2947,2948,2949,2950,2951,2952,2953,2954,2955,2956,2957,2958,2959,2960,2961, 2962,2963,2964,1252,2965,2966,2967,2968,2969,2970,2971,2972,2973,2974,2975,2976, 2977,2978,2979,2980,2981,2982,2983,2984,2985,2986,2987,2988,2989,2990,2991,2992, 2993,2994,2995,2996,2997,2998,2999,3000,3001,3002,3003,3004,3005,3006,3007,3008, 3009,3010,3011,3012,1553,3013,3014,3015,3016,3017,1554,3018,1332,3019,3020,3021, 3022,3023,3024,3025,3026,3027,3028,3029,3030,3031,3032,3033,3034,3035,3036,3037, 3038,3039,3040,3041,3042,3043,3044,3045,3046,3047,3048,3049,3050,1555,3051,3052, 3053,1556,1557,3054,3055,3056,3057,3058,3059,3060,3061,3062,3063,3064,3065,3066, 3067,1558,3068,3069,3070,3071,3072,3073,3074,3075,3076,1559,3077,3078,3079,3080, 3081,3082,3083,1253,3084,3085,3086,3087,3088,3089,3090,3091,3092,3093,3094,3095, 3096,3097,3098,3099,3100,3101,3102,3103,3104,3105,3106,3107,3108,1152,3109,3110, 3111,3112,3113,1560,3114,3115,3116,3117,1111,3118,3119,3120,3121,3122,3123,3124, 3125,3126,3127,3128,3129,3130,3131,3132,3133,3134,3135,3136,3137,3138,3139,3140, 3141,3142,3143,3144,3145,3146,3147,3148,3149,3150,3151,3152,3153,3154,3155,3156, 3157,3158,3159,3160,3161,3162,3163,3164,3165,3166,3167,3168,3169,3170,3171,3172, 3173,3174,3175,3176,1333,3177,3178,3179,3180,3181,3182,3183,3184,3185,3186,3187, 3188,3189,1561,3190,3191,1334,3192,3193,3194,3195,3196,3197,3198,3199,3200,3201, 3202,3203,3204,3205,3206,3207,3208,3209,3210,3211,3212,3213,3214,3215,3216,3217, 3218,3219,3220,3221,3222,3223,3224,3225,3226,3227,3228,3229,3230,3231,3232,3233, 3234,1562,3235,3236,3237,3238,3239,3240,3241,3242,3243,3244,3245,3246,3247,3248, 3249,3250,3251,3252,3253,3254,3255,3256,3257,3258,3259,3260,3261,3262,3263,3264, 3265,3266,3267,3268,3269,3270,3271,3272,3273,3274,3275,3276,3277,1563,3278,3279, 3280,3281,3282,3283,3284,3285,3286,3287,3288,3289,3290,3291,3292,3293,3294,3295, 3296,3297,3298,3299,3300,3301,3302,3303,3304,3305,3306,3307,3308,3309,3310,3311, 3312,3313,3314,3315,3316,3317,3318,3319,3320,3321,3322,3323,3324,3325,3326,3327, 3328,3329,3330,3331,3332,3333,3334,3335,3336,3337,3338,3339,3340,3341,3342,3343, 3344,3345,3346,3347,3348,3349,3350,3351,3352,3353,3354,3355,3356,3357,3358,3359, 3360,3361,3362,3363,3364,1335,3365,3366,3367,3368,3369,3370,3371,3372,3373,3374, 3375,3376,3377,3378,3379,3380,3381,3382,3383,3384,3385,3386,3387,1336,3388,3389, 3390,3391,3392,3393,3394,3395,3396,3397,3398,3399,3400,3401,3402,3403,3404,3405, 3406,3407,3408,3409,3410,3411,3412,3413,3414,1337,3415,3416,3417,3418,3419,1338, 3420,3421,3422,1564,1565,3423,3424,3425,3426,3427,3428,3429,3430,3431,1254,3432, 3433,3434,1339,3435,3436,3437,3438,3439,1566,3440,3441,3442,3443,3444,3445,3446, 3447,3448,3449,3450,3451,3452,3453,3454,1255,3455,3456,3457,3458,3459,1567,1191, 3460,1568,1569,3461,3462,3463,1570,3464,3465,3466,3467,3468,1571,3469,3470,3471, 3472,3473,1572,3474,3475,3476,3477,3478,3479,3480,3481,3482,3483,3484,3485,3486, 1340,3487,3488,3489,3490,3491,3492,1021,3493,3494,3495,3496,3497,3498,1573,3499, 1341,3500,3501,3502,3503,3504,3505,3506,3507,3508,3509,3510,3511,1342,3512,3513, 3514,3515,3516,1574,1343,3517,3518,3519,1575,3520,1576,3521,3522,3523,3524,3525, 3526,3527,3528,3529,3530,3531,3532,3533,3534,3535,3536,3537,3538,3539,3540,3541, 3542,3543,3544,3545,3546,3547,3548,3549,3550,3551,3552,3553,3554,3555,3556,3557, 3558,3559,3560,3561,3562,3563,3564,3565,3566,3567,3568,3569,3570,3571,3572,3573, 3574,3575,3576,3577,3578,3579,3580,1577,3581,3582,1578,3583,3584,3585,3586,3587, 3588,3589,3590,3591,3592,3593,3594,3595,3596,3597,3598,3599,3600,3601,3602,3603, 3604,1579,3605,3606,3607,3608,3609,3610,3611,3612,3613,3614,3615,3616,3617,3618, 3619,3620,3621,3622,3623,3624,3625,3626,3627,3628,3629,1580,3630,3631,1581,3632, 3633,3634,3635,3636,3637,3638,3639,3640,3641,3642,3643,3644,3645,3646,3647,3648, 3649,3650,3651,3652,3653,3654,3655,3656,1582,3657,3658,3659,3660,3661,3662,3663, 3664,3665,3666,3667,3668,3669,3670,3671,3672,3673,3674,3675,3676,3677,3678,3679, 3680,3681,3682,3683,3684,3685,3686,3687,3688,3689,3690,3691,3692,3693,3694,3695, 3696,3697,3698,3699,3700,1192,3701,3702,3703,3704,1256,3705,3706,3707,3708,1583, 1257,3709,3710,3711,3712,3713,3714,3715,3716,1584,3717,3718,3719,3720,3721,3722, 3723,3724,3725,3726,3727,3728,3729,3730,3731,3732,3733,3734,3735,3736,3737,3738, 3739,3740,3741,3742,3743,3744,3745,1344,3746,3747,3748,3749,3750,3751,3752,3753, 3754,3755,3756,1585,3757,3758,3759,3760,3761,3762,3763,3764,3765,3766,1586,3767, 3768,3769,3770,3771,3772,3773,3774,3775,3776,3777,3778,1345,3779,3780,3781,3782, 3783,3784,3785,3786,3787,3788,3789,3790,3791,3792,3793,3794,3795,1346,1587,3796, 3797,1588,3798,3799,3800,3801,3802,3803,3804,3805,3806,1347,3807,3808,3809,3810, 3811,1589,3812,3813,3814,3815,3816,3817,3818,3819,3820,3821,1590,3822,3823,1591, 1348,3824,3825,3826,3827,3828,3829,3830,1592,3831,3832,1593,3833,3834,3835,3836, 3837,3838,3839,3840,3841,3842,3843,3844,1349,3845,3846,3847,3848,3849,3850,3851, 3852,3853,3854,3855,3856,3857,3858,1594,3859,3860,3861,3862,3863,3864,3865,3866, 3867,3868,3869,1595,3870,3871,3872,3873,1596,3874,3875,3876,3877,3878,3879,3880, 3881,3882,3883,3884,3885,3886,1597,3887,3888,3889,3890,3891,3892,3893,3894,3895, 1598,3896,3897,3898,1599,1600,3899,1350,3900,1351,3901,3902,1352,3903,3904,3905, 3906,3907,3908,3909,3910,3911,3912,3913,3914,3915,3916,3917,3918,3919,3920,3921, 3922,3923,3924,1258,3925,3926,3927,3928,3929,3930,3931,1193,3932,1601,3933,3934, 3935,3936,3937,3938,3939,3940,3941,3942,3943,1602,3944,3945,3946,3947,3948,1603, 3949,3950,3951,3952,3953,3954,3955,3956,3957,3958,3959,3960,3961,3962,3963,3964, 3965,1604,3966,3967,3968,3969,3970,3971,3972,3973,3974,3975,3976,3977,1353,3978, 3979,3980,3981,3982,3983,3984,3985,3986,3987,3988,3989,3990,3991,1354,3992,3993, 3994,3995,3996,3997,3998,3999,4000,4001,4002,4003,4004,4005,4006,4007,4008,4009, 4010,4011,4012,4013,4014,4015,4016,4017,4018,4019,4020,4021,4022,4023,1355,4024, 4025,4026,4027,4028,4029,4030,4031,4032,4033,4034,4035,4036,4037,4038,4039,4040, 1605,4041,4042,4043,4044,4045,4046,4047,4048,4049,4050,4051,4052,4053,4054,4055, 4056,4057,4058,4059,4060,1606,4061,4062,4063,4064,1607,4065,4066,4067,4068,4069, 4070,4071,4072,4073,4074,4075,4076,1194,4077,4078,1608,4079,4080,4081,4082,4083, 4084,4085,4086,4087,1609,4088,4089,4090,4091,4092,4093,4094,4095,4096,4097,4098, 4099,4100,4101,4102,4103,4104,4105,4106,4107,4108,1259,4109,4110,4111,4112,4113, 4114,4115,4116,4117,4118,4119,4120,4121,4122,4123,4124,1195,4125,4126,4127,1610, 4128,4129,4130,4131,4132,4133,4134,4135,4136,4137,1356,4138,4139,4140,4141,4142, 4143,4144,1611,4145,4146,4147,4148,4149,4150,4151,4152,4153,4154,4155,4156,4157, 4158,4159,4160,4161,4162,4163,4164,4165,4166,4167,4168,4169,4170,4171,4172,4173, 4174,4175,4176,4177,4178,4179,4180,4181,4182,4183,4184,4185,4186,4187,4188,4189, 4190,4191,4192,4193,4194,4195,4196,4197,4198,4199,4200,4201,4202,4203,4204,4205, 4206,4207,4208,4209,4210,4211,4212,4213,4214,4215,4216,4217,4218,4219,1612,4220, 4221,4222,4223,4224,4225,4226,4227,1357,4228,1613,4229,4230,4231,4232,4233,4234, 4235,4236,4237,4238,4239,4240,4241,4242,4243,1614,4244,4245,4246,4247,4248,4249, 4250,4251,4252,4253,4254,4255,4256,4257,4258,4259,4260,4261,4262,4263,4264,4265, 4266,4267,4268,4269,4270,1196,1358,4271,4272,4273,4274,4275,4276,4277,4278,4279, 4280,4281,4282,4283,4284,4285,4286,4287,1615,4288,4289,4290,4291,4292,4293,4294, 4295,4296,4297,4298,4299,4300,4301,4302,4303,4304,4305,4306,4307,4308,4309,4310, 4311,4312,4313,4314,4315,4316,4317,4318,4319,4320,4321,4322,4323,4324,4325,4326, 4327,4328,4329,4330,4331,4332,4333,4334,1616,4335,4336,4337,4338,4339,4340,4341, 4342,4343,4344,4345,4346,4347,4348,4349,4350,4351,4352,4353,4354,4355,4356,4357, 4358,4359,4360,1617,4361,4362,4363,4364,4365,1618,4366,4367,4368,4369,4370,4371, 4372,4373,4374,4375,4376,4377,4378,4379,4380,4381,4382,4383,4384,4385,4386,4387, 4388,4389,4390,4391,4392,4393,4394,4395,4396,4397,4398,4399,4400,4401,4402,4403, 4404,4405,4406,4407,4408,4409,4410,4411,4412,4413,4414,4415,4416,1619,4417,4418, 4419,4420,4421,4422,4423,4424,4425,1112,4426,4427,4428,4429,4430,1620,4431,4432, 4433,4434,4435,4436,4437,4438,4439,4440,4441,4442,1260,1261,4443,4444,4445,4446, 4447,4448,4449,4450,4451,4452,4453,4454,4455,1359,4456,4457,4458,4459,4460,4461, 4462,4463,4464,4465,1621,4466,4467,4468,4469,4470,4471,4472,4473,4474,4475,4476, 4477,4478,4479,4480,4481,4482,4483,4484,4485,4486,4487,4488,4489,1055,4490,4491, 4492,4493,4494,4495,4496,4497,4498,4499,4500,4501,4502,4503,4504,4505,4506,4507, 4508,4509,4510,4511,4512,4513,4514,4515,4516,4517,4518,1622,4519,4520,4521,1623, 4522,4523,4524,4525,4526,4527,4528,4529,4530,4531,4532,4533,4534,4535,1360,4536, 4537,4538,4539,4540,4541,4542,4543, 975,4544,4545,4546,4547,4548,4549,4550,4551, 4552,4553,4554,4555,4556,4557,4558,4559,4560,4561,4562,4563,4564,4565,4566,4567, 4568,4569,4570,4571,1624,4572,4573,4574,4575,4576,1625,4577,4578,4579,4580,4581, 4582,4583,4584,1626,4585,4586,4587,4588,4589,4590,4591,4592,4593,4594,4595,1627, 4596,4597,4598,4599,4600,4601,4602,4603,4604,4605,4606,4607,4608,4609,4610,4611, 4612,4613,4614,4615,1628,4616,4617,4618,4619,4620,4621,4622,4623,4624,4625,4626, 4627,4628,4629,4630,4631,4632,4633,4634,4635,4636,4637,4638,4639,4640,4641,4642, 4643,4644,4645,4646,4647,4648,4649,1361,4650,4651,4652,4653,4654,4655,4656,4657, 4658,4659,4660,4661,1362,4662,4663,4664,4665,4666,4667,4668,4669,4670,4671,4672, 4673,4674,4675,4676,4677,4678,4679,4680,4681,4682,1629,4683,4684,4685,4686,4687, 1630,4688,4689,4690,4691,1153,4692,4693,4694,1113,4695,4696,4697,4698,4699,4700, 4701,4702,4703,4704,4705,4706,4707,4708,4709,4710,4711,1197,4712,4713,4714,4715, 4716,4717,4718,4719,4720,4721,4722,4723,4724,4725,4726,4727,4728,4729,4730,4731, 4732,4733,4734,4735,1631,4736,1632,4737,4738,4739,4740,4741,4742,4743,4744,1633, 4745,4746,4747,4748,4749,1262,4750,4751,4752,4753,4754,1363,4755,4756,4757,4758, 4759,4760,4761,4762,4763,4764,4765,4766,4767,4768,1634,4769,4770,4771,4772,4773, 4774,4775,4776,4777,4778,1635,4779,4780,4781,4782,4783,4784,4785,4786,4787,4788, 4789,1636,4790,4791,4792,4793,4794,4795,4796,4797,4798,4799,4800,4801,4802,4803, 4804,4805,4806,1637,4807,4808,4809,1638,4810,4811,4812,4813,4814,4815,4816,4817, 4818,1639,4819,4820,4821,4822,4823,4824,4825,4826,4827,4828,4829,4830,4831,4832, 4833,1077,4834,4835,4836,4837,4838,4839,4840,4841,4842,4843,4844,4845,4846,4847, 4848,4849,4850,4851,4852,4853,4854,4855,4856,4857,4858,4859,4860,4861,4862,4863, 4864,4865,4866,4867,4868,4869,4870,4871,4872,4873,4874,4875,4876,4877,4878,4879, 4880,4881,4882,4883,1640,4884,4885,1641,4886,4887,4888,4889,4890,4891,4892,4893, 4894,4895,4896,4897,4898,4899,4900,4901,4902,4903,4904,4905,4906,4907,4908,4909, 4910,4911,1642,4912,4913,4914,1364,4915,4916,4917,4918,4919,4920,4921,4922,4923, 4924,4925,4926,4927,4928,4929,4930,4931,1643,4932,4933,4934,4935,4936,4937,4938, 4939,4940,4941,4942,4943,4944,4945,4946,4947,4948,4949,4950,4951,4952,4953,4954, 4955,4956,4957,4958,4959,4960,4961,4962,4963,4964,4965,4966,4967,4968,4969,4970, 4971,4972,4973,4974,4975,4976,4977,4978,4979,4980,1644,4981,4982,4983,4984,1645, 4985,4986,1646,4987,4988,4989,4990,4991,4992,4993,4994,4995,4996,4997,4998,4999, 5000,5001,5002,5003,5004,5005,1647,5006,1648,5007,5008,5009,5010,5011,5012,1078, 5013,5014,5015,5016,5017,5018,5019,5020,5021,5022,5023,5024,5025,5026,5027,5028, 1365,5029,5030,5031,5032,5033,5034,5035,5036,5037,5038,5039,1649,5040,5041,5042, 5043,5044,5045,1366,5046,5047,5048,5049,5050,5051,5052,5053,5054,5055,1650,5056, 5057,5058,5059,5060,5061,5062,5063,5064,5065,5066,5067,5068,5069,5070,5071,5072, 5073,5074,5075,5076,5077,1651,5078,5079,5080,5081,5082,5083,5084,5085,5086,5087, 5088,5089,5090,5091,5092,5093,5094,5095,5096,5097,5098,5099,5100,5101,5102,5103, 5104,5105,5106,5107,5108,5109,5110,1652,5111,5112,5113,5114,5115,5116,5117,5118, 1367,5119,5120,5121,5122,5123,5124,5125,5126,5127,5128,5129,1653,5130,5131,5132, 5133,5134,5135,5136,5137,5138,5139,5140,5141,5142,5143,5144,5145,5146,5147,5148, 5149,1368,5150,1654,5151,1369,5152,5153,5154,5155,5156,5157,5158,5159,5160,5161, 5162,5163,5164,5165,5166,5167,5168,5169,5170,5171,5172,5173,5174,5175,5176,5177, 5178,1370,5179,5180,5181,5182,5183,5184,5185,5186,5187,5188,5189,5190,5191,5192, 5193,5194,5195,5196,5197,5198,1655,5199,5200,5201,5202,1656,5203,5204,5205,5206, 1371,5207,1372,5208,5209,5210,5211,1373,5212,5213,1374,5214,5215,5216,5217,5218, 5219,5220,5221,5222,5223,5224,5225,5226,5227,5228,5229,5230,5231,5232,5233,5234, 5235,5236,5237,5238,5239,5240,5241,5242,5243,5244,5245,5246,5247,1657,5248,5249, 5250,5251,1658,1263,5252,5253,5254,5255,5256,1375,5257,5258,5259,5260,5261,5262, 5263,5264,5265,5266,5267,5268,5269,5270,5271,5272,5273,5274,5275,5276,5277,5278, 5279,5280,5281,5282,5283,1659,5284,5285,5286,5287,5288,5289,5290,5291,5292,5293, 5294,5295,5296,5297,5298,5299,5300,1660,5301,5302,5303,5304,5305,5306,5307,5308, 5309,5310,5311,5312,5313,5314,5315,5316,5317,5318,5319,5320,5321,1376,5322,5323, 5324,5325,5326,5327,5328,5329,5330,5331,5332,5333,1198,5334,5335,5336,5337,5338, 5339,5340,5341,5342,5343,1661,5344,5345,5346,5347,5348,5349,5350,5351,5352,5353, 5354,5355,5356,5357,5358,5359,5360,5361,5362,5363,5364,5365,5366,5367,5368,5369, 5370,5371,5372,5373,5374,5375,5376,5377,5378,5379,5380,5381,5382,5383,5384,5385, 5386,5387,5388,5389,5390,5391,5392,5393,5394,5395,5396,5397,5398,1264,5399,5400, 5401,5402,5403,5404,5405,5406,5407,5408,5409,5410,5411,5412,1662,5413,5414,5415, 5416,1663,5417,5418,5419,5420,5421,5422,5423,5424,5425,5426,5427,5428,5429,5430, 5431,5432,5433,5434,5435,5436,5437,5438,1664,5439,5440,5441,5442,5443,5444,5445, 5446,5447,5448,5449,5450,5451,5452,5453,5454,5455,5456,5457,5458,5459,5460,5461, 5462,5463,5464,5465,5466,5467,5468,5469,5470,5471,5472,5473,5474,5475,5476,5477, 5478,1154,5479,5480,5481,5482,5483,5484,5485,1665,5486,5487,5488,5489,5490,5491, 5492,5493,5494,5495,5496,5497,5498,5499,5500,5501,5502,5503,5504,5505,5506,5507, 5508,5509,5510,5511,5512,5513,5514,5515,5516,5517,5518,5519,5520,5521,5522,5523, 5524,5525,5526,5527,5528,5529,5530,5531,5532,5533,5534,5535,5536,5537,5538,5539, 5540,5541,5542,5543,5544,5545,5546,5547,5548,1377,5549,5550,5551,5552,5553,5554, 5555,5556,5557,5558,5559,5560,5561,5562,5563,5564,5565,5566,5567,5568,5569,5570, 1114,5571,5572,5573,5574,5575,5576,5577,5578,5579,5580,5581,5582,5583,5584,5585, 5586,5587,5588,5589,5590,5591,5592,1378,5593,5594,5595,5596,5597,5598,5599,5600, 5601,5602,5603,5604,5605,5606,5607,5608,5609,5610,5611,5612,5613,5614,1379,5615, 5616,5617,5618,5619,5620,5621,5622,5623,5624,5625,5626,5627,5628,5629,5630,5631, 5632,5633,5634,1380,5635,5636,5637,5638,5639,5640,5641,5642,5643,5644,5645,5646, 5647,5648,5649,1381,1056,5650,5651,5652,5653,5654,5655,5656,5657,5658,5659,5660, 1666,5661,5662,5663,5664,5665,5666,5667,5668,1667,5669,1668,5670,5671,5672,5673, 5674,5675,5676,5677,5678,1155,5679,5680,5681,5682,5683,5684,5685,5686,5687,5688, 5689,5690,5691,5692,5693,5694,5695,5696,5697,5698,1669,5699,5700,5701,5702,5703, 5704,5705,1670,5706,5707,5708,5709,5710,1671,5711,5712,5713,5714,1382,5715,5716, 5717,5718,5719,5720,5721,5722,5723,5724,5725,1672,5726,5727,1673,1674,5728,5729, 5730,5731,5732,5733,5734,5735,5736,1675,5737,5738,5739,5740,5741,5742,5743,5744, 1676,5745,5746,5747,5748,5749,5750,5751,1383,5752,5753,5754,5755,5756,5757,5758, 5759,5760,5761,5762,5763,5764,5765,5766,5767,5768,1677,5769,5770,5771,5772,5773, 1678,5774,5775,5776, 998,5777,5778,5779,5780,5781,5782,5783,5784,5785,1384,5786, 5787,5788,5789,5790,5791,5792,5793,5794,5795,5796,5797,5798,5799,5800,1679,5801, 5802,5803,1115,1116,5804,5805,5806,5807,5808,5809,5810,5811,5812,5813,5814,5815, 5816,5817,5818,5819,5820,5821,5822,5823,5824,5825,5826,5827,5828,5829,5830,5831, 5832,5833,5834,5835,5836,5837,5838,5839,5840,5841,5842,5843,5844,5845,5846,5847, 5848,5849,5850,5851,5852,5853,5854,5855,1680,5856,5857,5858,5859,5860,5861,5862, 5863,5864,1681,5865,5866,5867,1682,5868,5869,5870,5871,5872,5873,5874,5875,5876, 5877,5878,5879,1683,5880,1684,5881,5882,5883,5884,1685,5885,5886,5887,5888,5889, 5890,5891,5892,5893,5894,5895,5896,5897,5898,5899,5900,5901,5902,5903,5904,5905, 5906,5907,1686,5908,5909,5910,5911,5912,5913,5914,5915,5916,5917,5918,5919,5920, 5921,5922,5923,5924,5925,5926,5927,5928,5929,5930,5931,5932,5933,5934,5935,1687, 5936,5937,5938,5939,5940,5941,5942,5943,5944,5945,5946,5947,5948,5949,5950,5951, 5952,1688,1689,5953,1199,5954,5955,5956,5957,5958,5959,5960,5961,1690,5962,5963, 5964,5965,5966,5967,5968,5969,5970,5971,5972,5973,5974,5975,5976,5977,5978,5979, 5980,5981,1385,5982,1386,5983,5984,5985,5986,5987,5988,5989,5990,5991,5992,5993, 5994,5995,5996,5997,5998,5999,6000,6001,6002,6003,6004,6005,6006,6007,6008,6009, 6010,6011,6012,6013,6014,6015,6016,6017,6018,6019,6020,6021,6022,6023,6024,6025, 6026,6027,1265,6028,6029,1691,6030,6031,6032,6033,6034,6035,6036,6037,6038,6039, 6040,6041,6042,6043,6044,6045,6046,6047,6048,6049,6050,6051,6052,6053,6054,6055, 6056,6057,6058,6059,6060,6061,6062,6063,6064,6065,6066,6067,6068,6069,6070,6071, 6072,6073,6074,6075,6076,6077,6078,6079,6080,6081,6082,6083,6084,1692,6085,6086, 6087,6088,6089,6090,6091,6092,6093,6094,6095,6096,6097,6098,6099,6100,6101,6102, 6103,6104,6105,6106,6107,6108,6109,6110,6111,6112,6113,6114,6115,6116,6117,6118, 6119,6120,6121,6122,6123,6124,6125,6126,6127,6128,6129,6130,6131,1693,6132,6133, 6134,6135,6136,1694,6137,6138,6139,6140,6141,1695,6142,6143,6144,6145,6146,6147, 6148,6149,6150,6151,6152,6153,6154,6155,6156,6157,6158,6159,6160,6161,6162,6163, 6164,6165,6166,6167,6168,6169,6170,6171,6172,6173,6174,6175,6176,6177,6178,6179, 6180,6181,6182,6183,6184,6185,1696,6186,6187,6188,6189,6190,6191,6192,6193,6194, 6195,6196,6197,6198,6199,6200,6201,6202,6203,6204,6205,6206,6207,6208,6209,6210, 6211,6212,6213,6214,6215,6216,6217,6218,6219,1697,6220,6221,6222,6223,6224,6225, 6226,6227,6228,6229,6230,6231,6232,6233,6234,6235,6236,6237,6238,6239,6240,6241, 6242,6243,6244,6245,6246,6247,6248,6249,6250,6251,6252,6253,1698,6254,6255,6256, 6257,6258,6259,6260,6261,6262,6263,1200,6264,6265,6266,6267,6268,6269,6270,6271, //1024 6272,6273,6274,6275,6276,6277,6278,6279,6280,6281,6282,6283,6284,6285,6286,6287, 6288,6289,6290,6291,6292,6293,6294,6295,6296,6297,6298,6299,6300,6301,6302,1699, 6303,6304,1700,6305,6306,6307,6308,6309,6310,6311,6312,6313,6314,6315,6316,6317, 6318,6319,6320,6321,6322,6323,6324,6325,6326,6327,6328,6329,6330,6331,6332,6333, 6334,6335,6336,6337,6338,6339,1701,6340,6341,6342,6343,6344,1387,6345,6346,6347, 6348,6349,6350,6351,6352,6353,6354,6355,6356,6357,6358,6359,6360,6361,6362,6363, 6364,6365,6366,6367,6368,6369,6370,6371,6372,6373,6374,6375,6376,6377,6378,6379, 6380,6381,6382,6383,6384,6385,6386,6387,6388,6389,6390,6391,6392,6393,6394,6395, 6396,6397,6398,6399,6400,6401,6402,6403,6404,6405,6406,6407,6408,6409,6410,6411, 6412,6413,1702,6414,6415,6416,6417,6418,6419,6420,6421,6422,1703,6423,6424,6425, 6426,6427,6428,6429,6430,6431,6432,6433,6434,6435,6436,6437,6438,1704,6439,6440, 6441,6442,6443,6444,6445,6446,6447,6448,6449,6450,6451,6452,6453,6454,6455,6456, 6457,6458,6459,6460,6461,6462,6463,6464,6465,6466,6467,6468,6469,6470,6471,6472, 6473,6474,6475,6476,6477,6478,6479,6480,6481,6482,6483,6484,6485,6486,6487,6488, 6489,6490,6491,6492,6493,6494,6495,6496,6497,6498,6499,6500,6501,6502,6503,1266, 6504,6505,6506,6507,6508,6509,6510,6511,6512,6513,6514,6515,6516,6517,6518,6519, 6520,6521,6522,6523,6524,6525,6526,6527,6528,6529,6530,6531,6532,6533,6534,6535, 6536,6537,6538,6539,6540,6541,6542,6543,6544,6545,6546,6547,6548,6549,6550,6551, 1705,1706,6552,6553,6554,6555,6556,6557,6558,6559,6560,6561,6562,6563,6564,6565, 6566,6567,6568,6569,6570,6571,6572,6573,6574,6575,6576,6577,6578,6579,6580,6581, 6582,6583,6584,6585,6586,6587,6588,6589,6590,6591,6592,6593,6594,6595,6596,6597, 6598,6599,6600,6601,6602,6603,6604,6605,6606,6607,6608,6609,6610,6611,6612,6613, 6614,6615,6616,6617,6618,6619,6620,6621,6622,6623,6624,6625,6626,6627,6628,6629, 6630,6631,6632,6633,6634,6635,6636,6637,1388,6638,6639,6640,6641,6642,6643,6644, 1707,6645,6646,6647,6648,6649,6650,6651,6652,6653,6654,6655,6656,6657,6658,6659, 6660,6661,6662,6663,1708,6664,6665,6666,6667,6668,6669,6670,6671,6672,6673,6674, 1201,6675,6676,6677,6678,6679,6680,6681,6682,6683,6684,6685,6686,6687,6688,6689, 6690,6691,6692,6693,6694,6695,6696,6697,6698,6699,6700,6701,6702,6703,6704,6705, 6706,6707,6708,6709,6710,6711,6712,6713,6714,6715,6716,6717,6718,6719,6720,6721, 6722,6723,6724,6725,1389,6726,6727,6728,6729,6730,6731,6732,6733,6734,6735,6736, 1390,1709,6737,6738,6739,6740,6741,6742,1710,6743,6744,6745,6746,1391,6747,6748, 6749,6750,6751,6752,6753,6754,6755,6756,6757,1392,6758,6759,6760,6761,6762,6763, 6764,6765,6766,6767,6768,6769,6770,6771,6772,6773,6774,6775,6776,6777,6778,6779, 6780,1202,6781,6782,6783,6784,6785,6786,6787,6788,6789,6790,6791,6792,6793,6794, 6795,6796,6797,6798,6799,6800,6801,6802,6803,6804,6805,6806,6807,6808,6809,1711, 6810,6811,6812,6813,6814,6815,6816,6817,6818,6819,6820,6821,6822,6823,6824,6825, 6826,6827,6828,6829,6830,6831,6832,6833,6834,6835,6836,1393,6837,6838,6839,6840, 6841,6842,6843,6844,6845,6846,6847,6848,6849,6850,6851,6852,6853,6854,6855,6856, 6857,6858,6859,6860,6861,6862,6863,6864,6865,6866,6867,6868,6869,6870,6871,6872, 6873,6874,6875,6876,6877,6878,6879,6880,6881,6882,6883,6884,6885,6886,6887,6888, 6889,6890,6891,6892,6893,6894,6895,6896,6897,6898,6899,6900,6901,6902,1712,6903, 6904,6905,6906,6907,6908,6909,6910,1713,6911,6912,6913,6914,6915,6916,6917,6918, 6919,6920,6921,6922,6923,6924,6925,6926,6927,6928,6929,6930,6931,6932,6933,6934, 6935,6936,6937,6938,6939,6940,6941,6942,6943,6944,6945,6946,6947,6948,6949,6950, 6951,6952,6953,6954,6955,6956,6957,6958,6959,6960,6961,6962,6963,6964,6965,6966, 6967,6968,6969,6970,6971,6972,6973,6974,1714,6975,6976,6977,6978,6979,6980,6981, 6982,6983,6984,6985,6986,6987,6988,1394,6989,6990,6991,6992,6993,6994,6995,6996, 6997,6998,6999,7000,1715,7001,7002,7003,7004,7005,7006,7007,7008,7009,7010,7011, 7012,7013,7014,7015,7016,7017,7018,7019,7020,7021,7022,7023,7024,7025,7026,7027, 7028,1716,7029,7030,7031,7032,7033,7034,7035,7036,7037,7038,7039,7040,7041,7042, 7043,7044,7045,7046,7047,7048,7049,7050,7051,7052,7053,7054,7055,7056,7057,7058, 7059,7060,7061,7062,7063,7064,7065,7066,7067,7068,7069,7070,7071,7072,7073,7074, 7075,7076,7077,7078,7079,7080,7081,7082,7083,7084,7085,7086,7087,7088,7089,7090, 7091,7092,7093,7094,7095,7096,7097,7098,7099,7100,7101,7102,7103,7104,7105,7106, 7107,7108,7109,7110,7111,7112,7113,7114,7115,7116,7117,7118,7119,7120,7121,7122, 7123,7124,7125,7126,7127,7128,7129,7130,7131,7132,7133,7134,7135,7136,7137,7138, 7139,7140,7141,7142,7143,7144,7145,7146,7147,7148,7149,7150,7151,7152,7153,7154, 7155,7156,7157,7158,7159,7160,7161,7162,7163,7164,7165,7166,7167,7168,7169,7170, 7171,7172,7173,7174,7175,7176,7177,7178,7179,7180,7181,7182,7183,7184,7185,7186, 7187,7188,7189,7190,7191,7192,7193,7194,7195,7196,7197,7198,7199,7200,7201,7202, 7203,7204,7205,7206,7207,1395,7208,7209,7210,7211,7212,7213,1717,7214,7215,7216, 7217,7218,7219,7220,7221,7222,7223,7224,7225,7226,7227,7228,7229,7230,7231,7232, 7233,7234,7235,7236,7237,7238,7239,7240,7241,7242,7243,7244,7245,7246,7247,7248, 7249,7250,7251,7252,7253,7254,7255,7256,7257,7258,7259,7260,7261,7262,7263,7264, 7265,7266,7267,7268,7269,7270,7271,7272,7273,7274,7275,7276,7277,7278,7279,7280, 7281,7282,7283,7284,7285,7286,7287,7288,7289,7290,7291,7292,7293,7294,7295,7296, 7297,7298,7299,7300,7301,7302,7303,7304,7305,7306,7307,7308,7309,7310,7311,7312, 7313,1718,7314,7315,7316,7317,7318,7319,7320,7321,7322,7323,7324,7325,7326,7327, 7328,7329,7330,7331,7332,7333,7334,7335,7336,7337,7338,7339,7340,7341,7342,7343, 7344,7345,7346,7347,7348,7349,7350,7351,7352,7353,7354,7355,7356,7357,7358,7359, 7360,7361,7362,7363,7364,7365,7366,7367,7368,7369,7370,7371,7372,7373,7374,7375, 7376,7377,7378,7379,7380,7381,7382,7383,7384,7385,7386,7387,7388,7389,7390,7391, 7392,7393,7394,7395,7396,7397,7398,7399,7400,7401,7402,7403,7404,7405,7406,7407, 7408,7409,7410,7411,7412,7413,7414,7415,7416,7417,7418,7419,7420,7421,7422,7423, 7424,7425,7426,7427,7428,7429,7430,7431,7432,7433,7434,7435,7436,7437,7438,7439, 7440,7441,7442,7443,7444,7445,7446,7447,7448,7449,7450,7451,7452,7453,7454,7455, 7456,7457,7458,7459,7460,7461,7462,7463,7464,7465,7466,7467,7468,7469,7470,7471, 7472,7473,7474,7475,7476,7477,7478,7479,7480,7481,7482,7483,7484,7485,7486,7487, 7488,7489,7490,7491,7492,7493,7494,7495,7496,7497,7498,7499,7500,7501,7502,7503, 7504,7505,7506,7507,7508,7509,7510,7511,7512,7513,7514,7515,7516,7517,7518,7519, 7520,7521,7522,7523,7524,7525,7526,7527,7528,7529,7530,7531,7532,7533,7534,7535, 7536,7537,7538,7539,7540,7541,7542,7543,7544,7545,7546,7547,7548,7549,7550,7551, 7552,7553,7554,7555,7556,7557,7558,7559,7560,7561,7562,7563,7564,7565,7566,7567, 7568,7569,7570,7571,7572,7573,7574,7575,7576,7577,7578,7579,7580,7581,7582,7583, 7584,7585,7586,7587,7588,7589,7590,7591,7592,7593,7594,7595,7596,7597,7598,7599, 7600,7601,7602,7603,7604,7605,7606,7607,7608,7609,7610,7611,7612,7613,7614,7615, 7616,7617,7618,7619,7620,7621,7622,7623,7624,7625,7626,7627,7628,7629,7630,7631, 7632,7633,7634,7635,7636,7637,7638,7639,7640,7641,7642,7643,7644,7645,7646,7647, 7648,7649,7650,7651,7652,7653,7654,7655,7656,7657,7658,7659,7660,7661,7662,7663, 7664,7665,7666,7667,7668,7669,7670,7671,7672,7673,7674,7675,7676,7677,7678,7679, 7680,7681,7682,7683,7684,7685,7686,7687,7688,7689,7690,7691,7692,7693,7694,7695, 7696,7697,7698,7699,7700,7701,7702,7703,7704,7705,7706,7707,7708,7709,7710,7711, 7712,7713,7714,7715,7716,7717,7718,7719,7720,7721,7722,7723,7724,7725,7726,7727, 7728,7729,7730,7731,7732,7733,7734,7735,7736,7737,7738,7739,7740,7741,7742,7743, 7744,7745,7746,7747,7748,7749,7750,7751,7752,7753,7754,7755,7756,7757,7758,7759, 7760,7761,7762,7763,7764,7765,7766,7767,7768,7769,7770,7771,7772,7773,7774,7775, 7776,7777,7778,7779,7780,7781,7782,7783,7784,7785,7786,7787,7788,7789,7790,7791, 7792,7793,7794,7795,7796,7797,7798,7799,7800,7801,7802,7803,7804,7805,7806,7807, 7808,7809,7810,7811,7812,7813,7814,7815,7816,7817,7818,7819,7820,7821,7822,7823, 7824,7825,7826,7827,7828,7829,7830,7831,7832,7833,7834,7835,7836,7837,7838,7839, 7840,7841,7842,7843,7844,7845,7846,7847,7848,7849,7850,7851,7852,7853,7854,7855, 7856,7857,7858,7859,7860,7861,7862,7863,7864,7865,7866,7867,7868,7869,7870,7871, 7872,7873,7874,7875,7876,7877,7878,7879,7880,7881,7882,7883,7884,7885,7886,7887, 7888,7889,7890,7891,7892,7893,7894,7895,7896,7897,7898,7899,7900,7901,7902,7903, 7904,7905,7906,7907,7908,7909,7910,7911,7912,7913,7914,7915,7916,7917,7918,7919, 7920,7921,7922,7923,7924,7925,7926,7927,7928,7929,7930,7931,7932,7933,7934,7935, 7936,7937,7938,7939,7940,7941,7942,7943,7944,7945,7946,7947,7948,7949,7950,7951, 7952,7953,7954,7955,7956,7957,7958,7959,7960,7961,7962,7963,7964,7965,7966,7967, 7968,7969,7970,7971,7972,7973,7974,7975,7976,7977,7978,7979,7980,7981,7982,7983, 7984,7985,7986,7987,7988,7989,7990,7991,7992,7993,7994,7995,7996,7997,7998,7999, 8000,8001,8002,8003,8004,8005,8006,8007,8008,8009,8010,8011,8012,8013,8014,8015, 8016,8017,8018,8019,8020,8021,8022,8023,8024,8025,8026,8027,8028,8029,8030,8031, 8032,8033,8034,8035,8036,8037,8038,8039,8040,8041,8042,8043,8044,8045,8046,8047, 8048,8049,8050,8051,8052,8053,8054,8055,8056,8057,8058,8059,8060,8061,8062,8063, 8064,8065,8066,8067,8068,8069,8070,8071,8072,8073,8074,8075,8076,8077,8078,8079, 8080,8081,8082,8083,8084,8085,8086,8087,8088,8089,8090,8091,8092,8093,8094,8095, 8096,8097,8098,8099,8100,8101,8102,8103,8104,8105,8106,8107,8108,8109,8110,8111, 8112,8113,8114,8115,8116,8117,8118,8119,8120,8121,8122,8123,8124,8125,8126,8127, 8128,8129,8130,8131,8132,8133,8134,8135,8136,8137,8138,8139,8140,8141,8142,8143, 8144,8145,8146,8147,8148,8149,8150,8151,8152,8153,8154,8155,8156,8157,8158,8159, 8160,8161,8162,8163,8164,8165,8166,8167,8168,8169,8170,8171,8172,8173,8174,8175, 8176,8177,8178,8179,8180,8181,8182,8183,8184,8185,8186,8187,8188,8189,8190,8191, 8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8203,8204,8205,8206,8207, 8208,8209,8210,8211,8212,8213,8214,8215,8216,8217,8218,8219,8220,8221,8222,8223, 8224,8225,8226,8227,8228,8229,8230,8231,8232,8233,8234,8235,8236,8237,8238,8239, 8240,8241,8242,8243,8244,8245,8246,8247,8248,8249,8250,8251,8252,8253,8254,8255, 8256,8257,8258,8259,8260,8261,8262,8263,8264,8265,8266,8267,8268,8269,8270,8271, 8272,8273,8274,8275,8276,8277,8278,8279,8280,8281,8282,8283,8284,8285,8286,8287, 8288,8289,8290,8291,8292,8293,8294,8295,8296,8297,8298,8299,8300,8301,8302,8303, 8304,8305,8306,8307,8308,8309,8310,8311,8312,8313,8314,8315,8316,8317,8318,8319, 8320,8321,8322,8323,8324,8325,8326,8327,8328,8329,8330,8331,8332,8333,8334,8335, 8336,8337,8338,8339,8340,8341,8342,8343,8344,8345,8346,8347,8348,8349,8350,8351, 8352,8353,8354,8355,8356,8357,8358,8359,8360,8361,8362,8363,8364,8365,8366,8367, 8368,8369,8370,8371,8372,8373,8374,8375,8376,8377,8378,8379,8380,8381,8382,8383, 8384,8385,8386,8387,8388,8389,8390,8391,8392,8393,8394,8395,8396,8397,8398,8399, 8400,8401,8402,8403,8404,8405,8406,8407,8408,8409,8410,8411,8412,8413,8414,8415, 8416,8417,8418,8419,8420,8421,8422,8423,8424,8425,8426,8427,8428,8429,8430,8431, 8432,8433,8434,8435,8436,8437,8438,8439,8440,8441,8442,8443,8444,8445,8446,8447, 8448,8449,8450,8451,8452,8453,8454,8455,8456,8457,8458,8459,8460,8461,8462,8463, 8464,8465,8466,8467,8468,8469,8470,8471,8472,8473,8474,8475,8476,8477,8478,8479, 8480,8481,8482,8483,8484,8485,8486,8487,8488,8489,8490,8491,8492,8493,8494,8495, 8496,8497,8498,8499,8500,8501,8502,8503,8504,8505,8506,8507,8508,8509,8510,8511, 8512,8513,8514,8515,8516,8517,8518,8519,8520,8521,8522,8523,8524,8525,8526,8527, 8528,8529,8530,8531,8532,8533,8534,8535,8536,8537,8538,8539,8540,8541,8542,8543, 8544,8545,8546,8547,8548,8549,8550,8551,8552,8553,8554,8555,8556,8557,8558,8559, 8560,8561,8562,8563,8564,8565,8566,8567,8568,8569,8570,8571,8572,8573,8574,8575, 8576,8577,8578,8579,8580,8581,8582,8583,8584,8585,8586,8587,8588,8589,8590,8591, 8592,8593,8594,8595,8596,8597,8598,8599,8600,8601,8602,8603,8604,8605,8606,8607, 8608,8609,8610,8611,8612,8613,8614,8615,8616,8617,8618,8619,8620,8621,8622,8623, 8624,8625,8626,8627,8628,8629,8630,8631,8632,8633,8634,8635,8636,8637,8638,8639, 8640,8641,8642,8643,8644,8645,8646,8647,8648,8649,8650,8651,8652,8653,8654,8655, 8656,8657,8658,8659,8660,8661,8662,8663,8664,8665,8666,8667,8668,8669,8670,8671, 8672,8673,8674,8675,8676,8677,8678,8679,8680,8681,8682,8683,8684,8685,8686,8687, 8688,8689,8690,8691,8692,8693,8694,8695,8696,8697,8698,8699,8700,8701,8702,8703, 8704,8705,8706,8707,8708,8709,8710,8711,8712,8713,8714,8715,8716,8717,8718,8719, 8720,8721,8722,8723,8724,8725,8726,8727,8728,8729,8730,8731,8732,8733,8734,8735, 8736,8737,8738,8739,8740,8741 ****************************************************************************************/ }; } }
/* FluorineFx open source library Copyright (C) 2007 Zoltan Csibi, [email protected], FluorineFx.com This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; using System.Collections; using System.Net; using System.Web; using log4net; using FluorineFx.Util; using FluorineFx.Collections; using FluorineFx.Messaging.Api; using FluorineFx.Messaging.Endpoints; using FluorineFx.Messaging.Rtmp; using FluorineFx.Messaging.Messages; using FluorineFx.Threading; namespace FluorineFx.Messaging.Rtmpt { class PendingData { private object _buffer; private RtmpPacket _packet; public PendingData(object buffer, RtmpPacket packet) { _buffer = buffer; _packet = packet; } public PendingData(object buffer) { _buffer = buffer; } public object Buffer { get { return _buffer; } } public RtmpPacket Packet { get { return _packet; } } } class RtmptConnection : RtmpConnection { private static readonly ILog log = LogManager.GetLogger(typeof(RtmptConnection)); /// <summary> /// Try to generate responses that contain at least 32768 bytes data. /// Increasing this value results in better stream performance, but also increases the latency. /// </summary> internal static int RESPONSE_TARGET_SIZE = 32768; /// <summary> /// Start to increase the polling delay after this many empty results /// </summary> protected static long INCREASE_POLLING_DELAY_COUNT = 10; /// <summary> /// Polling delay to start with. /// </summary> protected static byte INITIAL_POLLING_DELAY = 0; /// <summary> /// Maximum polling delay. /// </summary> protected static byte MAX_POLLING_DELAY = 32; /// <summary> /// Polling delay value /// </summary> protected byte _pollingDelay = INITIAL_POLLING_DELAY; /// <summary> /// Timeframe without pending messages. If this time is greater then polling delay, then polling delay increased /// </summary> protected long _noPendingMessages; /// <summary> /// List of pending messages (PendingData) /// </summary> protected LinkedList _pendingMessages; /// <summary> /// Number of read bytes /// </summary> protected AtomicLong _readBytes; /// <summary> /// Number of written bytes /// </summary> protected AtomicLong _writtenBytes; protected ByteBuffer _buffer; IPEndPoint _remoteEndPoint; RtmptServer _rtmptServer; FastReaderWriterLock _lock; public RtmptConnection(RtmptServer rtmptServer, IPEndPoint ipEndPoint, string path, Hashtable parameters) : base(rtmptServer.RtmpHandler, RtmpMode.Server, path, parameters) { _lock = new FastReaderWriterLock(); _remoteEndPoint = ipEndPoint; _rtmptServer = rtmptServer; _readBytes = new AtomicLong(); _writtenBytes = new AtomicLong(); _session = rtmptServer.Endpoint.GetMessageBroker().SessionManager.CreateSession(this); } /* public RtmptConnection(RtmptServer rtmptServer, IPEndPoint ipEndPoint, ISession session, string path, Hashtable parameters) : base(rtmptServer.RtmpHandler, path, parameters) { _lock = new FastReaderWriterLock(); _remoteEndPoint = ipEndPoint; _rtmptServer = rtmptServer; _readBytes = new AtomicLong(); _writtenBytes = new AtomicLong(); _session = session; } */ public override IPEndPoint RemoteEndPoint { get { if( _remoteEndPoint != null ) return _remoteEndPoint; else { if (HttpContext.Current != null) { IPAddress ipAddress = IPAddress.Parse(HttpContext.Current.Request.UserHostAddress); IPEndPoint remoteEndPoint = new IPEndPoint(ipAddress, 80); return remoteEndPoint; } } return null; } } public IEndpoint Endpoint { get { return _rtmptServer.Endpoint; } } public override long ReadBytes { get { return _readBytes.Value; } } public override long WrittenBytes { get { return _writtenBytes.Value; } } public byte PollingDelay { get { try { _lock.AcquireReaderLock(); if (this.State == RtmpState.Disconnected) { // Special value to notify client about a closed connection. return (byte)0; } return (byte)(_pollingDelay + 1); } finally { _lock.ReleaseReaderLock(); } } } public ByteBuffer GetPendingMessages(int targetSize) { ByteBuffer result = null; LinkedList toNotify = new LinkedList(); try { _lock.AcquireWriterLock(); if (_pendingMessages == null || _pendingMessages.Count == 0) { _noPendingMessages += 1; if (_noPendingMessages > INCREASE_POLLING_DELAY_COUNT) { if (_pollingDelay == 0) _pollingDelay = 1; _pollingDelay = (byte)(_pollingDelay * 2); if (_pollingDelay > MAX_POLLING_DELAY) _pollingDelay = MAX_POLLING_DELAY; } return null; } _noPendingMessages = 0; _pollingDelay = INITIAL_POLLING_DELAY; if (_pendingMessages.Count == 0) return null; if (log.IsDebugEnabled) log.Debug(__Res.GetString(__Res.Rtmpt_ReturningMessages, _pendingMessages.Count)); result = ByteBuffer.Allocate(2048); while (_pendingMessages.Count > 0) { PendingData pendingData = _pendingMessages[0] as PendingData; _pendingMessages.RemoveAt(0); if (pendingData.Buffer is ByteBuffer) result.Put(pendingData.Buffer as ByteBuffer); if (pendingData.Buffer is byte[]) result.Put(pendingData.Buffer as byte[]); if (pendingData.Packet != null) toNotify.Add(pendingData.Packet); if ((result.Position > targetSize)) break; } } finally { _lock.ReleaseWriterLock(); } if (toNotify != null) { foreach (object message in toNotify) { try { _handler.MessageSent(this, message); } catch (Exception ex) { log.Error(__Res.GetString(__Res.Rtmpt_NotifyError), ex); continue; } } } result.Flip(); _writtenBytes.Increment(result.Limit); return result; } public override void Write(RtmpPacket packet) { _lock.AcquireReaderLock(); try { if (IsClosed || IsClosing) return; } finally { _lock.ReleaseReaderLock(); } try { _lock.AcquireWriterLock(); ByteBuffer data; try { data = RtmpProtocolEncoder.Encode(this.Context, packet); } catch (Exception ex) { log.Error("Could not encode message " + packet, ex); return; } // Mark packet as being written WritingMessage(packet); if (_pendingMessages == null) _pendingMessages = new LinkedList(); _pendingMessages.Add(new PendingData(data, packet)); } finally { _lock.ReleaseWriterLock(); } } public override void Write(ByteBuffer buffer) { _lock.AcquireReaderLock(); try { if (IsClosed || IsClosing) return; } finally { _lock.ReleaseReaderLock(); } try { _lock.AcquireWriterLock(); if (_pendingMessages == null) _pendingMessages = new LinkedList(); _pendingMessages.Add(new PendingData(buffer)); } finally { _lock.ReleaseWriterLock(); } } public override void Write(byte[] buffer) { _lock.AcquireReaderLock(); try { if (IsClosed || IsClosing) return; } finally { _lock.ReleaseReaderLock(); } try { _lock.AcquireWriterLock(); if (_pendingMessages == null) _pendingMessages = new LinkedList(); _pendingMessages.Add(new PendingData(buffer)); } finally { _lock.ReleaseWriterLock(); } } public IList Decode(ByteBuffer data) { _lock.AcquireReaderLock(); try { if (IsClosed || IsClosing) return Internal.EmptyIList;// Already shutting down. } finally { _lock.ReleaseReaderLock(); } _readBytes.Increment(data.Limit); if( _buffer == null ) _buffer = ByteBuffer.Allocate(2048); _buffer.Put(data); _buffer.Flip(); try { IList result = RtmpProtocolDecoder.DecodeBuffer(this.Context, _buffer); return result; } catch (HandshakeFailedException hfe) { #if !SILVERLIGHT if (log.IsDebugEnabled) log.Debug(string.Format("Handshake failed: {0}", hfe.Message)); #endif // Clear buffer if something is wrong in protocol decoding. _buffer.Clear(); this.Close(); } catch (Exception ex) { // Catch any exception in the decoding then clear the buffer to eliminate memory leaks when we can't parse protocol // Also close Connection because we can't parse data from it #if !SILVERLIGHT log.Error("Error decoding buffer", ex); #endif // Clear buffer if something is wrong in protocol decoding. _buffer.Clear(); this.Close(); } return null; } public override void Close() { // Defer actual closing so we can send back pending messages to the client. _lock.AcquireReaderLock(); try { if (IsClosed || IsClosing) return; // Already shutting down. try { _lock.UpgradeToWriterLock(); SetIsClosing(true); _lock.DowngradeToReaderLock(); } catch (ApplicationException) { //Some other thread did an upgrade return; } } finally { _lock.ReleaseReaderLock(); } } public void RealClose() { _lock.AcquireReaderLock(); try { if (!IsClosing) return; } finally { _lock.ReleaseReaderLock(); } try { _lock.AcquireWriterLock(); if (_buffer != null) { _buffer.Dispose(); _buffer = null; } if (_pendingMessages != null) { _pendingMessages.Clear(); _pendingMessages = null; } _rtmptServer.RemoveConnection(this.ConnectionId); } finally { _lock.ReleaseWriterLock(); } base.Close(); _lock.AcquireWriterLock(); try { SetIsClosed(true); SetIsClosing(false); } finally { _lock.ReleaseWriterLock(); } } public override void Push(IMessage message, IMessageClient messageClient) { _lock.AcquireReaderLock(); try { if (IsClosed || IsClosing) return; // Already shutting down. } finally { _lock.ReleaseReaderLock(); } RtmpHandler.Push(this, message, messageClient); /* IMessage messageClone = message.Clone() as IMessage; messageClone.SetHeader(MessageBase.DestinationClientIdHeader, messageClient.ClientId); messageClone.clientId = messageClient.ClientId; messageClient.AddMessage(messageClone); */ } protected override void OnInactive() { if( log.IsDebugEnabled ) log.Debug(string.Format("Inactive connection {0}, closing", this.ConnectionId)); //this.Timeout(); Close(); RealClose(); } public override string ToString() { return "RtmptConnection " + _connectionId; } } }
/* * 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 Apache.Geode.Client; namespace PdxTests { public class PositionPdx : IPdxSerializable { #region Private members private long m_avg20DaysVol; private string m_bondRating; private double m_convRatio; private string m_country; private double m_delta; private long m_industry; private long m_issuer; private double m_mktValue; private double m_qty; private string m_secId; private string m_secLinks; private string m_secType; private int m_sharesOutstanding; private string m_underlyer; private long m_volatility; private int m_pid; private static int m_count = 0; #endregion #region Private methods private void Init() { m_avg20DaysVol = 0; m_bondRating = null; m_convRatio = 0.0; m_country = null; m_delta = 0.0; m_industry = 0; m_issuer = 0; m_mktValue = 0.0; m_qty = 0.0; m_secId = null; m_secLinks = null; m_secType = null; m_sharesOutstanding = 0; m_underlyer = null; m_volatility = 0; m_pid = 0; } private UInt32 GetObjectSize(IGeodeSerializable obj) { return (obj == null ? 0 : obj.ObjectSize); } #endregion #region Public accessors public string SecId { get { return m_secId; } } public int Id { get { return m_pid; } } public int SharesOutstanding { get { return m_sharesOutstanding; } } public static int Count { get { return m_count; } set { m_count = value; } } public override string ToString() { return "Position [secId="+m_secId+" sharesOutstanding="+m_sharesOutstanding+ " type="+m_secType +" id="+m_pid+"]"; } #endregion #region Constructors public PositionPdx() { Init(); } //This ctor is for a data validation test public PositionPdx(Int32 iForExactVal) { Init(); char[] id = new char[iForExactVal+1]; for (int i = 0; i <= iForExactVal; i++) { id[i] = 'a'; } m_secId = new string(id); m_qty = iForExactVal % 2 == 0 ? 1000 : 100; m_mktValue = m_qty * 2; m_sharesOutstanding = iForExactVal; m_secType = "a"; m_pid = iForExactVal; } public PositionPdx(string id, int shares) { Init(); m_secId = id; m_qty = shares * (m_count % 2 == 0 ? 10.0 : 100.0); m_mktValue = m_qty * 1.2345998; m_sharesOutstanding = shares; m_secType = "a"; m_pid = m_count++; } #endregion public static IPdxSerializable CreateDeserializable() { return new PositionPdx(); } #region IPdxSerializable Members public void FromData(IPdxReader reader) { m_avg20DaysVol = reader.ReadLong("avg20DaysVol"); m_bondRating = reader.ReadString("bondRating"); m_convRatio = reader.ReadDouble("convRatio"); m_country = reader.ReadString("country"); m_delta = reader.ReadDouble("delta"); m_industry = reader.ReadLong("industry"); m_issuer = reader.ReadLong("issuer"); m_mktValue = reader.ReadDouble("mktValue"); m_qty = reader.ReadDouble("qty"); m_secId = reader.ReadString("secId"); m_secLinks = reader.ReadString("secLinks"); m_secType = reader.ReadString("secType"); m_sharesOutstanding = reader.ReadInt("sharesOutstanding"); m_underlyer = reader.ReadString("underlyer"); m_volatility = reader.ReadLong("volatility"); m_pid = reader.ReadInt("pid"); } public void ToData(IPdxWriter writer) { writer.WriteLong("avg20DaysVol", m_avg20DaysVol); writer.WriteString("bondRating", m_bondRating); writer.WriteDouble("convRatio", m_convRatio); writer.WriteString("country", m_country); writer.WriteDouble("delta", m_delta); writer.WriteLong("industry", m_industry); writer.WriteLong("issuer", m_issuer); writer.WriteDouble("mktValue", m_mktValue); writer.WriteDouble("qty", m_qty); writer.WriteString("secId", m_secId); writer.WriteString("secLinks", m_secLinks); writer.WriteString("secType", m_secType); writer.WriteInt("sharesOutstanding", m_sharesOutstanding); writer.WriteString("underlyer", m_underlyer); writer.WriteLong("volatility", m_volatility); writer.WriteInt("pid", m_pid); //identity field writer.MarkIdentityField("pid"); } #endregion } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the Apache License, Version 2.0. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.Collections.ObjectModel; namespace Common { public class ReflectionUtils { private class TypePair { private Type t1; private Type t2; public TypePair(Type t1, Type t2) { this.t1 = t1; this.t2 = t2; } public override bool Equals(object obj) { TypePair other = obj as TypePair; if (other == null) return false; return this.t1.Equals(other.t1) && this.t2.Equals(other.t2); } public override int GetHashCode() { int result = 17; result = 37 * result + t1.GetHashCode(); result = 37 * result + t2.GetHashCode(); return result; } } #region cached data structures private static Dictionary <Type,Collection<Type>> cachedRelatedTypes = new Dictionary<Type,Collection<Type>>(); private static Dictionary<Type, Collection<Assembly>> cachedRelatedAssembliesPerType = new Dictionary<Type,Collection<Assembly>>(); private static Dictionary<FieldInfo, Collection<Assembly>> cachedRelatedAssembliesPerField = new Dictionary<FieldInfo,Collection<Assembly>>(); private static Dictionary<MethodBase, Collection<Assembly>> cachedRelatedAssembliesPerMethod = new Dictionary<MethodBase,Collection<Assembly>>(); private static Dictionary<TypePair, bool> subTypeCached = new Dictionary<TypePair, bool>(); #endregion public static bool IsSubclassOrEqual(Type t1, Type t2) { if (t1 == null) throw new ArgumentNullException(); if (t2 == null) throw new ArgumentNullException(); if (t1.Equals(t2)) return true; bool result; TypePair typePair = new TypePair(t1, t2); if (!subTypeCached.TryGetValue(typePair, out result)) { result = subTypeCached[typePair] = t1.IsSubclassOf(t2); } return result; } public static Collection<Type> GetExplorableTypes(Collection<Assembly> assemblies) { Collection<Type> retval = new Collection<Type>(); foreach (Assembly assembly in assemblies) { foreach (Type t in assembly.GetExportedTypes()) { retval.Add(t); } } return retval; } /// <summary> /// Checks if mi is a known overloaded operator /// </summary> /// <param name="mi"></param> /// <returns></returns> public static bool IsOverloadedOperator(MethodInfo mi, out string op) { op = ""; bool status = true; if (mi.Name.Contains("op_Equality")) { op = "=="; } else if (mi.Name.Contains("op_LogicalNot")) { op = "!"; } else if (mi.Name.Contains("op_Inequality")) { op = "!="; } else if (mi.Name.Contains("op_GreaterThan")) { op = ">"; } else if (mi.Name.Contains("op_LessThan")) { op = "<"; } else if (mi.Name.Contains("op_LessThanOrEqual")) { op = "<="; } else if (mi.Name.Contains("op_GreaterThanOrEqual")) { op = ">="; } else if (mi.Name.Contains("op_Addition")) { op = "+"; } else if (mi.Name.Contains("op_Subtraction")) { op = "-"; } else if (mi.Name.Contains("op_Multiply")) { op = "*"; } else if (mi.Name.Contains("op_Division")) { op = "/"; } else if (mi.Name.Contains("op_Increment")) { op = "++"; } else if (mi.Name.Contains("op_Decrement")) { op = "--"; } else if (mi.Name.Contains("op_UnaryNegation")) { op = "-"; } else if (mi.Name.Contains("op_UnaryPlus")) { op = "+"; } else if (mi.Name.Contains("op_Modulus")) { op = "%"; } else if (mi.Name.Contains("op_ExclusiveOr")) { op = "^"; } else if (mi.Name.Contains("op_BitwiseAnd")) { op = "&"; } else if (mi.Name.Contains("op_BitwiseOr")) { op = "|"; } else if (mi.Name.Contains("op_OnesComplement")) { op = "~"; } else if (mi.Name.Contains("op_Negation")) { op = "!"; } else if (mi.Name.Contains("op_LeftShift")) { op = "<<"; } else if (mi.Name.Contains("op_RightShift")) { op = ">>"; } else { status = false; } return status; } /// <summary> /// Casts between various types /// </summary> /// <param name="mi"></param> /// <param name="castOp"></param> /// <returns></returns> public static bool IsCastOperator(MethodInfo mi, out string castOp) { bool status = true; castOp = ""; if (mi.Name.Contains("op_Explicit") || mi.Name.Contains("op_Implicit")) { castOp = "(" + SourceCodePrinting.ToCodeString(mi.ReturnType) + ")"; } else if (mi.Name.Contains("op_True")) { castOp = "(bool)"; } else if (mi.Name.Contains("op_False")) { castOp = "(bool)"; } else { status = false; } return status; } public static ReadOnlyCollection<Type> GetRelatedTypes(Type type) { Collection<Type> ret; cachedRelatedTypes.TryGetValue(type, out ret); if (ret != null) return new ReadOnlyCollection<Type>(ret); List<Type> relatedTypes = new List<Type>(); // Add the type and its base types. relatedTypes.Add(type); relatedTypes.AddRange(BaseTypesRecursive(type)); relatedTypes.AddRange(CollectInterfaces(type)); cachedRelatedTypes.Add(type, new Collection<Type>(relatedTypes)); return new ReadOnlyCollection<Type>(relatedTypes); } // TODO add explanation of motivation behind this definition // of "related assemblies." public static ReadOnlyCollection<Assembly> GetRelatedAssemblies(Type type) { Collection<Assembly> ret; cachedRelatedAssembliesPerType.TryGetValue(type, out ret); if (ret != null) return new ReadOnlyCollection<Assembly>(ret); ReadOnlyCollection<Type> relatedTypes = GetRelatedTypes(type); // Collect related assemblies. Collection<Assembly> retval = new Collection<Assembly>(); foreach (Type t in relatedTypes) { if (t.Assembly != null) retval.Add(t.Assembly); } cachedRelatedAssembliesPerType.Add(type, new Collection<Assembly>(retval)); return new ReadOnlyCollection<Assembly>(retval); } public static ReadOnlyCollection<Assembly> GetRelatedAssemblies(FieldInfo field) { Collection<Assembly> ret; cachedRelatedAssembliesPerField.TryGetValue(field, out ret); if (ret != null) return new ReadOnlyCollection<Assembly>(ret); List<Type> relatedTypes = new List<Type>(); // Add the type and base types of the field. relatedTypes.Add(field.FieldType); relatedTypes.AddRange(BaseTypesRecursive(field.FieldType)); relatedTypes.AddRange(CollectInterfaces(field.FieldType)); // Add the types and base types of the declaring type. relatedTypes.Add(field.DeclaringType); relatedTypes.AddRange(BaseTypesRecursive(field.DeclaringType)); relatedTypes.AddRange(CollectInterfaces(field.DeclaringType)); // Collect related assemblies. List<Assembly> retval = new List<Assembly>(); foreach (Type t in relatedTypes) { if (t.Assembly != null) retval.Add(t.Assembly); } cachedRelatedAssembliesPerField.Add(field, new Collection<Assembly>(retval)); return new ReadOnlyCollection<Assembly>(retval); } public static ReadOnlyCollection<Assembly> GetRelatedAssemblies(MethodBase m) { Collection<Assembly> ret; cachedRelatedAssembliesPerMethod.TryGetValue(m, out ret); if (ret != null) return new ReadOnlyCollection<Assembly>(ret); List<Type> relatedTypes = new List<Type>(); // Add the type and base types of the declaring type. relatedTypes.Add(m.DeclaringType); relatedTypes.AddRange(BaseTypesRecursive(m.DeclaringType)); relatedTypes.AddRange(CollectInterfaces(m.DeclaringType)); // Add the types and base types of the parameters. foreach (ParameterInfo pi in m.GetParameters()) { relatedTypes.Add(pi.ParameterType); relatedTypes.AddRange(BaseTypesRecursive(pi.ParameterType)); relatedTypes.AddRange(CollectInterfaces(pi.ParameterType)); } // Collect related assemblies. Collection<Assembly> retval = new Collection<Assembly>(); foreach (Type t in relatedTypes) { if (t.Assembly != null) retval.Add(t.Assembly); } cachedRelatedAssembliesPerMethod.Add(m, new Collection<Assembly>(retval)); return new ReadOnlyCollection<Assembly>(retval); } private static ReadOnlyCollection<Type> CollectInterfaces(Type type) { if (type == null) throw new ArgumentNullException(); List<Type> retval = new List<Type>(); foreach (Type inter in type.GetInterfaces()) { retval.AddRange(CollectInterfaces(inter)); retval.Add(inter); } return new ReadOnlyCollection<Type>(retval); } private static Collection<Type> BaseTypesRecursive(Type type) { Collection<Type> retval = new Collection<Type>(); Type baseType = type.BaseType; while (baseType != null) { retval.Add(baseType); baseType = baseType.BaseType; } return retval; } public static bool IsPublic(Type t) { return t.IsNestedPublic || t.IsPublic; } } }
// Copyright 2010 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; using NodaTime.Testing.TimeZones; using NodaTime.TimeZones; using NUnit.Framework; using System.IO; using NodaTime.TimeZones.IO; using System.Linq; namespace NodaTime.Test.TimeZones { public class PrecalculatedDateTimeZoneTest { private static readonly ZoneInterval FirstInterval = new ZoneInterval("First", Instant.BeforeMinValue, Instant.FromUtc(2000, 3, 10, 10, 0), Offset.FromHours(3), Offset.Zero); // Note that this is effectively UTC +3 + 1 hour DST. private static readonly ZoneInterval SecondInterval = new ZoneInterval("Second", FirstInterval.End, Instant.FromUtc(2000, 9, 15, 5, 0), Offset.FromHours(4), Offset.FromHours(1)); private static readonly ZoneInterval ThirdInterval = new ZoneInterval("Third", SecondInterval.End, Instant.FromUtc(2005, 1, 20, 8, 0), Offset.FromHours(-5), Offset.Zero); private static readonly ZoneRecurrence Winter = new ZoneRecurrence("Winter", Offset.Zero, new ZoneYearOffset(TransitionMode.Wall, 10, 5, 0, false, new LocalTime(2, 0)), 1960, int.MaxValue); private static readonly ZoneRecurrence Summer = new ZoneRecurrence("Summer", Offset.FromHours(1), new ZoneYearOffset(TransitionMode.Wall, 3, 10, 0, false, new LocalTime(1, 0)), 1960, int.MaxValue); private static readonly StandardDaylightAlternatingMap TailZone = new StandardDaylightAlternatingMap(Offset.FromHours(-6), Winter, Summer); // We don't actually want an interval from the beginning of time when we ask our composite time zone for an interval // - because that could give the wrong idea. So we clamp it at the end of the precalculated interval. private static readonly ZoneInterval ClampedTailZoneInterval = TailZone.GetZoneInterval(ThirdInterval.End).WithStart(ThirdInterval.End); private static readonly PrecalculatedDateTimeZone TestZone = new PrecalculatedDateTimeZone("Test", new[] { FirstInterval, SecondInterval, ThirdInterval }, TailZone); [Test] public void MinMaxOffsets() { Assert.AreEqual(Offset.FromHours(-6), TestZone.MinOffset); Assert.AreEqual(Offset.FromHours(4), TestZone.MaxOffset); } [Test] public void MinMaxOffsetsWithOtherTailZone() { var tailZone = new FixedDateTimeZone("TestFixed", Offset.FromHours(8)); var testZone = new PrecalculatedDateTimeZone("Test", new[] { FirstInterval, SecondInterval, ThirdInterval }, tailZone); Assert.AreEqual(Offset.FromHours(-5), testZone.MinOffset); Assert.AreEqual(Offset.FromHours(8), testZone.MaxOffset); } [Test] public void MinMaxOffsetsWithNullTailZone() { var testZone = new PrecalculatedDateTimeZone("Test", new[] { FirstInterval, SecondInterval, ThirdInterval, new ZoneInterval("Last", ThirdInterval.End, Instant.AfterMaxValue, Offset.Zero, Offset.Zero) }, null); Assert.AreEqual(Offset.FromHours(-5), testZone.MinOffset); Assert.AreEqual(Offset.FromHours(4), testZone.MaxOffset); } [Test] public void GetZoneIntervalInstant_End() { Assert.AreEqual(SecondInterval, TestZone.GetZoneInterval(SecondInterval.End - Duration.Epsilon)); } [Test] public void GetZoneIntervalInstant_Start() { Assert.AreEqual(SecondInterval, TestZone.GetZoneInterval(SecondInterval.Start)); } [Test] public void GetZoneIntervalInstant_FinalInterval_End() { Assert.AreEqual(ThirdInterval, TestZone.GetZoneInterval(ThirdInterval.End - Duration.Epsilon)); } [Test] public void GetZoneIntervalInstant_FinalInterval_Start() { Assert.AreEqual(ThirdInterval, TestZone.GetZoneInterval(ThirdInterval.Start)); } [Test] public void GetZoneIntervalInstant_TailZone() { Assert.AreEqual(ClampedTailZoneInterval, TestZone.GetZoneInterval(ThirdInterval.End)); } [Test] public void MapLocal_UnambiguousInPrecalculated() { CheckMapping(new LocalDateTime(2000, 6, 1, 0, 0), SecondInterval, SecondInterval, 1); } [Test] public void MapLocal_UnambiguousInTailZone() { CheckMapping(new LocalDateTime(2005, 2, 1, 0, 0), ClampedTailZoneInterval, ClampedTailZoneInterval, 1); } [Test] public void MapLocal_AmbiguousWithinPrecalculated() { // Transition from +4 to -5 has a 9 hour ambiguity CheckMapping(ThirdInterval.IsoLocalStart, SecondInterval, ThirdInterval, 2); } [Test] public void MapLocal_AmbiguousAroundTailZoneTransition() { // Transition from -5 to -6 has a 1 hour ambiguity CheckMapping(ThirdInterval.IsoLocalEnd.PlusNanoseconds(-1L), ThirdInterval, ClampedTailZoneInterval, 2); } [Test] public void MapLocal_AmbiguousButTooEarlyInTailZoneTransition() { // Tail zone is +10 / +8, with the transition occurring just after // the transition *to* the tail zone from the precalculated zone. // A local instant of one hour before after the transition from the precalculated zone (which is -5) // will therefore be ambiguous, but the resulting instants from the ambiguity occur // before our transition into the tail zone, so are ignored. var tailZone = new SingleTransitionDateTimeZone(ThirdInterval.End + Duration.FromHours(1), 10, 8); var gapZone = new PrecalculatedDateTimeZone("Test", new[] { FirstInterval, SecondInterval, ThirdInterval }, tailZone); var mapping = gapZone.MapLocal(ThirdInterval.IsoLocalEnd.PlusHours(-1)); Assert.AreEqual(ThirdInterval, mapping.EarlyInterval); Assert.AreEqual(ThirdInterval, mapping.LateInterval); Assert.AreEqual(1, mapping.Count); } [Test] public void MapLocal_GapWithinPrecalculated() { // Transition from +3 to +4 has a 1 hour gap Assert.IsTrue(FirstInterval.IsoLocalEnd < SecondInterval.IsoLocalStart); CheckMapping(FirstInterval.IsoLocalEnd, FirstInterval, SecondInterval, 0); } [Test] public void MapLocal_SingleIntervalAroundTailZoneTransition() { // Tail zone is fixed at +5. A local instant of one hour before the transition // from the precalculated zone (which is -5) will therefore give an instant from // the tail zone which occurs before the precalculated-to-tail transition, // and can therefore be ignored, resulting in an overall unambiguous time. var tailZone = new FixedDateTimeZone(Offset.FromHours(5)); var gapZone = new PrecalculatedDateTimeZone("Test", new[] { FirstInterval, SecondInterval, ThirdInterval }, tailZone); var mapping = gapZone.MapLocal(ThirdInterval.IsoLocalEnd.PlusHours(-1)); Assert.AreEqual(ThirdInterval, mapping.EarlyInterval); Assert.AreEqual(ThirdInterval, mapping.LateInterval); Assert.AreEqual(1, mapping.Count); } [Test] public void MapLocal_GapAroundTailZoneTransition() { // Tail zone is fixed at +5. A local time at the transition // from the precalculated zone (which is -5) will therefore give an instant from // the tail zone which occurs before the precalculated-to-tail transition, // and can therefore be ignored, resulting in an overall gap. var tailZone = new FixedDateTimeZone(Offset.FromHours(5)); var gapZone = new PrecalculatedDateTimeZone("Test", new[] { FirstInterval, SecondInterval, ThirdInterval }, tailZone); var mapping = gapZone.MapLocal(ThirdInterval.IsoLocalEnd); Assert.AreEqual(ThirdInterval, mapping.EarlyInterval); Assert.AreEqual(new ZoneInterval("UTC+05", ThirdInterval.End, Instant.AfterMaxValue, Offset.FromHours(5), Offset.Zero), mapping.LateInterval); Assert.AreEqual(0, mapping.Count); } [Test] public void MapLocal_GapAroundAndInTailZoneTransition() { // Tail zone is -10 / +5, with the transition occurring just after // the transition *to* the tail zone from the precalculated zone. // A local time of one hour after the transition from the precalculated zone (which is -5) // will therefore be in the gap. var tailZone = new SingleTransitionDateTimeZone(ThirdInterval.End + Duration.FromHours(1), -10, +5); var gapZone = new PrecalculatedDateTimeZone("Test", new[] { FirstInterval, SecondInterval, ThirdInterval }, tailZone); var mapping = gapZone.MapLocal(ThirdInterval.IsoLocalEnd.PlusHours(1)); Assert.AreEqual(ThirdInterval, mapping.EarlyInterval); Assert.AreEqual(new ZoneInterval("Single-Early", ThirdInterval.End, tailZone.Transition, Offset.FromHours(-10), Offset.Zero), mapping.LateInterval); Assert.AreEqual(0, mapping.Count); } [Test] public void GetZoneIntervals_NullTailZone_Eot() { ZoneInterval[] intervals = { new ZoneInterval("foo", Instant.BeforeMinValue, Instant.FromUnixTimeTicks(20), Offset.Zero, Offset.Zero), new ZoneInterval("foo", Instant.FromUnixTimeTicks(20), Instant.AfterMaxValue, Offset.Zero, Offset.Zero) }; var zone = new PrecalculatedDateTimeZone("Test", intervals, null); Assert.AreEqual(intervals[1], zone.GetZoneInterval(Instant.MaxValue)); } private void CheckMapping(LocalDateTime localDateTime, ZoneInterval earlyInterval, ZoneInterval lateInterval, int count) { var mapping = TestZone.MapLocal(localDateTime); Assert.AreEqual(earlyInterval, mapping.EarlyInterval); Assert.AreEqual(lateInterval, mapping.LateInterval); Assert.AreEqual(count, mapping.Count); } [Test] public void Validation_EmptyPeriodArray() { Assert.Throws<ArgumentException>(() => PrecalculatedDateTimeZone.ValidatePeriods(new ZoneInterval[0], DateTimeZone.Utc)); } [Test] public void Validation_BadFirstStartingPoint() { ZoneInterval[] intervals = { new ZoneInterval("foo", Instant.FromUnixTimeTicks(10), Instant.FromUnixTimeTicks(20), Offset.Zero, Offset.Zero), new ZoneInterval("foo", Instant.FromUnixTimeTicks(20), Instant.FromUnixTimeTicks(30), Offset.Zero, Offset.Zero) }; Assert.Throws<ArgumentException>(() => PrecalculatedDateTimeZone.ValidatePeriods(intervals, DateTimeZone.Utc)); } [Test] public void Validation_NonAdjoiningIntervals() { ZoneInterval[] intervals = { new ZoneInterval("foo", Instant.BeforeMinValue, Instant.FromUnixTimeTicks(20), Offset.Zero, Offset.Zero), new ZoneInterval("foo", Instant.FromUnixTimeTicks(25), Instant.FromUnixTimeTicks(30), Offset.Zero, Offset.Zero) }; Assert.Throws<ArgumentException>(() => PrecalculatedDateTimeZone.ValidatePeriods(intervals, DateTimeZone.Utc)); } [Test] public void Validation_Success() { ZoneInterval[] intervals = { new ZoneInterval("foo", Instant.BeforeMinValue, Instant.FromUnixTimeTicks(20), Offset.Zero, Offset.Zero), new ZoneInterval("foo", Instant.FromUnixTimeTicks(20), Instant.FromUnixTimeTicks(30), Offset.Zero, Offset.Zero), new ZoneInterval("foo", Instant.FromUnixTimeTicks(30), Instant.FromUnixTimeTicks(100), Offset.Zero, Offset.Zero), new ZoneInterval("foo", Instant.FromUnixTimeTicks(100), Instant.FromUnixTimeTicks(200), Offset.Zero, Offset.Zero) }; PrecalculatedDateTimeZone.ValidatePeriods(intervals, DateTimeZone.Utc); } [Test] public void Validation_NullTailZoneWithMiddleOfTimeFinalPeriod() { ZoneInterval[] intervals = { new ZoneInterval("foo", Instant.BeforeMinValue, Instant.FromUnixTimeTicks(20), Offset.Zero, Offset.Zero), new ZoneInterval("foo", Instant.FromUnixTimeTicks(20), Instant.FromUnixTimeTicks(30), Offset.Zero, Offset.Zero) }; Assert.Throws<ArgumentException>(() => PrecalculatedDateTimeZone.ValidatePeriods(intervals, null)); } [Test] public void Validation_NullTailZoneWithEotPeriodEnd() { ZoneInterval[] intervals = { new ZoneInterval("foo", Instant.BeforeMinValue, Instant.FromUnixTimeTicks(20), Offset.Zero, Offset.Zero), new ZoneInterval("foo", Instant.FromUnixTimeTicks(20), Instant.AfterMaxValue, Offset.Zero, Offset.Zero) }; PrecalculatedDateTimeZone.ValidatePeriods(intervals, null); } [Test] public void Serialization() { var stream = new MemoryStream(); var writer = new DateTimeZoneWriter(stream, null); TestZone.Write(writer); stream.Position = 0; var reloaded = PrecalculatedDateTimeZone.Read(new DateTimeZoneReader(stream, null), TestZone.Id); // Check equivalence by finding zone intervals var interval = new Interval(Instant.FromUtc(1990, 1, 1, 0, 0), Instant.FromUtc(2010, 1, 1, 0, 0)); var originalZoneIntervals = TestZone.GetZoneIntervals(interval, ZoneEqualityComparer.Options.StrictestMatch).ToList(); var reloadedZoneIntervals = TestZone.GetZoneIntervals(interval, ZoneEqualityComparer.Options.StrictestMatch).ToList(); CollectionAssert.AreEqual(originalZoneIntervals, reloadedZoneIntervals); } } }
/***************************************************************************** * Skeleton Utility created by Mitch Thompson * Full irrevocable rights and permissions granted to Esoteric Software *****************************************************************************/ using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using Spine; [CustomEditor(typeof(SkeletonUtilityBone)), CanEditMultipleObjects] public class SkeletonUtilityBoneInspector : Editor { SerializedProperty mode, boneName, zPosition, position, rotation, scale, overrideAlpha, parentReference, flip, flipX; //multi selected flags bool containsFollows, containsOverrides, multiObject; //single selected helpers SkeletonUtilityBone utilityBone; SkeletonUtility skeletonUtility; bool canCreateHingeChain = false; Dictionary<Slot, List<BoundingBoxAttachment>> boundingBoxTable = new Dictionary<Slot, List<BoundingBoxAttachment>>(); string currentSkinName = ""; void OnEnable () { mode = this.serializedObject.FindProperty("mode"); boneName = this.serializedObject.FindProperty("boneName"); zPosition = this.serializedObject.FindProperty("zPosition"); position = this.serializedObject.FindProperty("position"); rotation = this.serializedObject.FindProperty("rotation"); scale = this.serializedObject.FindProperty("scale"); overrideAlpha = this.serializedObject.FindProperty("overrideAlpha"); parentReference = this.serializedObject.FindProperty("parentReference"); flip = this.serializedObject.FindProperty("flip"); flipX = this.serializedObject.FindProperty("flipX"); EvaluateFlags(); if (utilityBone.valid == false && skeletonUtility != null && skeletonUtility.skeletonRenderer != null) { skeletonUtility.skeletonRenderer.Initialize(false); } canCreateHingeChain = CanCreateHingeChain(); boundingBoxTable.Clear(); if (multiObject) return; if (utilityBone.bone == null) return; var skeleton = utilityBone.bone.Skeleton; int slotCount = skeleton.Slots.Count; Skin skin = skeleton.Skin; if (skeleton.Skin == null) skin = skeleton.Data.DefaultSkin; currentSkinName = skin.Name; for(int i = 0; i < slotCount; i++){ Slot slot = skeletonUtility.skeletonRenderer.skeleton.Slots.Items[i]; if (slot.Bone == utilityBone.bone) { List<Attachment> attachments = new List<Attachment>(); skin.FindAttachmentsForSlot(skeleton.FindSlotIndex(slot.Data.Name), attachments); List<BoundingBoxAttachment> boundingBoxes = new List<BoundingBoxAttachment>(); foreach (var att in attachments) { if (att is BoundingBoxAttachment) { boundingBoxes.Add((BoundingBoxAttachment)att); } } if (boundingBoxes.Count > 0) { boundingBoxTable.Add(slot, boundingBoxes); } } } } void EvaluateFlags () { utilityBone = (SkeletonUtilityBone)target; skeletonUtility = utilityBone.skeletonUtility; if (Selection.objects.Length == 1) { containsFollows = utilityBone.mode == SkeletonUtilityBone.Mode.Follow; containsOverrides = utilityBone.mode == SkeletonUtilityBone.Mode.Override; } else { int boneCount = 0; foreach (Object o in Selection.objects) { if (o is GameObject) { GameObject go = (GameObject)o; SkeletonUtilityBone sub = go.GetComponent<SkeletonUtilityBone>(); if (sub != null) { boneCount++; if (sub.mode == SkeletonUtilityBone.Mode.Follow) containsFollows = true; if (sub.mode == SkeletonUtilityBone.Mode.Override) containsOverrides = true; } } } if (boneCount > 1) multiObject = true; } } public override void OnInspectorGUI () { serializedObject.Update(); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(mode); if (EditorGUI.EndChangeCheck()) { containsOverrides = mode.enumValueIndex == 1; containsFollows = mode.enumValueIndex == 0; } EditorGUI.BeginDisabledGroup(multiObject); { string str = boneName.stringValue; if (str == "") str = "<None>"; if (multiObject) str = "<Multiple>"; GUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Bone"); if (GUILayout.Button(str, EditorStyles.popup)) { BoneSelectorContextMenu(str, ((SkeletonUtilityBone)target).skeletonUtility.skeletonRenderer.skeleton.Bones, "<None>", TargetBoneSelected); } GUILayout.EndHorizontal(); } EditorGUI.EndDisabledGroup(); EditorGUILayout.PropertyField(zPosition); EditorGUILayout.PropertyField(position); EditorGUILayout.PropertyField(rotation); EditorGUILayout.PropertyField(scale); EditorGUILayout.PropertyField(flip); EditorGUI.BeginDisabledGroup(containsFollows); { EditorGUILayout.PropertyField(overrideAlpha); EditorGUILayout.PropertyField(parentReference); EditorGUI.BeginDisabledGroup(multiObject || !flip.boolValue); { EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(flipX); if (EditorGUI.EndChangeCheck()) { FlipX(flipX.boolValue); } } EditorGUI.EndDisabledGroup(); } EditorGUI.EndDisabledGroup(); EditorGUILayout.Space(); GUILayout.BeginHorizontal(); { EditorGUI.BeginDisabledGroup(multiObject || !utilityBone.valid || utilityBone.bone == null || utilityBone.bone.Children.Count == 0); { if (GUILayout.Button(new GUIContent("Add Child", SpineEditorUtilities.Icons.bone), GUILayout.Width(150), GUILayout.Height(24))) BoneSelectorContextMenu("", utilityBone.bone.Children, "<Recursively>", SpawnChildBoneSelected); } EditorGUI.EndDisabledGroup(); EditorGUI.BeginDisabledGroup(multiObject || !utilityBone.valid || utilityBone.bone == null || containsOverrides); { if (GUILayout.Button(new GUIContent("Add Override", SpineEditorUtilities.Icons.poseBones), GUILayout.Width(150), GUILayout.Height(24))) SpawnOverride(); } EditorGUI.EndDisabledGroup(); EditorGUI.BeginDisabledGroup(multiObject || !utilityBone.valid || !canCreateHingeChain); { if (GUILayout.Button(new GUIContent("Create Hinge Chain", SpineEditorUtilities.Icons.hingeChain), GUILayout.Width(150), GUILayout.Height(24))) CreateHingeChain(); } EditorGUI.EndDisabledGroup(); } GUILayout.EndHorizontal(); EditorGUI.BeginDisabledGroup(multiObject || boundingBoxTable.Count == 0); EditorGUILayout.LabelField(new GUIContent("Bounding Boxes", SpineEditorUtilities.Icons.boundingBox), EditorStyles.boldLabel); foreach(var entry in boundingBoxTable){ EditorGUI.indentLevel++; EditorGUILayout.LabelField(entry.Key.Data.Name); EditorGUI.indentLevel++; foreach (var box in entry.Value) { GUILayout.BeginHorizontal(); GUILayout.Space(30); if (GUILayout.Button(box.Name, GUILayout.Width(200))) { var child = utilityBone.transform.FindChild("[BoundingBox]" + box.Name); if (child != null) { var originalCollider = child.GetComponent<PolygonCollider2D>(); var updatedCollider = SkeletonUtility.AddBoundingBoxAsComponent(box, child.gameObject, originalCollider.isTrigger); originalCollider.points = updatedCollider.points; if (EditorApplication.isPlaying) Destroy(updatedCollider); else DestroyImmediate(updatedCollider); } else { utilityBone.AddBoundingBox(currentSkinName, entry.Key.Data.Name, box.Name); } } GUILayout.EndHorizontal(); } } EditorGUI.EndDisabledGroup(); serializedObject.ApplyModifiedProperties(); } void FlipX (bool state) { utilityBone.FlipX(state); if (Application.isPlaying == false) { skeletonUtility.skeletonAnimation.LateUpdate(); } } void BoneSelectorContextMenu (string current, ExposedList<Bone> bones, string topValue, GenericMenu.MenuFunction2 callback) { GenericMenu menu = new GenericMenu(); if (topValue != "") menu.AddItem(new GUIContent(topValue), current == topValue, callback, null); for (int i = 0; i < bones.Count; i++) { menu.AddItem(new GUIContent(bones.Items[i].Data.Name), bones.Items[i].Data.Name == current, callback, bones.Items[i]); } menu.ShowAsContext(); } void TargetBoneSelected (object obj) { if (obj == null) { boneName.stringValue = ""; serializedObject.ApplyModifiedProperties(); } else { Bone bone = (Bone)obj; boneName.stringValue = bone.Data.Name; serializedObject.ApplyModifiedProperties(); utilityBone.Reset(); } } void SpawnChildBoneSelected (object obj) { if (obj == null) { //add recursively foreach (var bone in utilityBone.bone.Children) { GameObject go = skeletonUtility.SpawnBoneRecursively(bone, utilityBone.transform, utilityBone.mode, utilityBone.position, utilityBone.rotation, utilityBone.scale); SkeletonUtilityBone[] newUtilityBones = go.GetComponentsInChildren<SkeletonUtilityBone>(); foreach (SkeletonUtilityBone utilBone in newUtilityBones) SkeletonUtilityInspector.AttachIcon(utilBone); } } else { Bone bone = (Bone)obj; GameObject go = skeletonUtility.SpawnBone(bone, utilityBone.transform, utilityBone.mode, utilityBone.position, utilityBone.rotation, utilityBone.scale); SkeletonUtilityInspector.AttachIcon(go.GetComponent<SkeletonUtilityBone>()); Selection.activeGameObject = go; EditorGUIUtility.PingObject(go); } } void SpawnOverride () { GameObject go = skeletonUtility.SpawnBone(utilityBone.bone, utilityBone.transform.parent, SkeletonUtilityBone.Mode.Override, utilityBone.position, utilityBone.rotation, utilityBone.scale); go.name = go.name + " [Override]"; SkeletonUtilityInspector.AttachIcon(go.GetComponent<SkeletonUtilityBone>()); Selection.activeGameObject = go; EditorGUIUtility.PingObject(go); } bool CanCreateHingeChain () { if (utilityBone == null) return false; if (utilityBone.GetComponent<Rigidbody>() != null) return false; if (utilityBone.bone != null && utilityBone.bone.Children.Count == 0) return false; Rigidbody[] rigidbodies = utilityBone.GetComponentsInChildren<Rigidbody>(); if (rigidbodies.Length > 0) return false; return true; } void CreateHingeChain () { var utilBoneArr = utilityBone.GetComponentsInChildren<SkeletonUtilityBone>(); foreach (var utilBone in utilBoneArr) { AttachRigidbody(utilBone); } utilityBone.GetComponent<Rigidbody>().isKinematic = true; foreach (var utilBone in utilBoneArr) { if (utilBone == utilityBone) continue; utilBone.mode = SkeletonUtilityBone.Mode.Override; HingeJoint joint = utilBone.gameObject.AddComponent<HingeJoint>(); joint.axis = Vector3.forward; joint.connectedBody = utilBone.transform.parent.GetComponent<Rigidbody>(); joint.useLimits = true; JointLimits limits = new JointLimits(); limits.min = -20; limits.max = 20; joint.limits = limits; utilBone.GetComponent<Rigidbody>().mass = utilBone.transform.parent.GetComponent<Rigidbody>().mass * 0.75f; } } void AttachRigidbody (SkeletonUtilityBone utilBone) { if (utilBone.GetComponent<Collider>() == null) { if (utilBone.bone.Data.Length == 0) { SphereCollider sphere = utilBone.gameObject.AddComponent<SphereCollider>(); sphere.radius = 0.1f; } else { float length = utilBone.bone.Data.Length; BoxCollider box = utilBone.gameObject.AddComponent<BoxCollider>(); box.size = new Vector3(length, length / 3, 0.2f); box.center = new Vector3(length / 2, 0, 0); } } utilBone.gameObject.AddComponent<Rigidbody>(); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace TypeScripter.Common { public static class Utils { public static string Camelize(this string value) { char[] chars = value.ToCharArray(); chars[0] = char.ToLower(chars[0]); return new string(chars); } public static bool WriteIfChanged(string text, string path) { if(!File.Exists(path) || !string.Equals(text, File.ReadAllText(path))) { File.WriteAllText(path, text); return true; } return false; } public static TypeDetails ToTypeScriptType(this Type t, PropertyInfo p = null) { if (IsModelType(t) || t.IsEnum) { return new TypeDetails(t.Name); } if (t == typeof(bool)) { return new TypeDetails("boolean"); } if ( t == typeof(byte) || t == typeof(sbyte) || t == typeof(ushort) || t == typeof(short) || t == typeof(uint) || t == typeof(int) || t == typeof(ulong) || t == typeof(long) || t == typeof(float) || t == typeof(double) || t == typeof(decimal)) { return new TypeDetails("number"); } if (t == typeof(string) || t == typeof(char) || t == typeof(Guid)) { return new TypeDetails("string"); } if (t.IsArray) { return new TypeDetails(ToTypeScriptType(t.GetElementType(), p) + "[]", " = []"); } if (t.IsGenericType && IsGenericEnumerable(t)) { return new TypeDetails(ToTypeScriptType(t.GetGenericArguments()[0], p) + "[]", " = []"); } if (t.Name == "Nullable`1") { return ToTypeScriptType(t.GetGenericArguments()[0], p); } if (t == typeof(DateTime)) { var utc = p?.GetCustomAttributes().Any(x => x.GetType().Name == "TypeScripterUtcDateAttribute"); return new TypeDetails("moment.Moment"){UtcDate = utc ?? false}; } if (t.IsGenericType && t.GetGenericArguments().Length == 1) { return ToTypeScriptType(t.GetGenericArguments()[0], p); } return new TypeDetails("any"); } private static bool IsGenericEnumerable(Type t) { if (!t.IsGenericType) { return false; } var typeDef = t.GetGenericTypeDefinition(); return typeDef != typeof(Dictionary<,>) && typeDef != typeof(IDictionary<,>) && ( typeDef == typeof(IEnumerable<>) || t.GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>)) ); } public static bool IsModelType(this Type t) { if(!t.IsClass || t.Namespace == null || t == typeof(string)) { return false; } bool isModel = t.FullName != null && !t.FullName.StartsWith("System.") && !t.FullName.StartsWith("Microsoft."); return isModel; } private static readonly HashSet<string> NonModelTypes = new HashSet<string> {"boolean", "number", "string", "moment.Moment", "any"}; public static bool IsOrContainsModelType(this Type type) { // Note: When Enum support is implemented, this code will need to // be updated to handle enums properly (right now enums act // like objects) var typescriptType = ToTypeScriptType(type).Name.Replace("[]", ""); return !NonModelTypes.Contains(typescriptType); } public static Type GetPropertyType(this PropertyInfo pi) { if(pi.PropertyType.IsGenericType) { return pi.PropertyType.GetGenericArguments()[0]; } return pi.PropertyType; } public static bool IsNotAbstractModelType(this Type t) { return !t.IsAbstract && IsModelType(t); } public static ClassMemberInfo[] GetAllPropertiesInType(this Type t) { return t.GetProperties(BindingFlags.Public | BindingFlags.Instance) .Select(p => new ClassMemberInfo { Name = p.Name, Type = ToTypeScriptType(p.PropertyType, p) }) .Distinct() .OrderBy(p => p.Name) .ToArray(); } public static ClassMemberInfo[] GetDeclaredPropertiesInType(this Type t) { return t.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) .Select(p => new ClassMemberInfo { Name = p.Name, Type = ToTypeScriptType(p.PropertyType,p) }) .Distinct() .OrderBy(p => p.Name) .ToArray(); } public static ClassMemberInfo[] GetStaticPropertiesForType(this Type t) { var result = t.GetDeclaredConstantsInType(); var emitStaticReadonlyMembers = t.GetInterface("ITypeScripterEmitStaticReadonlyMembers") != null; if (emitStaticReadonlyMembers) { result = result.Concat(t.GetStaticReadonlyPropertiesInType()).ToArray(); } return result; } private static ClassMemberInfo[] GetDeclaredConstantsInType(this Type t) { Type[] allowedTypes = { typeof(int), typeof(string) }; return t.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly) .Where(x => x.IsLiteral && !x.IsInitOnly && allowedTypes.Contains(x.FieldType)) .Select(p => new ClassMemberInfo { Name = p.Name, Type = ToTypeScriptType(p.FieldType), Value = p.GetRawConstantValue().ToString() }).Distinct() .OrderBy(p => p.Name) .ToArray(); } private static ClassMemberInfo[] GetStaticReadonlyPropertiesInType(this Type t) { return t .GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly) .Where(x => x.IsInitOnly) .Select(x => new ClassMemberInfo { Name = x.Name, Type = ToTypeScriptType(x.FieldType), Value = x.GetValue(null).ToString() }) .Distinct() .OrderBy(x => x.Name) .ToArray(); } public static IEnumerable<string> FindChildModelTypeNames(this Type parentType) { return parentType.GetProperties(BindingFlags.Public | BindingFlags.Instance) .Select(p => p.GetPropertyType()) .Where(t => t.IsModelType() || t.IsEnum) .Where(x => x != parentType) .Distinct() .OrderBy(p => p.Name) .Select(p => p.Name) .ToArray(); } public static ClassMemberInfo[] GetItterableModelPropertiesInType(this Type t) { return t.GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(x => x.PropertyType.IsGenericType && typeof(IEnumerable<object>).IsAssignableFrom(x.PropertyType) && x.PropertyType.GetGenericArguments()[0].IsNotAbstractModelType()) .Select(p => new ClassMemberInfo() { Name = p.Name, Type = p.PropertyType.GetGenericArguments()[0].ToTypeScriptType(p:p) }) .Distinct() .OrderBy(p => p.Name) .ToArray(); } public static ClassMemberInfo[] GetModelPropertiesInType(this Type t) { return t.GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(x => x.PropertyType.IsNotAbstractModelType()) .Select(p => new ClassMemberInfo { Name = p.Name, Type = p.PropertyType.ToTypeScriptType(p:p) }) .Distinct() .OrderBy(p => p.Name) .ToArray(); } } }
using System; using System.Threading; using Microsoft.Extensions.Logging; using Orleans.Messaging; using Orleans.Serialization; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.Hosting; namespace Orleans.Runtime.Messaging { internal class MessageCenter : ISiloMessageCenter, IDisposable { private Gateway Gateway { get; set; } private IncomingMessageAcceptor ima; private readonly ILogger log; private Action<Message> rerouteHandler; internal Func<Message, bool> ShouldDrop; private IHostedClient hostedClient; // ReSharper disable NotAccessedField.Local private IntValueStatistic sendQueueLengthCounter; private IntValueStatistic receiveQueueLengthCounter; // ReSharper restore NotAccessedField.Local internal IOutboundMessageQueue OutboundQueue { get; set; } internal IInboundMessageQueue InboundQueue { get; set; } internal SocketManager SocketManager; private readonly SerializationManager serializationManager; private readonly MessageFactory messageFactory; private readonly ILoggerFactory loggerFactory; private readonly ExecutorService executorService; private readonly Action<Message>[] localMessageHandlers; internal bool IsBlockingApplicationMessages { get; private set; } public void SetHostedClient(IHostedClient client) => this.hostedClient = client; public bool IsProxying => this.Gateway != null || this.hostedClient?.ClientId != null; public bool TryDeliverToProxy(Message msg) { if (!msg.TargetGrain.IsClient) return false; if (this.Gateway != null && this.Gateway.TryDeliverToProxy(msg)) return true; return this.hostedClient?.TryDispatchToClient(msg) ?? false; } // This is determined by the IMA but needed by the OMS, and so is kept here in the message center itself. public SiloAddress MyAddress { get; private set; } public MessageCenter( ILocalSiloDetails siloDetails, IOptions<EndpointOptions> endpointOptions, IOptions<SiloMessagingOptions> messagingOptions, IOptions<NetworkingOptions> networkingOptions, SerializationManager serializationManager, MessageFactory messageFactory, Factory<MessageCenter, Gateway> gatewayFactory, ExecutorService executorService, ILoggerFactory loggerFactory, IOptions<StatisticsOptions> statisticsOptions) { this.loggerFactory = loggerFactory; this.log = loggerFactory.CreateLogger<MessageCenter>(); this.serializationManager = serializationManager; this.messageFactory = messageFactory; this.executorService = executorService; this.MyAddress = siloDetails.SiloAddress; this.Initialize(endpointOptions, messagingOptions, networkingOptions, statisticsOptions); if (siloDetails.GatewayAddress != null) { Gateway = gatewayFactory(this); } localMessageHandlers = new Action<Message>[Enum.GetValues(typeof(Message.Categories)).Length]; } private void Initialize(IOptions<EndpointOptions> endpointOptions, IOptions<SiloMessagingOptions> messagingOptions, IOptions<NetworkingOptions> networkingOptions, IOptions<StatisticsOptions> statisticsOptions) { if (log.IsEnabled(LogLevel.Trace)) log.Trace("Starting initialization."); SocketManager = new SocketManager(networkingOptions, this.loggerFactory); var listeningEndpoint = endpointOptions.Value.GetListeningSiloEndpoint(); ima = new IncomingMessageAcceptor(this, listeningEndpoint, SocketDirection.SiloToSilo, this.messageFactory, this.serializationManager, this.executorService, this.loggerFactory); InboundQueue = new InboundMessageQueue(this.loggerFactory, statisticsOptions); OutboundQueue = new OutboundMessageQueue(this, messagingOptions, this.serializationManager, this.executorService, this.loggerFactory); sendQueueLengthCounter = IntValueStatistic.FindOrCreate(StatisticNames.MESSAGE_CENTER_SEND_QUEUE_LENGTH, () => SendQueueLength); receiveQueueLengthCounter = IntValueStatistic.FindOrCreate(StatisticNames.MESSAGE_CENTER_RECEIVE_QUEUE_LENGTH, () => ReceiveQueueLength); if (log.IsEnabled(LogLevel.Trace)) log.Trace("Completed initialization."); } public void Start() { IsBlockingApplicationMessages = false; ima.Start(); OutboundQueue.Start(); } public void StartGateway(ClientObserverRegistrar clientRegistrar) { if (Gateway != null) Gateway.Start(clientRegistrar); } public void PrepareToStop() { } public void Stop() { IsBlockingApplicationMessages = true; try { ima.Stop(); } catch (Exception exc) { log.Error(ErrorCode.Runtime_Error_100108, "Stop failed.", exc); } StopAcceptingClientMessages(); try { OutboundQueue.Stop(); } catch (Exception exc) { log.Error(ErrorCode.Runtime_Error_100110, "Stop failed.", exc); } try { SocketManager.Stop(); } catch (Exception exc) { log.Error(ErrorCode.Runtime_Error_100111, "Stop failed.", exc); } } public void StopAcceptingClientMessages() { if (log.IsEnabled(LogLevel.Debug)) log.Debug("StopClientMessages"); if (Gateway == null) return; try { Gateway.Stop(); } catch (Exception exc) { log.Error(ErrorCode.Runtime_Error_100109, "Stop failed.", exc); } Gateway = null; } public Action<Message> RerouteHandler { set { if (rerouteHandler != null) throw new InvalidOperationException("MessageCenter RerouteHandler already set"); rerouteHandler = value; } } public void RerouteMessage(Message message) { if (rerouteHandler != null) rerouteHandler(message); else SendMessage(message); } public Action<Message> SniffIncomingMessage { set { ima.SniffIncomingMessage = value; } } public Func<SiloAddress, bool> SiloDeadOracle { get; set; } public void SendMessage(Message msg) { // Note that if we identify or add other grains that are required for proper stopping, we will need to treat them as we do the membership table grain here. if (IsBlockingApplicationMessages && (msg.Category == Message.Categories.Application) && (msg.Result != Message.ResponseTypes.Rejection) && !Constants.SystemMembershipTableId.Equals(msg.TargetGrain)) { // Drop the message on the floor if it's an application message that isn't a rejection } else { if (msg.SendingSilo == null) msg.SendingSilo = MyAddress; OutboundQueue.SendMessage(msg); } } public bool TrySendLocal(Message message) { if (!message.TargetSilo.Equals(MyAddress)) { return false; } if (log.IsEnabled(LogLevel.Trace)) log.Trace("Message has been looped back to this silo: {0}", message); MessagingStatisticsGroup.LocalMessagesSent.Increment(); var localHandler = localMessageHandlers[(int) message.Category]; if (localHandler != null) { localHandler(message); } else { InboundQueue.PostMessage(message); } return true; } internal void SendRejection(Message msg, Message.RejectionTypes rejectionType, string reason) { MessagingStatisticsGroup.OnRejectedMessage(msg); if (string.IsNullOrEmpty(reason)) reason = string.Format("Rejection from silo {0} - Unknown reason.", MyAddress); Message error = this.messageFactory.CreateRejectionResponse(msg, rejectionType, reason); // rejection msgs are always originated in the local silo, they are never remote. InboundQueue.PostMessage(error); } public Message WaitMessage(Message.Categories type, CancellationToken ct) { return InboundQueue.WaitMessage(type); } public void RegisterLocalMessageHandler(Message.Categories category, Action<Message> handler) { localMessageHandlers[(int) category] = handler; } public void Dispose() { if (ima != null) { ima.Dispose(); ima = null; } InboundQueue?.Dispose(); OutboundQueue?.Dispose(); GC.SuppressFinalize(this); } public int SendQueueLength { get { return OutboundQueue.Count; } } public int ReceiveQueueLength { get { return InboundQueue.Count; } } /// <summary> /// Indicates that application messages should be blocked from being sent or received. /// This method is used by the "fast stop" process. /// <para> /// Specifically, all outbound application messages are dropped, except for rejections and messages to the membership table grain. /// Inbound application requests are rejected, and other inbound application messages are dropped. /// </para> /// </summary> public void BlockApplicationMessages() { if(log.IsEnabled(LogLevel.Debug)) log.Debug("BlockApplicationMessages"); IsBlockingApplicationMessages = true; } } }
#if UNITY_EDITOR using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEditor; using UMA; namespace UMAEditor { //[CustomEditor(typeof(SlotDataAsset))] public class SlotInspector : Editor { [MenuItem("Assets/Create/UMA Slot Asset")] public static void CreateSlotMenuItem() { CustomAssetUtility.CreateAsset<SlotDataAsset>(); } static private void RecurseTransformsInPrefab(Transform root, List<Transform> transforms) { for (int i = 0; i < root.childCount; i++) { Transform child = root.GetChild(i); transforms.Add(child); RecurseTransformsInPrefab(child, transforms); } } static protected Transform[] GetTransformsInPrefab(Transform prefab) { List<Transform> transforms = new List<Transform>(); RecurseTransformsInPrefab(prefab, transforms); return transforms.ToArray(); } protected SlotDataAsset slot; protected bool showBones; protected Vector2 boneScroll = new Vector2(); protected Transform[] umaBoneData; public void OnEnable() { slot = target as SlotDataAsset; #pragma warning disable 618 if (slot.meshData != null) { //if (slot.meshData.rootBoneHash != null) //{ // umaBoneData = GetTransformsInPrefab(slot.meshData.rootBone); //} //else //{ umaBoneData = new Transform[0]; //} } #if !UMA2_LEAN_AND_CLEAN else if (slot.meshRenderer != null) { umaBoneData = GetTransformsInPrefab(slot.meshRenderer.rootBone); } #endif else { umaBoneData = new Transform[0]; } #pragma warning restore 618 } public override void OnInspectorGUI() { // TODO deprecated #pragma warning disable 0618 EditorGUIUtility.LookLikeControls(); slot.slotName = EditorGUILayout.TextField("Slot Name", slot.slotName); slot.slotDNA = EditorGUILayout.ObjectField("DNA Converter", slot.slotDNA, typeof(DnaConverterBehaviour), false) as DnaConverterBehaviour; EditorGUILayout.Space(); slot.subMeshIndex = EditorGUILayout.IntField("Sub Mesh Index", slot.subMeshIndex); if (GUI.changed) { EditorUtility.SetDirty(slot); } EditorGUILayout.Space(); if (umaBoneData == null) { showBones = false; GUI.enabled = false; } showBones = EditorGUILayout.Foldout(showBones, "Bones"); if (showBones) { EditorGUI.indentLevel++; EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Name"); GUILayout.FlexibleSpace(); EditorGUILayout.LabelField("Animated"); GUILayout.Space(40f); EditorGUILayout.EndHorizontal(); boneScroll = EditorGUILayout.BeginScrollView(boneScroll); EditorGUILayout.BeginVertical(); foreach (Transform bone in umaBoneData) { bool wasAnimated = ArrayUtility.Contains<Transform>(slot.animatedBones, bone); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(bone.name); bool animated = EditorGUILayout.Toggle(wasAnimated, GUILayout.Width(40f)); if (animated != wasAnimated) { if (animated) { ArrayUtility.Add<Transform>(ref slot.animatedBones, bone); EditorUtility.SetDirty(slot); } else { ArrayUtility.Remove<Transform>(ref slot.animatedBones, bone); EditorUtility.SetDirty(slot); } } EditorGUILayout.EndHorizontal(); } EditorGUILayout.EndVertical(); EditorGUILayout.EndScrollView(); EditorGUI.indentLevel--; if (GUILayout.Button("Clear Animated Bones")) { slot.animatedBones = new Transform[0]; EditorUtility.SetDirty(slot); } } GUI.enabled = true; EditorGUILayout.Space(); slot.slotGroup = EditorGUILayout.TextField("Slot Group", slot.slotGroup); var textureNameList = serializedObject.FindProperty("textureNameList"); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(textureNameList, true); if (EditorGUI.EndChangeCheck()) { serializedObject.ApplyModifiedProperties(); } SerializedProperty tags = serializedObject.FindProperty("tags"); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(tags, true); if (EditorGUI.EndChangeCheck()) { serializedObject.ApplyModifiedProperties(); } SerializedProperty begunCallback = serializedObject.FindProperty("CharacterBegun"); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(begunCallback, true); if (EditorGUI.EndChangeCheck()) { serializedObject.ApplyModifiedProperties(); } SerializedProperty atlasCallback = serializedObject.FindProperty("SlotAtlassed"); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(atlasCallback, true); if (EditorGUI.EndChangeCheck()) { serializedObject.ApplyModifiedProperties(); } SerializedProperty dnaAppliedCallback = serializedObject.FindProperty("DNAApplied"); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(dnaAppliedCallback, true); if (EditorGUI.EndChangeCheck()) { serializedObject.ApplyModifiedProperties(); } SerializedProperty characterCompletedCallback = serializedObject.FindProperty("CharacterCompleted"); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(characterCompletedCallback, true); if (EditorGUI.EndChangeCheck()) { serializedObject.ApplyModifiedProperties(); } foreach (var field in slot.GetType().GetFields()) { foreach (var attribute in System.Attribute.GetCustomAttributes(field)) { if (attribute is UMAAssetFieldVisible) { SerializedProperty serializedProp = serializedObject.FindProperty(field.Name); EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(serializedProp); if (EditorGUI.EndChangeCheck()) { serializedObject.ApplyModifiedProperties(); } break; } } } EditorGUIUtility.LookLikeControls(); if (GUI.changed) { EditorUtility.SetDirty(slot); AssetDatabase.SaveAssets(); } } } } #endif
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Text; using System.Diagnostics; using System.Globalization; using System.Collections.Generic; using System.Runtime.InteropServices; using Internal.NativeCrypto; using Internal.Cryptography; using Internal.Cryptography.Pal.Native; using System.Security.Cryptography; using FILETIME = Internal.Cryptography.Pal.Native.FILETIME; using SafeX509ChainHandle = Microsoft.Win32.SafeHandles.SafeX509ChainHandle; using System.Security.Cryptography.X509Certificates; namespace Internal.Cryptography.Pal { internal sealed partial class ChainPal : IDisposable, IChainPal { private static X509ChainStatus[] GetChainStatusInformation(CertTrustErrorStatus dwStatus) { if (dwStatus == CertTrustErrorStatus.CERT_TRUST_NO_ERROR) return Array.Empty<X509ChainStatus>(); int count = 0; for (uint bits = (uint)dwStatus; bits != 0; bits = bits >> 1) { if ((bits & 0x1) != 0) count++; } X509ChainStatus[] chainStatus = new X509ChainStatus[count]; int index = 0; if ((dwStatus & CertTrustErrorStatus.CERT_TRUST_IS_NOT_SIGNATURE_VALID) != 0) { chainStatus[index].StatusInformation = GetSystemErrorString(ErrorCode.TRUST_E_CERT_SIGNATURE); chainStatus[index].Status = X509ChainStatusFlags.NotSignatureValid; index++; dwStatus &= ~CertTrustErrorStatus.CERT_TRUST_IS_NOT_SIGNATURE_VALID; } if ((dwStatus & CertTrustErrorStatus.CERT_TRUST_CTL_IS_NOT_SIGNATURE_VALID) != 0) { chainStatus[index].StatusInformation = GetSystemErrorString(ErrorCode.TRUST_E_CERT_SIGNATURE); chainStatus[index].Status = X509ChainStatusFlags.CtlNotSignatureValid; index++; dwStatus &= ~CertTrustErrorStatus.CERT_TRUST_CTL_IS_NOT_SIGNATURE_VALID; } if ((dwStatus & CertTrustErrorStatus.CERT_TRUST_IS_UNTRUSTED_ROOT) != 0) { chainStatus[index].StatusInformation = GetSystemErrorString(ErrorCode.CERT_E_UNTRUSTEDROOT); chainStatus[index].Status = X509ChainStatusFlags.UntrustedRoot; index++; dwStatus &= ~CertTrustErrorStatus.CERT_TRUST_IS_UNTRUSTED_ROOT; } if ((dwStatus & CertTrustErrorStatus.CERT_TRUST_IS_PARTIAL_CHAIN) != 0) { chainStatus[index].StatusInformation = GetSystemErrorString(ErrorCode.CERT_E_CHAINING); chainStatus[index].Status = X509ChainStatusFlags.PartialChain; index++; dwStatus &= ~CertTrustErrorStatus.CERT_TRUST_IS_PARTIAL_CHAIN; } if ((dwStatus & CertTrustErrorStatus.CERT_TRUST_IS_REVOKED) != 0) { chainStatus[index].StatusInformation = GetSystemErrorString(ErrorCode.CRYPT_E_REVOKED); chainStatus[index].Status = X509ChainStatusFlags.Revoked; index++; dwStatus &= ~CertTrustErrorStatus.CERT_TRUST_IS_REVOKED; } if ((dwStatus & CertTrustErrorStatus.CERT_TRUST_IS_NOT_VALID_FOR_USAGE) != 0) { chainStatus[index].StatusInformation = GetSystemErrorString(ErrorCode.CERT_E_WRONG_USAGE); chainStatus[index].Status = X509ChainStatusFlags.NotValidForUsage; index++; dwStatus &= ~CertTrustErrorStatus.CERT_TRUST_IS_NOT_VALID_FOR_USAGE; } if ((dwStatus & CertTrustErrorStatus.CERT_TRUST_CTL_IS_NOT_VALID_FOR_USAGE) != 0) { chainStatus[index].StatusInformation = GetSystemErrorString(ErrorCode.CERT_E_WRONG_USAGE); chainStatus[index].Status = X509ChainStatusFlags.CtlNotValidForUsage; index++; dwStatus &= ~CertTrustErrorStatus.CERT_TRUST_CTL_IS_NOT_VALID_FOR_USAGE; } if ((dwStatus & CertTrustErrorStatus.CERT_TRUST_IS_NOT_TIME_VALID) != 0) { chainStatus[index].StatusInformation = GetSystemErrorString(ErrorCode.CERT_E_EXPIRED); chainStatus[index].Status = X509ChainStatusFlags.NotTimeValid; index++; dwStatus &= ~CertTrustErrorStatus.CERT_TRUST_IS_NOT_TIME_VALID; } if ((dwStatus & CertTrustErrorStatus.CERT_TRUST_CTL_IS_NOT_TIME_VALID) != 0) { chainStatus[index].StatusInformation = GetSystemErrorString(ErrorCode.CERT_E_EXPIRED); chainStatus[index].Status = X509ChainStatusFlags.CtlNotTimeValid; index++; dwStatus &= ~CertTrustErrorStatus.CERT_TRUST_CTL_IS_NOT_TIME_VALID; } if ((dwStatus & CertTrustErrorStatus.CERT_TRUST_INVALID_NAME_CONSTRAINTS) != 0) { chainStatus[index].StatusInformation = GetSystemErrorString(ErrorCode.CERT_E_INVALID_NAME); chainStatus[index].Status = X509ChainStatusFlags.InvalidNameConstraints; index++; dwStatus &= ~CertTrustErrorStatus.CERT_TRUST_INVALID_NAME_CONSTRAINTS; } if ((dwStatus & CertTrustErrorStatus.CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT) != 0) { chainStatus[index].StatusInformation = GetSystemErrorString(ErrorCode.CERT_E_INVALID_NAME); chainStatus[index].Status = X509ChainStatusFlags.HasNotSupportedNameConstraint; index++; dwStatus &= ~CertTrustErrorStatus.CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT; } if ((dwStatus & CertTrustErrorStatus.CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT) != 0) { chainStatus[index].StatusInformation = GetSystemErrorString(ErrorCode.CERT_E_INVALID_NAME); chainStatus[index].Status = X509ChainStatusFlags.HasNotDefinedNameConstraint; index++; dwStatus &= ~CertTrustErrorStatus.CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT; } if ((dwStatus & CertTrustErrorStatus.CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT) != 0) { chainStatus[index].StatusInformation = GetSystemErrorString(ErrorCode.CERT_E_INVALID_NAME); chainStatus[index].Status = X509ChainStatusFlags.HasNotPermittedNameConstraint; index++; dwStatus &= ~CertTrustErrorStatus.CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT; } if ((dwStatus & CertTrustErrorStatus.CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT) != 0) { chainStatus[index].StatusInformation = GetSystemErrorString(ErrorCode.CERT_E_INVALID_NAME); chainStatus[index].Status = X509ChainStatusFlags.HasExcludedNameConstraint; index++; dwStatus &= ~CertTrustErrorStatus.CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT; } if ((dwStatus & CertTrustErrorStatus.CERT_TRUST_INVALID_POLICY_CONSTRAINTS) != 0) { chainStatus[index].StatusInformation = GetSystemErrorString(ErrorCode.CERT_E_INVALID_POLICY); chainStatus[index].Status = X509ChainStatusFlags.InvalidPolicyConstraints; index++; dwStatus &= ~CertTrustErrorStatus.CERT_TRUST_INVALID_POLICY_CONSTRAINTS; } if ((dwStatus & CertTrustErrorStatus.CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY) != 0) { chainStatus[index].StatusInformation = GetSystemErrorString(ErrorCode.CERT_E_INVALID_POLICY); chainStatus[index].Status = X509ChainStatusFlags.NoIssuanceChainPolicy; index++; dwStatus &= ~CertTrustErrorStatus.CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY; } if ((dwStatus & CertTrustErrorStatus.CERT_TRUST_INVALID_BASIC_CONSTRAINTS) != 0) { chainStatus[index].StatusInformation = GetSystemErrorString(ErrorCode.TRUST_E_BASIC_CONSTRAINTS); chainStatus[index].Status = X509ChainStatusFlags.InvalidBasicConstraints; index++; dwStatus &= ~CertTrustErrorStatus.CERT_TRUST_INVALID_BASIC_CONSTRAINTS; } if ((dwStatus & CertTrustErrorStatus.CERT_TRUST_IS_NOT_TIME_NESTED) != 0) { chainStatus[index].StatusInformation = GetSystemErrorString(ErrorCode.CERT_E_VALIDITYPERIODNESTING); chainStatus[index].Status = X509ChainStatusFlags.NotTimeNested; index++; dwStatus &= ~CertTrustErrorStatus.CERT_TRUST_IS_NOT_TIME_NESTED; } if ((dwStatus & CertTrustErrorStatus.CERT_TRUST_REVOCATION_STATUS_UNKNOWN) != 0) { chainStatus[index].StatusInformation = GetSystemErrorString(ErrorCode.CRYPT_E_NO_REVOCATION_CHECK); chainStatus[index].Status = X509ChainStatusFlags.RevocationStatusUnknown; index++; dwStatus &= ~CertTrustErrorStatus.CERT_TRUST_REVOCATION_STATUS_UNKNOWN; } if ((dwStatus & CertTrustErrorStatus.CERT_TRUST_IS_OFFLINE_REVOCATION) != 0) { chainStatus[index].StatusInformation = GetSystemErrorString(ErrorCode.CRYPT_E_REVOCATION_OFFLINE); chainStatus[index].Status = X509ChainStatusFlags.OfflineRevocation; index++; dwStatus &= ~CertTrustErrorStatus.CERT_TRUST_IS_OFFLINE_REVOCATION; } int shiftCount = 0; for (uint bits = (uint)dwStatus; bits != 0; bits = bits >> 1) { if ((bits & 0x1) != 0) { chainStatus[index].Status = (X509ChainStatusFlags)(1 << shiftCount); chainStatus[index].StatusInformation = SR.Unknown_Error; index++; } shiftCount++; } return chainStatus; } private static String GetSystemErrorString(int errorCode) { StringBuilder strMessage = new StringBuilder(512); int dwErrorCode = Interop.localization.FormatMessage( FormatMessageFlags.FORMAT_MESSAGE_FROM_SYSTEM | FormatMessageFlags.FORMAT_MESSAGE_IGNORE_INSERTS, IntPtr.Zero, errorCode, 0, strMessage, strMessage.Capacity, IntPtr.Zero); if (dwErrorCode != 0) return strMessage.ToString(); else return SR.Unknown_Error; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using Microsoft.Azure; namespace Microsoft.WindowsAzure.Management.Compute.Models { /// <summary> /// Parameters returned from the Create Virtual Machine Image operation. /// </summary> public partial class VirtualMachineOSImageUpdateResponse : AzureOperationResponse { private string _category; /// <summary> /// Optional. The repository classification of the image. All user /// images have the category User. /// </summary> public string Category { get { return this._category; } set { this._category = value; } } private string _description; /// <summary> /// Optional. Specifies the description of the OS image. /// </summary> public string Description { get { return this._description; } set { this._description = value; } } private string _eula; /// <summary> /// Optional. Specifies the End User License Agreement that is /// associated with the image. The value for this element is a string, /// but it is recommended that the value be a URL that points to a /// EULA. /// </summary> public string Eula { get { return this._eula; } set { this._eula = value; } } private string _iconUri; /// <summary> /// Optional. Specifies the URI to the icon that is displayed for the /// image in the Management Portal. /// </summary> public string IconUri { get { return this._iconUri; } set { this._iconUri = value; } } private string _imageFamily; /// <summary> /// Optional. Specifies a value that can be used to group OS images. /// </summary> public string ImageFamily { get { return this._imageFamily; } set { this._imageFamily = value; } } private string _iOType; /// <summary> /// Optional. Gets or sets the IO type. /// </summary> public string IOType { get { return this._iOType; } set { this._iOType = value; } } private bool? _isPremium; /// <summary> /// Optional. Indicates if the image contains software or associated /// services that will incur charges above the core price for the /// virtual machine. /// </summary> public bool? IsPremium { get { return this._isPremium; } set { this._isPremium = value; } } private string _label; /// <summary> /// Optional. Specifies the friendly name of the image. /// </summary> public string Label { get { return this._label; } set { this._label = value; } } private string _language; /// <summary> /// Optional. Specifies the language of the image. The Language element /// is only available using version 2013-03-01 or higher. /// </summary> public string Language { get { return this._language; } set { this._language = value; } } private string _location; /// <summary> /// Optional. The geo-location in which this media is located. The /// Location value is derived from storage account that contains the /// blob in which the media is located. If the storage account belongs /// to an affinity group the value is NULL. If the version is set to /// 2012-08-01 or later, the locations are returned for platform /// images; otherwise, this value is NULL for platform images. /// </summary> public string Location { get { return this._location; } set { this._location = value; } } private double _logicalSizeInGB; /// <summary> /// Optional. The size, in GB, of the image. /// </summary> public double LogicalSizeInGB { get { return this._logicalSizeInGB; } set { this._logicalSizeInGB = value; } } private Uri _mediaLinkUri; /// <summary> /// Optional. Specifies the location of the blob in Azure storage. The /// blob location must belong to a storage account in the subscription /// specified by the SubscriptionId value in the operation call. /// Example: http://example.blob.core.windows.net/disks/mydisk.vhd. /// </summary> public Uri MediaLinkUri { get { return this._mediaLinkUri; } set { this._mediaLinkUri = value; } } private string _name; /// <summary> /// Optional. Specifies a name that Azure uses to identify the image /// when creating one or more virtual machines. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } private string _operatingSystemType; /// <summary> /// Optional. The operating system type of the OS image. Possible /// values are: Linux or Windows. /// </summary> public string OperatingSystemType { get { return this._operatingSystemType; } set { this._operatingSystemType = value; } } private Uri _privacyUri; /// <summary> /// Optional. Specifies the URI that points to a document that contains /// the privacy policy related to the OS image. /// </summary> public Uri PrivacyUri { get { return this._privacyUri; } set { this._privacyUri = value; } } private System.DateTime? _publishedDate; /// <summary> /// Optional. Specifies the date when the OS image was added to the /// image repository. /// </summary> public System.DateTime? PublishedDate { get { return this._publishedDate; } set { this._publishedDate = value; } } private string _publisherName; /// <summary> /// Optional. Specifies the name of the publisher of the image. /// </summary> public string PublisherName { get { return this._publisherName; } set { this._publisherName = value; } } private string _recommendedVMSize; /// <summary> /// Optional. Specifies the size to use for the virtual machine that is /// created from the OS image. /// </summary> public string RecommendedVMSize { get { return this._recommendedVMSize; } set { this._recommendedVMSize = value; } } private bool? _showInGui; /// <summary> /// Optional. Specifies whether the image should appear in the image /// gallery. /// </summary> public bool? ShowInGui { get { return this._showInGui; } set { this._showInGui = value; } } private string _smallIconUri; /// <summary> /// Optional. Specifies the URI to the small icon that is displayed /// when the image is presented in the Azure Management Portal. The /// SmallIconUri element is only available using version 2013-03-01 or /// higher. /// </summary> public string SmallIconUri { get { return this._smallIconUri; } set { this._smallIconUri = value; } } /// <summary> /// Initializes a new instance of the /// VirtualMachineOSImageUpdateResponse class. /// </summary> public VirtualMachineOSImageUpdateResponse() { } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Xml; using OpenMetaverse; using log4net; using Nini.Config; using Nwc.XmlRpc; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Framework.Communications.Cache; namespace OpenSimSearch.Modules.OpenSearch { public class OpenSearchModule : IRegionModule { // // Log module // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // // Module vars // private IConfigSource m_gConfig; private List<Scene> m_Scenes = new List<Scene>(); private string m_SearchServer = ""; private bool m_Enabled = true; public void Initialise(Scene scene, IConfigSource config) { if (!m_Enabled) return; IConfig searchConfig = config.Configs["Search"]; if (m_Scenes.Count == 0) // First time { if (searchConfig == null) { m_log.Info("[SEARCH] Not configured, disabling"); m_Enabled = false; return; } m_SearchServer = searchConfig.GetString("SearchURL", ""); if (m_SearchServer == "") { m_log.Error("[SEARCH] No search server, disabling search"); m_Enabled = false; return; } else { m_log.Info("[SEARCH] Search module is activated"); m_Enabled = true; } } if (!m_Scenes.Contains(scene)) m_Scenes.Add(scene); m_gConfig = config; // Hook up events scene.EventManager.OnNewClient += OnNewClient; } public void PostInitialise() { if (!m_Enabled) return; } public void Close() { } public string Name { get { return "SearchModule"; } } public bool IsSharedModule { get { return true; } } /// New Client Event Handler private void OnNewClient(IClientAPI client) { // Subscribe to messages client.OnDirPlacesQuery += DirPlacesQuery; client.OnDirFindQuery += DirFindQuery; client.OnDirPopularQuery += DirPopularQuery; client.OnDirLandQuery += DirLandQuery; client.OnDirClassifiedQuery += DirClassifiedQuery; // Response after Directory Queries client.OnEventInfoRequest += EventInfoRequest; client.OnClassifiedInfoRequest += ClassifiedInfoRequest; client.OnMapItemRequest += HandleMapItemRequest; } // // Make external XMLRPC request // private Hashtable GenericXMLRPCRequest(Hashtable ReqParams, string method) { ArrayList SendParams = new ArrayList(); SendParams.Add(ReqParams); // Send Request XmlRpcResponse Resp; try { XmlRpcRequest Req = new XmlRpcRequest(method, SendParams); Resp = Req.Send(m_SearchServer, 30000); } catch (WebException ex) { m_log.ErrorFormat("[SEARCH]: Unable to connect to Search " + "Server {0}. Exception {1}", m_SearchServer, ex); Hashtable ErrorHash = new Hashtable(); ErrorHash["success"] = false; ErrorHash["errorMessage"] = "Unable to search at this time. "; ErrorHash["errorURI"] = ""; return ErrorHash; } catch (SocketException ex) { m_log.ErrorFormat( "[SEARCH]: Unable to connect to Search Server {0}. " + "Exception {1}", m_SearchServer, ex); Hashtable ErrorHash = new Hashtable(); ErrorHash["success"] = false; ErrorHash["errorMessage"] = "Unable to search at this time. "; ErrorHash["errorURI"] = ""; return ErrorHash; } catch (XmlException ex) { m_log.ErrorFormat( "[SEARCH]: Unable to connect to Search Server {0}. " + "Exception {1}", m_SearchServer, ex); Hashtable ErrorHash = new Hashtable(); ErrorHash["success"] = false; ErrorHash["errorMessage"] = "Unable to search at this time. "; ErrorHash["errorURI"] = ""; return ErrorHash; } if (Resp.IsFault) { Hashtable ErrorHash = new Hashtable(); ErrorHash["success"] = false; ErrorHash["errorMessage"] = "Unable to search at this time. "; ErrorHash["errorURI"] = ""; return ErrorHash; } Hashtable RespData = (Hashtable)Resp.Value; return RespData; } protected void DirPlacesQuery(IClientAPI remoteClient, UUID queryID, string queryText, int queryFlags, int category, string simName, int queryStart) { Hashtable ReqHash = new Hashtable(); ReqHash["text"] = queryText; ReqHash["flags"] = queryFlags.ToString(); ReqHash["category"] = category.ToString(); ReqHash["sim_name"] = simName; ReqHash["query_start"] = queryStart.ToString(); Hashtable result = GenericXMLRPCRequest(ReqHash, "dir_places_query"); if (!Convert.ToBoolean(result["success"])) { remoteClient.SendAgentAlertMessage( result["errorMessage"].ToString(), false); return; } ArrayList dataArray = (ArrayList)result["data"]; int count = dataArray.Count; if (count > 100) count = 101; DirPlacesReplyData[] data = new DirPlacesReplyData[count]; int i = 0; foreach (Object o in dataArray) { Hashtable d = (Hashtable)o; data[i] = new DirPlacesReplyData(); data[i].parcelID = new UUID(d["parcel_id"].ToString()); data[i].name = d["name"].ToString(); data[i].forSale = Convert.ToBoolean(d["for_sale"]); data[i].auction = Convert.ToBoolean(d["auction"]); data[i].dwell = Convert.ToSingle(d["dwell"]); i++; if (i >= count) break; } remoteClient.SendDirPlacesReply(queryID, data); } public void DirPopularQuery(IClientAPI remoteClient, UUID queryID, uint queryFlags) { Hashtable ReqHash = new Hashtable(); ReqHash["flags"] = queryFlags.ToString(); Hashtable result = GenericXMLRPCRequest(ReqHash, "dir_popular_query"); if (!Convert.ToBoolean(result["success"])) { remoteClient.SendAgentAlertMessage( result["errorMessage"].ToString(), false); return; } ArrayList dataArray = (ArrayList)result["data"]; int count = dataArray.Count; if (count > 100) count = 101; DirPopularReplyData[] data = new DirPopularReplyData[count]; int i = 0; foreach (Object o in dataArray) { Hashtable d = (Hashtable)o; data[i] = new DirPopularReplyData(); data[i].parcelID = new UUID(d["parcel_id"].ToString()); data[i].name = d["name"].ToString(); data[i].dwell = Convert.ToSingle(d["dwell"]); i++; if (i >= count) break; } remoteClient.SendDirPopularReply(queryID, data); } public void DirLandQuery(IClientAPI remoteClient, UUID queryID, uint queryFlags, uint searchType, int price, int area, int queryStart) { Hashtable ReqHash = new Hashtable(); ReqHash["flags"] = queryFlags.ToString(); ReqHash["type"] = searchType.ToString(); ReqHash["price"] = price.ToString(); ReqHash["area"] = area.ToString(); ReqHash["query_start"] = queryStart.ToString(); Hashtable result = GenericXMLRPCRequest(ReqHash, "dir_land_query"); if (!Convert.ToBoolean(result["success"])) { remoteClient.SendAgentAlertMessage( result["errorMessage"].ToString(), false); return; } ArrayList dataArray = (ArrayList)result["data"]; int count = dataArray.Count; if (count > 100) count = 101; DirLandReplyData[] data = new DirLandReplyData[count]; int i = 0; foreach (Object o in dataArray) { Hashtable d = (Hashtable)o; if (d["name"] == null) continue; data[i] = new DirLandReplyData(); data[i].parcelID = new UUID(d["parcel_id"].ToString()); data[i].name = d["name"].ToString(); data[i].auction = Convert.ToBoolean(d["auction"]); data[i].forSale = Convert.ToBoolean(d["for_sale"]); data[i].salePrice = Convert.ToInt32(d["sale_price"]); data[i].actualArea = Convert.ToInt32(d["area"]); i++; if (i >= count) break; } remoteClient.SendDirLandReply(queryID, data); } public void DirFindQuery(IClientAPI remoteClient, UUID queryID, string queryText, uint queryFlags, int queryStart) { if ((queryFlags & 1) != 0) { DirPeopleQuery(remoteClient, queryID, queryText, queryFlags, queryStart); return; } else if ((queryFlags & 32) != 0) { DirEventsQuery(remoteClient, queryID, queryText, queryFlags, queryStart); return; } } public void DirPeopleQuery(IClientAPI remoteClient, UUID queryID, string queryText, uint queryFlags, int queryStart) { List<AvatarPickerAvatar> AvatarResponses = new List<AvatarPickerAvatar>(); AvatarResponses = m_Scenes[0].SceneGridService. GenerateAgentPickerRequestResponse(queryID, queryText); DirPeopleReplyData[] data = new DirPeopleReplyData[AvatarResponses.Count]; int i = 0; foreach (AvatarPickerAvatar item in AvatarResponses) { data[i] = new DirPeopleReplyData(); data[i].agentID = item.AvatarID; data[i].firstName = item.firstName; data[i].lastName = item.lastName; data[i].group = ""; data[i].online = false; data[i].reputation = 0; i++; } remoteClient.SendDirPeopleReply(queryID, data); } public void DirEventsQuery(IClientAPI remoteClient, UUID queryID, string queryText, uint queryFlags, int queryStart) { Hashtable ReqHash = new Hashtable(); ReqHash["text"] = queryText; ReqHash["flags"] = queryFlags.ToString(); ReqHash["query_start"] = queryStart.ToString(); Hashtable result = GenericXMLRPCRequest(ReqHash, "dir_events_query"); if (!Convert.ToBoolean(result["success"])) { remoteClient.SendAgentAlertMessage( result["errorMessage"].ToString(), false); return; } ArrayList dataArray = (ArrayList)result["data"]; int count = dataArray.Count; if (count > 100) count = 101; DirEventsReplyData[] data = new DirEventsReplyData[count]; int i = 0; foreach (Object o in dataArray) { Hashtable d = (Hashtable)o; data[i] = new DirEventsReplyData(); data[i].ownerID = new UUID(d["owner_id"].ToString()); data[i].name = d["name"].ToString(); data[i].eventID = Convert.ToUInt32(d["event_id"]); data[i].date = d["date"].ToString(); data[i].unixTime = Convert.ToUInt32(d["unix_time"]); data[i].eventFlags = Convert.ToUInt32(d["event_flags"]); i++; if (i >= count) break; } remoteClient.SendDirEventsReply(queryID, data); } public void DirClassifiedQuery(IClientAPI remoteClient, UUID queryID, string queryText, uint queryFlags, uint category, int queryStart) { Hashtable ReqHash = new Hashtable(); ReqHash["text"] = queryText; ReqHash["flags"] = queryFlags.ToString(); ReqHash["category"] = category.ToString(); ReqHash["query_start"] = queryStart.ToString(); Hashtable result = GenericXMLRPCRequest(ReqHash, "dir_classified_query"); if (!Convert.ToBoolean(result["success"])) { remoteClient.SendAgentAlertMessage( result["errorMessage"].ToString(), false); return; } ArrayList dataArray = (ArrayList)result["data"]; int count = dataArray.Count; if (count > 100) count = 101; DirClassifiedReplyData[] data = new DirClassifiedReplyData[count]; int i = 0; foreach (Object o in dataArray) { Hashtable d = (Hashtable)o; data[i] = new DirClassifiedReplyData(); data[i].classifiedID = new UUID(d["classifiedid"].ToString()); data[i].name = d["name"].ToString(); data[i].classifiedFlags = Convert.ToByte(d["classifiedflags"]); data[i].creationDate = Convert.ToUInt32(d["creation_date"]); data[i].expirationDate = Convert.ToUInt32(d["expiration_date"]); data[i].price = Convert.ToInt32(d["priceforlisting"]); i++; if (i >= count) break; } remoteClient.SendDirClassifiedReply(queryID, data); } public void EventInfoRequest(IClientAPI remoteClient, uint queryEventID) { Hashtable ReqHash = new Hashtable(); ReqHash["eventID"] = queryEventID.ToString(); Hashtable result = GenericXMLRPCRequest(ReqHash, "event_info_query"); if (!Convert.ToBoolean(result["success"])) { remoteClient.SendAgentAlertMessage( result["errorMessage"].ToString(), false); return; } ArrayList dataArray = (ArrayList)result["data"]; if (dataArray.Count == 0) { // something bad happened here, if we could return an // event after the search, // we should be able to find it here // TODO do some (more) sensible error-handling here remoteClient.SendAgentAlertMessage("Couldn't find event.", false); return; } Hashtable d = (Hashtable)dataArray[0]; EventData data = new EventData(); data.eventID = Convert.ToUInt32(d["event_id"]); data.creator = d["creator"].ToString(); data.name = d["name"].ToString(); data.category = d["category"].ToString(); data.description = d["description"].ToString(); data.date = d["date"].ToString(); data.dateUTC = Convert.ToUInt32(d["dateUTC"]); data.duration = Convert.ToUInt32(d["duration"]); data.cover = Convert.ToUInt32(d["covercharge"]); data.amount = Convert.ToUInt32(d["coveramount"]); data.simName = d["simname"].ToString(); Vector3.TryParse(d["globalposition"].ToString(), out data.globalPos); data.eventFlags = Convert.ToUInt32(d["eventflags"]); remoteClient.SendEventInfoReply(data); } public void ClassifiedInfoRequest(UUID queryClassifiedID, IClientAPI remoteClient) { Hashtable ReqHash = new Hashtable(); ReqHash["classifiedID"] = queryClassifiedID.ToString(); Hashtable result = GenericXMLRPCRequest(ReqHash, "classifieds_info_query"); if (!Convert.ToBoolean(result["success"])) { remoteClient.SendAgentAlertMessage( result["errorMessage"].ToString(), false); return; } ArrayList dataArray = (ArrayList)result["data"]; if (dataArray.Count == 0) { // something bad happened here, if we could return an // event after the search, // we should be able to find it here // TODO do some (more) sensible error-handling here remoteClient.SendAgentAlertMessage("Couldn't find any classifieds.", false); return; } Hashtable d = (Hashtable)dataArray[0]; Vector3 globalPos = new Vector3(); Vector3.TryParse(d["posglobal"].ToString(), out globalPos); remoteClient.SendClassifiedInfoReply( new UUID(d["classifieduuid"].ToString()), new UUID(d["creatoruuid"].ToString()), Convert.ToUInt32(d["creationdate"]), Convert.ToUInt32(d["expirationdate"]), Convert.ToUInt32(d["category"]), d["name"].ToString(), d["description"].ToString(), new UUID(d["parceluuid"].ToString()), Convert.ToUInt32(d["parentestate"]), new UUID(d["snapshotuuid"].ToString()), d["simname"].ToString(), globalPos, d["parcelname"].ToString(), Convert.ToByte(d["classifiedflags"]), Convert.ToInt32(d["priceforlisting"])); } public void HandleMapItemRequest(IClientAPI remoteClient, uint flags, uint EstateID, bool godlike, uint itemtype, ulong regionhandle) { //The following constant appears to be from GridLayerType enum //defined in OpenMetaverse/GridManager.cs of libopenmetaverse. if (itemtype == 7) //(land sales) { int tc = Environment.TickCount; Hashtable ReqHash = new Hashtable(); //The flags are: SortAsc (1 << 15), PerMeterSort (1 << 17) ReqHash["flags"] = "163840"; ReqHash["type"] = "4294967295"; //This is -1 in 32 bits ReqHash["price"] = "0"; ReqHash["area"] = "0"; ReqHash["query_start"] = "0"; Hashtable result = GenericXMLRPCRequest(ReqHash, "dir_land_query"); if (!Convert.ToBoolean(result["success"])) { remoteClient.SendAgentAlertMessage( result["errorMessage"].ToString(), false); return; } ArrayList dataArray = (ArrayList)result["data"]; int count = dataArray.Count; if (count > 100) count = 101; DirLandReplyData[] Landdata = new DirLandReplyData[count]; int i = 0; string[] ParcelLandingPoint = new string[count]; string[] ParcelRegionUUID = new string[count]; foreach (Object o in dataArray) { Hashtable d = (Hashtable)o; if (d["name"] == null) continue; Landdata[i] = new DirLandReplyData(); Landdata[i].parcelID = new UUID(d["parcel_id"].ToString()); Landdata[i].name = d["name"].ToString(); Landdata[i].auction = Convert.ToBoolean(d["auction"]); Landdata[i].forSale = Convert.ToBoolean(d["for_sale"]); Landdata[i].salePrice = Convert.ToInt32(d["sale_price"]); Landdata[i].actualArea = Convert.ToInt32(d["area"]); ParcelLandingPoint[i] = d["landing_point"].ToString(); ParcelRegionUUID[i] = d["region_UUID"].ToString(); i++; if (i >= count) break; } i = 0; uint locX = 0; uint locY = 0; List<mapItemReply> mapitems = new List<mapItemReply>(); foreach (DirLandReplyData landDir in Landdata) { foreach(Scene scene in m_Scenes) { if(scene.RegionInfo.RegionID.ToString() == ParcelRegionUUID[i]) { locX = scene.RegionInfo.RegionLocX; locY = scene.RegionInfo.RegionLocY; } } string[] landingpoint = ParcelLandingPoint[i].Split('/'); mapItemReply mapitem = new mapItemReply(); mapitem.x = (uint)(locX + Convert.ToDecimal(landingpoint[0])); mapitem.y = (uint)(locY + Convert.ToDecimal(landingpoint[1])); mapitem.id = landDir.parcelID; mapitem.name = landDir.name; mapitem.Extra = landDir.actualArea; mapitem.Extra2 = landDir.salePrice; mapitems.Add(mapitem); i++; } remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags); mapitems.Clear(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void OrDouble() { var test = new SimpleBinaryOpTest__OrDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__OrDouble { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Double> _fld1; public Vector256<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__OrDouble testClass) { var result = Avx.Or(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__OrDouble testClass) { fixed (Vector256<Double>* pFld1 = &_fld1) fixed (Vector256<Double>* pFld2 = &_fld2) { var result = Avx.Or( Avx.LoadVector256((Double*)(pFld1)), Avx.LoadVector256((Double*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector256<Double> _clsVar1; private static Vector256<Double> _clsVar2; private Vector256<Double> _fld1; private Vector256<Double> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__OrDouble() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); } public SimpleBinaryOpTest__OrDouble() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx.Or( Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx.Or( Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx.Or( Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx).GetMethod(nameof(Avx.Or), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.Or), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx).GetMethod(nameof(Avx.Or), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx.Or( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Double>* pClsVar1 = &_clsVar1) fixed (Vector256<Double>* pClsVar2 = &_clsVar2) { var result = Avx.Or( Avx.LoadVector256((Double*)(pClsVar1)), Avx.LoadVector256((Double*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr); var result = Avx.Or(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)); var result = Avx.Or(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)); var result = Avx.Or(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__OrDouble(); var result = Avx.Or(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__OrDouble(); fixed (Vector256<Double>* pFld1 = &test._fld1) fixed (Vector256<Double>* pFld2 = &test._fld2) { var result = Avx.Or( Avx.LoadVector256((Double*)(pFld1)), Avx.LoadVector256((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx.Or(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Double>* pFld1 = &_fld1) fixed (Vector256<Double>* pFld2 = &_fld2) { var result = Avx.Or( Avx.LoadVector256((Double*)(pFld1)), Avx.LoadVector256((Double*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx.Or(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx.Or( Avx.LoadVector256((Double*)(&test._fld1)), Avx.LoadVector256((Double*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Double> op1, Vector256<Double> op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((BitConverter.DoubleToInt64Bits(left[0]) | BitConverter.DoubleToInt64Bits(right[0])) != BitConverter.DoubleToInt64Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((BitConverter.DoubleToInt64Bits(left[i]) | BitConverter.DoubleToInt64Bits(right[i])) != BitConverter.DoubleToInt64Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.Or)}<Double>(Vector256<Double>, Vector256<Double>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.ComponentModel; namespace WeifenLuo.WinFormsUI.Docking { internal class VS2012LightDockPaneStrip : DockPaneStripBase { private class TabVS2012Light : Tab { public TabVS2012Light(IDockContent content) : base(content) { } private int m_tabX; public int TabX { get { return m_tabX; } set { m_tabX = value; } } private int m_tabWidth; public int TabWidth { get { return m_tabWidth; } set { m_tabWidth = value; } } private int m_maxWidth; public int MaxWidth { get { return m_maxWidth; } set { m_maxWidth = value; } } private bool m_flag; protected internal bool Flag { get { return m_flag; } set { m_flag = value; } } } protected internal override Tab CreateTab(IDockContent content) { return new TabVS2012Light(content); } private sealed class InertButton : InertButtonBase { private Bitmap m_image0, m_image1; public InertButton(Bitmap image0, Bitmap image1) : base() { m_image0 = image0; m_image1 = image1; } private int m_imageCategory = 0; public int ImageCategory { get { return m_imageCategory; } set { if (m_imageCategory == value) return; m_imageCategory = value; Invalidate(); } } public override Bitmap Image { get { return ImageCategory == 0 ? m_image0 : m_image1; } } } #region Constants private const int _ToolWindowStripGapTop = 0; private const int _ToolWindowStripGapBottom = 1; private const int _ToolWindowStripGapLeft = 0; private const int _ToolWindowStripGapRight = 0; private const int _ToolWindowImageHeight = 16; private const int _ToolWindowImageWidth = 0;//16; private const int _ToolWindowImageGapTop = 3; private const int _ToolWindowImageGapBottom = 1; private const int _ToolWindowImageGapLeft = 2; private const int _ToolWindowImageGapRight = 0; private const int _ToolWindowTextGapRight = 3; private const int _ToolWindowTabSeperatorGapTop = 3; private const int _ToolWindowTabSeperatorGapBottom = 3; private const int _DocumentStripGapTop = 0; private const int _DocumentStripGapBottom = 0; private const int _DocumentTabMaxWidth = 200; private const int _DocumentButtonGapTop = 3; private const int _DocumentButtonGapBottom = 3; private const int _DocumentButtonGapBetween = 0; private const int _DocumentButtonGapRight = 3; private const int _DocumentTabGapTop = 0;//3; private const int _DocumentTabGapLeft = 0;//3; private const int _DocumentTabGapRight = 0;//3; private const int _DocumentIconGapBottom = 2;//2; private const int _DocumentIconGapLeft = 8; private const int _DocumentIconGapRight = 0; private const int _DocumentIconHeight = 16; private const int _DocumentIconWidth = 16; private const int _DocumentTextGapRight = 6; #endregion #region Members private ContextMenuStrip m_selectMenu; private static Bitmap m_imageButtonClose; private InertButton m_buttonClose; private static Bitmap m_imageButtonWindowList; private static Bitmap m_imageButtonWindowListOverflow; private InertButton m_buttonWindowList; private IContainer m_components; private ToolTip m_toolTip; private Font m_font; private Font m_boldFont; private int m_startDisplayingTab = 0; private int m_endDisplayingTab = 0; private int m_firstDisplayingTab = 0; private bool m_documentTabsOverflow = false; private static string m_toolTipSelect; private static string m_toolTipClose; private bool m_closeButtonVisible = false; private Rectangle _activeClose; private int _selectMenuMargin = 5; private bool _initialized; #endregion #region Properties private Rectangle TabStripRectangle { get { if (Appearance == DockPane.AppearanceStyle.Document) return TabStripRectangle_Document; else return TabStripRectangle_ToolWindow; } } private Rectangle TabStripRectangle_ToolWindow { get { Rectangle rect = ClientRectangle; return new Rectangle(rect.X, rect.Top + ToolWindowStripGapTop, rect.Width, rect.Height - ToolWindowStripGapTop - ToolWindowStripGapBottom); } } private Rectangle TabStripRectangle_Document { get { Rectangle rect = ClientRectangle; return new Rectangle(rect.X, rect.Top + DocumentStripGapTop, rect.Width, rect.Height + DocumentStripGapTop - ToolWindowStripGapBottom); } } private Rectangle TabsRectangle { get { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return TabStripRectangle; Rectangle rectWindow = TabStripRectangle; int x = rectWindow.X; int y = rectWindow.Y; int width = rectWindow.Width; int height = rectWindow.Height; x += DocumentTabGapLeft; width -= DocumentTabGapLeft + DocumentTabGapRight + DocumentButtonGapRight + ButtonClose.Width + ButtonWindowList.Width + 2 * DocumentButtonGapBetween; return new Rectangle(x, y, width, height); } } private ContextMenuStrip SelectMenu { get { return m_selectMenu; } } public int SelectMenuMargin { get { return _selectMenuMargin; } set { _selectMenuMargin = value; } } private static Bitmap ImageButtonClose { get { if (m_imageButtonClose == null) m_imageButtonClose = Resources.DockPane_Close; return m_imageButtonClose; } } private InertButton ButtonClose { get { if (m_buttonClose == null) { m_buttonClose = new InertButton(ImageButtonClose, ImageButtonClose); m_toolTip.SetToolTip(m_buttonClose, ToolTipClose); m_buttonClose.Click += new EventHandler(Close_Click); Controls.Add(m_buttonClose); } return m_buttonClose; } } private static Bitmap ImageButtonWindowList { get { if (m_imageButtonWindowList == null) m_imageButtonWindowList = Resources.DockPane_Option; return m_imageButtonWindowList; } } private static Bitmap ImageButtonWindowListOverflow { get { if (m_imageButtonWindowListOverflow == null) m_imageButtonWindowListOverflow = Resources.DockPane_OptionOverflow; return m_imageButtonWindowListOverflow; } } private InertButton ButtonWindowList { get { if (m_buttonWindowList == null) { m_buttonWindowList = new InertButton(ImageButtonWindowList, ImageButtonWindowListOverflow); m_toolTip.SetToolTip(m_buttonWindowList, ToolTipSelect); m_buttonWindowList.Click += new EventHandler(WindowList_Click); Controls.Add(m_buttonWindowList); } return m_buttonWindowList; } } private static GraphicsPath GraphicsPath { get { return VS2005AutoHideStrip.GraphicsPath; } } private IContainer Components { get { return m_components; } } public Font TextFont { get { return DockPane.DockPanel.Skin.DockPaneStripSkin.TextFont; } } private Font BoldFont { get { if (IsDisposed) return null; if (m_boldFont == null) { m_font = TextFont; m_boldFont = new Font(TextFont, FontStyle.Bold); } else if (m_font != TextFont) { m_boldFont.Dispose(); m_font = TextFont; m_boldFont = new Font(TextFont, FontStyle.Bold); } return m_boldFont; } } private int StartDisplayingTab { get { return m_startDisplayingTab; } set { m_startDisplayingTab = value; Invalidate(); } } private int EndDisplayingTab { get { return m_endDisplayingTab; } set { m_endDisplayingTab = value; } } private int FirstDisplayingTab { get { return m_firstDisplayingTab; } set { m_firstDisplayingTab = value; } } private bool DocumentTabsOverflow { set { if (m_documentTabsOverflow == value) return; m_documentTabsOverflow = value; if (value) ButtonWindowList.ImageCategory = 1; else ButtonWindowList.ImageCategory = 0; } } #region Customizable Properties private static int ToolWindowStripGapTop { get { return _ToolWindowStripGapTop; } } private static int ToolWindowStripGapBottom { get { return _ToolWindowStripGapBottom; } } private static int ToolWindowStripGapLeft { get { return _ToolWindowStripGapLeft; } } private static int ToolWindowStripGapRight { get { return _ToolWindowStripGapRight; } } private static int ToolWindowImageHeight { get { return _ToolWindowImageHeight; } } private static int ToolWindowImageWidth { get { return _ToolWindowImageWidth; } } private static int ToolWindowImageGapTop { get { return _ToolWindowImageGapTop; } } private static int ToolWindowImageGapBottom { get { return _ToolWindowImageGapBottom; } } private static int ToolWindowImageGapLeft { get { return _ToolWindowImageGapLeft; } } private static int ToolWindowImageGapRight { get { return _ToolWindowImageGapRight; } } private static int ToolWindowTextGapRight { get { return _ToolWindowTextGapRight; } } private static int ToolWindowTabSeperatorGapTop { get { return _ToolWindowTabSeperatorGapTop; } } private static int ToolWindowTabSeperatorGapBottom { get { return _ToolWindowTabSeperatorGapBottom; } } private static string ToolTipClose { get { if (m_toolTipClose == null) m_toolTipClose = Strings.DockPaneStrip_ToolTipClose; return m_toolTipClose; } } private static string ToolTipSelect { get { if (m_toolTipSelect == null) m_toolTipSelect = Strings.DockPaneStrip_ToolTipWindowList; return m_toolTipSelect; } } private TextFormatFlags ToolWindowTextFormat { get { TextFormatFlags textFormat = TextFormatFlags.EndEllipsis | TextFormatFlags.HorizontalCenter | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter; if (RightToLeft == RightToLeft.Yes) return textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right; else return textFormat; } } private static int DocumentStripGapTop { get { return _DocumentStripGapTop; } } private static int DocumentStripGapBottom { get { return _DocumentStripGapBottom; } } private TextFormatFlags DocumentTextFormat { get { TextFormatFlags textFormat = TextFormatFlags.EndEllipsis | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.HorizontalCenter; if (RightToLeft == RightToLeft.Yes) return textFormat | TextFormatFlags.RightToLeft; else return textFormat; } } private static int DocumentTabMaxWidth { get { return _DocumentTabMaxWidth; } } private static int DocumentButtonGapTop { get { return _DocumentButtonGapTop; } } private static int DocumentButtonGapBottom { get { return _DocumentButtonGapBottom; } } private static int DocumentButtonGapBetween { get { return _DocumentButtonGapBetween; } } private static int DocumentButtonGapRight { get { return _DocumentButtonGapRight; } } private static int DocumentTabGapTop { get { return _DocumentTabGapTop; } } private static int DocumentTabGapLeft { get { return _DocumentTabGapLeft; } } private static int DocumentTabGapRight { get { return _DocumentTabGapRight; } } private static int DocumentIconGapBottom { get { return _DocumentIconGapBottom; } } private static int DocumentIconGapLeft { get { return _DocumentIconGapLeft; } } private static int DocumentIconGapRight { get { return _DocumentIconGapRight; } } private static int DocumentIconWidth { get { return _DocumentIconWidth; } } private static int DocumentIconHeight { get { return _DocumentIconHeight; } } private static int DocumentTextGapRight { get { return _DocumentTextGapRight; } } private static Pen PenToolWindowTabBorder { get { return SystemPens.ControlDark; } } private static Pen PenDocumentTabActiveBorder { get { return SystemPens.ControlDarkDark; } } private static Pen PenDocumentTabInactiveBorder { get { return SystemPens.GrayText; } } #endregion #endregion public VS2012LightDockPaneStrip(DockPane pane) : base(pane) { SetStyle(ControlStyles.ResizeRedraw | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true); SuspendLayout(); m_components = new Container(); m_toolTip = new ToolTip(Components); m_selectMenu = new ContextMenuStrip(Components); ResumeLayout(); } protected override void Dispose(bool disposing) { if (disposing) { Components.Dispose(); if (m_boldFont != null) { m_boldFont.Dispose(); m_boldFont = null; } } base.Dispose(disposing); } protected internal override int MeasureHeight() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return MeasureHeight_ToolWindow(); else return MeasureHeight_Document(); } private int MeasureHeight_ToolWindow() { if (DockPane.IsAutoHide || Tabs.Count <= 1) return 0; int height = Math.Max(TextFont.Height, ToolWindowImageHeight + ToolWindowImageGapTop + ToolWindowImageGapBottom) + ToolWindowStripGapTop + ToolWindowStripGapBottom; return height; } private int MeasureHeight_Document() { int height = Math.Max(TextFont.Height + DocumentTabGapTop, ButtonClose.Height + DocumentButtonGapTop + DocumentButtonGapBottom) + DocumentStripGapBottom + DocumentStripGapTop; return height; } protected override void OnPaint(PaintEventArgs e) { Rectangle rect = TabsRectangle; if (Appearance == DockPane.AppearanceStyle.Document) { rect.X -= DocumentTabGapLeft; // Add these values back in so that the DockStrip color is drawn // beneath the close button and window list button. rect.Width += DocumentTabGapLeft + DocumentTabGapRight + DocumentButtonGapRight + ButtonClose.Width + ButtonWindowList.Width; // It is possible depending on the DockPanel DocumentStyle to have // a Document without a DockStrip. if (rect.Width > 0 && rect.Height > 0) { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.LinearGradientMode; using (LinearGradientBrush brush = new LinearGradientBrush(rect, startColor, endColor, gradientMode)) { e.Graphics.FillRectangle(brush, rect); } } } else { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.LinearGradientMode; using (LinearGradientBrush brush = new LinearGradientBrush(rect, startColor, endColor, gradientMode)) { e.Graphics.FillRectangle(brush, rect); } } base.OnPaint(e); CalculateTabs(); if (Appearance == DockPane.AppearanceStyle.Document && DockPane.ActiveContent != null) { if (EnsureDocumentTabVisible(DockPane.ActiveContent, false)) CalculateTabs(); } DrawTabStrip(e.Graphics); } protected override void OnRefreshChanges() { SetInertButtons(); Invalidate(); } protected internal override GraphicsPath GetOutline(int index) { if (Appearance == DockPane.AppearanceStyle.Document) return GetOutline_Document(index); else return GetOutline_ToolWindow(index); } private GraphicsPath GetOutline_Document(int index) { Rectangle rectTab = GetTabRectangle(index); rectTab.X -= rectTab.Height / 2; rectTab.Intersect(TabsRectangle); rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); GraphicsPath path = new GraphicsPath(); GraphicsPath pathTab = GetTabOutline_Document(Tabs[index], true, true, true); path.AddPath(pathTab, true); if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { path.AddLine(rectTab.Right, rectTab.Top, rectPaneClient.Right, rectTab.Top); path.AddLine(rectPaneClient.Right, rectTab.Top, rectPaneClient.Right, rectPaneClient.Top); path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Left, rectPaneClient.Top); path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Left, rectTab.Top); path.AddLine(rectPaneClient.Left, rectTab.Top, rectTab.Right, rectTab.Top); } else { path.AddLine(rectTab.Right, rectTab.Bottom, rectPaneClient.Right, rectTab.Bottom); path.AddLine(rectPaneClient.Right, rectTab.Bottom, rectPaneClient.Right, rectPaneClient.Bottom); path.AddLine(rectPaneClient.Right, rectPaneClient.Bottom, rectPaneClient.Left, rectPaneClient.Bottom); path.AddLine(rectPaneClient.Left, rectPaneClient.Bottom, rectPaneClient.Left, rectTab.Bottom); path.AddLine(rectPaneClient.Left, rectTab.Bottom, rectTab.Right, rectTab.Bottom); } return path; } private GraphicsPath GetOutline_ToolWindow(int index) { Rectangle rectTab = GetTabRectangle(index); rectTab.Intersect(TabsRectangle); rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); GraphicsPath path = new GraphicsPath(); GraphicsPath pathTab = GetTabOutline(Tabs[index], true, true); path.AddPath(pathTab, true); path.AddLine(rectTab.Left, rectTab.Top, rectPaneClient.Left, rectTab.Top); path.AddLine(rectPaneClient.Left, rectTab.Top, rectPaneClient.Left, rectPaneClient.Top); path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Right, rectPaneClient.Top); path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Right, rectTab.Top); path.AddLine(rectPaneClient.Right, rectTab.Top, rectTab.Right, rectTab.Top); return path; } private void CalculateTabs() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) CalculateTabs_ToolWindow(); else CalculateTabs_Document(); } private void CalculateTabs_ToolWindow() { if (Tabs.Count <= 1 || DockPane.IsAutoHide) return; Rectangle rectTabStrip = TabStripRectangle; // Calculate tab widths int countTabs = Tabs.Count; foreach (TabVS2012Light tab in Tabs) { tab.MaxWidth = GetMaxTabWidth(Tabs.IndexOf(tab)); tab.Flag = false; } // Set tab whose max width less than average width bool anyWidthWithinAverage = true; int totalWidth = rectTabStrip.Width - ToolWindowStripGapLeft - ToolWindowStripGapRight; int totalAllocatedWidth = 0; int averageWidth = totalWidth / countTabs; int remainedTabs = countTabs; for (anyWidthWithinAverage = true; anyWidthWithinAverage && remainedTabs > 0; ) { anyWidthWithinAverage = false; foreach (TabVS2012Light tab in Tabs) { if (tab.Flag) continue; if (tab.MaxWidth <= averageWidth) { tab.Flag = true; tab.TabWidth = tab.MaxWidth; totalAllocatedWidth += tab.TabWidth; anyWidthWithinAverage = true; remainedTabs--; } } if (remainedTabs != 0) averageWidth = (totalWidth - totalAllocatedWidth) / remainedTabs; } // If any tab width not set yet, set it to the average width if (remainedTabs > 0) { int roundUpWidth = (totalWidth - totalAllocatedWidth) - (averageWidth * remainedTabs); foreach (TabVS2012Light tab in Tabs) { if (tab.Flag) continue; tab.Flag = true; if (roundUpWidth > 0) { tab.TabWidth = averageWidth + 1; roundUpWidth--; } else tab.TabWidth = averageWidth; } } // Set the X position of the tabs int x = rectTabStrip.X + ToolWindowStripGapLeft; foreach (TabVS2012Light tab in Tabs) { tab.TabX = x; x += tab.TabWidth; } } private bool CalculateDocumentTab(Rectangle rectTabStrip, ref int x, int index) { bool overflow = false; var tab = Tabs[index] as TabVS2012Light; tab.MaxWidth = GetMaxTabWidth(index); int width = Math.Min(tab.MaxWidth, DocumentTabMaxWidth); if (x + width < rectTabStrip.Right || index == StartDisplayingTab) { tab.TabX = x; tab.TabWidth = width; EndDisplayingTab = index; } else { tab.TabX = 0; tab.TabWidth = 0; overflow = true; } x += width; return overflow; } /// <summary> /// Calculate which tabs are displayed and in what order. /// </summary> private void CalculateTabs_Document() { if (m_startDisplayingTab >= Tabs.Count) m_startDisplayingTab = 0; Rectangle rectTabStrip = TabsRectangle; int x = rectTabStrip.X; //+ rectTabStrip.Height / 2; bool overflow = false; // Originally all new documents that were considered overflow // (not enough pane strip space to show all tabs) were added to // the far left (assuming not right to left) and the tabs on the // right were dropped from view. If StartDisplayingTab is not 0 // then we are dealing with making sure a specific tab is kept in focus. if (m_startDisplayingTab > 0) { int tempX = x; var tab = Tabs[m_startDisplayingTab] as TabVS2012Light; tab.MaxWidth = GetMaxTabWidth(m_startDisplayingTab); // Add the active tab and tabs to the left for (int i = StartDisplayingTab; i >= 0; i--) CalculateDocumentTab(rectTabStrip, ref tempX, i); // Store which tab is the first one displayed so that it // will be drawn correctly (without part of the tab cut off) FirstDisplayingTab = EndDisplayingTab; tempX = x; // Reset X location because we are starting over // Start with the first tab displayed - name is a little misleading. // Loop through each tab and set its location. If there is not enough // room for all of them overflow will be returned. for (int i = EndDisplayingTab; i < Tabs.Count; i++) overflow = CalculateDocumentTab(rectTabStrip, ref tempX, i); // If not all tabs are shown then we have an overflow. if (FirstDisplayingTab != 0) overflow = true; } else { for (int i = StartDisplayingTab; i < Tabs.Count; i++) overflow = CalculateDocumentTab(rectTabStrip, ref x, i); for (int i = 0; i < StartDisplayingTab; i++) overflow = CalculateDocumentTab(rectTabStrip, ref x, i); FirstDisplayingTab = StartDisplayingTab; } if (!overflow) { m_startDisplayingTab = 0; FirstDisplayingTab = 0; x = rectTabStrip.X;// +rectTabStrip.Height / 2; foreach (TabVS2012Light tab in Tabs) { tab.TabX = x; x += tab.TabWidth; } } DocumentTabsOverflow = overflow; } protected internal override void EnsureTabVisible(IDockContent content) { if (Appearance != DockPane.AppearanceStyle.Document || !Tabs.Contains(content)) return; CalculateTabs(); EnsureDocumentTabVisible(content, true); } private bool EnsureDocumentTabVisible(IDockContent content, bool repaint) { int index = Tabs.IndexOf(content); var tab = Tabs[index] as TabVS2012Light; if (tab.TabWidth != 0) return false; StartDisplayingTab = index; if (repaint) Invalidate(); return true; } private int GetMaxTabWidth(int index) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetMaxTabWidth_ToolWindow(index); else return GetMaxTabWidth_Document(index); } private int GetMaxTabWidth_ToolWindow(int index) { IDockContent content = Tabs[index].Content; Size sizeString = TextRenderer.MeasureText(content.DockHandler.TabText, TextFont); return ToolWindowImageWidth + sizeString.Width + ToolWindowImageGapLeft + ToolWindowImageGapRight + ToolWindowTextGapRight; } private const int TAB_CLOSE_BUTTON_WIDTH = 30; private int GetMaxTabWidth_Document(int index) { IDockContent content = Tabs[index].Content; int height = GetTabRectangle_Document(index).Height; Size sizeText = TextRenderer.MeasureText(content.DockHandler.TabText, BoldFont, new Size(DocumentTabMaxWidth, height), DocumentTextFormat); int width; if (DockPane.DockPanel.ShowDocumentIcon) width = sizeText.Width + DocumentIconWidth + DocumentIconGapLeft + DocumentIconGapRight + DocumentTextGapRight; else width = sizeText.Width + DocumentIconGapLeft + DocumentTextGapRight; width += TAB_CLOSE_BUTTON_WIDTH; return width; } private void DrawTabStrip(Graphics g) { if (Appearance == DockPane.AppearanceStyle.Document) DrawTabStrip_Document(g); else DrawTabStrip_ToolWindow(g); } private void DrawTabStrip_Document(Graphics g) { int count = Tabs.Count; if (count == 0) return; Rectangle rectTabStrip = TabStripRectangle; rectTabStrip.Height += 1; // Draw the tabs Rectangle rectTabOnly = TabsRectangle; Rectangle rectTab = Rectangle.Empty; TabVS2012Light tabActive = null; g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); for (int i = 0; i < count; i++) { rectTab = GetTabRectangle(i); if (Tabs[i].Content == DockPane.ActiveContent) { tabActive = Tabs[i] as TabVS2012Light; continue; } if (rectTab.IntersectsWith(rectTabOnly)) DrawTab(g, Tabs[i] as TabVS2012Light, rectTab); } g.SetClip(rectTabStrip); if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Top + 1, rectTabStrip.Right, rectTabStrip.Top + 1); else { Color tabUnderLineColor; if (tabActive != null && DockPane.IsActiveDocumentPane) tabUnderLineColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor; else tabUnderLineColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor; g.DrawLine(new Pen(tabUnderLineColor, 4), rectTabStrip.Left, rectTabStrip.Bottom, rectTabStrip.Right, rectTabStrip.Bottom); } g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); if (tabActive != null) { rectTab = GetTabRectangle(Tabs.IndexOf(tabActive)); if (rectTab.IntersectsWith(rectTabOnly)) { rectTab.Intersect(rectTabOnly); DrawTab(g, tabActive, rectTab); } } } private void DrawTabStrip_ToolWindow(Graphics g) { Rectangle rectTabStrip = TabStripRectangle; g.DrawLine(PenToolWindowTabBorder, rectTabStrip.Left, rectTabStrip.Top, rectTabStrip.Right, rectTabStrip.Top); for (int i = 0; i < Tabs.Count; i++) DrawTab(g, Tabs[i] as TabVS2012Light, GetTabRectangle(i)); } private Rectangle GetTabRectangle(int index) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetTabRectangle_ToolWindow(index); else return GetTabRectangle_Document(index); } private Rectangle GetTabRectangle_ToolWindow(int index) { Rectangle rectTabStrip = TabStripRectangle; TabVS2012Light tab = (TabVS2012Light)(Tabs[index]); return new Rectangle(tab.TabX, rectTabStrip.Y, tab.TabWidth, rectTabStrip.Height); } private Rectangle GetTabRectangle_Document(int index) { Rectangle rectTabStrip = TabStripRectangle; var tab = (TabVS2012Light)Tabs[index]; Rectangle rect = new Rectangle(); rect.X = tab.TabX; rect.Width = tab.TabWidth; rect.Height = rectTabStrip.Height - DocumentTabGapTop; if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) rect.Y = rectTabStrip.Y + DocumentStripGapBottom; else rect.Y = rectTabStrip.Y + DocumentTabGapTop; return rect; } private void DrawTab(Graphics g, TabVS2012Light tab, Rectangle rect) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) DrawTab_ToolWindow(g, tab, rect); else DrawTab_Document(g, tab, rect); } private GraphicsPath GetTabOutline(Tab tab, bool rtlTransform, bool toScreen) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetTabOutline_ToolWindow(tab, rtlTransform, toScreen); else return GetTabOutline_Document(tab, rtlTransform, toScreen, false); } private GraphicsPath GetTabOutline_ToolWindow(Tab tab, bool rtlTransform, bool toScreen) { Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab)); if (rtlTransform) rect = DrawHelper.RtlTransform(this, rect); if (toScreen) rect = RectangleToScreen(rect); DrawHelper.GetRoundedCornerTab(GraphicsPath, rect, false); return GraphicsPath; } private GraphicsPath GetTabOutline_Document(Tab tab, bool rtlTransform, bool toScreen, bool full) { GraphicsPath.Reset(); Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab)); // Shorten TabOutline so it doesn't get overdrawn by icons next to it rect.Intersect(TabsRectangle); rect.Width--; if (rtlTransform) rect = DrawHelper.RtlTransform(this, rect); if (toScreen) rect = RectangleToScreen(rect); GraphicsPath.AddRectangle(rect); return GraphicsPath; } private void DrawTab_ToolWindow(Graphics g, TabVS2012Light tab, Rectangle rect) { rect.Y += 1; Rectangle rectIcon = new Rectangle( rect.X + ToolWindowImageGapLeft, rect.Y - 1 + rect.Height - ToolWindowImageGapBottom - ToolWindowImageHeight, ToolWindowImageWidth, ToolWindowImageHeight); Rectangle rectText = rectIcon; rectText.X += rectIcon.Width + ToolWindowImageGapRight; rectText.Width = rect.Width - rectIcon.Width - ToolWindowImageGapLeft - ToolWindowImageGapRight - ToolWindowTextGapRight; Rectangle rectTab = DrawHelper.RtlTransform(this, rect); rectText = DrawHelper.RtlTransform(this, rectText); rectIcon = DrawHelper.RtlTransform(this, rectIcon); if (DockPane.ActiveContent == tab.Content && ((DockContent)tab.Content).IsActivated) { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.LinearGradientMode; g.FillRectangle(new LinearGradientBrush(rectTab, startColor, endColor, gradientMode), rect); Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor; TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat); } else { Color textColor; if (tab.Content == DockPane.MouseOverTab) textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor; else textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor; TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat); } g.DrawLine(PenToolWindowTabBorder, rect.X + rect.Width - 1, rect.Y, rect.X + rect.Width - 1, rect.Height); if (rectTab.Contains(rectIcon)) g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon); } private void DrawTab_Document(Graphics g, TabVS2012Light tab, Rectangle rect) { if (tab.TabWidth == 0) return; var rectCloseButton = GetCloseButtonRect(rect); Rectangle rectIcon = new Rectangle( rect.X + DocumentIconGapLeft, rect.Y + rect.Height - DocumentIconGapBottom - DocumentIconHeight, DocumentIconWidth, DocumentIconHeight); Rectangle rectText = rectIcon; if (DockPane.DockPanel.ShowDocumentIcon) { rectText.X += rectIcon.Width + DocumentIconGapRight; rectText.Y = rect.Y; rectText.Width = rect.Width - rectIcon.Width - DocumentIconGapLeft - DocumentIconGapRight - DocumentTextGapRight - rectCloseButton.Width; rectText.Height = rect.Height; } else rectText.Width = rect.Width - DocumentIconGapLeft - DocumentTextGapRight - rectCloseButton.Width; Rectangle rectTab = DrawHelper.RtlTransform(this, rect); Rectangle rectBack = DrawHelper.RtlTransform(this, rect); rectBack.Width += rect.X; rectBack.X = 0; rectText = DrawHelper.RtlTransform(this, rectText); rectIcon = DrawHelper.RtlTransform(this, rectIcon); Color activeColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor; Color lostFocusColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor; Color inactiveColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor; Color mouseHoverColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.EndColor; Color activeText = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.TextColor; Color inactiveText = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor; Color lostFocusText = SystemColors.GrayText; if (DockPane.ActiveContent == tab.Content) { if (DockPane.IsActiveDocumentPane) { g.FillRectangle(new SolidBrush(activeColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, activeText, DocumentTextFormat); g.DrawImage(rectCloseButton == ActiveClose ? Resources.ActiveTabHover_Close : Resources.ActiveTab_Close, rectCloseButton); } else { g.FillRectangle(new SolidBrush(lostFocusColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, lostFocusText, DocumentTextFormat); g.DrawImage(rectCloseButton == ActiveClose ? Resources.LostFocusTabHover_Close : Resources.LostFocusTab_Close, rectCloseButton); } } else { if (tab.Content == DockPane.MouseOverTab) { g.FillRectangle(new SolidBrush(mouseHoverColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, activeText, DocumentTextFormat); g.DrawImage(rectCloseButton == ActiveClose ? Resources.InactiveTabHover_Close : Resources.ActiveTabHover_Close, rectCloseButton); } else { g.FillRectangle(new SolidBrush(inactiveColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, inactiveText, DocumentTextFormat); } } if (rectTab.Contains(rectIcon) && DockPane.DockPanel.ShowDocumentIcon) g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon); } protected override void OnMouseClick(MouseEventArgs e) { base.OnMouseClick(e); if (e.Button != MouseButtons.Left || Appearance != DockPane.AppearanceStyle.Document) return; var indexHit = HitTest(); if (indexHit > -1) TabCloseButtonHit(indexHit); } private void TabCloseButtonHit(int index) { var mousePos = PointToClient(MousePosition); var tabRect = GetTabRectangle(index); var closeButtonRect = GetCloseButtonRect(tabRect); var mouseRect = new Rectangle(mousePos, new Size(1, 1)); if (closeButtonRect.IntersectsWith(mouseRect)) DockPane.CloseActiveContent(); } private Rectangle GetCloseButtonRect(Rectangle rectTab) { if (Appearance != Docking.DockPane.AppearanceStyle.Document) { return Rectangle.Empty; } const int gap = 3; const int imageSize = 15; return new Rectangle(rectTab.X + rectTab.Width - imageSize - gap - 1, rectTab.Y + gap, imageSize, imageSize); } private void WindowList_Click(object sender, EventArgs e) { SelectMenu.Items.Clear(); foreach (TabVS2012Light tab in Tabs) { IDockContent content = tab.Content; ToolStripItem item = SelectMenu.Items.Add(content.DockHandler.TabText, content.DockHandler.Icon.ToBitmap()); item.Tag = tab.Content; item.Click += new EventHandler(ContextMenuItem_Click); } var workingArea = Screen.GetWorkingArea(ButtonWindowList.PointToScreen(new Point(ButtonWindowList.Width / 2, ButtonWindowList.Height / 2))); var menu = new Rectangle(ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Location.Y + ButtonWindowList.Height)), SelectMenu.Size); var menuMargined = new Rectangle(menu.X - SelectMenuMargin, menu.Y - SelectMenuMargin, menu.Width + SelectMenuMargin, menu.Height + SelectMenuMargin); if (workingArea.Contains(menuMargined)) { SelectMenu.Show(menu.Location); } else { var newPoint = menu.Location; newPoint.X = DrawHelper.Balance(SelectMenu.Width, SelectMenuMargin, newPoint.X, workingArea.Left, workingArea.Right); newPoint.Y = DrawHelper.Balance(SelectMenu.Size.Height, SelectMenuMargin, newPoint.Y, workingArea.Top, workingArea.Bottom); var button = ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Height)); if (newPoint.Y < button.Y) { // flip the menu up to be above the button. newPoint.Y = button.Y - ButtonWindowList.Height; SelectMenu.Show(newPoint, ToolStripDropDownDirection.AboveRight); } else { SelectMenu.Show(newPoint); } } } private void ContextMenuItem_Click(object sender, EventArgs e) { ToolStripMenuItem item = sender as ToolStripMenuItem; if (item != null) { IDockContent content = (IDockContent)item.Tag; DockPane.ActiveContent = content; } } private void SetInertButtons() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) { if (m_buttonClose != null) m_buttonClose.Left = -m_buttonClose.Width; if (m_buttonWindowList != null) m_buttonWindowList.Left = -m_buttonWindowList.Width; } else { ButtonClose.Enabled = false; m_closeButtonVisible = false; ButtonClose.Visible = m_closeButtonVisible; ButtonClose.RefreshChanges(); ButtonWindowList.RefreshChanges(); } } protected override void OnLayout(LayoutEventArgs levent) { if (Appearance == DockPane.AppearanceStyle.Document) { LayoutButtons(); OnRefreshChanges(); } base.OnLayout(levent); } private void LayoutButtons() { Rectangle rectTabStrip = TabStripRectangle; // Set position and size of the buttons int buttonWidth = ButtonClose.Image.Width; int buttonHeight = ButtonClose.Image.Height; int height = rectTabStrip.Height - DocumentButtonGapTop - DocumentButtonGapBottom; if (buttonHeight < height) { buttonWidth = buttonWidth * (height / buttonHeight); buttonHeight = height; } Size buttonSize = new Size(buttonWidth, buttonHeight); int x = rectTabStrip.X + rectTabStrip.Width - DocumentTabGapLeft - DocumentButtonGapRight - buttonWidth; int y = rectTabStrip.Y + DocumentButtonGapTop; Point point = new Point(x, y); ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); // If the close button is not visible draw the window list button overtop. // Otherwise it is drawn to the left of the close button. if (m_closeButtonVisible) point.Offset(-(DocumentButtonGapBetween + buttonWidth), 0); ButtonWindowList.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); } private void Close_Click(object sender, EventArgs e) { DockPane.CloseActiveContent(); } protected internal override int HitTest(Point ptMouse) { if (!TabsRectangle.Contains(ptMouse)) return -1; foreach (Tab tab in Tabs) { GraphicsPath path = GetTabOutline(tab, true, false); if (path.IsVisible(ptMouse)) return Tabs.IndexOf(tab); } return -1; } private Rectangle ActiveClose { get { return _activeClose; } } private bool SetActiveClose(Rectangle rectangle) { if (_activeClose == rectangle) return false; _activeClose = rectangle; return true; } private bool SetMouseOverTab(IDockContent content) { if (DockPane.MouseOverTab == content) return false; DockPane.MouseOverTab = content; return true; } protected override void OnMouseHover(EventArgs e) { int index = HitTest(PointToClient(MousePosition)); string toolTip = string.Empty; base.OnMouseHover(e); bool tabUpdate = false; bool buttonUpdate = false; if (index != -1) { var tab = Tabs[index] as TabVS2012Light; if (Appearance == DockPane.AppearanceStyle.ToolWindow || Appearance == DockPane.AppearanceStyle.Document) { tabUpdate = SetMouseOverTab(tab.Content == DockPane.ActiveContent ? null : tab.Content); } if (!String.IsNullOrEmpty(tab.Content.DockHandler.ToolTipText)) toolTip = tab.Content.DockHandler.ToolTipText; else if (tab.MaxWidth > tab.TabWidth) toolTip = tab.Content.DockHandler.TabText; var mousePos = PointToClient(MousePosition); var tabRect = GetTabRectangle(index); var closeButtonRect = GetCloseButtonRect(tabRect); var mouseRect = new Rectangle(mousePos, new Size(1, 1)); buttonUpdate = SetActiveClose(closeButtonRect.IntersectsWith(mouseRect) ? closeButtonRect : Rectangle.Empty); } else { tabUpdate = SetMouseOverTab(null); buttonUpdate = SetActiveClose(Rectangle.Empty); } if (tabUpdate || buttonUpdate) Invalidate(); if (m_toolTip.GetToolTip(this) != toolTip) { m_toolTip.Active = false; m_toolTip.SetToolTip(this, toolTip); m_toolTip.Active = true; } // requires further tracking of mouse hover behavior, ResetMouseEventArgs(); } protected override void OnMouseLeave(EventArgs e) { var tabUpdate = SetMouseOverTab(null); var buttonUpdate = SetActiveClose(Rectangle.Empty); if (tabUpdate || buttonUpdate) Invalidate(); base.OnMouseLeave(e); } protected override void OnRightToLeftChanged(EventArgs e) { base.OnRightToLeftChanged(e); PerformLayout(); } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. 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. *******************************************************************************/ // // Novell.Directory.Ldap.LdapControl.cs // // Author: // Sunil Kumar ([email protected]) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using Novell.Directory.Ldap.Utilclass; using Novell.Directory.Ldap.Asn1; using Novell.Directory.Ldap.Rfc2251; namespace Novell.Directory.Ldap { /// <summary> Encapsulates optional additional parameters or constraints to be applied to /// an Ldap operation. /// /// When included with LdapConstraints or LdapSearchConstraints /// on an LdapConnection or with a specific operation request, it is /// sent to the server along with operation requests. /// /// </summary> /// <seealso cref="LdapConnection.ResponseControls"> /// </seealso> /// <seealso cref="LdapConstraints.getControls"> /// </seealso> /// <seealso cref="LdapConstraints.setControls"> /// </seealso> public class LdapControl : System.ICloneable { /// <summary> Returns the identifier of the control. /// /// </summary> /// <returns> The object ID of the control. /// </returns> virtual public System.String ID { get { return new System.Text.StringBuilder(control.ControlType.stringValue()).ToString(); } } /// <summary> Returns whether the control is critical for the operation. /// /// </summary> /// <returns> Returns true if the control must be supported for an associated /// operation to be executed, and false if the control is not required for /// the operation. /// </returns> virtual public bool Critical { get { return control.Criticality.booleanValue(); } } internal static RespControlVector RegisteredControls { /* package */ get { return registeredControls; } } /// <summary> Returns the RFC 2251 Control object. /// /// </summary> /// <returns> An ASN.1 RFC 2251 Control. /// </returns> virtual internal RfcControl Asn1Object { /*package*/ get { return control; } } private static RespControlVector registeredControls; private RfcControl control; // An RFC 2251 Control /// <summary> Constructs a new LdapControl object using the specified values. /// /// </summary> /// <param name="oid"> The OID of the control, as a dotted string. /// /// </param> /// <param name="critical"> True if the Ldap operation should be discarded if /// the control is not supported. False if /// the operation can be processed without the control. /// /// </param> /// <param name="values"> The control-specific data. /// </param> [CLSCompliantAttribute(false)] public LdapControl(System.String oid, bool critical, sbyte[] values) { if ((System.Object) oid == null) { throw new System.ArgumentException("An OID must be specified"); } if (values == null) { control = new RfcControl(new RfcLdapOID(oid), new Asn1Boolean(critical)); } else { control = new RfcControl(new RfcLdapOID(oid), new Asn1Boolean(critical), new Asn1OctetString(values)); } return ; } /// <summary> Create an LdapControl from an existing control.</summary> protected internal LdapControl(RfcControl control) { this.control = control; return ; } /// <summary> Returns a copy of the current LdapControl object. /// /// </summary> /// <returns> A copy of the current LdapControl object. /// </returns> public System.Object Clone() { LdapControl cont; try { cont = (LdapControl) base.MemberwiseClone(); } catch (System.Exception ce) { throw new System.SystemException("Internal error, cannot create clone"); } sbyte[] vals = this.getValue(); sbyte[] twin = null; if (vals != null) { //is this necessary? // Yes even though the contructor above allocates a // new Asn1OctetString, vals in that constuctor // is only copied by reference twin = new sbyte[vals.Length]; for (int i = 0; i < vals.Length; i++) { twin[i] = vals[i]; } cont.control = new RfcControl(new RfcLdapOID(ID), new Asn1Boolean(Critical), new Asn1OctetString(twin)); } return cont; } /// <summary> Returns the control-specific data of the object. /// /// </summary> /// <returns> The control-specific data of the object as a byte array, /// or null if the control has no data. /// </returns> [CLSCompliantAttribute(false)] public virtual sbyte[] getValue() { sbyte[] result = null; Asn1OctetString val = control.ControlValue; if (val != null) { result = val.byteValue(); } return result; } /// <summary> Sets the control-specific data of the object. This method is for /// use by an extension of LdapControl. /// </summary> [CLSCompliantAttribute(false)] protected internal virtual void setValue(sbyte[] controlValue) { control.ControlValue = new Asn1OctetString(controlValue); return ; } /// <summary> Registers a class to be instantiated on receipt of a control with the /// given OID. /// /// Any previous registration for the OID is overridden. The /// controlClass must be an extension of LdapControl. /// /// </summary> /// <param name="oid"> The object identifier of the control. /// /// </param> /// <param name="controlClass"> A class which can instantiate an LdapControl. /// </param> public static void register(System.String oid, System.Type controlClass) { registeredControls.registerResponseControl(oid, controlClass); return ; } static LdapControl() { registeredControls = new RespControlVector(5, 5); } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections; using System.IO; using System.Linq; using System.Management.Automation.Internal; using System.Management.Automation.Language; namespace System.Management.Automation { /// <summary> /// Holds the information for a given breakpoint /// </summary> public abstract class Breakpoint { #region properties /// <summary> /// The action to take when the breakpoint is hit /// </summary> public ScriptBlock Action { get; private set; } /// <summary> /// Gets whether this breakpoint is enabled /// </summary> public bool Enabled { get; private set; } internal void SetEnabled(bool value) { Enabled = value; } /// <summary> /// Records how many times this breakpoint has been triggered /// </summary> public int HitCount { get; private set; } /// <summary> /// This breakpoint's Id /// </summary> public int Id { get; private set; } /// <summary> /// True if breakpoint is set on a script, false if the breakpoint is not scoped /// </summary> internal bool IsScriptBreakpoint { get { return Script != null; } } /// <summary> /// The script this breakpoint is on, or null if the breakpoint is not scoped /// </summary> public string Script { get; private set; } #endregion properties #region constructors internal Breakpoint(string script, ScriptBlock action) { Enabled = true; Script = script; Id = s_lastID++; Action = action; HitCount = 0; } internal Breakpoint(string script, ScriptBlock action, int id) { Enabled = true; Script = script; Id = id; Action = action; HitCount = 0; } #endregion constructors #region methods internal BreakpointAction Trigger() { ++HitCount; if (null == Action) { return BreakpointAction.Break; } try { // Pass this to the action so the breakpoint. This could be used to // implement a "trigger once" breakpoint that disables itself after first hit. // One could also share an action across many breakpoints - and hence needs // to know something about the breakpoint that is hit, e.g. in a poor mans code coverage tool. Action.DoInvoke(dollarUnder: this, input: null, args: Utils.EmptyArray<object>()); } catch (BreakException) { return BreakpointAction.Break; } catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); } return BreakpointAction.Continue; } internal virtual void RemoveSelf(ScriptDebugger debugger) { } #endregion methods #region enums internal enum BreakpointAction { Continue = 0x0, Break = 0x1 } #endregion enums #region private members private static int s_lastID; #endregion private members } /// <summary> /// A breakpoint on a command /// </summary> public class CommandBreakpoint : Breakpoint { internal CommandBreakpoint(string script, WildcardPattern command, string commandString, ScriptBlock action) : base(script, action) { CommandPattern = command; Command = commandString; } internal CommandBreakpoint(string script, WildcardPattern command, string commandString, ScriptBlock action, int id) : base(script, action, id) { CommandPattern = command; Command = commandString; } /// <summary> /// Which command this breakpoint is on /// </summary> public string Command { get; private set; } internal WildcardPattern CommandPattern { get; private set; } /// <summary> /// Gets a string representation of this breakpoint. /// </summary> /// <returns>A string representation of this breakpoint</returns> public override string ToString() { return IsScriptBreakpoint ? StringUtil.Format(DebuggerStrings.CommandScriptBreakpointString, Script, Command) : StringUtil.Format(DebuggerStrings.CommandBreakpointString, Command); } internal override void RemoveSelf(ScriptDebugger debugger) { debugger.RemoveCommandBreakpoint(this); } private bool CommandInfoMatches(CommandInfo commandInfo) { if (commandInfo == null) return false; if (CommandPattern.IsMatch(commandInfo.Name)) return true; // If the breakpoint looks like it might have specified a module name and the command // we're checking is in a module, try matching the module\command against the pattern // in the breakpoint. if (!string.IsNullOrEmpty(commandInfo.ModuleName) && Command.IndexOf('\\') != -1) { if (CommandPattern.IsMatch(commandInfo.ModuleName + "\\" + commandInfo.Name)) return true; } var externalScript = commandInfo as ExternalScriptInfo; if (externalScript != null) { if (externalScript.Path.Equals(Command, StringComparison.OrdinalIgnoreCase)) return true; if (CommandPattern.IsMatch(Path.GetFileNameWithoutExtension(externalScript.Path))) return true; } return false; } internal bool Trigger(InvocationInfo invocationInfo) { // invocationInfo.MyCommand can be null when invoked via ScriptBlock.Invoke() if (CommandPattern.IsMatch(invocationInfo.InvocationName) || CommandInfoMatches(invocationInfo.MyCommand)) { return (Script == null || Script.Equals(invocationInfo.ScriptName, StringComparison.OrdinalIgnoreCase)); } return false; } } /// <summary> /// The access type for variable breakpoints to break on /// </summary> public enum VariableAccessMode { /// <summary> /// Break on read access only /// </summary> Read, /// <summary> /// Break on write access only (default) /// </summary> Write, /// <summary> /// Breakon read or write access /// </summary> ReadWrite } /// <summary> /// A breakpoint on a variable /// </summary> public class VariableBreakpoint : Breakpoint { internal VariableBreakpoint(string script, string variable, VariableAccessMode accessMode, ScriptBlock action) : base(script, action) { Variable = variable; AccessMode = accessMode; } internal VariableBreakpoint(string script, string variable, VariableAccessMode accessMode, ScriptBlock action, int id) : base(script, action, id) { Variable = variable; AccessMode = accessMode; } /// <summary> /// The access mode to trigger this variable breakpoint on /// </summary> public VariableAccessMode AccessMode { get; private set; } /// <summary> /// Which variable this breakpoint is on /// </summary> public string Variable { get; private set; } /// <summary> /// Gets the string representation of this breakpoint /// </summary> /// <returns>The string representation of this breakpoint</returns> public override string ToString() { return IsScriptBreakpoint ? StringUtil.Format(DebuggerStrings.VariableScriptBreakpointString, Script, Variable, AccessMode) : StringUtil.Format(DebuggerStrings.VariableBreakpointString, Variable, AccessMode); } internal bool Trigger(string currentScriptFile, bool read) { if (!Enabled) return false; if (AccessMode != VariableAccessMode.ReadWrite && AccessMode != (read ? VariableAccessMode.Read : VariableAccessMode.Write)) return false; if (Script == null || Script.Equals(currentScriptFile, StringComparison.OrdinalIgnoreCase)) { return Trigger() == BreakpointAction.Break; } return false; } internal override void RemoveSelf(ScriptDebugger debugger) { debugger.RemoveVariableBreakpoint(this); } } /// <summary> /// A breakpoint on a line or statement /// </summary> public class LineBreakpoint : Breakpoint { internal LineBreakpoint(string script, int line, ScriptBlock action) : base(script, action) { Diagnostics.Assert(!string.IsNullOrEmpty(script), "Caller to verify script parameter is not null or empty."); Line = line; Column = 0; SequencePointIndex = -1; } internal LineBreakpoint(string script, int line, int column, ScriptBlock action) : base(script, action) { Diagnostics.Assert(!string.IsNullOrEmpty(script), "Caller to verify script parameter is not null or empty."); Line = line; Column = column; SequencePointIndex = -1; } internal LineBreakpoint(string script, int line, int column, ScriptBlock action, int id) : base(script, action, id) { Diagnostics.Assert(!string.IsNullOrEmpty(script), "Caller to verify script parameter is not null or empty."); Line = line; Column = column; SequencePointIndex = -1; } /// <summary> /// Which column this breakpoint is on /// </summary> public int Column { get; private set; } /// <summary> /// Which line this breakpoint is on. /// </summary> public int Line { get; private set; } /// <summary> /// Gets a string representation of this breakpoint. /// </summary> /// <returns>A string representation of this breakpoint</returns> public override string ToString() { return Column == 0 ? StringUtil.Format(DebuggerStrings.LineBreakpointString, Script, Line) : StringUtil.Format(DebuggerStrings.StatementBreakpointString, Script, Line, Column); } internal int SequencePointIndex { get; set; } internal IScriptExtent[] SequencePoints { get; set; } internal BitArray BreakpointBitArray { get; set; } private class CheckBreakpointInScript : AstVisitor { public static bool IsInNestedScriptBlock(Ast ast, LineBreakpoint breakpoint) { var visitor = new CheckBreakpointInScript { _breakpoint = breakpoint }; ast.InternalVisit(visitor); return visitor._result; } private LineBreakpoint _breakpoint; private bool _result; public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) { if (functionDefinitionAst.Extent.ContainsLineAndColumn(_breakpoint.Line, _breakpoint.Column)) { _result = true; return AstVisitAction.StopVisit; } // We don't need to visit the body, we're just checking extents of the topmost functions. // We'll visit the bodies eventually, but only when the nested function/script is executed. return AstVisitAction.SkipChildren; } public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst) { if (scriptBlockExpressionAst.Extent.ContainsLineAndColumn(_breakpoint.Line, _breakpoint.Column)) { _result = true; return AstVisitAction.StopVisit; } // We don't need to visit the body, we're just checking extents of the topmost functions. // We'll visit the bodies eventually, but only when the nested function/script is executed. return AstVisitAction.SkipChildren; } } internal bool TrySetBreakpoint(string scriptFile, FunctionContext functionContext) { Diagnostics.Assert(SequencePointIndex == -1, "shouldn't be trying to set on a pending breakpoint"); if (!scriptFile.Equals(this.Script, StringComparison.OrdinalIgnoreCase)) return false; // A quick check to see if the breakpoint is within the scriptblock. bool couldBeInNestedScriptBlock; var scriptBlock = functionContext._scriptBlock; if (scriptBlock != null) { var ast = scriptBlock.Ast; if (!ast.Extent.ContainsLineAndColumn(Line, Column)) return false; var sequencePoints = functionContext._sequencePoints; if (sequencePoints.Length == 1 && sequencePoints[0] == scriptBlock.Ast.Extent) { // If there was no real executable code in the function (e.g. only function definitions), // we added the entire scriptblock as a sequence point, but it shouldn't be allowed as a breakpoint. return false; } couldBeInNestedScriptBlock = CheckBreakpointInScript.IsInNestedScriptBlock(((IParameterMetadataProvider)ast).Body, this); } else { couldBeInNestedScriptBlock = false; } int sequencePointIndex; var sequencePoint = FindSequencePoint(functionContext, Line, Column, out sequencePointIndex); if (sequencePoint != null) { // If the bp could be in a nested script block, we want to be careful and get the bp in the correct script block. // If it's a simple line bp (no column specified), then the start line must match the bp line exactly, otherwise // we assume the bp is in the nested script block. if (!couldBeInNestedScriptBlock || (sequencePoint.StartLineNumber == Line && Column == 0)) { SetBreakpoint(functionContext, sequencePointIndex); return true; } } // Before using heuristics, make sure the breakpoint isn't in a nested function/script block. if (couldBeInNestedScriptBlock) { return false; } // Not found. First, we check if the line/column is before any real code. If so, we'll // move the breakpoint to the first interesting sequence point (could be a dynamicparam, // begin, process, or end block.) if (scriptBlock != null) { var ast = scriptBlock.Ast; var bodyAst = ((IParameterMetadataProvider)ast).Body; if ((bodyAst.DynamicParamBlock == null || bodyAst.DynamicParamBlock.Extent.IsAfter(Line, Column)) && (bodyAst.BeginBlock == null || bodyAst.BeginBlock.Extent.IsAfter(Line, Column)) && (bodyAst.ProcessBlock == null || bodyAst.ProcessBlock.Extent.IsAfter(Line, Column)) && (bodyAst.EndBlock == null || bodyAst.EndBlock.Extent.IsAfter(Line, Column))) { SetBreakpoint(functionContext, 0); return true; } } // Still not found. Try fudging a bit, but only if it's a simple line breakpoint. if (Column == 0 && FindSequencePoint(functionContext, Line + 1, 0, out sequencePointIndex) != null) { SetBreakpoint(functionContext, sequencePointIndex); return true; } return false; } private static IScriptExtent FindSequencePoint(FunctionContext functionContext, int line, int column, out int sequencePointIndex) { var sequencePoints = functionContext._sequencePoints; for (int i = 0; i < sequencePoints.Length; ++i) { var extent = sequencePoints[i]; if (extent.ContainsLineAndColumn(line, column)) { sequencePointIndex = i; return extent; } } sequencePointIndex = -1; return null; } private void SetBreakpoint(FunctionContext functionContext, int sequencePointIndex) { // Remember the bitarray so we when the last breakpoint is removed, we can avoid // stopping at the sequence point. this.BreakpointBitArray = functionContext._breakPoints; this.SequencePoints = functionContext._sequencePoints; SequencePointIndex = sequencePointIndex; this.BreakpointBitArray.Set(SequencePointIndex, true); } internal override void RemoveSelf(ScriptDebugger debugger) { if (this.SequencePoints != null) { // Remove ourselves from the list of bound breakpoints in this script. It's possible the breakpoint was never // bound, in which case there is nothing to do. var boundBreakPoints = debugger.GetBoundBreakpoints(this.SequencePoints); if (boundBreakPoints != null) { Diagnostics.Assert(boundBreakPoints.Contains(this), "If we set _scriptBlock, we should have also added the breakpoint to the bound breakpoint list"); boundBreakPoints.Remove(this); if (boundBreakPoints.All(breakpoint => breakpoint.SequencePointIndex != this.SequencePointIndex)) { // No other line breakpoints are at the same sequence point, so disable the breakpoint so // we don't go looking for breakpoints the next time we hit the sequence point. // This isn't strictly necessary, but script execution will be faster. this.BreakpointBitArray.Set(SequencePointIndex, false); } } } debugger.RemoveLineBreakpoint(this); } } }
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Security; using System.Xml; namespace Umbraco.Core { public static class ObjectExtensions { //private static readonly ConcurrentDictionary<Type, Func<object>> ObjectFactoryCache = new ConcurrentDictionary<Type, Func<object>>(); public static IEnumerable<T> AsEnumerableOfOne<T>(this T input) { return Enumerable.Repeat(input, 1); } public static void DisposeIfDisposable(this object input) { var disposable = input as IDisposable; if (disposable != null) disposable.Dispose(); } /// <summary> /// Provides a shortcut way of safely casting an input when you cannot guarantee the <typeparam name="T"></typeparam> is an instance type (i.e., when the C# AS keyword is not applicable) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="input">The input.</param> /// <returns></returns> internal static T SafeCast<T>(this object input) { if (ReferenceEquals(null, input) || ReferenceEquals(default(T), input)) return default(T); if (input is T) return (T)input; return default(T); } /// <summary> /// Tries to convert the input object to the output type using TypeConverters /// </summary> /// <typeparam name="T"></typeparam> /// <param name="input"></param> /// <returns></returns> public static Attempt<T> TryConvertTo<T>(this object input) { var result = TryConvertTo(input, typeof(T)); if (!result.Success) { //just try a straight up conversion try { var converted = (T) input; return Attempt<T>.Succeed(converted); } catch (Exception e) { return Attempt<T>.Fail(e); } } return !result.Success ? Attempt<T>.Fail() : Attempt<T>.Succeed((T)result.Result); } /// <summary> /// Tries to convert the input object to the output type using TypeConverters. If the destination type is a superclass of the input type, /// if will use <see cref="Convert.ChangeType(object,System.Type)"/>. /// </summary> /// <param name="input">The input.</param> /// <param name="destinationType">Type of the destination.</param> /// <returns></returns> public static Attempt<object> TryConvertTo(this object input, Type destinationType) { //if it is null and it is nullable, then return success with null if (input == null && destinationType.IsGenericType && destinationType.GetGenericTypeDefinition() == typeof (Nullable<>)) { return Attempt<object>.Succeed(null); } //if its not nullable and it is a value type if (input == null && destinationType.IsValueType) return Attempt<object>.Fail(); //if the type can be null, then no problem if (input == null && destinationType.IsValueType == false) return Attempt<object>.Succeed(null); if (destinationType == typeof(object)) return Attempt.Succeed(input); if (input.GetType() == destinationType) return Attempt.Succeed(input); //check for string so that overloaders of ToString() can take advantage of the conversion. if (destinationType == typeof(string)) return Attempt<object>.Succeed(input.ToString()); // if we've got a nullable of something, we try to convert directly to that thing. if (destinationType.IsGenericType && destinationType.GetGenericTypeDefinition() == typeof(Nullable<>)) { var underlyingType = Nullable.GetUnderlyingType(destinationType); //special case for empty strings for bools/dates which should return null if an empty string var asString = input as string; if (asString != null && string.IsNullOrEmpty(asString) && (underlyingType == typeof(DateTime) || underlyingType == typeof(bool))) { return Attempt<object>.Succeed(null); } // recursively call into myself with the inner (not-nullable) type and handle the outcome var nonNullable = input.TryConvertTo(underlyingType); // and if sucessful, fall on through to rewrap in a nullable; if failed, pass on the exception if (nonNullable.Success) input = nonNullable.Result; // now fall on through... else return Attempt<object>.Fail(nonNullable.Exception); } // we've already dealed with nullables, so any other generic types need to fall through if (!destinationType.IsGenericType) { if (input is string) { var result = TryConvertToFromString(input as string, destinationType); // if we processed the string (succeed or fail), we're done if (result.HasValue) return result.Value; } //TODO: Do a check for destination type being IEnumerable<T> and source type implementing IEnumerable<T> with // the same 'T', then we'd have to find the extension method for the type AsEnumerable() and execute it. if (TypeHelper.IsTypeAssignableFrom(destinationType, input.GetType()) && TypeHelper.IsTypeAssignableFrom<IConvertible>(input)) { try { var casted = Convert.ChangeType(input, destinationType); return Attempt.Succeed(casted); } catch (Exception e) { return Attempt<object>.Fail(e); } } } var inputConverter = TypeDescriptor.GetConverter(input); if (inputConverter.CanConvertTo(destinationType)) { try { var converted = inputConverter.ConvertTo(input, destinationType); return Attempt.Succeed(converted); } catch (Exception e) { return Attempt<object>.Fail(e); } } if (destinationType == typeof(bool)) { var boolConverter = new CustomBooleanTypeConverter(); if (boolConverter.CanConvertFrom(input.GetType())) { try { var converted = boolConverter.ConvertFrom(input); return Attempt.Succeed(converted); } catch (Exception e) { return Attempt<object>.Fail(e); } } } var outputConverter = TypeDescriptor.GetConverter(destinationType); if (outputConverter.CanConvertFrom(input.GetType())) { try { var converted = outputConverter.ConvertFrom(input); return Attempt.Succeed(converted); } catch (Exception e) { return Attempt<object>.Fail(e); } } if (TypeHelper.IsTypeAssignableFrom<IConvertible>(input)) { try { var casted = Convert.ChangeType(input, destinationType); return Attempt.Succeed(casted); } catch (Exception e) { return Attempt<object>.Fail(e); } } return Attempt<object>.Fail(); } private static Nullable<Attempt<object>> TryConvertToFromString(this string input, Type destinationType) { if (destinationType == typeof(string)) return Attempt<object>.Succeed(input); if (string.IsNullOrEmpty(input)) { if (destinationType == typeof(Boolean)) return Attempt<object>.Succeed(false); // special case for booleans, null/empty == false if (destinationType == typeof(DateTime)) return Attempt<object>.Succeed(DateTime.MinValue); } // we have a non-empty string, look for type conversions in the expected order of frequency of use... if (destinationType.IsPrimitive) { if (destinationType == typeof(Int32)) { Int32 value; return Int32.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } if (destinationType == typeof(Int64)) { Int64 value; return Int64.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } if (destinationType == typeof(Boolean)) { Boolean value; if (Boolean.TryParse(input, out value)) return Attempt<object>.Succeed(value); // don't declare failure so the CustomBooleanTypeConverter can try } else if (destinationType == typeof(Int16)) { Int16 value; return Int16.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } else if (destinationType == typeof(Double)) { Double value; var input2 = NormalizeNumberDecimalSeparator(input); return Double.TryParse(input2, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } else if (destinationType == typeof(Single)) { Single value; var input2 = NormalizeNumberDecimalSeparator(input); return Single.TryParse(input2, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } else if (destinationType == typeof(Char)) { Char value; return Char.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } else if (destinationType == typeof(Byte)) { Byte value; return Byte.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } else if (destinationType == typeof(SByte)) { SByte value; return SByte.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } else if (destinationType == typeof(UInt32)) { UInt32 value; return UInt32.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } else if (destinationType == typeof(UInt16)) { UInt16 value; return UInt16.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } else if (destinationType == typeof(UInt64)) { UInt64 value; return UInt64.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } } else if (destinationType == typeof(Guid)) { Guid value; return Guid.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } else if (destinationType == typeof(DateTime)) { DateTime value; if (DateTime.TryParse(input, out value)) { switch (value.Kind) { case DateTimeKind.Unspecified: case DateTimeKind.Utc: return Attempt<object>.Succeed(value); case DateTimeKind.Local: return Attempt<object>.Succeed(value.ToUniversalTime()); default: throw new ArgumentOutOfRangeException(); } } return Attempt<object>.Fail(); } else if (destinationType == typeof(DateTimeOffset)) { DateTimeOffset value; return DateTimeOffset.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } else if (destinationType == typeof(TimeSpan)) { TimeSpan value; return TimeSpan.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } else if (destinationType == typeof(Decimal)) { Decimal value; var input2 = NormalizeNumberDecimalSeparator(input); return Decimal.TryParse(input2, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } else if (destinationType == typeof(Version)) { Version value; return Version.TryParse(input, out value) ? Attempt<object>.Succeed(value) : Attempt<object>.Fail(); } // E_NOTIMPL IPAddress, BigInteger return null; // we can't decide... } private readonly static char[] NumberDecimalSeparatorsToNormalize = new[] {'.', ','}; private static string NormalizeNumberDecimalSeparator(string s) { var normalized = System.Threading.Thread.CurrentThread.CurrentUICulture.NumberFormat.NumberDecimalSeparator[0]; return s.ReplaceMany(NumberDecimalSeparatorsToNormalize, normalized); } internal static void CheckThrowObjectDisposed(this IDisposable disposable, bool isDisposed, string objectname) { //TODO: Localise this exception if (isDisposed) throw new ObjectDisposedException(objectname); } //public enum PropertyNamesCaseType //{ // CamelCase, // CaseInsensitive //} ///// <summary> ///// Convert an object to a JSON string with camelCase formatting ///// </summary> ///// <param name="obj"></param> ///// <returns></returns> //public static string ToJsonString(this object obj) //{ // return obj.ToJsonString(PropertyNamesCaseType.CamelCase); //} ///// <summary> ///// Convert an object to a JSON string with the specified formatting ///// </summary> ///// <param name="obj">The obj.</param> ///// <param name="propertyNamesCaseType">Type of the property names case.</param> ///// <returns></returns> //public static string ToJsonString(this object obj, PropertyNamesCaseType propertyNamesCaseType) //{ // var type = obj.GetType(); // var dateTimeStyle = "yyyy-MM-dd HH:mm:ss"; // if (type.IsPrimitive || typeof(string).IsAssignableFrom(type)) // { // return obj.ToString(); // } // if (typeof(DateTime).IsAssignableFrom(type) || typeof(DateTimeOffset).IsAssignableFrom(type)) // { // return Convert.ToDateTime(obj).ToString(dateTimeStyle); // } // var serializer = new JsonSerializer(); // switch (propertyNamesCaseType) // { // case PropertyNamesCaseType.CamelCase: // serializer.ContractResolver = new CamelCasePropertyNamesContractResolver(); // break; // } // var dateTimeConverter = new IsoDateTimeConverter // { // DateTimeStyles = System.Globalization.DateTimeStyles.None, // DateTimeFormat = dateTimeStyle // }; // if (typeof(IDictionary).IsAssignableFrom(type)) // { // return JObject.FromObject(obj, serializer).ToString(Formatting.None, dateTimeConverter); // } // if (type.IsArray || (typeof(IEnumerable).IsAssignableFrom(type))) // { // return JArray.FromObject(obj, serializer).ToString(Formatting.None, dateTimeConverter); // } // return JObject.FromObject(obj, serializer).ToString(Formatting.None, dateTimeConverter); //} /// <summary> /// Converts an object into a dictionary /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TProperty"></typeparam> /// <typeparam name="TVal"> </typeparam> /// <param name="o"></param> /// <param name="ignoreProperties"></param> /// <returns></returns> internal static IDictionary<string, TVal> ToDictionary<T, TProperty, TVal>(this T o, params Expression<Func<T, TProperty>>[] ignoreProperties) { return o.ToDictionary<TVal>(ignoreProperties.Select(e => o.GetPropertyInfo(e)).Select(propInfo => propInfo.Name).ToArray()); } /// <summary> /// Turns object into dictionary /// </summary> /// <param name="o"></param> /// <param name="ignoreProperties">Properties to ignore</param> /// <returns></returns> internal static IDictionary<string, TVal> ToDictionary<TVal>(this object o, params string[] ignoreProperties) { if (o != null) { var props = TypeDescriptor.GetProperties(o); var d = new Dictionary<string, TVal>(); foreach (var prop in props.Cast<PropertyDescriptor>().Where(x => !ignoreProperties.Contains(x.Name))) { var val = prop.GetValue(o); if (val != null) { d.Add(prop.Name, (TVal)val); } } return d; } return new Dictionary<string, TVal>(); } internal static string ToDebugString(this object obj, int levels = 0) { if (obj == null) return "{null}"; try { if (obj is string) { return "\"{0}\"".InvariantFormat(obj); } if (obj is int || obj is Int16 || obj is Int64 || obj is float || obj is double || obj is bool || obj is int? || obj is Int16? || obj is Int64? || obj is float? || obj is double? || obj is bool?) { return "{0}".InvariantFormat(obj); } if (obj is Enum) { return "[{0}]".InvariantFormat(obj); } if (obj is IEnumerable) { var enumerable = (obj as IEnumerable); var items = (from object enumItem in enumerable let value = GetEnumPropertyDebugString(enumItem, levels) where value != null select value).Take(10).ToList(); return items.Count() > 0 ? "{{ {0} }}".InvariantFormat(String.Join(", ", items)) : null; } var props = obj.GetType().GetProperties(); if ((props.Count() == 2) && props[0].Name == "Key" && props[1].Name == "Value" && levels > -2) { try { var key = props[0].GetValue(obj, null) as string; var value = props[1].GetValue(obj, null).ToDebugString(levels - 1); return "{0}={1}".InvariantFormat(key, value); } catch (Exception) { return "[KeyValuePropertyException]"; } } if (levels > -1) { var items = from propertyInfo in props let value = GetPropertyDebugString(propertyInfo, obj, levels) where value != null select "{0}={1}".InvariantFormat(propertyInfo.Name, value); return items.Count() > 0 ? "[{0}]:{{ {1} }}".InvariantFormat(obj.GetType().Name, String.Join(", ", items)) : null; } } catch (Exception ex) { return "[Exception:{0}]".InvariantFormat(ex.Message); } return null; } /// <summary> /// Attempts to serialize the value to an XmlString using ToXmlString /// </summary> /// <param name="value"></param> /// <param name="type"></param> /// <returns></returns> internal static Attempt<string> TryConvertToXmlString(this object value, Type type) { try { var output = value.ToXmlString(type); return Attempt.Succeed(output); } catch (NotSupportedException ex) { return Attempt<string>.Fail(ex); } } /// <summary> /// Returns an XmlSerialized safe string representation for the value /// </summary> /// <param name="value"></param> /// <param name="type">The Type can only be a primitive type or Guid and byte[] otherwise an exception is thrown</param> /// <returns></returns> internal static string ToXmlString(this object value, Type type) { if (value == null) return string.Empty; if (type == typeof(string)) return (value.ToString().IsNullOrWhiteSpace() ? "" : value.ToString()); if (type == typeof(bool)) return XmlConvert.ToString((bool)value); if (type == typeof(byte)) return XmlConvert.ToString((byte)value); if (type == typeof(char)) return XmlConvert.ToString((char)value); if (type == typeof(DateTime)) return XmlConvert.ToString((DateTime)value, XmlDateTimeSerializationMode.Unspecified); if (type == typeof(DateTimeOffset)) return XmlConvert.ToString((DateTimeOffset)value); if (type == typeof(decimal)) return XmlConvert.ToString((decimal)value); if (type == typeof(double)) return XmlConvert.ToString((double)value); if (type == typeof(float)) return XmlConvert.ToString((float)value); if (type == typeof(Guid)) return XmlConvert.ToString((Guid)value); if (type == typeof(int)) return XmlConvert.ToString((int)value); if (type == typeof(long)) return XmlConvert.ToString((long)value); if (type == typeof(sbyte)) return XmlConvert.ToString((sbyte)value); if (type == typeof(short)) return XmlConvert.ToString((short)value); if (type == typeof(TimeSpan)) return XmlConvert.ToString((TimeSpan)value); if (type == typeof(bool)) return XmlConvert.ToString((bool)value); if (type == typeof(uint)) return XmlConvert.ToString((uint)value); if (type == typeof(ulong)) return XmlConvert.ToString((ulong)value); if (type == typeof(ushort)) return XmlConvert.ToString((ushort)value); throw new NotSupportedException("Cannot convert type " + type.FullName + " to a string using ToXmlString as it is not supported by XmlConvert"); } /// <summary> /// Returns an XmlSerialized safe string representation for the value and type /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value"></param> /// <returns></returns> internal static string ToXmlString<T>(this object value) { return value.ToXmlString(typeof (T)); } private static string GetEnumPropertyDebugString(object enumItem, int levels) { try { return enumItem.ToDebugString(levels - 1); } catch (Exception) { return "[GetEnumPartException]"; } } private static string GetPropertyDebugString(PropertyInfo propertyInfo, object obj, int levels) { try { return propertyInfo.GetValue(obj, null).ToDebugString(levels - 1); } catch (Exception) { return "[GetPropertyValueException]"; } } } }
// // 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. // using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using JetBrains.Annotations; using NLog.Common; using NLog.Filters; using NLog.Internal; using NLog.Layouts; using NLog.Targets; using NLog.Targets.Wrappers; using NLog.Time; namespace NLog.Config { /// <summary> /// Loads NLog configuration from <see cref="ILoggingConfigurationElement"/> /// </summary> public abstract class LoggingConfigurationParser : LoggingConfiguration { private readonly ServiceRepository _serviceRepository; /// <summary> /// Constructor /// </summary> /// <param name="logFactory"></param> protected LoggingConfigurationParser(LogFactory logFactory) : base(logFactory) { _serviceRepository = logFactory.ServiceRepository; } /// <summary> /// Loads NLog configuration from provided config section /// </summary> /// <param name="nlogConfig"></param> /// <param name="basePath">Directory where the NLog-config-file was loaded from</param> protected void LoadConfig(ILoggingConfigurationElement nlogConfig, string basePath) { InternalLogger.Trace("ParseNLogConfig"); nlogConfig.AssertName("nlog"); SetNLogElementSettings(nlogConfig); var validatedConfig = ValidatedConfigurationElement.Create(nlogConfig, LogFactory); // Validate after having loaded initial settings //first load the extensions, as the can be used in other elements (targets etc) foreach (var extensionsChild in validatedConfig.ValidChildren) { if (extensionsChild.MatchesName("extensions")) { ParseExtensionsElement(extensionsChild, basePath); } } var rulesList = new List<ValidatedConfigurationElement>(); //parse all other direct elements foreach (var child in validatedConfig.ValidChildren) { if (child.MatchesName("rules")) { //postpone parsing <rules> to the end rulesList.Add(child); } else if (child.MatchesName("extensions")) { //already parsed } else if (!ParseNLogSection(child)) { var configException = new NLogConfigurationException($"Unrecognized element '{child.Name}' from section 'NLog'"); if (MustThrowConfigException(configException)) throw configException; } } foreach (var ruleChild in rulesList) { ParseRulesElement(ruleChild, LoggingRules); } } private void SetNLogElementSettings(ILoggingConfigurationElement nlogConfig) { var sortedList = CreateUniqueSortedListFromConfig(nlogConfig); CultureInfo defaultCultureInfo = DefaultCultureInfo ?? LogFactory._defaultCultureInfo; bool? parseMessageTemplates = null; bool internalLoggerEnabled = false; bool autoLoadExtensions = false; foreach (var configItem in sortedList) { switch (configItem.Key.ToUpperInvariant()) { case "THROWEXCEPTIONS": LogFactory.ThrowExceptions = ParseBooleanValue(configItem.Key, configItem.Value, LogFactory.ThrowExceptions); break; case "THROWCONFIGEXCEPTIONS": LogFactory.ThrowConfigExceptions = ParseNullableBooleanValue(configItem.Key, configItem.Value, false); break; case "INTERNALLOGLEVEL": InternalLogger.LogLevel = ParseLogLevelSafe(configItem.Key, configItem.Value, InternalLogger.LogLevel); internalLoggerEnabled = InternalLogger.LogLevel != LogLevel.Off; break; case "USEINVARIANTCULTURE": if (ParseBooleanValue(configItem.Key, configItem.Value, false)) defaultCultureInfo = DefaultCultureInfo = CultureInfo.InvariantCulture; break; case "KEEPVARIABLESONRELOAD": LogFactory.KeepVariablesOnReload = ParseBooleanValue(configItem.Key, configItem.Value, LogFactory.KeepVariablesOnReload); break; case "INTERNALLOGTOCONSOLE": InternalLogger.LogToConsole = ParseBooleanValue(configItem.Key, configItem.Value, InternalLogger.LogToConsole); break; case "INTERNALLOGTOCONSOLEERROR": InternalLogger.LogToConsoleError = ParseBooleanValue(configItem.Key, configItem.Value, InternalLogger.LogToConsoleError); break; case "INTERNALLOGFILE": var internalLogFile = configItem.Value?.Trim(); if (!string.IsNullOrEmpty(internalLogFile)) { internalLogFile = ExpandFilePathVariables(internalLogFile); InternalLogger.LogFile = internalLogFile; } break; case "INTERNALLOGTOTRACE": InternalLogger.LogToTrace = ParseBooleanValue(configItem.Key, configItem.Value, InternalLogger.LogToTrace); break; case "INTERNALLOGINCLUDETIMESTAMP": InternalLogger.IncludeTimestamp = ParseBooleanValue(configItem.Key, configItem.Value, InternalLogger.IncludeTimestamp); break; case "GLOBALTHRESHOLD": LogFactory.GlobalThreshold = ParseLogLevelSafe(configItem.Key, configItem.Value, LogFactory.GlobalThreshold); break; // expanding variables not possible here, they are created later case "PARSEMESSAGETEMPLATES": parseMessageTemplates = ParseNullableBooleanValue(configItem.Key, configItem.Value, true); break; case "AUTOSHUTDOWN": LogFactory.AutoShutdown = ParseBooleanValue(configItem.Key, configItem.Value, true); break; case "AUTORELOAD": break; // Ignore here, used by other logic case "AUTOLOADEXTENSIONS": autoLoadExtensions = ParseBooleanValue(configItem.Key, configItem.Value, false); break; default: var configException = new NLogConfigurationException($"Unrecognized value '{configItem.Key}'='{configItem.Value}' for element '{nlogConfig.Name}'"); if (MustThrowConfigException(configException)) throw configException; break; } } if (defaultCultureInfo != null && !ReferenceEquals(DefaultCultureInfo, defaultCultureInfo)) { DefaultCultureInfo = defaultCultureInfo; } if (!internalLoggerEnabled && !InternalLogger.HasActiveLoggers()) { InternalLogger.LogLevel = LogLevel.Off; // Reduce overhead of the InternalLogger when not configured } if (autoLoadExtensions) { ConfigurationItemFactory.ScanForAutoLoadExtensions(LogFactory); } _serviceRepository.RegisterMessageTemplateParser(parseMessageTemplates); } /// <summary> /// Builds list with unique keys, using last value of duplicates. High priority keys placed first. /// </summary> /// <param name="nlogConfig"></param> /// <returns></returns> private ICollection<KeyValuePair<string, string>> CreateUniqueSortedListFromConfig(ILoggingConfigurationElement nlogConfig) { var dict = ValidatedConfigurationElement.Create(nlogConfig, LogFactory).ValueLookup; if (dict.Count == 0) return dict; var sortedList = new List<KeyValuePair<string, string>>(dict.Count); var highPriorityList = new[] { "ThrowExceptions", "ThrowConfigExceptions", "InternalLogLevel", "InternalLogFile", "InternalLogToConsole", }; foreach (var highPrioritySetting in highPriorityList) { if (dict.TryGetValue(highPrioritySetting, out var settingValue)) { sortedList.Add(new KeyValuePair<string, string>(highPrioritySetting, settingValue)); dict.Remove(highPrioritySetting); } } foreach (var configItem in dict) { sortedList.Add(configItem); } return sortedList; } private string ExpandFilePathVariables(string internalLogFile) { try { if (ContainsSubStringIgnoreCase(internalLogFile, "${currentdir}", out string currentDirToken)) internalLogFile = internalLogFile.Replace(currentDirToken, System.IO.Directory.GetCurrentDirectory() + System.IO.Path.DirectorySeparatorChar.ToString()); if (ContainsSubStringIgnoreCase(internalLogFile, "${basedir}", out string baseDirToken)) internalLogFile = internalLogFile.Replace(baseDirToken, LogFactory.CurrentAppEnvironment.AppDomainBaseDirectory + System.IO.Path.DirectorySeparatorChar.ToString()); if (ContainsSubStringIgnoreCase(internalLogFile, "${tempdir}", out string tempDirToken)) internalLogFile = internalLogFile.Replace(tempDirToken, LogFactory.CurrentAppEnvironment.UserTempFilePath + System.IO.Path.DirectorySeparatorChar.ToString()); #if !NETSTANDARD1_3 if (ContainsSubStringIgnoreCase(internalLogFile, "${processdir}", out string processDirToken)) internalLogFile = internalLogFile.Replace(processDirToken, System.IO.Path.GetDirectoryName(LogFactory.CurrentAppEnvironment.CurrentProcessFilePath) + System.IO.Path.DirectorySeparatorChar.ToString()); #endif if (internalLogFile.IndexOf('%') >= 0) internalLogFile = Environment.ExpandEnvironmentVariables(internalLogFile); return internalLogFile; } catch { return internalLogFile; } } private static bool ContainsSubStringIgnoreCase(string haystack, string needle, out string result) { int needlePos = haystack.IndexOf(needle, StringComparison.OrdinalIgnoreCase); result = needlePos >= 0 ? haystack.Substring(needlePos, needle.Length) : null; return result != null; } /// <summary> /// Parse loglevel, but don't throw if exception throwing is disabled /// </summary> /// <param name="propertyName">Name of attribute for logging.</param> /// <param name="propertyValue">Value of parse.</param> /// <param name="fallbackValue">Used if there is an exception</param> /// <returns></returns> private LogLevel ParseLogLevelSafe(string propertyName, string propertyValue, LogLevel fallbackValue) { try { var internalLogLevel = LogLevel.FromString(propertyValue?.Trim()); return internalLogLevel; } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) throw; var configException = new NLogConfigurationException($"Property '{propertyName}' assigned invalid LogLevel value '{propertyValue}'. Fallback to '{fallbackValue}'", exception); if (MustThrowConfigException(configException)) throw configException; return fallbackValue; } } /// <summary> /// Parses a single config section within the NLog-config /// </summary> /// <param name="configSection"></param> /// <returns>Section was recognized</returns> protected virtual bool ParseNLogSection(ILoggingConfigurationElement configSection) { switch (configSection.Name?.Trim().ToUpperInvariant()) { case "TIME": ParseTimeElement(ValidatedConfigurationElement.Create(configSection, LogFactory)); return true; case "VARIABLE": ParseVariableElement(ValidatedConfigurationElement.Create(configSection, LogFactory)); return true; case "VARIABLES": ParseVariablesElement(ValidatedConfigurationElement.Create(configSection, LogFactory)); return true; case "APPENDERS": case "TARGETS": ParseTargetsElement(ValidatedConfigurationElement.Create(configSection, LogFactory)); return true; } return false; } private void ParseExtensionsElement(ValidatedConfigurationElement extensionsElement, string baseDirectory) { extensionsElement.AssertName("extensions"); foreach (var childItem in extensionsElement.ValidChildren) { string prefix = null; string type = null; string assemblyFile = null; string assemblyName = null; foreach (var childProperty in childItem.Values) { if (MatchesName(childProperty.Key, "prefix")) { prefix = childProperty.Value + "."; } else if (MatchesName(childProperty.Key, "type")) { type = childProperty.Value; } else if (MatchesName(childProperty.Key, "assemblyFile")) { assemblyFile = childProperty.Value; } else if (MatchesName(childProperty.Key, "assembly")) { assemblyName = childProperty.Value; } else { var configException = new NLogConfigurationException($"Unrecognized value '{childProperty.Key}'='{childProperty.Value}' for element '{childItem.Name}' in section '{extensionsElement.Name}'"); if (MustThrowConfigException(configException)) throw configException; } } if (!StringHelpers.IsNullOrWhiteSpace(type)) { RegisterExtension(type, prefix); } #if !NETSTANDARD1_3 if (!StringHelpers.IsNullOrWhiteSpace(assemblyFile)) { ParseExtensionWithAssemblyFile(baseDirectory, assemblyFile, prefix); continue; } #endif if (!StringHelpers.IsNullOrWhiteSpace(assemblyName)) { ParseExtensionWithAssembly(assemblyName, prefix); } } } private void RegisterExtension(string type, string itemNamePrefix) { try { ConfigurationItemFactory.Default.RegisterType(Type.GetType(type, true), itemNamePrefix); } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) throw; var configException = new NLogConfigurationException("Error loading extensions: " + type, exception); if (MustThrowConfigException(configException)) throw configException; } } #if !NETSTANDARD1_3 private void ParseExtensionWithAssemblyFile(string baseDirectory, string assemblyFile, string prefix) { try { Assembly asm = AssemblyHelpers.LoadFromPath(assemblyFile, baseDirectory); ConfigurationItemFactory.Default.RegisterItemsFromAssembly(asm, prefix); } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) throw; var configException = new NLogConfigurationException("Error loading extensions: " + assemblyFile, exception); if (MustThrowConfigException(configException)) throw configException; } } #endif private void ParseExtensionWithAssembly(string assemblyName, string prefix) { try { Assembly asm = AssemblyHelpers.LoadFromName(assemblyName); ConfigurationItemFactory.Default.RegisterItemsFromAssembly(asm, prefix); } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) throw; var configException = new NLogConfigurationException("Error loading extensions: " + assemblyName, exception); if (MustThrowConfigException(configException)) throw configException; } } private void ParseVariableElement(ValidatedConfigurationElement variableElement) { string variableName = null; string variableValue = null; foreach (var childProperty in variableElement.Values) { if (MatchesName(childProperty.Key, "name")) variableName = childProperty.Value; else if (MatchesName(childProperty.Key, "value") || MatchesName(childProperty.Key, "layout")) variableValue = childProperty.Value; else { var configException = new NLogConfigurationException($"Unrecognized value '{childProperty.Key}'='{childProperty.Value}' for element '{variableElement.Name}' in section 'variables'"); if (MustThrowConfigException(configException)) throw configException; } } if (!AssertNonEmptyValue(variableName, "name", variableElement.Name, "variables")) return; Layout variableLayout = variableValue is null ? ParseVariableLayoutValue(variableElement) : CreateSimpleLayout(ExpandSimpleVariables(variableValue)); if (!AssertNotNullValue(variableLayout, "value", variableElement.Name, "variables")) return; InsertParsedConfigVariable(variableName, variableLayout); } private Layout ParseVariableLayoutValue(ValidatedConfigurationElement variableElement) { var childElement = variableElement.ValidChildren.FirstOrDefault(); if (childElement != null) { var variableLayout = TryCreateLayoutInstance(childElement, typeof(Layout)); if (variableLayout != null) { ConfigureFromAttributesAndElements(variableLayout, childElement); return variableLayout; } } return null; } private void ParseVariablesElement(ValidatedConfigurationElement variableElement) { variableElement.AssertName("variables"); foreach (var childItem in variableElement.ValidChildren) { ParseVariableElement(childItem); } } private void ParseTimeElement(ValidatedConfigurationElement timeElement) { timeElement.AssertName("time"); string timeSourceType = null; foreach (var childProperty in timeElement.Values) { if (MatchesName(childProperty.Key, "type")) { timeSourceType = childProperty.Value; } else { var configException = new NLogConfigurationException($"Unrecognized value '{childProperty.Key}'='{childProperty.Value}' for element '{timeElement.Name}'"); if (MustThrowConfigException(configException)) throw configException; } } if (!AssertNonEmptyValue(timeSourceType, "type", timeElement.Name, string.Empty)) return; TimeSource newTimeSource = FactoryCreateInstance(timeSourceType, ConfigurationItemFactory.Default.TimeSources); if (newTimeSource != null) { ConfigureFromAttributesAndElements(newTimeSource, timeElement); InternalLogger.Info("Selecting time source {0}", newTimeSource); TimeSource.Current = newTimeSource; } } [ContractAnnotation("value:notnull => true")] private bool AssertNotNullValue(object value, string propertyName, string elementName, string sectionName) { if (value is null) return AssertNonEmptyValue(string.Empty, propertyName, elementName, sectionName); return true; } [ContractAnnotation("value:null => false")] private bool AssertNonEmptyValue(string value, string propertyName, string elementName, string sectionName) { if (!StringHelpers.IsNullOrWhiteSpace(value)) return true; var configException = new NLogConfigurationException($"Property '{propertyName}' has blank value, for element '{elementName}' in section '{sectionName}'"); if (MustThrowConfigException(configException)) throw configException; return false; } /// <summary> /// Parse {Rules} xml element /// </summary> /// <param name="rulesElement"></param> /// <param name="rulesCollection">Rules are added to this parameter.</param> private void ParseRulesElement(ValidatedConfigurationElement rulesElement, IList<LoggingRule> rulesCollection) { InternalLogger.Trace("ParseRulesElement"); rulesElement.AssertName("rules"); foreach (var childItem in rulesElement.ValidChildren) { LoggingRule loggingRule = ParseRuleElement(childItem); if (loggingRule != null) { lock (rulesCollection) { rulesCollection.Add(loggingRule); } } } } private LogLevel LogLevelFromString(string text) { return LogLevel.FromString(ExpandSimpleVariables(text).Trim()); } /// <summary> /// Parse {Logger} xml element /// </summary> /// <param name="loggerElement"></param> private LoggingRule ParseRuleElement(ValidatedConfigurationElement loggerElement) { string minLevel = null; string maxLevel = null; string finalMinLevel = null; string enableLevels = null; string ruleName = null; string namePattern = null; bool enabled = true; bool final = false; string writeTargets = null; string filterDefaultAction = null; foreach (var childProperty in loggerElement.Values) { switch (childProperty.Key?.Trim().ToUpperInvariant()) { case "NAME": if (loggerElement.MatchesName("logger")) namePattern = childProperty.Value; // Legacy Style else ruleName = childProperty.Value; break; case "RULENAME": ruleName = childProperty.Value; break; case "LOGGER": namePattern = childProperty.Value; break; case "ENABLED": enabled = ParseBooleanValue(childProperty.Key, childProperty.Value, true); break; case "APPENDTO": writeTargets = childProperty.Value; break; case "WRITETO": writeTargets = childProperty.Value; break; case "FINAL": final = ParseBooleanValue(childProperty.Key, childProperty.Value, false); break; case "LEVEL": case "LEVELS": enableLevels = childProperty.Value; break; case "MINLEVEL": minLevel = childProperty.Value; break; case "MAXLEVEL": maxLevel = childProperty.Value; break; case "FINALMINLEVEL": finalMinLevel = childProperty.Value; break; case "FILTERDEFAULTACTION": filterDefaultAction = childProperty.Value; break; default: var configException = new NLogConfigurationException($"Unrecognized value '{childProperty.Key}'='{childProperty.Value}' for element '{loggerElement.Name}' in section 'rules'"); if (MustThrowConfigException(configException)) throw configException; break; } } if (string.IsNullOrEmpty(ruleName) && string.IsNullOrEmpty(namePattern) && string.IsNullOrEmpty(writeTargets) && !final) { InternalLogger.Debug("Logging rule without name or filter or targets is ignored"); return null; } namePattern = namePattern ?? "*"; if (!enabled) { InternalLogger.Debug("Logging rule {0} with name pattern `{1}` is disabled", ruleName, namePattern); return null; } var rule = new LoggingRule(ruleName) { LoggerNamePattern = namePattern, Final = final, }; if (!string.IsNullOrEmpty(finalMinLevel)) { rule.FinalMinLevel = LogLevelFromString(finalMinLevel); if (string.IsNullOrEmpty(enableLevels) && string.IsNullOrEmpty(minLevel)) { minLevel = finalMinLevel; } } EnableLevelsForRule(rule, enableLevels, minLevel, maxLevel); ParseLoggingRuleTargets(writeTargets, rule); ParseLoggingRuleChildren(loggerElement, rule, filterDefaultAction); return rule; } private void EnableLevelsForRule(LoggingRule rule, string enableLevels, string minLevel, string maxLevel) { if (enableLevels != null) { enableLevels = ExpandSimpleVariables(enableLevels); if (enableLevels.IndexOf('{') >= 0) { SimpleLayout simpleLayout = ParseLevelLayout(enableLevels); rule.EnableLoggingForLevelLayout(simpleLayout); } else { foreach (var logLevel in enableLevels.SplitAndTrimTokens(',')) { rule.EnableLoggingForLevel(LogLevelFromString(logLevel)); } } } else { minLevel = minLevel != null ? ExpandSimpleVariables(minLevel) : minLevel; maxLevel = maxLevel != null ? ExpandSimpleVariables(maxLevel) : maxLevel; if (minLevel?.IndexOf('{') >= 0 || maxLevel?.IndexOf('{') >= 0) { SimpleLayout minLevelLayout = ParseLevelLayout(minLevel); SimpleLayout maxLevelLayout = ParseLevelLayout(maxLevel); rule.EnableLoggingForLevelsLayout(minLevelLayout, maxLevelLayout); } else { LogLevel minLogLevel = minLevel != null ? LogLevelFromString(minLevel) : LogLevel.MinLevel; LogLevel maxLogLevel = maxLevel != null ? LogLevelFromString(maxLevel) : LogLevel.MaxLevel; rule.SetLoggingLevels(minLogLevel, maxLogLevel); } } } private SimpleLayout ParseLevelLayout(string levelLayout) { SimpleLayout simpleLayout = !StringHelpers.IsNullOrWhiteSpace(levelLayout) ? CreateSimpleLayout(levelLayout) : null; simpleLayout?.Initialize(this); return simpleLayout; } private void ParseLoggingRuleTargets(string writeTargets, LoggingRule rule) { if (string.IsNullOrEmpty(writeTargets)) return; foreach (string targetName in writeTargets.SplitAndTrimTokens(',')) { Target target = FindTargetByName(targetName); if (target != null) { rule.Targets.Add(target); } else { var configException = new NLogConfigurationException($"Target '{targetName}' not found for logging rule: {(string.IsNullOrEmpty(rule.RuleName) ? rule.LoggerNamePattern : rule.RuleName)}."); if (MustThrowConfigException(configException)) throw configException; } } } private void ParseLoggingRuleChildren(ValidatedConfigurationElement loggerElement, LoggingRule rule, string filterDefaultAction = null) { foreach (var child in loggerElement.ValidChildren) { LoggingRule childRule = null; if (child.MatchesName("filters")) { ParseFilters(rule, child, filterDefaultAction); } else if (child.MatchesName("logger") && loggerElement.MatchesName("logger")) { childRule = ParseRuleElement(child); } else if (child.MatchesName("rule") && loggerElement.MatchesName("rule")) { childRule = ParseRuleElement(child); } else { var configException = new NLogConfigurationException($"Unrecognized child element '{child.Name}' for element '{loggerElement.Name}' in section 'rules'"); if (MustThrowConfigException(configException)) throw configException; } if (childRule != null) { lock (rule.ChildRules) { rule.ChildRules.Add(childRule); } } } } private void ParseFilters(LoggingRule rule, ValidatedConfigurationElement filtersElement, string filterDefaultAction = null) { filtersElement.AssertName("filters"); filterDefaultAction = filtersElement.GetOptionalValue("defaultAction", null) ?? filtersElement.GetOptionalValue(nameof(rule.FilterDefaultAction), null) ?? filterDefaultAction; if (filterDefaultAction != null) { SetPropertyValueFromString(rule, nameof(rule.FilterDefaultAction), filterDefaultAction, filtersElement); } foreach (var filterElement in filtersElement.ValidChildren) { var filterType = filterElement.GetOptionalValue("type", null) ?? filterElement.Name; Filter filter = FactoryCreateInstance(filterType, ConfigurationItemFactory.Default.Filters); ConfigureFromAttributesAndElements(filter, filterElement, true); rule.Filters.Add(filter); } } private void ParseTargetsElement(ValidatedConfigurationElement targetsElement) { targetsElement.AssertName("targets", "appenders"); bool asyncWrap = ParseBooleanValue("async", targetsElement.GetOptionalValue("async", "false"), false); ValidatedConfigurationElement defaultWrapperElement = null; var typeNameToDefaultTargetParameters = new Dictionary<string, ValidatedConfigurationElement>(StringComparer.OrdinalIgnoreCase); foreach (var targetElement in targetsElement.ValidChildren) { string targetTypeName = targetElement.GetConfigItemTypeAttribute(); string targetValueName = targetElement.GetOptionalValue("name", null); Target newTarget = null; if (!string.IsNullOrEmpty(targetValueName)) targetValueName = $"{targetElement.Name}(Name={targetValueName})"; else targetValueName = targetElement.Name; switch (targetElement.Name?.Trim().ToUpperInvariant()) { case "DEFAULT-WRAPPER": case "TARGETDEFAULTWRAPPER": if (AssertNonEmptyValue(targetTypeName, "type", targetValueName, targetsElement.Name)) { defaultWrapperElement = targetElement; } break; case "DEFAULT-TARGET-PARAMETERS": case "TARGETDEFAULTPARAMETERS": if (AssertNonEmptyValue(targetTypeName, "type", targetValueName, targetsElement.Name)) { typeNameToDefaultTargetParameters[targetTypeName.Trim()] = targetElement; } break; case "TARGET": case "APPENDER": case "WRAPPER": case "WRAPPER-TARGET": case "COMPOUND-TARGET": if (AssertNonEmptyValue(targetTypeName, "type", targetValueName, targetsElement.Name)) { newTarget = CreateTargetType(targetTypeName); if (newTarget != null) { ParseTargetElement(newTarget, targetElement, typeNameToDefaultTargetParameters); } } break; default: var configException = new NLogConfigurationException($"Unrecognized element '{targetValueName}' in section '{targetsElement.Name}'"); if (MustThrowConfigException(configException)) throw configException; break; } if (newTarget != null) { if (asyncWrap) { newTarget = WrapWithAsyncTargetWrapper(newTarget); } if (defaultWrapperElement != null) { newTarget = WrapWithDefaultWrapper(newTarget, defaultWrapperElement); } InternalLogger.Info("Adding target {0}(Name={1})", newTarget.GetType().Name, newTarget.Name); AddTarget(newTarget.Name, newTarget); } } } private Target CreateTargetType(string targetTypeName) { return FactoryCreateInstance(targetTypeName, ConfigurationItemFactory.Default.Targets); } private void ParseTargetElement(Target target, ValidatedConfigurationElement targetElement, Dictionary<string, ValidatedConfigurationElement> typeNameToDefaultTargetParameters = null) { string targetTypeName = targetElement.GetConfigItemTypeAttribute("targets"); if (typeNameToDefaultTargetParameters != null && typeNameToDefaultTargetParameters.TryGetValue(targetTypeName, out var defaults)) { ParseTargetElement(target, defaults, null); } var compound = target as CompoundTargetBase; var wrapper = target as WrapperTargetBase; ConfigureObjectFromAttributes(target, targetElement, true); foreach (var childElement in targetElement.ValidChildren) { if (compound != null && ParseCompoundTarget(compound, childElement, typeNameToDefaultTargetParameters, null)) { continue; } if (wrapper != null && ParseTargetWrapper(wrapper, childElement, typeNameToDefaultTargetParameters)) { continue; } SetPropertyValuesFromElement(target, childElement, targetElement); } } private bool ParseTargetWrapper( WrapperTargetBase wrapper, ValidatedConfigurationElement childElement, Dictionary<string, ValidatedConfigurationElement> typeNameToDefaultTargetParameters) { if (IsTargetRefElement(childElement.Name)) { var targetName = childElement.GetRequiredValue("name", GetName(wrapper)); Target newTarget = FindTargetByName(targetName); if (newTarget is null) { var configException = new NLogConfigurationException($"Referenced target '{targetName}' not found."); if (MustThrowConfigException(configException)) throw configException; } wrapper.WrappedTarget = newTarget; return true; } if (IsTargetElement(childElement.Name)) { string targetTypeName = childElement.GetConfigItemTypeAttribute(GetName(wrapper)); Target newTarget = CreateTargetType(targetTypeName); if (newTarget != null) { ParseTargetElement(newTarget, childElement, typeNameToDefaultTargetParameters); if (!string.IsNullOrEmpty(newTarget.Name)) { // if the new target has name, register it AddTarget(newTarget.Name, newTarget); } else if (!string.IsNullOrEmpty(wrapper.Name)) { newTarget.Name = wrapper.Name + "_wrapped"; } if (wrapper.WrappedTarget != null) { var configException = new NLogConfigurationException($"Failed to assign wrapped target {targetTypeName}, because target {wrapper.Name} already has one."); if (MustThrowConfigException(configException)) throw configException; } } wrapper.WrappedTarget = newTarget; return true; } return false; } private bool ParseCompoundTarget( CompoundTargetBase compound, ValidatedConfigurationElement childElement, Dictionary<string, ValidatedConfigurationElement> typeNameToDefaultTargetParameters, string targetName) { if (MatchesName(childElement.Name, "targets") || MatchesName(childElement.Name, "appenders")) { foreach (var child in childElement.ValidChildren) { ParseCompoundTarget(compound, child, typeNameToDefaultTargetParameters, null); } return true; } if (IsTargetRefElement(childElement.Name)) { targetName = childElement.GetRequiredValue("name", GetName(compound)); Target newTarget = FindTargetByName(targetName); if (newTarget is null) { throw new NLogConfigurationException("Referenced target '" + targetName + "' not found."); } compound.Targets.Add(newTarget); return true; } if (IsTargetElement(childElement.Name)) { string targetTypeName = childElement.GetConfigItemTypeAttribute(GetName(compound)); Target newTarget = CreateTargetType(targetTypeName); if (newTarget != null) { if (targetName != null) newTarget.Name = targetName; ParseTargetElement(newTarget, childElement, typeNameToDefaultTargetParameters); if (newTarget.Name != null) { // if the new target has name, register it AddTarget(newTarget.Name, newTarget); } compound.Targets.Add(newTarget); } return true; } return false; } private void ConfigureObjectFromAttributes(object targetObject, ValidatedConfigurationElement element, bool ignoreType) { foreach (var kvp in element.ValueLookup) { string childName = kvp.Key; string childValue = kvp.Value; if (ignoreType && MatchesName(childName, "type")) { continue; } SetPropertyValueFromString(targetObject, childName, childValue, element); } } private void SetPropertyValueFromString(object targetObject, string propertyName, string propertyValue, ValidatedConfigurationElement element) { try { var propertyValueExpanded = ExpandSimpleVariables(propertyValue, out var matchingVariableName); if (matchingVariableName != null && propertyValueExpanded == propertyValue && TrySetPropertyFromConfigVariableLayout(targetObject, propertyName, matchingVariableName)) return; PropertyHelper.SetPropertyFromString(targetObject, propertyName, propertyValueExpanded, ConfigurationItemFactory.Default); } catch (NLogConfigurationException ex) { if (MustThrowConfigException(ex)) throw; } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; var configException = new NLogConfigurationException($"'{targetObject?.GetType()?.Name}' cannot assign property '{propertyName}'='{propertyValue}' in section '{element.Name}'. Error: {ex.Message}", ex); if (MustThrowConfigException(configException)) throw; } } private bool TrySetPropertyFromConfigVariableLayout(object targetObject, string propertyName, string configVariableName) { if (TryLookupDynamicVariable(configVariableName, out var matchingLayout) && PropertyHelper.TryGetPropertyInfo(targetObject, propertyName, out var propInfo) && propInfo.PropertyType.IsAssignableFrom(matchingLayout.GetType())) { propInfo.SetValue(targetObject, matchingLayout, null); return true; } return false; } private void SetPropertyValuesFromElement(object o, ValidatedConfigurationElement childElement, ILoggingConfigurationElement parentElement) { if (!PropertyHelper.TryGetPropertyInfo(o, childElement.Name, out var propInfo)) { var configException = new NLogConfigurationException($"'{o?.GetType()?.Name}' cannot assign unknown property '{childElement.Name}' in section '{parentElement.Name}'"); if (MustThrowConfigException(configException)) throw configException; return; } if (AddArrayItemFromElement(o, propInfo, childElement)) { return; } if (SetLayoutFromElement(o, propInfo, childElement)) { return; } if (SetFilterFromElement(o, propInfo, childElement)) { return; } object item = propInfo.GetValue(o, null); ConfigureFromAttributesAndElements(item, childElement); } private bool AddArrayItemFromElement(object o, PropertyInfo propInfo, ValidatedConfigurationElement element) { Type elementType = PropertyHelper.GetArrayItemType(propInfo); if (elementType != null) { IList propertyValue = (IList)propInfo.GetValue(o, null); if (string.Equals(propInfo.Name, element.Name, StringComparison.OrdinalIgnoreCase)) { bool foundChild = false; foreach (var child in element.ValidChildren) { foundChild = true; propertyValue.Add(ParseArrayItemFromElement(elementType, child)); } if (foundChild) return true; } object arrayItem = ParseArrayItemFromElement(elementType, element); propertyValue.Add(arrayItem); return true; } return false; } private object ParseArrayItemFromElement(Type elementType, ValidatedConfigurationElement element) { object arrayItem = TryCreateLayoutInstance(element, elementType); // arrayItem is not a layout if (arrayItem is null) arrayItem = _serviceRepository.GetService(elementType); ConfigureFromAttributesAndElements(arrayItem, element); return arrayItem; } private bool SetLayoutFromElement(object o, PropertyInfo propInfo, ValidatedConfigurationElement element) { var layout = TryCreateLayoutInstance(element, propInfo.PropertyType); // and is a Layout and 'type' attribute has been specified if (layout != null) { SetItemOnProperty(o, propInfo, element, layout); return true; } return false; } private bool SetFilterFromElement(object o, PropertyInfo propInfo, ValidatedConfigurationElement element) { var type = propInfo.PropertyType; Filter filter = TryCreateFilterInstance(element, type); // and is a Filter and 'type' attribute has been specified if (filter != null) { SetItemOnProperty(o, propInfo, element, filter); return true; } return false; } private SimpleLayout CreateSimpleLayout(string layoutText) { return new SimpleLayout(layoutText, ConfigurationItemFactory.Default, LogFactory.ThrowConfigExceptions); } private Layout TryCreateLayoutInstance(ValidatedConfigurationElement element, Type type) { return TryCreateInstance(element, type, ConfigurationItemFactory.Default.Layouts); } private Filter TryCreateFilterInstance(ValidatedConfigurationElement element, Type type) { return TryCreateInstance(element, type, ConfigurationItemFactory.Default.Filters); } private T TryCreateInstance<T>(ValidatedConfigurationElement element, Type type, INamedItemFactory<T, Type> factory) where T : class { // Check if correct type if (!typeof(T).IsAssignableFrom(type)) return null; // Check if the 'type' attribute has been specified string classType = element.GetConfigItemTypeAttribute(); if (classType is null) return null; return FactoryCreateInstance(classType, factory); } private T FactoryCreateInstance<T>(string classType, INamedItemFactory<T, Type> factory) where T : class { T newInstance = null; try { classType = ExpandSimpleVariables(classType); if (classType.Contains(',')) { // Possible specification of assemlby-name detected if (factory.TryCreateInstance(classType, out newInstance) && newInstance != null) return newInstance; // Attempt to load the assembly name extracted from the prefix classType = RegisterExtensionFromAssemblyName(classType); } newInstance = factory.CreateInstance(classType); if (newInstance is null) { throw new NLogConfigurationException($"Factory returned null for {typeof(T).Name} of type: {classType}"); } } catch (NLogConfigurationException configException) { if (MustThrowConfigException(configException)) throw; } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; var configException = new NLogConfigurationException($"Failed to create {typeof(T).Name} of type: {classType}", ex); if (MustThrowConfigException(configException)) throw configException; } return newInstance; } private string RegisterExtensionFromAssemblyName(string classType) { var assemblyName = classType.Substring(classType.IndexOf(',') + 1).Trim(); if (!string.IsNullOrEmpty(assemblyName)) { try { ParseExtensionWithAssembly(assemblyName, string.Empty); return classType.Substring(0, classType.IndexOf(',')).Trim() + ", " + assemblyName; // uniform format } catch (Exception ex) { if (ex.MustBeRethrownImmediately()) throw; } } return classType; } private void SetItemOnProperty(object o, PropertyInfo propInfo, ValidatedConfigurationElement element, object properyValue) { ConfigureFromAttributesAndElements(properyValue, element); propInfo.SetValue(o, properyValue, null); } private void ConfigureFromAttributesAndElements(object targetObject, ValidatedConfigurationElement element, bool ignoreTypeProperty = true) { ConfigureObjectFromAttributes(targetObject, element, ignoreTypeProperty); foreach (var childElement in element.ValidChildren) { SetPropertyValuesFromElement(targetObject, childElement, element); } } private static Target WrapWithAsyncTargetWrapper(Target target) { #if !NET35 if (target is AsyncTaskTarget) { InternalLogger.Debug("Skip wrapping target '{0}' with AsyncTargetWrapper", target.Name); return target; } #endif if (target is AsyncTargetWrapper) { InternalLogger.Debug("Skip wrapping target '{0}' with AsyncTargetWrapper", target.Name); return target; } var asyncTargetWrapper = new AsyncTargetWrapper(); asyncTargetWrapper.WrappedTarget = target; asyncTargetWrapper.Name = target.Name; target.Name = target.Name + "_wrapped"; InternalLogger.Debug("Wrapping target '{0}' with AsyncTargetWrapper and renaming to '{1}", asyncTargetWrapper.Name, target.Name); target = asyncTargetWrapper; return target; } private Target WrapWithDefaultWrapper(Target target, ValidatedConfigurationElement defaultWrapperElement) { string wrapperTypeName = defaultWrapperElement.GetConfigItemTypeAttribute("targets"); Target wrapperTargetInstance = CreateTargetType(wrapperTypeName); WrapperTargetBase wtb = wrapperTargetInstance as WrapperTargetBase; if (wtb is null) { throw new NLogConfigurationException("Target type specified on <default-wrapper /> is not a wrapper."); } ParseTargetElement(wrapperTargetInstance, defaultWrapperElement); while (wtb.WrappedTarget != null) { wtb = wtb.WrappedTarget as WrapperTargetBase; if (wtb is null) { throw new NLogConfigurationException( "Child target type specified on <default-wrapper /> is not a wrapper."); } } #if !NET35 if (target is AsyncTaskTarget && wrapperTargetInstance is AsyncTargetWrapper && ReferenceEquals(wrapperTargetInstance, wtb)) { InternalLogger.Debug("Skip wrapping target '{0}' with AsyncTargetWrapper", target.Name); return target; } #endif wtb.WrappedTarget = target; wrapperTargetInstance.Name = target.Name; target.Name = target.Name + "_wrapped"; InternalLogger.Debug("Wrapping target '{0}' with '{1}' and renaming to '{2}", wrapperTargetInstance.Name, wrapperTargetInstance.GetType().Name, target.Name); return wrapperTargetInstance; } /// <summary> /// Parse boolean /// </summary> /// <param name="propertyName">Name of the property for logging.</param> /// <param name="value">value to parse</param> /// <param name="defaultValue">Default value to return if the parse failed</param> /// <returns>Boolean attribute value or default.</returns> private bool ParseBooleanValue(string propertyName, string value, bool defaultValue) { try { return Convert.ToBoolean(value?.Trim(), CultureInfo.InvariantCulture); } catch (Exception exception) { if (exception.MustBeRethrownImmediately()) throw; var configException = new NLogConfigurationException($"'{propertyName}' hasn't a valid boolean value '{value}'. {defaultValue} will be used", exception); if (MustThrowConfigException(configException)) throw configException; return defaultValue; } } private bool? ParseNullableBooleanValue(string propertyName, string value, bool defaultValue) { return StringHelpers.IsNullOrWhiteSpace(value) ? (bool?)null : ParseBooleanValue(propertyName, value, defaultValue); } private bool MustThrowConfigException(NLogConfigurationException configException) { if (configException.MustBeRethrown()) return true; // Global LogManager says throw if (LogFactory.ThrowConfigExceptions ?? LogFactory.ThrowExceptions) return true; // Local LogFactory says throw return false; } private static bool MatchesName(string key, string expectedKey) { return string.Equals(key?.Trim(), expectedKey, StringComparison.OrdinalIgnoreCase); } private static bool IsTargetElement(string name) { return name.Equals("target", StringComparison.OrdinalIgnoreCase) || name.Equals("wrapper", StringComparison.OrdinalIgnoreCase) || name.Equals("wrapper-target", StringComparison.OrdinalIgnoreCase) || name.Equals("compound-target", StringComparison.OrdinalIgnoreCase); } private static bool IsTargetRefElement(string name) { return name.Equals("target-ref", StringComparison.OrdinalIgnoreCase) || name.Equals("wrapper-target-ref", StringComparison.OrdinalIgnoreCase) || name.Equals("compound-target-ref", StringComparison.OrdinalIgnoreCase); } private static string GetName(Target target) { return string.IsNullOrEmpty(target.Name) ? target.GetType().Name : target.Name; } /// <summary> /// Config element that's validated and having extra context /// </summary> private class ValidatedConfigurationElement : ILoggingConfigurationElement { private static readonly IDictionary<string, string> EmptyDefaultDictionary = new SortHelpers.ReadOnlySingleBucketDictionary<string, string>(); private readonly ILoggingConfigurationElement _element; private readonly bool _throwConfigExceptions; private IList<ValidatedConfigurationElement> _validChildren; public static ValidatedConfigurationElement Create(ILoggingConfigurationElement element, LogFactory logFactory) { if (element is ValidatedConfigurationElement validConfig) return validConfig; bool throwConfigExceptions = (logFactory.ThrowConfigExceptions ?? logFactory.ThrowExceptions) || (LogManager.ThrowConfigExceptions ?? LogManager.ThrowExceptions); return new ValidatedConfigurationElement(element, throwConfigExceptions); } public ValidatedConfigurationElement(ILoggingConfigurationElement element, bool throwConfigExceptions) { _throwConfigExceptions = throwConfigExceptions; Name = element.Name.Trim(); ValueLookup = CreateValueLookup(element, throwConfigExceptions); _element = element; } public string Name { get; } public IDictionary<string, string> ValueLookup { get; } public IEnumerable<ValidatedConfigurationElement> ValidChildren { get { if (_validChildren is null) return YieldAndCacheValidChildren(); else return _validChildren; } } IEnumerable<ValidatedConfigurationElement> YieldAndCacheValidChildren() { foreach (var child in _element.Children) { _validChildren = _validChildren ?? new List<ValidatedConfigurationElement>(); var validChild = new ValidatedConfigurationElement(child, _throwConfigExceptions); _validChildren.Add(validChild); yield return validChild; } _validChildren = _validChildren ?? ArrayHelper.Empty<ValidatedConfigurationElement>(); } public IEnumerable<KeyValuePair<string, string>> Values => ValueLookup; /// <remarks> /// Explicit cast because NET35 doesn't support covariance. /// </remarks> IEnumerable<ILoggingConfigurationElement> ILoggingConfigurationElement.Children => ValidChildren.Cast<ILoggingConfigurationElement>(); public string GetRequiredValue(string attributeName, string section) { string value = GetOptionalValue(attributeName, null); if (value is null) { throw new NLogConfigurationException($"Expected {attributeName} on {Name} in {section}"); } if (StringHelpers.IsNullOrWhiteSpace(value)) { throw new NLogConfigurationException( $"Expected non-empty {attributeName} on {Name} in {section}"); } return value; } public string GetOptionalValue(string attributeName, string defaultValue) { ValueLookup.TryGetValue(attributeName, out string value); return value ?? defaultValue; } private static IDictionary<string, string> CreateValueLookup(ILoggingConfigurationElement element, bool throwConfigExceptions) { IDictionary<string, string> valueLookup = null; List<string> warnings = null; foreach (var attribute in element.Values) { var attributeKey = attribute.Key?.Trim() ?? string.Empty; valueLookup = valueLookup ?? new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); if (!string.IsNullOrEmpty(attributeKey) && !valueLookup.ContainsKey(attributeKey)) { valueLookup[attributeKey] = attribute.Value; } else { string validationError = string.IsNullOrEmpty(attributeKey) ? $"Invalid property for '{element.Name}' without name. Value={attribute.Value}" : $"Duplicate value for '{element.Name}'. PropertyName={attributeKey}. Skips Value={attribute.Value}. Existing Value={valueLookup[attributeKey]}"; InternalLogger.Debug("Skipping {0}", validationError); if (throwConfigExceptions) { warnings = warnings ?? new List<string>(); warnings.Add(validationError); } } } if (throwConfigExceptions && warnings?.Count > 0) { throw new NLogConfigurationException(StringHelpers.Join(Environment.NewLine, warnings)); } return valueLookup ?? EmptyDefaultDictionary; } public override string ToString() { return Name; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using Microsoft.Build.BackEnd; using Microsoft.Build.Framework; using Microsoft.Build.UnitTests.BackEnd; using Microsoft.Build.Utilities; using Xunit; namespace Microsoft.Build.UnitTests { /// <summary> /// Class to specifically test the TaskParameter class, particularly its serialization /// of various types of parameters. /// </summary> public class TaskParameter_Tests { /// <summary> /// Verifies that construction and serialization with a null parameter is OK. /// </summary> [Fact] public void NullParameter() { TaskParameter t = new TaskParameter(null); Assert.Null(t.WrappedParameter); Assert.Equal(TaskParameterType.Null, t.ParameterType); ((ITranslatable)t).Translate(TranslationHelpers.GetWriteTranslator()); TaskParameter t2 = TaskParameter.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); Assert.Null(t2.WrappedParameter); Assert.Equal(TaskParameterType.Null, t2.ParameterType); } /// <summary> /// Verifies that construction and serialization with a string parameter is OK. /// </summary> [Fact] public void StringParameter() { TaskParameter t = new TaskParameter("foo"); Assert.Equal("foo", t.WrappedParameter); Assert.Equal(TaskParameterType.String, t.ParameterType); ((ITranslatable)t).Translate(TranslationHelpers.GetWriteTranslator()); TaskParameter t2 = TaskParameter.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); Assert.Equal("foo", t2.WrappedParameter); Assert.Equal(TaskParameterType.String, t2.ParameterType); } /// <summary> /// Verifies that construction and serialization with a string array parameter is OK. /// </summary> [Fact] public void StringArrayParameter() { TaskParameter t = new TaskParameter(new string[] { "foo", "bar" }); Assert.Equal(TaskParameterType.StringArray, t.ParameterType); string[] wrappedParameter = t.WrappedParameter as string[]; Assert.NotNull(wrappedParameter); Assert.Equal(2, wrappedParameter.Length); Assert.Equal("foo", wrappedParameter[0]); Assert.Equal("bar", wrappedParameter[1]); ((ITranslatable)t).Translate(TranslationHelpers.GetWriteTranslator()); TaskParameter t2 = TaskParameter.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); Assert.Equal(TaskParameterType.StringArray, t2.ParameterType); string[] wrappedParameter2 = t2.WrappedParameter as string[]; Assert.NotNull(wrappedParameter2); Assert.Equal(2, wrappedParameter2.Length); Assert.Equal("foo", wrappedParameter2[0]); Assert.Equal("bar", wrappedParameter2[1]); } /// <summary> /// Verifies that construction and serialization with a value type (integer) parameter is OK. /// </summary> [Fact] public void ValueTypeParameter() { TaskParameter t = new TaskParameter(1); Assert.Equal(1, t.WrappedParameter); Assert.Equal(TaskParameterType.ValueType, t.ParameterType); ((ITranslatable)t).Translate(TranslationHelpers.GetWriteTranslator()); TaskParameter t2 = TaskParameter.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); Assert.Equal(1, t2.WrappedParameter); Assert.Equal(TaskParameterType.ValueType, t2.ParameterType); } /// <summary> /// Verifies that construction and serialization with a parameter that is an array of value types (ints) is OK. /// </summary> [Fact] public void ValueTypeArrayParameter() { TaskParameter t = new TaskParameter(new int[] { 2, 15 }); Assert.Equal(TaskParameterType.ValueTypeArray, t.ParameterType); int[] wrappedParameter = t.WrappedParameter as int[]; Assert.NotNull(wrappedParameter); Assert.Equal(2, wrappedParameter.Length); Assert.Equal(2, wrappedParameter[0]); Assert.Equal(15, wrappedParameter[1]); ((ITranslatable)t).Translate(TranslationHelpers.GetWriteTranslator()); TaskParameter t2 = TaskParameter.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); Assert.Equal(TaskParameterType.ValueTypeArray, t2.ParameterType); int[] wrappedParameter2 = t2.WrappedParameter as int[]; Assert.NotNull(wrappedParameter2); Assert.Equal(2, wrappedParameter2.Length); Assert.Equal(2, wrappedParameter2[0]); Assert.Equal(15, wrappedParameter2[1]); } /// <summary> /// Verifies that construction and serialization with an ITaskItem parameter is OK. /// </summary> [Fact] public void ITaskItemParameter() { TaskParameter t = new TaskParameter(new TaskItem("foo")); Assert.Equal(TaskParameterType.ITaskItem, t.ParameterType); ITaskItem foo = t.WrappedParameter as ITaskItem; Assert.NotNull(foo); Assert.Equal("foo", foo.ItemSpec); ((ITranslatable)t).Translate(TranslationHelpers.GetWriteTranslator()); TaskParameter t2 = TaskParameter.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); Assert.Equal(TaskParameterType.ITaskItem, t2.ParameterType); ITaskItem foo2 = t2.WrappedParameter as ITaskItem; Assert.NotNull(foo2); Assert.Equal("foo", foo2.ItemSpec); } /// <summary> /// Verifies that construction and serialization with an ITaskItem parameter that has custom metadata is OK. /// </summary> [Fact] public void ITaskItemParameterWithMetadata() { TaskItem baseItem = new TaskItem("foo"); baseItem.SetMetadata("a", "a1"); baseItem.SetMetadata("b", "b1"); TaskParameter t = new TaskParameter(baseItem); Assert.Equal(TaskParameterType.ITaskItem, t.ParameterType); ITaskItem foo = t.WrappedParameter as ITaskItem; Assert.NotNull(foo); Assert.Equal("foo", foo.ItemSpec); Assert.Equal("a1", foo.GetMetadata("a")); Assert.Equal("b1", foo.GetMetadata("b")); ((ITranslatable)t).Translate(TranslationHelpers.GetWriteTranslator()); TaskParameter t2 = TaskParameter.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); Assert.Equal(TaskParameterType.ITaskItem, t2.ParameterType); ITaskItem foo2 = t2.WrappedParameter as ITaskItem; Assert.NotNull(foo2); Assert.Equal("foo", foo2.ItemSpec); Assert.Equal("a1", foo2.GetMetadata("a")); Assert.Equal("b1", foo2.GetMetadata("b")); } /// <summary> /// Verifies that construction and serialization with a parameter that is an array of ITaskItems is OK. /// </summary> [Fact] public void ITaskItemArrayParameter() { TaskParameter t = new TaskParameter(new ITaskItem[] { new TaskItem("foo"), new TaskItem("bar") }); Assert.Equal(TaskParameterType.ITaskItemArray, t.ParameterType); ITaskItem[] wrappedParameter = t.WrappedParameter as ITaskItem[]; Assert.NotNull(wrappedParameter); Assert.Equal(2, wrappedParameter.Length); Assert.Equal("foo", wrappedParameter[0].ItemSpec); Assert.Equal("bar", wrappedParameter[1].ItemSpec); ((ITranslatable)t).Translate(TranslationHelpers.GetWriteTranslator()); TaskParameter.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); Assert.Equal(TaskParameterType.ITaskItemArray, t.ParameterType); ITaskItem[] wrappedParameter2 = t.WrappedParameter as ITaskItem[]; Assert.NotNull(wrappedParameter2); Assert.Equal(2, wrappedParameter2.Length); Assert.Equal("foo", wrappedParameter2[0].ItemSpec); Assert.Equal("bar", wrappedParameter2[1].ItemSpec); } /// <summary> /// Verifies that construction and serialization with a parameter that is an ITaskItem with an /// itemspec containing escapable characters translates the escaping correctly. /// </summary> [Fact] public void ITaskItemParameter_EscapedItemSpec() { TaskParameter t = new TaskParameter(new TaskItem("foo%3bbar")); Assert.Equal(TaskParameterType.ITaskItem, t.ParameterType); ITaskItem foo = t.WrappedParameter as ITaskItem; Assert.NotNull(foo); Assert.Equal("foo;bar", foo.ItemSpec); ((ITranslatable)t).Translate(TranslationHelpers.GetWriteTranslator()); TaskParameter t2 = TaskParameter.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); Assert.Equal(TaskParameterType.ITaskItem, t2.ParameterType); ITaskItem foo2 = t2.WrappedParameter as ITaskItem; Assert.NotNull(foo2); Assert.Equal("foo;bar", foo2.ItemSpec); } /// <summary> /// Verifies that construction and serialization with a parameter that is an ITaskItem with an /// itemspec containing doubly-escaped characters translates the escaping correctly. /// </summary> [Fact] public void ITaskItemParameter_DoubleEscapedItemSpec() { TaskParameter t = new TaskParameter(new TaskItem("foo%253bbar")); Assert.Equal(TaskParameterType.ITaskItem, t.ParameterType); ITaskItem foo = t.WrappedParameter as ITaskItem; Assert.NotNull(foo); Assert.Equal("foo%3bbar", foo.ItemSpec); ((ITranslatable)t).Translate(TranslationHelpers.GetWriteTranslator()); TaskParameter t2 = TaskParameter.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); Assert.Equal(TaskParameterType.ITaskItem, t2.ParameterType); ITaskItem foo2 = t2.WrappedParameter as ITaskItem; Assert.NotNull(foo2); Assert.Equal("foo%3bbar", foo2.ItemSpec); TaskParameter t3 = new TaskParameter(t2.WrappedParameter); ((ITranslatable)t3).Translate(TranslationHelpers.GetWriteTranslator()); TaskParameter t4 = TaskParameter.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); Assert.Equal(TaskParameterType.ITaskItem, t4.ParameterType); ITaskItem foo4 = t4.WrappedParameter as ITaskItem; Assert.NotNull(foo4); Assert.Equal("foo%3bbar", foo4.ItemSpec); } /// <summary> /// Verifies that construction and serialization with a parameter that is an ITaskItem with an /// itemspec containing the non-escaped forms of escapable characters translates the escaping correctly. /// </summary> [Fact] public void ITaskItemParameter_EscapableNotEscapedItemSpec() { TaskParameter t = new TaskParameter(new TaskItem("foo;bar")); Assert.Equal(TaskParameterType.ITaskItem, t.ParameterType); ITaskItem2 foo = t.WrappedParameter as ITaskItem2; Assert.NotNull(foo); Assert.Equal("foo;bar", foo.ItemSpec); Assert.Equal("foo;bar", foo.EvaluatedIncludeEscaped); ((ITranslatable)t).Translate(TranslationHelpers.GetWriteTranslator()); TaskParameter t2 = TaskParameter.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); Assert.Equal(TaskParameterType.ITaskItem, t2.ParameterType); ITaskItem2 foo2 = t2.WrappedParameter as ITaskItem2; Assert.NotNull(foo2); Assert.Equal("foo;bar", foo2.ItemSpec); Assert.Equal("foo;bar", foo2.EvaluatedIncludeEscaped); } /// <summary> /// Verifies that construction and serialization with a parameter that is an ITaskItem with /// metadata containing escapable characters translates the escaping correctly. /// </summary> [Fact] public void ITaskItemParameter_EscapedMetadata() { IDictionary metadata = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); metadata.Add("a", "a1%25b1"); metadata.Add("b", "c1%28d1"); TaskParameter t = new TaskParameter(new TaskItem("foo", metadata)); Assert.Equal(TaskParameterType.ITaskItem, t.ParameterType); ITaskItem foo = t.WrappedParameter as ITaskItem; Assert.NotNull(foo); Assert.Equal("foo", foo.ItemSpec); Assert.Equal("a1%b1", foo.GetMetadata("a")); Assert.Equal("c1(d1", foo.GetMetadata("b")); ((ITranslatable)t).Translate(TranslationHelpers.GetWriteTranslator()); TaskParameter t2 = TaskParameter.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); Assert.Equal(TaskParameterType.ITaskItem, t2.ParameterType); ITaskItem foo2 = t2.WrappedParameter as ITaskItem; Assert.NotNull(foo2); Assert.Equal("foo", foo2.ItemSpec); Assert.Equal("a1%b1", foo2.GetMetadata("a")); Assert.Equal("c1(d1", foo2.GetMetadata("b")); } /// <summary> /// Verifies that construction and serialization with a parameter that is an ITaskItem with /// metadata containing doubly-escaped characters translates the escaping correctly. /// </summary> [Fact] public void ITaskItemParameter_DoubleEscapedMetadata() { IDictionary metadata = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); metadata.Add("a", "a1%2525b1"); metadata.Add("b", "c1%2528d1"); TaskParameter t = new TaskParameter(new TaskItem("foo", metadata)); Assert.Equal(TaskParameterType.ITaskItem, t.ParameterType); ITaskItem foo = t.WrappedParameter as ITaskItem; Assert.NotNull(foo); Assert.Equal("foo", foo.ItemSpec); Assert.Equal("a1%25b1", foo.GetMetadata("a")); Assert.Equal("c1%28d1", foo.GetMetadata("b")); ((ITranslatable)t).Translate(TranslationHelpers.GetWriteTranslator()); TaskParameter t2 = TaskParameter.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); Assert.Equal(TaskParameterType.ITaskItem, t2.ParameterType); ITaskItem foo2 = t2.WrappedParameter as ITaskItem; Assert.NotNull(foo2); Assert.Equal("foo", foo2.ItemSpec); Assert.Equal("a1%25b1", foo2.GetMetadata("a")); Assert.Equal("c1%28d1", foo2.GetMetadata("b")); TaskParameter t3 = new TaskParameter(t2.WrappedParameter); ((ITranslatable)t3).Translate(TranslationHelpers.GetWriteTranslator()); TaskParameter t4 = TaskParameter.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); Assert.Equal(TaskParameterType.ITaskItem, t4.ParameterType); ITaskItem foo4 = t4.WrappedParameter as ITaskItem; Assert.NotNull(foo4); Assert.Equal("foo", foo4.ItemSpec); Assert.Equal("a1%25b1", foo4.GetMetadata("a")); Assert.Equal("c1%28d1", foo4.GetMetadata("b")); } /// <summary> /// Verifies that construction and serialization with a parameter that is an ITaskItem with /// metadata containing the non-escaped versions of escapable characters translates the /// escaping correctly. /// </summary> [Fact] public void ITaskItemParameter_EscapableNotEscapedMetadata() { IDictionary metadata = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); metadata.Add("a", "a1(b1"); metadata.Add("b", "c1)d1"); TaskParameter t = new TaskParameter(new TaskItem("foo", metadata)); Assert.Equal(TaskParameterType.ITaskItem, t.ParameterType); ITaskItem2 foo = t.WrappedParameter as ITaskItem2; Assert.NotNull(foo); Assert.Equal("foo", foo.ItemSpec); Assert.Equal("a1(b1", foo.GetMetadata("a")); Assert.Equal("c1)d1", foo.GetMetadata("b")); Assert.Equal("a1(b1", foo.GetMetadataValueEscaped("a")); Assert.Equal("c1)d1", foo.GetMetadataValueEscaped("b")); ((ITranslatable)t).Translate(TranslationHelpers.GetWriteTranslator()); TaskParameter t2 = TaskParameter.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); Assert.Equal(TaskParameterType.ITaskItem, t2.ParameterType); ITaskItem2 foo2 = t2.WrappedParameter as ITaskItem2; Assert.NotNull(foo2); Assert.Equal("foo", foo2.ItemSpec); Assert.Equal("a1(b1", foo2.GetMetadata("a")); Assert.Equal("c1)d1", foo2.GetMetadata("b")); Assert.Equal("a1(b1", foo2.GetMetadataValueEscaped("a")); Assert.Equal("c1)d1", foo2.GetMetadataValueEscaped("b")); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; namespace MS.Internal.Xml.XPath { internal class CompiledXpathExpr : XPathExpression { private Query _query; private string _expr; private bool _needContext; internal CompiledXpathExpr(Query query, string expression, bool needContext) { _query = query; _expr = expression; _needContext = needContext; } internal Query QueryTree { get { if (_needContext) { throw XPathException.Create(SR.Xp_NoContext); } return _query; } } public override string Expression { get { return _expr; } } public virtual void CheckErrors() { Debug.Assert(_query != null, "In case of error in XPath we create ErrorXPathExpression"); } public override void AddSort(object expr, IComparer comparer) { // sort makes sense only when we are dealing with a query that // returns a nodeset. Query evalExpr; if (expr is string) { evalExpr = new QueryBuilder().Build((string)expr, out _needContext); // this will throw if expr is invalid } else if (expr is CompiledXpathExpr) { evalExpr = ((CompiledXpathExpr)expr).QueryTree; } else { throw XPathException.Create(SR.Xp_BadQueryObject); } SortQuery sortQuery = _query as SortQuery; if (sortQuery == null) { _query = sortQuery = new SortQuery(_query); } sortQuery.AddSort(evalExpr, comparer); } public override void AddSort(object expr, XmlSortOrder order, XmlCaseOrder caseOrder, string lang, XmlDataType dataType) { AddSort(expr, new XPathComparerHelper(order, caseOrder, lang, dataType)); } public override XPathExpression Clone() { return new CompiledXpathExpr(Query.Clone(_query), _expr, _needContext); } public override void SetContext(XmlNamespaceManager nsManager) { SetContext((IXmlNamespaceResolver)nsManager); } public override void SetContext(IXmlNamespaceResolver nsResolver) { XsltContext xsltContext = nsResolver as XsltContext; if (xsltContext == null) { if (nsResolver == null) { nsResolver = new XmlNamespaceManager(new NameTable()); } xsltContext = new UndefinedXsltContext(nsResolver); } _query.SetXsltContext(xsltContext); _needContext = false; } public override XPathResultType ReturnType { get { return _query.StaticType; } } private class UndefinedXsltContext : XsltContext { private IXmlNamespaceResolver _nsResolver; public UndefinedXsltContext(IXmlNamespaceResolver nsResolver) { _nsResolver = nsResolver; } //----- Namespace support ----- public override string DefaultNamespace { get { return string.Empty; } } public override string LookupNamespace(string prefix) { Debug.Assert(prefix != null); if (prefix.Length == 0) { return string.Empty; } string ns = _nsResolver.LookupNamespace(prefix); if (ns == null) { throw XPathException.Create(SR.XmlUndefinedAlias, prefix); } return ns; } //----- XsltContext support ----- public override IXsltContextVariable ResolveVariable(string prefix, string name) { throw XPathException.Create(SR.Xp_UndefinedXsltContext); } public override IXsltContextFunction ResolveFunction(string prefix, string name, XPathResultType[] ArgTypes) { throw XPathException.Create(SR.Xp_UndefinedXsltContext); } public override bool Whitespace { get { return false; } } public override bool PreserveWhitespace(XPathNavigator node) { return false; } public override int CompareDocument(string baseUri, string nextbaseUri) { return string.CompareOrdinal(baseUri, nextbaseUri); } } } internal sealed class XPathComparerHelper : IComparer { private XmlSortOrder _order; private XmlCaseOrder _caseOrder; private CultureInfo _cinfo; private XmlDataType _dataType; public XPathComparerHelper(XmlSortOrder order, XmlCaseOrder caseOrder, string lang, XmlDataType dataType) { if (lang == null) { _cinfo = CultureInfo.CurrentCulture; } else { try { _cinfo = new CultureInfo(lang); } catch (System.ArgumentException) { throw; // Throwing an XsltException would be a breaking change } } if (order == XmlSortOrder.Descending) { if (caseOrder == XmlCaseOrder.LowerFirst) { caseOrder = XmlCaseOrder.UpperFirst; } else if (caseOrder == XmlCaseOrder.UpperFirst) { caseOrder = XmlCaseOrder.LowerFirst; } } _order = order; _caseOrder = caseOrder; _dataType = dataType; } public int Compare(object x, object y) { switch (_dataType) { case XmlDataType.Text: string s1 = Convert.ToString(x, _cinfo); string s2 = Convert.ToString(y, _cinfo); int result = _cinfo.CompareInfo.Compare(s1, s2, _caseOrder != XmlCaseOrder.None ? CompareOptions.IgnoreCase : CompareOptions.None); if (result != 0 || _caseOrder == XmlCaseOrder.None) return (_order == XmlSortOrder.Ascending) ? result : -result; // If we came this far, it means that strings s1 and s2 are // equal to each other when case is ignored. Now it's time to check // and see if they differ in case only and take into account the user // requested case order for sorting purposes. result = _cinfo.CompareInfo.Compare(s1, s2); return (_caseOrder == XmlCaseOrder.LowerFirst) ? result : -result; case XmlDataType.Number: double r1 = XmlConvertEx.ToXPathDouble(x); double r2 = XmlConvertEx.ToXPathDouble(y); result = r1.CompareTo(r2); return (_order == XmlSortOrder.Ascending) ? result : -result; default: // dataType doesn't support any other value throw new InvalidOperationException(SR.Xml_InvalidOperation); } } // Compare () } // class XPathComparerHelper }
/* Copyright 2006 - 2010 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Data; using System.Drawing; using System.Collections; using System.Windows.Forms; using System.ComponentModel; using OpenSource.UPnP; namespace UPnPLight { /// <summary> /// Summary description for Form1. /// </summary> public class MainForm : System.Windows.Forms.Form { private System.Windows.Forms.ContextMenu contextMenu; private System.Windows.Forms.MenuItem menuItem1; private System.Windows.Forms.MenuItem menuItem2; private System.ComponentModel.IContainer components; private UPnPDevice upnpLightDevice = null; private UPnPService upnpLightService = null; private UPnPService upnpDimmerService = null; private bool lightState = false; private System.Windows.Forms.PictureBox pictureBox; private System.Windows.Forms.MenuItem menuItem4; private System.Windows.Forms.MenuItem RaiseDimMenuItem; private System.Windows.Forms.MenuItem LowerDimMenuItem6; private System.Windows.Forms.MenuItem TrackerMenuItem; private byte dimmedLevel = 100; private System.Windows.Forms.ImageList iconImageList; private int CacheTime = 900; private ImageList lightImageList; private int PortNum = 0; public MainForm(string[] args) { // // Required for Windows Form Designer support // InitializeComponent(); foreach (string parm in args) { if (parm.ToUpper().StartsWith("/CACHE:")) { DText p = new DText(); p.ATTRMARK = ":"; p[0] = parm; try { CacheTime = int.Parse(p[2]); } catch (Exception) { } } else if (parm.ToUpper() == "/DEBUG") { OpenSource.Utilities.EventLogger.Enabled = true; OpenSource.Utilities.EventLogger.ShowAll = true; OpenSource.Utilities.InstanceTracker.Display(); } else if (parm.ToUpper().StartsWith("/PORT:")) { DText p = new DText(); p.ATTRMARK = ":"; p[0] = parm; try { PortNum = int.Parse(p[2]); } catch (Exception) { } } } upnpLightDevice = UPnPDevice.CreateRootDevice(CacheTime, 1, "web\\"); upnpLightDevice.Icon = iconImageList.Images[0]; upnpLightDevice.HasPresentation = true; upnpLightDevice.PresentationURL = "/"; upnpLightDevice.FriendlyName = this.Text + " (" + System.Windows.Forms.SystemInformation.ComputerName + ")"; upnpLightDevice.Manufacturer = "OpenSource"; upnpLightDevice.ManufacturerURL = "http://opentools.homeip.net"; upnpLightDevice.ModelName = "Network Light Bulb"; upnpLightDevice.ModelDescription = "Software Emulated Light Bulb"; upnpLightDevice.ModelURL = new Uri("http://opentools.homeip.net"); upnpLightDevice.ModelNumber = "XPC-L1"; upnpLightDevice.StandardDeviceType = "DimmableLight"; upnpLightDevice.UniqueDeviceName = System.Guid.NewGuid().ToString(); // Switch Power upnpLightService = new UPnPService(1, "SwitchPower.0001", "SwitchPower", true, this); upnpLightService.AddMethod("SetTarget"); upnpLightService.AddMethod("GetTarget"); upnpLightService.AddMethod("GetStatus"); UPnPStateVariable upnpStatusVar = new UPnPStateVariable("Status", typeof(bool), true); upnpStatusVar.AddAssociation("GetStatus", "ResultStatus"); upnpStatusVar.Value = false; upnpLightService.AddStateVariable(upnpStatusVar); UPnPStateVariable upnpTargetVar = new UPnPStateVariable("Target", typeof(bool), false); upnpTargetVar.AddAssociation("SetTarget", "newTargetValue"); upnpTargetVar.AddAssociation("GetTarget", "newTargetValue"); upnpTargetVar.Value = false; upnpLightService.AddStateVariable(upnpTargetVar); // Dimmable device upnpDimmerService = new UPnPService(1, "Dimming.0001", "Dimming", true, this); upnpDimmerService.AddMethod("SetLoadLevelTarget"); upnpDimmerService.AddMethod("GetLoadLevelTarget"); upnpDimmerService.AddMethod("GetLoadLevelStatus"); upnpDimmerService.AddMethod("GetMinLevel"); UPnPStateVariable upnpLevelTargetVar = new UPnPStateVariable("LoadLevelTarget", typeof(byte), false); upnpLevelTargetVar.AddAssociation("SetLoadLevelTarget", "NewLoadLevelTarget"); upnpLevelTargetVar.AddAssociation("GetLoadLevelTarget", "NewLoadLevelTarget"); upnpLevelTargetVar.Value = (byte)100; upnpLevelTargetVar.SetRange((byte)0, (byte)100, null); upnpDimmerService.AddStateVariable(upnpLevelTargetVar); UPnPStateVariable upnpLevelStatusVar = new UPnPStateVariable("LoadLevelStatus", typeof(byte), true); upnpLevelStatusVar.AddAssociation("GetLoadLevelStatus", "RetLoadLevelStatus"); upnpLevelStatusVar.Value = (byte)100; upnpLevelStatusVar.SetRange((byte)0, (byte)100, null); upnpDimmerService.AddStateVariable(upnpLevelStatusVar); UPnPStateVariable upnpMinLevelVar = new UPnPStateVariable("MinLevel", typeof(byte), false); upnpMinLevelVar.AddAssociation("GetMinLevel", "MinLevel"); upnpMinLevelVar.Value = (byte)0; upnpDimmerService.AddStateVariable(upnpMinLevelVar); // Add Services upnpLightDevice.AddService(upnpLightService); upnpLightDevice.AddService(upnpDimmerService); } public void SetTarget(bool newTargetValue) { if (lightState == newTargetValue) return; upnpLightService.SetStateVariable("Target", newTargetValue); upnpLightService.SetStateVariable("Status", newTargetValue); lightState = newTargetValue; menuItem1.Checked = newTargetValue; if (lightState == false) SetLightLevel(0); if (lightState == true) SetLightLevel(dimmedLevel); } public void GetTarget(out bool newTargetValue) { newTargetValue = lightState; } public void GetStatus(out bool ResultStatus) { ResultStatus = lightState; } public void SetLoadLevelTarget(byte NewLoadLevelTarget) { dimmedLevel = NewLoadLevelTarget; upnpDimmerService.SetStateVariable("LoadLevelStatus", NewLoadLevelTarget); if (lightState == true) SetLightLevel(dimmedLevel); } public void GetLoadLevelTarget(out byte NewLoadLevelTarget) { NewLoadLevelTarget = (byte)dimmedLevel; } public void GetLoadLevelStatus(out byte RetLoadLevelStatus) { RetLoadLevelStatus = (byte)dimmedLevel; } public void GetMinLevel(out byte MinLevel) { MinLevel = 0; } /// <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.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); this.pictureBox = new System.Windows.Forms.PictureBox(); this.contextMenu = new System.Windows.Forms.ContextMenu(); this.menuItem1 = new System.Windows.Forms.MenuItem(); this.menuItem2 = new System.Windows.Forms.MenuItem(); this.RaiseDimMenuItem = new System.Windows.Forms.MenuItem(); this.LowerDimMenuItem6 = new System.Windows.Forms.MenuItem(); this.menuItem4 = new System.Windows.Forms.MenuItem(); this.TrackerMenuItem = new System.Windows.Forms.MenuItem(); this.iconImageList = new System.Windows.Forms.ImageList(this.components); this.lightImageList = new System.Windows.Forms.ImageList(this.components); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).BeginInit(); this.SuspendLayout(); // // pictureBox // this.pictureBox.ContextMenu = this.contextMenu; resources.ApplyResources(this.pictureBox, "pictureBox"); this.pictureBox.Name = "pictureBox"; this.pictureBox.TabStop = false; this.pictureBox.DoubleClick += new System.EventHandler(this.menuItem1_Click); // // contextMenu // this.contextMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { this.menuItem1, this.menuItem2, this.RaiseDimMenuItem, this.LowerDimMenuItem6, this.menuItem4, this.TrackerMenuItem}); // // menuItem1 // this.menuItem1.DefaultItem = true; this.menuItem1.Index = 0; resources.ApplyResources(this.menuItem1, "menuItem1"); this.menuItem1.Click += new System.EventHandler(this.menuItem1_Click); // // menuItem2 // this.menuItem2.Index = 1; resources.ApplyResources(this.menuItem2, "menuItem2"); // // RaiseDimMenuItem // this.RaiseDimMenuItem.Index = 2; resources.ApplyResources(this.RaiseDimMenuItem, "RaiseDimMenuItem"); this.RaiseDimMenuItem.Click += new System.EventHandler(this.RaiseDimMenuItem_Click); // // LowerDimMenuItem6 // this.LowerDimMenuItem6.Index = 3; resources.ApplyResources(this.LowerDimMenuItem6, "LowerDimMenuItem6"); this.LowerDimMenuItem6.Click += new System.EventHandler(this.LowerDimMenuItem6_Click); // // menuItem4 // this.menuItem4.Index = 4; resources.ApplyResources(this.menuItem4, "menuItem4"); // // TrackerMenuItem // this.TrackerMenuItem.Index = 5; resources.ApplyResources(this.TrackerMenuItem, "TrackerMenuItem"); this.TrackerMenuItem.Click += new System.EventHandler(this.TrackerMenuItem_Click); // // iconImageList // this.iconImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("iconImageList.ImageStream"))); this.iconImageList.TransparentColor = System.Drawing.Color.Transparent; this.iconImageList.Images.SetKeyName(0, ""); // // lightImageList // this.lightImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("lightImageList.ImageStream"))); this.lightImageList.TransparentColor = System.Drawing.Color.Transparent; this.lightImageList.Images.SetKeyName(0, "lamp-0.jpg"); this.lightImageList.Images.SetKeyName(1, "lamp-10.jpg"); this.lightImageList.Images.SetKeyName(2, "lamp-20.jpg"); this.lightImageList.Images.SetKeyName(3, "lamp-30.jpg"); this.lightImageList.Images.SetKeyName(4, "lamp-40.jpg"); this.lightImageList.Images.SetKeyName(5, "lamp-50.jpg"); this.lightImageList.Images.SetKeyName(6, "lamp-60.jpg"); this.lightImageList.Images.SetKeyName(7, "lamp-70.jpg"); this.lightImageList.Images.SetKeyName(8, "lamp-80.jpg"); this.lightImageList.Images.SetKeyName(9, "lamp-90.jpg"); this.lightImageList.Images.SetKeyName(10, "lamp-100.jpg"); // // MainForm // resources.ApplyResources(this, "$this"); this.BackColor = System.Drawing.Color.White; this.Controls.Add(this.pictureBox); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "MainForm"; this.Load += new System.EventHandler(this.OnLoad); this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing); this.HelpRequested += new System.Windows.Forms.HelpEventHandler(this.MainForm_HelpRequested); ((System.ComponentModel.ISupportInitialize)(this.pictureBox)).EndInit(); this.ResumeLayout(false); } #endregion /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { for (int i = 0; i < (args.Length); i++) { if (args[i].ToLower() == "-en") System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en"); if (args[i].ToLower() == "-fr") System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("fr"); } Application.Run(new MainForm(args)); } private void menuItem1_Click(object sender, System.EventArgs e) { lightState = !lightState; //upnpLightService.SetStateVariable("TestVariable",null); upnpLightService.SetStateVariable("Target", lightState); upnpLightService.SetStateVariable("Status", lightState); menuItem1.Checked = lightState; if (lightState == false) SetLightLevel(0); if (lightState == true) SetLightLevel(dimmedLevel); } private void SetLightLevel(int level) { if (level < 0) level = 0; if (level > 100) level = 100; pictureBox.Image = lightImageList.Images[level / 10]; } private void RaiseDimMenuItem_Click(object sender, System.EventArgs e) { dimmedLevel += 20; if (dimmedLevel > 100) dimmedLevel = 100; upnpDimmerService.SetStateVariable("LoadLevelStatus", dimmedLevel); if (lightState == true) SetLightLevel(dimmedLevel); } private void LowerDimMenuItem6_Click(object sender, System.EventArgs e) { if (dimmedLevel < 20) dimmedLevel = 0; else dimmedLevel -= 20; upnpDimmerService.SetStateVariable("LoadLevelStatus", dimmedLevel); if (lightState == true) SetLightLevel(dimmedLevel); } private void TrackerMenuItem_Click(object sender, System.EventArgs e) { OpenSource.Utilities.InstanceTracker.Display(); } private void helpMenuItem_Click(object sender, System.EventArgs e) { Help.ShowHelp(this, "ToolsHelp.chm", HelpNavigator.KeywordIndex, "Network Light"); } private void MainForm_HelpRequested(object sender, System.Windows.Forms.HelpEventArgs hlpevent) { Help.ShowHelp(this, "ToolsHelp.chm", HelpNavigator.KeywordIndex, "Network Light"); } private void OnLoad(object sender, System.EventArgs e) { upnpLightDevice.StartDevice(PortNum); } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { upnpLightDevice.StopDevice(); upnpLightDevice = null; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Collections.Generic; using System.Net; using Microsoft.Azure.Management.Network; using Microsoft.Azure.Management.Network.Models; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.Azure.Test; using Networks.Tests.Helpers; using ResourceGroups.Tests; using Xunit; namespace Networks.Tests { using System.Linq; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; public class VirtualNetworkTests { [Fact(Skip="Disable tests")] public void VirtualNetworkApiTest() { var handler1 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; var handler2 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { var resourcesClient = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(context, handler1, true); var networkManagementClient = NetworkManagementTestUtilities.GetNetworkManagementClientWithHandler(context, handler2); var location = NetworkManagementTestUtilities.GetResourceLocation(resourcesClient, "Microsoft.Network/virtualNetworks"); string resourceGroupName = TestUtilities.GenerateName("csmrg"); resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = location }); string vnetName = TestUtilities.GenerateName(); string subnet1Name = TestUtilities.GenerateName(); string subnet2Name = TestUtilities.GenerateName(); var vnet = new VirtualNetwork() { Location = location, AddressSpace = new AddressSpace() { AddressPrefixes = new List<string>() { "10.0.0.0/16", } }, DhcpOptions = new DhcpOptions() { DnsServers = new List<string>() { "10.1.1.1", "10.1.2.4" } }, Subnets = new List<Subnet>() { new Subnet() { Name = subnet1Name, AddressPrefix = "10.0.1.0/24", }, new Subnet() { Name = subnet2Name, AddressPrefix = "10.0.2.0/24", } } }; // Put Vnet var putVnetResponse = networkManagementClient.VirtualNetworks.CreateOrUpdate(resourceGroupName, vnetName, vnet); Assert.Equal("Succeeded", putVnetResponse.ProvisioningState); // Get Vnet var getVnetResponse = networkManagementClient.VirtualNetworks.Get(resourceGroupName, vnetName); Assert.Equal(vnetName, getVnetResponse.Name); Assert.NotNull(getVnetResponse.ResourceGuid); Assert.Equal("Succeeded", getVnetResponse.ProvisioningState); Assert.Equal("10.1.1.1", getVnetResponse.DhcpOptions.DnsServers[0]); Assert.Equal("10.1.2.4", getVnetResponse.DhcpOptions.DnsServers[1]); Assert.Equal("10.0.0.0/16", getVnetResponse.AddressSpace.AddressPrefixes[0]); Assert.Equal(subnet1Name, getVnetResponse.Subnets[0].Name); Assert.Equal(subnet2Name, getVnetResponse.Subnets[1].Name); // Get all Vnets var getAllVnets = networkManagementClient.VirtualNetworks.List(resourceGroupName); Assert.Equal(vnetName, getAllVnets.ElementAt(0).Name); Assert.Equal("Succeeded", getAllVnets.ElementAt(0).ProvisioningState); Assert.Equal("10.0.0.0/16", getAllVnets.ElementAt(0).AddressSpace.AddressPrefixes[0]); Assert.Equal(subnet1Name, getAllVnets.ElementAt(0).Subnets[0].Name); Assert.Equal(subnet2Name, getAllVnets.ElementAt(0).Subnets[1].Name); // Get all Vnets in a subscription var getAllVnetInSubscription = networkManagementClient.VirtualNetworks.ListAll(); Assert.NotEmpty(getAllVnetInSubscription); // Delete Vnet networkManagementClient.VirtualNetworks.Delete(resourceGroupName, vnetName); // Get all Vnets getAllVnets = networkManagementClient.VirtualNetworks.List(resourceGroupName); Assert.Empty(getAllVnets); } } [Fact(Skip="Disable tests")] public void VirtualNetworkCheckIpAddressAvailabilityTest() { var handler1 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; var handler2 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { var resourcesClient = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(context, handler1, true); var networkManagementClient = NetworkManagementTestUtilities.GetNetworkManagementClientWithHandler(context, handler2); var location = NetworkManagementTestUtilities.GetResourceLocation(resourcesClient, "Microsoft.Network/virtualNetworks"); string resourceGroupName = TestUtilities.GenerateName("csmrg"); resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = location }); string vnetName = TestUtilities.GenerateName(); string subnetName = TestUtilities.GenerateName(); var vnet = new VirtualNetwork() { Location = location, AddressSpace = new AddressSpace() { AddressPrefixes = new List<string>() { "10.0.0.0/16", } }, DhcpOptions = new DhcpOptions() { DnsServers = new List<string>() { "10.1.1.1", "10.1.2.4" } }, Subnets = new List<Subnet>() { new Subnet() { Name = subnetName, AddressPrefix = "10.0.1.0/24", }, } }; // Put Vnet var putVnetResponse = networkManagementClient.VirtualNetworks.CreateOrUpdate(resourceGroupName, vnetName, vnet); Assert.Equal("Succeeded", putVnetResponse.ProvisioningState); var getSubnetResponse = networkManagementClient.Subnets.Get(resourceGroupName, vnetName, subnetName); // Create Nic string nicName = TestUtilities.GenerateName(); string ipConfigName = TestUtilities.GenerateName(); var nicParameters = new NetworkInterface() { Location = location, Tags = new Dictionary<string, string>() { {"key","value"} }, IpConfigurations = new List<NetworkInterfaceIPConfiguration>() { new NetworkInterfaceIPConfiguration() { Name = ipConfigName, PrivateIPAllocationMethod = IPAllocationMethod.Static, PrivateIPAddress = "10.0.1.9", Subnet = new Subnet() { Id = getSubnetResponse.Id } } } }; var putNicResponse = networkManagementClient.NetworkInterfaces.CreateOrUpdate(resourceGroupName, nicName, nicParameters); // Check Ip Address availability API var responseAvailable = networkManagementClient.VirtualNetworks.CheckIPAddressAvailability(resourceGroupName, vnetName, "10.0.1.10"); Assert.True(responseAvailable.Available); Assert.Null(responseAvailable.AvailableIPAddresses); var responseTaken = networkManagementClient.VirtualNetworks.CheckIPAddressAvailability(resourceGroupName, vnetName, "10.0.1.9"); Assert.False(responseTaken.Available); Assert.Equal(5, responseTaken.AvailableIPAddresses.Count); networkManagementClient.NetworkInterfaces.Delete(resourceGroupName, nicName); networkManagementClient.VirtualNetworks.Delete(resourceGroupName, vnetName); } } [Fact(Skip="Disable tests")] public void VirtualNetworkPeeringTest() { var handler1 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; var handler2 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { var resourcesClient = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(context, handler1, true); var networkManagementClient = NetworkManagementTestUtilities.GetNetworkManagementClientWithHandler(context, handler2); var location = NetworkManagementTestUtilities.GetResourceLocation(resourcesClient, "Microsoft.Network/virtualNetworks"); string resourceGroupName = TestUtilities.GenerateName("csmrg"); resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = location }); string vnet1Name = TestUtilities.GenerateName(); string vnet2Name = TestUtilities.GenerateName(); string subnet1Name = TestUtilities.GenerateName(); string subnet2Name = TestUtilities.GenerateName(); var vnet = new VirtualNetwork() { Location = location, AddressSpace = new AddressSpace() { AddressPrefixes = new List<string>() { "10.0.0.0/16", } }, DhcpOptions = new DhcpOptions() { DnsServers = new List<string>() { "10.1.1.1", "10.1.2.4" } }, Subnets = new List<Subnet>() { new Subnet() { Name = subnet1Name, AddressPrefix = "10.0.1.0/24", }, new Subnet() { Name = subnet2Name, AddressPrefix = "10.0.2.0/24", } } }; // Put Vnet var putVnetResponse = networkManagementClient.VirtualNetworks.CreateOrUpdate(resourceGroupName, vnet1Name, vnet); Assert.Equal("Succeeded", putVnetResponse.ProvisioningState); // Get Vnet var getVnetResponse = networkManagementClient.VirtualNetworks.Get(resourceGroupName, vnet1Name); Assert.Equal(vnet1Name, getVnetResponse.Name); Assert.NotNull(getVnetResponse.ResourceGuid); Assert.Equal("Succeeded", getVnetResponse.ProvisioningState); // Create vnet2 var vnet2 = new VirtualNetwork() { Location = location, AddressSpace = new AddressSpace() { AddressPrefixes = new List<string>() { "10.1.0.0/16", } }, Subnets = new List<Subnet>() { new Subnet() { Name = subnet1Name, AddressPrefix = "10.1.1.0/24", } } }; // Put Vnet2 var putVnet2 = networkManagementClient.VirtualNetworks.CreateOrUpdate(resourceGroupName, vnet2Name, vnet2); Assert.Equal("Succeeded", putVnet2.ProvisioningState); // Create peering object var peering = new VirtualNetworkPeering() { AllowForwardedTraffic = true, RemoteVirtualNetwork = new Microsoft.Azure.Management.Network.Models.SubResource { Id = putVnet2.Id } }; // Create Peering networkManagementClient.VirtualNetworkPeerings.CreateOrUpdate(resourceGroupName, vnet1Name, "peer1", peering); // Get Peering var getPeer = networkManagementClient.VirtualNetworkPeerings.Get(resourceGroupName, vnet1Name, "peer1"); Assert.Equal("peer1", getPeer.Name); Assert.True(getPeer.AllowForwardedTraffic); Assert.True(getPeer.AllowVirtualNetworkAccess); Assert.False(getPeer.AllowGatewayTransit); Assert.NotNull(getPeer.RemoteVirtualNetwork); Assert.Equal(putVnet2.Id, getPeer.RemoteVirtualNetwork.Id); // List Peering var listPeer = networkManagementClient.VirtualNetworkPeerings.List(resourceGroupName, vnet1Name).ToList(); Assert.Single(listPeer); Assert.Equal("peer1", listPeer[0].Name); Assert.True(listPeer[0].AllowForwardedTraffic); Assert.True(listPeer[0].AllowVirtualNetworkAccess); Assert.False(listPeer[0].AllowGatewayTransit); Assert.NotNull(listPeer[0].RemoteVirtualNetwork); Assert.Equal(putVnet2.Id, listPeer[0].RemoteVirtualNetwork.Id); // Get peering from GET vnet var peeringVnet = networkManagementClient.VirtualNetworks.Get(resourceGroupName, vnet1Name); Assert.Equal(vnet1Name, peeringVnet.Name); Assert.Single(peeringVnet.VirtualNetworkPeerings); Assert.Equal("peer1", peeringVnet.VirtualNetworkPeerings[0].Name); Assert.True(peeringVnet.VirtualNetworkPeerings[0].AllowForwardedTraffic); Assert.True(peeringVnet.VirtualNetworkPeerings[0].AllowVirtualNetworkAccess); Assert.False(peeringVnet.VirtualNetworkPeerings[0].AllowGatewayTransit); Assert.NotNull(peeringVnet.VirtualNetworkPeerings[0].RemoteVirtualNetwork); Assert.Equal(putVnet2.Id, peeringVnet.VirtualNetworkPeerings[0].RemoteVirtualNetwork.Id); // Delete Peering networkManagementClient.VirtualNetworkPeerings.Delete(resourceGroupName, vnet1Name, "peer1"); listPeer = networkManagementClient.VirtualNetworkPeerings.List(resourceGroupName, vnet1Name).ToList(); Assert.Empty(listPeer); peeringVnet = networkManagementClient.VirtualNetworks.Get(resourceGroupName, vnet1Name); Assert.Equal(vnet1Name, peeringVnet.Name); Assert.Empty(peeringVnet.VirtualNetworkPeerings); // Delete Vnets networkManagementClient.VirtualNetworks.Delete(resourceGroupName, vnet1Name); networkManagementClient.VirtualNetworks.Delete(resourceGroupName, vnet2Name); } } [Fact(Skip="Disable tests")] public void VirtualNetworkUsageTest() { var handler1 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; var handler2 = new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }; using (MockContext context = MockContext.Start(this.GetType())) { var resourcesClient = ResourcesManagementTestUtilities.GetResourceManagementClientWithHandler(context, handler1, true); var networkManagementClient = NetworkManagementTestUtilities.GetNetworkManagementClientWithHandler(context, handler2); var location = NetworkManagementTestUtilities.GetResourceLocation(resourcesClient, "Microsoft.Network/virtualNetworks"); string resourceGroupName = TestUtilities.GenerateName("csmrg"); resourcesClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = location }); string vnetName = TestUtilities.GenerateName(); string subnetName = TestUtilities.GenerateName(); var vnet = new VirtualNetwork() { Location = location, AddressSpace = new AddressSpace() { AddressPrefixes = new List<string>() { "10.0.0.0/16", } }, DhcpOptions = new DhcpOptions() { DnsServers = new List<string>() { "10.1.1.1", "10.1.2.4" } }, Subnets = new List<Subnet>() { new Subnet() { Name = subnetName, AddressPrefix = "10.0.1.0/24", }, } }; // Put Vnet var putVnetResponse = networkManagementClient.VirtualNetworks.CreateOrUpdate(resourceGroupName, vnetName, vnet); Assert.Equal("Succeeded", putVnetResponse.ProvisioningState); var getSubnetResponse = networkManagementClient.Subnets.Get(resourceGroupName, vnetName, subnetName); // Get Vnet usage var listUsageResponse = networkManagementClient.VirtualNetworks.ListUsage(resourceGroupName, vnetName).ToList(); Assert.Equal(0.0, listUsageResponse[0].CurrentValue); // Create Nic string nicName = TestUtilities.GenerateName(); string ipConfigName = TestUtilities.GenerateName(); var nicParameters = new NetworkInterface() { Location = location, Tags = new Dictionary<string, string>() { {"key","value"} }, IpConfigurations = new List<NetworkInterfaceIPConfiguration>() { new NetworkInterfaceIPConfiguration() { Name = ipConfigName, PrivateIPAllocationMethod = IPAllocationMethod.Static, PrivateIPAddress = "10.0.1.9", Subnet = new Subnet() { Id = getSubnetResponse.Id } } } }; var putNicResponse = networkManagementClient.NetworkInterfaces.CreateOrUpdate(resourceGroupName, nicName, nicParameters); // Get Vnet usage again listUsageResponse = networkManagementClient.VirtualNetworks.ListUsage(resourceGroupName, vnetName).ToList(); Assert.Equal(1.0, listUsageResponse[0].CurrentValue); // Delete Vnet and Nic networkManagementClient.NetworkInterfaces.Delete(resourceGroupName, nicName); networkManagementClient.VirtualNetworks.Delete(resourceGroupName, vnetName); } } } }
using FluentNHibernate.MappingModel; using FluentNHibernate.MappingModel.Collections; using FluentNHibernate.MappingModel.Output; using FluentNHibernate.Testing.Testing; using NUnit.Framework; namespace FluentNHibernate.Testing.MappingModel.Output { [TestFixture] public class XmlSetWriterTester { private IXmlWriter<CollectionMapping> writer; [SetUp] public void GetWriterFromContainer() { var container = new XmlWriterContainer(); writer = container.Resolve<IXmlWriter<CollectionMapping>>(); } [Test] public void ShouldWriteAccessAttribute() { var testHelper = Helper(); testHelper.Check(x => x.Access, "acc").MapsToAttribute("access"); testHelper.VerifyAll(writer); } [Test] public void ShouldWriteBatchSizeAttribute() { var testHelper = Helper(); testHelper.Check(x => x.BatchSize, 10).MapsToAttribute("batch-size"); testHelper.VerifyAll(writer); } [Test] public void ShouldWriteCascadeAttribute() { var testHelper = Helper(); testHelper.Check(x => x.Cascade, "all").MapsToAttribute("cascade"); testHelper.VerifyAll(writer); } [Test] public void ShouldWriteCheckAttribute() { var testHelper = Helper(); testHelper.Check(x => x.Check, "ck").MapsToAttribute("check"); testHelper.VerifyAll(writer); } [Test] public void ShouldWriteCollectionTypeAttribute() { var testHelper = Helper(); testHelper.Check(x => x.CollectionType, new TypeReference("type")).MapsToAttribute("collection-type"); testHelper.VerifyAll(writer); } [Test] public void ShouldNotWriteCollectionTypeWhenEmpty() { var mapping = CollectionMapping.Set(); mapping.Set(x => x.CollectionType, Layer.Defaults, TypeReference.Empty); writer.VerifyXml(mapping) .DoesntHaveAttribute("collection-type"); } [Test] public void ShouldWriteFetchAttribute() { var testHelper = Helper(); testHelper.Check(x => x.Fetch, "fetch").MapsToAttribute("fetch"); testHelper.VerifyAll(writer); } [Test] public void ShouldWriteGenericAttribute() { var testHelper = Helper(); testHelper.Check(x => x.Generic, true).MapsToAttribute("generic"); testHelper.VerifyAll(writer); } [Test] public void ShouldWriteInverseAttribute() { var testHelper = Helper(); testHelper.Check(x => x.Inverse, true).MapsToAttribute("inverse"); testHelper.VerifyAll(writer); } [Test] public void ShouldWriteLazyAttribute() { var testHelper = Helper(); testHelper.Check(x => x.Lazy, Lazy.True).MapsToAttribute("lazy"); testHelper.VerifyAll(writer); } [Test] public void ShouldWriteNameAttribute() { var testHelper = Helper(); testHelper.Check(x => x.Name, "name").MapsToAttribute("name"); testHelper.VerifyAll(writer); } [Test] public void ShouldWriteOptimisticLockAttribute() { var testHelper = Helper(); testHelper.Check(x => x.OptimisticLock, true).MapsToAttribute("optimistic-lock"); testHelper.VerifyAll(writer); } [Test] public void ShouldWriteOrderByAttribute() { var testHelper = Helper(); testHelper.Check(x => x.OrderBy, "ord").MapsToAttribute("order-by"); testHelper.VerifyAll(writer); } [Test] public void ShouldWritePersisterAttribute() { var testHelper = Helper(); testHelper.Check(x => x.Persister, new TypeReference(typeof(string))).MapsToAttribute("persister"); testHelper.VerifyAll(writer); } [Test] public void ShouldWriteSchemaAttribute() { var testHelper = Helper(); testHelper.Check(x => x.Schema, "dbo").MapsToAttribute("schema"); testHelper.VerifyAll(writer); } [Test] public void ShouldWriteTableAttribute() { var testHelper = Helper(); testHelper.Check(x => x.TableName, "table").MapsToAttribute("table"); testHelper.VerifyAll(writer); } [Test] public void ShouldWriteWhereAttribute() { var testHelper = Helper(); testHelper.Check(x => x.Where, "x = 1").MapsToAttribute("where"); testHelper.VerifyAll(writer); } [Test] public void ShouldWriteSortAttribute() { var testHelper = Helper(); testHelper.Check(x => x.Sort, "asc").MapsToAttribute("sort"); testHelper.VerifyAll(writer); } [Test] public void ShouldWriteKey() { var mapping = CollectionMapping.Set(); mapping.Set(x => x.Key, Layer.Defaults, new KeyMapping()); writer.VerifyXml(mapping) .Element("key").Exists(); } [Test] public void ShouldWriteRelationshipElement() { var mapping = CollectionMapping.Set(); mapping.Set(x => x.Relationship, Layer.Defaults, new OneToManyMapping()); writer.VerifyXml(mapping) .Element("one-to-many").Exists(); } [Test] public void ShouldWriteCacheElement() { var mapping = CollectionMapping.Set(); mapping.Set(x => x.Cache, Layer.Defaults, new CacheMapping()); writer.VerifyXml(mapping) .Element("cache").Exists(); } [Test] public void ShouldWriteElement() { var mapping = CollectionMapping.Set(); mapping.Set(x => x.Element, Layer.Defaults, new ElementMapping()); writer.VerifyXml(mapping) .Element("element").Exists(); } static XmlWriterTestHelper<CollectionMapping> Helper() { var helper = new XmlWriterTestHelper<CollectionMapping>(); helper.CreateInstance(CollectionMapping.Set); return helper; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using DlxLib.EnumerableArrayAdapter; // I have used variable names c, r and j deliberately to make it easier to // relate the code back to the original "Dancing Links" paper: // // Dancing Links (Donald E. Knuth, Stanford University) // http://arxiv.org/pdf/cs/0011047v1.pdf namespace DlxLib { /// <summary> /// /// </summary> public class Dlx { private class SearchData { public SearchData(ColumnObject root) { Root = root; } public ColumnObject Root { get; private set; } public int IterationCount { get; private set; } public int SolutionCount { get; private set; } public void IncrementIterationCount() { IterationCount++; } public void IncrementSolutionCount() { SolutionCount++; } public void PushCurrentSolutionRowIndex(int rowIndex) { _currentSolution.Push(rowIndex); } public void PopCurrentSolutionRowIndex() { _currentSolution.Pop(); } public Solution CurrentSolution { get { return new Solution(_currentSolution); } } private readonly Stack<int> _currentSolution = new Stack<int>(); } /// <summary> /// /// </summary> public Dlx() { } // /// <summary> // /// // /// </summary> // /// <param name="cancellationToken"></param> // public Dlx(CancellationToken cancellationToken) // { // _cancellationTokenSource = null; // _cancellationToken = cancellationToken; // } /// <summary> /// /// </summary> /// <param name="matrix"></param> /// <returns></returns> public IEnumerable<Solution> Solve(bool[,] matrix) { return Solve<bool>(matrix); } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="matrix"></param> /// <returns></returns> public IEnumerable<Solution> Solve<T>(T[,] matrix) { var defaultEqualityComparerT = EqualityComparer<T>.Default; var defaultT = default(T); Func<T, bool> predicate = t => !defaultEqualityComparerT.Equals(t, defaultT); return Solve(matrix, predicate); } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="matrix"></param> /// <param name="predicate"></param> /// <returns></returns> public IEnumerable<Solution> Solve<T>(T[,] matrix, Func<T, bool> predicate) { if (matrix == null) { throw new ArgumentNullException("matrix"); } return Solve<T[,], IEnumerable<T>, T>( matrix, (m, f) => { foreach (var r in new Enumerable2DArray<T>(m)) f(r); }, (r, f) => { foreach (var c in r) f(c); }, predicate); } /// <summary> /// /// </summary> /// <typeparam name="TData"></typeparam> /// <typeparam name="TRow"></typeparam> /// <typeparam name="TCol"></typeparam> /// <param name="data"></param> /// <param name="iterateRows"></param> /// <param name="iterateCols"></param> /// <returns></returns> public IEnumerable<Solution> Solve<TData, TRow, TCol>( TData data, Action<TData, Action<TRow>> iterateRows, Action<TRow, Action<TCol>> iterateCols) { var defaultEqualityComparerTCol = EqualityComparer<TCol>.Default; var defaultTCol = default(TCol); Func<TCol, bool> predicate = col => !defaultEqualityComparerTCol.Equals(col, defaultTCol); return Solve( data, iterateRows, iterateCols, predicate); } /// <summary> /// /// </summary> /// <typeparam name="TData"></typeparam> /// <typeparam name="TRow"></typeparam> /// <typeparam name="TCol"></typeparam> /// <param name="data"></param> /// <param name="iterateRows"></param> /// <param name="iterateCols"></param> /// <param name="predicate"></param> /// <returns></returns> public IEnumerable<Solution> Solve<TData, TRow, TCol>( TData data, Action<TData, Action<TRow>> iterateRows, Action<TRow, Action<TCol>> iterateCols, Func<TCol, bool> predicate) { if (data.Equals(default(TData))) throw new ArgumentNullException("data"); var root = BuildInternalStructure(data, iterateRows, iterateCols, predicate); return Search(0, new SearchData(root)); } bool cancelled = false; public void Cancel() { cancelled = true; } /// <summary> /// /// </summary> public EventHandler Started; /// <summary> /// /// </summary> public EventHandler Finished; /// <summary> /// /// </summary> public EventHandler Cancelled; /// <summary> /// /// </summary> public EventHandler<SearchStepEventArgs> SearchStep; /// <summary> /// /// </summary> public EventHandler<SolutionFoundEventArgs> SolutionFound; private bool IsCancelled() { return cancelled; } private static ColumnObject BuildInternalStructure<TData, TRow, TCol>( TData data, Action<TData, Action<TRow>> iterateRows, Action<TRow, Action<TCol>> iterateCols, Func<TCol, bool> predicate) { var root = new ColumnObject(); int? numColumns = null; var rowIndex = 0; var colIndexToListHeader = new Dictionary<int, ColumnObject>(); iterateRows(data, row => { DataObject firstDataObjectInThisRow = null; var localRowIndex = rowIndex; var colIndex = 0; iterateCols(row, col => { if (localRowIndex == 0) { var listHeader = new ColumnObject(); root.AppendColumnHeader(listHeader); colIndexToListHeader[colIndex] = listHeader; } if (predicate(col)) { // Create a new DataObject and add it to the appropriate list header. var listHeader = colIndexToListHeader[colIndex]; var dataObject = new DataObject(listHeader, localRowIndex); if (firstDataObjectInThisRow != null) firstDataObjectInThisRow.AppendToRow(dataObject); else firstDataObjectInThisRow = dataObject; } colIndex++; }); if (numColumns.HasValue) { if (colIndex != numColumns) { throw new ArgumentException("All rows must contain the same number of columns!", "data"); } } else { numColumns = colIndex; } rowIndex++; }); return root; } private static bool MatrixIsEmpty(ColumnObject root) { return root.NextColumnObject == root; } private IEnumerable<Solution> Search(int k, SearchData searchData) { try { if (k == 0) RaiseStarted(); if (IsCancelled()) { RaiseCancelled(); yield break; } RaiseSearchStep(searchData.IterationCount, searchData.CurrentSolution.RowIndexes); searchData.IncrementIterationCount(); if (MatrixIsEmpty(searchData.Root)) { if (searchData.CurrentSolution.RowIndexes.Any()) { searchData.IncrementSolutionCount(); var solutionIndex = searchData.SolutionCount - 1; var solution = searchData.CurrentSolution; RaiseSolutionFound(solution, solutionIndex); yield return solution; } yield break; } var c = ChooseColumnWithLeastRows(searchData.Root); CoverColumn(c); for (var r = c.Down; r != c; r = r.Down) { if (IsCancelled()) { RaiseCancelled(); yield break; } searchData.PushCurrentSolutionRowIndex(r.RowIndex); for (var j = r.Right; j != r; j = j.Right) CoverColumn(j.ListHeader); var recursivelyFoundSolutions = Search(k + 1, searchData); foreach (var solution in recursivelyFoundSolutions) yield return solution; for (var j = r.Left; j != r; j = j.Left) UncoverColumn(j.ListHeader); searchData.PopCurrentSolutionRowIndex(); } UncoverColumn(c); } finally { if (k == 0) RaiseFinished(); } } private static ColumnObject ChooseColumnWithLeastRows(ColumnObject root) { ColumnObject chosenColumn = null; for (var columnHeader = root.NextColumnObject; columnHeader != root; columnHeader = columnHeader.NextColumnObject) { if (chosenColumn == null || columnHeader.NumberOfRows < chosenColumn.NumberOfRows) chosenColumn = columnHeader; } return chosenColumn; } private static void CoverColumn(ColumnObject c) { c.UnlinkColumnHeader(); for (var i = c.Down; i != c; i = i.Down) { for (var j = i.Right; j != i; j = j.Right) { j.ListHeader.UnlinkDataObject(j); } } } private static void UncoverColumn(ColumnObject c) { for (var i = c.Up; i != c; i = i.Up) { for (var j = i.Left; j != i; j = j.Left) { j.ListHeader.RelinkDataObject(j); } } c.RelinkColumnHeader(); } private void RaiseStarted() { var handler = Started; if (handler != null) handler(this, EventArgs.Empty); } private void RaiseFinished() { var handler = Finished; if (handler != null) handler(this, EventArgs.Empty); } private void RaiseCancelled() { var handler = Cancelled; if (handler != null) handler(this, EventArgs.Empty); } private void RaiseSearchStep(int iteration, IEnumerable<int> rowIndexes) { var handler = SearchStep; if (handler != null) handler(this, new SearchStepEventArgs(iteration, rowIndexes)); } private void RaiseSolutionFound(Solution solution, int solutionIndex) { var handler = SolutionFound; if (handler != null) handler(this, new SolutionFoundEventArgs(solution, solutionIndex)); } } }
/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * 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.Security; using System.Security.AccessControl; using FileStream = System.IO.FileStream; namespace Alphaleonis.Win32.Filesystem { public static partial class File { /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path with read/write access.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">The file to open.</param> /// <param name="mode"> /// A <see cref="FileMode"/> value that specifies whether a file is created if one does not exist, and determines whether the contents /// of existing files are retained or overwritten. /// </param> /// <returns>A <see cref="FileStream"/> opened in the specified mode and path, with read/write access and not shared.</returns> [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode) { return OpenCore(transaction, path, mode, mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite, FileShare.None, ExtendedFileAttributes.Normal, null, null, PathFormat.RelativePath); } /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path with read/write access.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">The file to open.</param> /// <param name="mode"> /// A <see cref="FileMode"/> value that specifies whether a file is created if one does not exist, and determines whether the contents /// of existing files are retained or overwritten. /// </param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> /// <returns>A <see cref="FileStream"/> opened in the specified mode and path, with read/write access and not shared.</returns> [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, PathFormat pathFormat) { return OpenCore(transaction, path, mode, mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite, FileShare.None, ExtendedFileAttributes.Normal, null, null, pathFormat); } #region Using FileAccess /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path, with the specified mode and access.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">The file to open.</param> /// <param name="mode"> /// A <see cref="FileMode"/> value that specifies whether a file is created if one does not exist, and determines whether the contents /// of existing files are retained or overwritten. /// </param> /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the file.</param> /// <returns> /// An unshared <see cref="FileStream"/> that provides access to the specified file, with the specified mode and access. /// </returns> [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access) { return OpenCore(transaction, path, mode, access, FileShare.None, ExtendedFileAttributes.Normal, null, null, PathFormat.RelativePath); } /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">The file to open.</param> /// <param name="mode"> /// A <see cref="FileMode"/> value that specifies whether a file is created if one does not exist, and determines whether the contents /// of existing files are retained or overwritten. /// </param> /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the file.</param> /// <param name="share">A <see cref="FileShare"/> value specifying the type of access other threads have to the file.</param> /// <returns> /// A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write access and the /// specified sharing option. /// </returns> [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share) { return OpenCore(transaction, path, mode, access, share, ExtendedFileAttributes.Normal, null, null, PathFormat.RelativePath); } /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path, with the specified mode and access.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">The file to open.</param> /// <param name="mode"> /// A <see cref="FileMode"/> value that specifies whether a file is created if one does not exist, and determines whether the contents /// of existing files are retained or overwritten. /// </param> /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the file.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> /// <returns> /// An unshared <see cref="FileStream"/> that provides access to the specified file, with the specified mode and access. /// </returns> [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, PathFormat pathFormat) { return OpenCore(transaction, path, mode, access, FileShare.None, ExtendedFileAttributes.Normal, null, null, pathFormat); } /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">The file to open.</param> /// <param name="mode">A <see cref="FileMode"/> value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten.</param> /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the file.</param> /// <param name="share">A <see cref="FileShare"/> value specifying the type of access other threads have to the file.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> /// <returns>A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option.</returns> [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, PathFormat pathFormat) { return OpenCore(transaction, path, mode, access, share, ExtendedFileAttributes.Normal, null, null, pathFormat); } /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write access and the specified sharing option.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">The file to open.</param> /// <param name="mode"> /// A <see cref="FileMode"/> value that specifies whether a file is created if one does not exist, and determines whether the contents /// of existing files are retained or overwritten. /// </param> /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the file.</param> /// <param name="share">A <see cref="FileShare"/> value specifying the type of access other threads have to the file.</param> /// <param name="extendedAttributes">The extended attributes.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> /// <returns> /// A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write access and the /// specified sharing option. /// </returns> [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, ExtendedFileAttributes extendedAttributes, PathFormat pathFormat) { return OpenCore(transaction, path, mode, access, share, extendedAttributes, null, null, pathFormat); } /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">The file to open.</param> /// <param name="mode">A constant that determines how to open or create the file.</param> /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the /// file.</param> /// <param name="share">A constant that determines how the file will be shared by processes.</param> /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The /// default buffer size is 4096.</param> /// <returns> /// A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// </returns> [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, int bufferSize) { return OpenCore(transaction, path, mode, access, share, ExtendedFileAttributes.Normal, bufferSize, null, PathFormat.RelativePath); } /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">The file to open.</param> /// <param name="mode">A constant that determines how to open or create the file.</param> /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the /// file.</param> /// <param name="share">A constant that determines how the file will be shared by processes.</param> /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The /// default buffer size is 4096.</param> /// <param name="useAsync">Specifies whether to use asynchronous I/O or synchronous I/O. However, note that the /// underlying operating system might not support asynchronous I/O, so when specifying true, the handle might be /// opened synchronously depending on the platform. When opened asynchronously, the BeginRead and BeginWrite methods /// perform better on large reads or writes, but they might be much slower for small reads or writes. If the /// application is designed to take advantage of asynchronous I/O, set the useAsync parameter to true. Using /// asynchronous I/O correctly can speed up applications by as much as a factor of 10, but using it without /// redesigning the application for asynchronous I/O can decrease performance by as much as a factor of 10.</param> /// <returns> /// A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// </returns> [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync) { return OpenCore(transaction, path, mode, access, share, ExtendedFileAttributes.Normal | (useAsync ? ExtendedFileAttributes.Overlapped : ExtendedFileAttributes.Normal), bufferSize, null, PathFormat.RelativePath); } /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">The file to open.</param> /// <param name="mode">A constant that determines how to open or create the file.</param> /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the /// file.</param> /// <param name="share">A constant that determines how the file will be shared by processes.</param> /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The /// default buffer size is 4096.</param> /// <param name="options">A value that specifies additional file options.</param> /// <returns> /// A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// </returns> [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options) { return OpenCore(transaction, path, mode, access, share, (ExtendedFileAttributes) options, bufferSize, null, PathFormat.RelativePath); } /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">The file to open.</param> /// <param name="mode">A constant that determines how to open or create the file.</param> /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the /// file.</param> /// <param name="share">A constant that determines how the file will be shared by processes.</param> /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The /// default buffer size is 4096.</param> /// <param name="extendedAttributes">The extended attributes specifying additional options.</param> /// <returns> /// A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// </returns> [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, ExtendedFileAttributes extendedAttributes) { return OpenCore(transaction, path, mode, access, share, extendedAttributes, bufferSize, null, PathFormat.RelativePath); } /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">The file to open.</param> /// <param name="mode">A constant that determines how to open or create the file.</param> /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the /// file.</param> /// <param name="share">A constant that determines how the file will be shared by processes.</param> /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The /// default buffer size is 4096.</param> /// <param name="pathFormat">Indicates the format of the path parameter.</param> /// <returns> /// A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// </returns> [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, PathFormat pathFormat) { return OpenCore(transaction, path, mode, access, share, ExtendedFileAttributes.Normal, bufferSize, null, pathFormat); } /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">The file to open.</param> /// <param name="mode">A constant that determines how to open or create the file.</param> /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the /// file.</param> /// <param name="share">A constant that determines how the file will be shared by processes.</param> /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The /// default buffer size is 4096.</param> /// <param name="useAsync">Specifies whether to use asynchronous I/O or synchronous I/O. However, note that the /// underlying operating system might not support asynchronous I/O, so when specifying true, the handle might be /// opened synchronously depending on the platform. When opened asynchronously, the BeginRead and BeginWrite methods /// perform better on large reads or writes, but they might be much slower for small reads or writes. If the /// application is designed to take advantage of asynchronous I/O, set the useAsync parameter to true. Using /// asynchronous I/O correctly can speed up applications by as much as a factor of 10, but using it without /// redesigning the application for asynchronous I/O can decrease performance by as much as a factor of 10.</param> /// <param name="pathFormat">Indicates the format of the path parameter.</param> /// <returns> /// A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// </returns> [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync, PathFormat pathFormat) { return OpenCore(transaction, path, mode, access, share, ExtendedFileAttributes.Normal | (useAsync ? ExtendedFileAttributes.Overlapped : ExtendedFileAttributes.Normal), bufferSize, null, pathFormat); } /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">The file to open.</param> /// <param name="mode">A constant that determines how to open or create the file.</param> /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the /// file.</param> /// <param name="share">A constant that determines how the file will be shared by processes.</param> /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The /// default buffer size is 4096.</param> /// <param name="options">A value that specifies additional file options.</param> /// <param name="pathFormat">Indicates the format of the path parameter.</param> /// <returns> /// A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// </returns> [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, PathFormat pathFormat) { return OpenCore(transaction, path, mode, access, share, (ExtendedFileAttributes) options, bufferSize, null, pathFormat); } /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">The file to open.</param> /// <param name="mode">A constant that determines how to open or create the file.</param> /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the /// file.</param> /// <param name="share">A constant that determines how the file will be shared by processes.</param> /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The /// default buffer size is 4096.</param> /// <param name="extendedAttributes">The extended attributes specifying additional options.</param> /// <param name="pathFormat">Indicates the format of the path parameter.</param> /// <returns> /// A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// </returns> [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, ExtendedFileAttributes extendedAttributes, PathFormat pathFormat) { return OpenCore(transaction, path, mode, access, share, extendedAttributes, bufferSize, null, pathFormat); } #endregion // Using FileAccess #region Using FileSystemRights /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">The file to open.</param> /// <param name="mode">A constant that determines how to open or create the file.</param> /// <param name="rights">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the /// file.</param> /// <param name="share">A constant that determines how the file will be shared by processes.</param> /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The /// default buffer size is 4096.</param> /// <param name="options">A value that specifies additional file options.</param> /// <returns> /// A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// </returns> [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options) { return OpenCore(transaction, path, mode, rights, share, (ExtendedFileAttributes) options, bufferSize, null, PathFormat.RelativePath); } /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">The file to open.</param> /// <param name="mode">A constant that determines how to open or create the file.</param> /// <param name="rights">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the /// file.</param> /// <param name="share">A constant that determines how the file will be shared by processes.</param> /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The /// default buffer size is 4096.</param> /// <param name="extendedAttributes">Extended attributes specifying additional options.</param> /// <returns> /// A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// </returns> [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, ExtendedFileAttributes extendedAttributes) { return OpenCore(transaction, path, mode, rights, share, extendedAttributes, bufferSize, null, PathFormat.RelativePath); } /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">The file to open.</param> /// <param name="mode">A constant that determines how to open or create the file.</param> /// <param name="rights">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the /// file.</param> /// <param name="share">A constant that determines how the file will be shared by processes.</param> /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The /// default buffer size is 4096.</param> /// <param name="options">A value that specifies additional file options.</param> /// <param name="security">A value that determines the access control and audit security for the file.</param> /// <returns> /// A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// </returns> [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity security) { return OpenCore(transaction, path, mode, rights, share, (ExtendedFileAttributes) options, bufferSize, security, PathFormat.RelativePath); } /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">The file to open.</param> /// <param name="mode">A constant that determines how to open or create the file.</param> /// <param name="rights">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the /// file.</param> /// <param name="share">A constant that determines how the file will be shared by processes.</param> /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The /// default buffer size is 4096.</param> /// <param name="extendedAttributes">Extended attributes specifying additional options.</param> /// <param name="security">A value that determines the access control and audit security for the file.</param> /// <returns> /// A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// </returns> [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, ExtendedFileAttributes extendedAttributes, FileSecurity security) { return OpenCore(transaction, path, mode, rights, share, extendedAttributes, bufferSize, security, PathFormat.RelativePath); } /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">The file to open.</param> /// <param name="mode">A constant that determines how to open or create the file.</param> /// <param name="rights">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the /// file.</param> /// <param name="share">A constant that determines how the file will be shared by processes.</param> /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The /// default buffer size is 4096.</param> /// <param name="options">A value that specifies additional file options.</param> /// <param name="pathFormat">Indicates the format of the path parameter.</param> /// <returns> /// A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// </returns> [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, PathFormat pathFormat) { return OpenCore(transaction, path, mode, rights, share, (ExtendedFileAttributes) options, bufferSize, null, pathFormat); } /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, read/write and sharing permission, and buffer size.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">The file to open.</param> /// <param name="mode">A constant that determines how to open or create the file.</param> /// <param name="rights">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the /// file.</param> /// <param name="share">A constant that determines how the file will be shared by processes.</param> /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The /// default buffer size is 4096.</param> /// <param name="extendedAttributes">Extended attributes specifying additional options.</param> /// <param name="pathFormat">Indicates the format of the path parameter.</param> /// <returns> /// A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// </returns> [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, ExtendedFileAttributes extendedAttributes, PathFormat pathFormat) { return OpenCore(transaction, path, mode, rights, share, extendedAttributes, bufferSize, null, pathFormat); } /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, access rights and sharing permission, the buffer size, additional file options, access control and audit security.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">The file to open.</param> /// <param name="mode">A constant that determines how to open or create the file.</param> /// <param name="rights">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the /// file.</param> /// <param name="share">A constant that determines how the file will be shared by processes.</param> /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The /// default buffer size is 4096.</param> /// <param name="options">A value that specifies additional file options.</param> /// <param name="security">A value that determines the access control and audit security for the file.</param> /// <param name="pathFormat">Indicates the format of the path parameter.</param> /// <returns> /// A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// </returns> [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity security, PathFormat pathFormat) { return OpenCore(transaction, path, mode, rights, share, (ExtendedFileAttributes) options, bufferSize, security, pathFormat); } /// <summary>[AlphaFS] (Transacted) Opens a <see cref="FileStream"/> on the specified path using the specified creation mode, access rights and sharing permission, the buffer size, additional file options, access control and audit security.</summary> /// <param name="transaction">The transaction.</param> /// <param name="path">The file to open.</param> /// <param name="mode">A constant that determines how to open or create the file.</param> /// <param name="rights">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the /// file.</param> /// <param name="share">A constant that determines how the file will be shared by processes.</param> /// <param name="bufferSize">A positive <see cref="System.Int32"/> value greater than 0 indicating the buffer size. The /// default buffer size is 4096.</param> /// <param name="extendedAttributes">Extended attributes specifying additional options.</param> /// <param name="security">A value that determines the access control and audit security for the file.</param> /// <param name="pathFormat">Indicates the format of the path parameter.</param> /// <returns> /// A <see cref="FileStream"/> on the specified path, having the specified mode with read, write, or read/write /// access and the specified sharing option. /// </returns> [SecurityCritical] public static FileStream OpenTransacted(KernelTransaction transaction, string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, ExtendedFileAttributes extendedAttributes, FileSecurity security, PathFormat pathFormat) { return OpenCore(transaction, path, mode, rights, share, extendedAttributes, bufferSize, security, pathFormat); } #endregion // Using FileSystemRights } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using CURLAUTH = Interop.libcurl.CURLAUTH; using CURLcode = Interop.libcurl.CURLcode; using CurlFeatures = Interop.libcurl.CURL_VERSION_Features; using CURLMcode = Interop.libcurl.CURLMcode; using CURLoption = Interop.libcurl.CURLoption; using CurlVersionInfoData = Interop.libcurl.curl_version_info_data; namespace System.Net.Http { internal partial class CurlHandler : HttpMessageHandler { #region Constants private const string s_httpPrefix = "HTTP/"; private const char SpaceChar = ' '; private const int StatusCodeLength = 3; private const string UriSchemeHttp = "http"; private const string UriSchemeHttps = "https"; private const string EncodingNameGzip = "gzip"; private const string EncodingNameDeflate = "deflate"; private const int RequestBufferSize = 16384; // Default used by libcurl private const string NoTransferEncoding = HttpKnownHeaderNames.TransferEncoding + ":"; private const int CurlAge = 5; private const int MinCurlAge = 3; #endregion #region Fields private readonly static char[] s_newLineCharArray = new char[] { HttpRuleParser.CR, HttpRuleParser.LF }; private readonly static string[] s_authenticationSchemes = { "Negotiate", "Digest", "Basic" }; // the order in which libcurl goes over authentication schemes private readonly static ulong[] s_authSchemePriorityOrder = { CURLAUTH.Negotiate, CURLAUTH.Digest, CURLAUTH.Basic }; private readonly static CurlVersionInfoData s_curlVersionInfoData; private readonly static bool s_supportsAutomaticDecompression; private readonly static bool s_supportsSSL; private readonly MultiAgent _agent = new MultiAgent(); private volatile bool _anyOperationStarted; private volatile bool _disposed; private IWebProxy _proxy = null; private ICredentials _serverCredentials = null; private ProxyUsePolicy _proxyPolicy = ProxyUsePolicy.UseDefaultProxy; private DecompressionMethods _automaticDecompression = HttpHandlerDefaults.DefaultAutomaticDecompression; private bool _preAuthenticate = HttpHandlerDefaults.DefaultPreAuthenticate; private CredentialCache _credentialCache = null; // protected by LockObject private CookieContainer _cookieContainer = null; private bool _useCookie = HttpHandlerDefaults.DefaultUseCookies; private bool _automaticRedirection = HttpHandlerDefaults.DefaultAutomaticRedirection; private int _maxAutomaticRedirections = HttpHandlerDefaults.DefaultMaxAutomaticRedirections; private object LockObject { get { return _agent; } } #endregion static CurlHandler() { // curl_global_init call handled by Interop.libcurl's cctor // Verify the version of curl we're using is new enough s_curlVersionInfoData = Marshal.PtrToStructure<CurlVersionInfoData>(Interop.libcurl.curl_version_info(CurlAge)); if (s_curlVersionInfoData.age < MinCurlAge) { throw new InvalidOperationException(SR.net_http_unix_https_libcurl_too_old); } // Feature detection s_supportsSSL = (CurlFeatures.CURL_VERSION_SSL & s_curlVersionInfoData.features) != 0; s_supportsAutomaticDecompression = (CurlFeatures.CURL_VERSION_LIBZ & s_curlVersionInfoData.features) != 0; } #region Properties internal bool AutomaticRedirection { get { return _automaticRedirection; } set { CheckDisposedOrStarted(); _automaticRedirection = value; } } internal bool SupportsProxy { get { return true; } } internal bool UseProxy { get { return _proxyPolicy != ProxyUsePolicy.DoNotUseProxy; } set { CheckDisposedOrStarted(); _proxyPolicy = value ? ProxyUsePolicy.UseCustomProxy : ProxyUsePolicy.DoNotUseProxy; } } internal IWebProxy Proxy { get { return _proxy; } set { CheckDisposedOrStarted(); _proxy = value; } } internal ICredentials Credentials { get { return _serverCredentials; } set { _serverCredentials = value; } } internal ClientCertificateOption ClientCertificateOptions { get { return ClientCertificateOption.Manual; } set { if (ClientCertificateOption.Manual != value) { throw new PlatformNotSupportedException(SR.net_http_unix_invalid_client_cert_option); } } } internal bool SupportsAutomaticDecompression { get { return s_supportsAutomaticDecompression; } } internal DecompressionMethods AutomaticDecompression { get { return _automaticDecompression; } set { CheckDisposedOrStarted(); _automaticDecompression = value; } } internal bool PreAuthenticate { get { return _preAuthenticate; } set { CheckDisposedOrStarted(); _preAuthenticate = value; if (value && _credentialCache == null) { _credentialCache = new CredentialCache(); } } } internal bool UseCookie { get { return _useCookie; } set { CheckDisposedOrStarted(); _useCookie = value; } } internal CookieContainer CookieContainer { get { return LazyInitializer.EnsureInitialized(ref _cookieContainer); } set { CheckDisposedOrStarted(); _cookieContainer = value; } } internal int MaxAutomaticRedirections { get { return _maxAutomaticRedirections; } set { if (value <= 0) { throw new ArgumentOutOfRangeException( "value", value, SR.Format(SR.net_http_value_must_be_greater_than, 0)); } CheckDisposedOrStarted(); _maxAutomaticRedirections = value; } } #endregion protected override void Dispose(bool disposing) { _disposed = true; base.Dispose(disposing); } protected internal override Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) { if (request == null) { throw new ArgumentNullException("request", SR.net_http_handler_norequest); } if ((request.RequestUri.Scheme != UriSchemeHttp) && (request.RequestUri.Scheme != UriSchemeHttps)) { throw NotImplemented.ByDesignWithMessage(SR.net_http_client_http_baseaddress_required); } if (request.RequestUri.Scheme == UriSchemeHttps && !s_supportsSSL) { throw new PlatformNotSupportedException(SR.net_http_unix_https_support_unavailable_libcurl); } if (request.Headers.TransferEncodingChunked.GetValueOrDefault() && (request.Content == null)) { throw new InvalidOperationException(SR.net_http_chunked_not_allowed_with_empty_content); } // TODO: Check that SendAsync is not being called again for same request object. // Probably fix is needed in WinHttpHandler as well CheckDisposed(); SetOperationStarted(); // Do an initial cancellation check to avoid initiating the async operation if // cancellation has already been requested. After this, we'll rely on CancellationToken.Register // to notify us of cancellation requests and shut down the operation if possible. if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<HttpResponseMessage>(cancellationToken); } // Create the easy request. This associates the easy request with this handler and configures // it based on the settings configured for the handler. var easy = new EasyRequest(this, request, cancellationToken); // Submit the easy request to the multi agent. if (request.Content != null) { // If there is request content to be sent, preload the stream // and submit the request to the multi agent. This is separated // out into a separate async method to avoid associated overheads // in the case where there is no request content stream. return QueueOperationWithRequestContentAsync(easy); } else { // Otherwise, just submit the request. _agent.Queue(easy); return easy.Task; } } /// <summary> /// Loads the request's request content stream asynchronously and /// then submits the request to the multi agent. /// </summary> private async Task<HttpResponseMessage> QueueOperationWithRequestContentAsync(EasyRequest easy) { Debug.Assert(easy.RequestMessage.Content != null, "Expected request to have non-null request content"); easy.RequestContentStream = await easy.RequestMessage.Content.ReadAsStreamAsync().ConfigureAwait(false); if (easy.CancellationToken.IsCancellationRequested) { easy.FailRequest(new OperationCanceledException(easy.CancellationToken)); easy.Cleanup(); // no active processing remains, so we can cleanup } else { _agent.Queue(easy); } return await easy.Task.ConfigureAwait(false); } #region Private methods private void SetOperationStarted() { if (!_anyOperationStarted) { _anyOperationStarted = true; } } private NetworkCredential GetNetworkCredentials(ICredentials credentials, Uri requestUri) { if (_preAuthenticate) { NetworkCredential nc = null; lock (LockObject) { Debug.Assert(_credentialCache != null, "Expected non-null credential cache"); nc = GetCredentials(_credentialCache, requestUri); } if (nc != null) { return nc; } } return GetCredentials(credentials, requestUri); } private void AddCredentialToCache(Uri serverUri, ulong authAvail, NetworkCredential nc) { lock (LockObject) { for (int i=0; i < s_authSchemePriorityOrder.Length; i++) { if ((authAvail & s_authSchemePriorityOrder[i]) != 0) { Debug.Assert(_credentialCache != null, "Expected non-null credential cache"); _credentialCache.Add(serverUri, s_authenticationSchemes[i], nc); } } } } private static NetworkCredential GetCredentials(ICredentials credentials, Uri requestUri) { if (credentials == null) { return null; } foreach (var authScheme in s_authenticationSchemes) { NetworkCredential networkCredential = credentials.GetCredential(requestUri, authScheme); if (networkCredential != null) { return networkCredential; } } return null; } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } } private void CheckDisposedOrStarted() { CheckDisposed(); if (_anyOperationStarted) { throw new InvalidOperationException(SR.net_http_operation_started); } } private static void ThrowIfCURLEError(int error) { if (error != CURLcode.CURLE_OK) { throw CreateHttpRequestException(new CurlException(error, isMulti: false)); } } private static void ThrowIfCURLMError(int error) { if (error != CURLMcode.CURLM_OK) { string msg = CurlException.GetCurlErrorString(error, true); switch (error) { case CURLMcode.CURLM_ADDED_ALREADY: case CURLMcode.CURLM_BAD_EASY_HANDLE: case CURLMcode.CURLM_BAD_HANDLE: case CURLMcode.CURLM_BAD_SOCKET: throw new ArgumentException(msg); case CURLMcode.CURLM_UNKNOWN_OPTION: throw new ArgumentOutOfRangeException(msg); case CURLMcode.CURLM_OUT_OF_MEMORY: throw new OutOfMemoryException(msg); case CURLMcode.CURLM_INTERNAL_ERROR: default: throw CreateHttpRequestException(new CurlException(error, msg)); } } } private static Exception CreateHttpRequestException(Exception inner = null) { return new HttpRequestException(SR.net_http_client_execution_error, inner); } private static bool TryParseStatusLine(HttpResponseMessage response, string responseHeader, EasyRequest state) { if (!responseHeader.StartsWith(s_httpPrefix, StringComparison.OrdinalIgnoreCase)) { return false; } // Clear the header if status line is recieved again. This signifies that there are multiple response headers (like in redirection). response.Headers.Clear(); response.Content.Headers.Clear(); int responseHeaderLength = responseHeader.Length; // Check if line begins with HTTP/1.1 or HTTP/1.0 int prefixLength = s_httpPrefix.Length; int versionIndex = prefixLength + 2; if ((versionIndex < responseHeaderLength) && (responseHeader[prefixLength] == '1') && (responseHeader[prefixLength + 1] == '.')) { response.Version = responseHeader[versionIndex] == '1' ? HttpVersion.Version11 : responseHeader[versionIndex] == '0' ? HttpVersion.Version10 : new Version(0, 0); } else { response.Version = new Version(0, 0); } // TODO: Parsing errors are treated as fatal. Find right behaviour int spaceIndex = responseHeader.IndexOf(SpaceChar); if (spaceIndex > -1) { int codeStartIndex = spaceIndex + 1; int statusCode = 0; // Parse first 3 characters after a space as status code if (TryParseStatusCode(responseHeader, codeStartIndex, out statusCode)) { response.StatusCode = (HttpStatusCode)statusCode; // For security reasons, we drop the server credential if it is a // NetworkCredential. But we allow credentials in a CredentialCache // since they are specifically tied to URI's. if ((response.StatusCode == HttpStatusCode.Redirect) && !(state.Handler.Credentials is CredentialCache)) { state.SetCurlOption(CURLoption.CURLOPT_HTTPAUTH, CURLAUTH.None); state.SetCurlOption(CURLoption.CURLOPT_USERNAME, IntPtr.Zero); state.SetCurlOption(CURLoption.CURLOPT_PASSWORD, IntPtr.Zero); state.NetworkCredential = null; } int codeEndIndex = codeStartIndex + StatusCodeLength; int reasonPhraseIndex = codeEndIndex + 1; if (reasonPhraseIndex < responseHeaderLength && responseHeader[codeEndIndex] == SpaceChar) { int newLineCharIndex = responseHeader.IndexOfAny(s_newLineCharArray, reasonPhraseIndex); int reasonPhraseEnd = newLineCharIndex >= 0 ? newLineCharIndex : responseHeaderLength; response.ReasonPhrase = responseHeader.Substring(reasonPhraseIndex, reasonPhraseEnd - reasonPhraseIndex); } } } return true; } private static bool TryParseStatusCode(string responseHeader, int statusCodeStartIndex, out int statusCode) { if (statusCodeStartIndex + StatusCodeLength > responseHeader.Length) { statusCode = 0; return false; } char c100 = responseHeader[statusCodeStartIndex]; char c10 = responseHeader[statusCodeStartIndex + 1]; char c1 = responseHeader[statusCodeStartIndex + 2]; if (c100 < '0' || c100 > '9' || c10 < '0' || c10 > '9' || c1 < '0' || c1 > '9') { statusCode = 0; return false; } statusCode = (c100 - '0') * 100 + (c10 - '0') * 10 + (c1 - '0'); return true; } private static void SetChunkedModeForSend(HttpRequestMessage request) { bool chunkedMode = request.Headers.TransferEncodingChunked.GetValueOrDefault(); HttpContent requestContent = request.Content; Debug.Assert(requestContent != null, "request is null"); // Deal with conflict between 'Content-Length' vs. 'Transfer-Encoding: chunked' semantics. // libcurl adds a Tranfer-Encoding header by default and the request fails if both are set. if (requestContent.Headers.ContentLength.HasValue) { if (chunkedMode) { // Same behaviour as WinHttpHandler requestContent.Headers.ContentLength = null; } else { // Prevent libcurl from adding Transfer-Encoding header request.Headers.TransferEncodingChunked = false; } } } #endregion private enum ProxyUsePolicy { DoNotUseProxy = 0, // Do not use proxy. Ignores the value set in the environment. UseDefaultProxy = 1, // Do not set the proxy parameter. Use the value of environment variable, if any. UseCustomProxy = 2 // Use The proxy specified by the user. } } }
//! \file ArcINT.cs //! \date Fri Jul 11 09:32:36 2014 //! \brief Frontwing games archive. // // Copyright (C) 2014 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.IO; using System.Linq; using System.Text; using System.ComponentModel; using System.ComponentModel.Composition; using System.Collections.Generic; using Simias.Encryption; using System.Runtime.InteropServices; using GameRes.Formats.Strings; using GameRes.Formats.Properties; using GameRes.Utility; namespace GameRes.Formats.CatSystem { public class FrontwingArchive : ArcFile { public readonly Blowfish Encryption; public FrontwingArchive (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir, Blowfish cipher) : base (arc, impl, dir) { Encryption = cipher; } } [Serializable] public struct KeyData { public uint Key; public string Passphrase; public KeyData (string password) { Passphrase = password; Key = EncodePassPhrase (password); } public static uint EncodePassPhrase (string password) { byte[] pass_bytes = Encodings.cp932.GetBytes (password); uint key = 0xffffffff; foreach (var c in pass_bytes) { uint val = (uint)c << 24; key ^= val; for (int i = 0; i < 8; ++i) { bool carry = 0 != (key & 0x80000000); key <<= 1; if (carry) key ^= 0x4C11DB7; } key = ~key; } return key; } } [Serializable] public class IntScheme : ResourceScheme { public Dictionary<string, KeyData> KnownKeys; } [Serializable] public class IntEncryptionInfo { public uint? Key { get; set; } public string Scheme { get; set; } public string Password { get; set; } public uint? GetKey () { if (null != Key && Key.HasValue) return Key; if (!string.IsNullOrEmpty (Scheme)) { KeyData keydata; if (IntOpener.KnownSchemes.TryGetValue (Scheme, out keydata)) return keydata.Key; } if (!string.IsNullOrEmpty (Password)) return KeyData.EncodePassPhrase (Password); return null; } } public class IntOptions : ResourceOptions { public IntEncryptionInfo EncryptionInfo { get; set; } } [Export(typeof(ArchiveFormat))] public class IntOpener : ArchiveFormat { public override string Tag { get { return "INT"; } } public override string Description { get { return arcStrings.INTDescription; } } public override uint Signature { get { return 0x0046494b; } } public override bool IsHierarchic { get { return false; } } public override bool CanCreate { get { return true; } } static readonly byte[] NameSizes = { 0x20, 0x40 }; public override ArcFile TryOpen (ArcView file) { int entry_count = file.View.ReadInt32 (4); if (!IsSaneCount (entry_count)) return null; if (file.View.AsciiEqual (8, "__key__.dat\x00")) { uint? key = QueryEncryptionInfo(); if (null == key) throw new UnknownEncryptionScheme(); return OpenEncrypted (file, entry_count, key.Value); } var dir = new List<Entry> (entry_count); foreach (var name_length in NameSizes) { dir.Clear(); try { long current_offset = 8; for (int i = 0; i < entry_count; ++i) { string name = file.View.ReadString (current_offset, name_length); if (0 == name.Length) { dir.Clear(); break; } var entry = FormatCatalog.Instance.Create<Entry> (name); current_offset += name_length; entry.Offset = file.View.ReadUInt32 (current_offset); entry.Size = file.View.ReadUInt32 (current_offset+4); if (entry.Offset <= current_offset || !entry.CheckPlacement (file.MaxOffset)) { dir.Clear(); break; } dir.Add (entry); current_offset += 8; } if (dir.Count > 0) return new ArcFile (file, this, dir); } catch { /* ignore parse errors */ } } return null; } private ArcFile OpenEncrypted (ArcView file, int entry_count, uint main_key) { if (1 == entry_count) return null; // empty archive long current_offset = 8; uint seed = file.View.ReadUInt32 (current_offset+0x44); var twister = new MersenneTwister (seed); byte[] blowfish_key = BitConverter.GetBytes (twister.Rand()); if (!BitConverter.IsLittleEndian) Array.Reverse (blowfish_key); var blowfish = new Blowfish (blowfish_key); var dir = new List<Entry> (entry_count-1); byte[] name_buffer = new byte[0x40]; for (int i = 1; i < entry_count; ++i) { current_offset += 0x48; file.View.Read (current_offset, name_buffer, 0, 0x40); uint offset = file.View.ReadUInt32 (current_offset+0x40) + (uint)i; uint size = file.View.ReadUInt32 (current_offset+0x44); blowfish.Decipher (ref offset, ref size); twister.SRand (main_key + (uint)i); uint name_key = twister.Rand(); string name = DecipherName (name_buffer, name_key); var entry = FormatCatalog.Instance.Create<Entry> (name); entry.Offset = offset; entry.Size = size; if (!entry.CheckPlacement (file.MaxOffset)) return null; dir.Add (entry); } return new FrontwingArchive (file, this, dir, blowfish); } private Stream OpenEncryptedEntry (FrontwingArchive arc, Entry entry) { byte[] data = arc.File.View.ReadBytes (entry.Offset, entry.Size); arc.Encryption.Decipher (data, data.Length/8*8); return new MemoryStream (data); } public override Stream OpenEntry (ArcFile arc, Entry entry) { if (arc is FrontwingArchive) return OpenEncryptedEntry (arc as FrontwingArchive, entry); else return base.OpenEntry (arc, entry); } public string DecipherName (byte[] name, uint key) { string alphabet = "zyxwvutsrqponmlkjihgfedcbaZYXWVUTSRQPONMLKJIHGFEDCBA"; int k = (byte)((key >> 24) + (key >> 16) + (key >> 8) + key); int i; for (i = 0; i < name.Length && name[i] != 0; ++i) { int j = alphabet.IndexOf ((char)name[i]); if (j != -1) { j -= k % 0x34; if (j < 0) j += 0x34; name[i] = (byte)alphabet[0x33-j]; } ++k; } return Encodings.cp932.GetString (name, 0, i); } public static Dictionary<string, KeyData> KnownSchemes = new Dictionary<string, KeyData>(); public override ResourceScheme Scheme { get { return new IntScheme { KnownKeys = KnownSchemes }; } set { KnownSchemes = ((IntScheme)value).KnownKeys; } } public override ResourceOptions GetDefaultOptions () { return new IntOptions { EncryptionInfo = Settings.Default.INTEncryption ?? new IntEncryptionInfo(), }; } public override ResourceOptions GetOptions (object w) { var widget = w as GUI.WidgetINT; if (null != widget) { Settings.Default.INTEncryption = widget.Info; return new IntOptions { EncryptionInfo = widget.Info }; } return this.GetDefaultOptions(); } public override object GetAccessWidget () { return new GUI.WidgetINT (); } public override object GetCreationWidget () { return new GUI.CreateINTWidget(); } uint? QueryEncryptionInfo () { var options = Query<IntOptions> (arcStrings.INTNotice); return options.EncryptionInfo.GetKey(); } public override void Create (Stream output, IEnumerable<Entry> list, ResourceOptions options, EntryCallback callback) { int file_count = list.Count(); if (null != callback) callback (file_count+2, null, null); int callback_count = 0; using (var writer = new BinaryWriter (output, Encoding.ASCII, true)) { writer.Write (Signature); writer.Write (file_count); long dir_offset = output.Position; var encoding = Encodings.cp932.WithFatalFallback(); byte[] name_buf = new byte[0x40]; int previous_size = 0; if (null != callback) callback (callback_count++, null, arcStrings.MsgWritingIndex); // first, write names only foreach (var entry in list) { string name = Path.GetFileName (entry.Name); try { int size = encoding.GetBytes (name, 0, name.Length, name_buf, 0); for (int i = size; i < previous_size; ++i) name_buf[i] = 0; previous_size = size; } catch (EncoderFallbackException X) { throw new InvalidFileName (entry.Name, arcStrings.MsgIllegalCharacters, X); } catch (ArgumentException X) { throw new InvalidFileName (entry.Name, arcStrings.MsgFileNameTooLong, X); } writer.Write (name_buf); writer.BaseStream.Seek (8, SeekOrigin.Current); } // now, write files and remember offset/sizes long current_offset = output.Position; foreach (var entry in list) { if (null != callback) callback (callback_count++, entry, arcStrings.MsgAddingFile); entry.Offset = current_offset; using (var input = File.OpenRead (entry.Name)) { var size = input.Length; if (size > uint.MaxValue || current_offset + size > uint.MaxValue) throw new FileSizeException(); current_offset += (uint)size; entry.Size = (uint)size; input.CopyTo (output); } } if (null != callback) callback (callback_count++, null, arcStrings.MsgUpdatingIndex); // at last, go back to directory and write offset/sizes dir_offset += 0x40; foreach (var entry in list) { writer.BaseStream.Position = dir_offset; writer.Write ((uint)entry.Offset); writer.Write (entry.Size); dir_offset += 0x48; } } } /// <summary> /// Parse certain executable resources for encryption passphrase. /// Returns null if no passphrase found. /// </summary> public static string GetPassFromExe (string filename) { var exe = NativeMethods.LoadLibraryEx (filename, IntPtr.Zero, 0x20); // LOAD_LIBRARY_AS_IMAGE_RESOURCE if (IntPtr.Zero == exe) throw new Win32Exception (Marshal.GetLastWin32Error()); try { var code = GetResource (exe, "DATA", "V_CODE2"); if (null == code || code.Length < 8) return null; var key = GetResource (exe, "KEY", "KEY_CODE"); if (null != key) { for (int i = 0; i < key.Length; ++i) key[i] ^= 0xCD; } else { key = Encoding.ASCII.GetBytes ("windmill"); } var blowfish = new Blowfish (key); blowfish.Decipher (code, code.Length/8*8); int length = Array.IndexOf<byte> (code, 0); if (-1 == length) length = code.Length; return Encodings.cp932.GetString (code, 0, length); } finally { NativeMethods.FreeLibrary (exe); } } static byte[] GetResource (IntPtr exe, string name, string type) { var res = NativeMethods.FindResource (exe, name, type); if (IntPtr.Zero == res) return null; var glob = NativeMethods.LoadResource (exe, res); if (IntPtr.Zero == glob) return null; uint size = NativeMethods.SizeofResource (exe, res); var src = NativeMethods.LockResource (glob); if (IntPtr.Zero == src) return null; var dst = new byte[size]; Marshal.Copy (src, dst, 0, dst.Length); return dst; } } static internal class NativeMethods { [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] static internal extern IntPtr LoadLibraryEx (string lpFileName, IntPtr hReservedNull, uint dwFlags); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] static internal extern bool FreeLibrary (IntPtr hModule); [DllImport( "kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] static internal extern IntPtr FindResource (IntPtr hModule, string lpName, string lpType); [DllImport("Kernel32.dll", SetLastError = true)] static internal extern IntPtr LoadResource (IntPtr hModule, IntPtr hResource); [DllImport("Kernel32.dll", SetLastError = true)] static internal extern uint SizeofResource (IntPtr hModule, IntPtr hResource); [DllImport("kernel32.dll")] static internal extern IntPtr LockResource (IntPtr hResData); } }
// 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.Runtime.CompilerServices; using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.integeregererface01.integeregererface01 { using ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.integeregererface01.integeregererface01; // <Title> CLS Compliance for Dynamic </Title> // <Description> Types Rule : Interface Methods (Compiler) // CLS-compliant language compilers must have syntax for the situation where a single type implements // two interfaces and each of those interfaces requires the definition of a method with the same name and signature. // Such methods must be considered distinct and need not have the same implementation. // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> //[assembly: System.CLSCompliant(true)] namespace MyNamespace { public interface MyInterface1 { dynamic Method01(int n); T Method02<T>(dynamic n); dynamic Method03(byte b, ref dynamic n); } public interface MyInterface2 { dynamic Method01(int n); T Method02<T>(dynamic n); dynamic Method03(byte b, ref dynamic n); } public class MyClass : MyInterface1, MyInterface2 { dynamic MyInterface1.Method01(int n) { return default(dynamic); } T MyInterface1.Method02<T>(dynamic n) { return default(T); } dynamic MyInterface1.Method03(byte b, ref dynamic n) { return default(dynamic); } dynamic MyInterface2.Method01(int n) { return default(dynamic); } T MyInterface2.Method02<T>(dynamic n) { return default(T); } dynamic MyInterface2.Method03(byte b, ref dynamic n) { return default(dynamic); } } public struct MyStruct : MyInterface1, MyInterface2 { public dynamic Method01(int n) { return default(dynamic); } public T Method02<T>(dynamic n) { return default(T); } public dynamic Method03(byte b, ref dynamic n) { return default(dynamic); } } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.mixedmode02.mixedmode02 { using ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.mixedmode02.mixedmode02; // <Title> CLS Compliance for Dynamic </Title> // <Description> Naming Rule : Characters and casing // CLS-compliant language compilers must follow the rules of Annex 7 of Technical Report 15 of // the Unicode Standard 3.0, which governs the set of characters that can start and be included in identifiers. // This standard is available from the Web site of the Unicode Consortium. // For two identifiers to be considered distinct, they must differ by more than just their case. // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=warning>\(79,55\).*CS3022</Expects> //<Expects Status=warning>\(80,55\).*CS3022</Expects> //<Expects Status=warning>\(47,29\).*CS3026.*vd1</Expects> //<Expects Status=warning>\(50,23\).*CS3002.*RefMethod01\<T\>\(ref dynamic, T\)</Expects> //<Expects Status=warning>\(51,23\).*CS3002.*refMethod01\<T\></Expects> //<Expects Status=warning>\(51,23\).*CS3005</Expects> //<Expects Status=warning>\(65,13\).*CS3010.*MyInterface\<T,U,V\>.Method01</Expects> //<Expects Status=warning>\(69,7\).*CS3005.*MyInterface\<T,U,V\>.method02</Expects> //<Expects Status=warning>\(72,13\).*CS3005.*method03\<X,Y\></Expects> //<Expects Status=warning>\(75,27\).*CS3010.*MyInterface\<T,U,V\>.MyEvent</Expects> //<Expects Status=warning>\(75,27\).*CS3010</Expects> //<Expects Status=warning>\(75,27\).*CS3010</Expects> //<Expects Status=warning>\(80,22\).*CS3005.*myDelegate01\<T\></Expects> //<Expects Status=success></Expects> // <Code> // <Expects Status=notin>CS3005.*outMethod01\<X\></Expects> // <Expects Status=notin>CS3005.*method01\<X\></Expects> // <Expects Status=notin>CS3005.*myDelegate02\<U,V\></Expects> // <Code> //[assembly: System.CLSCompliant(true)] [type: System.CLSCompliant(false)] public class MyClass<T> { public volatile dynamic vd; public static T OutMethod01<X>(T t, ref X x, out dynamic d) { d = default(object); return default(T); } public static T outMethod01<X>(T t, ref X x, out dynamic d) { d = default(object); return default(T); } } [type: System.CLSCompliant(true)] public struct MyStruct<U, V> { public volatile dynamic vd1; [method: System.CLSCompliant(true)] public MyClass<T> RefMethod01<T>(ref dynamic d, T t) { d = default(object); return new MyClass<T>(); } public MyClass<T> refMethod01<T>(ref dynamic d, T t) { d = default(object); return new MyClass<T>(); } [property: System.CLSCompliant(false)] public dynamic Prop { get; set; } public dynamic prop { get; set; } [field: System.CLSCompliant(false)] public dynamic field; public dynamic fielD; } public interface MyInterface<T, U, V> { [method: System.CLSCompliant(false)] dynamic Method01<X>(X n); dynamic method01<X>(X n); T Method02(dynamic n, U u); T method02(dynamic n, U u); [method: System.CLSCompliant(true)] dynamic Method03<X, Y>(out X x, ref Y y, dynamic n); dynamic method03<X, Y>(out X x, ref Y y, dynamic n); [event: System.CLSCompliant(false)] event MyDelegate01<T> MyEvent; event MyDelegate01<T> Myevent; } public delegate void MyDelegate01<T>(ref T t, [param: System.CLSCompliant(false)] dynamic d, int n); public delegate void myDelegate01<T>(ref T t, [param: System.CLSCompliant(true)] dynamic d, int n); [System.CLSCompliantAttribute(false)] public delegate V MyDelegate02<U, V>(U u, params dynamic[] ary); public delegate V myDelegate02<U, V>(U u, params dynamic[] ary); // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingchr02.namingchr02 { using ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingchr02.namingchr02; // <Title> CLS Compliance for Dynamic </Title> // <Description> Naming Rule : Characters and casing // CLS-compliant language compilers must follow the rules of Annex 7 of Technical Report 15 of // the Unicode Standard 3.0, which governs the set of characters that can start and be included in identifiers. // This standard is available from the Web site of the Unicode Consortium. // For two identifiers to be considered distinct, they must differ by more than just their case. // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=warning>\(30,14\).*CS3005.*outMethod01\<X\></Expects> //<Expects Status=warning>\(36,23\).*CS3005.*refMethod01\<T\></Expects> //<Expects Status=warning>\(42,13\).*CS3005.*method01\<X\></Expects> //<Expects Status=warning>\(45,7\).*CS3005.*MyInterface\<T,U,V\>.method02</Expects> //<Expects Status=warning>\(48,13\).*CS3005.*method03\<X,Y\></Expects> //<Expects Status=warning>\(52,22\).*CS3005.*myDelegate01\<T\></Expects> //<Expects Status=warning>\(55,19\).*CS3005.*myDelegate02\<U,V\></Expects> //<Expects Status=success></Expects> // <Code> // <Code> //[assembly: System.CLSCompliant(true)] public class MyClass<T> { public T OutMethod01<X>(T t, ref X x, out dynamic d) { d = default(object); return default(T); } public T outMethod01<X>(T t, ref X x, out dynamic d) { d = default(object); return default(T); } } public struct MyStruct<U, V> { public MyClass<T> RefMethod01<T>(ref dynamic d, T t) { d = default(object); return new MyClass<T>(); } public MyClass<T> refMethod01<T>(ref dynamic d, T t) { d = default(object); return new MyClass<T>(); } } public interface MyInterface<T, U, V> { dynamic Method01<X>(X n); dynamic method01<X>(X n); T Method02(dynamic n, U u); T method02(dynamic n, U u); dynamic Method03<X, Y>(out X x, ref Y y, dynamic n); dynamic method03<X, Y>(out X x, ref Y y, dynamic n); } public delegate void MyDelegate01<T>(ref T t, dynamic d, int n); public delegate void myDelegate01<T>(ref T t, dynamic d, int n); public delegate V MyDelegate02<U, V>(U u, params dynamic[] ary); public delegate V myDelegate02<U, V>(U u, params dynamic[] ary); // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingchr03.namingchr03 { using ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingchr03.namingchr03; // <Title> CLS Compliance for Dynamic </Title> // <Description> Naming Rule : Characters and casing // CLS-compliant language compilers must follow the rules of Annex 7 of Technical Report 15 of // the Unicode Standard 3.0, which governs the set of characters that can start and be included in identifiers. // This standard is available from the Web site of the Unicode Consortium. // For two identifiers to be considered distinct, they must differ by more than just their case. // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=warning>\(57,24\).*CS0108</Expects> //<Expects Status=warning>\(41,24\).*CS3005.*method01</Expects> //<Expects Status=warning>\(42,18\).*CS3005.*method02\<T\></Expects> //<Expects Status=warning>\(49,24\).*CS3005.*classIdentifier</Expects> //<Expects Status=warning>\(50,24\).*CS3005.*MEthod01</Expects> //<Expects Status=warning>\(51,18\).*CS3005.*mEthod02\<T\></Expects> //<Expects Status=warning>\(52,24\).*CS3005.*method03\<X,Y></Expects> //<Expects Status=warning>\(57,24\).*CS3005</Expects> //<Expects Status=warning>\(58,24\).*CS3005.*MyClass3\<U,V\>\.Method01</Expects> //<Expects Status=warning>\(59,24\).*CS3005.*MyClass3\<U,V\>\.Method03</Expects> //<Expects Status=success></Expects> // <Code> // <Code> //[assembly: System.CLSCompliant(true)] namespace MyNamespace { public class MyBase { public dynamic Method01(int n, ref dynamic d) { return default(object); } public T Method02<T>(T t, out dynamic d) { d = default(object); return default(T); } } public class MyClass : MyBase { public dynamic ClassIdentifier; public dynamic method01(int n, ref dynamic d) { return default(object); } public T method02<T>(T t, out dynamic d) { d = default(object); return default(T); } public dynamic Method03<X, Y>(X x, ref Y y, params dynamic[] ary) { return default(object); } } public class MyClass2 : MyClass { public dynamic classIdentifier; public dynamic MEthod01(int n, ref dynamic d) { return default(object); } public T mEthod02<T>(T t, out dynamic d) { d = default(object); return default(T); } public dynamic method03<X, Y>(X x, ref Y y, params dynamic[] ary) { return default(object); } } public class MyClass3<U, V> : MyClass2 { public dynamic ClassIdentifier; public dynamic Method01(long n, ref dynamic d) { return default(object); } public dynamic Method03(U x, ref V y, params dynamic[] ary) { return default(object); } } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingchr04.namingchr04 { using ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingchr04.namingchr04; // <Title> CLS Compliance for Dynamic </Title> // <Description> Visibility - CLS rules apply only to those parts of a type that are exposed outside the defining assembly. // Naming Rule : Characters and casing // CLS-compliant language compilers must follow the rules of Annex 7 of Technical Report 15 of // the Unicode Standard 3.0, which governs the set of characters that can start and be included in identifiers. // This standard is available from the Web site of the Unicode Consortium. // For two identifiers to be considered distinct, they must differ by more than just their case. // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=warning>\(31,17\).*CS0169</Expects> //<Expects Status=warning>\(43,25\).*CS0169</Expects> //<Expects Status=success></Expects> // <Code> //[assembly: System.CLSCompliant(true)] namespace MyNamespace { public class MyBase { public dynamic[][][] array; //jagged array private dynamic Method01(int n, ref dynamic d) { return default(object); } private T Method02<T>(T t, out dynamic d) { d = default(object); return default(T); } } public class MyClass : MyBase { private dynamic _classIdentifier; internal dynamic method01(int n, ref dynamic d) { return default(object); } protected T method02<T>(T t, out dynamic d) { d = default(object); return default(T); } private dynamic Method03<X, Y>(X x, ref Y y, params dynamic[] ary) { return default(object); } } public class MyClass2 : MyClass { //static public dynamic[,,,] array1; //cube array private dynamic _classIdentifier; private dynamic MEthod01(int n, ref dynamic d) { return default(object); } private T mEthod02<T>(T t, out dynamic d) { d = default(object); return default(T); } protected dynamic method03<X, Y>(X x, ref Y y, params dynamic[] ary) { return default(object); } } public class MyClass3<U, V> : MyClass2 { protected dynamic ClassIdentifier; private dynamic Method01(long n, ref dynamic d) { return default(object); } internal protected dynamic method03(U x, ref V y, params dynamic[] ary) { return default(object); } } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingkeyword01.namingkeyword01 { using ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.namingkeyword01.namingkeyword01; // <Title> CLS Compliance for Dynamic </Title> // <Description> Naming Rule : Keywords (Compiler) // CLS-compliant language compilers supply a mechanism for referencing identifiers that coincide with keywords. // CLS-compliant language compilers provide a mechanism for defining and overriding virtual methods // with names that are keywords in the language. // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> //[assembly: System.CLSCompliant(true)] namespace MyNamespace { public class MyClass { public dynamic @dynamic; public dynamic Method01(ref int @dynamic) { return default(dynamic); } } public struct MyStruct { public dynamic @dynamic; public void Method02(out dynamic @dynamic) { @dynamic = default(dynamic); } } public interface MyInterface { dynamic Method01(int n, dynamic @dynamic); dynamic @dynamic(string n, dynamic d); } public delegate void myDelegate02(params dynamic[] @dynamic); public delegate int @dynamic(int n); namespace MyNamespace11 { public enum @dynamic { } } } namespace MyNamespace1 { public class @dynamic { private dynamic Method01(out int n, dynamic d) { n = 0; return default(dynamic); } } namespace MyNamespace2 { public struct @dynamic { private dynamic Method01(int n, ref dynamic d) { return default(dynamic); } } namespace MyNamespace3 { public interface @dynamic { dynamic Method01(int n, ref dynamic d); } } } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.typegeneral01.typegeneral01 { using ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.typegeneral01.typegeneral01; // <Title> CLS Compliance for Dynamic </Title> // <Description> Types Rule : Interface Methods (Compiler) // CLS-compliant language compilers must have syntax for the situation where a single type implements // two interfaces and each of those interfaces requires the definition of a method with the same name and signature. // Such methods must be considered distinct and need not have the same implementation. // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> using System; //[assembly: System.CLSCompliant(true)] namespace MyNamespace { public class MyClass { public dynamic Method01(int x, int y = 0, int z = 1) { return default(dynamic); } // public T Method02<T>(dynamic d = default(dynamic), string s = "QQQ") { return default(T); } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { MyClass c = new MyClass(); c.Method01(999); c.Method01(9, 8); c.Method01(9, 8, 7); c.Method01(999, z: 888); c.Method01(999, z: 888, y: 666); c.Method02<byte>(); c.Method02<int>(default(dynamic)); c.Method02<long>(default(dynamic), "CCC"); var v = new MyStruct<dynamic>(); v.Method11(); v.Method11(default(dynamic)); v.Method11(default(object), default(object), default(object)); v.Method12<int, dynamic>(); v.Method12<int, dynamic>(100); v.Method12<int, dynamic>(-9999, default(dynamic)); return 0; } } public struct MyStruct<T> { public dynamic Method11(T t = default(T), params dynamic[] ary) { return default(dynamic); } public T Method12<U, V>(U u = default(U), V v = default(V)) { return default(T); } } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.bug89385_a.bug89385_a { using ManagedTests.DynamicCSharp.Conformance.dynamic.ClsCompliance.bug89385_a.bug89385_a; // <Title> regression test</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Foo { public static void Method(string s) { if (s == "abc") Test.Result++; } public string Prop { get; set; } } public class Test { public Foo Foo { get; set; } public static void DoExample(dynamic d) { Foo.Method(d.Prop); } public static int Result = -1; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { try { DoExample(new Foo() { Prop = "abc" } ); } catch (System.Exception) { Test.Result--; } return Test.Result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Globalization; using System.IO; using System.Net.Http; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Testing; using Xunit; namespace Microsoft.AspNetCore.Server.HttpSys { public class OpaqueUpgradeTests { [ConditionalFact] [MaximumOSVersion(OperatingSystems.Windows, WindowsVersions.Win7)] public async Task OpaqueUpgrade_DownLevel_FeatureIsAbsent() { using (Utilities.CreateHttpServer(out var address, httpContext => { try { var opaqueFeature = httpContext.Features.Get<IHttpUpgradeFeature>(); Assert.Null(opaqueFeature); } catch (Exception ex) { return httpContext.Response.WriteAsync(ex.ToString()); } return Task.FromResult(0); })) { HttpResponseMessage response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); Assert.False(response.Headers.TransferEncodingChunked.HasValue, "Chunked"); Assert.Equal(0, response.Content.Headers.ContentLength); Assert.Equal(string.Empty, await response.Content.ReadAsStringAsync()); } } [ConditionalFact] [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win8)] public async Task OpaqueUpgrade_SupportKeys_Present() { string address; using (Utilities.CreateHttpServer(out address, httpContext => { try { var opaqueFeature = httpContext.Features.Get<IHttpUpgradeFeature>(); Assert.NotNull(opaqueFeature); } catch (Exception ex) { httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError; return httpContext.Response.WriteAsync(ex.ToString()); } return Task.FromResult(0); })) { HttpResponseMessage response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); Assert.False(response.Headers.TransferEncodingChunked.HasValue, "Chunked"); Assert.Equal(0, response.Content.Headers.ContentLength); Assert.Equal(string.Empty, await response.Content.ReadAsStringAsync()); } } [ConditionalFact] [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win8)] public async Task OpaqueUpgrade_AfterHeadersSent_Throws() { bool? upgradeThrew = null; string address; using (Utilities.CreateHttpServer(out address, async httpContext => { await httpContext.Response.WriteAsync("Hello World"); await httpContext.Response.Body.FlushAsync(); try { var opaqueFeature = httpContext.Features.Get<IHttpUpgradeFeature>(); Assert.NotNull(opaqueFeature); await opaqueFeature.UpgradeAsync(); upgradeThrew = false; } catch (InvalidOperationException) { upgradeThrew = true; } })) { HttpResponseMessage response = await SendRequestAsync(address); Assert.Equal(200, (int)response.StatusCode); Assert.True(response.Headers.TransferEncodingChunked.Value, "Chunked"); Assert.True(upgradeThrew.Value); } } [ConditionalFact] [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win8)] public async Task OpaqueUpgrade_GetUpgrade_Success() { var upgraded = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); using (Utilities.CreateHttpServer(out var address, async httpContext => { httpContext.Response.Headers["Upgrade"] = "websocket"; // Win8.1 blocks anything but WebSockets var opaqueFeature = httpContext.Features.Get<IHttpUpgradeFeature>(); Assert.NotNull(opaqueFeature); Assert.True(opaqueFeature.IsUpgradableRequest); await opaqueFeature.UpgradeAsync(); upgraded.SetResult(true); })) { using (Stream stream = await SendOpaqueRequestAsync("GET", address)) { Assert.True(await upgraded.Task.TimeoutAfter(TimeSpan.FromSeconds(1))); } } } [ConditionalFact] [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win8)] public async Task OpaqueUpgrade_GetUpgrade_NotAffectedByMaxRequestBodyLimit() { var upgraded = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); using (Utilities.CreateHttpServer(out var address, async httpContext => { var feature = httpContext.Features.Get<IHttpMaxRequestBodySizeFeature>(); Assert.NotNull(feature); Assert.False(feature.IsReadOnly); Assert.Null(feature.MaxRequestBodySize); // GET/Upgrade requests don't actually have an entity body, so they can't set the limit. httpContext.Response.Headers["Upgrade"] = "websocket"; // Win8.1 blocks anything but WebSockets var opaqueFeature = httpContext.Features.Get<IHttpUpgradeFeature>(); Assert.NotNull(opaqueFeature); Assert.True(opaqueFeature.IsUpgradableRequest); var stream = await opaqueFeature.UpgradeAsync(); Assert.True(feature.IsReadOnly); Assert.Null(feature.MaxRequestBodySize); Assert.Throws<InvalidOperationException>(() => feature.MaxRequestBodySize = 12); Assert.Equal(15, await stream.ReadAsync(new byte[15], 0, 15)); upgraded.SetResult(true); }, options => options.MaxRequestBodySize = 10)) { using (Stream stream = await SendOpaqueRequestAsync("GET", address)) { stream.Write(new byte[15], 0, 15); Assert.True(await upgraded.Task.TimeoutAfter(TimeSpan.FromSeconds(10))); } } } [ConditionalFact] [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win8)] public async Task OpaqueUpgrade_WithOnStarting_CallbackCalled() { var callbackCalled = false; var upgraded = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); using (Utilities.CreateHttpServer(out var address, async httpContext => { httpContext.Response.OnStarting(_ => { callbackCalled = true; return Task.FromResult(0); }, null); httpContext.Response.Headers["Upgrade"] = "websocket"; // Win8.1 blocks anything but WebSockets var opaqueFeature = httpContext.Features.Get<IHttpUpgradeFeature>(); Assert.NotNull(opaqueFeature); Assert.True(opaqueFeature.IsUpgradableRequest); await opaqueFeature.UpgradeAsync(); upgraded.SetResult(true); })) { using (Stream stream = await SendOpaqueRequestAsync("GET", address)) { Assert.True(await upgraded.Task.TimeoutAfter(TimeSpan.FromSeconds(1))); Assert.True(callbackCalled, "Callback not called"); } } } [ConditionalTheory] [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win8)] // See HTTP_VERB for known verbs [InlineData("UNKNOWN", null)] [InlineData("INVALID", null)] [InlineData("OPTIONS", null)] [InlineData("GET", null)] [InlineData("HEAD", null)] [InlineData("DELETE", null)] [InlineData("TRACE", null)] [InlineData("CONNECT", null)] [InlineData("TRACK", null)] [InlineData("MOVE", null)] [InlineData("COPY", null)] [InlineData("PROPFIND", null)] [InlineData("PROPPATCH", null)] [InlineData("MKCOL", null)] [InlineData("LOCK", null)] [InlineData("UNLOCK", null)] [InlineData("SEARCH", null)] [InlineData("CUSTOMVERB", null)] [InlineData("PATCH", null)] [InlineData("POST", "Content-Length: 0")] [InlineData("PUT", "Content-Length: 0")] public async Task OpaqueUpgrade_VariousMethodsUpgradeSendAndReceive_Success(string method, string extraHeader) { string address; using (Utilities.CreateHttpServer(out address, async httpContext => { try { httpContext.Response.Headers["Upgrade"] = "websocket"; // Win8.1 blocks anything but WebSockets var opaqueFeature = httpContext.Features.Get<IHttpUpgradeFeature>(); Assert.NotNull(opaqueFeature); Assert.True(opaqueFeature.IsUpgradableRequest); var opaqueStream = await opaqueFeature.UpgradeAsync(); byte[] buffer = new byte[100]; int read = await opaqueStream.ReadAsync(buffer, 0, buffer.Length); await opaqueStream.WriteAsync(buffer, 0, read); } catch (Exception ex) { await httpContext.Response.WriteAsync(ex.ToString()); } })) { using (Stream stream = await SendOpaqueRequestAsync(method, address, extraHeader)) { byte[] data = new byte[100]; await stream.WriteAsync(data, 0, 49); int read = await stream.ReadAsync(data, 0, data.Length); Assert.Equal(49, read); } } } [ConditionalTheory] [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win8)] // Http.Sys returns a 411 Length Required if PUT or POST does not specify content-length or chunked. [InlineData("POST", "Content-Length: 10")] [InlineData("POST", "Transfer-Encoding: chunked")] [InlineData("PUT", "Content-Length: 10")] [InlineData("PUT", "Transfer-Encoding: chunked")] [InlineData("CUSTOMVERB", "Content-Length: 10")] [InlineData("CUSTOMVERB", "Transfer-Encoding: chunked")] public async Task OpaqueUpgrade_InvalidMethodUpgrade_Disconnected(string method, string extraHeader) { string address; using (Utilities.CreateHttpServer(out address, async httpContext => { try { var opaqueFeature = httpContext.Features.Get<IHttpUpgradeFeature>(); Assert.NotNull(opaqueFeature); Assert.False(opaqueFeature.IsUpgradableRequest); } catch (Exception ex) { await httpContext.Response.WriteAsync(ex.ToString()); } })) { var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await SendOpaqueRequestAsync(method, address, extraHeader)); Assert.Equal("The response status code was incorrect: HTTP/1.1 200 OK", ex.Message); } } [ConditionalFact] [MinimumOSVersion(OperatingSystems.Windows, WindowsVersions.Win8)] public async Task OpaqueUpgrade_PostWithBodyAndUpgradeHeaders_Accepted() { using (Utilities.CreateHttpServer(out string address, async httpContext => { try { var opaqueFeature = httpContext.Features.Get<IHttpUpgradeFeature>(); Assert.NotNull(opaqueFeature); Assert.False(opaqueFeature.IsUpgradableRequest); } catch (Exception ex) { await httpContext.Response.WriteAsync(ex.ToString()); } })) { using var client = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Post, address); request.Headers.Connection.Add("upgrade"); request.Content = new StringContent("Hello World"); var response = await client.SendAsync(request); response.EnsureSuccessStatusCode(); } } private async Task<HttpResponseMessage> SendRequestAsync(string uri) { using (HttpClient client = new HttpClient()) { return await client.GetAsync(uri); } } // Returns a bidirectional opaque stream or throws if the upgrade fails private async Task<Stream> SendOpaqueRequestAsync(string method, string address, string extraHeader = null) { // Connect with a socket Uri uri = new Uri(address); TcpClient client = new TcpClient(); try { await client.ConnectAsync(uri.Host, uri.Port); NetworkStream stream = client.GetStream(); // Send an HTTP GET request byte[] requestBytes = BuildGetRequest(method, uri, extraHeader); await stream.WriteAsync(requestBytes, 0, requestBytes.Length); // Read the response headers, fail if it's not a 101 await ParseResponseAsync(stream); // Return the opaque network stream return stream; } catch (Exception) { ((IDisposable)client).Dispose(); throw; } } private byte[] BuildGetRequest(string method, Uri uri, string extraHeader) { StringBuilder builder = new StringBuilder(); builder.Append(method); builder.Append(" "); builder.Append(uri.PathAndQuery); builder.Append(" HTTP/1.1"); builder.AppendLine(); builder.Append("Host: "); builder.Append(uri.Host); builder.Append(':'); builder.Append(uri.Port); builder.AppendLine(); if (!string.IsNullOrEmpty(extraHeader)) { builder.AppendLine(extraHeader); } builder.AppendLine(); return Encoding.ASCII.GetBytes(builder.ToString()); } // Read the response headers, fail if it's not a 101 private async Task ParseResponseAsync(NetworkStream stream) { StreamReader reader = new StreamReader(stream); string statusLine = await reader.ReadLineAsync(); string[] parts = statusLine.Split(' '); if (int.Parse(parts[1], CultureInfo.InvariantCulture) != 101) { throw new InvalidOperationException("The response status code was incorrect: " + statusLine); } // Scan to the end of the headers while (!string.IsNullOrEmpty(reader.ReadLine())) { } } } }
#region File Description //----------------------------------------------------------------------------- // BasicEffect.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; #endregion namespace StockEffects { /// <summary> /// Built-in effect that supports optional texturing, vertex coloring, fog, and lighting. /// </summary> public class BasicEffect : Effect, IEffectMatrices, IEffectLights, IEffectFog { #region Effect Parameters EffectParameter textureParam; EffectParameter diffuseColorParam; EffectParameter emissiveColorParam; EffectParameter specularColorParam; EffectParameter specularPowerParam; EffectParameter eyePositionParam; EffectParameter fogColorParam; EffectParameter fogVectorParam; EffectParameter worldParam; EffectParameter worldInverseTransposeParam; EffectParameter worldViewProjParam; EffectParameter shaderIndexParam; #endregion #region Fields bool lightingEnabled; bool preferPerPixelLighting; bool oneLight; bool fogEnabled; bool textureEnabled; bool vertexColorEnabled; Matrix world = Matrix.Identity; Matrix view = Matrix.Identity; Matrix projection = Matrix.Identity; Matrix worldView; Vector3 diffuseColor = Vector3.One; Vector3 emissiveColor = Vector3.Zero; Vector3 ambientLightColor = Vector3.Zero; float alpha = 1; DirectionalLight light0; DirectionalLight light1; DirectionalLight light2; float fogStart = 0; float fogEnd = 1; EffectDirtyFlags dirtyFlags = EffectDirtyFlags.All; #endregion #region Public Properties /// <summary> /// Gets or sets the world matrix. /// </summary> public Matrix World { get { return world; } set { world = value; dirtyFlags |= EffectDirtyFlags.World | EffectDirtyFlags.WorldViewProj | EffectDirtyFlags.Fog; } } /// <summary> /// Gets or sets the view matrix. /// </summary> public Matrix View { get { return view; } set { view = value; dirtyFlags |= EffectDirtyFlags.WorldViewProj | EffectDirtyFlags.EyePosition | EffectDirtyFlags.Fog; } } /// <summary> /// Gets or sets the projection matrix. /// </summary> public Matrix Projection { get { return projection; } set { projection = value; dirtyFlags |= EffectDirtyFlags.WorldViewProj; } } /// <summary> /// Gets or sets the material diffuse color (range 0 to 1). /// </summary> public Vector3 DiffuseColor { get { return diffuseColor; } set { diffuseColor = value; dirtyFlags |= EffectDirtyFlags.MaterialColor; } } /// <summary> /// Gets or sets the material emissive color (range 0 to 1). /// </summary> public Vector3 EmissiveColor { get { return emissiveColor; } set { emissiveColor = value; dirtyFlags |= EffectDirtyFlags.MaterialColor; } } /// <summary> /// Gets or sets the material specular color (range 0 to 1). /// </summary> public Vector3 SpecularColor { get { return specularColorParam.GetValueVector3(); } set { specularColorParam.SetValue(value); } } /// <summary> /// Gets or sets the material specular power. /// </summary> public float SpecularPower { get { return specularPowerParam.GetValueSingle(); } set { specularPowerParam.SetValue(value); } } /// <summary> /// Gets or sets the material alpha. /// </summary> public float Alpha { get { return alpha; } set { alpha = value; dirtyFlags |= EffectDirtyFlags.MaterialColor; } } /// <summary> /// Gets or sets the lighting enable flag. /// </summary> public bool LightingEnabled { get { return lightingEnabled; } set { if (lightingEnabled != value) { lightingEnabled = value; dirtyFlags |= EffectDirtyFlags.ShaderIndex | EffectDirtyFlags.MaterialColor; } } } /// <summary> /// Gets or sets the per-pixel lighting prefer flag. /// </summary> public bool PreferPerPixelLighting { get { return preferPerPixelLighting; } set { if (preferPerPixelLighting != value) { preferPerPixelLighting = value; dirtyFlags |= EffectDirtyFlags.ShaderIndex; } } } /// <summary> /// Gets or sets the ambient light color (range 0 to 1). /// </summary> public Vector3 AmbientLightColor { get { return ambientLightColor; } set { ambientLightColor = value; dirtyFlags |= EffectDirtyFlags.MaterialColor; } } /// <summary> /// Gets the first directional light. /// </summary> public DirectionalLight DirectionalLight0 { get { return light0; } } /// <summary> /// Gets the second directional light. /// </summary> public DirectionalLight DirectionalLight1 { get { return light1; } } /// <summary> /// Gets the third directional light. /// </summary> public DirectionalLight DirectionalLight2 { get { return light2; } } /// <summary> /// Gets or sets the fog enable flag. /// </summary> public bool FogEnabled { get { return fogEnabled; } set { if (fogEnabled != value) { fogEnabled = value; dirtyFlags |= EffectDirtyFlags.ShaderIndex | EffectDirtyFlags.FogEnable; } } } /// <summary> /// Gets or sets the fog start distance. /// </summary> public float FogStart { get { return fogStart; } set { fogStart = value; dirtyFlags |= EffectDirtyFlags.Fog; } } /// <summary> /// Gets or sets the fog end distance. /// </summary> public float FogEnd { get { return fogEnd; } set { fogEnd = value; dirtyFlags |= EffectDirtyFlags.Fog; } } /// <summary> /// Gets or sets the fog color. /// </summary> public Vector3 FogColor { get { return fogColorParam.GetValueVector3(); } set { fogColorParam.SetValue(value); } } /// <summary> /// Gets or sets whether texturing is enabled. /// </summary> public bool TextureEnabled { get { return textureEnabled; } set { if (textureEnabled != value) { textureEnabled = value; dirtyFlags |= EffectDirtyFlags.ShaderIndex; } } } /// <summary> /// Gets or sets the current texture. /// </summary> public Texture2D Texture { get { return textureParam.GetValueTexture2D(); } set { textureParam.SetValue(value); } } /// <summary> /// Gets or sets whether vertex color is enabled. /// </summary> public bool VertexColorEnabled { get { return vertexColorEnabled; } set { if (vertexColorEnabled != value) { vertexColorEnabled = value; dirtyFlags |= EffectDirtyFlags.ShaderIndex; } } } #endregion #region Methods /// <summary> /// Creates a new BasicEffect with default parameter settings. /// </summary> public BasicEffect(GraphicsDevice device) : base(device, Resources.BasicEffect) { CacheEffectParameters(null); DirectionalLight0.Enabled = true; SpecularColor = Vector3.One; SpecularPower = 16; } /// <summary> /// Creates a new BasicEffect by cloning parameter settings from an existing instance. /// </summary> protected BasicEffect(BasicEffect cloneSource) : base(cloneSource) { CacheEffectParameters(cloneSource); lightingEnabled = cloneSource.lightingEnabled; preferPerPixelLighting = cloneSource.preferPerPixelLighting; fogEnabled = cloneSource.fogEnabled; textureEnabled = cloneSource.textureEnabled; vertexColorEnabled = cloneSource.vertexColorEnabled; world = cloneSource.world; view = cloneSource.view; projection = cloneSource.projection; diffuseColor = cloneSource.diffuseColor; emissiveColor = cloneSource.emissiveColor; ambientLightColor = cloneSource.ambientLightColor; alpha = cloneSource.alpha; fogStart = cloneSource.fogStart; fogEnd = cloneSource.fogEnd; } /// <summary> /// Creates a clone of the current BasicEffect instance. /// </summary> public override Effect Clone() { return new BasicEffect(this); } /// <summary> /// Sets up the standard key/fill/back lighting rig. /// </summary> public void EnableDefaultLighting() { LightingEnabled = true; AmbientLightColor = EffectHelpers.EnableDefaultLighting(light0, light1, light2); } /// <summary> /// Looks up shortcut references to our effect parameters. /// </summary> void CacheEffectParameters(BasicEffect cloneSource) { textureParam = Parameters["Texture"]; diffuseColorParam = Parameters["DiffuseColor"]; emissiveColorParam = Parameters["EmissiveColor"]; specularColorParam = Parameters["SpecularColor"]; specularPowerParam = Parameters["SpecularPower"]; eyePositionParam = Parameters["EyePosition"]; fogColorParam = Parameters["FogColor"]; fogVectorParam = Parameters["FogVector"]; worldParam = Parameters["World"]; worldInverseTransposeParam = Parameters["WorldInverseTranspose"]; worldViewProjParam = Parameters["WorldViewProj"]; shaderIndexParam = Parameters["ShaderIndex"]; light0 = new DirectionalLight(Parameters["DirLight0Direction"], Parameters["DirLight0DiffuseColor"], Parameters["DirLight0SpecularColor"], (cloneSource != null) ? cloneSource.light0 : null); light1 = new DirectionalLight(Parameters["DirLight1Direction"], Parameters["DirLight1DiffuseColor"], Parameters["DirLight1SpecularColor"], (cloneSource != null) ? cloneSource.light1 : null); light2 = new DirectionalLight(Parameters["DirLight2Direction"], Parameters["DirLight2DiffuseColor"], Parameters["DirLight2SpecularColor"], (cloneSource != null) ? cloneSource.light2 : null); } /// <summary> /// Lazily computes derived parameter values immediately before applying the effect. /// </summary> protected override void OnApply() { // Recompute the world+view+projection matrix or fog vector? dirtyFlags = EffectHelpers.SetWorldViewProjAndFog(dirtyFlags, ref world, ref view, ref projection, ref worldView, fogEnabled, fogStart, fogEnd, worldViewProjParam, fogVectorParam); // Recompute the diffuse/emissive/alpha material color parameters? if ((dirtyFlags & EffectDirtyFlags.MaterialColor) != 0) { EffectHelpers.SetMaterialColor(lightingEnabled, alpha, ref diffuseColor, ref emissiveColor, ref ambientLightColor, diffuseColorParam, emissiveColorParam); dirtyFlags &= ~EffectDirtyFlags.MaterialColor; } if (lightingEnabled) { // Recompute the world inverse transpose and eye position? dirtyFlags = EffectHelpers.SetLightingMatrices(dirtyFlags, ref world, ref view, worldParam, worldInverseTransposeParam, eyePositionParam); // Check if we can use the only-bother-with-the-first-light shader optimization. bool newOneLight = !light1.Enabled && !light2.Enabled; if (oneLight != newOneLight) { oneLight = newOneLight; dirtyFlags |= EffectDirtyFlags.ShaderIndex; } } // Recompute the shader index? if ((dirtyFlags & EffectDirtyFlags.ShaderIndex) != 0) { int shaderIndex = 0; if (!fogEnabled) shaderIndex += 1; if (vertexColorEnabled) shaderIndex += 2; if (textureEnabled) shaderIndex += 4; if (lightingEnabled) { if (preferPerPixelLighting) shaderIndex += 24; else if (oneLight) shaderIndex += 16; else shaderIndex += 8; } shaderIndexParam.SetValue(shaderIndex); dirtyFlags &= ~EffectDirtyFlags.ShaderIndex; } } #endregion } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the glacier-2012-06-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Glacier.Model { /// <summary> /// Describes an Amazon Glacier job. /// </summary> public partial class DescribeJobResponse : AmazonWebServiceResponse { private ActionCode _action; private string _archiveId; private string _archiveSHA256TreeHash; private long? _archiveSizeInBytes; private bool? _completed; private DateTime? _completionDate; private DateTime? _creationDate; private InventoryRetrievalJobDescription _inventoryRetrievalParameters; private long? _inventorySizeInBytes; private string _jobDescription; private string _jobId; private string _retrievalByteRange; private string _sha256TreeHash; private string _snsTopic; private StatusCode _statusCode; private string _statusMessage; private string _vaultARN; /// <summary> /// Gets and sets the property Action. /// <para> /// The job type. It is either ArchiveRetrieval or InventoryRetrieval. /// </para> /// </summary> public ActionCode Action { get { return this._action; } set { this._action = value; } } // Check to see if Action property is set internal bool IsSetAction() { return this._action != null; } /// <summary> /// Gets and sets the property ArchiveId. /// <para> /// For an ArchiveRetrieval job, this is the archive ID requested for download. Otherwise, /// this field is null. /// </para> /// </summary> public string ArchiveId { get { return this._archiveId; } set { this._archiveId = value; } } // Check to see if ArchiveId property is set internal bool IsSetArchiveId() { return this._archiveId != null; } /// <summary> /// Gets and sets the property ArchiveSHA256TreeHash. /// <para> /// The SHA256 tree hash of the entire archive for an archive retrieval. For inventory /// retrieval jobs, this field is null. /// </para> /// </summary> public string ArchiveSHA256TreeHash { get { return this._archiveSHA256TreeHash; } set { this._archiveSHA256TreeHash = value; } } // Check to see if ArchiveSHA256TreeHash property is set internal bool IsSetArchiveSHA256TreeHash() { return this._archiveSHA256TreeHash != null; } /// <summary> /// Gets and sets the property ArchiveSizeInBytes. /// <para> /// For an ArchiveRetrieval job, this is the size in bytes of the archive being requested /// for download. For the InventoryRetrieval job, the value is null. /// </para> /// </summary> public long ArchiveSizeInBytes { get { return this._archiveSizeInBytes.GetValueOrDefault(); } set { this._archiveSizeInBytes = value; } } // Check to see if ArchiveSizeInBytes property is set internal bool IsSetArchiveSizeInBytes() { return this._archiveSizeInBytes.HasValue; } /// <summary> /// Gets and sets the property Completed. /// <para> /// The job status. When a job is completed, you get the job's output. /// </para> /// </summary> public bool Completed { get { return this._completed.GetValueOrDefault(); } set { this._completed = value; } } // Check to see if Completed property is set internal bool IsSetCompleted() { return this._completed.HasValue; } /// <summary> /// Gets and sets the property CompletionDate. /// <para> /// The UTC time that the archive retrieval request completed. While the job is in progress, /// the value will be null. /// </para> /// </summary> public DateTime CompletionDate { get { return this._completionDate.GetValueOrDefault(); } set { this._completionDate = value; } } // Check to see if CompletionDate property is set internal bool IsSetCompletionDate() { return this._completionDate.HasValue; } /// <summary> /// Gets and sets the property CreationDate. /// <para> /// The UTC date when the job was created. A string representation of ISO 8601 date format, /// for example, "2012-03-20T17:03:43.221Z". /// </para> /// </summary> public DateTime CreationDate { get { return this._creationDate.GetValueOrDefault(); } set { this._creationDate = value; } } // Check to see if CreationDate property is set internal bool IsSetCreationDate() { return this._creationDate.HasValue; } /// <summary> /// Gets and sets the property InventoryRetrievalParameters. /// <para> /// Parameters used for range inventory retrieval. /// </para> /// </summary> public InventoryRetrievalJobDescription InventoryRetrievalParameters { get { return this._inventoryRetrievalParameters; } set { this._inventoryRetrievalParameters = value; } } // Check to see if InventoryRetrievalParameters property is set internal bool IsSetInventoryRetrievalParameters() { return this._inventoryRetrievalParameters != null; } /// <summary> /// Gets and sets the property InventorySizeInBytes. /// <para> /// For an InventoryRetrieval job, this is the size in bytes of the inventory requested /// for download. For the ArchiveRetrieval job, the value is null. /// </para> /// </summary> public long InventorySizeInBytes { get { return this._inventorySizeInBytes.GetValueOrDefault(); } set { this._inventorySizeInBytes = value; } } // Check to see if InventorySizeInBytes property is set internal bool IsSetInventorySizeInBytes() { return this._inventorySizeInBytes.HasValue; } /// <summary> /// Gets and sets the property JobDescription. /// <para> /// The job description you provided when you initiated the job. /// </para> /// </summary> public string JobDescription { get { return this._jobDescription; } set { this._jobDescription = value; } } // Check to see if JobDescription property is set internal bool IsSetJobDescription() { return this._jobDescription != null; } /// <summary> /// Gets and sets the property JobId. /// <para> /// An opaque string that identifies an Amazon Glacier job. /// </para> /// </summary> public string JobId { get { return this._jobId; } set { this._jobId = value; } } // Check to see if JobId property is set internal bool IsSetJobId() { return this._jobId != null; } /// <summary> /// Gets and sets the property RetrievalByteRange. /// <para> /// The retrieved byte range for archive retrieval jobs in the form "<i>StartByteValue</i>-<i>EndByteValue</i>" /// If no range was specified in the archive retrieval, then the whole archive is retrieved /// and <i>StartByteValue</i> equals 0 and <i>EndByteValue</i> equals the size of the /// archive minus 1. For inventory retrieval jobs this field is null. /// </para> /// </summary> public string RetrievalByteRange { get { return this._retrievalByteRange; } set { this._retrievalByteRange = value; } } // Check to see if RetrievalByteRange property is set internal bool IsSetRetrievalByteRange() { return this._retrievalByteRange != null; } /// <summary> /// Gets and sets the property SHA256TreeHash. /// <para> /// For an ArchiveRetrieval job, it is the checksum of the archive. Otherwise, the value /// is null. /// </para> /// /// <para> /// The SHA256 tree hash value for the requested range of an archive. If the Initiate /// a Job request for an archive specified a tree-hash aligned range, then this field /// returns a value. /// </para> /// /// <para> /// For the specific case when the whole archive is retrieved, this value is the same /// as the ArchiveSHA256TreeHash value. /// </para> /// /// <para> /// This field is null in the following situations: <ul> <li> /// <para> /// Archive retrieval jobs that specify a range that is not tree-hash aligned. /// </para> /// </li> </ul> <ul> <li> /// <para> /// Archival jobs that specify a range that is equal to the whole archive and the job /// status is InProgress. /// </para> /// </li> </ul> <ul> <li> /// <para> /// Inventory jobs. /// </para> /// </li> </ul> /// </para> /// </summary> public string SHA256TreeHash { get { return this._sha256TreeHash; } set { this._sha256TreeHash = value; } } // Check to see if SHA256TreeHash property is set internal bool IsSetSHA256TreeHash() { return this._sha256TreeHash != null; } /// <summary> /// Gets and sets the property SNSTopic. /// <para> /// An Amazon Simple Notification Service (Amazon SNS) topic that receives notification. /// </para> /// </summary> public string SNSTopic { get { return this._snsTopic; } set { this._snsTopic = value; } } // Check to see if SNSTopic property is set internal bool IsSetSNSTopic() { return this._snsTopic != null; } /// <summary> /// Gets and sets the property StatusCode. /// <para> /// The status code can be InProgress, Succeeded, or Failed, and indicates the status /// of the job. /// </para> /// </summary> public StatusCode StatusCode { get { return this._statusCode; } set { this._statusCode = value; } } // Check to see if StatusCode property is set internal bool IsSetStatusCode() { return this._statusCode != null; } /// <summary> /// Gets and sets the property StatusMessage. /// <para> /// A friendly message that describes the job status. /// </para> /// </summary> public string StatusMessage { get { return this._statusMessage; } set { this._statusMessage = value; } } // Check to see if StatusMessage property is set internal bool IsSetStatusMessage() { return this._statusMessage != null; } /// <summary> /// Gets and sets the property VaultARN. /// <para> /// The Amazon Resource Name (ARN) of the vault from which the archive retrieval was requested. /// </para> /// </summary> public string VaultARN { get { return this._vaultARN; } set { this._vaultARN = value; } } // Check to see if VaultARN property is set internal bool IsSetVaultARN() { return this._vaultARN != null; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation.Runspaces; namespace System.Management.Automation { internal class PowerShellExecutionHelper { #region Constructors // Creates a new PowerShellExecutionHelper with the PowerShell instance that will be used to execute the tab expansion commands // Used by the ISE internal PowerShellExecutionHelper(PowerShell powershell) { if (powershell == null) { throw PSTraceSource.NewArgumentNullException(nameof(powershell)); } CurrentPowerShell = powershell; } #endregion Constructors #region Fields and Properties // Gets and sets a flag set to false at the beginning of each tab completion and // set to true if a pipeline is stopped to indicate all commands should return empty matches internal bool CancelTabCompletion { get; set; } // Gets and sets the PowerShell instance used to run command completion commands // Used by the ISE internal PowerShell CurrentPowerShell { get; set; } // Returns true if this instance is currently executing a command internal bool IsRunning => CurrentPowerShell.InvocationStateInfo.State == PSInvocationState.Running; // Returns true if the command executed by this instance was stopped internal bool IsStopped => CurrentPowerShell.InvocationStateInfo.State == PSInvocationState.Stopped; #endregion Fields and Properties #region Command Execution internal Collection<PSObject> ExecuteCommand(string command) { Exception unused; return ExecuteCommand(command, true, out unused, null); } internal bool ExecuteCommandAndGetResultAsBool() { Exception exceptionThrown; Collection<PSObject> streamResults = ExecuteCurrentPowerShell(out exceptionThrown); if (exceptionThrown != null || streamResults == null || streamResults.Count == 0) { return false; } // we got back one or more objects. return (streamResults.Count > 1) || (LanguagePrimitives.IsTrue(streamResults[0])); } internal string ExecuteCommandAndGetResultAsString() { Exception exceptionThrown; Collection<PSObject> streamResults = ExecuteCurrentPowerShell(out exceptionThrown); if (exceptionThrown != null || streamResults == null || streamResults.Count == 0) { return null; } // we got back one or more objects. Pick off the first result. if (streamResults[0] == null) return string.Empty; // And convert the base object into a string. We can't use the proxied // ToString() on the PSObject because there is no default runspace // available. return SafeToString(streamResults[0]); } internal Collection<PSObject> ExecuteCommand(string command, bool isScript, out Exception exceptionThrown, Hashtable args) { Diagnostics.Assert(command != null, "caller to verify command is not null"); exceptionThrown = null; // This flag indicates a previous call to this method had its pipeline cancelled if (CancelTabCompletion) { return new Collection<PSObject>(); } CurrentPowerShell.AddCommand(command); Command cmd = new Command(command, isScript); if (args != null) { foreach (DictionaryEntry arg in args) { cmd.Parameters.Add((string)(arg.Key), arg.Value); } } Collection<PSObject> results = null; try { // blocks until all results are retrieved. // results = this.ExecuteCommand(cmd); // If this pipeline has been stopped lets set a flag to cancel all future tab completion calls // until the next completion if (IsStopped) { results = new Collection<PSObject>(); CancelTabCompletion = true; } } catch (Exception e) { exceptionThrown = e; } return results; } internal Collection<PSObject> ExecuteCurrentPowerShell(out Exception exceptionThrown, IEnumerable input = null) { exceptionThrown = null; // This flag indicates a previous call to this method had its pipeline cancelled if (CancelTabCompletion) { return new Collection<PSObject>(); } Collection<PSObject> results = null; try { results = CurrentPowerShell.Invoke(input); // If this pipeline has been stopped lets set a flag to cancel all future tab completion calls // until the next completion if (IsStopped) { results = new Collection<PSObject>(); CancelTabCompletion = true; } } catch (Exception e) { exceptionThrown = e; } finally { CurrentPowerShell.Commands.Clear(); } return results; } #endregion Command Execution #region Helpers /// <summary> /// Converts an object to a string safely... /// </summary> /// <param name="obj">The object to convert.</param> /// <returns>The result of the conversion...</returns> internal static string SafeToString(object obj) { if (obj == null) { return string.Empty; } try { PSObject pso = obj as PSObject; string result; if (pso != null) { object baseObject = pso.BaseObject; if (baseObject != null && baseObject is not PSCustomObject) result = baseObject.ToString(); else result = pso.ToString(); } else { result = obj.ToString(); } return result; } catch (Exception) { // We swallow all exceptions from command completion because we don't want the shell to crash return string.Empty; } } /// <summary> /// Converts an object to a string adn, if the string is not empty, adds it to the list. /// </summary> /// <param name="list">The list to update.</param> /// <param name="obj">The object to convert to a string...</param> internal static void SafeAddToStringList(List<string> list, object obj) { if (list == null) return; string result = SafeToString(obj); if (!string.IsNullOrEmpty(result)) list.Add(result); } #endregion Helpers } internal static class PowerShellExtensionHelpers { internal static PowerShell AddCommandWithPreferenceSetting(this PowerShellExecutionHelper helper, string command, Type type = null) { return helper.CurrentPowerShell.AddCommandWithPreferenceSetting(command, type); } internal static PowerShell AddCommandWithPreferenceSetting(this PowerShell powershell, string command, Type type = null) { Diagnostics.Assert(powershell != null, "the passed-in powershell cannot be null"); Diagnostics.Assert(!string.IsNullOrWhiteSpace(command), "the passed-in command name should not be null or whitespaces"); if (type != null) { var cmdletInfo = new CmdletInfo(command, type); powershell.AddCommand(cmdletInfo); } else { powershell.AddCommand(command); } powershell .AddParameter("ErrorAction", ActionPreference.Ignore) .AddParameter("WarningAction", ActionPreference.Ignore) .AddParameter("InformationAction", ActionPreference.Ignore) .AddParameter("Verbose", false) .AddParameter("Debug", false); return powershell; } } }
using System; using System.Collections.Generic; using System.Linq; using UnityEngine.Assertions; namespace UnityEngine.Rendering.PostProcessing { #if UNITY_2017_2_OR_NEWER using XRSettings = UnityEngine.XR.XRSettings; #elif UNITY_5_6_OR_NEWER using XRSettings = UnityEngine.VR.VRSettings; #endif // TODO: XMLDoc everything (?) [DisallowMultipleComponent, ExecuteInEditMode, ImageEffectAllowedInSceneView] [AddComponentMenu("Rendering/Post-process Layer", 1000)] [RequireComponent(typeof(Camera))] public sealed class PostProcessLayer : MonoBehaviour { public enum Antialiasing { None, FastApproximateAntialiasing, SubpixelMorphologicalAntialiasing, TemporalAntialiasing } // Settings public Transform volumeTrigger; public LayerMask volumeLayer; public bool stopNaNPropagation = true; // Builtins / hardcoded effects that don't benefit from volume blending public Antialiasing antialiasingMode = Antialiasing.None; public TemporalAntialiasing temporalAntialiasing; public SubpixelMorphologicalAntialiasing subpixelMorphologicalAntialiasing; public FastApproximateAntialiasing fastApproximateAntialiasing; public Fog fog; public Dithering dithering; public PostProcessDebugLayer debugLayer; [SerializeField] PostProcessResources m_Resources; // UI states [SerializeField] bool m_ShowToolkit; [SerializeField] bool m_ShowCustomSorter; // Will stop applying post-processing effects just before color grading is applied // Currently used to export to exr without color grading public bool breakBeforeColorGrading = false; // Pre-ordered custom user effects // These are automatically populated and made to work properly with the serialization // system AND the editor. Modify at your own risk. [Serializable] public sealed class SerializedBundleRef { // We can't serialize Type so use assemblyQualifiedName instead, we only need this at // init time anyway so it's fine public string assemblyQualifiedName; // Not serialized, is set/reset when deserialization kicks in public PostProcessBundle bundle; } [SerializeField] List<SerializedBundleRef> m_BeforeTransparentBundles; [SerializeField] List<SerializedBundleRef> m_BeforeStackBundles; [SerializeField] List<SerializedBundleRef> m_AfterStackBundles; public Dictionary<PostProcessEvent, List<SerializedBundleRef>> sortedBundles { get; private set; } // We need to keep track of bundle initialization because for some obscure reason, on // assembly reload a MonoBehavior's Editor OnEnable will be called BEFORE the MonoBehavior's // own OnEnable... So we'll use it to pre-init bundles if the layer inspector is opened and // the component hasn't been enabled yet. public bool haveBundlesBeenInited { get; private set; } // Settings/Renderer bundles mapped to settings types Dictionary<Type, PostProcessBundle> m_Bundles; PropertySheetFactory m_PropertySheetFactory; CommandBuffer m_LegacyCmdBufferBeforeReflections; CommandBuffer m_LegacyCmdBufferBeforeLighting; CommandBuffer m_LegacyCmdBufferOpaque; CommandBuffer m_LegacyCmdBuffer; Camera m_Camera; PostProcessRenderContext m_CurrentContext; LogHistogram m_LogHistogram; bool m_SettingsUpdateNeeded = true; bool m_IsRenderingInSceneView = false; TargetPool m_TargetPool; bool m_NaNKilled = false; // Recycled list - used to reduce GC stress when gathering active effects in a bundle list // on each frame readonly List<PostProcessEffectRenderer> m_ActiveEffects = new List<PostProcessEffectRenderer>(); readonly List<RenderTargetIdentifier> m_Targets = new List<RenderTargetIdentifier>(); void OnEnable() { Init(null); if (!haveBundlesBeenInited) InitBundles(); m_LogHistogram = new LogHistogram(); m_PropertySheetFactory = new PropertySheetFactory(); m_TargetPool = new TargetPool(); debugLayer.OnEnable(); if (RuntimeUtilities.scriptableRenderPipelineActive) return; InitLegacy(); } void InitLegacy() { m_LegacyCmdBufferBeforeReflections = new CommandBuffer { name = "Deferred Ambient Occlusion" }; m_LegacyCmdBufferBeforeLighting = new CommandBuffer { name = "Deferred Ambient Occlusion" }; m_LegacyCmdBufferOpaque = new CommandBuffer { name = "Opaque Only Post-processing" }; m_LegacyCmdBuffer = new CommandBuffer { name = "Post-processing" }; m_Camera = GetComponent<Camera>(); m_Camera.forceIntoRenderTexture = true; // Needed when running Forward / LDR / No MSAA m_Camera.AddCommandBuffer(CameraEvent.BeforeReflections, m_LegacyCmdBufferBeforeReflections); m_Camera.AddCommandBuffer(CameraEvent.BeforeLighting, m_LegacyCmdBufferBeforeLighting); m_Camera.AddCommandBuffer(CameraEvent.BeforeImageEffectsOpaque, m_LegacyCmdBufferOpaque); m_Camera.AddCommandBuffer(CameraEvent.BeforeImageEffects, m_LegacyCmdBuffer); // Internal context used if no SRP is set m_CurrentContext = new PostProcessRenderContext(); } public void Init(PostProcessResources resources) { if (resources != null) m_Resources = resources; RuntimeUtilities.CreateIfNull(ref temporalAntialiasing); RuntimeUtilities.CreateIfNull(ref subpixelMorphologicalAntialiasing); RuntimeUtilities.CreateIfNull(ref fastApproximateAntialiasing); RuntimeUtilities.CreateIfNull(ref dithering); RuntimeUtilities.CreateIfNull(ref fog); RuntimeUtilities.CreateIfNull(ref debugLayer); } public void InitBundles() { if (haveBundlesBeenInited) return; // Create these lists only once, the serialization system will take over after that RuntimeUtilities.CreateIfNull(ref m_BeforeTransparentBundles); RuntimeUtilities.CreateIfNull(ref m_BeforeStackBundles); RuntimeUtilities.CreateIfNull(ref m_AfterStackBundles); // Create a bundle for each effect type m_Bundles = new Dictionary<Type, PostProcessBundle>(); foreach (var type in PostProcessManager.instance.settingsTypes.Keys) { var settings = (PostProcessEffectSettings)ScriptableObject.CreateInstance(type); var bundle = new PostProcessBundle(settings); m_Bundles.Add(type, bundle); } // Update sorted lists with newly added or removed effects in the assemblies UpdateBundleSortList(m_BeforeTransparentBundles, PostProcessEvent.BeforeTransparent); UpdateBundleSortList(m_BeforeStackBundles, PostProcessEvent.BeforeStack); UpdateBundleSortList(m_AfterStackBundles, PostProcessEvent.AfterStack); // Push all sorted lists in a dictionary for easier access sortedBundles = new Dictionary<PostProcessEvent, List<SerializedBundleRef>>(new PostProcessEventComparer()) { { PostProcessEvent.BeforeTransparent, m_BeforeTransparentBundles }, { PostProcessEvent.BeforeStack, m_BeforeStackBundles }, { PostProcessEvent.AfterStack, m_AfterStackBundles } }; // Done haveBundlesBeenInited = true; } void UpdateBundleSortList(List<SerializedBundleRef> sortedList, PostProcessEvent evt) { // First get all effects associated with the injection point var effects = m_Bundles.Where(kvp => kvp.Value.attribute.eventType == evt && !kvp.Value.attribute.builtinEffect) .Select(kvp => kvp.Value) .ToList(); // Remove types that don't exist anymore sortedList.RemoveAll(x => { string searchStr = x.assemblyQualifiedName; return !effects.Exists(b => b.settings.GetType().AssemblyQualifiedName == searchStr); }); // Add new ones foreach (var effect in effects) { string typeName = effect.settings.GetType().AssemblyQualifiedName; if (!sortedList.Exists(b => b.assemblyQualifiedName == typeName)) { var sbr = new SerializedBundleRef { assemblyQualifiedName = typeName }; sortedList.Add(sbr); } } // Link internal references foreach (var effect in sortedList) { string typeName = effect.assemblyQualifiedName; var bundle = effects.Find(b => b.settings.GetType().AssemblyQualifiedName == typeName); effect.bundle = bundle; } } void OnDisable() { if (!RuntimeUtilities.scriptableRenderPipelineActive) { m_Camera.RemoveCommandBuffer(CameraEvent.BeforeReflections, m_LegacyCmdBufferBeforeReflections); m_Camera.RemoveCommandBuffer(CameraEvent.BeforeLighting, m_LegacyCmdBufferBeforeLighting); m_Camera.RemoveCommandBuffer(CameraEvent.BeforeImageEffectsOpaque, m_LegacyCmdBufferOpaque); m_Camera.RemoveCommandBuffer(CameraEvent.BeforeImageEffects, m_LegacyCmdBuffer); } temporalAntialiasing.Release(); m_LogHistogram.Release(); foreach (var bundle in m_Bundles.Values) bundle.Release(); m_Bundles.Clear(); m_PropertySheetFactory.Release(); if (debugLayer != null) debugLayer.OnDisable(); // Might be an issue if several layers are blending in the same frame... TextureLerper.instance.Clear(); haveBundlesBeenInited = false; } // Called everytime the user resets the component from the inspector and more importantly // the first time it's added to a GameObject. As we don't have added/removed event for // components, this will do fine void Reset() { volumeTrigger = transform; } void OnPreCull() { // Unused in scriptable render pipelines if (RuntimeUtilities.scriptableRenderPipelineActive) return; if (m_Camera == null || m_CurrentContext == null) InitLegacy(); // Resets the projection matrix from previous frame in case TAA was enabled. // We also need to force reset the non-jittered projection matrix here as it's not done // when ResetProjectionMatrix() is called and will break transparent rendering if TAA // is switched off and the FOV or any other camera property changes. m_Camera.ResetProjectionMatrix(); m_Camera.nonJitteredProjectionMatrix = m_Camera.projectionMatrix; if (m_Camera.stereoEnabled) { m_Camera.ResetStereoProjectionMatrices(); Shader.SetGlobalFloat(ShaderIDs.RenderViewportScaleFactor, XRSettings.renderViewportScale); } else { Shader.SetGlobalFloat(ShaderIDs.RenderViewportScaleFactor, 1.0f); } BuildCommandBuffers(); } void OnPreRender() { // Unused in scriptable render pipelines // Only needed for multi-pass stereo right eye if (RuntimeUtilities.scriptableRenderPipelineActive || (m_Camera.stereoActiveEye != Camera.MonoOrStereoscopicEye.Right)) return; BuildCommandBuffers(); } void BuildCommandBuffers() { var context = m_CurrentContext; var sourceFormat = m_Camera.allowHDR ? RuntimeUtilities.defaultHDRRenderTextureFormat : RenderTextureFormat.Default; if (!RuntimeUtilities.isFloatingPointFormat(sourceFormat)) m_NaNKilled = true; context.Reset(); context.camera = m_Camera; context.sourceFormat = sourceFormat; // TODO: Investigate retaining command buffers on XR multi-pass right eye m_LegacyCmdBufferBeforeReflections.Clear(); m_LegacyCmdBufferBeforeLighting.Clear(); m_LegacyCmdBufferOpaque.Clear(); m_LegacyCmdBuffer.Clear(); SetupContext(context); context.command = m_LegacyCmdBufferOpaque; TextureLerper.instance.BeginFrame(context); UpdateSettingsIfNeeded(context); // Lighting & opaque-only effects var aoBundle = GetBundle<AmbientOcclusion>(); var aoSettings = aoBundle.CastSettings<AmbientOcclusion>(); var aoRenderer = aoBundle.CastRenderer<AmbientOcclusionRenderer>(); bool aoSupported = aoSettings.IsEnabledAndSupported(context); bool aoAmbientOnly = aoRenderer.IsAmbientOnly(context); bool isAmbientOcclusionDeferred = aoSupported && aoAmbientOnly; bool isAmbientOcclusionOpaque = aoSupported && !aoAmbientOnly; var ssrBundle = GetBundle<ScreenSpaceReflections>(); var ssrSettings = ssrBundle.settings; var ssrRenderer = ssrBundle.renderer; bool isScreenSpaceReflectionsActive = ssrSettings.IsEnabledAndSupported(context); // Ambient-only AO is a special case and has to be done in separate command buffers if (isAmbientOcclusionDeferred) { var ao = aoRenderer.Get(); // Render as soon as possible - should be done async in SRPs when available context.command = m_LegacyCmdBufferBeforeReflections; ao.RenderAmbientOnly(context); // Composite with GBuffer right before the lighting pass context.command = m_LegacyCmdBufferBeforeLighting; ao.CompositeAmbientOnly(context); } else if (isAmbientOcclusionOpaque) { context.command = m_LegacyCmdBufferOpaque; aoRenderer.Get().RenderAfterOpaque(context); } bool isFogActive = fog.IsEnabledAndSupported(context); bool hasCustomOpaqueOnlyEffects = HasOpaqueOnlyEffects(context); int opaqueOnlyEffects = 0; opaqueOnlyEffects += isScreenSpaceReflectionsActive ? 1 : 0; opaqueOnlyEffects += isFogActive ? 1 : 0; opaqueOnlyEffects += hasCustomOpaqueOnlyEffects ? 1 : 0; // This works on right eye because it is resolved/populated at runtime var cameraTarget = new RenderTargetIdentifier(BuiltinRenderTextureType.CameraTarget); if (opaqueOnlyEffects > 0) { var cmd = m_LegacyCmdBufferOpaque; context.command = cmd; // We need to use the internal Blit method to copy the camera target or it'll fail // on tiled GPU as it won't be able to resolve int tempTarget0 = m_TargetPool.Get(); context.GetScreenSpaceTemporaryRT(cmd, tempTarget0, 0, sourceFormat); cmd.Blit(cameraTarget, tempTarget0); context.source = tempTarget0; int tempTarget1 = -1; if (opaqueOnlyEffects > 1) { tempTarget1 = m_TargetPool.Get(); context.GetScreenSpaceTemporaryRT(cmd, tempTarget1, 0, sourceFormat); context.destination = tempTarget1; } else context.destination = cameraTarget; if (isScreenSpaceReflectionsActive) { ssrRenderer.Render(context); opaqueOnlyEffects--; var prevSource = context.source; context.source = context.destination; context.destination = opaqueOnlyEffects == 1 ? cameraTarget : prevSource; } if (isFogActive) { fog.Render(context); opaqueOnlyEffects--; var prevSource = context.source; context.source = context.destination; context.destination = opaqueOnlyEffects == 1 ? cameraTarget : prevSource; } if (hasCustomOpaqueOnlyEffects) RenderOpaqueOnly(context); if (opaqueOnlyEffects > 1) cmd.ReleaseTemporaryRT(tempTarget1); cmd.ReleaseTemporaryRT(tempTarget0); } // Post-transparency stack // Same as before, first blit needs to use the builtin Blit command to properly handle // tiled GPUs int tempRt = m_TargetPool.Get(); context.GetScreenSpaceTemporaryRT(m_LegacyCmdBuffer, tempRt, 0, sourceFormat, RenderTextureReadWrite.sRGB); m_LegacyCmdBuffer.Blit(cameraTarget, tempRt, RuntimeUtilities.copyStdMaterial, stopNaNPropagation ? 1 : 0); if (!m_NaNKilled) m_NaNKilled = stopNaNPropagation; context.command = m_LegacyCmdBuffer; context.source = tempRt; context.destination = cameraTarget; Render(context); m_LegacyCmdBuffer.ReleaseTemporaryRT(tempRt); } void OnPostRender() { // Unused in scriptable render pipelines if (RuntimeUtilities.scriptableRenderPipelineActive) return; if (m_CurrentContext.IsTemporalAntialiasingActive()) { m_Camera.ResetProjectionMatrix(); if (m_CurrentContext.stereoActive) { if (RuntimeUtilities.isSinglePassStereoEnabled || m_Camera.stereoActiveEye == Camera.MonoOrStereoscopicEye.Right) m_Camera.ResetStereoProjectionMatrices(); } } } public PostProcessBundle GetBundle<T>() where T : PostProcessEffectSettings { return GetBundle(typeof(T)); } public PostProcessBundle GetBundle(Type settingsType) { Assert.IsTrue(m_Bundles.ContainsKey(settingsType), "Invalid type"); return m_Bundles[settingsType]; } public T GetSettings<T>() where T : PostProcessEffectSettings { return GetBundle<T>().CastSettings<T>(); } public void BakeMSVOMap(CommandBuffer cmd, Camera camera, RenderTargetIdentifier destination, RenderTargetIdentifier? depthMap, bool invert) { var bundle = GetBundle<AmbientOcclusion>(); var renderer = bundle.CastRenderer<AmbientOcclusionRenderer>().GetMultiScaleVO(); renderer.SetResources(m_Resources); renderer.GenerateAOMap(cmd, camera, destination, depthMap, invert); } internal void OverrideSettings(List<PostProcessEffectSettings> baseSettings, float interpFactor) { // Go through all settings & overriden parameters for the given volume and lerp values foreach (var settings in baseSettings) { if (!settings.active) continue; var target = GetBundle(settings.GetType()).settings; int count = settings.parameters.Count; for (int i = 0; i < count; i++) { var toParam = settings.parameters[i]; if (toParam.overrideState) { var fromParam = target.parameters[i]; fromParam.Interp(fromParam, toParam, interpFactor); } } } } // In the legacy render loop you have to explicitely set flags on camera to tell that you // need depth, depth+normals or motion vectors... This won't have any effect with most // scriptable render pipelines. void SetLegacyCameraFlags(PostProcessRenderContext context) { var flags = context.camera.depthTextureMode; foreach (var bundle in m_Bundles) { if (bundle.Value.settings.IsEnabledAndSupported(context)) flags |= bundle.Value.renderer.GetCameraFlags(); } // Special case for AA & lighting effects if (context.IsTemporalAntialiasingActive()) flags |= temporalAntialiasing.GetCameraFlags(); if (fog.IsEnabledAndSupported(context)) flags |= fog.GetCameraFlags(); if (debugLayer.debugOverlay != DebugOverlay.None) flags |= debugLayer.GetCameraFlags(); context.camera.depthTextureMode = flags; } // Call this function whenever you need to reset any temporal effect (TAA, Motion Blur etc). // Mainly used when doing camera cuts. public void ResetHistory() { foreach (var bundle in m_Bundles) bundle.Value.ResetHistory(); temporalAntialiasing.ResetHistory(); } public bool HasOpaqueOnlyEffects(PostProcessRenderContext context) { return HasActiveEffects(PostProcessEvent.BeforeTransparent, context); } public bool HasActiveEffects(PostProcessEvent evt, PostProcessRenderContext context) { var list = sortedBundles[evt]; foreach (var item in list) { if (item.bundle.settings.IsEnabledAndSupported(context)) return true; } return false; } void SetupContext(PostProcessRenderContext context) { m_IsRenderingInSceneView = context.camera.cameraType == CameraType.SceneView; context.isSceneView = m_IsRenderingInSceneView; context.resources = m_Resources; context.propertySheets = m_PropertySheetFactory; context.debugLayer = debugLayer; context.antialiasing = antialiasingMode; context.temporalAntialiasing = temporalAntialiasing; context.logHistogram = m_LogHistogram; SetLegacyCameraFlags(context); // Prepare debug overlay debugLayer.SetFrameSize(context.width, context.height); // Unsafe to keep this around but we need it for OnGUI events for debug views // Will be removed eventually m_CurrentContext = context; } void UpdateSettingsIfNeeded(PostProcessRenderContext context) { if (m_SettingsUpdateNeeded) { context.command.BeginSample("VolumeBlending"); PostProcessManager.instance.UpdateSettings(this, context.camera); context.command.EndSample("VolumeBlending"); m_TargetPool.Reset(); // TODO: fix me once VR support is in SRP // Needed in SRP so that _RenderViewportScaleFactor isn't 0 if (RuntimeUtilities.scriptableRenderPipelineActive) Shader.SetGlobalFloat(ShaderIDs.RenderViewportScaleFactor, 1f); } m_SettingsUpdateNeeded = false; } // Renders before-transparent effects. // Make sure you check `HasOpaqueOnlyEffects()` before calling this method as it won't // automatically blit source into destination if no opaque effects are active. public void RenderOpaqueOnly(PostProcessRenderContext context) { if (RuntimeUtilities.scriptableRenderPipelineActive) SetupContext(context); TextureLerper.instance.BeginFrame(context); // Update & override layer settings first (volume blending), will only be done once per // frame, either here or in Render() if there isn't any opaque-only effect to render. UpdateSettingsIfNeeded(context); RenderList(sortedBundles[PostProcessEvent.BeforeTransparent], context, "OpaqueOnly"); } // Renders everything not opaque-only // // Current order of operation is as following: // 1. Pre-stack // 2. Built-in stack // 3. Post-stack // 4. Built-in final pass // // Final pass should be skipped when outputting to a HDR display. public void Render(PostProcessRenderContext context) { if (RuntimeUtilities.scriptableRenderPipelineActive) SetupContext(context); TextureLerper.instance.BeginFrame(context); var cmd = context.command; // Update & override layer settings first (volume blending) if the opaque only pass // hasn't been called this frame. UpdateSettingsIfNeeded(context); // Do a NaN killing pass if needed int lastTarget = -1; if (stopNaNPropagation && !m_NaNKilled) { lastTarget = m_TargetPool.Get(); context.GetScreenSpaceTemporaryRT(cmd, lastTarget, 0, context.sourceFormat); cmd.BlitFullscreenTriangle(context.source, lastTarget, RuntimeUtilities.copySheet, 1); context.source = lastTarget; m_NaNKilled = true; } // Do temporal anti-aliasing first if (context.IsTemporalAntialiasingActive()) { if (!RuntimeUtilities.scriptableRenderPipelineActive) { if (context.stereoActive) { // We only need to configure all of this once for stereo, during OnPreCull if (context.camera.stereoActiveEye != Camera.MonoOrStereoscopicEye.Right) temporalAntialiasing.ConfigureStereoJitteredProjectionMatrices(context); } else { temporalAntialiasing.ConfigureJitteredProjectionMatrix(context); } } var taaTarget = m_TargetPool.Get(); var finalDestination = context.destination; context.GetScreenSpaceTemporaryRT(cmd, taaTarget, 0, context.sourceFormat); context.destination = taaTarget; temporalAntialiasing.Render(context); context.source = taaTarget; context.destination = finalDestination; if (lastTarget > -1) cmd.ReleaseTemporaryRT(lastTarget); lastTarget = taaTarget; } bool hasBeforeStackEffects = HasActiveEffects(PostProcessEvent.BeforeStack, context); bool hasAfterStackEffects = HasActiveEffects(PostProcessEvent.AfterStack, context) && !breakBeforeColorGrading; bool needsFinalPass = (hasAfterStackEffects || (antialiasingMode == Antialiasing.FastApproximateAntialiasing) || (antialiasingMode == Antialiasing.SubpixelMorphologicalAntialiasing && subpixelMorphologicalAntialiasing.IsSupported())) && !breakBeforeColorGrading; // Right before the builtin stack if (hasBeforeStackEffects) lastTarget = RenderInjectionPoint(PostProcessEvent.BeforeStack, context, "BeforeStack", lastTarget); // Builtin stack lastTarget = RenderBuiltins(context, !needsFinalPass, lastTarget); // After the builtin stack but before the final pass (before FXAA & Dithering) if (hasAfterStackEffects) lastTarget = RenderInjectionPoint(PostProcessEvent.AfterStack, context, "AfterStack", lastTarget); // And close with the final pass if (needsFinalPass) RenderFinalPass(context, lastTarget); // Render debug monitors & overlay if requested debugLayer.RenderSpecialOverlays(context); debugLayer.RenderMonitors(context); // End frame cleanup TextureLerper.instance.EndFrame(); debugLayer.EndFrame(); m_SettingsUpdateNeeded = true; m_NaNKilled = false; } int RenderInjectionPoint(PostProcessEvent evt, PostProcessRenderContext context, string marker, int releaseTargetAfterUse = -1) { int tempTarget = m_TargetPool.Get(); var finalDestination = context.destination; var cmd = context.command; context.GetScreenSpaceTemporaryRT(cmd, tempTarget, 0, context.sourceFormat); context.destination = tempTarget; RenderList(sortedBundles[evt], context, marker); context.source = tempTarget; context.destination = finalDestination; if (releaseTargetAfterUse > -1) cmd.ReleaseTemporaryRT(releaseTargetAfterUse); return tempTarget; } void RenderList(List<SerializedBundleRef> list, PostProcessRenderContext context, string marker) { var cmd = context.command; cmd.BeginSample(marker); // First gather active effects - we need this to manage render targets more efficiently m_ActiveEffects.Clear(); for (int i = 0; i < list.Count; i++) { var effect = list[i].bundle; if (effect.settings.IsEnabledAndSupported(context)) { if (!context.isSceneView || (context.isSceneView && effect.attribute.allowInSceneView)) m_ActiveEffects.Add(effect.renderer); } } int count = m_ActiveEffects.Count; // If there's only one active effect, we can simply execute it and skip the rest if (count == 1) { m_ActiveEffects[0].Render(context); } else { // Else create the target chain m_Targets.Clear(); m_Targets.Add(context.source); // First target is always source int tempTarget1 = m_TargetPool.Get(); int tempTarget2 = m_TargetPool.Get(); for (int i = 0; i < count - 1; i++) m_Targets.Add(i % 2 == 0 ? tempTarget1 : tempTarget2); m_Targets.Add(context.destination); // Last target is always destination // Render context.GetScreenSpaceTemporaryRT(cmd, tempTarget1, 0, context.sourceFormat); if (count > 2) context.GetScreenSpaceTemporaryRT(cmd, tempTarget2, 0, context.sourceFormat); for (int i = 0; i < count; i++) { context.source = m_Targets[i]; context.destination = m_Targets[i + 1]; m_ActiveEffects[i].Render(context); } cmd.ReleaseTemporaryRT(tempTarget1); if (count > 2) cmd.ReleaseTemporaryRT(tempTarget2); } cmd.EndSample(marker); } void ApplyFlip(PostProcessRenderContext context, MaterialPropertyBlock properties) { if (context.flip && !context.isSceneView) properties.SetVector(ShaderIDs.UVTransform, new Vector4(1.0f, 1.0f, 0.0f, 0.0f)); else ApplyDefaultFlip(properties); } void ApplyDefaultFlip(MaterialPropertyBlock properties) { properties.SetVector(ShaderIDs.UVTransform, SystemInfo.graphicsUVStartsAtTop ? new Vector4(1.0f, -1.0f, 0.0f, 1.0f) : new Vector4(1.0f, 1.0f, 0.0f, 0.0f)); } int RenderBuiltins(PostProcessRenderContext context, bool isFinalPass, int releaseTargetAfterUse = -1) { var uberSheet = context.propertySheets.Get(context.resources.shaders.uber); uberSheet.ClearKeywords(); uberSheet.properties.Clear(); context.uberSheet = uberSheet; context.autoExposureTexture = RuntimeUtilities.whiteTexture; context.bloomBufferNameID = -1; var cmd = context.command; cmd.BeginSample("BuiltinStack"); int tempTarget = -1; var finalDestination = context.destination; if (!isFinalPass) { // Render to an intermediate target as this won't be the final pass tempTarget = m_TargetPool.Get(); context.GetScreenSpaceTemporaryRT(cmd, tempTarget, 0, context.sourceFormat); context.destination = tempTarget; // Handle FXAA's keep alpha mode if (antialiasingMode == Antialiasing.FastApproximateAntialiasing && !fastApproximateAntialiasing.keepAlpha) uberSheet.properties.SetFloat(ShaderIDs.LumaInAlpha, 1f); } // Depth of field final combination pass used to be done in Uber which led to artifacts // when used at the same time as Bloom (because both effects used the same source, so // the stronger bloom was, the more DoF was eaten away in out of focus areas) int depthOfFieldTarget = RenderEffect<DepthOfField>(context, true); // Motion blur is a separate pass - could potentially be done after DoF depending on the // kind of results you're looking for... int motionBlurTarget = RenderEffect<MotionBlur>(context, true); // Prepare exposure histogram if needed if (ShouldGenerateLogHistogram(context)) m_LogHistogram.Generate(context); // Uber effects RenderEffect<AutoExposure>(context); uberSheet.properties.SetTexture(ShaderIDs.AutoExposureTex, context.autoExposureTexture); RenderEffect<LensDistortion>(context); RenderEffect<ChromaticAberration>(context); RenderEffect<Bloom>(context); RenderEffect<Vignette>(context); RenderEffect<Grain>(context); if (!breakBeforeColorGrading) RenderEffect<ColorGrading>(context); if (isFinalPass) { uberSheet.EnableKeyword("FINALPASS"); dithering.Render(context); ApplyFlip(context, uberSheet.properties); } else { ApplyDefaultFlip(uberSheet.properties); } cmd.BlitFullscreenTriangle(context.source, context.destination, uberSheet, 0); context.source = context.destination; context.destination = finalDestination; if (releaseTargetAfterUse > -1) cmd.ReleaseTemporaryRT(releaseTargetAfterUse); if (motionBlurTarget > -1) cmd.ReleaseTemporaryRT(motionBlurTarget); if (depthOfFieldTarget > -1) cmd.ReleaseTemporaryRT(depthOfFieldTarget); if (context.bloomBufferNameID > -1) cmd.ReleaseTemporaryRT(context.bloomBufferNameID); cmd.EndSample("BuiltinStack"); return tempTarget; } // This pass will have to be disabled for HDR screen output as it's an LDR pass void RenderFinalPass(PostProcessRenderContext context, int releaseTargetAfterUse = -1) { var cmd = context.command; cmd.BeginSample("FinalPass"); if (breakBeforeColorGrading) { var sheet = context.propertySheets.Get(context.resources.shaders.discardAlpha); cmd.BlitFullscreenTriangle(context.source, context.destination, sheet, 0); } else { var uberSheet = context.propertySheets.Get(context.resources.shaders.finalPass); uberSheet.ClearKeywords(); uberSheet.properties.Clear(); context.uberSheet = uberSheet; int tempTarget = -1; if (antialiasingMode == Antialiasing.FastApproximateAntialiasing) { uberSheet.EnableKeyword(fastApproximateAntialiasing.fastMode ? "FXAA_LOW" : "FXAA" ); if (fastApproximateAntialiasing.keepAlpha) uberSheet.EnableKeyword("FXAA_KEEP_ALPHA"); } else if (antialiasingMode == Antialiasing.SubpixelMorphologicalAntialiasing && subpixelMorphologicalAntialiasing.IsSupported()) { tempTarget = m_TargetPool.Get(); var finalDestination = context.destination; context.GetScreenSpaceTemporaryRT(context.command, tempTarget, 0, context.sourceFormat); context.destination = tempTarget; subpixelMorphologicalAntialiasing.Render(context); context.source = tempTarget; context.destination = finalDestination; } dithering.Render(context); ApplyFlip(context, uberSheet.properties); cmd.BlitFullscreenTriangle(context.source, context.destination, uberSheet, 0); if (tempTarget > -1) cmd.ReleaseTemporaryRT(tempTarget); } if (releaseTargetAfterUse > -1) cmd.ReleaseTemporaryRT(releaseTargetAfterUse); cmd.EndSample("FinalPass"); } int RenderEffect<T>(PostProcessRenderContext context, bool useTempTarget = false) where T : PostProcessEffectSettings { var effect = GetBundle<T>(); if (!effect.settings.IsEnabledAndSupported(context)) return -1; if (m_IsRenderingInSceneView && !effect.attribute.allowInSceneView) return -1; if (!useTempTarget) { effect.renderer.Render(context); return -1; } var finalDestination = context.destination; var tempTarget = m_TargetPool.Get(); context.GetScreenSpaceTemporaryRT(context.command, tempTarget, 0, context.sourceFormat); context.destination = tempTarget; effect.renderer.Render(context); context.source = tempTarget; context.destination = finalDestination; return tempTarget; } bool ShouldGenerateLogHistogram(PostProcessRenderContext context) { bool autoExpo = GetBundle<AutoExposure>().settings.IsEnabledAndSupported(context); bool lightMeter = debugLayer.lightMeter.IsRequestedAndSupported(context); return autoExpo || lightMeter; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using puzzlegen.relationship; public class PlayState : MonoBehaviour { // Place spawnable prefabs here public GameObject playerPrefab, wallPrefab, ladderPrefab, puzzleItemPrefab, goblinPrefab, spikePrefab; // For playing global audio public AudioClip pickupClip, talkClip, lockClip; // The popup text for item descriptions public GameObject popupTextPrefab; private enum GameState { PAUSE_STATE, RUN_STATE, } private GameState _currentState = GameState.RUN_STATE; // Singleton pattern private static PlayState _instance; public static PlayState instance { get { return _instance; } } // For generating the same level again on a reset public static bool seedGenerate = false; private static int _currentSeed; // The Inventory private Inventory _inventory; public Inventory inventory { get { return _inventory; } } // The generate game private ProcGame _currentGame; // Player and room information private Player _player; public Player player { get { return _player; } } private Room _currentRoom; private tk2dSprite _floorSprite; private tk2dTextMesh _popupText; private AudioSource _audioSource; // Grid variables (might need to make these correspond to different rooms if possible private List<GridPiece> _gridPieces = new List<GridPiece>(); // Current grid accessible to every piece while they're making decisions private List<GridPiece>[,] _currentGrid; // The claimed grid for recording claimed positions during a turn private List<GridPiece>[,] _claimedGrid; // The pieces that will be removed at the end of the update private List<GridPiece> _piecesToRemove; private List<GridPiece> _piecesToDestroy; public int gridX { get { return (int)transform.position.x; } } public int gridY { get { return (int)transform.position.y; } } private int _gridWidth, _gridHeight; public int gridWidth { get { return _gridWidth; } set { _gridWidth = value; } } public int gridHeight { get { return _gridHeight; } set { _gridHeight = value; } } protected bool _hasSandwich = false; public void sandwichGet() { _hasSandwich = true; } protected bool _npcTextShowing = false; public bool npcTextShowing { get { return _npcTextShowing; } set { _npcTextShowing = value; } } protected bool _shouldHidePopupText = true; public void setPopupText(string text, Vector2 textGridPos) { _shouldHidePopupText = false; float textX = textGridPos.x; if (textX < 2) textX = 2; if (textX > 13) textX = 13; float textY = textGridPos.y+1; _popupText.anchor = TextAnchor.LowerCenter; if (textY > Globals.ROOM_HEIGHT-2) { textY = textGridPos.y; _popupText.anchor = TextAnchor.UpperCenter; } Vector2 actualPos = toActualCoordinates(new Vector2(textX, textY)); _popupText.transform.localPosition = new Vector3(actualPos.x, actualPos.y-Globals.CELL_SIZE/2, _popupText.transform.localPosition.z); _popupText.text = text; _popupText.Commit(); _popupText.gameObject.SetActive(true); } // For drawing dialogue next to the mouse public void setMousePopupText(string text, Vector2 mousePos) { _shouldHidePopupText = false; float textX = mousePos.x; if (textX < 2*Globals.CELL_SIZE) textX = 2*Globals.CELL_SIZE; if (textX > 14*Globals.CELL_SIZE) textX = 14*Globals.CELL_SIZE; float textY = mousePos.y+Globals.CELL_SIZE/2; _popupText.anchor = TextAnchor.LowerCenter; if (textY > Globals.CELL_SIZE*(Globals.ROOM_HEIGHT-1)+gridY) { _popupText.anchor = TextAnchor.LowerCenter; textY = Globals.CELL_SIZE*(Globals.ROOM_HEIGHT-1)+gridY; } _popupText.transform.position = new Vector3(textX, textY, _popupText.transform.position.z); _popupText.text = text; _popupText.Commit(); _popupText.gameObject.SetActive(true); } // For drawing temporary text on the screen public void addTempText(string text, Vector2 textGridPos, float duration) { GameObject textObj = GameObject.Instantiate(popupTextPrefab) as GameObject; textObj.transform.parent = transform; tk2dTextMesh textToAdd = textObj.GetComponent<tk2dTextMesh>(); TemporaryText tempText = textObj.AddComponent<TemporaryText>(); tempText.timeVisible = duration; float textX = textGridPos.x; if (textX < 2) textX = 2; if (textX > 13) textX = 13; float textY = textGridPos.y+1; _popupText.anchor = TextAnchor.LowerCenter; if (textY > Globals.ROOM_HEIGHT-2) { textY = textGridPos.y; _popupText.anchor = TextAnchor.UpperCenter; } Vector2 actualPos = toActualCoordinates(new Vector2(textX, textY)); textToAdd.transform.localPosition = new Vector3(actualPos.x, actualPos.y-Globals.CELL_SIZE/2, textToAdd.transform.localPosition.z); textToAdd.text = text; textToAdd.Commit(); textToAdd.gameObject.SetActive(true); } public void addPlayerText(string text) { _player.activateText(text, 2); } protected SpawnedPuzzleItem _highlightedItem; public void setHighlightedItem(SpawnedPuzzleItem item) { _highlightedItem = item; } public void playAudio(AudioClip clip) { _audioSource.PlayOneShot(clip); } // Use this for initialization void Start () { // If we're generating from a seed if (seedGenerate) Random.seed = _currentSeed; _currentSeed = Random.seed; Random.seed = _currentSeed; _instance = this; _inventory = (GameObject.Find("inventory") as GameObject).GetComponent<Inventory>(); _audioSource = GetComponent<AudioSource>(); _floorSprite = GetComponentInChildren<tk2dSprite>(); _popupText = (Instantiate(popupTextPrefab) as GameObject).GetComponent<tk2dTextMesh>(); _popupText.transform.parent = transform; _popupText.gameObject.SetActive(false); _piecesToRemove = new List<GridPiece>(); _piecesToDestroy = new List<GridPiece>(); _gridWidth = Globals.ROOM_WIDTH; _gridHeight = Globals.ROOM_HEIGHT; _currentGame = new ProcGame(); _currentRoom = _currentGame.startRoom; _player = _currentGame.player; _floorSprite.spriteId = _floorSprite.GetSpriteIdByName(_currentRoom.floorTilesName); _gridPieces = _currentRoom.gridPieces; foreach (GridPiece piece in _gridPieces) { piece.gameObject.SetActive(true); } // Begin the game addPlayerText("Hungry...."); } // Update is called once per frame void Update () { // Check if we've won yet if (_hasSandwich && !_player.textActive) { MainMenuState.winState = true; Application.LoadLevel("TitleScene"); } else if (Input.GetKeyDown(KeyCode.Escape)) { MainMenuState.winState = false; Application.LoadLevel("TitleScene"); } // If we want to reset the level if (Input.GetKeyDown(KeyCode.R)) { seedGenerate = true; Application.LoadLevel("PlayScene"); } // remove or destroy any pieces that need to be removed before we begin foreach (GridPiece piece in _piecesToRemove) { if (piece != null) { _gridPieces.Remove(piece); } } _piecesToRemove.Clear(); foreach (GridPiece piece in _piecesToDestroy) { if (piece != null) Destroy(piece.gameObject); } _piecesToDestroy.Clear(); if (_shouldHidePopupText) _popupText.gameObject.SetActive(false); _shouldHidePopupText = true; Vector3 mouseActualPos = tk2dCamera.inst.mainCamera.ScreenToWorldPoint(Input.mousePosition); Vector2 mousePos = new Vector2(mouseActualPos.x, mouseActualPos.y); Vector2 mouseGridPos = PlayState.instance.toGridCoordinates(mouseActualPos.x-PlayState.instance.gridX, mouseActualPos.y-PlayState.instance.gridY); // Check to see if we have a selected item if (_inventory.selectedSlot != null) { string useText = string.Format("Use {0} with", _inventory.selectedSlot.item.itemName); if (_inventory.selectedSlot.item.insideItem && _highlightedItem == null && _inventory.hoveredSlot == null) { if (inGrid(mouseGridPos) && currentGridInhabitants(mouseGridPos).Count == 0) { useText = string.Format("Remove {0} from {1}", _inventory.selectedSlot.item.itemName, _inventory.selectedSlot.item.parentItem.itemName); } } else if (_inventory.selectedSlot != null && _highlightedItem == null && _inventory.selectedSlot.item.insideItem && _inventory.selectedSlot.item.carryable && _inventory.hoveredSlot.isEmpty) { useText = string.Format("Remove {0} from {1}", _inventory.selectedSlot.item.itemName, _inventory.selectedSlot.item.parentItem.itemName); } if (_highlightedItem != null) useText = string.Format("Use {0} with {1}", _inventory.selectedSlot.item.itemName, _highlightedItem.itemName); setMousePopupText(useText, mousePos); } else if (_highlightedItem != null && !_highlightedItem.textActive) { setPopupText(_highlightedItem.description(), _highlightedItem.gridPos); } if (_inventory.selectedSlot != null && _highlightedItem != null && Input.GetMouseButtonDown(0)) { useItemsTogether(_inventory.selectedSlot.item, _highlightedItem); } else if (_inventory.selectedSlot != null && _highlightedItem == null && _inventory.selectedSlot.item.insideItem && _inventory.hoveredSlot == null && Input.GetMouseButtonDown(0)) { // Check to see if we're over a grid position if (inGrid(mouseGridPos) && currentGridInhabitants(mouseGridPos).Count == 0) { SpawnedPuzzleItem itemInContainer = _inventory.selectedSlot.item; itemInContainer.removeFromOtherItem(); itemInContainer.transform.parent = transform; Vector2 actualPos = toActualCoordinates(mouseGridPos); itemInContainer.transform.localScale = new Vector3(4, 4, 1); itemInContainer.x = actualPos.x; itemInContainer.y = actualPos.y; itemInContainer.gridPos = mouseGridPos; itemInContainer.nextPoint = itemInContainer.gridPos; itemInContainer.enabled = true; _gridPieces.Add(itemInContainer); _inventory.selectedSlot = null; } } // Finally, removing into the inventory else if (_inventory.selectedSlot != null && _highlightedItem == null && _inventory.selectedSlot.item.insideItem && _inventory.selectedSlot.item.carryable && _inventory.hoveredSlot != null && _inventory.hoveredSlot.isEmpty && Input.GetMouseButtonDown(0)) { SpawnedPuzzleItem itemInContainer = _inventory.selectedSlot.item; itemInContainer.removeFromOtherItem(); itemInContainer.transform.parent = transform; itemInContainer.transform.localScale = new Vector3(4, 4, 1); itemInContainer.addToInventory(); _inventory.selectedSlot = null; } _highlightedItem = null; if (_currentState == GameState.RUN_STATE) { // Before anything, check to see if we're at an exit if (!_player.moving) { Vector2 playerGridPos = toGridCoordinates(_player.x, _player.y); if (_currentRoom.checkForPlayerExit(playerGridPos)) return; } constructCurrentGrid(); constructClaimedGrid(); bool turnReady = true; _npcTextShowing = false; foreach (GridPiece piece in _gridPieces) { if (!piece.isTurnReady()) turnReady = false; if (!piece.hasType(GridPiece.PLAYER_TYPE) && piece.textActive) _npcTextShowing = true; } // Perform the turn if we're ready for it if (turnReady) { // First, a pre-turn foreach (GridPiece piece in _gridPieces) { piece.turnPerformed = false; piece.preTurn(); } // Now the actual turn. Since pieces might be added to // The piece list, using a normal for loop (rather than foreach) for (int i = 0; i < _gridPieces.Count; i++) { GridPiece piece = _gridPieces[i]; performPieceTurn(piece); } // Update movement foreach (GridPiece piece in _gridPieces) { performTurnMovement(piece); } // Finally, the post turn foreach (GridPiece piece in _gridPieces) { piece.postTurn(); } } } } public void performPieceTurn(GridPiece piece) { if (!piece.turnPerformed) { piece.turnPerformed = true; piece.performTurn(); if (inGrid(piece.nextPoint)) _claimedGrid[(int)piece.nextPoint.x, (int)piece.nextPoint.y].Add(piece); } } private void performTurnMovement(GridPiece piece) { if (piece.nextPoint != piece.gridPos) { float moveSpeed = Globals.MOVE_SPEED; Vector2 nextActualPoint = toActualCoordinates(piece.nextPoint); piece.moveToPoint(nextActualPoint, moveSpeed); } } public void constructCurrentGrid() { _currentGrid = new List<GridPiece>[_gridWidth, _gridHeight]; for (int i = 0; i < _gridWidth; i++) { for (int j = 0; j < _gridHeight; j++) { _currentGrid[i, j] = new List<GridPiece>(); } } foreach (GridPiece piece in _gridPieces) { Vector2 gridPos = toGridCoordinates(piece.x, piece.y); if (inGrid(gridPos)) _currentGrid[(int)gridPos.x, (int)gridPos.y].Add(piece); } } public void constructClaimedGrid() { _claimedGrid = new List<GridPiece>[_gridWidth, _gridHeight]; for (int i = 0; i < _gridWidth; i++) { for (int j = 0; j < _gridHeight; j++) { _claimedGrid[i, j] = new List<GridPiece>(); } } } public List<GridPiece> currentGridInhabitants(Vector2 point) { if (inGrid(point)) return _currentGrid[(int)point.x, (int)point.y]; else return new List<GridPiece>(); } public List<GridPiece> claimedGridInhabitants(Vector2 point) { if (inGrid(point)) return _claimedGrid[(int)point.x, (int)point.y]; else return new List<GridPiece>(); } // Useful grid functions public bool inGrid(Vector2 point) { return point.x >= 0 && point.x < _gridWidth && point.y >= 0 && point.y < _gridHeight; } public Vector2 toGridCoordinates(float x, float y) { return new Vector2(Mathf.Floor(x / Globals.CELL_SIZE), Mathf.Floor( y / Globals.CELL_SIZE)); } public Vector2 toActualCoordinates(Vector2 point) { return new Vector2(point.x*Globals.CELL_SIZE + Globals.CELL_SIZE/2, point.y*Globals.CELL_SIZE + Globals.CELL_SIZE/2); } public void removeFromGame(GridPiece item) { _piecesToRemove.Add(item); _piecesToDestroy.Add(item); } public void removeFromGrid(GridPiece item) { _piecesToRemove.Add(item); } // Room switching code public void switchRoom(Room newRoom, Vector2 newPlayerGridPos) { // First up, remove the player from our current grid piece list _gridPieces.Remove(_player); Vector2 actualPos = toActualCoordinates(newPlayerGridPos); _player.x = actualPos.x; _player.y = actualPos.y; _player.resetGridPos(); _player.roomStartPos = newPlayerGridPos; // Deactivate all the current room grid pieces foreach (GridPiece piece in _gridPieces) { piece.gameObject.SetActive(false); } // Switch! _currentRoom = newRoom; _floorSprite.spriteId = _floorSprite.GetSpriteIdByName(newRoom.floorTilesName); _gridPieces = newRoom.gridPieces; _gridPieces.Add(_player); // Reactivate all the pieces. foreach (GridPiece piece in _gridPieces) { piece.gameObject.SetActive(true); } } public void useItemsTogether(SpawnedPuzzleItem item1, SpawnedPuzzleItem item2) { Debug.Log(string.Format("Using {0} with {1}", item1.itemName, item2.itemName)); IRelationship maybeRel = _currentGame.getRelationship(item1.itemName, item2.itemName); if (maybeRel != null) { // Create an executor for using these two items RelationshipExecutor executor = new RelationshipExecutor(item1, item2, _currentRoom, _currentGame); maybeRel.addRelationshipToGame(executor); } else { _player.activateText("\"I don't think I can use those together.\"", 2); } _inventory.selectedSlot = null; } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using MGTK.EventArguments; using MGTK.Services; namespace MGTK.Controls { public class TextBox : Control { protected Scrollbar horizontalScrollbar; protected Scrollbar verticalScrollbar; protected InnerTextBox innerTextBox; private bool useVerticalScrollBar = true, useHorizontalScrollBar = true; public int CursorX { get { return innerTextBox.CursorX; } set { innerTextBox.CursorX = value; } } public int CursorY { get { return innerTextBox.CursorY; } set { innerTextBox.CursorY = value; } } public bool UseVerticalScrollBar { get { if (!MultiLine) return false; return useVerticalScrollBar; } set { useVerticalScrollBar = value; ConfigureCoordinatesAndSizes(); } } public bool UseHorizontalScrollBar { get { if (!MultiLine) return false; return useHorizontalScrollBar; } set { useHorizontalScrollBar = value; ConfigureCoordinatesAndSizes(); } } public bool MultiLine { get { return innerTextBox.MultiLine; } set { innerTextBox.MultiLine = value; } } public new string Text { get { return innerTextBox.Text; } set { innerTextBox.Text = value; } } public new event EventHandler TextChanged; public event TextChangingEventHandler TextChanging; public TextBox(Form formowner) : base(formowner) { horizontalScrollbar = new Scrollbar(formowner) { Type = ScrollBarType.Horizontal }; verticalScrollbar = new Scrollbar(formowner) { Type = ScrollBarType.Vertical }; innerTextBox = new InnerTextBox(formowner); horizontalScrollbar.Parent = verticalScrollbar.Parent = innerTextBox.Parent = this; horizontalScrollbar.IndexChanged += new EventHandler(horizontalScrollbar_IndexChanged); verticalScrollbar.IndexChanged += new EventHandler(verticalScrollbar_IndexChanged); innerTextBox.TextChanged += new EventHandler(innerTextBox_TextChanged); innerTextBox.ScrollChanged += new EventHandler(innerTextBox_ScrollChanged); innerTextBox.TextChanging += new TextChangingEventHandler(innerTextBox_TextChanging); this.Controls.Add(innerTextBox); this.Controls.Add(horizontalScrollbar); this.Controls.Add(verticalScrollbar); this.Init += new EventHandler(TextBox_Init); this.WidthChanged += new EventHandler(TextBox_SizeChanged); this.HeightChanged += new EventHandler(TextBox_SizeChanged); } void innerTextBox_TextChanging(object sender, TextChangingEventArgs e) { if (TextChanging != null) TextChanging(this, e); } void TextBox_SizeChanged(object sender, EventArgs e) { ConfigureInternalTextCounters(); } void innerTextBox_ScrollChanged(object sender, EventArgs e) { horizontalScrollbar.Index = innerTextBox.ScrollX; verticalScrollbar.Index = innerTextBox.ScrollY; } void innerTextBox_TextChanged(object sender, EventArgs e) { if (Initialized) ConfigureInternalTextCounters(); if (TextChanged != null) TextChanged(this, new EventArgs()); } void TextBox_TextChanged(object sender, EventArgs e) { if (TextChanged != null) TextChanged(this, new EventArgs()); } void TextBox_Init(object sender, EventArgs e) { ConfigureCoordinatesAndSizes(); } public override void Draw() { DrawingService.DrawFrame(SpriteBatchProvider, Theme.TextBoxFrame, OwnerX + X, OwnerY + Y, Width, Height, Z - 0.001f); horizontalScrollbar.Z = verticalScrollbar.Z = Z - 0.0015f; innerTextBox.Z = Z - 0.001f; base.Draw(); } private void ConfigureInternalTextCounters() { verticalScrollbar.NrItemsPerPage = innerTextBox.NrItemsVisible; verticalScrollbar.TotalNrItems = innerTextBox.NrLines; if (innerTextBox.internalText != null && innerTextBox.internalText.Count > 0) { horizontalScrollbar.TotalNrItems = 0; horizontalScrollbar.NrItemsPerPage = 0; for (int i = 0; i < innerTextBox.internalText.Count; i++) { if (innerTextBox.internalText[i].Text.Length > horizontalScrollbar.TotalNrItems) horizontalScrollbar.TotalNrItems = innerTextBox.internalText[i].Text.Length; if (innerTextBox.internalText[i].NrCharsVisible > horizontalScrollbar.NrItemsPerPage) horizontalScrollbar.NrItemsPerPage = innerTextBox.internalText[i].NrCharsVisible; } } } private void ConfigureCoordinatesAndSizes() { innerTextBox.X = 2; innerTextBox.Y = 2; innerTextBox.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom; verticalScrollbar.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right; verticalScrollbar.X = Width - 16 - 2; verticalScrollbar.Y = 2; verticalScrollbar.Width = 16; verticalScrollbar.Height = Height - 4; horizontalScrollbar.X = 2; horizontalScrollbar.Y = Height - 16 - 2; horizontalScrollbar.Width = Width - 4; horizontalScrollbar.Height = 16; horizontalScrollbar.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom; if (UseVerticalScrollBar) innerTextBox.Width = Width - verticalScrollbar.Width - 4 - 1; else innerTextBox.Width = Width - 4; if (UseHorizontalScrollBar) innerTextBox.Height = Height - horizontalScrollbar.Height - 4 - 1; else innerTextBox.Height = Height - 4; if (UseVerticalScrollBar && UseHorizontalScrollBar) { horizontalScrollbar.Width -= 16; verticalScrollbar.Height -= 16; } horizontalScrollbar.Visible = UseHorizontalScrollBar; verticalScrollbar.Visible = UseVerticalScrollBar; ConfigureInternalTextCounters(); } void verticalScrollbar_IndexChanged(object sender, EventArgs e) { innerTextBox.ScrollY = verticalScrollbar.Index; } void horizontalScrollbar_IndexChanged(object sender, EventArgs e) { innerTextBox.ScrollX = horizontalScrollbar.Index; } } }
using System.Collections.Generic; using UnityEditor; using UnityEngine; using UnityEditor.Animations; namespace Cinemachine.Editor { [CustomEditor(typeof(CinemachineStateDrivenCamera))] internal sealed class CinemachineStateDrivenCameraEditor : CinemachineVirtualCameraBaseEditor<CinemachineStateDrivenCamera> { EmbeddeAssetEditor<CinemachineBlenderSettings> m_BlendsEditor; protected override List<string> GetExcludedPropertiesInInspector() { List<string> excluded = base.GetExcludedPropertiesInInspector(); excluded.Add(FieldPath(x => x.m_CustomBlends)); excluded.Add(FieldPath(x => x.m_Instructions)); return excluded; } private UnityEditorInternal.ReorderableList mChildList; private UnityEditorInternal.ReorderableList mInstructionList; protected override void OnEnable() { base.OnEnable(); m_BlendsEditor = new EmbeddeAssetEditor<CinemachineBlenderSettings>( FieldPath(x => x.m_CustomBlends), this); m_BlendsEditor.OnChanged = (CinemachineBlenderSettings b) => { UnityEditorInternal.InternalEditorUtility.RepaintAllViews(); }; m_BlendsEditor.OnCreateEditor = (UnityEditor.Editor ed) => { CinemachineBlenderSettingsEditor editor = ed as CinemachineBlenderSettingsEditor; if (editor != null) editor.GetAllVirtualCameras = () => { return Target.ChildCameras; }; }; mChildList = null; mInstructionList = null; } protected override void OnDisable() { base.OnDisable(); if (m_BlendsEditor != null) m_BlendsEditor.OnDisable(); } public override void OnInspectorGUI() { BeginInspector(); if (mInstructionList == null) SetupInstructionList(); if (mChildList == null) SetupChildList(); if (Target.m_AnimatedTarget == null) EditorGUILayout.HelpBox("An Animated Target is required", MessageType.Warning); // Ordinary properties DrawHeaderInInspector(); DrawPropertyInInspector(FindProperty(x => x.m_Priority)); DrawTargetsInInspector(FindProperty(x => x.m_Follow), FindProperty(x => x.m_LookAt)); DrawPropertyInInspector(FindProperty(x => x.m_AnimatedTarget)); // Layer index EditorGUI.BeginChangeCheck(); UpdateTargetStates(); UpdateCameraCandidates(); SerializedProperty layerProp = FindAndExcludeProperty(x => x.m_LayerIndex); int currentLayer = layerProp.intValue; int layerSelection = EditorGUILayout.Popup("Layer", currentLayer, mLayerNames); if (currentLayer != layerSelection) layerProp.intValue = layerSelection; if (EditorGUI.EndChangeCheck()) { serializedObject.ApplyModifiedProperties(); Target.ValidateInstructions(); } DrawRemainingPropertiesInInspector(); // Blends m_BlendsEditor.DrawEditorCombo( "Create New Blender Asset", Target.gameObject.name + " Blends", "asset", string.Empty, "Custom Blends", false); // Instructions EditorGUI.BeginChangeCheck(); EditorGUILayout.Separator(); mInstructionList.DoLayoutList(); // vcam children EditorGUILayout.Separator(); mChildList.DoLayoutList(); if (EditorGUI.EndChangeCheck()) { serializedObject.ApplyModifiedProperties(); Target.ValidateInstructions(); } // Extensions DrawExtensionsWidgetInInspector(); } private string[] mLayerNames; private int[] mTargetStates; private string[] mTargetStateNames; private Dictionary<int, int> mStateIndexLookup; private void UpdateTargetStates() { // Scrape the Animator Controller for states AnimatorController ac = (Target.m_AnimatedTarget == null) ? null : Target.m_AnimatedTarget.runtimeAnimatorController as AnimatorController; StateCollector collector = new StateCollector(); collector.CollectStates(ac, Target.m_LayerIndex); mTargetStates = collector.mStates.ToArray(); mTargetStateNames = collector.mStateNames.ToArray(); mStateIndexLookup = collector.mStateIndexLookup; if (ac == null) mLayerNames = new string[0]; else { mLayerNames = new string[ac.layers.Length]; for (int i = 0; i < ac.layers.Length; ++i) mLayerNames[i] = ac.layers[i].name; } // Create the parent map in the target List<CinemachineStateDrivenCamera.ParentHash> parents = new List<CinemachineStateDrivenCamera.ParentHash>(); foreach (var i in collector.mStateParentLookup) parents.Add(new CinemachineStateDrivenCamera.ParentHash(i.Key, i.Value)); Target.m_ParentHash = parents.ToArray(); } class StateCollector { public List<int> mStates; public List<string> mStateNames; public Dictionary<int, int> mStateIndexLookup; public Dictionary<int, int> mStateParentLookup; public void CollectStates(AnimatorController ac, int layerIndex) { mStates = new List<int>(); mStateNames = new List<string>(); mStateIndexLookup = new Dictionary<int, int>(); mStateParentLookup = new Dictionary<int, int>(); mStateIndexLookup[0] = mStates.Count; mStateNames.Add("(default)"); mStates.Add(0); if (ac != null && layerIndex >= 0 && layerIndex < ac.layers.Length) { AnimatorStateMachine fsm = ac.layers[layerIndex].stateMachine; string name = fsm.name; int hash = Animator.StringToHash(name); CollectStatesFromFSM(fsm, name + ".", hash, string.Empty); } } void CollectStatesFromFSM( AnimatorStateMachine fsm, string hashPrefix, int parentHash, string displayPrefix) { ChildAnimatorState[] states = fsm.states; for (int i = 0; i < states.Length; i++) { AnimatorState state = states[i].state; int hash = AddState(hashPrefix + state.name, parentHash, displayPrefix + state.name); // Also process clips as pseudo-states, if more than 1 is present. // Since they don't have hashes, we can manufacture some. List<string> clips = CollectClipNames(state.motion); if (clips.Count > 1) { string substatePrefix = displayPrefix + state.name + "."; foreach (string name in clips) AddState( CinemachineStateDrivenCamera.CreateFakeHashName(hash, name), hash, substatePrefix + name); } } ChildAnimatorStateMachine[] fsmChildren = fsm.stateMachines; foreach (var child in fsmChildren) { string name = hashPrefix + child.stateMachine.name; string displayName = displayPrefix + child.stateMachine.name; int hash = AddState(name, parentHash, displayName); CollectStatesFromFSM(child.stateMachine, name + ".", hash, displayName + "."); } } List<string> CollectClipNames(Motion motion) { List<string> names = new List<string>(); AnimationClip clip = motion as AnimationClip; if (clip != null) names.Add(clip.name); BlendTree tree = motion as BlendTree; if (tree != null) { ChildMotion[] children = tree.children; foreach (var child in children) names.AddRange(CollectClipNames(child.motion)); } return names; } int AddState(string hashName, int parentHash, string displayName) { int hash = Animator.StringToHash(hashName); if (parentHash != 0) mStateParentLookup[hash] = parentHash; mStateIndexLookup[hash] = mStates.Count; mStateNames.Add(displayName); mStates.Add(hash); return hash; } } private int GetStateHashIndex(int stateHash) { if (stateHash == 0) return 0; if (!mStateIndexLookup.ContainsKey(stateHash)) return 0; return mStateIndexLookup[stateHash]; } private string[] mCameraCandidates; private Dictionary<CinemachineVirtualCameraBase, int> mCameraIndexLookup; private void UpdateCameraCandidates() { List<string> vcams = new List<string>(); mCameraIndexLookup = new Dictionary<CinemachineVirtualCameraBase, int>(); vcams.Add("(none)"); CinemachineVirtualCameraBase[] children = Target.ChildCameras; foreach (var c in children) { mCameraIndexLookup[c] = vcams.Count; vcams.Add(c.Name); } mCameraCandidates = vcams.ToArray(); } private int GetCameraIndex(Object obj) { if (obj == null || mCameraIndexLookup == null) return 0; CinemachineVirtualCameraBase vcam = obj as CinemachineVirtualCameraBase; if (vcam == null) return 0; if (!mCameraIndexLookup.ContainsKey(vcam)) return 0; return mCameraIndexLookup[vcam]; } void SetupInstructionList() { mInstructionList = new UnityEditorInternal.ReorderableList(serializedObject, serializedObject.FindProperty(() => Target.m_Instructions), true, true, true, true); // Needed for accessing field names as strings CinemachineStateDrivenCamera.Instruction def = new CinemachineStateDrivenCamera.Instruction(); float vSpace = 2; float hSpace = 3; float floatFieldWidth = EditorGUIUtility.singleLineHeight * 2.5f; float hBigSpace = EditorGUIUtility.singleLineHeight * 2 / 3; mInstructionList.drawHeaderCallback = (Rect rect) => { float sharedWidth = rect.width - EditorGUIUtility.singleLineHeight - 2 * (hBigSpace + floatFieldWidth) - hSpace; rect.x += EditorGUIUtility.singleLineHeight; rect.width = sharedWidth / 2; EditorGUI.LabelField(rect, "State"); rect.x += rect.width + hSpace; EditorGUI.LabelField(rect, "Camera"); rect.x += rect.width + hBigSpace; rect.width = floatFieldWidth; EditorGUI.LabelField(rect, "Wait"); rect.x += rect.width + hBigSpace; EditorGUI.LabelField(rect, "Min"); }; mInstructionList.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => { SerializedProperty instProp = mInstructionList.serializedProperty.GetArrayElementAtIndex(index); float sharedWidth = rect.width - 2 * (hBigSpace + floatFieldWidth) - hSpace; rect.y += vSpace; rect.height = EditorGUIUtility.singleLineHeight; rect.width = sharedWidth / 2; SerializedProperty stateSelProp = instProp.FindPropertyRelative(() => def.m_FullHash); int currentState = GetStateHashIndex(stateSelProp.intValue); int stateSelection = EditorGUI.Popup(rect, currentState, mTargetStateNames); if (currentState != stateSelection) stateSelProp.intValue = mTargetStates[stateSelection]; rect.x += rect.width + hSpace; SerializedProperty vcamSelProp = instProp.FindPropertyRelative(() => def.m_VirtualCamera); int currentVcam = GetCameraIndex(vcamSelProp.objectReferenceValue); int vcamSelection = EditorGUI.Popup(rect, currentVcam, mCameraCandidates); if (currentVcam != vcamSelection) vcamSelProp.objectReferenceValue = (vcamSelection == 0) ? null : Target.ChildCameras[vcamSelection - 1]; float oldWidth = EditorGUIUtility.labelWidth; EditorGUIUtility.labelWidth = hBigSpace; rect.x += rect.width; rect.width = floatFieldWidth + hBigSpace; SerializedProperty activeAfterProp = instProp.FindPropertyRelative(() => def.m_ActivateAfter); EditorGUI.PropertyField(rect, activeAfterProp, new GUIContent(" ", activeAfterProp.tooltip)); rect.x += rect.width; SerializedProperty minDurationProp = instProp.FindPropertyRelative(() => def.m_MinDuration); EditorGUI.PropertyField(rect, minDurationProp, new GUIContent(" ", minDurationProp.tooltip)); EditorGUIUtility.labelWidth = oldWidth; }; mInstructionList.onAddDropdownCallback = (Rect buttonRect, UnityEditorInternal.ReorderableList l) => { var menu = new GenericMenu(); menu.AddItem(new GUIContent("New State"), false, (object data) => { ++mInstructionList.serializedProperty.arraySize; serializedObject.ApplyModifiedProperties(); Target.ValidateInstructions(); }, null); menu.AddItem(new GUIContent("All Unhandled States"), false, (object data) => { CinemachineStateDrivenCamera target = Target; int len = mInstructionList.serializedProperty.arraySize; for (int i = 0; i < mTargetStates.Length; ++i) { int hash = mTargetStates[i]; if (hash == 0) continue; bool alreadyThere = false; for (int j = 0; j < len; ++j) { if (target.m_Instructions[j].m_FullHash == hash) { alreadyThere = true; break; } } if (!alreadyThere) { int index = mInstructionList.serializedProperty.arraySize; ++mInstructionList.serializedProperty.arraySize; SerializedProperty p = mInstructionList.serializedProperty.GetArrayElementAtIndex(index); p.FindPropertyRelative(() => def.m_FullHash).intValue = hash; } } serializedObject.ApplyModifiedProperties(); Target.ValidateInstructions(); }, null); menu.ShowAsContext(); }; } void SetupChildList() { float vSpace = 2; float hSpace = 3; float floatFieldWidth = EditorGUIUtility.singleLineHeight * 2.5f; float hBigSpace = EditorGUIUtility.singleLineHeight * 2 / 3; mChildList = new UnityEditorInternal.ReorderableList(serializedObject, serializedObject.FindProperty(() => Target.m_ChildCameras), true, true, true, true); mChildList.drawHeaderCallback = (Rect rect) => { EditorGUI.LabelField(rect, "Virtual Camera Children"); GUIContent priorityText = new GUIContent("Priority"); var textDimensions = GUI.skin.label.CalcSize(priorityText); rect.x += rect.width - textDimensions.x; rect.width = textDimensions.x; EditorGUI.LabelField(rect, priorityText); }; mChildList.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => { rect.y += vSpace; rect.height = EditorGUIUtility.singleLineHeight; rect.width -= floatFieldWidth + hBigSpace; SerializedProperty element = mChildList.serializedProperty.GetArrayElementAtIndex(index); EditorGUI.PropertyField(rect, element, GUIContent.none); float oldWidth = EditorGUIUtility.labelWidth; EditorGUIUtility.labelWidth = hBigSpace; SerializedObject obj = new SerializedObject(element.objectReferenceValue); rect.x += rect.width + hSpace; rect.width = floatFieldWidth + hBigSpace; SerializedProperty priorityProp = obj.FindProperty(() => Target.m_Priority); EditorGUI.PropertyField(rect, priorityProp, new GUIContent(" ", priorityProp.tooltip)); EditorGUIUtility.labelWidth = oldWidth; obj.ApplyModifiedProperties(); }; mChildList.onChangedCallback = (UnityEditorInternal.ReorderableList l) => { if (l.index < 0 || l.index >= l.serializedProperty.arraySize) return; Object o = l.serializedProperty.GetArrayElementAtIndex( l.index).objectReferenceValue; CinemachineVirtualCameraBase vcam = (o != null) ? (o as CinemachineVirtualCameraBase) : null; if (vcam != null) vcam.transform.SetSiblingIndex(l.index); }; mChildList.onAddCallback = (UnityEditorInternal.ReorderableList l) => { var index = l.serializedProperty.arraySize; var vcam = CinemachineMenu.CreateDefaultVirtualCamera(); Undo.SetTransformParent(vcam.transform, Target.transform, ""); vcam.transform.SetSiblingIndex(index); }; mChildList.onRemoveCallback = (UnityEditorInternal.ReorderableList l) => { Object o = l.serializedProperty.GetArrayElementAtIndex( l.index).objectReferenceValue; CinemachineVirtualCameraBase vcam = (o != null) ? (o as CinemachineVirtualCameraBase) : null; if (vcam != null) Undo.DestroyObjectImmediate(vcam.gameObject); }; } } }
using System.Collections.Generic; using System.Linq; namespace Piglet.Lexer.Construction { internal class NfaBuilder { public static NFA Create(ShuntingYard yard) { var stack = new Stack<NFA>(); foreach (var token in yard.ShuntedTokens()) { switch (token.Type) { case RegExToken.TokenType.OperatorMul: stack.Push(RepeatZeroOrMore(stack.Pop())); break; case RegExToken.TokenType.OperatorQuestion: stack.Push(RepeatZeroOrOnce(stack.Pop())); break; case RegExToken.TokenType.OperatorOr: stack.Push(Or(stack.Pop(), stack.Pop())); break; case RegExToken.TokenType.OperatorPlus: stack.Push(RepeatOnceOrMore(stack.Pop())); break; case RegExToken.TokenType.Accept: stack.Push(Accept(token.Characters)); break; case RegExToken.TokenType.OperatorConcat: // & is not commutative, and the stack is reversed. var second = stack.Pop(); var first = stack.Pop(); stack.Push(And(first, second)); break; case RegExToken.TokenType.NumberedRepeat: stack.Push(NumberedRepeat(stack.Pop(), token.MinRepetitions, token.MaxRepetitions)); break; default: throw new LexerConstructionException("Unknown operator!"); } } // We should end up with only ONE NFA on the stack or the expression // is malformed. if (stack.Count() != 1) { throw new LexerConstructionException("Malformed regexp expression"); } // Pop it from the stack, and assign each state a number, primarily for debugging purposes, // they dont _really_ need it. The state numbers actually used are the one used in the DFA. var nfa = stack.Pop(); nfa.AssignStateNumbers(); return nfa; } private static NFA RepeatOnceOrMore(NFA nfa) { // Add an epsilon transition from the accept state back to the start state NFA.State oldAcceptState = nfa.States.First(f => f.AcceptState); nfa.Transitions.Add(new Transition<NFA.State>(oldAcceptState, nfa.StartState)); // Add a new accept state, since we cannot have edges exiting the accept state var newAcceptState = new NFA.State { AcceptState = true }; nfa.Transitions.Add(new Transition<NFA.State>(oldAcceptState, newAcceptState)); nfa.States.Add(newAcceptState); // Clear the accept flag of the old accept state oldAcceptState.AcceptState = false; return nfa; } private static NFA Accept(CharSet acceptCharacters) { // Generate a NFA with a simple path with one state transitioning into an accept state. var nfa = new NFA(); var state = new NFA.State(); nfa.States.Add(state); var acceptState = new NFA.State { AcceptState = true }; nfa.States.Add(acceptState); nfa.Transitions.Add(new Transition<NFA.State>(state, acceptState, acceptCharacters)); nfa.StartState = state; return nfa; } public static NFA And(NFA first, NFA second) { // Create a new NFA and use the first NFAs start state as the starting point var nfa = new NFA { StartState = first.StartState }; // Change all links in to first acceptstate to go to seconds // start state foreach (var edge in first.Transitions.Where(f => f.To.AcceptState)) { edge.To = second.StartState; } // Remove acceptstate from first first.States.Remove(first.States.First(f => f.AcceptState)); // Add all states and edges in both NFAs // Second NFA already has an accept state, there is no need to create another one nfa.AddAll(first); nfa.AddAll(second); return nfa; } public static NFA Or(NFA a, NFA b) { var nfa = new NFA(); // Composite NFA contains all the and all edges in both NFAs nfa.AddAll(a); nfa.AddAll(b); // Add a start state, link to both NFAs old start state with // epsilon links nfa.StartState = new NFA.State(); nfa.States.Add(nfa.StartState); nfa.Transitions.Add(new Transition<NFA.State>(nfa.StartState, a.StartState)); nfa.Transitions.Add(new Transition<NFA.State>(nfa.StartState, b.StartState)); // Add a new accept state, link all old accept states to the new accept // state with an epsilon link and remove the accept flag var newAcceptState = new NFA.State { AcceptState = true }; foreach (var oldAcceptState in nfa.States.Where(f => f.AcceptState)) { oldAcceptState.AcceptState = false; nfa.Transitions.Add(new Transition<NFA.State>(oldAcceptState, newAcceptState)); } nfa.States.Add(newAcceptState); return nfa; } public static NFA RepeatZeroOrMore(NFA input) { var nfa = new NFA(); // Add everything from the input nfa.AddAll(input); // Create a new starting state, link it to the old accept state with Epsilon nfa.StartState = new NFA.State(); nfa.States.Add(nfa.StartState); NFA.State oldAcceptState = input.States.First(f => f.AcceptState); nfa.Transitions.Add(new Transition<NFA.State>(nfa.StartState, oldAcceptState)); // Add epsilon link from old accept state of input to start, to allow for repetition nfa.Transitions.Add(new Transition<NFA.State>(oldAcceptState, input.StartState)); // Create new accept state, link old accept state to new accept state with epsilon var acceptState = new NFA.State { AcceptState = true }; nfa.States.Add(acceptState); oldAcceptState.AcceptState = false; nfa.Transitions.Add(new Transition<NFA.State>(oldAcceptState, acceptState)); return nfa; } private static NFA RepeatZeroOrOnce(NFA nfa) { // Easy enough, add an epsilon transition from the start state // to the end state. Done nfa.Transitions.Add(new Transition<NFA.State>(nfa.StartState, nfa.States.First(f => f.AcceptState))); return nfa; } private static NFA NumberedRepeat(NFA nfa, int minRepetitions, int maxRepetitions) { // To create a suitable expression, the special case of infinite max repetitions // must be separately handled. bool infiniteMax = false; if (maxRepetitions == int.MaxValue) { infiniteMax = true; maxRepetitions = minRepetitions; } else if (maxRepetitions < minRepetitions) { maxRepetitions = minRepetitions; } // Copy the NFA max repetitions times, link them together. NFA output = nfa.Copy(); var epsilonLinkStates = new Stack<NFA.State>(); for (int i = 1; i < maxRepetitions; ++i) { NFA newNfa = nfa.Copy(); if (i >= minRepetitions || (infiniteMax && i == maxRepetitions - 1 )) { epsilonLinkStates.Push(newNfa.StartState); } output = And(output, newNfa); } if (infiniteMax) { // Use Single to force an exception if this has gone astray var finalState = epsilonLinkStates.Single(); // Make a little epsilon loop from the final accept state to the start state of the final state output.Transitions.Add(new Transition<NFA.State>(output.States.Single(f => f.AcceptState), finalState)); } else { // Add epsilon transitions from accept to beginning states of NFAs in the chain var acceptState = output.States.Single(f => f.AcceptState); while (epsilonLinkStates.Any()) { output.Transitions.Add(new Transition<NFA.State>(epsilonLinkStates.Pop(), acceptState)); } } return output; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using Xunit; namespace System.Tests { public partial class GetEnvironmentVariable { [Fact] public void InvalidArguments_ThrowsExceptions() { AssertExtensions.Throws<ArgumentNullException>("variable", () => Environment.GetEnvironmentVariable(null)); AssertExtensions.Throws<ArgumentNullException>("variable", () => Environment.SetEnvironmentVariable(null, "test")); AssertExtensions.Throws<ArgumentException>("variable", () => Environment.SetEnvironmentVariable("", "test")); AssertExtensions.Throws<ArgumentException>("variable", () => Environment.SetEnvironmentVariable("", "test", EnvironmentVariableTarget.Machine)); AssertExtensions.Throws<ArgumentNullException>("variable", () => Environment.SetEnvironmentVariable(null, "test", EnvironmentVariableTarget.User)); AssertExtensions.Throws<ArgumentNullException>("variable", () => Environment.GetEnvironmentVariable(null, EnvironmentVariableTarget.Process)); AssertExtensions.Throws<ArgumentOutOfRangeException, ArgumentException>("target", null, () => Environment.GetEnvironmentVariable("test", (EnvironmentVariableTarget)42)); AssertExtensions.Throws<ArgumentOutOfRangeException, ArgumentException>("target", null, () => Environment.SetEnvironmentVariable("test", "test", (EnvironmentVariableTarget)(-1))); AssertExtensions.Throws<ArgumentOutOfRangeException, ArgumentException>("target", null, () => Environment.GetEnvironmentVariables((EnvironmentVariableTarget)(3))); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && System.Tests.SetEnvironmentVariable.IsSupportedTarget(EnvironmentVariableTarget.User)) { AssertExtensions.Throws<ArgumentException>("variable", null, () => Environment.SetEnvironmentVariable(new string('s', 256), "value", EnvironmentVariableTarget.User)); } } [Fact] public void EmptyVariableReturnsNull() { Assert.Null(Environment.GetEnvironmentVariable(string.Empty)); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // GetEnvironmentVariable by design doesn't respect changes via setenv public void RandomLongVariableNameCanRoundTrip() { // NOTE: The limit of 32766 characters enforced by desktop // SetEnvironmentVariable is antiquated. I was // able to create ~1GB names and values on my Windows 8.1 box. On // desktop, GetEnvironmentVariable throws OOM during its attempt to // demand huge EnvironmentPermission well before that. Also, the old // test for long name case wasn't very good: it just checked that an // arbitrary long name > 32766 characters returned null (not found), but // that had nothing to do with the limit, the variable was simply not // found! string variable = "LongVariable_" + new string('@', 33000); const string value = "TestValue"; try { SetEnvironmentVariableWithPInvoke(variable, value); Assert.Equal(value, Environment.GetEnvironmentVariable(variable)); } finally { SetEnvironmentVariableWithPInvoke(variable, null); } } [Fact] public void RandomVariableThatDoesNotExistReturnsNull() { string variable = "TestVariable_SurelyThisDoesNotExist"; Assert.Null(Environment.GetEnvironmentVariable(variable)); } [Fact] public void VariableNamesAreCaseInsensitiveAsAppropriate() { string value = "TestValue"; try { Environment.SetEnvironmentVariable("ThisIsATestEnvironmentVariable", value); Assert.Equal(value, Environment.GetEnvironmentVariable("ThisIsATestEnvironmentVariable")); if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { value = null; } Assert.Equal(value, Environment.GetEnvironmentVariable("thisisatestenvironmentvariable")); Assert.Equal(value, Environment.GetEnvironmentVariable("THISISATESTENVIRONMENTVARIABLE")); Assert.Equal(value, Environment.GetEnvironmentVariable("ThISISATeSTENVIRoNMEnTVaRIABLE")); } finally { Environment.SetEnvironmentVariable("ThisIsATestEnvironmentVariable", null); } } [Fact] public void CanGetAllVariablesIndividually() { Random r = new Random(); string envVar1 = "TestVariable_CanGetVariablesIndividually_" + r.Next().ToString(); string envVar2 = "TestVariable_CanGetVariablesIndividually_" + r.Next().ToString(); try { Environment.SetEnvironmentVariable(envVar1, envVar1); Environment.SetEnvironmentVariable(envVar2, envVar2); IDictionary envBlock = Environment.GetEnvironmentVariables(); // Make sure the environment variables we set are part of the dictionary returned. Assert.True(envBlock.Contains(envVar1)); Assert.True(envBlock.Contains(envVar1)); // Make sure the values match the expected ones. Assert.Equal(envVar1, envBlock[envVar1]); Assert.Equal(envVar2, envBlock[envVar2]); // Make sure we can read the individual variables as well Assert.Equal(envVar1, Environment.GetEnvironmentVariable(envVar1)); Assert.Equal(envVar2, Environment.GetEnvironmentVariable(envVar2)); } finally { // Clear the variables we just set Environment.SetEnvironmentVariable(envVar1, null); Environment.SetEnvironmentVariable(envVar2, null); } } [Fact] public void EnumerateYieldsDictionaryEntryFromIEnumerable() { // GetEnvironmentVariables has always yielded DictionaryEntry from IEnumerable IDictionary vars = Environment.GetEnvironmentVariables(); IEnumerator enumerator = ((IEnumerable)vars).GetEnumerator(); if (enumerator.MoveNext()) { Assert.IsType<DictionaryEntry>(enumerator.Current); } else { Assert.Throws<InvalidOperationException>(() => enumerator.Current); } } [Fact] public void GetEnumerator_IDictionaryEnumerator_YieldsDictionaryEntries() { // GetEnvironmentVariables has always yielded DictionaryEntry from IDictionaryEnumerator IDictionary vars = Environment.GetEnvironmentVariables(); IDictionaryEnumerator enumerator = vars.GetEnumerator(); if (enumerator.MoveNext()) { Assert.IsType<DictionaryEntry>(enumerator.Current); } else { Assert.Throws<InvalidOperationException>(() => enumerator.Current); } } [Theory] [InlineData(null)] [MemberData(nameof(EnvironmentTests.EnvironmentVariableTargets), MemberType = typeof(EnvironmentTests))] public void GetEnumerator_LinqOverDictionaryEntries_Success(EnvironmentVariableTarget? target) { IDictionary envVars = target != null ? Environment.GetEnvironmentVariables(target.Value) : Environment.GetEnvironmentVariables(); Assert.IsType<Hashtable>(envVars); foreach (KeyValuePair<string, string> envVar in envVars.Cast<DictionaryEntry>().Select(de => new KeyValuePair<string, string>((string)de.Key, (string)de.Value))) { Assert.NotNull(envVar.Key); } } [Fact] public void EnvironmentVariablesAreHashtable() { // On NetFX, the type returned was always Hashtable Assert.IsType<Hashtable>(Environment.GetEnvironmentVariables()); } [Theory] [MemberData(nameof(EnvironmentTests.EnvironmentVariableTargets), MemberType = typeof(EnvironmentTests))] public void EnvironmentVariablesAreHashtable(EnvironmentVariableTarget target) { // On NetFX, the type returned was always Hashtable Assert.IsType<Hashtable>(Environment.GetEnvironmentVariables(target)); } [Theory] [MemberData(nameof(EnvironmentTests.EnvironmentVariableTargets), MemberType = typeof(EnvironmentTests))] public void EnumerateYieldsDictionaryEntryFromIEnumerable(EnvironmentVariableTarget target) { // GetEnvironmentVariables has always yielded DictionaryEntry from IEnumerable IDictionary vars = Environment.GetEnvironmentVariables(target); IEnumerator enumerator = ((IEnumerable)vars).GetEnumerator(); if (enumerator.MoveNext()) { Assert.IsType<DictionaryEntry>(enumerator.Current); } else { Assert.Throws<InvalidOperationException>(() => enumerator.Current); } } [Theory] [MemberData(nameof(EnvironmentTests.EnvironmentVariableTargets), MemberType = typeof(EnvironmentTests))] public void EnumerateEnvironmentVariables(EnvironmentVariableTarget target) { bool lookForSetValue = (target == EnvironmentVariableTarget.Process) || PlatformDetection.IsWindowsAndElevated; // [ActiveIssue(40226)] if (PlatformDetection.IsWindowsNanoServer && target == EnvironmentVariableTarget.User) { lookForSetValue = false; } string key = $"EnumerateEnvironmentVariables ({target})"; string value = Path.GetRandomFileName(); try { if (lookForSetValue) { Environment.SetEnvironmentVariable(key, value, target); Assert.Equal(value, Environment.GetEnvironmentVariable(key, target)); } IDictionary results = Environment.GetEnvironmentVariables(target); // Ensure we can walk through the results IDictionaryEnumerator enumerator = results.GetEnumerator(); while (enumerator.MoveNext()) { Assert.NotNull(enumerator.Entry.Key); } if (lookForSetValue) { // Ensure that we got our flagged value out Assert.Equal(value, results[key]); } } finally { if (lookForSetValue) { Environment.SetEnvironmentVariable(key, null, target); Assert.Null(Environment.GetEnvironmentVariable(key, target)); } } } private static void SetEnvironmentVariableWithPInvoke(string name, string value) { bool success = #if !Unix SetEnvironmentVariable(name, value); #else (value != null ? setenv(name, value, 1) : unsetenv(name)) == 0; #endif Assert.True(success); } [DllImport("kernel32.dll", EntryPoint = "SetEnvironmentVariableW" , CharSet = CharSet.Unicode, SetLastError = true)] private static extern bool SetEnvironmentVariable(string lpName, string lpValue); #if Unix [DllImport("libc")] private static extern int setenv(string name, string value, int overwrite); [DllImport("libc")] private static extern int unsetenv(string name); #endif } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using NUnit.Framework; using QuantConnect.Data; using QuantConnect.Util; using QuantConnect.Orders; using QuantConnect.Algorithm; using QuantConnect.Brokerages; using QuantConnect.Interfaces; using QuantConnect.Securities; using QuantConnect.Data.Market; using QuantConnect.Orders.Fees; using QuantConnect.Securities.Option; using QuantConnect.Tests.Engine.DataFeeds; using Option = QuantConnect.Securities.Option.Option; namespace QuantConnect.Tests.Common.Securities { [TestFixture] public class SecurityMarginModelTests { private static Symbol _symbol; private static FakeOrderProcessor _fakeOrderProcessor; [TestCase(1)] [TestCase(2)] [TestCase(50)] public void MarginRemainingForLeverage(decimal leverage) { var algorithm = GetAlgorithm(); algorithm.SetCash(1000); var spy = InitAndGetSecurity(algorithm, 0); spy.Holdings.SetHoldings(25, 100); spy.SetLeverage(leverage); var spyMarginAvailable = spy.Holdings.HoldingsValue - spy.Holdings.HoldingsValue * (1 / leverage); var marginRemaining = algorithm.Portfolio.MarginRemaining; Assert.AreEqual(1000 + spyMarginAvailable, marginRemaining); } [TestCase(1)] [TestCase(2)] [TestCase(50)] public void MarginUsedForPositionWhenPriceDrops(decimal leverage) { var algorithm = GetAlgorithm(); // (1000 * 20) = 20k // Initial and maintenance margin = (1000 * 20) / leverage = X var spy = InitAndGetSecurity(algorithm, 0); spy.Holdings.SetHoldings(20, 1000); spy.SetLeverage(leverage); // Drop 40% price from $20 to $12 // 1000 * 12 = 12k Update(spy, 12); var marginForPosition = spy.BuyingPowerModel.GetReservedBuyingPowerForPosition( new ReservedBuyingPowerForPositionParameters(spy)).AbsoluteUsedBuyingPower; Assert.AreEqual(1000 * 12 / leverage, marginForPosition); } [TestCase(1)] [TestCase(2)] [TestCase(50)] public void MarginUsedForPositionWhenPriceIncreases(decimal leverage) { var algorithm = GetAlgorithm(); algorithm.SetCash(1000); // (1000 * 20) = 20k // Initial and maintenance margin = (1000 * 20) / leverage = X var spy = InitAndGetSecurity(algorithm, 0); spy.Holdings.SetHoldings(25, 1000); spy.SetLeverage(leverage); // Increase from $20 to $40 // 1000 * 40 = 400000 Update(spy, 40); var marginForPosition = spy.BuyingPowerModel.GetReservedBuyingPowerForPosition( new ReservedBuyingPowerForPositionParameters(spy)).AbsoluteUsedBuyingPower; Assert.AreEqual(1000 * 40 / leverage, marginForPosition); } [Test] public void ZeroTargetWithZeroHoldingsIsNotAnError() { var algorithm = GetAlgorithm(); var security = InitAndGetSecurity(algorithm, 0); var model = new SecurityMarginModel(); var result = model.GetMaximumOrderQuantityForTargetBuyingPower(algorithm.Portfolio, security, 0, 0); Assert.AreEqual(0, result.Quantity); Assert.IsTrue(result.Reason.IsNullOrEmpty()); Assert.IsFalse(result.IsError); } [TestCase(0)] [TestCase(1)] [TestCase(-1)] public void ReturnsMinimumOrderValueReason(decimal holdings) { var algorithm = GetAlgorithm(); var security = InitAndGetSecurity(algorithm, 0); var model = new SecurityMarginModel(); security.Holdings.SetHoldings(security.Price, holdings); var currentSignedUsedMargin = model.GetInitialMarginRequirement(security, security.Holdings.Quantity); var totalPortfolioValue = algorithm.Portfolio.TotalPortfolioValue; var sign = Math.Sign(security.Holdings.Quantity) == 0 ? 1 : Math.Sign(security.Holdings.Quantity); // we increase it slightly, should not trigger a new order because it's increasing final margin usage, rounds down var newTarget = currentSignedUsedMargin / (totalPortfolioValue) + 0.00001m * sign; var result = model.GetMaximumOrderQuantityForTargetBuyingPower(algorithm.Portfolio, security, newTarget, 0); Assert.AreEqual(0m, result.Quantity); Assert.IsFalse(result.IsError); Assert.IsTrue(result.Reason.Contains("The order quantity is less than the lot size of", StringComparison.InvariantCultureIgnoreCase)); } [TestCase(1)] [TestCase(-1)] public void ReducesPositionWhenMarginAboveTargetWhenNegativeFreeMargin(decimal holdings) { var algorithm = GetAlgorithm(); var security = InitAndGetSecurity(algorithm, 0); var model = new SecurityMarginModel(); security.Holdings.SetHoldings(security.Price, holdings); var security2 = InitAndGetSecurity(algorithm, 0, symbol: "AAPL"); // eat up all our TPV security2.Holdings.SetHoldings(security.Price, (algorithm.Portfolio.TotalPortfolioValue / security.Price) * 2); var currentSignedUsedMargin = model.GetInitialMarginRequirement(security, security.Holdings.Quantity); var totalPortfolioValue = algorithm.Portfolio.TotalPortfolioValue; var sign = Math.Sign(security.Holdings.Quantity) == 0 ? 1 : Math.Sign(security.Holdings.Quantity); // we inverse the sign here so that new target is less than current, we expect a reduction var newTarget = currentSignedUsedMargin / (totalPortfolioValue) + 0.00001m * sign * -1; Assert.IsTrue(0 > algorithm.Portfolio.MarginRemaining); var result = model.GetMaximumOrderQuantityForTargetBuyingPower(algorithm.Portfolio, security, newTarget, 0); // Reproduces GH issue #5763 a small Reduction in the target should reduce the position Assert.AreEqual(1m * sign * -1, result.Quantity); Assert.IsFalse(result.IsError); } [TestCase(1, 0)] [TestCase(-1, 0)] [TestCase(1, 0.001d)] [TestCase(-1, 0.001d)] public void ReducesPositionWhenMarginAboveTargetBasedOnSetting(decimal holdings, decimal minimumOrderMarginPortfolioPercentage) { var algorithm = GetAlgorithm(); var security = InitAndGetSecurity(algorithm, 0); var model = new SecurityMarginModel(); security.Holdings.SetHoldings(security.Price, holdings); var currentSignedUsedMargin = model.GetInitialMarginRequirement(security, security.Holdings.Quantity); var totalPortfolioValue = algorithm.Portfolio.TotalPortfolioValue; var sign = Math.Sign(security.Holdings.Quantity) == 0 ? 1 : Math.Sign(security.Holdings.Quantity); // we inverse the sign here so that new target is less than current, we expect a reduction var newTarget = currentSignedUsedMargin / (totalPortfolioValue) + 0.00001m * sign * -1; var result = model.GetMaximumOrderQuantityForTargetBuyingPower(algorithm.Portfolio, security, newTarget, minimumOrderMarginPortfolioPercentage); if (minimumOrderMarginPortfolioPercentage == 0) { // Reproduces GH issue #5763 a small Reduction in the target should reduce the position Assert.AreEqual(1m * sign * -1, result.Quantity); Assert.IsFalse(result.IsError); } else { Assert.AreEqual(0, result.Quantity); Assert.IsFalse(result.IsError); } } [Test] public void ZeroTargetWithNonZeroHoldingsReturnsNegativeOfQuantity() { var algorithm = GetAlgorithm(); var security = InitAndGetSecurity(algorithm, 0); security.Holdings.SetHoldings(200, 10); var model = new SecurityMarginModel(); var result = model.GetMaximumOrderQuantityForTargetBuyingPower(algorithm.Portfolio, security, 0, 0); Assert.AreEqual(-10, result.Quantity); Assert.IsTrue(result.Reason.IsNullOrEmpty()); Assert.IsFalse(result.IsError); } [Test] public void SetHoldings_ZeroToFullLong() { var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 5); var actual = algo.CalculateOrderQuantity(_symbol, 1m * security.BuyingPowerModel.GetLeverage(security)); // (100000 * 2 * 0.9975 setHoldingsBuffer) / 25 - fee ~=7979m Assert.AreEqual(7979m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); } [Test] public void SetHoldings_ZeroToFullLong_NonAccountCurrency_ZeroQuoteCurrency() { var algorithm = GetAlgorithm(); algorithm.Portfolio.CashBook.Clear(); algorithm.Portfolio.SetAccountCurrency("EUR"); algorithm.Portfolio.SetCash(10000); // We don't have quote currency - we will get a "loan" algorithm.Portfolio.SetCash(Currencies.USD, 0, 0.88m); var security = InitAndGetSecurity(algorithm, 5); algorithm.Settings.FreePortfolioValue = algorithm.Portfolio.TotalPortfolioValue * algorithm.Settings.FreePortfolioValuePercentage; var actual = algorithm.CalculateOrderQuantity(_symbol, 1m * security.BuyingPowerModel.GetLeverage(security)); // (10000 * 2 * 0.9975 setHoldingsBuffer) / 25 * 0.88 conversion rate - 5 USD fee * 0.88 conversion rate ~=906m Assert.AreEqual(906m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algorithm)); } [TestCase("Long")] [TestCase("Short")] public void GetReservedBuyingPowerForPosition_NonAccountCurrency_ZeroQuoteCurrency(string position) { var algorithm = GetAlgorithm(); algorithm.Portfolio.CashBook.Clear(); algorithm.Portfolio.SetAccountCurrency("EUR"); algorithm.Portfolio.SetCash(10000); algorithm.Portfolio.SetCash(Currencies.USD, 0, 0.88m); var security = InitAndGetSecurity(algorithm, 5); security.Holdings.SetHoldings(security.Price, (position == "Long" ? 1 : -1) * 100); var actual = security.BuyingPowerModel.GetReservedBuyingPowerForPosition(new ReservedBuyingPowerForPositionParameters(security)); // 100quantity * 25price * 0.88rate * 0.5 MaintenanceMarginRequirement = 1100 Assert.AreEqual(1100, actual.AbsoluteUsedBuyingPower); } [Test] public void SetHoldings_ZeroToFullLong_NonAccountCurrency() { var algorithm = GetAlgorithm(); algorithm.Portfolio.CashBook.Clear(); algorithm.Portfolio.SetAccountCurrency("EUR"); algorithm.Portfolio.SetCash(10000); // We have 1000 USD too algorithm.Portfolio.SetCash(Currencies.USD, 1000, 0.88m); var security = InitAndGetSecurity(algorithm, 5); algorithm.Settings.FreePortfolioValue = algorithm.Portfolio.TotalPortfolioValue * algorithm.Settings.FreePortfolioValuePercentage; var actual = algorithm.CalculateOrderQuantity(_symbol, 1m * security.BuyingPowerModel.GetLeverage(security)); // ((10000 + 1000 USD * 0.88 rate) * 2 * 0.9975 setHoldingsBuffer) / 25 * 0.88 rate - 5 USD fee * 0.88 rate ~=986m Assert.AreEqual(986m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algorithm)); } [Test] public void SetHoldings_Long_TooBigOfATarget() { var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 5); var actual = algo.CalculateOrderQuantity(_symbol, 1m * security.BuyingPowerModel.GetLeverage(security) + 0.1m); // (100000 * 2.1* 0.9975 setHoldingsBuffer) / 25 - fee ~=8378m Assert.AreEqual(8378m, actual); Assert.IsFalse(HasSufficientBuyingPowerForOrder(actual, security, algo)); } [Test] public void SetHoldings_Long_TooBigOfATarget_NonAccountCurrency() { var algorithm = GetAlgorithm(); algorithm.Portfolio.CashBook.Clear(); algorithm.Portfolio.SetAccountCurrency("EUR"); algorithm.Portfolio.SetCash(10000); // We don't have quote currency - we will get a "loan" algorithm.Portfolio.SetCash(Currencies.USD, 0, 0.88m); var security = InitAndGetSecurity(algorithm, 5); algorithm.Settings.FreePortfolioValue = algorithm.Portfolio.TotalPortfolioValue * algorithm.Settings.FreePortfolioValuePercentage; var actual = algorithm.CalculateOrderQuantity(_symbol, 1m * security.BuyingPowerModel.GetLeverage(security) + 0.1m); // (10000 * 2.1 * 0.9975 setHoldingsBuffer) / 25 * 0.88 conversion rate - 5 USD fee * 0.88 conversion rate ~=951m Assert.AreEqual(951m, actual); Assert.IsFalse(HasSufficientBuyingPowerForOrder(actual, security, algorithm)); } [Test] public void SetHoldings_ZeroToFullShort() { var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 5); var actual = algo.CalculateOrderQuantity(_symbol, -1m * security.BuyingPowerModel.GetLeverage(security)); // (100000 * 2 * 0.9975 setHoldingsBuffer) / 25 - fee~=-7979m Assert.AreEqual(-7979m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); } [Test] public void SetHoldings_ZeroToFullShort_NonAccountCurrency_ZeroQuoteCurrency() { var algorithm = GetAlgorithm(); algorithm.Portfolio.CashBook.Clear(); algorithm.Portfolio.SetAccountCurrency("EUR"); algorithm.Portfolio.SetCash(10000); algorithm.Portfolio.SetCash(Currencies.USD, 0, 0.88m); var security = InitAndGetSecurity(algorithm, 5); algorithm.Settings.FreePortfolioValue = algorithm.Portfolio.TotalPortfolioValue * algorithm.Settings.FreePortfolioValuePercentage; var actual = algorithm.CalculateOrderQuantity(_symbol, -1m * security.BuyingPowerModel.GetLeverage(security)); // (10000 * - 2 * 0.9975 setHoldingsBuffer) / 25 * 0.88 conversion rate - 5 USD fee * 0.88 conversion rate ~=906m Assert.AreEqual(-906m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algorithm)); } [Test] public void SetHoldings_ZeroToFullShort_NonAccountCurrency() { var algorithm = GetAlgorithm(); algorithm.Portfolio.CashBook.Clear(); algorithm.Portfolio.SetAccountCurrency("EUR"); algorithm.Portfolio.SetCash(10000); algorithm.Portfolio.SetCash(Currencies.USD, 1000, 0.88m); var security = InitAndGetSecurity(algorithm, 5); algorithm.Settings.FreePortfolioValue = algorithm.Portfolio.TotalPortfolioValue * algorithm.Settings.FreePortfolioValuePercentage; var actual = algorithm.CalculateOrderQuantity(_symbol, -1m * security.BuyingPowerModel.GetLeverage(security)); // ((10000 + 1000 * 0.88)* - 2 * 0.9975 setHoldingsBuffer) / 25 * 0.88 conversion rate - 5 USD fee * 0.88 conversion rate ~=986m Assert.AreEqual(-986m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algorithm)); } [Test] public void SetHoldings_Short_TooBigOfATarget() { var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 5); var actual = algo.CalculateOrderQuantity(_symbol, -1m * security.BuyingPowerModel.GetLeverage(security) - 0.1m); // (100000 * - 2.1m * 0.9975 setHoldingsBuffer) / 25 - fee~=-8378m Assert.AreEqual(-8378m, actual); Assert.IsFalse(HasSufficientBuyingPowerForOrder(actual, security, algo)); } [Test] public void SetHoldings_Short_TooBigOfATarget_NonAccountCurrency() { var algorithm = GetAlgorithm(); algorithm.Portfolio.CashBook.Clear(); algorithm.Portfolio.SetAccountCurrency("EUR"); algorithm.Portfolio.SetCash(10000); algorithm.Portfolio.SetCash(Currencies.USD, 0, 0.88m); var security = InitAndGetSecurity(algorithm, 5); algorithm.Settings.FreePortfolioValue = algorithm.Portfolio.TotalPortfolioValue * algorithm.Settings.FreePortfolioValuePercentage; var actual = algorithm.CalculateOrderQuantity(_symbol, -1m * security.BuyingPowerModel.GetLeverage(security) - 0.1m); // (10000 * - 2.1 * 0.9975 setHoldingsBuffer) / 25 * 0.88 conversion rate - 5 USD fee * 0.88 conversion rate ~=951m Assert.AreEqual(-951m, actual); Assert.IsFalse(HasSufficientBuyingPowerForOrder(actual, security, algorithm)); } [Test] public void SetHoldings_ZeroToFullLong_NoFee() { var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 0); var actual = algo.CalculateOrderQuantity(_symbol, 1m * security.BuyingPowerModel.GetLeverage(security)); // (100000 * 2 * 0.9975 setHoldingsBuffer) / 25 =7980m Assert.AreEqual(7980m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); } [Test] public void SetHoldings_Long_TooBigOfATarget_NoFee() { var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 0); var actual = algo.CalculateOrderQuantity(_symbol, 1m * security.BuyingPowerModel.GetLeverage(security) + 0.1m); // (100000 * 2.1m* 0.9975 setHoldingsBuffer) / 25 = 8379m Assert.AreEqual(8379m, actual); Assert.IsFalse(HasSufficientBuyingPowerForOrder(actual, security, algo)); } [Test] public void SetHoldings_ZeroToFullShort_NoFee() { var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 0); var actual = algo.CalculateOrderQuantity(_symbol, -1m * security.BuyingPowerModel.GetLeverage(security)); var order = new MarketOrder(_symbol, actual, DateTime.UtcNow); // (100000 * 2 * 0.9975 setHoldingsBuffer) / 25 = -7980m Assert.AreEqual(-7980m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); } [Test] public void SetHoldings_Short_TooBigOfATarget_NoFee() { var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 0); var actual = algo.CalculateOrderQuantity(_symbol, -1m * security.BuyingPowerModel.GetLeverage(security) - 0.1m); // (100000 * -2.1 * 0.9975 setHoldingsBuffer) / 25 = -8379m Assert.AreEqual(-8379m, actual); Assert.IsFalse(HasSufficientBuyingPowerForOrder(actual, security, algo)); } [Test] public void FreeBuyingPowerPercentDefault_Equity() { var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 5, SecurityType.Equity); var model = security.BuyingPowerModel; var actual = algo.CalculateOrderQuantity(_symbol, 1m * model.GetLeverage(security)); // (100000 * 2 * 0.9975) / 25 - 1 order due to fees Assert.AreEqual(7979m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); Assert.AreEqual(algo.Portfolio.Cash, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Buy)); } [Test] public void FreeBuyingPowerPercentAppliesForCashAccount_Equity() { var algo = GetAlgorithm(); algo.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Cash); var security = InitAndGetSecurity(algo, 5, SecurityType.Equity); var requiredFreeBuyingPowerPercent = 0.05m; var model = security.BuyingPowerModel = new SecurityMarginModel(1, requiredFreeBuyingPowerPercent); var actual = algo.CalculateOrderQuantity(_symbol, 1m * model.GetLeverage(security)); // (100000 * 1 * 0.95 * 0.9975) / 25 - 1 order due to fees Assert.AreEqual(3790m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual * 1.0025m, security, algo)); Assert.IsFalse(HasSufficientBuyingPowerForOrder(actual * 1.0025m + security.SymbolProperties.LotSize + 9, security, algo)); var expectedBuyingPower = algo.Portfolio.Cash * (1 - requiredFreeBuyingPowerPercent); Assert.AreEqual(expectedBuyingPower, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Buy)); } [Test] public void FreeBuyingPowerPercentAppliesForMarginAccount_Equity() { var algo = GetAlgorithm(); algo.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin); var security = InitAndGetSecurity(algo, 5, SecurityType.Equity); var requiredFreeBuyingPowerPercent = 0.05m; var model = security.BuyingPowerModel = new SecurityMarginModel(2, requiredFreeBuyingPowerPercent); var actual = algo.CalculateOrderQuantity(_symbol, 1m * model.GetLeverage(security)); // (100000 * 2 * 0.95 * 0.9975) / 25 - 1 order due to fees Assert.AreEqual(7580m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual * 1.0025m, security, algo)); Assert.IsFalse(HasSufficientBuyingPowerForOrder(actual * 1.0025m + security.SymbolProperties.LotSize + 9, security, algo)); var expectedBuyingPower = algo.Portfolio.Cash * (1 - requiredFreeBuyingPowerPercent); Assert.AreEqual(expectedBuyingPower, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Buy)); } [Test] public void FreeBuyingPowerPercentCashAccountWithLongHoldings_Equity() { var algo = GetAlgorithm(); algo.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Cash); var security = InitAndGetSecurity(algo, 5, SecurityType.Equity); var requiredFreeBuyingPowerPercent = 0.05m; var model = security.BuyingPowerModel = new SecurityMarginModel(1, requiredFreeBuyingPowerPercent); security.Holdings.SetHoldings(25, 2000); security.SettlementModel.ApplyFunds(algo.Portfolio, security, DateTime.UtcNow.AddDays(-10), Currencies.USD, -2000 * 25); // Margin remaining 50k + used 50k + initial margin 50k - 5k free buying power percent (5% of 100k) Assert.AreEqual(145000, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Sell)); // Margin remaining 50k - 5k free buying power percent (5% of 100k) Assert.AreEqual(45000, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Buy)); var actual = algo.CalculateOrderQuantity(_symbol, -1m * model.GetLeverage(security)); // ((100k - 5) * -1 * 0.95 * 0.9975 - (50k holdings)) / 25 - 1 order due to fees Assert.AreEqual(-5790m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); Assert.IsFalse(HasSufficientBuyingPowerForOrder(actual * 1.0025m, security, algo)); } [Test] public void FreeBuyingPowerPercentMarginAccountWithLongHoldings_Equity() { var algo = GetAlgorithm(); algo.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin); var security = InitAndGetSecurity(algo, 5, SecurityType.Equity); var requiredFreeBuyingPowerPercent = 0.05m; var model = security.BuyingPowerModel = new SecurityMarginModel(2, requiredFreeBuyingPowerPercent); security.Holdings.SetHoldings(25, 2000); security.SettlementModel.ApplyFunds(algo.Portfolio, security, DateTime.UtcNow.AddDays(-10), Currencies.USD, -2000 * 25); // Margin remaining 75k + used 25k + initial margin 25k - 5k free buying power percent (5% of 100k) Assert.AreEqual(120000, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Sell)); // Margin remaining 75k - 5k free buying power percent Assert.AreEqual(70000, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Buy)); var actual = algo.CalculateOrderQuantity(_symbol, -1m * model.GetLeverage(security)); // ((100k - 5) * -2 * 0.95 * 0.9975 - (50k holdings)) / 25 - 1 order due to fees Assert.AreEqual(-9580m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); Assert.IsFalse(HasSufficientBuyingPowerForOrder(actual * 1.0025m, security, algo)); } [Test] public void FreeBuyingPowerPercentMarginAccountWithShortHoldings_Equity() { var algo = GetAlgorithm(); algo.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin); var security = InitAndGetSecurity(algo, 5, SecurityType.Equity); var requiredFreeBuyingPowerPercent = 0.05m; var model = security.BuyingPowerModel = new SecurityMarginModel(2, requiredFreeBuyingPowerPercent); security.Holdings.SetHoldings(25, -2000); security.SettlementModel.ApplyFunds(algo.Portfolio, security, DateTime.UtcNow.AddDays(-10), Currencies.USD, 2000 * 25); // Margin remaining 75k + used 25k + initial margin 25k - 5k free buying power percent (5% of 100k) Assert.AreEqual(120000, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Buy)); // Margin remaining 75k - 5k free buying power percent Assert.AreEqual(70000, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Sell)); var actual = algo.CalculateOrderQuantity(_symbol, 1m * model.GetLeverage(security)); // ((100k - 5) * 2 * 0.95 * 0.9975 - (-50k holdings)) / 25 - 1 order due to fees Assert.AreEqual(9580m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); Assert.IsFalse(HasSufficientBuyingPowerForOrder(actual * 1.0025m, security, algo)); } [Test] public void FreeBuyingPowerPercentDefault_Option() { const decimal price = 25m; const decimal underlyingPrice = 25m; var tz = TimeZones.NewYork; var equity = new QuantConnect.Securities.Equity.Equity( SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, tz, tz, true, false, false), new Cash(Currencies.USD, 0, 1m), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null ); equity.SetMarketPrice(new Tick { Value = underlyingPrice }); var optionPutSymbol = Symbol.CreateOption(Symbols.SPY, Market.USA, OptionStyle.American, OptionRight.Put, 207m, new DateTime(2015, 02, 27)); var security = new Option( SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig(typeof(TradeBar), optionPutSymbol, Resolution.Minute, tz, tz, true, false, false), new Cash(Currencies.USD, 0, 1m), new OptionSymbolProperties("", Currencies.USD, 100, 0.01m, 1), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null ); security.SetMarketPrice(new Tick { Value = price }); security.Underlying = equity; var algo = GetAlgorithm(); security.SetLocalTimeKeeper(algo.TimeKeeper.GetLocalTimeKeeper(tz)); var actual = security.BuyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower( new GetMaximumOrderQuantityForTargetBuyingPowerParameters(algo.Portfolio, security, 1, 0)).Quantity; // (100000 * 1) / (25 * 100 contract multiplier) - 1 order due to fees Assert.AreEqual(39m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); Assert.AreEqual(algo.Portfolio.Cash, security.BuyingPowerModel.GetBuyingPower(algo.Portfolio, security, OrderDirection.Buy)); } [Test] public void FreeBuyingPowerPercentAppliesForCashAccount_Option() { var algo = GetAlgorithm(); algo.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Cash); var security = InitAndGetSecurity(algo, 5, SecurityType.Option); var requiredFreeBuyingPowerPercent = 0.05m; var model = security.BuyingPowerModel = new SecurityMarginModel(1, requiredFreeBuyingPowerPercent); var actual = algo.CalculateOrderQuantity(_symbol, 1m * model.GetLeverage(security)); // (100000 * 1 * 0.95) / (25 * 100 contract multiplier) - 1 order due to fees Assert.AreEqual(37m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); var expectedBuyingPower = algo.Portfolio.Cash * (1 - requiredFreeBuyingPowerPercent); Assert.AreEqual(expectedBuyingPower, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Buy)); } [Test] public void FreeBuyingPowerPercentAppliesForMarginAccount_Option() { var algo = GetAlgorithm(); algo.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin); var security = InitAndGetSecurity(algo, 5, SecurityType.Option); var requiredFreeBuyingPowerPercent = 0.05m; var model = security.BuyingPowerModel = new SecurityMarginModel(2, requiredFreeBuyingPowerPercent); var actual = algo.CalculateOrderQuantity(_symbol, 1m * model.GetLeverage(security)); // (100000 * 2 * 0.95) / (25 * 100 contract multiplier) - 1 order due to fees Assert.AreEqual(75m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); var expectedBuyingPower = algo.Portfolio.Cash * (1 - requiredFreeBuyingPowerPercent); Assert.AreEqual(expectedBuyingPower, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Buy)); } [Test] public void FreeBuyingPowerPercentDefault_Future() { var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 5, SecurityType.Future, "ES", time: new DateTime(2020, 1, 27)); var model = security.BuyingPowerModel; var actual = algo.CalculateOrderQuantity(_symbol, 1m * model.GetLeverage(security)); // (100000 * 1 * 0.9975 ) / 6600 - 1 order due to fees Assert.AreEqual(13m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); Assert.AreEqual(algo.Portfolio.Cash, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Buy)); } [Test] public void FreeBuyingPowerPercentAppliesForCashAccount_Future() { var algo = GetAlgorithm(); algo.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Cash); var security = InitAndGetSecurity(algo, 5, SecurityType.Future); var requiredFreeBuyingPowerPercent = 0.05m; var model = security.BuyingPowerModel = new SecurityMarginModel(1, requiredFreeBuyingPowerPercent); var actual = algo.CalculateOrderQuantity(_symbol, 1m * model.GetLeverage(security)); // ((100000 - 5) * 1 * 0.95 * 0.9975 / (25 * 50) Assert.AreEqual(75m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); var expectedBuyingPower = algo.Portfolio.Cash * (1 - requiredFreeBuyingPowerPercent); Assert.AreEqual(expectedBuyingPower, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Buy)); } [Test] public void FreeBuyingPowerPercentAppliesForMarginAccount_Future() { var algo = GetAlgorithm(); algo.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Margin); var security = InitAndGetSecurity(algo, 5, SecurityType.Future); var requiredFreeBuyingPowerPercent = 0.05m; var model = security.BuyingPowerModel = new SecurityMarginModel(2, requiredFreeBuyingPowerPercent); var actual = algo.CalculateOrderQuantity(_symbol, 1m * model.GetLeverage(security)); // ((100000 - 5) * 2 * 0.95 * 0.9975 / (25 * 50) Assert.AreEqual(151m, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); var expectedBuyingPower = algo.Portfolio.Cash * (1 - requiredFreeBuyingPowerPercent); Assert.AreEqual(expectedBuyingPower, model.GetBuyingPower(algo.Portfolio, security, OrderDirection.Buy)); } [TestCase(0)] [TestCase(10000)] public void NonAccountCurrency_GetBuyingPower(decimal nonAccountCurrencyCash) { var algo = GetAlgorithm(); algo.Portfolio.CashBook.Clear(); algo.Portfolio.SetAccountCurrency("EUR"); algo.Portfolio.SetCash(10000); algo.Portfolio.SetCash(Currencies.USD, nonAccountCurrencyCash, 0.88m); var security = InitAndGetSecurity(algo, 0); Assert.AreEqual(10000m + algo.Portfolio.CashBook[Currencies.USD].ValueInAccountCurrency, algo.Portfolio.TotalPortfolioValue); var quantity = security.BuyingPowerModel.GetBuyingPower( new BuyingPowerParameters(algo.Portfolio, security, OrderDirection.Buy)).Value; Assert.AreEqual(10000m + algo.Portfolio.CashBook[Currencies.USD].ValueInAccountCurrency, quantity); } [Test] public void NonAccountCurrencyFees() { var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 0); algo.SetCash("EUR", 0, 100); security.FeeModel = new NonAccountCurrencyCustomFeeModel(); // ((100000 - 100 * 100) * 2 * 0.9975 / (25) var actual = algo.CalculateOrderQuantity(_symbol, 1m * security.BuyingPowerModel.GetLeverage(security)); Assert.AreEqual(7182m, actual); // ((100000 - 100 * 100) * 2 / (25) var quantity = security.BuyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower( algo.Portfolio, security, 1m, 0).Quantity; Assert.AreEqual(7200m, quantity); // the maximum order quantity can be executed Assert.IsTrue(HasSufficientBuyingPowerForOrder(quantity, security, algo)); ; } [TestCase(1)] [TestCase(-1)] public void GetMaximumOrderQuantityForTargetDeltaBuyingPower_NoHoldings(int side) { var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 5); // we use our entire buying power var buyingPower = algo.Portfolio.MarginRemaining * side; var actual = security.BuyingPowerModel.GetMaximumOrderQuantityForDeltaBuyingPower( new GetMaximumOrderQuantityForDeltaBuyingPowerParameters(algo.Portfolio, security, buyingPower, 0)).Quantity; // (100000 * 2 ) / 25 =8k - 1 fees Assert.AreEqual(7999 * side, actual); } [TestCase(100, 510, false)] [TestCase(-100, 510, false)] [TestCase(-100, 50000, true)] [TestCase(100, -510, false)] [TestCase(-100, -510, false)] [TestCase(100, -50000, true)] public void GetMaximumOrderQuantityForTargetDeltaBuyingPower_WithHoldings(decimal quantity, decimal buyingPowerDelta, bool invertsSide) { // TPV = 100k var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 0); // SPY @ $25 * Quantity Shares = Holdings // Quantity = 100 -> 2500; TPV = 102500 // Quantity = -100 -> -2500; TPV = 97500 security.Holdings.SetHoldings(security.Price, quantity); // Used Buying Power = Holdings / Leverage // Target BP = Used BP + buyingPowerDelta // Target Holdings = Target BP / Unit // Max Order For Delta BP = Target Holdings - Current Holdings // EX. -100 Quantity, 510 BP Delta. // Used BP = -2500 / 2 = -1250 // Target BP = -1250 + 510 = -740 // Target Holdings = -740 / 12.5 = -59.2 -> ~-59 // Max Order = -59 - (-100) = 41 var actual = security.BuyingPowerModel.GetMaximumOrderQuantityForDeltaBuyingPower( new GetMaximumOrderQuantityForDeltaBuyingPowerParameters(algo.Portfolio, security, buyingPowerDelta, 0)).Quantity; // Calculate expected using logic above var targetBuyingPower = ((quantity * (security.Price / security.Leverage)) + buyingPowerDelta); var targetHoldings = (targetBuyingPower / (security.Price / security.Leverage)); targetHoldings -= (targetHoldings % security.SymbolProperties.LotSize); var expectedQuantity = targetHoldings - quantity; Assert.AreEqual(expectedQuantity, actual); Assert.IsTrue(HasSufficientBuyingPowerForOrder(actual, security, algo)); if (invertsSide) { Assert.AreNotEqual(Math.Sign(quantity), Math.Sign(actual)); } } [TestCase(true, 1, 1)] [TestCase(true, 1, -1)] [TestCase(true, -1, -1)] [TestCase(true, -1, 1)] // reducing the position to target 0 is valid [TestCase(false, 0, -1)] [TestCase(false, 0, 1)] public void NegativeMarginRemaining(bool isError, int target, int side) { var algo = GetAlgorithm(); var security = InitAndGetSecurity(algo, 5); security.Holdings.SetHoldings(security.Price, 1000 * side); algo.Portfolio.CashBook.Add(algo.AccountCurrency, -100000, 1); var fakeOrderProcessor = new FakeOrderProcessor(); algo.Transactions.SetOrderProcessor(fakeOrderProcessor); Assert.IsTrue(algo.Portfolio.MarginRemaining < 0); var quantity = security.BuyingPowerModel.GetMaximumOrderQuantityForTargetBuyingPower( new GetMaximumOrderQuantityForTargetBuyingPowerParameters(algo.Portfolio, security, target * side, 0)).Quantity; if (!isError) { Assert.AreEqual(1000 * side * -1, quantity); } else { // even if we don't have margin 'GetMaximumOrderQuantityForTargetBuyingPower' doesn't care Assert.AreNotEqual(0, quantity); } var order = new MarketOrder(security.Symbol, quantity, new DateTime(2020, 1, 1)); fakeOrderProcessor.AddTicket(order.ToOrderTicket(algo.Transactions)); var actual = security.BuyingPowerModel.HasSufficientBuyingPowerForOrder( new HasSufficientBuyingPowerForOrderParameters(algo.Portfolio, security, order)); Assert.AreEqual(!isError, actual.IsSufficient); } private static QCAlgorithm GetAlgorithm() { SymbolCache.Clear(); // Initialize algorithm var algo = new QCAlgorithm(); algo.SetFinishedWarmingUp(); _fakeOrderProcessor = new FakeOrderProcessor(); algo.Transactions.SetOrderProcessor(_fakeOrderProcessor); return algo; } private static Security InitAndGetSecurity(QCAlgorithm algo, decimal fee, SecurityType securityType = SecurityType.Equity, string symbol = "SPY", DateTime? time = null) { algo.SubscriptionManager.SetDataManager(new DataManagerStub(algo)); Security security; if (securityType == SecurityType.Equity) { security = algo.AddEquity(symbol); _symbol = security.Symbol; } else if (securityType == SecurityType.Option) { security = algo.AddOption(symbol); _symbol = security.Symbol; } else if (securityType == SecurityType.Future) { security = algo.AddFuture(symbol == "SPY" ? "ES" : symbol); _symbol = security.Symbol; } else { throw new Exception("SecurityType not implemented"); } security.FeeModel = new ConstantFeeModel(fee); Update(security, 25, time); return security; } private static void Update(Security security, decimal close, DateTime? time = null) { security.SetMarketPrice(new TradeBar { Time = time ?? DateTime.Now, Symbol = security.Symbol, Open = close, High = close, Low = close, Close = close }); } private bool HasSufficientBuyingPowerForOrder(decimal orderQuantity, Security security, IAlgorithm algo) { var order = new MarketOrder(security.Symbol, orderQuantity, DateTime.UtcNow); _fakeOrderProcessor.AddTicket(order.ToOrderTicket(algo.Transactions)); var hashSufficientBuyingPower = security.BuyingPowerModel.HasSufficientBuyingPowerForOrder(algo.Portfolio, security, new MarketOrder(security.Symbol, orderQuantity, DateTime.UtcNow)); return hashSufficientBuyingPower.IsSufficient; } internal class NonAccountCurrencyCustomFeeModel : FeeModel { public string FeeCurrency = "EUR"; public decimal FeeAmount = 100m; public override OrderFee GetOrderFee(OrderFeeParameters parameters) { return new OrderFee(new CashAmount(FeeAmount, FeeCurrency)); } } } }
using System; using System.Collections.Generic; using UnityEngine; using KSP.Localization; namespace KERBALISM { public class Emitter : PartModule, ISpecifics, IKerbalismModule { // config [KSPField] public string active; // name of animation to play when enabling/disabling [KSPField(isPersistant = true)] public string title = string.Empty; // GUI name of the status action in the PAW [KSPField(isPersistant = true)] public bool toggle; // true if the effect can be toggled on/off [KSPField(isPersistant = true)] public double radiation; // radiation in rad/s [KSPField(isPersistant = true)] public double ec_rate; // EC consumption rate per-second (optional) [KSPField(isPersistant = true)] public bool running; [KSPField(isPersistant = true)] public double radiation_impact = 1.0; // calculated based on vessel design [KSPField(guiActive = true, guiActiveEditor = true, guiName = "_", groupName = "Radiation", groupDisplayName = "#KERBALISM_Group_Radiation")]//Radiation public string Status; // rate of radiation emitted/shielded // animations Animator active_anim; bool radiation_impact_calculated = false; // pseudo-ctor public override void OnStart(StartState state) { // don't break tutorial scenarios if (Lib.DisableScenario(this)) return; // update RMB ui if (string.IsNullOrEmpty(title)) title = radiation >= 0.0 ? "Radiation" : "Active shield"; Fields["Status"].guiName = title; Events["Toggle"].active = toggle; Actions["Action"].active = toggle; // deal with non-toggable emitters if (!toggle) running = true; // create animator active_anim = new Animator(part, active); // set animation initial state active_anim.Still(running ? 0.0 : 1.0); } public class HabitatInfo { public Habitat habitat; public float distance; public HabitatInfo(Habitat habitat, float distance) { this.habitat = habitat; this.distance = distance; } } List<HabitatInfo> habitatInfos = null; public void Recalculate() { habitatInfos = null; CalculateRadiationImpact(); } public void BuildHabitatInfos() { if (habitatInfos != null) return; if (part.transform == null) return; var emitterPosition = part.transform.position; List<Habitat> habitats; if (Lib.IsEditor()) { habitats = new List<Habitat>(); List<Part> parts = Lib.GetPartsRecursively(EditorLogic.RootPart); foreach (var p in parts) { var habitat = p.FindModuleImplementing<Habitat>(); if (habitat != null) habitats.Add(habitat); } } else { habitats = vessel.FindPartModulesImplementing<Habitat>(); } habitatInfos = new List<HabitatInfo>(); foreach (var habitat in habitats) { var habitatPosition = habitat.part.transform.position; var vector = habitatPosition - emitterPosition; HabitatInfo spi = new HabitatInfo(habitat, vector.magnitude); habitatInfos.Add(spi); } } /// <summary>Calculate the average radiation effect to all habitats. returns true if successful.</summary> public bool CalculateRadiationImpact() { if (radiation < 0) { radiation_impact = 1.0; return true; } if (habitatInfos == null) BuildHabitatInfos(); if (habitatInfos == null) return false; radiation_impact = 0.0; int habitatCount = 0; foreach (var hi in habitatInfos) { radiation_impact += Radiation.DistanceRadiation(1.0, hi.distance); habitatCount++; } if (habitatCount > 1) radiation_impact /= habitatCount; return true; } public void Update() { // update ui Status = running ? Lib.HumanReadableRadiation(Math.Abs(radiation)) : Local.Emitter_none;//"none" Events["Toggle"].guiName = Lib.StatusToggle(part.partInfo.title, running ? Local.Generic_ACTIVE : Local.Generic_DISABLED); } public void FixedUpdate() { if (!radiation_impact_calculated) radiation_impact_calculated = CalculateRadiationImpact(); } // See IKerbalismModule public static string BackgroundUpdate(Vessel v, ProtoPartSnapshot part_snapshot, ProtoPartModuleSnapshot module_snapshot, PartModule proto_part_module, Part proto_part, Dictionary<string, double> availableResources, List<KeyValuePair<string, double>> resourceChangeRequest, double elapsed_s) { Emitter emitter = proto_part_module as Emitter; if (emitter == null) return string.Empty; if (Lib.Proto.GetBool(module_snapshot, "running") && emitter.ec_rate > 0) { resourceChangeRequest.Add(new KeyValuePair<string, double>("ElectricCharge", -emitter.ec_rate)); } return emitter.title; } public virtual string ResourceUpdate(Dictionary<string, double> availableResources, List<KeyValuePair<string, double>> resourceChangeRequest) { // if enabled, and there is ec consumption if (running && ec_rate > 0) { resourceChangeRequest.Add(new KeyValuePair<string, double>("ElectricCharge", -ec_rate)); } return title; } public string PlannerUpdate(List<KeyValuePair<string, double>> resourceChangeRequest, CelestialBody body, Dictionary<string, double> environment) { return ResourceUpdate(null, resourceChangeRequest); } [KSPEvent(guiActive = true, guiActiveEditor = true, guiName = "_", active = true, groupName = "Radiation", groupDisplayName = "#KERBALISM_Group_Radiation")]//Radiation public void Toggle() { // switch status running = !running; // play animation active_anim.Play(running, false); // refresh VAB/SPH ui if (Lib.IsEditor()) GameEvents.onEditorShipModified.Fire(EditorLogic.fetch.ship); } // action groups [KSPAction("#KERBALISM_Emitter_Action")] public void Action(KSPActionParam param) { Toggle(); } // part tooltip public override string GetInfo() { string desc = radiation > double.Epsilon ? Local.Emitter_EmitIonizing : Local.Emitter_ReduceIncoming; return Specs().Info(desc); } // specifics support public Specifics Specs() { Specifics specs = new Specifics(); specs.Add(radiation >= 0.0 ? Local.Emitter_Emitted : Local.Emitter_ActiveShielding, Lib.HumanReadableRadiation(Math.Abs(radiation))); if (ec_rate > double.Epsilon) specs.Add("EC/s", Lib.HumanReadableRate(ec_rate)); return specs; } /// <summary> /// get the total radiation emitted by nearby emitters (used for EVAs). only works for loaded vessels. /// </summary> public static double Nearby(Vessel v) { if (!v.loaded || !v.isEVA) return 0.0; var evaPosition = v.rootPart.transform.position; double result = 0.0; foreach (Vessel n in FlightGlobals.VesselsLoaded) { var vd = n.KerbalismData(); if (!vd.IsSimulated) continue; foreach (var emitter in Lib.FindModules<Emitter>(n)) { if (emitter.part == null || emitter.part.transform == null) continue; if (emitter.radiation <= 0) continue; // ignore shielding effects here if (!emitter.running) continue; var emitterPosition = emitter.part.transform.position; var vector = evaPosition - emitterPosition; var distance = vector.magnitude; result += Radiation.DistanceRadiation(emitter.radiation, distance); } } return result; } // return total radiation emitted in a vessel public static double Total(Vessel v) { // get resource cache ResourceInfo ec = ResourceCache.GetResource(v, "ElectricCharge"); double tot = 0.0; if (v.loaded) { foreach (var emitter in Lib.FindModules<Emitter>(v)) { if (ec.Amount > double.Epsilon || emitter.ec_rate <= double.Epsilon) { if (emitter.running) { if (emitter.radiation > 0) tot += emitter.radiation * emitter.radiation_impact; else tot += emitter.radiation; // always account for full shielding effect } } } } else { foreach (ProtoPartModuleSnapshot m in Lib.FindModules(v.protoVessel, "Emitter")) { if (ec.Amount > double.Epsilon || Lib.Proto.GetDouble(m, "ec_rate") <= double.Epsilon) { if (Lib.Proto.GetBool(m, "running")) { var rad = Lib.Proto.GetDouble(m, "radiation"); if (rad < 0) tot += rad; else { tot += rad * Lib.Proto.GetDouble(m, "radiation_factor"); } } } } } return tot; } } } // KERBALISM
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.GrainDirectory; namespace Orleans.Runtime.GrainDirectory { [Serializable] internal class ActivationInfo : IActivationInfo { public SiloAddress SiloAddress { get; private set; } public DateTime TimeCreated { get; private set; } public GrainDirectoryEntryStatus RegistrationStatus { get; set; } public ActivationInfo(SiloAddress siloAddress, GrainDirectoryEntryStatus registrationStatus) { SiloAddress = siloAddress; TimeCreated = DateTime.UtcNow; RegistrationStatus = registrationStatus; } public ActivationInfo(IActivationInfo iActivationInfo) { SiloAddress = iActivationInfo.SiloAddress; TimeCreated = iActivationInfo.TimeCreated; RegistrationStatus = iActivationInfo.RegistrationStatus; } public bool OkToRemove(UnregistrationCause cause, TimeSpan lazyDeregistrationDelay) { switch (cause) { case UnregistrationCause.Force: return true; case UnregistrationCause.CacheInvalidation: return RegistrationStatus == GrainDirectoryEntryStatus.Cached; case UnregistrationCause.NonexistentActivation: { if (RegistrationStatus == GrainDirectoryEntryStatus.Cached) return true; // cache entries are always removed var delayparameter = lazyDeregistrationDelay; if (delayparameter <= TimeSpan.Zero) return false; // no lazy deregistration else return (TimeCreated <= DateTime.UtcNow - delayparameter); } default: throw new OrleansException("unhandled case"); } } public override string ToString() { return String.Format("{0}, {1}", SiloAddress, TimeCreated); } } [Serializable] internal class GrainInfo : IGrainInfo { public Dictionary<ActivationId, IActivationInfo> Instances { get; private set; } public int VersionTag { get; private set; } public bool SingleInstance { get; private set; } private static readonly SafeRandom rand; internal const int NO_ETAG = -1; static GrainInfo() { rand = new SafeRandom(); } internal GrainInfo() { Instances = new Dictionary<ActivationId, IActivationInfo>(); VersionTag = 0; SingleInstance = false; } public bool AddActivation(ActivationId act, SiloAddress silo) { if (SingleInstance && (Instances.Count > 0) && !Instances.ContainsKey(act)) { throw new InvalidOperationException( "Attempting to add a second activation to an existing grain in single activation mode"); } IActivationInfo info; if (Instances.TryGetValue(act, out info)) { if (info.SiloAddress.Equals(silo)) { // just refresh, no need to generate new VersionTag return false; } } Instances[act] = new ActivationInfo(silo, GrainDirectoryEntryStatus.ClusterLocal); VersionTag = rand.Next(); return true; } public ActivationAddress AddSingleActivation(GrainId grain, ActivationId act, SiloAddress silo, GrainDirectoryEntryStatus registrationStatus) { SingleInstance = true; if (Instances.Count > 0) { var item = Instances.First(); return ActivationAddress.GetAddress(item.Value.SiloAddress, grain, item.Key); } else { Instances.Add(act, new ActivationInfo(silo, registrationStatus)); VersionTag = rand.Next(); return ActivationAddress.GetAddress(silo, grain, act); } } public bool RemoveActivation(ActivationId act, UnregistrationCause cause, TimeSpan lazyDeregistrationDelay, out IActivationInfo info, out bool wasRemoved) { info = null; wasRemoved = false; if (Instances.TryGetValue(act, out info) && info.OkToRemove(cause, lazyDeregistrationDelay)) { Instances.Remove(act); wasRemoved = true; VersionTag = rand.Next(); } return Instances.Count == 0; } public Dictionary<SiloAddress, List<ActivationAddress>> Merge(GrainId grain, IGrainInfo other) { bool modified = false; foreach (var pair in other.Instances) { if (Instances.ContainsKey(pair.Key)) continue; Instances[pair.Key] = new ActivationInfo(pair.Value.SiloAddress, pair.Value.RegistrationStatus); modified = true; } if (modified) { VersionTag = rand.Next(); } if (SingleInstance && (Instances.Count > 0)) { // Grain is supposed to be in single activation mode, but we have two activations!! // Eventually we should somehow delegate handling this to the silo, but for now, we'll arbitrarily pick one value. var orderedActivations = Instances.OrderBy(pair => pair.Key); var activationToKeep = orderedActivations.First(); var activationsToDrop = orderedActivations.Skip(1); Instances.Clear(); Instances.Add(activationToKeep.Key, activationToKeep.Value); var mapping = new Dictionary<SiloAddress, List<ActivationAddress>>(); foreach (var activationPair in activationsToDrop) { var activation = ActivationAddress.GetAddress(activationPair.Value.SiloAddress, grain, activationPair.Key); List<ActivationAddress> activationsToRemoveOnSilo; if (!mapping.TryGetValue(activation.Silo, out activationsToRemoveOnSilo)) { activationsToRemoveOnSilo = mapping[activation.Silo] = new List<ActivationAddress>(1); } activationsToRemoveOnSilo.Add(activation); } return mapping; } return null; } public void CacheOrUpdateRemoteClusterRegistration(GrainId grain, ActivationId oldActivation, ActivationId activation, SiloAddress silo) { SingleInstance = true; if (Instances.Count > 0) { Instances.Remove(oldActivation); } Instances.Add(activation, new ActivationInfo(silo, GrainDirectoryEntryStatus.Cached)); } public bool UpdateClusterRegistrationStatus(ActivationId activationId, GrainDirectoryEntryStatus status, GrainDirectoryEntryStatus? compareWith = null) { IActivationInfo activationInfo; if (!Instances.TryGetValue(activationId, out activationInfo)) return false; if (compareWith.HasValue && compareWith.Value != activationInfo.RegistrationStatus) return false; activationInfo.RegistrationStatus = status; return true; } } internal class GrainDirectoryPartition { // Should we change this to SortedList<> or SortedDictionary so we can extract chunks better for shipping the full // parition to a follower, or should we leave it as a Dictionary to get O(1) lookups instead of O(log n), figuring we do // a lot more lookups and so can sort periodically? /// <summary> /// contains a map from grain to its list of activations along with the version (etag) counter for the list /// </summary> private Dictionary<GrainId, IGrainInfo> partitionData; private readonly object lockable; private readonly ILogger log; private readonly ILoggerFactory loggerFactory; private readonly ISiloStatusOracle siloStatusOracle; private readonly IInternalGrainFactory grainFactory; private readonly IOptions<GrainDirectoryOptions> grainDirectoryOptions; [ThreadStatic] private static ActivationId[] activationIdsHolder; [ThreadStatic] private static IActivationInfo[] activationInfosHolder; internal int Count { get { return partitionData.Count; } } public GrainDirectoryPartition(ISiloStatusOracle siloStatusOracle, IOptions<GrainDirectoryOptions> grainDirectoryOptions, IInternalGrainFactory grainFactory, ILoggerFactory loggerFactory) { partitionData = new Dictionary<GrainId, IGrainInfo>(); lockable = new object(); log = loggerFactory.CreateLogger<GrainDirectoryPartition>(); this.siloStatusOracle = siloStatusOracle; this.grainDirectoryOptions = grainDirectoryOptions; this.grainFactory = grainFactory; this.loggerFactory = loggerFactory; } private bool IsValidSilo(SiloAddress silo) { return this.siloStatusOracle.IsFunctionalDirectory(silo); } internal void Clear() { lock (lockable) { partitionData.Clear(); } } /// <summary> /// Returns all entries stored in the partition as an enumerable collection /// </summary> /// <returns></returns> public Dictionary<GrainId, IGrainInfo> GetItems() { lock (lockable) { return partitionData.Copy(); } } /// <summary> /// Adds a new activation to the directory partition /// </summary> /// <param name="grain"></param> /// <param name="activation"></param> /// <param name="silo"></param> /// <returns>The version associated with this directory mapping</returns> internal virtual int AddActivation(GrainId grain, ActivationId activation, SiloAddress silo) { if (!IsValidSilo(silo)) { return GrainInfo.NO_ETAG; } IGrainInfo grainInfo; lock (lockable) { if (!partitionData.TryGetValue(grain, out grainInfo)) { partitionData[grain] = grainInfo = new GrainInfo(); } grainInfo.AddActivation(activation, silo); } if (log.IsEnabled(LogLevel.Trace)) log.Trace("Adding activation for grain {0}", grain.ToString()); return grainInfo.VersionTag; } /// <summary> /// Adds a new activation to the directory partition /// </summary> /// <param name="grain"></param> /// <param name="activation"></param> /// <param name="silo"></param> /// <param name="registrationStatus"></param> /// <returns>The registered ActivationAddress and version associated with this directory mapping</returns> internal virtual AddressAndTag AddSingleActivation(GrainId grain, ActivationId activation, SiloAddress silo, GrainDirectoryEntryStatus registrationStatus) { if (log.IsEnabled(LogLevel.Trace)) log.Trace("Adding single activation for grain {0}{1}{2}", silo, grain, activation); AddressAndTag result = new AddressAndTag(); if (!IsValidSilo(silo)) return result; IGrainInfo grainInfo; lock (lockable) { if (!partitionData.TryGetValue(grain, out grainInfo)) { partitionData[grain] = grainInfo = new GrainInfo(); } result.Address = grainInfo.AddSingleActivation(grain, activation, silo, registrationStatus); result.VersionTag = grainInfo.VersionTag; } return result; } /// <summary> /// Removes an activation of the given grain from the partition /// </summary> /// <param name="grain">the identity of the grain</param> /// <param name="activation">the id of the activation</param> /// <param name="cause">reason for removing the activation</param> internal void RemoveActivation(GrainId grain, ActivationId activation, UnregistrationCause cause = UnregistrationCause.Force) { IActivationInfo ignore1; bool ignore2; RemoveActivation(grain, activation, cause, out ignore1, out ignore2); } /// <summary> /// Removes an activation of the given grain from the partition /// </summary> /// <param name="grain">the identity of the grain</param> /// <param name="activation">the id of the activation</param> /// <param name="cause">reason for removing the activation</param> /// <param name="entry">returns the entry, if found </param> /// <param name="wasRemoved">returns whether the entry was actually removed</param> internal void RemoveActivation(GrainId grain, ActivationId activation, UnregistrationCause cause, out IActivationInfo entry, out bool wasRemoved) { wasRemoved = false; entry = null; lock (lockable) { if (partitionData.ContainsKey(grain) && partitionData[grain].RemoveActivation(activation, cause, this.grainDirectoryOptions.Value.LazyDeregistrationDelay, out entry, out wasRemoved)) // if the last activation for the grain was removed, we remove the entire grain info partitionData.Remove(grain); } if (log.IsEnabled(LogLevel.Trace)) log.Trace("Removing activation for grain {0} cause={1} was_removed={2}", grain.ToString(), cause, wasRemoved); } /// <summary> /// Removes the grain (and, effectively, all its activations) from the directory /// </summary> /// <param name="grain"></param> internal void RemoveGrain(GrainId grain) { lock (lockable) { partitionData.Remove(grain); } if (log.IsEnabled(LogLevel.Trace)) log.Trace("Removing grain {0}", grain.ToString()); } /// <summary> /// Returns a list of activations (along with the version number of the list) for the given grain. /// If the grain is not found, null is returned. /// </summary> /// <param name="grain"></param> /// <returns></returns> internal AddressesAndTag LookUpActivations(GrainId grain) { var result = new AddressesAndTag(); ActivationId[] activationIds; IActivationInfo[] activationInfos; const int arrayReusingThreshold = 100; int grainInfoInstancesCount; lock (lockable) { IGrainInfo graininfo; if (!partitionData.TryGetValue(grain, out graininfo)) { return result; } result.VersionTag = graininfo.VersionTag; grainInfoInstancesCount = graininfo.Instances.Count; if (grainInfoInstancesCount < arrayReusingThreshold) { if ((activationIds = activationIdsHolder) == null) { activationIdsHolder = activationIds = new ActivationId[arrayReusingThreshold]; } if ((activationInfos = activationInfosHolder) == null) { activationInfosHolder = activationInfos = new IActivationInfo[arrayReusingThreshold]; } } else { activationIds = new ActivationId[grainInfoInstancesCount]; activationInfos = new IActivationInfo[grainInfoInstancesCount]; } graininfo.Instances.Keys.CopyTo(activationIds, 0); graininfo.Instances.Values.CopyTo(activationInfos, 0); } result.Addresses = new List<ActivationAddress>(grainInfoInstancesCount); for (var i = 0; i < grainInfoInstancesCount; i++) { var activationInfo = activationInfos[i]; if (IsValidSilo(activationInfo.SiloAddress)) { result.Addresses.Add(ActivationAddress.GetAddress(activationInfo.SiloAddress, grain, activationIds[i])); } activationInfos[i] = null; activationIds[i] = null; } return result; } /// <summary> /// Returns the activation of a single-activation grain, if present. /// </summary> internal GrainDirectoryEntryStatus TryGetActivation(GrainId grain, out ActivationAddress address, out int version) { IGrainInfo grainInfo; address = null; version = 0; lock (lockable) { if (!partitionData.TryGetValue(grain, out grainInfo)) { return GrainDirectoryEntryStatus.Invalid; } var first = grainInfo.Instances.FirstOrDefault(); if (first.Value != null) { address = ActivationAddress.GetAddress(first.Value.SiloAddress, grain, first.Key); version = grainInfo.VersionTag; return first.Value.RegistrationStatus; } } return GrainDirectoryEntryStatus.Invalid; } /// <summary> /// Returns the version number of the list of activations for the grain. /// If the grain is not found, -1 is returned. /// </summary> /// <param name="grain"></param> /// <returns></returns> internal int GetGrainETag(GrainId grain) { IGrainInfo grainInfo; lock (lockable) { if (!partitionData.TryGetValue(grain, out grainInfo)) { return GrainInfo.NO_ETAG; } return grainInfo.VersionTag; } } /// <summary> /// Merges one partition into another, assuming partitions are disjoint. /// This method is supposed to be used by handoff manager to update the partitions when the system view (set of live silos) changes. /// </summary> /// <param name="other"></param> /// <returns>Activations which must be deactivated.</returns> internal Dictionary<SiloAddress, List<ActivationAddress>> Merge(GrainDirectoryPartition other) { Dictionary<SiloAddress, List<ActivationAddress>> activationsToRemove = null; lock (lockable) { foreach (var pair in other.partitionData) { if (partitionData.ContainsKey(pair.Key)) { if (log.IsEnabled(LogLevel.Debug)) log.Debug("While merging two disjoint partitions, same grain " + pair.Key + " was found in both partitions"); var activationsToDrop = partitionData[pair.Key].Merge(pair.Key, pair.Value); if (activationsToDrop == null) continue; if (activationsToRemove == null) activationsToRemove = new Dictionary<SiloAddress, List<ActivationAddress>>(); foreach (var siloActivations in activationsToDrop) { if (activationsToRemove.TryGetValue(siloActivations.Key, out var activations)) { activations.AddRange(siloActivations.Value); } else { activationsToRemove[siloActivations.Key] = siloActivations.Value; } } } else { partitionData.Add(pair.Key, pair.Value); } } } return activationsToRemove; } /// <summary> /// Runs through all entries in the partition and moves/copies (depending on the given flag) the /// entries satisfying the given predicate into a new partition. /// This method is supposed to be used by handoff manager to update the partitions when the system view (set of live silos) changes. /// </summary> /// <param name="predicate">filter predicate (usually if the given grain is owned by particular silo)</param> /// <param name="modifyOrigin">flag controlling whether the source partition should be modified (i.e., the entries should be moved or just copied) </param> /// <returns>new grain directory partition containing entries satisfying the given predicate</returns> internal GrainDirectoryPartition Split(Predicate<GrainId> predicate, bool modifyOrigin) { var newDirectory = new GrainDirectoryPartition(this.siloStatusOracle, this.grainDirectoryOptions, this.grainFactory, this.loggerFactory); if (modifyOrigin) { // SInce we use the "pairs" list to modify the underlying collection below, we need to turn it into an actual list here List<KeyValuePair<GrainId, IGrainInfo>> pairs; lock (lockable) { pairs = partitionData.Where(pair => predicate(pair.Key)).ToList(); } foreach (var pair in pairs) { newDirectory.partitionData.Add(pair.Key, pair.Value); } lock (lockable) { foreach (var pair in pairs) { partitionData.Remove(pair.Key); } } } else { lock (lockable) { foreach (var pair in partitionData.Where(pair => predicate(pair.Key))) { newDirectory.partitionData.Add(pair.Key, pair.Value); } } } return newDirectory; } internal List<ActivationAddress> ToListOfActivations(bool singleActivation) { var result = new List<ActivationAddress>(); lock (lockable) { foreach (var pair in partitionData) { var grain = pair.Key; if (pair.Value.SingleInstance == singleActivation) { result.AddRange(pair.Value.Instances.Select(activationPair => ActivationAddress.GetAddress(activationPair.Value.SiloAddress, grain, activationPair.Key)) .Where(addr => IsValidSilo(addr.Silo))); } } } return result; } /// <summary> /// Sets the internal partition dictionary to the one given as input parameter. /// This method is supposed to be used by handoff manager to update the old partition with a new partition. /// </summary> /// <param name="newPartitionData">new internal partition dictionary</param> internal void Set(Dictionary<GrainId, IGrainInfo> newPartitionData) { partitionData = newPartitionData; } /// <summary> /// Updates partition with a new delta of changes. /// This method is supposed to be used by handoff manager to update the partition with a set of delta changes. /// </summary> /// <param name="newPartitionDelta">dictionary holding a set of delta updates to this partition. /// If the value for a given key in the delta is valid, then existing entry in the partition is replaced. /// Otherwise, i.e., if the value is null, the corresponding entry is removed. /// </param> internal void Update(Dictionary<GrainId, IGrainInfo> newPartitionDelta) { lock (lockable) { foreach (GrainId grain in newPartitionDelta.Keys) { if (newPartitionDelta[grain] != null) { partitionData[grain] = newPartitionDelta[grain]; } else { partitionData.Remove(grain); } } } } public override string ToString() { var sb = new StringBuilder(); lock (lockable) { foreach (var grainEntry in partitionData) { foreach (var activationEntry in grainEntry.Value.Instances) { sb.Append(" ").Append(grainEntry.Key.ToString()).Append("[" + grainEntry.Value.VersionTag + "]"). Append(" => ").Append(activationEntry.Key.ToString()). Append(" @ ").AppendLine(activationEntry.Value.ToString()); } } } return sb.ToString(); } public void CacheOrUpdateRemoteClusterRegistration(GrainId grain, ActivationId oldActivation, ActivationAddress otherClusterAddress) { lock (lockable) { if (partitionData.ContainsKey(grain)) { partitionData[grain].CacheOrUpdateRemoteClusterRegistration(grain, oldActivation, otherClusterAddress.Activation, otherClusterAddress.Silo); } else { AddSingleActivation(grain, otherClusterAddress.Activation, otherClusterAddress.Silo, GrainDirectoryEntryStatus.Cached); } } } public bool UpdateClusterRegistrationStatus(GrainId grain, ActivationId activationId, GrainDirectoryEntryStatus registrationStatus, GrainDirectoryEntryStatus? compareWith = null) { lock (lockable) { IGrainInfo graininfo; if (partitionData.TryGetValue(grain, out graininfo)) { return graininfo.UpdateClusterRegistrationStatus(activationId, registrationStatus, compareWith); } return false; } } } }
// Original source: http://servicestack.googlecode.com/svn/trunk/Common/ServiceStack.Redis/ServiceStack.Redis/Support/OrderedDictionary.cs using System; using System.Collections; using System.Collections.Generic; using System.Threading; namespace BitCoinSharp.Collections.Generic { /// <summary> /// Represents a generic collection of key/value pairs that are ordered independently of the key and value. /// </summary> /// <typeparam name="TKey">The type of the keys in the dictionary</typeparam> /// <typeparam name="TValue">The type of the values in the dictionary</typeparam> internal class OrderedDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary { private const int _defaultInitialCapacity = 0; private static readonly string _keyTypeName = typeof (TKey).FullName; private static readonly string _valueTypeName = typeof (TValue).FullName; private static readonly bool _valueTypeIsReferenceType = !typeof (ValueType).IsAssignableFrom(typeof (TValue)); private Dictionary<TKey, TValue> _dictionary; private List<KeyValuePair<TKey, TValue>> _list; private readonly IEqualityComparer<TKey> _comparer; private object _syncRoot; private readonly int _initialCapacity; /// <summary> /// Initializes a new instance of the <see cref="OrderedDictionary{TKey,TValue}"/> class. /// </summary> public OrderedDictionary() : this(_defaultInitialCapacity, null) { } /// <summary> /// Initializes a new instance of the <see cref="OrderedDictionary{TKey,TValue}"/> class using the specified initial capacity. /// </summary> /// <param name="capacity">The initial number of elements that the <see cref="OrderedDictionary{TKey,TValue}"/> can contain.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="capacity"/> is less than 0</exception> public OrderedDictionary(int capacity) : this(capacity, null) { } /// <summary> /// Initializes a new instance of the <see cref="OrderedDictionary{TKey,TValue}"/> class using the specified comparer. /// </summary> /// <param name="comparer">The <see cref="IEqualityComparer{TKey}"/> to use when comparing keys, or <null/> to use the default <see cref="EqualityComparer{TKey}"/> for the type of the key.</param> public OrderedDictionary(IEqualityComparer<TKey> comparer) : this(_defaultInitialCapacity, comparer) { } /// <summary> /// Initializes a new instance of the <see cref="OrderedDictionary{TKey,TValue}"/> class using the specified initial capacity and comparer. /// </summary> /// <param name="capacity">The initial number of elements that the <see cref="OrderedDictionary{TKey,TValue}"/> collection can contain.</param> /// <param name="comparer">The <see cref="IEqualityComparer{TKey}"/> to use when comparing keys, or <null/> to use the default <see cref="EqualityComparer{TKey}"/> for the type of the key.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="capacity"/> is less than 0</exception> public OrderedDictionary(int capacity, IEqualityComparer<TKey> comparer) { if (0 > capacity) throw new ArgumentOutOfRangeException("capacity", "'capacity' must be non-negative"); _initialCapacity = capacity; _comparer = comparer; } /// <summary> /// Converts the object passed as a key to the key type of the dictionary /// </summary> /// <param name="keyObject">The key object to check</param> /// <returns>The key object, cast as the key type of the dictionary</returns> /// <exception cref="ArgumentNullException"><paramref name="keyObject"/> is <null/>.</exception> /// <exception cref="ArgumentException">The key type of the <see cref="OrderedDictionary{TKey,TValue}"/> is not in the inheritance hierarchy of <paramref name="keyObject"/>.</exception> private static TKey ConvertToKeyType(object keyObject) { if (keyObject == null) { throw new ArgumentNullException("keyObject"); } if (!(keyObject is TKey)) { throw new ArgumentException("'key' must be of type " + _keyTypeName, "keyObject"); } return (TKey) keyObject; } /// <summary> /// Converts the object passed as a value to the value type of the dictionary /// </summary> /// <param name="value">The object to convert to the value type of the dictionary</param> /// <returns>The value object, converted to the value type of the dictionary</returns> /// <exception cref="ArgumentNullException"><paramref name="value"/> is <null/>, and the value type of the <see cref="OrderedDictionary{TKey,TValue}"/> is a value type.</exception> /// <exception cref="ArgumentException">The value type of the <see cref="OrderedDictionary{TKey,TValue}"/> is not in the inheritance hierarchy of <paramref name="value"/>.</exception> private static TValue ConvertToValueType(object value) { if (value == null) { if (!_valueTypeIsReferenceType) throw new ArgumentNullException("value"); return default(TValue); } if (!(value is TValue)) throw new ArgumentException("'value' must be of type " + _valueTypeName, "value"); return (TValue) value; } /// <summary> /// Gets the dictionary object that stores the keys and values /// </summary> /// <value>The dictionary object that stores the keys and values for the <see cref="OrderedDictionary{TKey,TValue}"/></value> /// <remarks>Accessing this property will create the dictionary object if necessary</remarks> private Dictionary<TKey, TValue> Dictionary { get { return _dictionary ?? (_dictionary = new Dictionary<TKey, TValue>(_initialCapacity, _comparer)); } } /// <summary> /// Gets the list object that stores the key/value pairs. /// </summary> /// <value>The list object that stores the key/value pairs for the <see cref="OrderedDictionary{TKey,TValue}"/></value> /// <remarks>Accessing this property will create the list object if necessary.</remarks> private List<KeyValuePair<TKey, TValue>> List { get { return _list ?? (_list = new List<KeyValuePair<TKey, TValue>>(_initialCapacity)); } } IDictionaryEnumerator IDictionary.GetEnumerator() { return Dictionary.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return List.GetEnumerator(); } IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return List.GetEnumerator(); } /// <summary> /// Inserts a new entry into the <see cref="OrderedDictionary{TKey,TValue}"/> collection with the specified key and value at the specified index. /// </summary> /// <param name="index">The zero-based index at which the element should be inserted.</param> /// <param name="key">The key of the entry to add.</param> /// <param name="value">The value of the entry to add. The value can be <null/> if the type of the values in the dictionary is a reference type.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than 0.<br/> /// -or-<br/> /// <paramref name="index"/> is greater than <see cref="Count"/>.</exception> /// <exception cref="ArgumentNullException"><paramref name="key"/> is <null/>.</exception> /// <exception cref="ArgumentException">An element with the same key already exists in the <see cref="OrderedDictionary{TKey,TValue}"/>.</exception> public void Insert(int index, TKey key, TValue value) { if (index > Count || index < 0) throw new ArgumentOutOfRangeException("index"); Dictionary.Add(key, value); List.Insert(index, new KeyValuePair<TKey, TValue>(key, value)); } /// <summary> /// Removes the entry at the specified index from the <see cref="OrderedDictionary{TKey,TValue}"/> collection. /// </summary> /// <param name="index">The zero-based index of the entry to remove.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than 0.<br/> /// -or-<br/> /// index is equal to or greater than <see cref="Count"/>.</exception> public void RemoveAt(int index) { if (index >= Count || index < 0) throw new ArgumentOutOfRangeException("index", "'index' must be non-negative and less than the size of the collection"); var key = List[index].Key; List.RemoveAt(index); Dictionary.Remove(key); } /// <summary> /// Gets or sets the value at the specified index. /// </summary> /// <param name="index">The zero-based index of the value to get or set.</param> /// <value>The value of the item at the specified index.</value> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than 0.<br/> /// -or-<br/> /// index is equal to or greater than <see cref="Count"/>.</exception> public TValue this[int index] { get { return List[index].Value; } set { if (index >= Count || index < 0) throw new ArgumentOutOfRangeException("index", "'index' must be non-negative and less than the size of the collection"); var key = List[index].Key; List[index] = new KeyValuePair<TKey, TValue>(key, value); Dictionary[key] = value; } } /// <summary> /// Adds an entry with the specified key and value into the <see cref="OrderedDictionary{TKey,TValue}"/> collection with the lowest available index. /// </summary> /// <param name="key">The key of the entry to add.</param> /// <param name="value">The value of the entry to add. This value can be <null/>.</param> /// <remarks>A key cannot be <null/>, but a value can be. /// <para>You can also use the indexer property to add new elements by setting the value of a key that does not exist in the <see cref="OrderedDictionary{TKey,TValue}"/> collection; however, if the specified key already exists in the <see cref="OrderedDictionary{TKey,TValue}"/>, setting the indexer property overwrites the old value. In contrast, the <see cref="Add"/> method does not modify existing elements.</para></remarks> /// <exception cref="ArgumentNullException"><paramref name="key"/> is <null/></exception> /// <exception cref="ArgumentException">An element with the same key already exists in the <see cref="OrderedDictionary{TKey,TValue}"/></exception> void IDictionary<TKey, TValue>.Add(TKey key, TValue value) { Add(key, value); } /// <summary> /// Adds an entry with the specified key and value into the <see cref="OrderedDictionary{TKey,TValue}"/> collection with the lowest available index. /// </summary> /// <param name="key">The key of the entry to add.</param> /// <param name="value">The value of the entry to add. This value can be <null/>.</param> /// <returns>The index of the newly added entry</returns> /// <remarks>A key cannot be <null/>, but a value can be. /// <para>You can also use the indexer property to add new elements by setting the value of a key that does not exist in the <see cref="OrderedDictionary{TKey,TValue}"/> collection; however, if the specified key already exists in the <see cref="OrderedDictionary{TKey,TValue}"/>, setting the indexer property overwrites the old value. In contrast, the <see cref="Add"/> method does not modify existing elements.</para></remarks> /// <exception cref="ArgumentNullException"><paramref name="key"/> is <null/></exception> /// <exception cref="ArgumentException">An element with the same key already exists in the <see cref="OrderedDictionary{TKey,TValue}"/></exception> public int Add(TKey key, TValue value) { Dictionary.Add(key, value); List.Add(new KeyValuePair<TKey, TValue>(key, value)); return Count - 1; } /// <summary> /// Adds an entry with the specified key and value into the <see cref="OrderedDictionary{TKey,TValue}"/> collection with the lowest available index. /// </summary> /// <param name="key">The key of the entry to add.</param> /// <param name="value">The value of the entry to add. This value can be <null/>.</param> /// <exception cref="ArgumentNullException"><paramref name="key"/> is <null/>.<br/> /// -or-<br/> /// <paramref name="value"/> is <null/>, and the value type of the <see cref="OrderedDictionary{TKey,TValue}"/> is a value type.</exception> /// <exception cref="ArgumentException">The key type of the <see cref="OrderedDictionary{TKey,TValue}"/> is not in the inheritance hierarchy of <paramref name="key"/>.<br/> /// -or-<br/> /// The value type of the <see cref="OrderedDictionary{TKey,TValue}"/> is not in the inheritance hierarchy of <paramref name="value"/>.</exception> void IDictionary.Add(object key, object value) { Add(ConvertToKeyType(key), ConvertToValueType(value)); } /// <summary> /// Removes all elements from the <see cref="OrderedDictionary{TKey,TValue}"/> collection. /// </summary> /// <remarks>The capacity is not changed as a result of calling this method.</remarks> public void Clear() { Dictionary.Clear(); List.Clear(); } /// <summary> /// Determines whether the <see cref="OrderedDictionary{TKey,TValue}"/> collection contains a specific key. /// </summary> /// <param name="key">The key to locate in the <see cref="OrderedDictionary{TKey,TValue}"/> collection.</param> /// <returns><see langword="true"/> if the <see cref="OrderedDictionary{TKey,TValue}"/> collection contains an element with the specified key; otherwise, <see langword="false"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is <null/></exception> public bool ContainsKey(TKey key) { return Dictionary.ContainsKey(key); } /// <summary> /// Determines whether the <see cref="OrderedDictionary{TKey,TValue}"/> collection contains a specific key. /// </summary> /// <param name="key">The key to locate in the <see cref="OrderedDictionary{TKey,TValue}"/> collection.</param> /// <returns><see langword="true"/> if the <see cref="OrderedDictionary{TKey,TValue}"/> collection contains an element with the specified key; otherwise, <see langword="false"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is <null/></exception> /// <exception cref="ArgumentException">The key type of the <see cref="OrderedDictionary{TKey,TValue}"/> is not in the inheritance hierarchy of <paramref name="key"/>.</exception> bool IDictionary.Contains(object key) { return ContainsKey(ConvertToKeyType(key)); } /// <summary> /// Gets a value indicating whether the <see cref="OrderedDictionary{TKey,TValue}"/> has a fixed size. /// </summary> /// <value><see langword="true"/> if the <see cref="OrderedDictionary{TKey,TValue}"/> has a fixed size; otherwise, <see langword="false"/>. The default is <see langword="false"/>.</value> bool IDictionary.IsFixedSize { get { return false; } } /// <summary> /// Gets a value indicating whether the <see cref="OrderedDictionary{TKey,TValue}"/> collection is read-only. /// </summary> /// <value><see langword="true"/> if the <see cref="OrderedDictionary{TKey,TValue}"/> is read-only; otherwise, <see langword="false"/>. The default is <see langword="false"/>.</value> /// <remarks> /// A collection that is read-only does not allow the addition, removal, or modification of elements after the collection is created. /// <para>A collection that is read-only is simply a collection with a wrapper that prevents modification of the collection; therefore, if changes are made to the underlying collection, the read-only collection reflects those changes.</para> /// </remarks> public bool IsReadOnly { get { return false; } } /// <summary> /// Gets an <see cref="ICollection"/> object containing the keys in the <see cref="OrderedDictionary{TKey,TValue}"/>. /// </summary> /// <value>An <see cref="ICollection"/> object containing the keys in the <see cref="OrderedDictionary{TKey,TValue}"/>.</value> /// <remarks>The returned <see cref="ICollection"/> object is not a static copy; instead, the collection refers back to the keys in the original <see cref="OrderedDictionary{TKey,TValue}"/>. Therefore, changes to the <see cref="OrderedDictionary{TKey,TValue}"/> continue to be reflected in the key collection.</remarks> ICollection IDictionary.Keys { get { return (ICollection) Keys; } } /// <summary> /// Returns the zero-based index of the specified key in the <see cref="OrderedDictionary{TKey,TValue}"/> /// </summary> /// <param name="key">The key to locate in the <see cref="OrderedDictionary{TKey,TValue}"/></param> /// <returns>The zero-based index of <paramref name="key"/>, if <paramref name="key"/> is found in the <see cref="OrderedDictionary{TKey,TValue}"/>; otherwise, -1</returns> /// <remarks>This method performs a linear search; therefore it has a cost of O(n) at worst.</remarks> public int IndexOfKey(TKey key) { if (Equals(key, default (TKey))) throw new ArgumentNullException("key"); for (var index = 0; index < List.Count; index++) { var entry = List[index]; var next = entry.Key; if (null != _comparer) { if (_comparer.Equals(next, key)) { return index; } } else if (next.Equals(key)) { return index; } } return -1; } /// <summary> /// Removes the entry with the specified key from the <see cref="OrderedDictionary{TKey,TValue}"/> collection. /// </summary> /// <param name="key">The key of the entry to remove</param> /// <returns><see langword="true"/> if the key was found and the corresponding element was removed; otherwise, <see langword="false"/></returns> public bool Remove(TKey key) { if (Equals(key, default(TKey))) throw new ArgumentNullException("key"); var index = IndexOfKey(key); if (index >= 0) { if (Dictionary.Remove(key)) { List.RemoveAt(index); return true; } } return false; } /// <summary> /// Removes the entry with the specified key from the <see cref="OrderedDictionary{TKey,TValue}"/> collection. /// </summary> /// <param name="key">The key of the entry to remove</param> void IDictionary.Remove(object key) { Remove(ConvertToKeyType(key)); } /// <summary> /// Gets an <see cref="ICollection"/> object containing the values in the <see cref="OrderedDictionary{TKey,TValue}"/> collection. /// </summary> /// <value>An <see cref="ICollection"/> object containing the values in the <see cref="OrderedDictionary{TKey,TValue}"/> collection.</value> /// <remarks>The returned <see cref="ICollection"/> object is not a static copy; instead, the <see cref="ICollection"/> refers back to the values in the original <see cref="OrderedDictionary{TKey,TValue}"/> collection. Therefore, changes to the <see cref="OrderedDictionary{TKey,TValue}"/> continue to be reflected in the <see cref="ICollection"/>.</remarks> ICollection IDictionary.Values { get { return (ICollection) Values; } } /// <summary> /// Gets or sets the value with the specified key. /// </summary> /// <param name="key">The key of the value to get or set.</param> /// <value>The value associated with the specified key. If the specified key is not found, attempting to get it returns <null/>, and attempting to set it creates a new element using the specified key.</value> public TValue this[TKey key] { get { return Dictionary[key]; } set { if (Dictionary.ContainsKey(key)) { Dictionary[key] = value; List[IndexOfKey(key)] = new KeyValuePair<TKey, TValue>(key, value); } else { Add(key, value); } } } /// <summary> /// Gets or sets the value with the specified key. /// </summary> /// <param name="key">The key of the value to get or set.</param> /// <value>The value associated with the specified key. If the specified key is not found, attempting to get it returns <null/>, and attempting to set it creates a new element using the specified key.</value> object IDictionary.this[object key] { get { return this[ConvertToKeyType(key)]; } set { this[ConvertToKeyType(key)] = ConvertToValueType(value); } } /// <summary> /// Copies the elements of the <see cref="OrderedDictionary{TKey,TValue}"/> elements to a one-dimensional Array object at the specified index. /// </summary> /// <param name="array">The one-dimensional <see cref="Array"/> object that is the destination of the <see cref="KeyValuePair{TKey,TValue}"/> objects copied from the <see cref="OrderedDictionary{TKey,TValue}"/>. The <see cref="Array"/> must have zero-based indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param> /// <remarks>The <see cref="ICollection.CopyTo(Array,int)"/> method preserves the order of the elements in the <see cref="OrderedDictionary{TKey,TValue}"/></remarks> void ICollection.CopyTo(Array array, int index) { ((ICollection) List).CopyTo(array, index); } /// <summary> /// Gets the number of key/values pairs contained in the <see cref="OrderedDictionary{TKey,TValue}"/> collection. /// </summary> /// <value>The number of key/value pairs contained in the <see cref="OrderedDictionary{TKey,TValue}"/> collection.</value> public int Count { get { return List.Count; } } /// <summary> /// Gets a value indicating whether access to the <see cref="OrderedDictionary{TKey,TValue}"/> object is synchronized (thread-safe). /// </summary> /// <value>This method always returns false.</value> bool ICollection.IsSynchronized { get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="OrderedDictionary{TKey,TValue}"/> object. /// </summary> /// <value>An object that can be used to synchronize access to the <see cref="OrderedDictionary{TKey,TValue}"/> object.</value> object ICollection.SyncRoot { get { if (_syncRoot == null) { Interlocked.CompareExchange(ref _syncRoot, new object(), null); } return _syncRoot; } } /// <summary> /// Gets an <see cref="System.Collections.Generic.ICollection{TKey}"/> object containing the keys in the <see cref="OrderedDictionary{TKey,TValue}"/>. /// </summary> /// <value>An <see cref="System.Collections.Generic.ICollection{TKey}"/> object containing the keys in the <see cref="OrderedDictionary{TKey,TValue}"/>.</value> /// <remarks>The returned <see cref="System.Collections.Generic.ICollection{TKey}"/> object is not a static copy; instead, the collection refers back to the keys in the original <see cref="OrderedDictionary{TKey,TValue}"/>. Therefore, changes to the <see cref="OrderedDictionary{TKey,TValue}"/> continue to be reflected in the key collection.</remarks> public ICollection<TKey> Keys { get { return Dictionary.Keys; } } /// <summary> /// Gets the value associated with the specified key. /// </summary> /// <param name="key">The key of the value to get.</param> /// <param name="value">When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of <paramref name="value"/>. This parameter can be passed uninitialized.</param> /// <returns><see langword="true"/> if the <see cref="OrderedDictionary{TKey,TValue}"/> contains an element with the specified key; otherwise, <see langword="false"/>.</returns> public bool TryGetValue(TKey key, out TValue value) { return Dictionary.TryGetValue(key, out value); } /// <summary> /// Gets an <see cref="ICollection{TValue}"/> object containing the values in the <see cref="OrderedDictionary{TKey,TValue}"/>. /// </summary> /// <value>An <see cref="ICollection{TValue}"/> object containing the values in the <see cref="OrderedDictionary{TKey,TValue}"/>.</value> /// <remarks>The returned <see cref="ICollection{TValue}"/> object is not a static copy; instead, the collection refers back to the values in the original <see cref="OrderedDictionary{TKey,TValue}"/>. Therefore, changes to the <see cref="OrderedDictionary{TKey,TValue}"/> continue to be reflected in the value collection.</remarks> public ICollection<TValue> Values { get { return Dictionary.Values; } } /// <summary> /// Adds the specified value to the <see cref="OrderedDictionary{TKey,TValue}"/> with the specified key. /// </summary> /// <param name="item">The <see cref="KeyValuePair{TKey,TValue}"/> structure representing the key and value to add to the <see cref="OrderedDictionary{TKey,TValue}"/>.</param> void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) { Add(item.Key, item.Value); } /// <summary> /// Determines whether the <see cref="OrderedDictionary{TKey,TValue}"/> contains a specific key and value. /// </summary> /// <param name="item">The <see cref="KeyValuePair{TKey,TValue}"/> structure to locate in the <see cref="OrderedDictionary{TKey,TValue}"/>.</param> /// <returns><see langword="true"/> if <paramref name="item"/> is found in the <see cref="OrderedDictionary{TKey,TValue}"/>; otherwise, <see langword="false"/>.</returns> bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) { return ((ICollection<KeyValuePair<TKey, TValue>>) Dictionary).Contains(item); } /// <summary> /// Copies the elements of the <see cref="OrderedDictionary{TKey,TValue}"/> to an array of type <see cref="KeyValuePair{TKey,TValue}"/>, starting at the specified index. /// </summary> /// <param name="array">The one-dimensional array of type <see cref="KeyValuePair{TKey,TValue}"/> that is the destination of the <see cref="KeyValuePair{TKey,TValue}"/> elements copied from the <see cref="OrderedDictionary{TKey,TValue}"/>. The array must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param> void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { ((ICollection<KeyValuePair<TKey, TValue>>) Dictionary).CopyTo(array, arrayIndex); } /// <summary> /// Removes a key and value from the dictionary. /// </summary> /// <param name="item">The <see cref="KeyValuePair{TKey,TValue}"/> structure representing the key and value to remove from the <see cref="OrderedDictionary{TKey,TValue}"/>.</param> /// <returns><see langword="true"/> if the key and value represented by <paramref name="item"/> is successfully found and removed; otherwise, <see langword="false"/>. This method returns <see langword="false"/> if <paramref name="item"/> is not found in the <see cref="OrderedDictionary{TKey,TValue}"/>.</returns> bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) { return Remove(item.Key); } } }
/****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2017. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ //#define VALIDATE using UnityEngine; using System; namespace Leap.Unity { public interface IMinHeapNode { int heapIndex { get; set; } } public class MinHeap<T> where T : IMinHeapNode, IComparable<T> { private T[] _array = new T[4]; private int _count = 0; public int Count { get { return _count; } } public void Clear() { Array.Clear(_array, 0, _count); _count = 0; } public void Insert(T element) { #if VALIDATE validateHeapInternal("Insert"); #endif //if the array isn't big enough, expand it if (_array.Length == _count) { T[] newArray = new T[_array.Length * 2]; Array.Copy(_array, newArray, _array.Length); _array = newArray; } element.heapIndex = _count; _count++; bubbleUp(element); } public void Remove(T element) { removeAt(element.heapIndex); } public T PeekMin() { if (_count == 0) { throw new Exception("Cannot peek when there are zero elements!"); } return _array[0]; } public T RemoveMin() { if (_count == 0) { throw new Exception("Cannot Remove Min when there are zero elements!"); } return removeAt(0); } private T removeAt(int index) { #if VALIDATE validateHeapInternal("Remove At"); #endif T ret = _array[index]; _count--; if (_count == 0) { return ret; } var bottom = _array[_count]; bottom.heapIndex = index; int parentIndex = getParentIndex(index); if (isValidIndex(parentIndex) && _array[parentIndex].CompareTo(bottom) > 0) { bubbleUp(bottom); } else { bubbleDown(bottom); } return ret; } private void bubbleUp(T element) { while (true) { if (element.heapIndex == 0) { break; } int parentIndex = getParentIndex(element.heapIndex); var parent = _array[parentIndex]; if (parent.CompareTo(element) <= 0) { break; } parent.heapIndex = element.heapIndex; _array[element.heapIndex] = parent; element.heapIndex = parentIndex; } _array[element.heapIndex] = element; #if VALIDATE validateHeapInternal("Bubble Up"); #endif } public bool Validate() { return validateHeapInternal("Validation "); } private void bubbleDown(T element) { int elementIndex = element.heapIndex; while (true) { int leftIndex = getChildLeftIndex(elementIndex); int rightIndex = getChildRightIndex(elementIndex); T smallest = element; int smallestIndex = elementIndex; if (isValidIndex(leftIndex)) { var leftChild = _array[leftIndex]; if (leftChild.CompareTo(smallest) < 0) { smallest = leftChild; smallestIndex = leftIndex; } } else { break; } if (isValidIndex(rightIndex)) { var rightChild = _array[rightIndex]; if (rightChild.CompareTo(smallest) < 0) { smallest = rightChild; smallestIndex = rightIndex; } } if (smallestIndex == elementIndex) { break; } smallest.heapIndex = elementIndex; _array[elementIndex] = smallest; elementIndex = smallestIndex; } element.heapIndex = elementIndex; _array[elementIndex] = element; #if VALIDATE validateHeapInternal("Bubble Down"); #endif } private bool validateHeapInternal(string operation) { for (int i = 0; i < _count; i++) { if (_array[i].heapIndex != i) { Debug.LogError("Element " + i + " had an index of " + _array[i].heapIndex + " instead, after " + operation); return false; } if (i != 0) { var parent = _array[getParentIndex(i)]; if (parent.CompareTo(_array[i]) > 0) { Debug.LogError("Element " + i + " had an incorrect order after " + operation); return false; } } } return true; } private static int getChildLeftIndex(int index) { return index * 2 + 1; } private static int getChildRightIndex(int index) { return index * 2 + 2; } private static int getParentIndex(int index) { return (index - 1) / 2; } private bool isValidIndex(int index) { return index < _count && index >= 0; } } }
/* * MindTouch Core - open source enterprise collaborative networking * Copyright (c) 2006-2010 MindTouch Inc. * www.mindtouch.com [email protected] * * For community documentation and downloads visit www.opengarden.org; * please review the licensing section. * * 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. * http://www.gnu.org/copyleft/gpl.html */ using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using MindTouch.Dream; namespace MindTouch.Deki.Tests.FileTests { [TestFixture] public class MoveTests { [Test] public void MoveFile() { // POST:files/{fileid}/move // http://developer.mindtouch.com/Deki/API_Reference/POST%3afiles%2f%2f%7bfileid%7d%2f%2fmove // 1. Create a source page // 2. Create a destination page // 3. Upload a file to source page // (4) Assert attachment exists in source page // 5. Move attachment to destination page // (6) Assert source page does not have the attachment // (7) Assert destination page has the attachment // 8. Delete page Plug p = Utils.BuildPlugForAdmin(); string id = null; DreamMessage msg = PageUtils.CreateRandomPage(p, out id); string toid = null; msg = PageUtils.CreateRandomPage(p, out toid); string fileid = null; string filename = null; msg = FileUtils.UploadRandomFile(p, id, out fileid, out filename); msg = p.At("pages", id, "files").Get(); Assert.AreEqual(DreamStatus.Ok, msg.Status, "GET pages/{id}/files failed. BEFORE move"); Assert.IsFalse(msg.ToDocument()[string.Format("file[@id=\"{0}\"]", fileid)].IsEmpty, "Source page does not have the attachment! BEFORE move"); msg = p.At("files", fileid, "move").With("to", toid).Post(); Assert.AreEqual(DreamStatus.Ok, msg.Status, "Move request failed!"); msg = p.At("pages", id, "files").Get(); Assert.AreEqual(DreamStatus.Ok, msg.Status, "GET pages/{id}/files failed. AFTER move"); Assert.IsTrue(msg.ToDocument()[string.Format("file[@id=\"{0}\"]", fileid)].IsEmpty, "Source page has the attachment! AFTER move"); msg = p.At("pages", toid, "files").Get(); Assert.AreEqual(DreamStatus.Ok, msg.Status, "GET pages/{toid}/files failed. AFTER move"); Assert.IsFalse(msg.ToDocument()[string.Format("file[@id=\"{0}\"]", fileid)].IsEmpty, "Destination page does not have the attachment! AFTER move"); PageUtils.DeletePageByID(p, id, true); } [Test] public void MoveFileToDeletedPage() { //Assumptions: //Actions: // 1. Create page1 // 2. Create page2 // 3. Delete page2 // 4. Upload file to page1 // 5. Attempt to move file from page1 to page2 // (6) Assert a Not Found response is retruned // 7. Delete page1 //Expected result: // NotFound Plug p = Utils.BuildPlugForAdmin(); string id = null; string path = null; DreamMessage msg = PageUtils.CreateRandomPage(p, out id, out path); string id2 = null; string path2 = null; msg = PageUtils.CreateRandomPage(p, out id2, out path2); PageUtils.DeletePageByID(p, id2, true); try { string fileid = null; string filename = null; msg = FileUtils.UploadRandomFile(p, id, out fileid, out filename); msg = p.At("files", fileid, "move").With("to", id2).Post(); Assert.IsTrue(false, "File move succeeded?!"); } catch (DreamResponseException ex) { Assert.AreEqual(DreamStatus.NotFound, ex.Response.Status, "Status other than \"Not Found\" returned: " + ex.Response.Status.ToString()); } PageUtils.DeletePageByID(p, id, true); } [Test] public void MoveFileFromAnonymous() { //Assumptions: // //Actions: // 1. Create page1 // 2. Create page2 // 3. Upload file to page1 // 4. Try to move file to page2 from anonymous account // (5) Assert an Unauthorized response is returned // 6. Delete page1 // 7. Delete page2 //Expected result: // Unauthorized Plug p = Utils.BuildPlugForAdmin(); string id = null; DreamMessage msg = PageUtils.CreateRandomPage(p, out id); string toid = null; msg = PageUtils.CreateRandomPage(p, out toid); string fileid = null; string filename = null; msg = FileUtils.UploadRandomFile(p, id, out fileid, out filename); p = Utils.BuildPlugForAnonymous(); try { msg = p.At("files", fileid, "move").With("to", toid).Post(); Assert.IsTrue(false, "File move succeeded?!"); } catch (DreamResponseException ex) { Assert.AreEqual(DreamStatus.Unauthorized, ex.Response.Status, "Status other than \"Unauthorized\" returned: " + ex.Response.Status.ToString()); } p = Utils.BuildPlugForAdmin(); PageUtils.DeletePageByID(p, id, true); PageUtils.DeletePageByID(p, toid, true); } [Test] public void MoveFileToChildPage() { //Assumptions: // //Actions: // 1. Create A // 2. Create B as child of page A // 3. Upload file to A // (4) Assert file exists on page A // 5. Try to move file to page B // (6) Assert file does not exist on page A // (7) Assert file exists on page B // 8. Delete page A recursively //Expected result: // file is moved Plug p = Utils.BuildPlugForAdmin(); string baseTreePath = PageUtils.BuildPageTree(p); string id = PageUtils.GetPage(p, baseTreePath + "/A").ToDocument()["@id"].AsText; string toid = PageUtils.GetPage(p, baseTreePath + "/A/B").ToDocument()["@id"].AsText; string fileid = null; string filename = null; DreamMessage msg = FileUtils.UploadRandomFile(p, id, out fileid, out filename); msg = p.At("pages", id, "files").Get(); Assert.AreEqual(DreamStatus.Ok, msg.Status, "GET pages/{id}/files request failed. BEFORE move"); Assert.IsFalse(msg.ToDocument()[string.Format("file[@id=\"{0}\"]", fileid)].IsEmpty, "Page does not contain generated file! BEFORE move"); msg = p.At("files", fileid, "move").With("to", toid).Post(); Assert.AreEqual(DreamStatus.Ok, msg.Status, "Move request failed"); msg = p.At("pages", id, "files").Get(); Assert.AreEqual(DreamStatus.Ok, msg.Status, "GET pages/{id}/files request failed. AFTER move"); Assert.IsTrue(msg.ToDocument()[string.Format("file[@id=\"{0}\"]", fileid)].IsEmpty, "Generated file still attached to page! AFTER move"); msg = p.At("pages", toid, "files").Get(); Assert.AreEqual(DreamStatus.Ok, msg.Status, "GET pages/{toid}/files request failed. AFTER move"); Assert.IsFalse(msg.ToDocument()[string.Format("file[@id=\"{0}\"]", fileid)].IsEmpty, "Subpage does not contain generated file! AFTER move"); PageUtils.DeletePageByID(p, id, true); } [Test] public void RenameFile() { // 1. Create a source page // 2. Create a destination page (child of source page) // 3. Upload a file to source page // (4) Assert move request without parameters fails // (5) Assert move request without renaming the file and without specifying destination fails // (6) Assert move request to same path fails // (7) Assert move request to exact same path and filename fails // (8) Assert move request to different location and name succeeds // (9) Assert a rename to a new name succeeds // (10) Assert move request to a different location works // (11) Assert the file revisions accurately reflect changes // 12. Delete the page Plug p = Utils.BuildPlugForAdmin(); string baseTreePath = PageUtils.BuildPageTree(p); string id = PageUtils.GetPage(p, baseTreePath + "/A").ToDocument()["@id"].AsText; string toid = PageUtils.GetPage(p, baseTreePath + "/A/B").ToDocument()["@id"].AsText; string fileid = null; string filename = null; DreamMessage msg = FileUtils.UploadRandomFile(p, id, out fileid, out filename); //Test no parametrs msg = p.At("files", fileid, "move").PostAsync().Wait(); Assert.AreEqual(DreamStatus.BadRequest, msg.Status, "No parameter test failed"); //Test no change msg = p.At("files", fileid, "move").With("name", filename).PostAsync().Wait(); Assert.AreEqual(DreamStatus.BadRequest, msg.Status, "No change test failed"); msg = p.At("files", fileid, "move").With("to", id).PostAsync().Wait(); Assert.AreEqual(DreamStatus.BadRequest, msg.Status, "No change test failed"); msg = p.At("files", fileid, "move").With("to", id).With("name", filename).PostAsync().Wait(); Assert.AreEqual(DreamStatus.BadRequest, msg.Status, "No change test failed"); string newFileName = "newname.txt"; //Move and rename msg = p.At("files", fileid, "move").With("to", toid).With("name", newFileName).Post(); Assert.AreEqual(DreamStatus.Ok, msg.Status, "move+rename failed"); Assert.AreEqual(toid, msg.ToDocument()["page.parent/@id"].AsText, "New page id is incorrect"); Assert.AreEqual(newFileName, msg.ToDocument()["filename"].AsText, "New filename is incorrect"); //rename msg = p.At("files", fileid, "move").With("name", filename).Post(); Assert.AreEqual(DreamStatus.Ok, msg.Status, "rename failed"); Assert.AreEqual(filename, msg.ToDocument()["filename"].AsText, "New filename is incorrect"); //move msg = p.At("files", fileid, "move").With("to", id).Post(); Assert.AreEqual(DreamStatus.Ok, msg.Status, "move failed"); Assert.AreEqual(id, msg.ToDocument()["page.parent/@id"].AsText, "New page id is incorrect"); //verify all revisions msg = p.At("files", fileid, "revisions").With("changefilter", "all").Get(); Assert.AreEqual(DreamStatus.Ok, msg.Status, "get revisions failed"); string actions = null; actions = msg.ToDocument()["file[@revision = '1']/user-action/@type"].AsText ?? string.Empty; Assert.IsTrue(actions.Contains("content"), "expected user action missing"); Assert.IsTrue(actions.Contains("parent"), "expected user action missing"); Assert.IsTrue(actions.Contains("name"), "expected user action missing"); actions = msg.ToDocument()["file[@revision = '2']/user-action/@type"].AsText ?? string.Empty; Assert.IsTrue(actions.Contains("parent"), "expected user action missing"); Assert.IsTrue(actions.Contains("name"), "expected user action missing"); actions = msg.ToDocument()["file[@revision = '3']/user-action/@type"].AsText ?? string.Empty; Assert.IsTrue(actions.Contains("name"), "expected user action missing"); actions = msg.ToDocument()["file[@revision = '4']/user-action/@type"].AsText ?? string.Empty; Assert.IsTrue(actions.Contains("parent"), "expected user action missing"); Assert.IsTrue(msg.ToDocument()["file[@revision = '5']"].IsEmpty, "5th rev exists!"); PageUtils.DeletePageByID(p, id, true); } [Test] public void UploadRename() { // 1. Build a page tree // 2. Upload a file to the root of page tree (A) // 3. Replace file and rename it // (4) Assert replacement succeeded // (5) Assert the file revisions accurately reflect changes // (6) Assert new file name is consistent // 7. Upload a file to page with same name // (8) Assert Conflict response is returned // 9. Delete the page (recursive) Plug p = Utils.BuildPlugForAdmin(); string baseTreePath = PageUtils.BuildPageTree(p); string pageid = PageUtils.GetPage(p, baseTreePath + "/A").ToDocument()["@id"].AsText; string fileid = null; string filename = null; string newfilename = "newfilename"; DreamMessage msg = FileUtils.UploadRandomFile(p, pageid, out fileid, out filename); //Upload a new rev with rename msg = p.At("files", fileid, "=" + newfilename).Put(DreamMessage.Ok(MimeType.BINARY, FileUtils.GenerateRandomContent())); Assert.AreEqual(DreamStatus.Ok, msg.Status, "upload with rename failed"); //validate revisions msg = p.At("files", fileid, "revisions").With("changefilter", "all").Get(); Assert.AreEqual(DreamStatus.Ok, msg.Status, "get revisions failed"); string actions = null; actions = msg.ToDocument()["file[@revision = '1']/user-action/@type"].AsText ?? string.Empty; Assert.IsTrue(actions.Contains("content"), "expected user action missing"); Assert.IsTrue(actions.Contains("parent"), "expected user action missing"); Assert.IsTrue(actions.Contains("name"), "expected user action missing"); actions = msg.ToDocument()["file[@revision = '2']/user-action/@type"].AsText ?? string.Empty; Assert.IsTrue(actions.Contains("content"), "expected user action missing"); Assert.IsTrue(actions.Contains("name"), "expected user action missing"); //Confirm new filename Assert.AreEqual(newfilename, msg.ToDocument()["file[@revision = '2']/filename"].AsText, "Filenames do not match!"); string file3name; string file3id; msg = FileUtils.UploadRandomFile(p, pageid, out file3id, out file3name); //Upload new rev of file with rename that conflits with previous rename msg = p.At("files", file3id, "=" + newfilename).PutAsync(DreamMessage.Ok(MimeType.BINARY, FileUtils.GenerateRandomContent())).Wait(); Assert.AreEqual(DreamStatus.Conflict, msg.Status, "upload with conflicting rename check failed"); PageUtils.DeletePageByID(p, pageid, true); } } }
using System; namespace JFLCSharp { //ALL FUNCTIONS IN THIS UTILITY ONLY SUPPORT VALUES SUPPORTED BY THE JVALUE CLASS public static class ComparisonUtility { const double MAX_DIFFERENCE = .00001; public static bool IsEqual(Object leftOperand, Object rightOperand) { if (leftOperand != null && rightOperand != null) { if (leftOperand.GetType() == typeof(bool) && rightOperand.GetType() == typeof(bool)) { return (bool)leftOperand == (bool)rightOperand; } else if (leftOperand.GetType() == typeof(DateTime) && rightOperand.GetType() == typeof(DateTime)) { return DateTime.Compare((DateTime)leftOperand, (DateTime)rightOperand) == 0; } else if (leftOperand.GetType() == typeof(Guid) && rightOperand.GetType() == typeof(Guid)) { return ((Guid)leftOperand).CompareTo((Guid)rightOperand) == 0; } else if (leftOperand.GetType() == typeof(string) && rightOperand.GetType() == typeof(string)) { return (string)leftOperand == (string)rightOperand; } else if (leftOperand.GetType() == typeof(TimeSpan) && rightOperand.GetType() == typeof(TimeSpan)) { return TimeSpan.Compare((TimeSpan)leftOperand, (TimeSpan)rightOperand) == 0; } else if (leftOperand.GetType() == typeof(Uri) && rightOperand.GetType() == typeof(Uri)) { return ((Uri)leftOperand).Equals((Uri)rightOperand); } else if (leftOperand.IsNumber() && rightOperand.IsNumber()) { double leftNumber = 0; double rightNumber = 0; if (leftOperand.GetType() == typeof(double)) leftNumber = (double)leftOperand; else if (leftOperand.GetType() == typeof(int)) leftNumber = (int)leftOperand; else if (leftOperand.GetType() == typeof(Int64)) leftNumber = (Int64)leftOperand; else if (leftOperand.GetType() == typeof(Single)) leftNumber = (Single)leftOperand; else if (leftOperand.GetType() == typeof(UInt64)) leftNumber = (UInt64)leftOperand; if (rightOperand.GetType() == typeof(double)) rightNumber = (double)rightOperand; else if (rightOperand.GetType() == typeof(int)) rightNumber = (int)rightOperand; else if (rightOperand.GetType() == typeof(Int64)) rightNumber = (Int64)rightOperand; else if (rightOperand.GetType() == typeof(Single)) rightNumber = (Single)rightOperand; else if (rightOperand.GetType() == typeof(UInt64)) rightNumber = (UInt64)rightOperand; return CompareNumbers(leftNumber, rightNumber) == 0; } } //If none of the cases hits, then the function can only compare based on memory address return leftOperand == rightOperand; } public static bool IsGreater(Object leftOperand, Object rightOperand) { if (leftOperand != null && rightOperand != null) { if (leftOperand.GetType() == typeof(DateTime) && rightOperand.GetType() == typeof(DateTime)) { return DateTime.Compare((DateTime)leftOperand, (DateTime)rightOperand) > 0; } else if (leftOperand.GetType() == typeof(Guid) && rightOperand.GetType() == typeof(Guid)) { return ((Guid)leftOperand).CompareTo((Guid)rightOperand) > 0; } else if (leftOperand.GetType() == typeof(TimeSpan) && rightOperand.GetType() == typeof(TimeSpan)) { return TimeSpan.Compare((TimeSpan)leftOperand, (TimeSpan)rightOperand) > 0; } else if (leftOperand.IsNumber() && rightOperand.IsNumber()) { double leftNumber = 0; double rightNumber = 0; if (leftOperand.GetType() == typeof(double)) leftNumber = (double)leftOperand; else if (leftOperand.GetType() == typeof(int)) leftNumber = (int)leftOperand; else if (leftOperand.GetType() == typeof(Int64)) leftNumber = (Int64)leftOperand; else if (leftOperand.GetType() == typeof(Single)) leftNumber = (Single)leftOperand; else if (leftOperand.GetType() == typeof(UInt64)) leftNumber = (UInt64)leftOperand; if (rightOperand.GetType() == typeof(double)) rightNumber = (double)rightOperand; else if (rightOperand.GetType() == typeof(int)) rightNumber = (int)rightOperand; else if (rightOperand.GetType() == typeof(Int64)) rightNumber = (Int64)rightOperand; else if (rightOperand.GetType() == typeof(Single)) rightNumber = (Single)rightOperand; else if (rightOperand.GetType() == typeof(UInt64)) rightNumber = (UInt64)rightOperand; return CompareNumbers(leftNumber, rightNumber) > 0; } } //If none of the cases hits, then the comparison is not valid return false; } public static bool IsLess(Object leftOperand, Object rightOperand) { if (leftOperand != null && rightOperand != null) { if (leftOperand.GetType() == typeof(DateTime) && rightOperand.GetType() == typeof(DateTime)) { return DateTime.Compare((DateTime)leftOperand, (DateTime)rightOperand) < 0; } else if (leftOperand.GetType() == typeof(Guid) && rightOperand.GetType() == typeof(Guid)) { return ((Guid)leftOperand).CompareTo((Guid)rightOperand) < 0; } else if (leftOperand.GetType() == typeof(TimeSpan) && rightOperand.GetType() == typeof(TimeSpan)) { return TimeSpan.Compare((TimeSpan)leftOperand, (TimeSpan)rightOperand) < 0; } else if (leftOperand.IsNumber() && rightOperand.IsNumber()) { double leftNumber = 0; double rightNumber = 0; if (leftOperand.GetType() == typeof(double)) leftNumber = (double)leftOperand; else if (leftOperand.GetType() == typeof(int)) leftNumber = (int)leftOperand; else if (leftOperand.GetType() == typeof(Int64)) leftNumber = (Int64)leftOperand; else if (leftOperand.GetType() == typeof(Single)) leftNumber = (Single)leftOperand; else if (leftOperand.GetType() == typeof(UInt64)) leftNumber = (UInt64)leftOperand; if (rightOperand.GetType() == typeof(double)) rightNumber = (double)rightOperand; else if (rightOperand.GetType() == typeof(int)) rightNumber = (int)rightOperand; else if (rightOperand.GetType() == typeof(Int64)) rightNumber = (Int64)rightOperand; else if (rightOperand.GetType() == typeof(Single)) rightNumber = (Single)rightOperand; else if (rightOperand.GetType() == typeof(UInt64)) rightNumber = (UInt64)rightOperand; return CompareNumbers (leftNumber, rightNumber) < 0; } } //If none of the cases hits, then the comparison is not valid return false; } public static bool IsGreaterOrEqual(Object leftOperand, Object rightOperand) { if (leftOperand != null && rightOperand != null) { if (leftOperand.GetType() == typeof(DateTime) && rightOperand.GetType() == typeof(DateTime)) { return DateTime.Compare((DateTime)leftOperand, (DateTime)rightOperand) >= 0; } else if (leftOperand.GetType() == typeof(Guid) && rightOperand.GetType() == typeof(Guid)) { return ((Guid)leftOperand).CompareTo((Guid)rightOperand) >= 0; } else if (leftOperand.GetType() == typeof(TimeSpan) && rightOperand.GetType() == typeof(TimeSpan)) { return TimeSpan.Compare((TimeSpan)leftOperand, (TimeSpan)rightOperand) >= 0; } else if (leftOperand.IsNumber() && rightOperand.IsNumber()) { double leftNumber = 0; double rightNumber = 0; if (leftOperand.GetType() == typeof(double)) leftNumber = (double)leftOperand; else if (leftOperand.GetType() == typeof(int)) leftNumber = (int)leftOperand; else if (leftOperand.GetType() == typeof(Int64)) leftNumber = (Int64)leftOperand; else if (leftOperand.GetType() == typeof(Single)) leftNumber = (Single)leftOperand; else if (leftOperand.GetType() == typeof(UInt64)) leftNumber = (UInt64)leftOperand; if (rightOperand.GetType() == typeof(double)) rightNumber = (double)rightOperand; else if (rightOperand.GetType() == typeof(int)) rightNumber = (int)rightOperand; else if (rightOperand.GetType() == typeof(Int64)) rightNumber = (Int64)rightOperand; else if (rightOperand.GetType() == typeof(Single)) rightNumber = (Single)rightOperand; else if (rightOperand.GetType() == typeof(UInt64)) rightNumber = (UInt64)rightOperand; return CompareNumbers(leftNumber, rightNumber) >= 0; } } //If none of the cases hits, then the comparison is not valid return false; } public static bool IsLessOrEqual(Object leftOperand, Object rightOperand) { if (leftOperand != null && rightOperand != null) { if (leftOperand.GetType() == typeof(DateTime) && rightOperand.GetType() == typeof(DateTime)) { return DateTime.Compare((DateTime)leftOperand, (DateTime)rightOperand) <= 0; } else if (leftOperand.GetType() == typeof(Guid) && rightOperand.GetType() == typeof(Guid)) { return ((Guid)leftOperand).CompareTo((Guid)rightOperand) <= 0; } else if (leftOperand.GetType() == typeof(TimeSpan) && rightOperand.GetType() == typeof(TimeSpan)) { return TimeSpan.Compare((TimeSpan)leftOperand, (TimeSpan)rightOperand) <= 0; } else if (leftOperand.IsNumber() && rightOperand.IsNumber()) { double leftNumber = 0; double rightNumber = 0; if (leftOperand.GetType() == typeof(double)) leftNumber = (double)leftOperand; else if (leftOperand.GetType() == typeof(int)) leftNumber = (int)leftOperand; else if (leftOperand.GetType() == typeof(Int64)) leftNumber = (Int64)leftOperand; else if (leftOperand.GetType() == typeof(Single)) leftNumber = (Single)leftOperand; else if (leftOperand.GetType() == typeof(UInt64)) leftNumber = (UInt64)leftOperand; if (rightOperand.GetType() == typeof(double)) rightNumber = (double)rightOperand; else if (rightOperand.GetType() == typeof(int)) rightNumber = (int)rightOperand; else if (rightOperand.GetType() == typeof(Int64)) rightNumber = (Int64)rightOperand; else if (rightOperand.GetType() == typeof(Single)) rightNumber = (Single)rightOperand; else if (rightOperand.GetType() == typeof(UInt64)) rightNumber = (UInt64)rightOperand; return CompareNumbers(leftNumber, rightNumber) <= 0; } } //If none of the cases hits, then the comparison is not valid return false; } private static bool IsNumber(this object obj) { if (obj.GetType() == typeof(double) || obj.GetType() == typeof(int) || obj.GetType() == typeof(Int64) || obj.GetType() == typeof(Single) || obj.GetType() == typeof(UInt64)) return true; return false; } /* This function calculates the difference between values, and compares the difference to a constant threshold. This is because conversions of other number types to doubles can create slight differences between normally equal numbers (2 as an Int64 and 2 as a Single might not be equal b/c the conversion makes one into 2.0000006). */ public static int CompareNumbers(double leftOperand, double rightOperand) { double difference = leftOperand - rightOperand; if (difference <= MAX_DIFFERENCE && difference >= -MAX_DIFFERENCE) return 0; else if (leftOperand < rightOperand) return -1; else return 1; } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- /// Blends between the scene and the tone mapped scene. $HDRPostFX::enableToneMapping = 0.5; /// The tone mapping middle grey or exposure value used /// to adjust the overall "balance" of the image. /// /// 0.18 is fairly common value. /// $HDRPostFX::keyValue = 0.18; /// The minimum luninace value to allow when tone mapping /// the scene. Is particularly useful if your scene very /// dark or has a black ambient color in places. $HDRPostFX::minLuminace = 0.001; /// The lowest luminance value which is mapped to white. This /// is usually set to the highest visible luminance in your /// scene. By setting this to smaller values you get a contrast /// enhancement. $HDRPostFX::whiteCutoff = 1.0; /// The rate of adaptation from the previous and new /// average scene luminance. $HDRPostFX::adaptRate = 2.0; /// Blends between the scene and the blue shifted version /// of the scene for a cinematic desaturated night effect. $HDRPostFX::enableBlueShift = 0.0; /// The blue shift color value. $HDRPostFX::blueShiftColor = "1.05 0.97 1.27"; /// Blends between the scene and the bloomed scene. $HDRPostFX::enableBloom = 1.0; /// The threshold luminace value for pixels which are /// considered "bright" and need to be bloomed. $HDRPostFX::brightPassThreshold = 1.0; /// These are used in the gaussian blur of the /// bright pass for the bloom effect. $HDRPostFX::gaussMultiplier = 0.3; $HDRPostFX::gaussMean = 0.0; $HDRPostFX::gaussStdDev = 0.8; /// The 1x255 color correction ramp texture used /// by both the HDR shader and the GammaPostFx shader /// for doing full screen color correction. $HDRPostFX::colorCorrectionRamp = "core/scripts/client/postFx/null_color_ramp.png"; singleton ShaderData( HDR_BrightPassShader ) { DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl"; DXPixelShaderFile = "shaders/common/postFx/hdr/brightPassFilterP.hlsl"; OGLVertexShaderFile = "shaders/common/postFx/gl/postFxV.glsl"; OGLPixelShaderFile = "shaders/common/postFx/hdr/gl/brightPassFilterP.glsl"; samplerNames[0] = "$inputTex"; samplerNames[1] = "$luminanceTex"; pixVersion = 3.0; }; singleton ShaderData( HDR_DownScale4x4Shader ) { DXVertexShaderFile = "shaders/common/postFx/hdr/downScale4x4V.hlsl"; DXPixelShaderFile = "shaders/common/postFx/hdr/downScale4x4P.hlsl"; OGLVertexShaderFile = "shaders/common/postFx/hdr/gl/downScale4x4V.glsl"; OGLPixelShaderFile = "shaders/common/postFx/hdr/gl/downScale4x4P.glsl"; samplerNames[0] = "$inputTex"; pixVersion = 2.0; }; singleton ShaderData( HDR_BloomGaussBlurHShader ) { DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl"; DXPixelShaderFile = "shaders/common/postFx/hdr/bloomGaussBlurHP.hlsl"; OGLVertexShaderFile = "shaders/common/postFx/gl/postFxV.glsl"; OGLPixelShaderFile = "shaders/common/postFx/hdr/gl/bloomGaussBlurHP.glsl"; samplerNames[0] = "$inputTex"; pixVersion = 3.0; }; singleton ShaderData( HDR_BloomGaussBlurVShader ) { DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl"; DXPixelShaderFile = "shaders/common/postFx/hdr/bloomGaussBlurVP.hlsl"; OGLVertexShaderFile = "shaders/common/postFx/gl/postFxV.glsl"; OGLPixelShaderFile = "shaders/common/postFx/hdr/gl/bloomGaussBlurVP.glsl"; samplerNames[0] = "$inputTex"; pixVersion = 3.0; }; singleton ShaderData( HDR_SampleLumShader ) { DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl"; DXPixelShaderFile = "shaders/common/postFx/hdr/sampleLumInitialP.hlsl"; OGLVertexShaderFile = "shaders/common/postFx/gl/postFxV.glsl"; OGLPixelShaderFile = "shaders/common/postFx/hdr/gl/sampleLumInitialP.glsl"; samplerNames[0] = "$inputTex"; pixVersion = 3.0; }; singleton ShaderData( HDR_DownSampleLumShader ) { DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl"; DXPixelShaderFile = "shaders/common/postFx/hdr/sampleLumIterativeP.hlsl"; OGLVertexShaderFile = "shaders/common/postFx/gl/postFxV.glsl"; OGLPixelShaderFile = "shaders/common/postFx/hdr/gl/sampleLumIterativeP.glsl"; samplerNames[0] = "$inputTex"; pixVersion = 3.0; }; singleton ShaderData( HDR_CalcAdaptedLumShader ) { DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl"; DXPixelShaderFile = "shaders/common/postFx/hdr/calculateAdaptedLumP.hlsl"; OGLVertexShaderFile = "shaders/common/postFx/gl/postFxV.glsl"; OGLPixelShaderFile = "shaders/common/postFx/hdr/gl/calculateAdaptedLumP.glsl"; samplerNames[0] = "$currLum"; samplerNames[1] = "$lastAdaptedLum"; pixVersion = 3.0; }; singleton ShaderData( HDR_CombineShader ) { DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl"; DXPixelShaderFile = "shaders/common/postFx/hdr/finalPassCombineP.hlsl"; OGLVertexShaderFile = "shaders/common/postFx/gl/postFxV.glsl"; OGLPixelShaderFile = "shaders/common/postFx/hdr/gl/finalPassCombineP.glsl"; samplerNames[0] = "$sceneTex"; samplerNames[1] = "$luminanceTex"; samplerNames[2] = "$bloomTex"; samplerNames[3] = "$colorCorrectionTex"; samplerNames[4] = "deferredTex"; pixVersion = 3.0; }; singleton GFXStateBlockData( HDR_SampleStateBlock : PFX_DefaultStateBlock ) { samplersDefined = true; samplerStates[0] = SamplerClampPoint; samplerStates[1] = SamplerClampPoint; }; singleton GFXStateBlockData( HDR_DownSampleStateBlock : PFX_DefaultStateBlock ) { samplersDefined = true; samplerStates[0] = SamplerClampLinear; samplerStates[1] = SamplerClampLinear; }; singleton GFXStateBlockData( HDR_CombineStateBlock : PFX_DefaultStateBlock ) { samplersDefined = true; samplerStates[0] = SamplerClampPoint; samplerStates[1] = SamplerClampLinear; samplerStates[2] = SamplerClampLinear; samplerStates[3] = SamplerClampLinear; }; singleton GFXStateBlockData( HDRStateBlock ) { samplersDefined = true; samplerStates[0] = SamplerClampLinear; samplerStates[1] = SamplerClampLinear; samplerStates[2] = SamplerClampLinear; samplerStates[3] = SamplerClampLinear; blendDefined = true; blendDest = GFXBlendOne; blendSrc = GFXBlendZero; zDefined = true; zEnable = false; zWriteEnable = false; cullDefined = true; cullMode = GFXCullNone; }; function HDRPostFX::setShaderConsts( %this ) { %this.setShaderConst( "$brightPassThreshold", $HDRPostFX::brightPassThreshold ); %this.setShaderConst( "$g_fMiddleGray", $HDRPostFX::keyValue ); %bloomH = %this-->bloomH; %bloomH.setShaderConst( "$gaussMultiplier", $HDRPostFX::gaussMultiplier ); %bloomH.setShaderConst( "$gaussMean", $HDRPostFX::gaussMean ); %bloomH.setShaderConst( "$gaussStdDev", $HDRPostFX::gaussStdDev ); %bloomV = %this-->bloomV; %bloomV.setShaderConst( "$gaussMultiplier", $HDRPostFX::gaussMultiplier ); %bloomV.setShaderConst( "$gaussMean", $HDRPostFX::gaussMean ); %bloomV.setShaderConst( "$gaussStdDev", $HDRPostFX::gaussStdDev ); %minLuminace = $HDRPostFX::minLuminace; if ( %minLuminace <= 0.0 ) { // The min should never be pure zero else the // log() in the shader will generate INFs. %minLuminace = 0.00001; } %this-->adaptLum.setShaderConst( "$g_fMinLuminace", %minLuminace ); %this-->finalLum.setShaderConst( "$adaptRate", $HDRPostFX::adaptRate ); %combinePass = %this-->combinePass; %combinePass.setShaderConst( "$g_fEnableToneMapping", $HDRPostFX::enableToneMapping ); %combinePass.setShaderConst( "$g_fMiddleGray", $HDRPostFX::keyValue ); %combinePass.setShaderConst( "$g_fBloomScale", $HDRPostFX::enableBloom ); %combinePass.setShaderConst( "$g_fEnableBlueShift", $HDRPostFX::enableBlueShift ); %combinePass.setShaderConst( "$g_fBlueShiftColor", $HDRPostFX::blueShiftColor ); %clampedGamma = mClamp( $pref::Video::Gamma, 2.0, 2.5); %combinePass.setShaderConst( "$g_fOneOverGamma", 1 / %clampedGamma ); %combinePass.setShaderConst( "$Brightness", $pref::Video::Brightness ); %combinePass.setShaderConst( "$Contrast", $pref::Video::Contrast ); %whiteCutoff = ( $HDRPostFX::whiteCutoff * $HDRPostFX::whiteCutoff ) * ( $HDRPostFX::whiteCutoff * $HDRPostFX::whiteCutoff ); %combinePass.setShaderConst( "$g_fWhiteCutoff", %whiteCutoff ); } function HDRPostFX::preProcess( %this ) { %combinePass = %this-->combinePass; if ( %combinePass.texture[3] !$= $HDRPostFX::colorCorrectionRamp ) %combinePass.setTexture( 3, $HDRPostFX::colorCorrectionRamp ); } function HDRPostFX::onEnabled( %this ) { // See what HDR format would be best. %format = getBestHDRFormat(); if ( %format $= "" || %format $= "GFXFormatR8G8B8A8" ) { // We didn't get a valid HDR format... so fail. return false; } // HDR does it's own gamma calculation so // disable this postFx. GammaPostFX.disable(); // Set the right global shader define for HDR. if ( %format $= "GFXFormatR10G10B10A2" ) addGlobalShaderMacro( "TORQUE_HDR_RGB10" ); else if ( %format $= "GFXFormatR16G16B16A16" ) addGlobalShaderMacro( "TORQUE_HDR_RGB16" ); echo( "HDR FORMAT: " @ %format ); // Change the format of the offscreen surface // to an HDR compatible format. AL_FormatToken.format = %format; setReflectFormat( %format ); // Reset the light manager which will ensure the new // hdr encoding takes effect in all the shaders and // that the offscreen surface is enabled. resetLightManager(); return true; } function HDRPostFX::onDisabled( %this ) { // Enable a special GammaCorrection PostFX when this is disabled. GammaPostFX.enable(); // Restore the non-HDR offscreen surface format. %format = getBestHDRFormat(); AL_FormatToken.format = %format; setReflectFormat( %format ); removeGlobalShaderMacro( "TORQUE_HDR_RGB10" ); removeGlobalShaderMacro( "TORQUE_HDR_RGB16" ); // Reset the light manager which will ensure the new // hdr encoding takes effect in all the shaders. resetLightManager(); } singleton PostEffect( HDRPostFX ) { isEnabled = false; allowReflectPass = false; // Resolve the HDR before we render any editor stuff // and before we resolve the scene to the backbuffer. renderTime = "PFXBeforeBin"; renderBin = "EditorBin"; renderPriority = 9999; // The bright pass generates a bloomed version of // the scene for pixels which are brighter than a // fixed threshold value. // // This is then used in the final HDR combine pass // at the end of this post effect chain. // shader = HDR_BrightPassShader; stateBlock = HDR_DownSampleStateBlock; texture[0] = "$backBuffer"; texture[1] = "#adaptedLum"; target = "$outTex"; targetFormat = "GFXFormatR16G16B16A16F"; targetScale = "0.5 0.5"; new PostEffect() { allowReflectPass = false; shader = HDR_DownScale4x4Shader; stateBlock = HDR_DownSampleStateBlock; texture[0] = "$inTex"; target = "$outTex"; targetFormat = "GFXFormatR16G16B16A16F"; targetScale = "0.25 0.25"; }; new PostEffect() { allowReflectPass = false; internalName = "bloomH"; shader = HDR_BloomGaussBlurHShader; stateBlock = HDR_DownSampleStateBlock; texture[0] = "$inTex"; target = "$outTex"; targetFormat = "GFXFormatR16G16B16A16F"; }; new PostEffect() { allowReflectPass = false; internalName = "bloomV"; shader = HDR_BloomGaussBlurVShader; stateBlock = HDR_DownSampleStateBlock; texture[0] = "$inTex"; target = "#bloomFinal"; targetFormat = "GFXFormatR16G16B16A16F"; }; // BrightPass End // Now calculate the adapted luminance. new PostEffect() { allowReflectPass = false; internalName = "adaptLum"; shader = HDR_SampleLumShader; stateBlock = HDR_DownSampleStateBlock; texture[0] = "$backBuffer"; target = "$outTex"; targetScale = "0.0625 0.0625"; // 1/16th targetFormat = "GFXFormatR16F"; new PostEffect() { allowReflectPass = false; shader = HDR_DownSampleLumShader; stateBlock = HDR_DownSampleStateBlock; texture[0] = "$inTex"; target = "$outTex"; targetScale = "0.25 0.25"; // 1/4 targetFormat = "GFXFormatR16F"; }; new PostEffect() { allowReflectPass = false; shader = HDR_DownSampleLumShader; stateBlock = HDR_DownSampleStateBlock; texture[0] = "$inTex"; target = "$outTex"; targetScale = "0.25 0.25"; // 1/4 targetFormat = "GFXFormatR16F"; }; new PostEffect() { allowReflectPass = false; shader = HDR_DownSampleLumShader; stateBlock = HDR_DownSampleStateBlock; texture[0] = "$inTex"; target = "$outTex"; targetScale = "0.25 0.25"; // At this point the target should be 1x1. targetFormat = "GFXFormatR16F"; }; // Note that we're reading the adapted luminance // from the previous frame when generating this new // one... PostEffect takes care to manage that. new PostEffect() { allowReflectPass = false; internalName = "finalLum"; shader = HDR_CalcAdaptedLumShader; stateBlock = HDR_DownSampleStateBlock; texture[0] = "$inTex"; texture[1] = "#adaptedLum"; target = "#adaptedLum"; targetFormat = "GFXFormatR16F"; targetClear = "PFXTargetClear_OnCreate"; targetClearColor = "1 1 1 1"; }; }; // Output the combined bloom and toned mapped // version of the scene. new PostEffect() { allowReflectPass = false; internalName = "combinePass"; shader = HDR_CombineShader; stateBlock = HDR_CombineStateBlock; texture[0] = "$backBuffer"; texture[1] = "#adaptedLum"; texture[2] = "#bloomFinal"; texture[3] = $HDRPostFX::colorCorrectionRamp; target = "$backBuffer"; }; }; singleton ShaderData( LuminanceVisShader ) { DXVertexShaderFile = "shaders/common/postFx/postFxV.hlsl"; DXPixelShaderFile = "shaders/common/postFx/hdr/luminanceVisP.hlsl"; OGLVertexShaderFile = "shaders/common/postFx/gl/postFxV.glsl"; OGLPixelShaderFile = "shaders/common/postFx/hdr/gl/luminanceVisP.glsl"; samplerNames[0] = "$inputTex"; pixVersion = 3.0; }; singleton GFXStateBlockData( LuminanceVisStateBlock : PFX_DefaultStateBlock ) { samplersDefined = true; samplerStates[0] = SamplerClampLinear; }; function LuminanceVisPostFX::setShaderConsts( %this ) { %this.setShaderConst( "$brightPassThreshold", $HDRPostFX::brightPassThreshold ); } singleton PostEffect( LuminanceVisPostFX ) { isEnabled = false; allowReflectPass = false; // Render before we do any editor rendering. renderTime = "PFXBeforeBin"; renderBin = "EditorBin"; renderPriority = 9999; shader = LuminanceVisShader; stateBlock = LuminanceVisStateBlock; texture[0] = "$backBuffer"; target = "$backBuffer"; //targetScale = "0.0625 0.0625"; // 1/16th //targetFormat = "GFXFormatR16F"; }; function LuminanceVisPostFX::onEnabled( %this ) { if ( !HDRPostFX.isEnabled() ) { HDRPostFX.enable(); } HDRPostFX.skip = true; return true; } function LuminanceVisPostFX::onDisabled( %this ) { HDRPostFX.skip = false; }
#region file using directives using System; using System.Drawing; using Oranikle.Studio.Controls.NWin32; #endregion namespace Oranikle.Studio.Controls.General { /// <summary> /// Summary description for ColorConvert. /// </summary> public class ColorUtil { #region Class static members static Color backgroundColor = Color.Empty; static Color selectionColor = Color.Empty; static Color controlColor = Color.Empty; static Color pressedColor = Color.Empty; static Color checkedColor = Color.Empty; static Color borderColor = Color.Empty; static SolidBrush m_brushBack; static SolidBrush m_brushSelect; static SolidBrush m_brushCtrl; static SolidBrush m_brushPress; static SolidBrush m_brushCheck; static SolidBrush m_brushBorder; static Pen m_penBack; static Pen m_penSelect; static Pen m_penCtrl; static Pen m_penPress; static Pen m_penCheck; static Pen m_penBorder; static bool useCustomColor = false; #endregion #region Initialization/Constructor // No need to construct this object private ColorUtil(){} static public bool UsingCustomColor { get { return useCustomColor; } } #endregion #region Systemcolors names static public string[] SystemColorNames = { "ActiveBorder", "ActiveCaption", "ActiveCaptionText", "AppWorkspace", "Control", "ControlDark", "ControlDarkDark", "ControlLight", "ControlLightLight", "ControlText", "Desktop", "GrayText", "HighLight", "HighLightText", "HotTrack", "InactiveBorder", "InactiveCaption", "InactiveCaptionText", "Info", "InfoText", "Menu", "MenuText", "ScrollBar", "Window", "WindowFrame", "WindowText" }; #endregion #region Conversion between RGB and Hue, Saturation and Luminosity function helpers static public void HSLToRGB(float h, float s, float l, ref float r, ref float g, ref float b) { // given h,s,l,[240 and r,g,b [0-255] // convert h [0-360], s,l,r,g,b [0-1] h=(h/240)*360; s /= 240; l /= 240; r /= 255; g /= 255; b /= 255; // Begin Foley float m1,m2; // Calc m2 if (l<=0.5f) { //m2=(l*(l+s)); seems to be typo in Foley??, replace l for 1 m2=(l*(1+s)); } else { m2=(l+s-l*s); } //calc m1 m1=2.0f*l-m2; //calc r,g,b in [0-1] if (s==0.0f) { // Achromatic: There is no hue // leave out the UNDEFINED part, h will always have value r=g=b=l; } else { // Chromatic: There is a hue r= getRGBValue(m1,m2,h+120.0f); g= getRGBValue(m1,m2,h); b= getRGBValue(m1,m2,h-120.0f); } // End Foley // convert to 0-255 ranges r*=255; g*=255; b*=255; } static private float getRGBValue(float n1, float n2, float hue) { // Helper function for the HSLToRGB function above if (hue>360.0f) { hue-=360.0f; } else if (hue<0.0f) { hue+=360.0f; } if (hue<60.0) { return n1+(n2-n1)*hue/60.0f; } else if (hue<180.0f) { return n2; } else if (hue<240.0f) { return n1+(n2-n1)*(240.0f-hue)/60.0f; } else { return n1; } } static public void RGBToHSL(int r, int g, int b, ref float h, ref float s, ref float l) { //Computer Graphics - Foley p.595 float delta; float fr = (float)r/255; float fg = (float)g/255; float fb = (float)b/255; float max = Math.Max(fr,Math.Max(fg,fb)); float min = Math.Min(fr,Math.Min(fg,fb)); //calc the lightness l = (max+min)/2; if (max==min) { //should be undefined but this works for what we need s = 0; h = 240.0f; } else { delta = max-min; //calc the Saturation if (l < 0.5) { s = delta/(max+min); } else { s = delta/(2.0f-(max+min)); } //calc the hue if (fr==max) { h = (fg-fb)/delta; } else if (fg==max) { h = 2.0f + (fb-fr)/delta; } else if (fb==max) { h = 4.0f + (fr-fg)/delta; } //convert hue to degrees h*=60.0f; if (h<0.0f) { h+=360.0f; } } //end foley //convert to 0-255 ranges //h [0-360], h,l [0-1] l*=240; s*=240; h=(h/360)*240; } #endregion #region Visual Studio .NET colors calculation helpers static public Color VSNetBackgroundColor { get { if ( useCustomColor && backgroundColor != Color.Empty ) return backgroundColor; else return CalculateColor(SystemColors.Window, SystemColors.Control, 220); } set { // Flag that we are going to use custom colors instead // of calculating the color based on the system colors // -- this is a way of hooking up into the VSNetColors that I use throughout // the Oranikle.Studio.Controls useCustomColor = true; backgroundColor = value; } } static public Brush VSNetBackgroundBrush { get { // if system colors changed by user then re-create brush if( m_brushBack == null ) { m_brushBack = new SolidBrush( VSNetBackgroundColor ); } m_brushBack.Color = VSNetBackgroundColor; return m_brushBack; } } static public Pen VSNetBackgroundPen { get { if( m_penBack == null ) m_penBack = new Pen( VSNetBackgroundBrush ); m_penBack.Color = VSNetBackgroundColor; return m_penBack; } } static public Color VSNetSelectionColor { get { if ( useCustomColor && selectionColor != Color.Empty ) return selectionColor; else return CalculateColor(SystemColors.Highlight, SystemColors.Window, 70); } set { // Flag that we are going to use custom colors instead // of calculating the color based on the system colors // -- this is a way of hooking up into the VSNetColor that I use throughout // the Oranikle.Studio.Controls useCustomColor = true; selectionColor = value; } } static public Brush VSNetSelectionBrush { get { if( m_brushSelect == null ) m_brushSelect = new SolidBrush( VSNetSelectionColor ); m_brushSelect.Color = VSNetSelectionColor; return m_brushSelect; } } static public Pen VSNetSelectionPen { get { if( m_penSelect == null ) m_penSelect = new Pen( VSNetSelectionBrush ); m_penSelect.Color = VSNetSelectionColor; return m_penSelect; } } static public Color VSNetControlColor { get { if( useCustomColor && controlColor != Color.Empty ) return controlColor; else return CalculateColor( SystemColors.Control, VSNetBackgroundColor, 195 ); } set { // Flag that we are going to use custom colors instead // of calculating the color based on the system colors // -- this is a way of hooking up into the VSNetColors that I use throughout // the Oranikle.Studio.Controls useCustomColor = true; controlColor = value; } } static public Brush VSNetControlBrush { get { if( m_brushCtrl == null ) m_brushCtrl = new SolidBrush( VSNetControlColor ); m_brushCtrl.Color = VSNetControlColor; return m_brushCtrl; } } static public Pen VSNetControlPen { get { if( m_penCtrl == null ) m_penCtrl = new Pen( VSNetControlBrush ); m_penCtrl.Color = VSNetControlColor; return m_penCtrl; } } static public Color VSNetPressedColor { get { if ( useCustomColor && pressedColor != Color.Empty ) return pressedColor; else return CalculateColor(SystemColors.Highlight, ColorUtil.VSNetSelectionColor, 70); } set { // Flag that we are going to use custom colors instead // of calculating the color based on the system colors // -- this is a way of hooking up into the VSNetColors that I use throughout // the Oranikle.Studio.Controls useCustomColor = true; pressedColor = value; } } static public Brush VSNetPressedBrush { get { if( m_brushPress == null ) m_brushPress = new SolidBrush( VSNetPressedColor ); m_brushPress.Color = VSNetPressedColor; return m_brushPress; } } static public Pen VSNetPressedPen { get { if( m_penPress == null ) m_penPress = new Pen( VSNetPressedBrush ); m_penPress.Color = VSNetPressedColor; return m_penPress; } } static public Color VSNetCheckedColor { get { if ( useCustomColor && pressedColor != Color.Empty ) return checkedColor; else return CalculateColor(SystemColors.Highlight, SystemColors.Window, 30); } set { // Flag that we are going to use custom colors instead // of calculating the color based on the system colors // -- this is a way of hooking up into the VSNetColors that I use throughout // the Oranikle.Studio.Controls useCustomColor = true; checkedColor = value; } } static public Brush VSNetCheckedBrush { get { if( m_brushCheck == null ) m_brushCheck = new SolidBrush( VSNetCheckedColor ); m_brushCheck.Color = VSNetCheckedColor; return m_brushCheck; } } static public Pen VSNetCheckedPen { get { if( m_penCheck == null ) m_penCheck = new Pen( VSNetCheckedBrush ); m_penCheck.Color = VSNetCheckedColor; return m_penCheck; } } static public Color VSNetBorderColor { get { if ( useCustomColor && borderColor != Color.Empty ) return borderColor; else { // This color is the default color unless we are using // custom colors return SystemColors.Highlight; } } set { // Flag that we are going to use custom colors instead // of calculating the color based on the system colors // -- this is a way of hooking up into the VSNetColors that I use throughout // the Oranikle.Studio.Controls useCustomColor = true; borderColor = value; } } static public Brush VSNetBorderBrush { get { if( m_brushBorder == null ) m_brushBorder = new SolidBrush( VSNetBorderColor ); m_brushBorder.Color = VSNetBorderColor; return m_brushBorder; } } static public Pen VSNetBorderPen { get { if( m_penBorder == null ) m_penBorder = new Pen( VSNetBorderBrush ); m_penBorder.Color = VSNetBorderColor; return m_penBorder; } } private static Color CalculateColor( Color front, Color back, int alpha ) { // Use alpha blending to brigthen the colors but don't use it // directly. Instead derive an opaque color that we can use. // -- if we use a color with alpha blending directly we won't be able // to paint over whatever color was in the background and there // would be shadows of that color showing through Color frontColor = Color.FromArgb(255, front); Color backColor = Color.FromArgb(255, back); float frontRed = frontColor.R; float frontGreen = frontColor.G; float frontBlue = frontColor.B; float backRed = backColor.R; float backGreen = backColor.G; float backBlue = backColor.B; float fRed = frontRed*alpha/255 + backRed*((float)(255-alpha)/255); byte newRed = (byte)fRed; float fGreen = frontGreen*alpha/255 + backGreen*((float)(255-alpha)/255); byte newGreen = (byte)fGreen; float fBlue = frontBlue*alpha/255 + backBlue*((float)(255-alpha)/255); byte newBlue = (byte)fBlue; return Color.FromArgb(255, newRed, newGreen, newBlue); } #endregion #region General functions static public Color ColorFromPoint( Graphics g, int x, int y ) { IntPtr hDC = g.GetHdc(); // Get the color of the pixel first uint colorref = WindowsAPI.GetPixel(hDC, x, y); byte Red = GetRValue(colorref); byte Green = GetGValue(colorref); byte Blue = GetBValue(colorref); g.ReleaseHdc(hDC); return Color.FromArgb(Red, Green, Blue); } static public bool IsKnownColor( Color color, ref Color knownColor, bool useTransparent ) { // Using the Color structrure "FromKnowColor" does not work if // we did not create the color as a known color to begin with // we need to compare the rgbs of both color Color currentColor = Color.Empty; bool badColor = false; for (KnownColor enumValue = 0; enumValue <= KnownColor.YellowGreen; enumValue++) { currentColor = Color.FromKnownColor(enumValue); string colorName = currentColor.Name; if ( !useTransparent ) badColor = (colorName == "Transparent"); if ( color.A == currentColor.A && color.R == currentColor.R && color.G == currentColor.G && color.B == currentColor.B && !currentColor.IsSystemColor && !badColor ) { knownColor = currentColor; return true; } } return false; } static public bool IsSystemColor( Color color, ref Color knownColor ) { // Using the Color structrure "FromKnowColor" does not work if // we did not create the color as a known color to begin with // we need to compare the rgbs of both color Color currentColor = Color.Empty; for (KnownColor enumValue = 0; enumValue <= KnownColor.YellowGreen; enumValue++) { currentColor = Color.FromKnownColor(enumValue); string colorName = currentColor.Name; if ( color.R == currentColor.R && color.G == currentColor.G && color.B == currentColor.B && currentColor.IsSystemColor ) { knownColor = currentColor; return true; } } return false; } static public uint GetCOLORREF( Color color ) { return RGB(color.R, color.G, color.B); } static public Color ColorFromRGBString( string text ) { Color rgbColor = Color.Empty; string[] RGBs = text.Split(','); if ( RGBs.Length != 3 ) { // If we don't have three pieces of information, then the // string is not properly formatted, inform the use throw new Exception("RGB color string is not well formed"); } string stringR = RGBs[0]; string stringG = RGBs[1]; string stringB = RGBs[2]; int R, G, B; try { R = Convert.ToInt32(stringR); G = Convert.ToInt32(stringG); B = Convert.ToInt32(stringB); if ( ( R < 0 || R > 255 ) || ( G < 0 || G > 255 ) || ( B < 0 || B > 255 ) ) { throw new Exception("Out of bounds RGB value"); } else { // Convert to color rgbColor = Color.FromArgb(R, G, B); // See if we have either a web color or a systgem color Color knownColor = Color.Empty; bool isKnown = ColorUtil.IsKnownColor( rgbColor, ref knownColor, true); if ( !isKnown ) isKnown = ColorUtil.IsSystemColor(rgbColor, ref knownColor); if ( isKnown ) rgbColor = knownColor; } } catch ( InvalidCastException ) { throw new Exception("Invalid RGB value"); } return rgbColor; } #endregion #region Windows RGB related macros static public byte GetRValue(uint color) { return (byte)color; } static public byte GetGValue(uint color) { return ((byte)(((short)(color)) >> 8)); } static public byte GetBValue(uint color) { return ((byte)((color)>>16)); } static public uint RGB(int r, int g, int b) { return ((uint)(((byte)(r)|((short)((byte)(g))<<8))|(((short)(byte)(b))<<16))); } static public uint RGB( Color clr ) { return ((uint)(((byte)(clr.R)|((short)((byte)(clr.G))<<8))|(((short)(byte)(clr.B))<<16))); } #endregion } }
// 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.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.UpgradeProject; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Async { public partial class UpgradeProjectTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (null, new CSharpUpgradeProjectCodeFixProvider()); private async Task TestLanguageVersionUpgradedAsync( string initialMarkup, LanguageVersion expected, ParseOptions parseOptions, int index = 0) { var parameters = new TestParameters(parseOptions: parseOptions); using (var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters)) { var actions = await GetCodeActionsAsync(workspace, parameters); var operations = await VerifyInputsAndGetOperationsAsync(index, actions, priority: null); var appliedChanges = ApplyOperationsAndGetSolution(workspace, operations); var oldSolution = appliedChanges.Item1; var newSolution = appliedChanges.Item2; Assert.True(newSolution.Projects.Where(p => p.Language == LanguageNames.CSharp) .All(p => ((CSharpParseOptions)p.ParseOptions).SpecifiedLanguageVersion == expected)); } await TestAsync(initialMarkup, initialMarkup, parseOptions); // no change to markup } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public async Task UpgradeProjectToDefault() { await TestLanguageVersionUpgradedAsync( @" class Program { void A() { var x = [|(1, 2)|]; } }", LanguageVersion.Default, new CSharpParseOptions(LanguageVersion.CSharp6)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public async Task UpgradeProjectToCSharp7() { await TestLanguageVersionUpgradedAsync( @" class Program { void A() { var x = [|(1, 2)|]; } }", LanguageVersion.CSharp7, new CSharpParseOptions(LanguageVersion.CSharp6), index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public async Task UpgradeAllProjectsToDefault() { await TestLanguageVersionUpgradedAsync( @"<Workspace> <Project Language=""C#"" LanguageVersion=""6""> <Document> class C { void A() { var x = [|(1, 2)|]; } } </Document> </Project> <Project Language=""C#"" LanguageVersion=""6""> </Project> <Project Language=""C#"" LanguageVersion=""Default""> </Project> <Project Language=""C#"" LanguageVersion=""7""> </Project> <Project Language=""Visual Basic""> </Project> </Workspace>", LanguageVersion.Default, parseOptions: null, index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public async Task UpgradeAllProjectsToCSharp7() { await TestLanguageVersionUpgradedAsync( @"<Workspace> <Project Language=""C#"" LanguageVersion=""6""> <Document> class C { void A() { var x = [|(1, 2)|]; } } </Document> </Project> <Project Language=""C#"" LanguageVersion=""6""> </Project> <Project Language=""C#"" LanguageVersion=""Default""> </Project> <Project Language=""C#"" LanguageVersion=""7""> </Project> <Project Language=""Visual Basic""> </Project> </Workspace>", LanguageVersion.Default, parseOptions: null, index: 2); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public async Task ListAllSuggestions() { await TestExactActionSetOfferedAsync( @"<Workspace> <Project Language=""C#"" LanguageVersion=""6""> <Document> class C { void A() { var x = [|(1, 2)|]; } } </Document> </Project> <Project Language=""C#"" LanguageVersion=""7""> </Project> <Project Language=""C#"" LanguageVersion=""Default""> </Project> </Workspace>", new[] { string.Format(CSharpFeaturesResources.Upgrade_this_project_to_csharp_language_version_0, "default"), string.Format(CSharpFeaturesResources.Upgrade_this_project_to_csharp_language_version_0, "7"), string.Format(CSharpFeaturesResources.Upgrade_all_csharp_projects_to_language_version_0, "default"), string.Format(CSharpFeaturesResources.Upgrade_all_csharp_projects_to_language_version_0, "7") }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public async Task FixAllProjectsNotOffered() { await TestExactActionSetOfferedAsync( @"<Workspace> <Project Language=""C#"" LanguageVersion=""6""> <Document> class C { void A() { var x = [|(1, 2)|]; } } </Document> </Project> <Project Language=""Visual Basic""> </Project> </Workspace>", new[] { string.Format(CSharpFeaturesResources.Upgrade_this_project_to_csharp_language_version_0, "default"), string.Format(CSharpFeaturesResources.Upgrade_this_project_to_csharp_language_version_0, "7") }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public async Task OnlyOfferFixAllProjectsToCSharp7WhenApplicable() { await TestExactActionSetOfferedAsync( @"<Workspace> <Project Language=""C#"" LanguageVersion=""6""> <Document> class C { void A() { var x = [|(1, 2)|]; } } </Document> </Project> <Project Language=""C#"" LanguageVersion=""7""> </Project> <Project Language=""Visual Basic""> </Project> </Workspace>", new[] { string.Format(CSharpFeaturesResources.Upgrade_this_project_to_csharp_language_version_0, "default"), string.Format(CSharpFeaturesResources.Upgrade_this_project_to_csharp_language_version_0, "7"), string.Format(CSharpFeaturesResources.Upgrade_all_csharp_projects_to_language_version_0, "default") }); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUpgradeProject)] public async Task OnlyOfferFixAllProjectsToDefaultWhenApplicable() { await TestExactActionSetOfferedAsync( @"<Workspace> <Project Language=""C#"" LanguageVersion=""6""> <Document> class C { void A() { var x = [|(1, 2)|]; } } </Document> </Project> <Project Language=""C#"" LanguageVersion=""Default""> </Project> <Project Language=""Visual Basic""> </Project> </Workspace>", new[] { string.Format(CSharpFeaturesResources.Upgrade_this_project_to_csharp_language_version_0, "default"), string.Format(CSharpFeaturesResources.Upgrade_this_project_to_csharp_language_version_0, "7"), string.Format(CSharpFeaturesResources.Upgrade_all_csharp_projects_to_language_version_0, "7") }); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.IO; using System.Threading; using System.Threading.Tasks; using Azure.Core; using Azure.Core.Pipeline; namespace Azure.AI.Personalizer { /// <summary> The Personalizer service client for instance management; Evaluations, Configuration, Model, Policy and Logs. </summary> public class PersonalizerAdministrationClient { internal LogRestClient LogRestClient { get; set; } internal ServiceConfigurationRestClient ServiceConfigurationRestClient { get; set; } internal ModelRestClient ModelRestClient { get; set; } internal EvaluationsRestClient EvaluationsRestClient { get; set; } internal PolicyRestClient PolicyRestClient { get; set; } private readonly ClientDiagnostics _clientDiagnostics; private readonly HttpPipeline _pipeline; /// <summary> Initializes a new instance of Personalizer Client for mocking. </summary> protected PersonalizerAdministrationClient() { } /// <summary> Initializes a new instance of PersonalizerClient. </summary> /// <param name="endpoint"> Supported Cognitive Services endpoint. </param> /// <param name="credential"> A credential used to authenticate to an Azure Service. </param> /// <param name="options"> The options for configuring the client. </param> public PersonalizerAdministrationClient(Uri endpoint, TokenCredential credential, PersonalizerClientOptions options = null) { if (endpoint == null) { throw new ArgumentNullException(nameof(endpoint)); } if (credential == null) { throw new ArgumentNullException(nameof(credential)); } options ??= new PersonalizerClientOptions(); _clientDiagnostics = new ClientDiagnostics(options); string[] scopes = { "https://cognitiveservices.azure.com/.default" }; _pipeline = HttpPipelineBuilder.Build(options, new BearerTokenAuthenticationPolicy(credential, scopes)); string stringEndpoint = endpoint.AbsoluteUri; LogRestClient = new LogRestClient(_clientDiagnostics, _pipeline, stringEndpoint); ServiceConfigurationRestClient = new ServiceConfigurationRestClient(_clientDiagnostics, _pipeline, stringEndpoint); ModelRestClient = new ModelRestClient(_clientDiagnostics, _pipeline, stringEndpoint); EvaluationsRestClient = new EvaluationsRestClient(_clientDiagnostics, _pipeline, stringEndpoint); PolicyRestClient = new PolicyRestClient(_clientDiagnostics, _pipeline, stringEndpoint); } /// <summary> Initializes a new instance of PersonalizerClient. </summary> /// <param name="endpoint"> Supported Cognitive Services endpoint. </param> /// <param name="credential"> A credential used to authenticate to an Azure Service. </param> /// <param name="options"> The options for configuring the client. </param> public PersonalizerAdministrationClient(Uri endpoint, AzureKeyCredential credential, PersonalizerClientOptions options = null) { if (endpoint == null) { throw new ArgumentNullException(nameof(endpoint)); } if (credential == null) { throw new ArgumentNullException(nameof(credential)); } options ??= new PersonalizerClientOptions(); _clientDiagnostics = new ClientDiagnostics(options); _pipeline = HttpPipelineBuilder.Build(options, new AzureKeyCredentialPolicy(credential, "Ocp-Apim-Subscription-Key")); string stringEndpoint = endpoint.AbsoluteUri; LogRestClient = new LogRestClient(_clientDiagnostics, _pipeline, stringEndpoint); ServiceConfigurationRestClient = new ServiceConfigurationRestClient(_clientDiagnostics, _pipeline, stringEndpoint); ModelRestClient = new ModelRestClient(_clientDiagnostics, _pipeline, stringEndpoint); EvaluationsRestClient = new EvaluationsRestClient(_clientDiagnostics, _pipeline, stringEndpoint); PolicyRestClient = new PolicyRestClient(_clientDiagnostics, _pipeline, stringEndpoint); } /// <summary> Initializes a new instance of LogClient. </summary> /// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param> /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param> /// <param name="endpoint"> Supported Cognitive Services endpoint. </param> internal PersonalizerAdministrationClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Uri endpoint) { string stringEndpoint = endpoint.AbsoluteUri; LogRestClient = new LogRestClient(_clientDiagnostics, _pipeline, stringEndpoint); ServiceConfigurationRestClient = new ServiceConfigurationRestClient(_clientDiagnostics, _pipeline, stringEndpoint); ModelRestClient = new ModelRestClient(_clientDiagnostics, _pipeline, stringEndpoint); EvaluationsRestClient = new EvaluationsRestClient(_clientDiagnostics, _pipeline, stringEndpoint); PolicyRestClient = new PolicyRestClient(_clientDiagnostics, _pipeline, stringEndpoint); _clientDiagnostics = clientDiagnostics; _pipeline = pipeline; } /// <summary> Delete all logs of Rank and Reward calls stored by Personalizer. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response> DeletePersonalizerLogsAsync(CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.DeletePersonalizerLogs"); scope.Start(); try { return await LogRestClient.DeleteAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Delete all logs of Rank and Reward calls stored by Personalizer. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response DeletePersonalizerLogs(CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.DeletePersonalizerLogs"); scope.Start(); try { return LogRestClient.Delete(cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Get properties of the Personalizer logs. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response<PersonalizerLogProperties>> GetPersonalizerLogPropertiesAsync(CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.GetPersonalizerLogProperties"); scope.Start(); try { return await LogRestClient.GetPropertiesAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Get properties of the Personalizer logs. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response<PersonalizerLogProperties> GetPersonalizerLogProperties(CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.GetPersonalizerLogProperties"); scope.Start(); try { return LogRestClient.GetProperties(cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Update the Personalizer service configuration. </summary> /// <param name="config"> The personalizer service configuration. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response<PersonalizerServiceProperties >> UpdatePersonalizerPropertiesAsync(PersonalizerServiceProperties config, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.UpdatePersonalizerProperties"); scope.Start(); try { return await ServiceConfigurationRestClient.UpdateAsync(config, cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Update the Personalizer service configuration. </summary> /// <param name="config"> The personalizer service configuration. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response<PersonalizerServiceProperties > UpdatePersonalizerProperties(PersonalizerServiceProperties config, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.UpdatePersonalizerProperties"); scope.Start(); try { return ServiceConfigurationRestClient.Update(config, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Get the Personalizer service configuration. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response<PersonalizerServiceProperties >> GetPersonalizerPropertiesAsync(CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.GetPersonalizerProperties"); scope.Start(); try { return await ServiceConfigurationRestClient.GetAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Get the Personalizer service configuration. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response<PersonalizerServiceProperties > GetPersonalizerProperties(CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.GetPersonalizerProperties"); scope.Start(); try { return ServiceConfigurationRestClient.Get(cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Apply Learning Settings and model from a pre-existing Offline Evaluation, making them the current online Learning Settings and model and replacing the previous ones. </summary> /// <param name="body"> The PolicyReferenceContract to use. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response> ApplyPersonalizerEvaluationAsync(PersonalizerPolicyReferenceOptions body, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.ApplyPersonalizerEvaluation"); scope.Start(); try { return await ServiceConfigurationRestClient.ApplyFromEvaluationAsync(body, cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Apply Learning Settings and model from a pre-existing Offline Evaluation, making them the current online Learning Settings and model and replacing the previous ones. </summary> /// <param name="body"> The PolicyReferenceContract to use. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response ApplyPersonalizerEvaluation(PersonalizerPolicyReferenceOptions body, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.ApplyPersonalizerEvaluation"); scope.Start(); try { return ServiceConfigurationRestClient.ApplyFromEvaluation(body, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Export the current model used by Personalizer service. </summary> /// <param name="isSigned">True if requesting signed model zip archive, false otherwise.</param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <remarks> Exports the Personalizer model. </remarks> public virtual async Task<Response<Stream>> ExportPersonalizerModelAsync(bool isSigned, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.ExportPersonalizerModel"); scope.Start(); try { return await ModelRestClient.GetAsync(isSigned, cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Export the current model used by Personalizer service. </summary> /// <param name="isSigned">True if requesting signed model zip archive, false otherwise.</param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <remarks> Exports the Personalizer model. </remarks> public virtual Response<Stream> ExportPersonalizerModel(bool isSigned, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.ExportPersonalizerModel"); scope.Start(); try { return ModelRestClient.Get(isSigned, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Replace the current model used by Personalizer service with an updated model. </summary> /// <param name="modelBody">Stream representing the digitally signed model zip archive.</param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response> ImportPersonalizerSignedModelAsync(Stream modelBody, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.ImportPersonalizerSignedModel"); scope.Start(); try { return await ModelRestClient.ImportAsync(modelBody, cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Replace the current model used by Personalizer service with an updated model. </summary> /// <param name="modelBody">Stream representing the digitally signed model zip archive.</param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response ImportPersonalizerSignedModel(Stream modelBody, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.ImportPersonalizerSignedModel"); scope.Start(); try { return ModelRestClient.Import(modelBody, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Resets the model file generated by Personalizer service. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response> ResetPersonalizerModelAsync(CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.ResetPersonalizerModel"); scope.Start(); try { return await ModelRestClient.ResetAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Resets the model file generated by Personalizer service. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response ResetPersonalizerModel(CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.ResetPersonalizerModel"); scope.Start(); try { return ModelRestClient.Reset(cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Get properties of the model file generated by Personalizer service. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response<PersonalizerModelProperties>> GetPersonalizerModelPropertiesAsync(CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.GetPersonalizerModelProperties"); scope.Start(); try { return await ModelRestClient.GetPropertiesAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Get properties of the model file generated by Personalizer service. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response<PersonalizerModelProperties> GetPersonalizerModelProperties(CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.GetPersonalizerModelProperties"); scope.Start(); try { return ModelRestClient.GetProperties(cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Get the Learning Settings currently used by the Personalizer service. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response<PersonalizerPolicy>> GetPersonalizerPolicyAsync(CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.GetPersonalizerPolicy"); scope.Start(); try { return await PolicyRestClient.GetAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Get the Learning Settings currently used by the Personalizer service. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response<PersonalizerPolicy> GetPersonalizerPolicy(CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.GetPersonalizerPolicy"); scope.Start(); try { return PolicyRestClient.Get(cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Update the Learning Settings that the Personalizer service will use to train models. </summary> /// <param name="policy"> The learning settings. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response<PersonalizerPolicy>> UpdatePersonalizerPolicyAsync(PersonalizerPolicy policy, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.UpdatePersonalizerPolicy"); scope.Start(); try { return await PolicyRestClient.UpdateAsync(policy, cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Update the Learning Settings that the Personalizer service will use to train models. </summary> /// <param name="policy"> The learning settings. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response<PersonalizerPolicy> UpdatePersonalizerPolicy(PersonalizerPolicy policy, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.UpdatePersonalizerPolicy"); scope.Start(); try { return PolicyRestClient.Update(policy, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Resets the learning settings of the Personalizer service to default. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response<PersonalizerPolicy>> ResetPersonalizerPolicyAsync(CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.ResetPersonalizerPolicy"); scope.Start(); try { return await PolicyRestClient.ResetAsync(cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Resets the learning settings of the Personalizer service to default. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response<PersonalizerPolicy> ResetPersonalizerPolicy(CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.ResetPersonalizerPolicy"); scope.Start(); try { return PolicyRestClient.Reset(cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Delete the Offline Evaluation associated with the Id. </summary> /// <param name="evaluationId"> Id of the Offline Evaluation to delete. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response> DeletePersonalizerEvaluationAsync(string evaluationId, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.DeletePersonalizerEvaluation"); scope.Start(); try { return await EvaluationsRestClient.DeleteAsync(evaluationId, cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Delete the Offline Evaluation associated with the Id. </summary> /// <param name="evaluationId"> Id of the Offline Evaluation to delete. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response DeletePersonalizerEvaluation(string evaluationId, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.DeletePersonalizerEvaluation"); scope.Start(); try { return EvaluationsRestClient.Delete(evaluationId, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Get the Offline Evaluation associated with the Id. </summary> /// <param name="evaluationId"> Id of the Offline Evaluation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response<PersonalizerEvaluation>> GetPersonalizerEvaluationAsync(string evaluationId, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.GetPersonalizerEvaluation"); scope.Start(); try { return await EvaluationsRestClient.GetAsync(evaluationId, cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Get the Offline Evaluation associated with the Id. </summary> /// <param name="evaluationId"> Id of the Offline Evaluation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response<PersonalizerEvaluation> GetPersonalizerEvaluation(string evaluationId, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.GetPersonalizerEvaluation"); scope.Start(); try { return EvaluationsRestClient.Get(evaluationId, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> List of all Offline Evaluations. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual AsyncPageable<PersonalizerEvaluation> GetPersonalizerEvaluationsAsync(CancellationToken cancellationToken = default) { return PageResponseEnumerator.CreateAsyncEnumerable(async (continuationToken) => { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.GetPersonalizerEvaluations"); scope.Start(); try { if (continuationToken != null) { throw new NotSupportedException("A continuation token is unsupported."); } Response<IReadOnlyList<PersonalizerEvaluation>> result = await EvaluationsRestClient.ListAsync(cancellationToken).ConfigureAwait(false); return Page<PersonalizerEvaluation>.FromValues(result.Value, null, result.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } }); } /// <summary> List of all Offline Evaluations. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Pageable<PersonalizerEvaluation> GetPersonalizerEvaluations(CancellationToken cancellationToken = default) { return PageResponseEnumerator.CreateEnumerable((continuationToken) => { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.GetPersonalizerEvaluations"); scope.Start(); try { if (continuationToken != null) { throw new NotSupportedException("A continuation token is unsupported."); } Response<IReadOnlyList<PersonalizerEvaluation>> result = EvaluationsRestClient.List(cancellationToken); return Page<PersonalizerEvaluation>.FromValues(result.Value, null, result.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } }); } /// <summary> Submit a new Offline Evaluation job. </summary> /// <param name="evaluation"> The Offline Evaluation job definition. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<PersonalizerCreateEvaluationOperation> CreatePersonalizerEvaluationAsync(PersonalizerEvaluationOptions evaluation, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.CreatePersonalizerEvaluation"); scope.Start(); try { Response<PersonalizerEvaluation> result = await EvaluationsRestClient.CreateAsync(evaluation, cancellationToken).ConfigureAwait(false); return new PersonalizerCreateEvaluationOperation(this, result.Value.Id, result.GetRawResponse(), cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Submit a new Offline Evaluation job. </summary> /// <param name="evaluation"> The Offline Evaluation job definition. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual PersonalizerCreateEvaluationOperation CreatePersonalizerEvaluation(PersonalizerEvaluationOptions evaluation, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope("PersonalizerAdministrationClient.CreatePersonalizerEvaluation"); scope.Start(); try { Response<PersonalizerEvaluation> result = EvaluationsRestClient.Create(evaluation, cancellationToken); return new PersonalizerCreateEvaluationOperation(this, result.Value.Id, result.GetRawResponse(), cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } } }
// 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 Microsoft.Xml.Schema { using System; using Microsoft.Xml; using System.Collections; using System.Collections.Generic; using System.IO; using System.Diagnostics; using System.Runtime.Versioning; #pragma warning disable 618 internal sealed class SchemaCollectionPreprocessor : BaseProcessor { private enum Compositor { Root, Include, Import }; private XmlSchema _schema; private string _targetNamespace; private bool _buildinIncluded = false; private XmlSchemaForm _elementFormDefault; private XmlSchemaForm _attributeFormDefault; private XmlSchemaDerivationMethod _blockDefault; private XmlSchemaDerivationMethod _finalDefault; //Dictionary<Uri, Uri> schemaLocations; private Hashtable _schemaLocations; private Hashtable _referenceNamespaces; private string _xmlns; private const XmlSchemaDerivationMethod schemaBlockDefaultAllowed = XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.Extension | XmlSchemaDerivationMethod.Substitution; private const XmlSchemaDerivationMethod schemaFinalDefaultAllowed = XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.Extension | XmlSchemaDerivationMethod.List | XmlSchemaDerivationMethod.Union; private const XmlSchemaDerivationMethod elementBlockAllowed = XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.Extension | XmlSchemaDerivationMethod.Substitution; private const XmlSchemaDerivationMethod elementFinalAllowed = XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.Extension; private const XmlSchemaDerivationMethod simpleTypeFinalAllowed = XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.List | XmlSchemaDerivationMethod.Union; private const XmlSchemaDerivationMethod complexTypeBlockAllowed = XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.Extension; private const XmlSchemaDerivationMethod complexTypeFinalAllowed = XmlSchemaDerivationMethod.Restriction | XmlSchemaDerivationMethod.Extension; private XmlResolver _xmlResolver = null; public SchemaCollectionPreprocessor(XmlNameTable nameTable, SchemaNames schemaNames, ValidationEventHandler eventHandler) : base(nameTable, schemaNames, eventHandler) { } public bool Execute(XmlSchema schema, string targetNamespace, bool loadExternals, XmlSchemaCollection xsc) { _schema = schema; _xmlns = NameTable.Add("xmlns"); Cleanup(schema); if (loadExternals && _xmlResolver != null) { _schemaLocations = new Hashtable(); //new Dictionary<Uri, Uri>(); if (schema.BaseUri != null) { _schemaLocations.Add(schema.BaseUri, schema.BaseUri); } LoadExternals(schema, xsc); } ValidateIdAttribute(schema); Preprocess(schema, targetNamespace, Compositor.Root); if (!HasErrors) { schema.IsPreprocessed = true; for (int i = 0; i < schema.Includes.Count; ++i) { XmlSchemaExternal include = (XmlSchemaExternal)schema.Includes[i]; if (include.Schema != null) { include.Schema.IsPreprocessed = true; } } } return !HasErrors; } private void Cleanup(XmlSchema schema) { if (schema.IsProcessing) { return; } schema.IsProcessing = true; for (int i = 0; i < schema.Includes.Count; ++i) { XmlSchemaExternal include = (XmlSchemaExternal)schema.Includes[i]; if (include.Schema != null) { Cleanup(include.Schema); } if (include is XmlSchemaRedefine) { XmlSchemaRedefine rdef = include as XmlSchemaRedefine; rdef.AttributeGroups.Clear(); rdef.Groups.Clear(); rdef.SchemaTypes.Clear(); } } schema.Attributes.Clear(); schema.AttributeGroups.Clear(); schema.SchemaTypes.Clear(); schema.Elements.Clear(); schema.Groups.Clear(); schema.Notations.Clear(); schema.Ids.Clear(); schema.IdentityConstraints.Clear(); schema.IsProcessing = false; } internal XmlResolver XmlResolver { set { _xmlResolver = value; } } // SxS: This method reads resource names from the source documents and does not return any resources to the caller // It's fine to disable the SxS warning private void LoadExternals(XmlSchema schema, XmlSchemaCollection xsc) { if (schema.IsProcessing) { return; } schema.IsProcessing = true; for (int i = 0; i < schema.Includes.Count; ++i) { XmlSchemaExternal include = (XmlSchemaExternal)schema.Includes[i]; Uri includeLocation = null; //CASE 1: If the Schema object of the include has been set if (include.Schema != null) { // already loaded if (include is XmlSchemaImport && ((XmlSchemaImport)include).Namespace == XmlReservedNs.NsXml) { _buildinIncluded = true; } else { includeLocation = include.BaseUri; if (includeLocation != null && _schemaLocations[includeLocation] == null) { _schemaLocations.Add(includeLocation, includeLocation); } LoadExternals(include.Schema, xsc); } continue; } //CASE 2: If the include has been already added to the schema collection directly if (xsc != null && include is XmlSchemaImport) { //Added for SchemaCollection compatibility XmlSchemaImport import = (XmlSchemaImport)include; string importNS = import.Namespace != null ? import.Namespace : string.Empty; include.Schema = xsc[importNS]; //Fetch it from the collection if (include.Schema != null) { include.Schema = include.Schema.Clone(); if (include.Schema.BaseUri != null && _schemaLocations[include.Schema.BaseUri] == null) { _schemaLocations.Add(include.Schema.BaseUri, include.Schema.BaseUri); } //To avoid re-including components that were already included through a different path Uri subUri = null; for (int j = 0; j < include.Schema.Includes.Count; ++j) { XmlSchemaExternal subInc = (XmlSchemaExternal)include.Schema.Includes[j]; if (subInc is XmlSchemaImport) { XmlSchemaImport subImp = (XmlSchemaImport)subInc; subUri = subImp.BaseUri != null ? subImp.BaseUri : (subImp.Schema != null && subImp.Schema.BaseUri != null ? subImp.Schema.BaseUri : null); if (subUri != null) { if (_schemaLocations[subUri] != null) { subImp.Schema = null; //So that the components are not included again } else { //if its not there already, add it _schemaLocations.Add(subUri, subUri); //The schema for that location is available } } } } continue; } } //CASE 3: If the imported namespace is the XML namespace, load built-in schema if (include is XmlSchemaImport && ((XmlSchemaImport)include).Namespace == XmlReservedNs.NsXml) { if (!_buildinIncluded) { _buildinIncluded = true; include.Schema = Preprocessor.GetBuildInSchema(); } continue; } //CASE4: Parse schema from the provided location string schemaLocation = include.SchemaLocation; if (schemaLocation == null) { continue; } Uri ruri = ResolveSchemaLocationUri(schema, schemaLocation); if (ruri != null && _schemaLocations[ruri] == null) { Stream stream = GetSchemaEntity(ruri); if (stream != null) { include.BaseUri = ruri; _schemaLocations.Add(ruri, ruri); XmlTextReader reader = new XmlTextReader(ruri.ToString(), stream, NameTable); reader.XmlResolver = _xmlResolver; try { Parser parser = new Parser(SchemaType.XSD, NameTable, SchemaNames, EventHandler); parser.Parse(reader, null); while (reader.Read()) ;// wellformness check include.Schema = parser.XmlSchema; LoadExternals(include.Schema, xsc); } catch (XmlSchemaException e) { SendValidationEventNoThrow(new XmlSchemaException(ResXml.Sch_CannotLoadSchema, new string[] { schemaLocation, e.Message }, e.SourceUri, e.LineNumber, e.LinePosition), XmlSeverityType.Error); } catch (Exception) { SendValidationEvent(ResXml.Sch_InvalidIncludeLocation, include, XmlSeverityType.Warning); } finally { reader.Close(); } } else { SendValidationEvent(ResXml.Sch_InvalidIncludeLocation, include, XmlSeverityType.Warning); } } } schema.IsProcessing = false; } private void BuildRefNamespaces(XmlSchema schema) { _referenceNamespaces = new Hashtable(); XmlSchemaImport import; string ns; //Add XSD namespace _referenceNamespaces.Add(XmlReservedNs.NsXs, XmlReservedNs.NsXs); _referenceNamespaces.Add(string.Empty, string.Empty); for (int i = 0; i < schema.Includes.Count; ++i) { import = schema.Includes[i] as XmlSchemaImport; if (import != null) { ns = import.Namespace; if (ns != null && _referenceNamespaces[ns] == null) _referenceNamespaces.Add(ns, ns); } } //Add the schema's targetnamespace if (schema.TargetNamespace != null && _referenceNamespaces[schema.TargetNamespace] == null) _referenceNamespaces.Add(schema.TargetNamespace, schema.TargetNamespace); } private void Preprocess(XmlSchema schema, string targetNamespace, Compositor compositor) { if (schema.IsProcessing) { return; } schema.IsProcessing = true; string tns = schema.TargetNamespace; if (tns != null) { schema.TargetNamespace = tns = NameTable.Add(tns); if (tns.Length == 0) { SendValidationEvent(ResXml.Sch_InvalidTargetNamespaceAttribute, schema); } else { try { XmlConvert.ToUri(tns); // can throw } catch { SendValidationEvent(ResXml.Sch_InvalidNamespace, schema.TargetNamespace, schema); } } } if (schema.Version != null) { try { XmlConvert.VerifyTOKEN(schema.Version); // can throw } catch (Exception) { SendValidationEvent(ResXml.Sch_AttributeValueDataType, "version", schema); } } switch (compositor) { case Compositor.Root: if (targetNamespace == null && schema.TargetNamespace != null) { // not specified targetNamespace = schema.TargetNamespace; } else if (schema.TargetNamespace == null && targetNamespace != null && targetNamespace.Length == 0) { // no namespace schema targetNamespace = null; } if (targetNamespace != schema.TargetNamespace) { SendValidationEvent(ResXml.Sch_MismatchTargetNamespaceEx, targetNamespace, schema.TargetNamespace, schema); } break; case Compositor.Import: if (targetNamespace != schema.TargetNamespace) { SendValidationEvent(ResXml.Sch_MismatchTargetNamespaceImport, targetNamespace, schema.TargetNamespace, schema); } break; case Compositor.Include: if (schema.TargetNamespace != null) { if (targetNamespace != schema.TargetNamespace) { SendValidationEvent(ResXml.Sch_MismatchTargetNamespaceInclude, targetNamespace, schema.TargetNamespace, schema); } } break; } for (int i = 0; i < schema.Includes.Count; ++i) { XmlSchemaExternal include = (XmlSchemaExternal)schema.Includes[i]; SetParent(include, schema); PreprocessAnnotation(include); string loc = include.SchemaLocation; if (loc != null) { try { XmlConvert.ToUri(loc); // can throw } catch { SendValidationEvent(ResXml.Sch_InvalidSchemaLocation, loc, include); } } else if ((include is XmlSchemaRedefine || include is XmlSchemaInclude) && include.Schema == null) { SendValidationEvent(ResXml.Sch_MissRequiredAttribute, "schemaLocation", include); } if (include.Schema != null) { if (include is XmlSchemaRedefine) { Preprocess(include.Schema, schema.TargetNamespace, Compositor.Include); } else if (include is XmlSchemaImport) { if (((XmlSchemaImport)include).Namespace == null && schema.TargetNamespace == null) { SendValidationEvent(ResXml.Sch_ImportTargetNamespaceNull, include); } else if (((XmlSchemaImport)include).Namespace == schema.TargetNamespace) { SendValidationEvent(ResXml.Sch_ImportTargetNamespace, include); } Preprocess(include.Schema, ((XmlSchemaImport)include).Namespace, Compositor.Import); } else { Preprocess(include.Schema, schema.TargetNamespace, Compositor.Include); } } else if (include is XmlSchemaImport) { string ns = ((XmlSchemaImport)include).Namespace; if (ns != null) { if (ns.Length == 0) { SendValidationEvent(ResXml.Sch_InvalidNamespaceAttribute, ns, include); } else { try { XmlConvert.ToUri(ns); //can throw } catch (FormatException) { SendValidationEvent(ResXml.Sch_InvalidNamespace, ns, include); } } } } } //Begin processing the current schema passed to preprocess //Build the namespaces that can be referenced in the current schema BuildRefNamespaces(schema); _targetNamespace = targetNamespace == null ? string.Empty : targetNamespace; if (schema.BlockDefault == XmlSchemaDerivationMethod.All) { _blockDefault = XmlSchemaDerivationMethod.All; } else if (schema.BlockDefault == XmlSchemaDerivationMethod.None) { _blockDefault = XmlSchemaDerivationMethod.Empty; } else { if ((schema.BlockDefault & ~schemaBlockDefaultAllowed) != 0) { SendValidationEvent(ResXml.Sch_InvalidBlockDefaultValue, schema); } _blockDefault = schema.BlockDefault & schemaBlockDefaultAllowed; } if (schema.FinalDefault == XmlSchemaDerivationMethod.All) { _finalDefault = XmlSchemaDerivationMethod.All; } else if (schema.FinalDefault == XmlSchemaDerivationMethod.None) { _finalDefault = XmlSchemaDerivationMethod.Empty; } else { if ((schema.FinalDefault & ~schemaFinalDefaultAllowed) != 0) { SendValidationEvent(ResXml.Sch_InvalidFinalDefaultValue, schema); } _finalDefault = schema.FinalDefault & schemaFinalDefaultAllowed; } _elementFormDefault = schema.ElementFormDefault; if (_elementFormDefault == XmlSchemaForm.None) { _elementFormDefault = XmlSchemaForm.Unqualified; } _attributeFormDefault = schema.AttributeFormDefault; if (_attributeFormDefault == XmlSchemaForm.None) { _attributeFormDefault = XmlSchemaForm.Unqualified; } for (int i = 0; i < schema.Includes.Count; ++i) { XmlSchemaExternal include = (XmlSchemaExternal)schema.Includes[i]; if (include is XmlSchemaRedefine) { XmlSchemaRedefine redefine = (XmlSchemaRedefine)include; if (include.Schema != null) { PreprocessRedefine(redefine); } else { for (int j = 0; j < redefine.Items.Count; ++j) { if (!(redefine.Items[j] is XmlSchemaAnnotation)) { SendValidationEvent(ResXml.Sch_RedefineNoSchema, redefine); break; } } } } XmlSchema includedSchema = include.Schema; if (includedSchema != null) { foreach (XmlSchemaElement element in includedSchema.Elements.Values) { AddToTable(schema.Elements, element.QualifiedName, element); } foreach (XmlSchemaAttribute attribute in includedSchema.Attributes.Values) { AddToTable(schema.Attributes, attribute.QualifiedName, attribute); } foreach (XmlSchemaGroup group in includedSchema.Groups.Values) { AddToTable(schema.Groups, group.QualifiedName, group); } foreach (XmlSchemaAttributeGroup attributeGroup in includedSchema.AttributeGroups.Values) { AddToTable(schema.AttributeGroups, attributeGroup.QualifiedName, attributeGroup); } foreach (XmlSchemaType type in includedSchema.SchemaTypes.Values) { AddToTable(schema.SchemaTypes, type.QualifiedName, type); } foreach (XmlSchemaNotation notation in includedSchema.Notations.Values) { AddToTable(schema.Notations, notation.QualifiedName, notation); } } ValidateIdAttribute(include); } List<XmlSchemaObject> removeItemsList = new List<XmlSchemaObject>(); for (int i = 0; i < schema.Items.Count; ++i) { SetParent(schema.Items[i], schema); XmlSchemaAttribute attribute = schema.Items[i] as XmlSchemaAttribute; if (attribute != null) { PreprocessAttribute(attribute); AddToTable(schema.Attributes, attribute.QualifiedName, attribute); } else if (schema.Items[i] is XmlSchemaAttributeGroup) { XmlSchemaAttributeGroup attributeGroup = (XmlSchemaAttributeGroup)schema.Items[i]; PreprocessAttributeGroup(attributeGroup); AddToTable(schema.AttributeGroups, attributeGroup.QualifiedName, attributeGroup); } else if (schema.Items[i] is XmlSchemaComplexType) { XmlSchemaComplexType complexType = (XmlSchemaComplexType)schema.Items[i]; PreprocessComplexType(complexType, false); AddToTable(schema.SchemaTypes, complexType.QualifiedName, complexType); } else if (schema.Items[i] is XmlSchemaSimpleType) { XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)schema.Items[i]; PreprocessSimpleType(simpleType, false); AddToTable(schema.SchemaTypes, simpleType.QualifiedName, simpleType); } else if (schema.Items[i] is XmlSchemaElement) { XmlSchemaElement element = (XmlSchemaElement)schema.Items[i]; PreprocessElement(element); AddToTable(schema.Elements, element.QualifiedName, element); } else if (schema.Items[i] is XmlSchemaGroup) { XmlSchemaGroup group = (XmlSchemaGroup)schema.Items[i]; PreprocessGroup(group); AddToTable(schema.Groups, group.QualifiedName, group); } else if (schema.Items[i] is XmlSchemaNotation) { XmlSchemaNotation notation = (XmlSchemaNotation)schema.Items[i]; PreprocessNotation(notation); AddToTable(schema.Notations, notation.QualifiedName, notation); } else if (!(schema.Items[i] is XmlSchemaAnnotation)) { SendValidationEvent(ResXml.Sch_InvalidCollection, schema.Items[i]); removeItemsList.Add(schema.Items[i]); } } for (int i = 0; i < removeItemsList.Count; ++i) { schema.Items.Remove(removeItemsList[i]); } schema.IsProcessing = false; } private void PreprocessRedefine(XmlSchemaRedefine redefine) { for (int i = 0; i < redefine.Items.Count; ++i) { SetParent(redefine.Items[i], redefine); XmlSchemaGroup group = redefine.Items[i] as XmlSchemaGroup; if (group != null) { PreprocessGroup(group); if (redefine.Groups[group.QualifiedName] != null) { SendValidationEvent(ResXml.Sch_GroupDoubleRedefine, group); } else { AddToTable(redefine.Groups, group.QualifiedName, group); group.Redefined = (XmlSchemaGroup)redefine.Schema.Groups[group.QualifiedName]; if (group.Redefined != null) { CheckRefinedGroup(group); } else { SendValidationEvent(ResXml.Sch_GroupRedefineNotFound, group); } } } else if (redefine.Items[i] is XmlSchemaAttributeGroup) { XmlSchemaAttributeGroup attributeGroup = (XmlSchemaAttributeGroup)redefine.Items[i]; PreprocessAttributeGroup(attributeGroup); if (redefine.AttributeGroups[attributeGroup.QualifiedName] != null) { SendValidationEvent(ResXml.Sch_AttrGroupDoubleRedefine, attributeGroup); } else { AddToTable(redefine.AttributeGroups, attributeGroup.QualifiedName, attributeGroup); attributeGroup.Redefined = (XmlSchemaAttributeGroup)redefine.Schema.AttributeGroups[attributeGroup.QualifiedName]; if (attributeGroup.Redefined != null) { CheckRefinedAttributeGroup(attributeGroup); } else { SendValidationEvent(ResXml.Sch_AttrGroupRedefineNotFound, attributeGroup); } } } else if (redefine.Items[i] is XmlSchemaComplexType) { XmlSchemaComplexType complexType = (XmlSchemaComplexType)redefine.Items[i]; PreprocessComplexType(complexType, false); if (redefine.SchemaTypes[complexType.QualifiedName] != null) { SendValidationEvent(ResXml.Sch_ComplexTypeDoubleRedefine, complexType); } else { AddToTable(redefine.SchemaTypes, complexType.QualifiedName, complexType); XmlSchemaType type = (XmlSchemaType)redefine.Schema.SchemaTypes[complexType.QualifiedName]; if (type != null) { if (type is XmlSchemaComplexType) { complexType.Redefined = type; CheckRefinedComplexType(complexType); } else { SendValidationEvent(ResXml.Sch_SimpleToComplexTypeRedefine, complexType); } } else { SendValidationEvent(ResXml.Sch_ComplexTypeRedefineNotFound, complexType); } } } else if (redefine.Items[i] is XmlSchemaSimpleType) { XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)redefine.Items[i]; PreprocessSimpleType(simpleType, false); if (redefine.SchemaTypes[simpleType.QualifiedName] != null) { SendValidationEvent(ResXml.Sch_SimpleTypeDoubleRedefine, simpleType); } else { AddToTable(redefine.SchemaTypes, simpleType.QualifiedName, simpleType); XmlSchemaType type = (XmlSchemaType)redefine.Schema.SchemaTypes[simpleType.QualifiedName]; if (type != null) { if (type is XmlSchemaSimpleType) { simpleType.Redefined = type; CheckRefinedSimpleType(simpleType); } else { SendValidationEvent(ResXml.Sch_ComplexToSimpleTypeRedefine, simpleType); } } else { SendValidationEvent(ResXml.Sch_SimpleTypeRedefineNotFound, simpleType); } } } } foreach (DictionaryEntry entry in redefine.Groups) { redefine.Schema.Groups.Insert((XmlQualifiedName)entry.Key, (XmlSchemaObject)entry.Value); } foreach (DictionaryEntry entry in redefine.AttributeGroups) { redefine.Schema.AttributeGroups.Insert((XmlQualifiedName)entry.Key, (XmlSchemaObject)entry.Value); } foreach (DictionaryEntry entry in redefine.SchemaTypes) { redefine.Schema.SchemaTypes.Insert((XmlQualifiedName)entry.Key, (XmlSchemaObject)entry.Value); } } private int CountGroupSelfReference(XmlSchemaObjectCollection items, XmlQualifiedName name) { int count = 0; for (int i = 0; i < items.Count; ++i) { XmlSchemaGroupRef groupRef = items[i] as XmlSchemaGroupRef; if (groupRef != null) { if (groupRef.RefName == name) { if (groupRef.MinOccurs != decimal.One || groupRef.MaxOccurs != decimal.One) { SendValidationEvent(ResXml.Sch_MinMaxGroupRedefine, groupRef); } count++; } } else if (items[i] is XmlSchemaGroupBase) { count += CountGroupSelfReference(((XmlSchemaGroupBase)items[i]).Items, name); } if (count > 1) { break; } } return count; } private void CheckRefinedGroup(XmlSchemaGroup group) { int count = 0; if (group.Particle != null) { count = CountGroupSelfReference(group.Particle.Items, group.QualifiedName); } if (count > 1) { SendValidationEvent(ResXml.Sch_MultipleGroupSelfRef, group); } } private void CheckRefinedAttributeGroup(XmlSchemaAttributeGroup attributeGroup) { int count = 0; for (int i = 0; i < attributeGroup.Attributes.Count; ++i) { XmlSchemaAttributeGroupRef groupRef = attributeGroup.Attributes[i] as XmlSchemaAttributeGroupRef; if (groupRef != null && groupRef.RefName == attributeGroup.QualifiedName) { count++; } } if (count > 1) { SendValidationEvent(ResXml.Sch_MultipleAttrGroupSelfRef, attributeGroup); } } private void CheckRefinedSimpleType(XmlSchemaSimpleType stype) { if (stype.Content != null && stype.Content is XmlSchemaSimpleTypeRestriction) { XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)stype.Content; if (restriction.BaseTypeName == stype.QualifiedName) { return; } } SendValidationEvent(ResXml.Sch_InvalidTypeRedefine, stype); } private void CheckRefinedComplexType(XmlSchemaComplexType ctype) { if (ctype.ContentModel != null) { XmlQualifiedName baseName; if (ctype.ContentModel is XmlSchemaComplexContent) { XmlSchemaComplexContent content = (XmlSchemaComplexContent)ctype.ContentModel; if (content.Content is XmlSchemaComplexContentRestriction) { baseName = ((XmlSchemaComplexContentRestriction)content.Content).BaseTypeName; } else { baseName = ((XmlSchemaComplexContentExtension)content.Content).BaseTypeName; } } else { XmlSchemaSimpleContent content = (XmlSchemaSimpleContent)ctype.ContentModel; if (content.Content is XmlSchemaSimpleContentRestriction) { baseName = ((XmlSchemaSimpleContentRestriction)content.Content).BaseTypeName; } else { baseName = ((XmlSchemaSimpleContentExtension)content.Content).BaseTypeName; } } if (baseName == ctype.QualifiedName) { return; } } SendValidationEvent(ResXml.Sch_InvalidTypeRedefine, ctype); } private void PreprocessAttribute(XmlSchemaAttribute attribute) { if (attribute.Name != null) { ValidateNameAttribute(attribute); attribute.SetQualifiedName(new XmlQualifiedName(attribute.Name, _targetNamespace)); } else { SendValidationEvent(ResXml.Sch_MissRequiredAttribute, "name", attribute); } if (attribute.Use != XmlSchemaUse.None) { SendValidationEvent(ResXml.Sch_ForbiddenAttribute, "use", attribute); } if (attribute.Form != XmlSchemaForm.None) { SendValidationEvent(ResXml.Sch_ForbiddenAttribute, "form", attribute); } PreprocessAttributeContent(attribute); ValidateIdAttribute(attribute); } private void PreprocessLocalAttribute(XmlSchemaAttribute attribute) { if (attribute.Name != null) { // name ValidateNameAttribute(attribute); PreprocessAttributeContent(attribute); attribute.SetQualifiedName(new XmlQualifiedName(attribute.Name, (attribute.Form == XmlSchemaForm.Qualified || (attribute.Form == XmlSchemaForm.None && _attributeFormDefault == XmlSchemaForm.Qualified)) ? _targetNamespace : null)); } else { // ref PreprocessAnnotation(attribute); //set parent of annotation child of ref if (attribute.RefName.IsEmpty) { SendValidationEvent(ResXml.Sch_AttributeNameRef, "???", attribute); } else { ValidateQNameAttribute(attribute, "ref", attribute.RefName); } if (!attribute.SchemaTypeName.IsEmpty || attribute.SchemaType != null || attribute.Form != XmlSchemaForm.None /*|| attribute.DefaultValue != null || attribute.FixedValue != null*/ ) { SendValidationEvent(ResXml.Sch_InvalidAttributeRef, attribute); } attribute.SetQualifiedName(attribute.RefName); } ValidateIdAttribute(attribute); } private void PreprocessAttributeContent(XmlSchemaAttribute attribute) { PreprocessAnnotation(attribute); if (_schema.TargetNamespace == XmlReservedNs.NsXsi) { SendValidationEvent(ResXml.Sch_TargetNamespaceXsi, attribute); } if (!attribute.RefName.IsEmpty) { SendValidationEvent(ResXml.Sch_ForbiddenAttribute, "ref", attribute); } if (attribute.DefaultValue != null && attribute.FixedValue != null) { SendValidationEvent(ResXml.Sch_DefaultFixedAttributes, attribute); } if (attribute.DefaultValue != null && attribute.Use != XmlSchemaUse.Optional && attribute.Use != XmlSchemaUse.None) { SendValidationEvent(ResXml.Sch_OptionalDefaultAttribute, attribute); } if (attribute.Name == _xmlns) { SendValidationEvent(ResXml.Sch_XmlNsAttribute, attribute); } if (attribute.SchemaType != null) { SetParent(attribute.SchemaType, attribute); if (!attribute.SchemaTypeName.IsEmpty) { SendValidationEvent(ResXml.Sch_TypeMutualExclusive, attribute); } PreprocessSimpleType(attribute.SchemaType, true); } if (!attribute.SchemaTypeName.IsEmpty) { ValidateQNameAttribute(attribute, "type", attribute.SchemaTypeName); } } private void PreprocessAttributeGroup(XmlSchemaAttributeGroup attributeGroup) { if (attributeGroup.Name != null) { ValidateNameAttribute(attributeGroup); attributeGroup.SetQualifiedName(new XmlQualifiedName(attributeGroup.Name, _targetNamespace)); } else { SendValidationEvent(ResXml.Sch_MissRequiredAttribute, "name", attributeGroup); } PreprocessAttributes(attributeGroup.Attributes, attributeGroup.AnyAttribute, attributeGroup); PreprocessAnnotation(attributeGroup); ValidateIdAttribute(attributeGroup); } private void PreprocessElement(XmlSchemaElement element) { if (element.Name != null) { ValidateNameAttribute(element); element.SetQualifiedName(new XmlQualifiedName(element.Name, _targetNamespace)); } else { SendValidationEvent(ResXml.Sch_MissRequiredAttribute, "name", element); } PreprocessElementContent(element); if (element.Final == XmlSchemaDerivationMethod.All) { element.SetFinalResolved(XmlSchemaDerivationMethod.All); } else if (element.Final == XmlSchemaDerivationMethod.None) { if (_finalDefault == XmlSchemaDerivationMethod.All) { element.SetFinalResolved(XmlSchemaDerivationMethod.All); } else { element.SetFinalResolved(_finalDefault & elementFinalAllowed); } } else { if ((element.Final & ~elementFinalAllowed) != 0) { SendValidationEvent(ResXml.Sch_InvalidElementFinalValue, element); } element.SetFinalResolved(element.Final & elementFinalAllowed); } if (element.Form != XmlSchemaForm.None) { SendValidationEvent(ResXml.Sch_ForbiddenAttribute, "form", element); } if (element.MinOccursString != null) { SendValidationEvent(ResXml.Sch_ForbiddenAttribute, "minOccurs", element); } if (element.MaxOccursString != null) { SendValidationEvent(ResXml.Sch_ForbiddenAttribute, "maxOccurs", element); } if (!element.SubstitutionGroup.IsEmpty) { ValidateQNameAttribute(element, "type", element.SubstitutionGroup); } ValidateIdAttribute(element); } private void PreprocessLocalElement(XmlSchemaElement element) { if (element.Name != null) { // name ValidateNameAttribute(element); PreprocessElementContent(element); element.SetQualifiedName(new XmlQualifiedName(element.Name, (element.Form == XmlSchemaForm.Qualified || (element.Form == XmlSchemaForm.None && _elementFormDefault == XmlSchemaForm.Qualified)) ? _targetNamespace : null)); } else { // ref PreprocessAnnotation(element); //Check annotation child for ref and set parent if (element.RefName.IsEmpty) { SendValidationEvent(ResXml.Sch_ElementNameRef, element); } else { ValidateQNameAttribute(element, "ref", element.RefName); } if (!element.SchemaTypeName.IsEmpty || element.IsAbstract || element.Block != XmlSchemaDerivationMethod.None || element.SchemaType != null || element.HasConstraints || element.DefaultValue != null || element.Form != XmlSchemaForm.None || element.FixedValue != null || element.HasNillableAttribute) { SendValidationEvent(ResXml.Sch_InvalidElementRef, element); } if (element.DefaultValue != null && element.FixedValue != null) { SendValidationEvent(ResXml.Sch_DefaultFixedAttributes, element); } element.SetQualifiedName(element.RefName); } if (element.MinOccurs > element.MaxOccurs) { element.MinOccurs = decimal.Zero; SendValidationEvent(ResXml.Sch_MinGtMax, element); } if (element.IsAbstract) { SendValidationEvent(ResXml.Sch_ForbiddenAttribute, "abstract", element); } if (element.Final != XmlSchemaDerivationMethod.None) { SendValidationEvent(ResXml.Sch_ForbiddenAttribute, "final", element); } if (!element.SubstitutionGroup.IsEmpty) { SendValidationEvent(ResXml.Sch_ForbiddenAttribute, "substitutionGroup", element); } ValidateIdAttribute(element); } private void PreprocessElementContent(XmlSchemaElement element) { PreprocessAnnotation(element); //Set parent for Annotation child of element if (!element.RefName.IsEmpty) { SendValidationEvent(ResXml.Sch_ForbiddenAttribute, "ref", element); } if (element.Block == XmlSchemaDerivationMethod.All) { element.SetBlockResolved(XmlSchemaDerivationMethod.All); } else if (element.Block == XmlSchemaDerivationMethod.None) { if (_blockDefault == XmlSchemaDerivationMethod.All) { element.SetBlockResolved(XmlSchemaDerivationMethod.All); } else { element.SetBlockResolved(_blockDefault & elementBlockAllowed); } } else { if ((element.Block & ~elementBlockAllowed) != 0) { SendValidationEvent(ResXml.Sch_InvalidElementBlockValue, element); } element.SetBlockResolved(element.Block & elementBlockAllowed); } if (element.SchemaType != null) { SetParent(element.SchemaType, element); //Set parent for simple / complex type child of element if (!element.SchemaTypeName.IsEmpty) { SendValidationEvent(ResXml.Sch_TypeMutualExclusive, element); } if (element.SchemaType is XmlSchemaComplexType) { PreprocessComplexType((XmlSchemaComplexType)element.SchemaType, true); } else { PreprocessSimpleType((XmlSchemaSimpleType)element.SchemaType, true); } } if (!element.SchemaTypeName.IsEmpty) { ValidateQNameAttribute(element, "type", element.SchemaTypeName); } if (element.DefaultValue != null && element.FixedValue != null) { SendValidationEvent(ResXml.Sch_DefaultFixedAttributes, element); } for (int i = 0; i < element.Constraints.Count; ++i) { SetParent(element.Constraints[i], element); PreprocessIdentityConstraint((XmlSchemaIdentityConstraint)element.Constraints[i]); } } private void PreprocessIdentityConstraint(XmlSchemaIdentityConstraint constraint) { bool valid = true; PreprocessAnnotation(constraint); //Set parent of annotation child of key/keyref/unique if (constraint.Name != null) { ValidateNameAttribute(constraint); constraint.SetQualifiedName(new XmlQualifiedName(constraint.Name, _targetNamespace)); } else { SendValidationEvent(ResXml.Sch_MissRequiredAttribute, "name", constraint); valid = false; } if (_schema.IdentityConstraints[constraint.QualifiedName] != null) { SendValidationEvent(ResXml.Sch_DupIdentityConstraint, constraint.QualifiedName.ToString(), constraint); valid = false; } else { _schema.IdentityConstraints.Add(constraint.QualifiedName, constraint); } if (constraint.Selector == null) { SendValidationEvent(ResXml.Sch_IdConstraintNoSelector, constraint); valid = false; } if (constraint.Fields.Count == 0) { SendValidationEvent(ResXml.Sch_IdConstraintNoFields, constraint); valid = false; } if (constraint is XmlSchemaKeyref) { XmlSchemaKeyref keyref = (XmlSchemaKeyref)constraint; if (keyref.Refer.IsEmpty) { SendValidationEvent(ResXml.Sch_IdConstraintNoRefer, constraint); valid = false; } else { ValidateQNameAttribute(keyref, "refer", keyref.Refer); } } if (valid) { ValidateIdAttribute(constraint); ValidateIdAttribute(constraint.Selector); SetParent(constraint.Selector, constraint); for (int i = 0; i < constraint.Fields.Count; ++i) { SetParent(constraint.Fields[i], constraint); ValidateIdAttribute(constraint.Fields[i]); } } } private void PreprocessSimpleType(XmlSchemaSimpleType simpleType, bool local) { if (local) { if (simpleType.Name != null) { SendValidationEvent(ResXml.Sch_ForbiddenAttribute, "name", simpleType); } } else { if (simpleType.Name != null) { ValidateNameAttribute(simpleType); simpleType.SetQualifiedName(new XmlQualifiedName(simpleType.Name, _targetNamespace)); } else { SendValidationEvent(ResXml.Sch_MissRequiredAttribute, "name", simpleType); } if (simpleType.Final == XmlSchemaDerivationMethod.All) { simpleType.SetFinalResolved(XmlSchemaDerivationMethod.All); } else if (simpleType.Final == XmlSchemaDerivationMethod.None) { if (_finalDefault == XmlSchemaDerivationMethod.All) { simpleType.SetFinalResolved(XmlSchemaDerivationMethod.All); } else { simpleType.SetFinalResolved(_finalDefault & simpleTypeFinalAllowed); } } else { if ((simpleType.Final & ~simpleTypeFinalAllowed) != 0) { SendValidationEvent(ResXml.Sch_InvalidSimpleTypeFinalValue, simpleType); } simpleType.SetFinalResolved(simpleType.Final & simpleTypeFinalAllowed); } } if (simpleType.Content == null) { SendValidationEvent(ResXml.Sch_NoSimpleTypeContent, simpleType); } else if (simpleType.Content is XmlSchemaSimpleTypeRestriction) { XmlSchemaSimpleTypeRestriction restriction = (XmlSchemaSimpleTypeRestriction)simpleType.Content; //SetParent SetParent(restriction, simpleType); for (int i = 0; i < restriction.Facets.Count; ++i) { SetParent(restriction.Facets[i], restriction); } if (restriction.BaseType != null) { if (!restriction.BaseTypeName.IsEmpty) { SendValidationEvent(ResXml.Sch_SimpleTypeRestRefBase, restriction); } PreprocessSimpleType(restriction.BaseType, true); } else { if (restriction.BaseTypeName.IsEmpty) { SendValidationEvent(ResXml.Sch_SimpleTypeRestRefBaseNone, restriction); } else { ValidateQNameAttribute(restriction, "base", restriction.BaseTypeName); } } PreprocessAnnotation(restriction); //set parent of annotation child of simple type restriction ValidateIdAttribute(restriction); } else if (simpleType.Content is XmlSchemaSimpleTypeList) { XmlSchemaSimpleTypeList list = (XmlSchemaSimpleTypeList)simpleType.Content; SetParent(list, simpleType); if (list.ItemType != null) { if (!list.ItemTypeName.IsEmpty) { SendValidationEvent(ResXml.Sch_SimpleTypeListRefBase, list); } SetParent(list.ItemType, list); PreprocessSimpleType(list.ItemType, true); } else { if (list.ItemTypeName.IsEmpty) { SendValidationEvent(ResXml.Sch_SimpleTypeListRefBaseNone, list); } else { ValidateQNameAttribute(list, "itemType", list.ItemTypeName); } } PreprocessAnnotation(list); //set parent of annotation child of simple type list ValidateIdAttribute(list); } else { // union XmlSchemaSimpleTypeUnion union1 = (XmlSchemaSimpleTypeUnion)simpleType.Content; SetParent(union1, simpleType); int baseTypeCount = union1.BaseTypes.Count; if (union1.MemberTypes != null) { baseTypeCount += union1.MemberTypes.Length; for (int i = 0; i < union1.MemberTypes.Length; ++i) { ValidateQNameAttribute(union1, "memberTypes", union1.MemberTypes[i]); } } if (baseTypeCount == 0) { SendValidationEvent(ResXml.Sch_SimpleTypeUnionNoBase, union1); } for (int i = 0; i < union1.BaseTypes.Count; ++i) { SetParent(union1.BaseTypes[i], union1); PreprocessSimpleType((XmlSchemaSimpleType)union1.BaseTypes[i], true); } PreprocessAnnotation(union1); //set parent of annotation child of simple type union ValidateIdAttribute(union1); } ValidateIdAttribute(simpleType); } private void PreprocessComplexType(XmlSchemaComplexType complexType, bool local) { if (local) { if (complexType.Name != null) { SendValidationEvent(ResXml.Sch_ForbiddenAttribute, "name", complexType); } } else { if (complexType.Name != null) { ValidateNameAttribute(complexType); complexType.SetQualifiedName(new XmlQualifiedName(complexType.Name, _targetNamespace)); } else { SendValidationEvent(ResXml.Sch_MissRequiredAttribute, "name", complexType); } if (complexType.Block == XmlSchemaDerivationMethod.All) { complexType.SetBlockResolved(XmlSchemaDerivationMethod.All); } else if (complexType.Block == XmlSchemaDerivationMethod.None) { complexType.SetBlockResolved(_blockDefault & complexTypeBlockAllowed); } else { if ((complexType.Block & ~complexTypeBlockAllowed) != 0) { SendValidationEvent(ResXml.Sch_InvalidComplexTypeBlockValue, complexType); } complexType.SetBlockResolved(complexType.Block & complexTypeBlockAllowed); } if (complexType.Final == XmlSchemaDerivationMethod.All) { complexType.SetFinalResolved(XmlSchemaDerivationMethod.All); } else if (complexType.Final == XmlSchemaDerivationMethod.None) { if (_finalDefault == XmlSchemaDerivationMethod.All) { complexType.SetFinalResolved(XmlSchemaDerivationMethod.All); } else { complexType.SetFinalResolved(_finalDefault & complexTypeFinalAllowed); } } else { if ((complexType.Final & ~complexTypeFinalAllowed) != 0) { SendValidationEvent(ResXml.Sch_InvalidComplexTypeFinalValue, complexType); } complexType.SetFinalResolved(complexType.Final & complexTypeFinalAllowed); } } if (complexType.ContentModel != null) { SetParent(complexType.ContentModel, complexType); //SimpleContent / complexCotent PreprocessAnnotation(complexType.ContentModel); if (complexType.Particle != null || complexType.Attributes != null) { // this is illigal } if (complexType.ContentModel is XmlSchemaSimpleContent) { XmlSchemaSimpleContent content = (XmlSchemaSimpleContent)complexType.ContentModel; if (content.Content == null) { if (complexType.QualifiedName == XmlQualifiedName.Empty) { SendValidationEvent(ResXml.Sch_NoRestOrExt, complexType); } else { SendValidationEvent(ResXml.Sch_NoRestOrExtQName, complexType.QualifiedName.Name, complexType.QualifiedName.Namespace, complexType); } } else { SetParent(content.Content, content); //simplecontent extension / restriction PreprocessAnnotation(content.Content); //annotation child of simple extension / restriction if (content.Content is XmlSchemaSimpleContentExtension) { XmlSchemaSimpleContentExtension contentExtension = (XmlSchemaSimpleContentExtension)content.Content; if (contentExtension.BaseTypeName.IsEmpty) { SendValidationEvent(ResXml.Sch_MissAttribute, "base", contentExtension); } else { ValidateQNameAttribute(contentExtension, "base", contentExtension.BaseTypeName); } PreprocessAttributes(contentExtension.Attributes, contentExtension.AnyAttribute, contentExtension); ValidateIdAttribute(contentExtension); } else { //XmlSchemaSimpleContentRestriction XmlSchemaSimpleContentRestriction contentRestriction = (XmlSchemaSimpleContentRestriction)content.Content; if (contentRestriction.BaseTypeName.IsEmpty) { SendValidationEvent(ResXml.Sch_MissAttribute, "base", contentRestriction); } else { ValidateQNameAttribute(contentRestriction, "base", contentRestriction.BaseTypeName); } if (contentRestriction.BaseType != null) { SetParent(contentRestriction.BaseType, contentRestriction); PreprocessSimpleType(contentRestriction.BaseType, true); } PreprocessAttributes(contentRestriction.Attributes, contentRestriction.AnyAttribute, contentRestriction); ValidateIdAttribute(contentRestriction); } } ValidateIdAttribute(content); } else { // XmlSchemaComplexContent XmlSchemaComplexContent content = (XmlSchemaComplexContent)complexType.ContentModel; if (content.Content == null) { if (complexType.QualifiedName == XmlQualifiedName.Empty) { SendValidationEvent(ResXml.Sch_NoRestOrExt, complexType); } else { SendValidationEvent(ResXml.Sch_NoRestOrExtQName, complexType.QualifiedName.Name, complexType.QualifiedName.Namespace, complexType); } } else { if (!content.HasMixedAttribute && complexType.IsMixed) { content.IsMixed = true; // fixup } SetParent(content.Content, content); //complexcontent extension / restriction PreprocessAnnotation(content.Content); //Annotation child of extension / restriction if (content.Content is XmlSchemaComplexContentExtension) { XmlSchemaComplexContentExtension contentExtension = (XmlSchemaComplexContentExtension)content.Content; if (contentExtension.BaseTypeName.IsEmpty) { SendValidationEvent(ResXml.Sch_MissAttribute, "base", contentExtension); } else { ValidateQNameAttribute(contentExtension, "base", contentExtension.BaseTypeName); } if (contentExtension.Particle != null) { SetParent(contentExtension.Particle, contentExtension); //Group / all / choice / sequence PreprocessParticle(contentExtension.Particle); } PreprocessAttributes(contentExtension.Attributes, contentExtension.AnyAttribute, contentExtension); ValidateIdAttribute(contentExtension); } else { // XmlSchemaComplexContentRestriction XmlSchemaComplexContentRestriction contentRestriction = (XmlSchemaComplexContentRestriction)content.Content; if (contentRestriction.BaseTypeName.IsEmpty) { SendValidationEvent(ResXml.Sch_MissAttribute, "base", contentRestriction); } else { ValidateQNameAttribute(contentRestriction, "base", contentRestriction.BaseTypeName); } if (contentRestriction.Particle != null) { SetParent(contentRestriction.Particle, contentRestriction); //Group / all / choice / sequence PreprocessParticle(contentRestriction.Particle); } PreprocessAttributes(contentRestriction.Attributes, contentRestriction.AnyAttribute, contentRestriction); ValidateIdAttribute(contentRestriction); } ValidateIdAttribute(content); } } } else { if (complexType.Particle != null) { SetParent(complexType.Particle, complexType); PreprocessParticle(complexType.Particle); } PreprocessAttributes(complexType.Attributes, complexType.AnyAttribute, complexType); } ValidateIdAttribute(complexType); } private void PreprocessGroup(XmlSchemaGroup group) { if (group.Name != null) { ValidateNameAttribute(group); group.SetQualifiedName(new XmlQualifiedName(group.Name, _targetNamespace)); } else { SendValidationEvent(ResXml.Sch_MissRequiredAttribute, "name", group); } if (group.Particle == null) { SendValidationEvent(ResXml.Sch_NoGroupParticle, group); return; } if (group.Particle.MinOccursString != null) { SendValidationEvent(ResXml.Sch_ForbiddenAttribute, "minOccurs", group.Particle); } if (group.Particle.MaxOccursString != null) { SendValidationEvent(ResXml.Sch_ForbiddenAttribute, "maxOccurs", group.Particle); } PreprocessParticle(group.Particle); PreprocessAnnotation(group); //Set parent of annotation child of group ValidateIdAttribute(group); } private void PreprocessNotation(XmlSchemaNotation notation) { if (notation.Name != null) { ValidateNameAttribute(notation); notation.QualifiedName = new XmlQualifiedName(notation.Name, _targetNamespace); } else { SendValidationEvent(ResXml.Sch_MissRequiredAttribute, "name", notation); } if (notation.Public != null) { try { XmlConvert.ToUri(notation.Public); // can throw } catch { SendValidationEvent(ResXml.Sch_InvalidPublicAttribute, notation.Public, notation); } } else { SendValidationEvent(ResXml.Sch_MissRequiredAttribute, "public", notation); } if (notation.System != null) { try { XmlConvert.ToUri(notation.System); // can throw } catch { SendValidationEvent(ResXml.Sch_InvalidSystemAttribute, notation.System, notation); } } PreprocessAnnotation(notation); //Set parent of annotation child of notation ValidateIdAttribute(notation); } private void PreprocessParticle(XmlSchemaParticle particle) { XmlSchemaAll schemaAll = particle as XmlSchemaAll; if (schemaAll != null) { if (particle.MinOccurs != decimal.Zero && particle.MinOccurs != decimal.One) { particle.MinOccurs = decimal.One; SendValidationEvent(ResXml.Sch_InvalidAllMin, particle); } if (particle.MaxOccurs != decimal.One) { particle.MaxOccurs = decimal.One; SendValidationEvent(ResXml.Sch_InvalidAllMax, particle); } for (int i = 0; i < schemaAll.Items.Count; ++i) { XmlSchemaElement element = (XmlSchemaElement)schemaAll.Items[i]; if (element.MaxOccurs != decimal.Zero && element.MaxOccurs != decimal.One) { element.MaxOccurs = decimal.One; SendValidationEvent(ResXml.Sch_InvalidAllElementMax, element); } SetParent(element, particle); PreprocessLocalElement(element); } } else { if (particle.MinOccurs > particle.MaxOccurs) { particle.MinOccurs = particle.MaxOccurs; SendValidationEvent(ResXml.Sch_MinGtMax, particle); } XmlSchemaChoice choice = particle as XmlSchemaChoice; if (choice != null) { XmlSchemaObjectCollection choices = choice.Items; for (int i = 0; i < choices.Count; ++i) { SetParent(choices[i], particle); XmlSchemaElement element = choices[i] as XmlSchemaElement; if (element != null) { PreprocessLocalElement(element); } else { PreprocessParticle((XmlSchemaParticle)choices[i]); } } } else if (particle is XmlSchemaSequence) { XmlSchemaObjectCollection sequences = ((XmlSchemaSequence)particle).Items; for (int i = 0; i < sequences.Count; ++i) { SetParent(sequences[i], particle); XmlSchemaElement element = sequences[i] as XmlSchemaElement; if (element != null) { PreprocessLocalElement(element); } else { PreprocessParticle((XmlSchemaParticle)sequences[i]); } } } else if (particle is XmlSchemaGroupRef) { XmlSchemaGroupRef groupRef = (XmlSchemaGroupRef)particle; if (groupRef.RefName.IsEmpty) { SendValidationEvent(ResXml.Sch_MissAttribute, "ref", groupRef); } else { ValidateQNameAttribute(groupRef, "ref", groupRef.RefName); } } else if (particle is XmlSchemaAny) { try { ((XmlSchemaAny)particle).BuildNamespaceListV1Compat(_targetNamespace); } catch { SendValidationEvent(ResXml.Sch_InvalidAny, particle); } } } PreprocessAnnotation(particle); //set parent of annotation child of group / all/ choice / sequence ValidateIdAttribute(particle); } private void PreprocessAttributes(XmlSchemaObjectCollection attributes, XmlSchemaAnyAttribute anyAttribute, XmlSchemaObject parent) { for (int i = 0; i < attributes.Count; ++i) { SetParent(attributes[i], parent); XmlSchemaAttribute attribute = attributes[i] as XmlSchemaAttribute; if (attribute != null) { PreprocessLocalAttribute(attribute); } else { // XmlSchemaAttributeGroupRef XmlSchemaAttributeGroupRef attributeGroupRef = (XmlSchemaAttributeGroupRef)attributes[i]; if (attributeGroupRef.RefName.IsEmpty) { SendValidationEvent(ResXml.Sch_MissAttribute, "ref", attributeGroupRef); } else { ValidateQNameAttribute(attributeGroupRef, "ref", attributeGroupRef.RefName); } PreprocessAnnotation(attributes[i]); //set parent of annotation child of attributeGroupRef ValidateIdAttribute(attributes[i]); } } if (anyAttribute != null) { try { SetParent(anyAttribute, parent); PreprocessAnnotation(anyAttribute); //set parent of annotation child of any attribute anyAttribute.BuildNamespaceListV1Compat(_targetNamespace); } catch { SendValidationEvent(ResXml.Sch_InvalidAnyAttribute, anyAttribute); } ValidateIdAttribute(anyAttribute); } } private void ValidateIdAttribute(XmlSchemaObject xso) { if (xso.IdAttribute != null) { try { xso.IdAttribute = NameTable.Add(XmlConvert.VerifyNCName(xso.IdAttribute)); if (_schema.Ids[xso.IdAttribute] != null) { SendValidationEvent(ResXml.Sch_DupIdAttribute, xso); } else { _schema.Ids.Add(xso.IdAttribute, xso); } } catch (Exception ex) { SendValidationEvent(ResXml.Sch_InvalidIdAttribute, ex.Message, xso); } } } private void ValidateNameAttribute(XmlSchemaObject xso) { string name = xso.NameAttribute; if (name == null || name.Length == 0) { SendValidationEvent(ResXml.Sch_InvalidNameAttributeEx, null, ResXml.Sch_NullValue, xso); } //Normalize whitespace since NCName has whitespace facet="collapse" name = XmlComplianceUtil.NonCDataNormalize(name); int len = ValidateNames.ParseNCName(name, 0); if (len != name.Length) { // If the string is not a valid NCName, then throw or return false string[] invCharArgs = XmlException.BuildCharExceptionArgs(name, len); string innerStr = string.Format(ResXml.Xml_BadNameCharWithPos, invCharArgs[0], invCharArgs[1], len); SendValidationEvent(ResXml.Sch_InvalidNameAttributeEx, name, innerStr, xso); } else { xso.NameAttribute = NameTable.Add(name); } } private void ValidateQNameAttribute(XmlSchemaObject xso, string attributeName, XmlQualifiedName value) { try { value.Verify(); value.Atomize(NameTable); if (_referenceNamespaces[value.Namespace] == null) { SendValidationEvent(ResXml.Sch_UnrefNS, value.Namespace, xso, XmlSeverityType.Warning); } } catch (Exception ex) { SendValidationEvent(ResXml.Sch_InvalidAttribute, attributeName, ex.Message, xso); } } private void SetParent(XmlSchemaObject child, XmlSchemaObject parent) { child.Parent = parent; } private void PreprocessAnnotation(XmlSchemaObject schemaObject) { XmlSchemaAnnotated annotated = schemaObject as XmlSchemaAnnotated; if (annotated != null) { if (annotated.Annotation != null) { annotated.Annotation.Parent = schemaObject; for (int i = 0; i < annotated.Annotation.Items.Count; ++i) { annotated.Annotation.Items[i].Parent = annotated.Annotation; //Can be documentation or appInfo } } } } // [ResourceConsumption(ResourceScope.Machine)] // [ResourceExposure(ResourceScope.Machine)] private Uri ResolveSchemaLocationUri(XmlSchema enclosingSchema, string location) { try { return _xmlResolver.ResolveUri(enclosingSchema.BaseUri, location); } catch { return null; } } private Stream GetSchemaEntity(Uri ruri) { try { return (Stream)_xmlResolver.GetEntity(ruri, null, null); } catch { return null; } } }; #pragma warning restore 618 } // namespace Microsoft.Xml
using System.Threading.Tasks; using OdooRpc.CoreCLR.Client.Models.Parameters; using OdooRpc.CoreCLR.Client.Internals; using JsonRpc.CoreCLR.Client.Models; using Xunit; using Newtonsoft.Json.Linq; using System; using OdooRpc.CoreCLR.Client.Tests.Helpers; using OdooRpc.CoreCLR.Client.Models; namespace OdooRpc.CoreCLR.Client.Tests { public partial class OdooRpcClientTests { [Fact] public async Task Get_WithIds_ShouldCallRpcWithCorrectParameters() { var requestParameters = new OdooGetParameters("res.partner", new long[] { 7 }); var testPartner = new TestPartner() { comment = false, country_id = new object[] { 21, "Belgium" }, id = 7, name = "Agrolait" }; var response = new JsonRpcResponse<TestPartner[]>(); response.Id = 1; response.Result = new TestPartner[] { testPartner }; await TestOdooRpcCall(new OdooRpcCallTestParameters<TestPartner[]>() { Validator = (p) => { Assert.Equal(6, p.args.Length); dynamic args = p.args[5]; Assert.Equal(1, args.Length); Assert.Equal(requestParameters.Ids, args[0]); }, Model = requestParameters.Model, Method = "read", ExecuteRpcCall = () => RpcClient.Get<TestPartner[]>(requestParameters), TestResponse = response }); } [Fact] public async Task Get_WithIds_And_WithFields_ShouldCallRpcWithCorrectParameters() { var requestParameters = new OdooGetParameters("res.partner", new long[] { 7 }); var testPartner = new TestPartner() { comment = false, country_id = new object[] { 21, "Belgium" }, id = 7, name = "Agrolait" }; var response = new JsonRpcResponse<TestPartner[]>(); response.Id = 1; response.Result = new TestPartner[] { testPartner }; await TestOdooRpcCall(new OdooRpcCallTestParameters<TestPartner[]>() { Validator = (p) => { Assert.Equal(7, p.args.Length); dynamic args = p.args[5]; Assert.Equal(1, args.Length); Assert.Equal(requestParameters.Ids, args[0]); dynamic fieldsArgs = p.args[6]; Assert.Equal(new string[] { "name", "country_id", "comment" }, fieldsArgs.fields); }, Model = requestParameters.Model, Method = "read", ExecuteRpcCall = () => { return RpcClient.Get<TestPartner[]>( requestParameters, new OdooFieldParameters(new string[] { "name", "country_id", "comment" }) ); }, TestResponse = response }); } [Fact] public async Task Get_WithSearch_ShouldCallRpcWithCorrectParameters() { var requestParameters = new OdooSearchParameters( "res.partner", new OdooDomainFilter() .Filter("is_company", "=", true) .Filter("customer", "=", true) ); var testPartners = new TestPartner[] { new TestPartner() { comment = false, country_id = new object[] { 21, "Belgium" }, id = 7, name = "Agrolait" }, new TestPartner() { comment = false, country_id = new object[] { 21, "Belgium" }, id = 8, name = "Parmalait" } }; var response = new JsonRpcResponse<TestPartner[]>(); response.Id = 1; response.Result = testPartners; await TestOdooRpcCall(new OdooRpcCallTestParameters<TestPartner[]>() { Validator = (p) => { Assert.Equal(6, p.args.Length); dynamic args = p.args[5]; Assert.Equal(2, args[0].Length); Assert.Equal( new object[] { new object[] { "is_company", "=", true }, new object[] { "customer", "=", true } }, args[0] ); }, Model = requestParameters.Model, Method = "search_read", ExecuteRpcCall = () => RpcClient.Get<TestPartner[]>(requestParameters), TestResponse = response }); } [Fact] public async Task Get_WithSearch_And_Pagination_ShouldCallRpcWithCorrectParameters() { var requestParameters = new OdooSearchParameters( "res.partner", new OdooDomainFilter() .Filter("is_company", "=", true) .Filter("customer", "=", true) ); var testPartners = new TestPartner[] { new TestPartner() { comment = false, country_id = new object[] { 21, "Belgium" }, id = 7, name = "Agrolait" }, new TestPartner() { comment = false, country_id = new object[] { 21, "Belgium" }, id = 8, name = "Parmalait" } }; var response = new JsonRpcResponse<TestPartner[]>(); response.Id = 1; response.Result = testPartners; await TestOdooRpcCall(new OdooRpcCallTestParameters<TestPartner[]>() { Validator = (p) => { Assert.Equal(7, p.args.Length); dynamic args = p.args[5]; Assert.Equal(2, args[0].Length); Assert.Equal( new object[] { new object[] { "is_company", "=", true }, new object[] { "customer", "=", true } }, args[0] ); dynamic pagArgs = p.args[6]; Assert.Equal(0, pagArgs.offset); Assert.Equal(5, pagArgs.limit); }, Model = requestParameters.Model, Method = "search_read", ExecuteRpcCall = () => RpcClient.Get<TestPartner[]>(requestParameters, new OdooPaginationParameters(0, 5)), TestResponse = response }); } [Fact] public async Task Get_WithSearch_And_Fields_And_Pagination_ShouldCallRpcWithCorrectParameters() { var requestParameters = new OdooSearchParameters( "res.partner", new OdooDomainFilter() .Filter("is_company", "=", true) .Filter("customer", "=", true) ); var testPartners = new TestPartner[] { new TestPartner() { comment = false, country_id = new object[] { 21, "Belgium" }, id = 7, name = "Agrolait" }, new TestPartner() { comment = false, country_id = new object[] { 21, "Belgium" }, id = 8, name = "Parmalait" } }; var response = new JsonRpcResponse<TestPartner[]>(); response.Id = 1; response.Result = testPartners; await TestOdooRpcCall(new OdooRpcCallTestParameters<TestPartner[]>() { Validator = (p) => { Assert.Equal(7, p.args.Length); dynamic args = p.args[5]; Assert.Equal(2, args[0].Length); Assert.Equal( new object[] { new object[] { "is_company", "=", true }, new object[] { "customer", "=", true } }, args[0] ); dynamic searchArgs = p.args[6]; Assert.Equal(0, searchArgs.offset); Assert.Equal(5, searchArgs.limit); Assert.Equal(new string[] { "name", "country_id", "comment" }, searchArgs.fields); }, Model = requestParameters.Model, Method = "search_read", ExecuteRpcCall = () => RpcClient.Get<TestPartner[]>(requestParameters, new OdooFieldParameters(new string[] { "name", "country_id", "comment" }), new OdooPaginationParameters(0, 5)), TestResponse = response }); } } }
// Author: abi // Project: DungeonQuest // Path: C:\code\Xna\DungeonQuest\Graphics // Creation date: 28.03.2007 01:01 // Last modified: 31.07.2007 04:40 #region Using directives using DungeonQuest.Game; using DungeonQuest.GameLogic; using DungeonQuest.Helpers; using DungeonQuest.Shaders; using DungeonQuest.Sounds; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml; #endregion namespace DungeonQuest.Graphics { /// <summary> /// Collada model. Supports bones and animation for collada (.dae) exported /// 3D Models from 3D Studio Max (8 or 9). /// This class is just for testing and it will only display one single mesh /// with bone and skinning support, the mesh also can only have one single /// material. Bones can be either in matrix mode or stored with transform /// and rotation values. TangentVertex is used to store the vertices, /// use derived classes for different formats. /// </summary> public class ColladaModel : IDisposable { #region Constants /// <summary> /// Default Extension for Collada files exported with 3ds max. /// </summary> public const string ColladaDirectory = "Content\\Models", ColladaExtension = "DAE"; #endregion #region Variables /// <summary> /// Name of this model /// </summary> protected internal string name; /// <summary> /// Material for the main mesh. Only one material is supported! /// </summary> internal Material material = null; /// <summary> /// Vertices for the main mesh (we only support one mesh here!). /// </summary> private List<TangentVertex> vertices = new List<TangentVertex>(); /// <summary> /// Number of vertices and number of indices we got in the /// vertex and index buffers. /// </summary> protected int numOfVertices = 0, numOfIndices = 0; /// <summary> /// Object matrix for our mesh. Often used to fix mesh to bone skeleton. /// </summary> protected Matrix objectMatrix = Matrix.Identity; /// <summary> /// Vertex buffer for the mesh. /// </summary> protected VertexBuffer vertexBuffer = null; /// <summary> /// Index buffer for the mesh. /// </summary> protected IndexBuffer indexBuffer = null; /// <summary> /// Helper to quickly check if this is the cave. /// </summary> bool isCave = false; #endregion #region Properties /// <summary> /// Get model name, currently just the filename without path and extension /// </summary> public string Name { get { return name; } // get } // name /// <summary> /// Was the model loaded successfully? /// </summary> public bool Loaded { get { return vertexBuffer != null && indexBuffer != null; } // get } // Loaded #endregion #region Constructor /// <summary> /// Empty constructor to allow deriving from this class. /// </summary> protected ColladaModel() { } // ColladaModel() /// <summary> /// Create a model from a collada file /// </summary> /// <param name="setName">Set name</param> public ColladaModel(string setName) { // Set name to identify this model and build the filename name = setName; string filename = Path.Combine(ColladaDirectory, StringHelper.ExtractFilename(name, true) + "." + ColladaExtension); // Load file Stream file = File.OpenRead(filename); string colladaXml = new StreamReader(file).ReadToEnd(); XmlNode colladaFile = XmlHelper.LoadXmlFromText(colladaXml); isCave = name == "Cave"; // Load material (we only support one) //Not used, always autoassign: LoadMaterial(colladaFile); AutoAssignMaterial(); // Load mesh (vertices data, combine with bone weights) LoadMesh(colladaFile); // If this is our level (the cave), load all lights and give them // to the LightManager. if (name == "Cave") { LightManager.allLights = LoadAllLights(colladaFile); // Find 6 closest lights, just in case we are in some unit test // that does not do this by itself. LightManager.FindClosestLights(BaseGame.CameraPos); // Also load all helpers (also build flares from light positions) LoadAllHelpers(colladaFile, LightManager.allLights); } // if (name) // Close file, we are done. file.Close(); } // ColladaModel(setFilename) #endregion #region Dispose /// <summary> /// Dispose stuff that need to be disposed in XNA. /// </summary> public void Dispose() { if (vertexBuffer != null) vertexBuffer.Dispose(); vertexBuffer = null; if (indexBuffer != null) indexBuffer.Dispose(); indexBuffer = null; } // Dispose() #endregion #region Load collada matrix helper method /// <summary> /// Create matrix from collada float value array. The matrices in collada /// are stored differently from the xna format (row based instead of /// columns). /// </summary> /// <param name="mat">mat</param> /// <returns>Matrix</returns> protected Matrix LoadColladaMatrix(float[] mat, int offset) { return new Matrix( mat[offset + 0], mat[offset + 4], mat[offset + 8], mat[offset + 12], mat[offset + 1], mat[offset + 5], mat[offset + 9], mat[offset + 13], mat[offset + 2], mat[offset + 6], mat[offset + 10], mat[offset + 14], mat[offset + 3], mat[offset + 7], mat[offset + 11], mat[offset + 15]); } // LoadColladaMatrix(mat, offset) /// <summary> /// Only scale transformation down to globalScaling, left rest of /// the matrix intact. This is required for rendering because all the /// models have their own scaling! /// </summary> /// <param name="mat">Matrix</param> /// <returns>Matrix</returns> protected Matrix OnlyScaleTransformation(Matrix mat) { mat.Translation = mat.Translation * globalScaling; return mat; } // OnlyScaleTransformation(mat) /// <summary> /// Only scale transformation inverse /// </summary> /// <param name="mat">Matrix</param> /// <returns>Matrix</returns> protected Matrix OnlyScaleTransformationInverse(Matrix mat) { mat.Translation = mat.Translation / globalScaling; return mat; } // OnlyScaleTransformationInverse(mat) #endregion #region Load material /*not used anymore, works fine, but we had problems at the GDC exporting * shader material data in 3DS Max 9 (always crashes the exporter). * Instead the AutoAssignMaterial method below is used. /// <summary> /// Load material information from a collada file /// </summary> /// <param name="colladaFile">Collada file xml node</param> private void LoadMaterial(XmlNode colladaFile) { // First get all textures, if there are none, ignore and quit. XmlNode texturesNode = XmlHelper.GetChildNode(colladaFile, "library_images"); if (texturesNode == null) return; // Get all used texture images Dictionary<string, Texture> textures = new Dictionary<string, Texture>(); foreach (XmlNode textureNode in texturesNode) { if (textureNode.Name == "image") { string filename = XmlHelper.GetChildNode(textureNode, "init_from").InnerText; textures.Add( XmlHelper.GetXmlAttribute(textureNode, "id"), new Texture(StringHelper.ExtractFilename(filename, true))); } // if (texture.name) else throw new InvalidOperationException( "Unknown Node " + textureNode.Name + " found in library_images"); } // foreach (texture) // Load all effects to find out the used effect in our material XmlNode effectsNode = XmlHelper.GetChildNode(colladaFile, "library_effects"); if (effectsNode == null) throw new InvalidOperationException( "library_effects node not found while loading Collada file " +name); Dictionary<string, string> effectIds = new Dictionary<string, string>(); foreach (XmlNode effectNode in effectsNode) { XmlNode fileNode = XmlHelper.GetChildNode(effectNode, "import"); if (fileNode == null) { // Use "include" node instead, this one is used when we got valid // techniques selected in the material (was sometimes used collada // 1.4 and different versions of collada exporters than ColladaMax). fileNode = XmlHelper.GetChildNode(effectNode, "include"); // Still null? if (fileNode == null) throw new InvalidOperationException( "Import or include node not found in effect node, file: " +name); } // if (filenode) effectIds.Add( XmlHelper.GetXmlAttribute(effectNode, "id"), XmlHelper.GetXmlAttribute(fileNode, "url")); } // foreach (effect) // And finally get all material nodes, but we only support one material // here, we will use the first one that uses shaders and ignore the rest. XmlNode materialsNode = XmlHelper.GetChildNode(colladaFile, "library_materials"); if (materialsNode == null) throw new InvalidOperationException( "library_materials node not found while loading Collada file "+name); foreach (XmlNode materialNode in materialsNode) { if (materialNode.Name == "material") { Material newMaterial = new Material(materialNode, textures, effectIds); if (material == null || newMaterial.shader != null) material = newMaterial; } // if (materialNode.name) else throw new InvalidOperationException("Unknown Node " + materialNode.Name + " found in library_materials"); } // foreach (material) } // LoadMaterial(colladaFile, TextureIDDictionary, MaterialIDDictionary)' */ /// <summary> /// Auto assign material /// </summary> protected void AutoAssignMaterial() { // Just load the material from the name of this model material = new Material( name, name + "Normal", name + "Specular"); // Custom material stuff for Cave (detail maps and different shader) // is handled in the CavePointNormalMapping class. // But make sure to use black for ambient, very bright yellow for // diffuse and white for specular. if (isCave) { material.ambientColor = Color.Black; material.diffuseColor = new Color(255, 255, 240); material.specularColor = Color.White; material.specularPower = 22; } // if (name) else if (name.Contains("Goblin") || name.Contains("Orge")) { // Use a higher specular for the monsters. material.specularPower = 16; material.specularColor = new Color(180, 180, 180); // Increase ambient a little (better visibility of monsters) material.ambientColor = new Color(80, 80, 80); } // else if } // AutoAssignMaterial() #endregion #region Load mesh /// <summary> /// Load mesh, must be called after we got all bones. Will also create /// the vertex and index buffers and optimize the vertices as much as /// we can. /// </summary> /// <param name="colladaFile">Collada file</param> private void LoadMesh(XmlNode colladaFile) { XmlNode geometrys = XmlHelper.GetChildNode(colladaFile, "library_geometries"); if (geometrys == null) throw new InvalidOperationException( "library_geometries node not found in collada file " + name); foreach (XmlNode geometry in geometrys) if (geometry.Name == "geometry") { // Load everything from the mesh node LoadMeshGeometry(colladaFile, XmlHelper.GetChildNode(colladaFile, "mesh"), XmlHelper.GetXmlAttribute(geometry, "name")); // Generate vertex buffer for rendering GenerateVertexAndIndexBuffers(); // Get outa here, we currently only support one single mesh! return; } // foreach if (geometry.name) } // LoadMesh(colladaFile) /// <summary> /// Helpers to remember how we can reuse vertices for OptimizeVertexBuffer. /// See below for more details. /// </summary> int[] reuseVertexPositions; /// <summary> /// Reverse reuse vertex positions, this one is even more important because /// this way we can get a list of used vertices for a shared vertex pos. /// </summary> List<int>[] reverseReuseVertexPositions; /// <summary> /// Global scaling we get for importing the mesh and all positions. /// This is important because 3DS max might use different units than we are. /// </summary> protected float globalScaling = 1.0f; /// <summary> /// Load mesh geometry /// </summary> /// <param name="geometry"></param> private void LoadMeshGeometry(XmlNode colladaFile, XmlNode meshNode, string meshName) { #region Load all source nodes Dictionary<string, List<float>> sources = new Dictionary<string, List<float>>(); foreach (XmlNode node in meshNode) { if (node.Name != "source") continue; XmlNode floatArray = XmlHelper.GetChildNode(node, "float_array"); List<float> floats = new List<float>( StringHelper.ConvertStringToFloatArray(floatArray.InnerText)); // Fill the array up int count = Convert.ToInt32(XmlHelper.GetXmlAttribute(floatArray, "count"), NumberFormatInfo.InvariantInfo); while (floats.Count < count) floats.Add(0.0f); sources.Add(XmlHelper.GetXmlAttribute(node, "id"), floats); } // foreach #endregion #region Vertices // Also add vertices node, redirected to position node into sources XmlNode verticesNode = XmlHelper.GetChildNode(meshNode, "vertices"); XmlNode posInput = XmlHelper.GetChildNode(verticesNode, "input"); if (XmlHelper.GetXmlAttribute(posInput, "semantic").ToLower( CultureInfo.InvariantCulture) != "position") throw new InvalidOperationException( "unsupported feature found in collada \"vertices\" node"); string verticesValueName = XmlHelper.GetXmlAttribute(posInput, "source").Substring(1); sources.Add(XmlHelper.GetXmlAttribute(verticesNode, "id"), sources[verticesValueName]); #endregion #region Get the global scaling from the exported units to meters! XmlNode unitNode = XmlHelper.GetChildNode( XmlHelper.GetChildNode(colladaFile, "asset"), "unit"); globalScaling = Convert.ToSingle( XmlHelper.GetXmlAttribute(unitNode, "meter"), NumberFormatInfo.InvariantInfo); #endregion #region Get the object matrix (its in the visual_scene node at the end) XmlNode sceneStuff = XmlHelper.GetChildNode( XmlHelper.GetChildNode(colladaFile, "library_visual_scenes"), "visual_scene"); if (sceneStuff == null) throw new InvalidOperationException( "library_visual_scenes node not found in collada file " + name); // Search for the node with the name of this geometry. foreach (XmlNode node in sceneStuff) if (node.Name == "node" && XmlHelper.GetXmlAttribute(node, "name") == meshName && XmlHelper.GetChildNode(node, "matrix") != null) { // Get the object matrix objectMatrix = LoadColladaMatrix( StringHelper.ConvertStringToFloatArray( XmlHelper.GetChildNode(node, "matrix").InnerText), 0) * Matrix.CreateScale(globalScaling); break; } // foreach if (node.Name) #endregion #region Construct all triangle polygons from the vertex data // Construct and generate vertices lists. Every 3 vertices will // span one triangle polygon, but everything is optimized later. foreach (XmlNode trianglenode in meshNode) { if (trianglenode.Name != "triangles") continue; // Find data source nodes XmlNode positionsnode = XmlHelper.GetChildNode(trianglenode, "semantic", "VERTEX"); XmlNode normalsnode = XmlHelper.GetChildNode(trianglenode, "semantic", "NORMAL"); XmlNode texcoordsnode = XmlHelper.GetChildNode(trianglenode, "semantic", "TEXCOORD"); XmlNode tangentsnode = XmlHelper.GetChildNode(trianglenode, "semantic", "TEXTANGENT"); // Get the data of the sources List<float> positions = sources[XmlHelper.GetXmlAttribute( positionsnode, "source").Substring(1)]; List<float> normals = sources[XmlHelper.GetXmlAttribute(normalsnode, "source").Substring(1)]; List<float> texcoords = sources[XmlHelper.GetXmlAttribute( texcoordsnode, "source").Substring(1)]; List<float> tangents = sources[XmlHelper.GetXmlAttribute(tangentsnode, "source").Substring(1)]; // Find the Offsets int positionsoffset = Convert.ToInt32(XmlHelper.GetXmlAttribute( positionsnode, "offset"), NumberFormatInfo.InvariantInfo); int normalsoffset = Convert.ToInt32(XmlHelper.GetXmlAttribute( normalsnode, "offset"), NumberFormatInfo.InvariantInfo); int texcoordsoffset = Convert.ToInt32(XmlHelper.GetXmlAttribute( texcoordsnode, "offset"), NumberFormatInfo.InvariantInfo); int tangentsoffset = Convert.ToInt32(XmlHelper.GetXmlAttribute( tangentsnode, "offset"), NumberFormatInfo.InvariantInfo); // Get the indexlist XmlNode p = XmlHelper.GetChildNode(trianglenode, "p"); int[] pints = StringHelper.ConvertStringToIntArray(p.InnerText); int trianglecount = Convert.ToInt32(XmlHelper.GetXmlAttribute( trianglenode, "count"), NumberFormatInfo.InvariantInfo); // The number of ints that form one vertex: int vertexcomponentcount = pints.Length / trianglecount / 3; // Construct data vertices.Clear(); // Initialize reuseVertexPositions and reverseReuseVertexPositions // to make it easier to use them below reuseVertexPositions = new int[trianglecount * 3]; reverseReuseVertexPositions = new List<int>[positions.Count / 3]; for (int i = 0; i < reverseReuseVertexPositions.Length; i++) reverseReuseVertexPositions[i] = new List<int>(); // We have to use int indices here because we often have models // with more than 64k triangles (even if that gets optimized later). for (int i = 0; i < trianglecount * 3; i++) { // Position int pos = pints[i * vertexcomponentcount + positionsoffset] * 3; Vector3 position = new Vector3( positions[pos], positions[pos + 1], positions[pos + 2]); // For the cave mesh we are not going to use a world matrix, // Just scale everything correctly right here! if (isCave) position *= globalScaling; // Normal int nor = pints[i * vertexcomponentcount + normalsoffset] * 3; Vector3 normal = new Vector3( normals[nor], normals[nor + 1], normals[nor + 2]); // Texture Coordinates int tex = pints[i * vertexcomponentcount + texcoordsoffset] * 3; float u = texcoords[tex]; // V coordinate is inverted in max float v = 1.0f - texcoords[tex + 1]; // Tangent int tan = pints[i * vertexcomponentcount + tangentsoffset] * 3; Vector3 tangent = new Vector3( tangents[tan], tangents[tan + 1], tangents[tan + 2]); // Set the vertex vertices.Add(new TangentVertex( position, u, v, normal, tangent)); // Remember pos for optimizing the vertices later more easily. reuseVertexPositions[i] = pos / 3; reverseReuseVertexPositions[pos / 3].Add(i); } // for (int) // Only support one mesh for now, get outta here. return; } // foreach (trianglenode) throw new InvalidOperationException( "No mesh found in this collada file, unable to continue!"); #endregion } // LoadMeshGeometry(geometry) #endregion #region LoadAllLights /// <summary> /// Load all lights /// </summary> /// <param name="colladaFile">Collada file</param> private List<Matrix> LoadAllLights(XmlNode colladaFile) { XmlNode sceneStuff = XmlHelper.GetChildNode( XmlHelper.GetChildNode(colladaFile, "library_visual_scenes"), "visual_scene"); if (sceneStuff == null) throw new InvalidOperationException( "library_visual_scenes node not found in collada file " + name); List<Matrix> ret = new List<Matrix>(); foreach (XmlNode node in sceneStuff) // Search for "Omni" nodes, this are the lights from 3DS Max. if (node.Name == "node" && XmlHelper.GetXmlAttribute(node, "name").Contains("Omni")) { // Get the matrix for this light, we need it for the flares. ret.Add(OnlyScaleTransformation(LoadColladaMatrix( StringHelper.ConvertStringToFloatArray( XmlHelper.GetChildNode(node, "matrix").InnerText), 0))); } // foreach if (geometry.name) return ret; } // LoadAllLights(colladaFile) #endregion #region LoadAllHelpers /// <summary> /// Load all helpers /// </summary> /// <param name="colladaFile">Collada file</param> private void LoadAllHelpers(XmlNode colladaFile, List<Matrix> lightMatrices) { XmlNode sceneStuff = XmlHelper.GetChildNode( XmlHelper.GetChildNode(colladaFile, "library_visual_scenes"), "visual_scene"); if (sceneStuff == null) throw new InvalidOperationException( "library_visual_scenes node not found in collada file " + name); // Add all flares automatically from the light positions. foreach (Matrix mat in lightMatrices) { GameManager.Add(GameManager.StaticTypes.Flare, mat); } // foreach (mat) foreach (XmlNode node in sceneStuff) // Search for all nodes, we check for helpers with the names if (node.Name == "node") { string nodeName = XmlHelper.GetXmlAttribute(node, "name").ToLower(); Matrix positionMatrix = Matrix.Identity; if (XmlHelper.GetChildNode(node, "matrix") != null) positionMatrix = OnlyScaleTransformation(LoadColladaMatrix( StringHelper.ConvertStringToFloatArray( XmlHelper.GetChildNode(node, "matrix").InnerText), 0)); if (nodeName.Contains("door")) { GameManager.doorPosition = positionMatrix.Translation; GameManager.Add(GameManager.StaticTypes.Door, positionMatrix); GameManager.Add(GameManager.StaticTypes.DoorWall, positionMatrix); } // if (nodeName.Contains) else if (nodeName.Contains("key")) // Actually place a monster here that got the key (randomly) GameManager.Add(GameManager.AnimatedTypes.Ogre, positionMatrix, // Give the key to the orge (overwrite the weapon if he would // drop one). AnimatedGameObject.DropObject.Key); //obs: GameManager.Add(GameManager.StaticTypes.Key, positionMatrix); else if (nodeName.Contains("treasure")) { // Move down a little (fix error with CaveCollision) positionMatrix = positionMatrix * Matrix.CreateTranslation(new Vector3(0, 0, -1)); GameManager.treasurePosition = positionMatrix.Translation; GameManager.Add(GameManager.StaticTypes.Treasure, positionMatrix); } // else if else if (nodeName.Contains("bigogre")) GameManager.Add(GameManager.AnimatedTypes.BigOgre, positionMatrix); else if (nodeName.Contains("ogre")) GameManager.Add(GameManager.AnimatedTypes.Ogre, positionMatrix); else if (nodeName.Contains("goblinwizard")) GameManager.Add(GameManager.AnimatedTypes.GoblinWizard, positionMatrix); else if (nodeName.Contains("goblinmaster")) GameManager.Add(GameManager.AnimatedTypes.GoblinMaster, positionMatrix); else if (nodeName.Contains("goblin")) GameManager.Add(GameManager.AnimatedTypes.Goblin, positionMatrix); } // foreach if (geometry.name) } // LoadAllLights(colladaFile) #endregion #region Optimize vertex buffer #region Flip index order /// <summary> /// Little helper method to flip indices from 0, 1, 2 to 0, 2, 1. /// This way we can render with CullClockwiseFace (default for XNA). /// </summary> /// <param name="oldIndex"></param> /// <returns></returns> private int FlipIndexOrder(int oldIndex) { int polygonIndex = oldIndex % 3; if (polygonIndex == 0) return oldIndex; else if (polygonIndex == 1) return oldIndex + 1; else //if (polygonIndex == 2) return oldIndex - 1; } // FlipIndexOrder(oldIndex) #endregion #region OptimizeVertexBuffer /// <summary> /// Optimize vertex buffer. Note: The vertices list array will be changed /// and shorted quite a lot here. We are also going to create the indices /// for the index buffer here (we don't have them yet, they are just /// sequential from the loading process above). /// /// Note: This method is highly optimized for speed, it performs /// hundred of times faster than OptimizeVertexBufferSlow, see below! /// </summary> /// <returns>int array for the optimized indices</returns> private int[] OptimizeVertexBuffer() { List<TangentVertex> newVertices = new List<TangentVertex>(); List<int> newIndices = new List<int>(); // Helper to only search already added newVertices and for checking the // old position indices by transforming them into newVertices indices. List<int> newVerticesPositions = new List<int>(); // Go over all vertices (indices are currently 1:1 with the vertices) for (int num = 0; num < vertices.Count; num++) { // Get current vertex TangentVertex currentVertex = vertices[num]; bool reusedExistingVertex = false; // Find out which position index was used, then we can compare // all other vertices that share this position. They will not // all be equal, but some of them can be merged. int sharedPos = reuseVertexPositions[num]; foreach (int otherVertexIndex in reverseReuseVertexPositions[sharedPos]) { // Only check the indices that have already been added! if (otherVertexIndex != num && // Make sure we already are that far in our new index list otherVertexIndex < newIndices.Count && // And make sure this index has been added to newVertices yet! newIndices[otherVertexIndex] < newVertices.Count && // Then finally compare vertices (this call is slow, but thanks to // all the other optimizations we don't have to call it that often) TangentVertex.NearlyEquals( currentVertex, newVertices[newIndices[otherVertexIndex]])) { // Reuse the existing vertex, don't add it again, just // add another index for it! newIndices.Add(newIndices[otherVertexIndex]); reusedExistingVertex = true; break; } // if (TangentVertex.NearlyEquals) } // foreach (otherVertexIndex) if (reusedExistingVertex == false) { // Add the currentVertex and set it as the current index newIndices.Add(newVertices.Count); newVertices.Add(currentVertex); } // if (reusedExistingVertex) } // for (num) // Finally flip order of all triangles to allow us rendering // with CullCounterClockwiseFace (default for XNA) because all the data // is in CullClockwiseFace format right now! for (int num = 0; num < newIndices.Count / 3; num++) { int swap = newIndices[num * 3 + 1]; newIndices[num * 3 + 1] = newIndices[num * 3 + 2]; newIndices[num * 3 + 2] = swap; } // for // Reassign the vertices, we might have deleted some duplicates! vertices = newVertices; // And return index list for the caller return newIndices.ToArray(); } // OptimizeVertexBuffer() #endregion #region OptimizeVertexBufferSlow /// <summary> /// Optimize vertex buffer. Note: The vertices list array will be changed /// and shorted quite a lot here. We are also going to create the indices /// for the index buffer here (we don't have them yet, they are just /// sequential from the loading process above). /// /// Note: Slow version because we have to check each vertex against /// each other vertex, which makes this method exponentially slower /// the more vertices we have. Takes 10 seconds for 30k vertices, /// and over 40 seconds for 60k vertices. It is much easier to understand, /// but it produces the same output as the fast OptimizeVertexBuffer /// method and you should always use that one (it only requires a couple /// of miliseconds instead of the many seconds this method will spend). /// </summary> /// <returns>int array for the optimized indices</returns> private int[] OptimizeVertexBufferSlow() { List<TangentVertex> newVertices = new List<TangentVertex>(); List<int> newIndices = new List<int>(); // Go over all vertices (indices are currently 1:1 with the vertices) for (int num = 0; num < vertices.Count; num++) { // Try to find already existing vertex in newVertices list that // matches the vertex of the current index. TangentVertex currentVertex = vertices[FlipIndexOrder(num)]; bool reusedExistingVertex = false; for (int checkNum = 0; checkNum < newVertices.Count; checkNum++) { if (TangentVertex.NearlyEquals( currentVertex, newVertices[checkNum])) { // Reuse the existing vertex, don't add it again, just // add another index for it! newIndices.Add(checkNum); reusedExistingVertex = true; break; } // if (TangentVertex.NearlyEquals) } // for (checkNum) if (reusedExistingVertex == false) { // Add the currentVertex and set it as the current index newIndices.Add(newVertices.Count); newVertices.Add(currentVertex); } // if (reusedExistingVertex) } // for (num) // Reassign the vertices, we might have deleted some duplicates! vertices = newVertices; // And return index list for the caller return newIndices.ToArray(); } // OptimizeVertexBufferSlow() #endregion #endregion #region Generate vertex and index buffers /// <summary> /// Generate vertex and index buffers /// </summary> private void GenerateVertexAndIndexBuffers() { // Optimize vertices first and build index buffer from that! int[] indices = OptimizeVertexBuffer(); // For testing, this one is REALLY slow (see method summary)! //int[] indices = OptimizeVertexBufferSlow(); // Create the vertex buffer from our vertices. vertexBuffer = new VertexBuffer( BaseGame.Device, typeof(TangentVertex), vertices.Count, BufferUsage.WriteOnly); vertexBuffer.SetData(vertices.ToArray()); numOfVertices = vertices.Count; // Create the index buffer from our indices. // To fully support the complex cave (200,000+ polys) we are using // int values here. indexBuffer = new IndexBuffer( BaseGame.Device, typeof(int), indices.Length, BufferUsage.WriteOnly); indexBuffer.SetData(indices); numOfIndices = indices.Length; } // GenerateVertexAndIndexBuffers() #endregion #region Render /// <summary> /// Render the animated model (will call UpdateAnimation internally, /// but if you do that yourself before calling this method, it gets /// optimized out). Rendering always uses the skinnedNormalMapping shader /// with the DiffuseSpecular30 technique. /// </summary> /// <param name="renderMatrix">Render matrix</param> public virtual void Render(Matrix renderMatrix) { // Make sure we use the correct vertex declaration for our shader. BaseGame.Device.VertexDeclaration = TangentVertex.VertexDeclaration; // Set the world matrix for this object (often Identity). // The renderMatrix is directly applied to the matrices we use // as bone matrices for the shader (has to be done this way because // the bone matrices are transmitted transposed and we could lose // important render matrix translation data if we do not apply it there). BaseGame.WorldMatrix = objectMatrix * renderMatrix; // Rendering is pretty straight forward (if you know how anyway). // For the cave we are going to use the CavePointNormalMapping shader. if (isCave) { ShaderEffect.caveMapping.RenderCave( material, //auto: LightManager.closestLightsForRendering, RenderVertices); } // if (name) else { // Just render with normal mapping //TODO: use lights here too! ShaderEffect.normalMapping.RenderSinglePassShader( //ShaderEffect.caveMapping.Render( material, //material, //auto: LightManager.closestLightsForRendering, RenderVertices); } // else } // Render(renderMatrix) /// <summary> /// Render vertices /// </summary> private void RenderVertices() { BaseGame.Device.Vertices[0].SetSource(vertexBuffer, 0, TangentVertex.SizeInBytes); BaseGame.Device.Indices = indexBuffer; BaseGame.Device.DrawIndexedPrimitives( PrimitiveType.TriangleList, 0, 0, numOfVertices, 0, numOfIndices / 3); } // RenderVertices() #endregion #region Generate shadow /// <summary> /// Generate shadow for this model in the generate shadow pass of our /// shadow mapping shader. All objects rendered here will cast shadows to /// our scene (if they are in range of the light). /// </summary> /// <param name="renderMatrix">Render matrix</param> public virtual void GenerateShadow(Matrix renderMatrix) { // Set bone matrices and the world matrix for the shader. ShaderEffect.shadowMapping.UpdateGenerateShadowWorldMatrix( objectMatrix * renderMatrix); /*obs, using static shader now // Reset all bone matrices, we will use some random data that // is currently set as blendWeights and blendIndices. Matrix[] defaultMatrices = new Matrix[80]; for (int i = 0; i < defaultMatrices.Length; i++) { defaultMatrices[i] = Matrix.Identity; } // for ShaderEffect.shadowMapping.SetBoneMatrices(defaultMatrices); */ // And render BaseGame.Device.VertexDeclaration = TangentVertex.VertexDeclaration; //SkinnedTangentVertex.VertexDeclaration; ShaderEffect.shadowMapping.UseStaticShadowShader(); RenderVertices(); } // Render(shader, shaderTechnique) #endregion #region Use shadow /// <summary> /// Use shadow on the plane, useful for our unit tests. The plane does not /// throw shadows, so we don't need a GenerateShadow method. /// </summary> public virtual void UseShadow(Matrix renderMatrix) { // Set bone matrices and the world matrix for the shader. ShaderEffect.shadowMapping.UpdateCalcShadowWorldMatrix( objectMatrix * renderMatrix); /*obs, using static shader now // Reset all bone matrices, we will use some random data that // is currently set as blendWeights and blendIndices. Matrix[] defaultMatrices = new Matrix[80]; for (int i = 0; i < defaultMatrices.Length; i++) { defaultMatrices[i] = Matrix.Identity; } // for ShaderEffect.shadowMapping.SetBoneMatrices(defaultMatrices); */ // And render BaseGame.Device.VertexDeclaration = TangentVertex.VertexDeclaration; ShaderEffect.shadowMapping.UseStaticShadowShader(); RenderVertices(); } // UseShadow() #endregion #region Unit Testing #if DEBUG #region TestCaveColladaModelScene /// <summary> /// TestCaveColladaModelScene /// </summary> public static void TestCaveColladaModelScene() { ColladaModel caveModel = null; //ColladaModel playerModel = null; //PlaneRenderer groundPlane = null; TestGame.Start("TestCaveColladaModelScene", delegate { // Load Cave caveModel = new ColladaModel("Cave"); caveModel.material.ambientColor = Material.DefaultAmbientColor; //TODO: playerModel = new ColladaModel("Hero"); // Play background music :) //Sound.StartMusic(); /*not needed here // Create ground plane groundPlane = new PlaneRenderer( new Vector3(0, 0, -0.001f), new Plane(new Vector3(0, 0, 1), 0), new Material( "CaveDetailGround", "CaveDetailGroundNormal"), 28); */ // Set light direction (light is coming from the front right pos). BaseGame.LightDirection = new Vector3(-18, -20, 16); }, delegate { if (Input.Keyboard.IsKeyDown(Keys.LeftAlt)) { // Start glow shader BaseGame.GlowShader.Start(); // Clear background with white color, looks much cooler for the // post screen glow effect. BaseGame.Device.Clear(Color.Black); } // if (Input.Keyboard.IsKeyDown) //BaseGame.Device.Clear(new Color(86, 86, 60)); // Render goblin always in center, but he is really big, bring him // down to a more normal size that fits better in our test scene. Matrix renderMatrix = Matrix.Identity;// Matrix.CreateScale(0.1f); // Restore z buffer state BaseGame.Device.RenderState.DepthBufferEnable = true; BaseGame.Device.RenderState.DepthBufferWriteEnable = true; /*TODO // Make sure we use skinned tangent vertex format for shadow mapping BaseGame.Device.VertexDeclaration = TangentVertex.VertexDeclaration; // Generate shadows ShaderEffect.shadowMapping.GenerateShadows( delegate { for (int x = 0; x < 2; x++) for (int y = 0; y < 3; y++) goblinModel.GenerateShadow(renderMatrix * Matrix.CreateTranslation(-5 + 10 * x, -10 + 10 * y, 0)); }); // Render shadows ShaderEffect.shadowMapping.RenderShadows( delegate { for (int x = 0; x < 2; x++) for (int y = 0; y < 3; y++) goblinModel.UseShadow(renderMatrix * Matrix.CreateTranslation(-5 + 10 * x, -10 + 10 * y, 0)); groundPlane.UseShadow(); }); */ // Show ground with DiffuseSpecular material and use parallax mapping! //not needed: groundPlane.Render(ShaderEffect.normalMapping, "Specular30"); /*obs // And show all goblins for (int x = 0; x < 2; x++) for (int y = 0; y < 3; y++) goblinModel.Render( renderMatrix * Matrix.CreateTranslation(-5 + 10 * x, -10 + 10 * y, 0)); */ caveModel.Render( Matrix.CreateTranslation(0, 0, +1)); LightManager.RenderAllCloseLightEffects(); // We have to render the effects ourselfs because // it is usually done in DungeonQuestGame! // Finally render all effects (before applying post screen effects) BaseGame.effectManager.HandleAllEffects(); /*TODO if (Input.Keyboard.IsKeyDown(Keys.LeftControl)) playerModel.Render( Matrix.CreateTranslation(BaseGame.camera.PlayerPos)); */ // And show shadows on top of the scene (with shadow blur effect). //TODO: ShaderEffect.shadowMapping.ShowShadows(); if (Input.Keyboard.IsKeyDown(Keys.LeftAlt)) { // And finally show glow shader on top of everything BaseGame.GlowShader.Show(); } // if (Input.Keyboard.IsKeyDown) /*TODO // If you press the right mouse button or B you can see all // shadow map and post screen render targets (for testing/debugging) if (Input.MouseRightButtonPressed || Input.GamePadBPressed) { BaseGame.AlphaBlending = false; BaseGame.Device.RenderState.AlphaTestEnable = false; // Line 1 (3 render targets, 2 shadow mapping, 1 post screen) ShaderEffect.shadowMapping.shadowMapTexture.RenderOnScreen( new Rectangle(10, 10, 256, 256)); ShaderEffect.shadowMapping.shadowMapBlur.SceneMapTexture. RenderOnScreen( new Rectangle(10 + 256 + 10, 10, 256, 256)); PostScreenMenu.sceneMapTexture.RenderOnScreenNoAlpha( new Rectangle(10 + 256 + 10 + 256 + 10, 10, 256, 256)); // Line 2 (3 render targets, 2 post screen blurs, 1 final scene) PostScreenMenu.downsampleMapTexture.RenderOnScreenNoAlpha( new Rectangle(10, 10 + 256 + 10, 256, 256)); PostScreenMenu.blurMap1Texture.RenderOnScreenNoAlpha( new Rectangle(10 + 256 + 10, 10 + 256 + 10, 256, 256)); PostScreenMenu.blurMap2Texture.RenderOnScreenNoAlpha( new Rectangle(10 + 256 + 10 + 256 + 10, 10 + 256 + 10, 256, 256)); } // if (Input.MouseRightButtonPressed) */ }); } // TestLoadColladaModel() #endregion #region TestCaveColladaModelSceneSplitScreen /// <summary> /// TestCaveColladaModelScene /// </summary> public static void TestCaveColladaModelSceneSplitScreen() { ColladaModel caveModel = null; Viewport originalViewport = new Viewport(), viewport1 = new Viewport(), viewport2 = new Viewport(); TestGame.Start("TestCaveColladaModelScene", delegate { // Load Cave caveModel = new ColladaModel("Cave"); caveModel.material.ambientColor = Material.DefaultAmbientColor; // Set light direction (light is coming from the front right pos). BaseGame.LightDirection = new Vector3(-18, -20, 16); // Create both viewports originalViewport = BaseGame.Device.Viewport; viewport1 = new Viewport(); viewport1.Width = BaseGame.Width / 2; viewport1.Height = BaseGame.Height; viewport1.X = 0; viewport1.Y = 0; viewport2 = new Viewport(); viewport2.Width = BaseGame.Width / 2; viewport2.Height = BaseGame.Height; viewport2.X = BaseGame.Width / 2; viewport2.Y = 0; // Fix projection matrix for 2 views BaseGame.ProjectionMatrix = Matrix.CreatePerspectiveFieldOfView( BaseGame.FieldOfView, BaseGame.aspectRatio / 2.0f, BaseGame.NearPlane, BaseGame.FarPlane); }, delegate { // Render goblin always in center, but he is really big, bring him // down to a more normal size that fits better in our test scene. Matrix renderMatrix = Matrix.Identity;// Matrix.CreateScale(0.1f); // Restore z buffer state BaseGame.Device.RenderState.DepthBufferEnable = true; BaseGame.Device.RenderState.DepthBufferWriteEnable = true; // Render viewport 1 BaseGame.Device.Viewport = viewport1; BaseGame.Device.Clear(BaseGame.BackgroundColor); caveModel.Render( Matrix.CreateTranslation(0, 0, +1)); LightManager.RenderAllCloseLightEffects(); BaseGame.effectManager.HandleAllEffects(); // Render viewport 2 BaseGame.Device.Viewport = viewport2; BaseGame.ViewMatrix = BaseGame.ViewMatrix * Matrix.CreateRotationY(1.4f); BaseGame.Device.Clear(BaseGame.BackgroundColor); caveModel.Render( Matrix.CreateTranslation(0, 0, +1)); LightManager.RenderAllCloseLightEffects(); BaseGame.effectManager.HandleAllEffects(); // Restore BaseGame.Device.Viewport = originalViewport; // Draw seperation line //BaseGame.Device.RenderState.DepthBufferEnable = true; //BaseGame.Device.RenderState.DepthBufferWriteEnable = true; //TODO UIManager.DrawUI(); }); } // TestCaveColladaModelSceneSplitScreen() #endregion #region TestLoadStaticModel /// <summary> /// Test load static model /// </summary> static public void TestLoadStaticModel() { ColladaModel someModel = null; TestGame.Start("TestLoadStaticModel", delegate { // Load the cave for all the lights (else everything will be dark) someModel = new ColladaModel("Cave"); someModel = new ColladaModel( //"Cave"); //"Flare"); //"Club"); "Sword"); //"Door"); }, delegate { someModel.Render( //Matrix.CreateTranslation( //BaseGame.camera.PlayerPos+new Vector3(0, 0, 1))); //Matrix.CreateScale(100)); Matrix.Identity); //Matrix.CreateTranslation(new Vector3(2, 0, 0))); }); } // TestLoadStaticModel() #endregion #endif #endregion } // class ColladaModel } // namespace DungeonQuest.Graphics
using System; using System.IO; using System.Net; using System.Text; using System.Xml; using Discovery.Library.Extensions; using Discovery.Library.Format; namespace Discovery.Library.Protocol { public sealed class HttpProtocol : IProtocol { #region IProtocol Members public void Append() { throw new NotImplementedException(); } public void Partial() { throw new NotImplementedException(); } public IProtocolResponse Read(Uri uri, string uriConfiguration, IFormatMarshaller formatMarshaller = null, string userName = "", string password = "") { //***** var document = new HttpProtocolResponse(); //***** var responseElement = document.AppendElement("response"); //***** try { //***** var request = (HttpWebRequest)WebRequest.Create(uri); //***** Test for uri configuration; //***** TODO:Factory + data format; var allConfig = new XmlDocument(); allConfig.Load(uriConfiguration); var uriConfigNode = allConfig.SelectSingleNode(string.Format("apis/api[starts-with('{0}', @uri)]", uri)); var responseMediaTypeOverride = ""; if (uriConfigNode != null) { //***** Response media type override; var mediaTypeNode = uriConfigNode.SelectSingleNode("mediaType"); if (mediaTypeNode != null) responseMediaTypeOverride = mediaTypeNode.InnerText; //***** Headers; var headers = uriConfigNode.SelectNodes("headers/header"); foreach (XmlNode header in headers) { var headerName = header.Attributes["name"].InnerText; var headerValue = header.InnerText; switch (headerName.ToLower()) { case "accept": request.Accept = headerValue; break; default: request.Headers.Add(headerName, headerValue); break; } } } //***** request.Method = "GET"; //***** Force Basic Authorization for now (assume empty password is allowed); if (!string.IsNullOrWhiteSpace(userName)) request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(userName + ":" + password)); //***** TODO:Allow to pass UserAgent? Most APIs dont seem to allow "agentless" calls; request.UserAgent = "Discovery"; /*request.Credentials = new NetworkCredential(userName, password); request.PreAuthenticate = true;*/ //***** string entityBody; //***** Get response; using (var response = (HttpWebResponse) request.GetResponse()) { #region Status Line //***** var statusLineElement = responseElement.AppendElement("statusLine"); //***** statusLineElement.AppendElement("protocolName", "HTTP"); statusLineElement.AppendElement("protocolVersion", response.ProtocolVersion.ToString()); statusLineElement.AppendElement("statusCode", Convert.ToInt32(response.StatusCode).ToString()); statusLineElement.AppendElement("statusDescription", response.StatusDescription); #endregion //***** Status Line; #region Headers var headersElement = responseElement.AppendElement("headers"); var headers = response.Headers; foreach (var key in headers.AllKeys) { //***** var headerElement = headersElement.AppendElement("header"); headerElement.AppendAttribute("name", key); //***** Handle specifics based on RFC2616; switch (key.ToLower()) { case "content-type": var contentTypeValues = headers.GetValues(key); var contentTypeValue = contentTypeValues[0]; var contentTypeParts = contentTypeValue.Split(new[]{";"}, StringSplitOptions.RemoveEmptyEntries); headerElement.AppendElement("mediaType", contentTypeParts[0].Trim()); if (contentTypeParts.Length == 2) { var contentEncodingParts = contentTypeParts[1].Split(new[]{"="}, StringSplitOptions.RemoveEmptyEntries); headerElement.AppendElement(contentEncodingParts[0].Trim(), contentEncodingParts[1].Trim()); } break; default: foreach (var value in headers.GetValues(key)) headerElement.AppendElement("value", value); break; } } #endregion //***** Headers #region Entity //***** var entityElement = responseElement.AppendElement("entity"); entityElement.AppendElement("encoding", response.ContentEncoding); entityElement.AppendElement("type", response.ContentType); //***** Get response body; //***** NOTE:RFC-2616:There is no default encoding => Don't apply, use StreamReader auto determine; var encodingName = response.ContentEncoding; if (string.IsNullOrWhiteSpace(encodingName)) { var charsetNode = document.SelectSingleNode("response/headers/header[@name='Content-Type']/charset"); if (charsetNode != null) encodingName = charsetNode.InnerText; } //***** if (string.IsNullOrWhiteSpace(encodingName)) using (var bodyReader = new StreamReader(response.GetResponseStream())) entityBody = bodyReader.ReadToEnd(); else using (var bodyReader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encodingName))) entityBody = bodyReader.ReadToEnd(); //***** TODO:Override only when media type is format type? var mediaType = responseMediaTypeOverride; if (string.IsNullOrWhiteSpace(mediaType)) { var mediaTypeNode = document.SelectSingleNode("response/headers/header[@name='Content-Type']/mediaType"); if (mediaTypeNode != null && string.IsNullOrWhiteSpace(mediaType)) mediaType = mediaTypeNode.InnerText.ToLower(); /*else if (mediaTypeNode == null && !string.IsNullOrWhiteSpace(responseMediaTypeOverride)) mediaType = responseMediaTypeOverride;*/ } //***** document.MediaType = mediaType; //***** if (string.IsNullOrWhiteSpace(mediaType)) entityElement.AppendElement("body", entityBody); else { var marshalledEntityBody = formatMarshaller.Marshal(mediaType, entityBody); entityElement.AppendElement("body", marshalledEntityBody, true); } //***** When the content length is not provided entityElement.AppendElement("length", response.ContentLength.ToString()); #endregion //***** Entity #region Raw document.Raw = string.Format("HTTP/{0} {1} {2}\r\n{3}{4}", response.ProtocolVersion, Convert.ToInt32(response.StatusCode), response.StatusDescription, response.Headers, entityBody); #endregion //***** Raw } } catch (WebException wex) { if (wex.Status == WebExceptionStatus.ProtocolError) { var response = (HttpWebResponse)wex.Response; #region Status Line var statusLineElement = responseElement.AppendElement("statusLine"); //***** statusLineElement.AppendElement("protocolName", "HTTP"); statusLineElement.AppendElement("protocolVersion", response.ProtocolVersion.ToString()); statusLineElement.AppendElement("statusCode", Convert.ToInt32(response.StatusCode).ToString()); statusLineElement.AppendElement("statusDescription", response.StatusDescription); #endregion //***** Status Line; } else if (wex.Status == WebExceptionStatus.ServerProtocolViolation) { //***** NOTE:Exception was thrown when calling https://api.github.com //***** Found solution on http://earljon.wordpress.com/2012/08/23/quickfix-server-committed-a-protocol-violation-error-in-net/ //***** Add <system.net><settings><httpWebRequest useUnsafeHeaderParsing="true"/></settings></system.net> to app.config //***** TODO:Add wex. Response is not available with this type of exception! } } catch (Exception ex) { //***** TODO:Non-protocol exception; /*var exception = ex; UberData dataElement = null; while (exception != null) { var exceptionElement = new UberData { Name = "Message", Value = ex.Message }; if (dataElement != null) dataElement.Data.Add(exceptionElement); exception = exception.InnerException; dataElement = exceptionElement; } if (dataElement == null) uber.Error.Add(new UberData { Value = "Unknown exception" }); else uber.Error.Add(dataElement);*/ } return document; } public void Remove() { throw new NotImplementedException(); } public void Replace() { throw new NotImplementedException(); } #endregion } }
// <copyright> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> namespace System.Activities.DynamicUpdate { using System; using System.Activities.DynamicUpdate; using System.Activities.Validation; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Runtime; using System.Runtime.CompilerServices; static class ActivityComparer { public static bool HasPrivateMemberOtherThanArgumentsChanged(DynamicUpdateMapBuilder.NestedIdSpaceFinalizer nestedFinalizer, Activity currentElement, Activity originalElement, bool isMemberOfUpdatedIdSpace, out DynamicUpdateMap argumentChangesMap) { Fx.Assert(currentElement != null && originalElement != null, "Both activities must be non-null."); argumentChangesMap = null; IdSpace currentPrivateIdSpace = currentElement.ParentOf; IdSpace originalPrivateIdSpace = originalElement.ParentOf; // for the implementation of an activity in the IdSpace being updated--but not anywhere deeper // in the tree--we allow adding, removing or rearranging named private variables. // We don't support matching unnamed private variables, and we don't support declaring new // default variable expressions. (That would would offset the private IdSpace, which will be caught by the subsquent checks.) if ((!isMemberOfUpdatedIdSpace || IsAnyNameless(currentElement.ImplementationVariables) || IsAnyNameless(originalElement.ImplementationVariables)) && !ListEquals(currentElement.ImplementationVariables, originalElement.ImplementationVariables, CompareVariableEquality)) { return true; } if (currentPrivateIdSpace == null && originalPrivateIdSpace == null) { return false; } else if ((currentPrivateIdSpace != null && originalPrivateIdSpace == null) || (currentPrivateIdSpace == null && originalPrivateIdSpace != null)) { return true; } if (!ListEquals<ActivityDelegate>(currentElement.ImplementationDelegates, originalElement.ImplementationDelegates, CompareDelegateEquality)) { return true; } // compare structural equality of members in the private IdSpaces PrivateIdSpaceMatcher privateIdSpaceMatcher = new PrivateIdSpaceMatcher(nestedFinalizer, originalPrivateIdSpace, currentPrivateIdSpace); return !privateIdSpaceMatcher.Match(out argumentChangesMap); } public static bool ListEquals(IList<RuntimeDelegateArgument> currentArguments, IList<RuntimeDelegateArgument> originalArguments) { return ListEquals(currentArguments, originalArguments, CompareRuntimeDelegateArgumentEquality); } public static bool ListEquals(IList<ArgumentInfo> currentArguments, IList<ArgumentInfo> originalArguments) { return ListEquals(currentArguments, originalArguments, ArgumentInfo.Equals); } public static bool ListEquals<T>(IList<T> currentMembers, IList<T> originalMembers, Func<T, T, bool> comparer) { if (currentMembers == null) { return originalMembers == null || originalMembers.Count == 0; } if (originalMembers == null) { return currentMembers.Count == 0; } if (currentMembers.Count != originalMembers.Count) { return false; } if (comparer != null) { for (int i = 0; i < currentMembers.Count; i++) { if (!comparer(currentMembers[i], originalMembers[i])) { return false; } } } return true; } public static bool SignatureEquals(Variable leftVar, Variable rightVar) { return AreVariableNamesIdentical(leftVar.Name, rightVar.Name) && leftVar.Type == rightVar.Type && leftVar.Modifiers == rightVar.Modifiers; } static bool AreVariableNamesIdentical(string leftName, string rightName) { if (string.IsNullOrEmpty(leftName) && string.IsNullOrEmpty(rightName)) { return true; } return leftName == rightName; } static bool IsAnyNameless(IEnumerable<Variable> variables) { return variables.Any(v => string.IsNullOrEmpty(v.Name)); } static IList<Activity> GetDeclaredChildren(IList<Activity> collection, Activity parent) { return collection.Where(a => a.Parent == parent).ToList(); } static IList<ActivityDelegate> GetDeclaredDelegates(IList<ActivityDelegate> collection, Activity parentActivity) { return collection.Where(d => d.Owner == parentActivity).ToList(); } static bool CompareChildEquality(Activity currentChild, IdSpace currentIdSpace, Activity originalChild, IdSpace originalIdSpace) { if (currentChild == null && originalChild == null) { return true; } else if ((currentChild == null && originalChild != null) || (currentChild != null && originalChild == null)) { return false; } if ((currentChild.MemberOf == currentIdSpace && originalChild.MemberOf != originalIdSpace) || (currentChild.MemberOf != currentIdSpace && originalChild.MemberOf == originalIdSpace)) { return false; } return true; } static bool CompareDelegateEquality(ActivityDelegate currentDelegate, ActivityDelegate originalDelegate) { Fx.Assert(currentDelegate != null && originalDelegate != null, "Both currentDelegate and originalDelegate must be non-null."); if (!ListEquals(currentDelegate.RuntimeDelegateArguments, originalDelegate.RuntimeDelegateArguments)) { return false; } bool isImplementation = currentDelegate.ParentCollectionType == ActivityCollectionType.Implementation; Fx.Assert(originalDelegate.ParentCollectionType == currentDelegate.ParentCollectionType, "Mismatched delegates"); IdSpace currentIdSpace = isImplementation ? currentDelegate.Owner.ParentOf : currentDelegate.Owner.MemberOf; IdSpace originalIdSpace = isImplementation ? originalDelegate.Owner.ParentOf : originalDelegate.Owner.MemberOf; return CompareChildEquality(currentDelegate.Handler, currentIdSpace, originalDelegate.Handler, originalIdSpace); } static bool CompareVariableEquality(Variable currentVariable, Variable originalVariable) { Fx.Assert(currentVariable != null && originalVariable != null, "Both currentVariable and originalVariable must be non-null."); if (!SignatureEquals(currentVariable, originalVariable)) { return false; } Fx.Assert(currentVariable.IsPublic == originalVariable.IsPublic, "Mismatched variables"); IdSpace currentIdSpace = currentVariable.IsPublic ? currentVariable.Owner.MemberOf : currentVariable.Owner.ParentOf; IdSpace originalIdSpace = originalVariable.IsPublic ? originalVariable.Owner.MemberOf : originalVariable.Owner.ParentOf; return CompareChildEquality(currentVariable.Default, currentIdSpace, originalVariable.Default, originalIdSpace); } static bool CompareArgumentEquality(RuntimeArgument currentArgument, RuntimeArgument originalArgument) { Fx.Assert(currentArgument != null && originalArgument != null, "Both currentArgument and originalArgument must be non-null."); if (currentArgument.Name != originalArgument.Name || currentArgument.Type != originalArgument.Type || currentArgument.Direction != originalArgument.Direction) { return false; } if (currentArgument.BoundArgument == null && originalArgument.BoundArgument == null) { return true; } else if ((currentArgument.BoundArgument != null && originalArgument.BoundArgument == null) || (currentArgument.BoundArgument == null && originalArgument.BoundArgument != null)) { return false; } return CompareChildEquality(currentArgument.BoundArgument.Expression, currentArgument.Owner.MemberOf, originalArgument.BoundArgument.Expression, originalArgument.Owner.MemberOf); } static bool CompareRuntimeDelegateArgumentEquality(RuntimeDelegateArgument newRuntimeDelegateArgument, RuntimeDelegateArgument oldRuntimeDelegateArgument) { // compare Name, Type and Direction if (!newRuntimeDelegateArgument.Name.Equals(oldRuntimeDelegateArgument.Name) || (newRuntimeDelegateArgument.Type != oldRuntimeDelegateArgument.Type) || (newRuntimeDelegateArgument.Direction != oldRuntimeDelegateArgument.Direction)) { return false; } return CompareDelegateArgumentEquality(newRuntimeDelegateArgument.BoundArgument, oldRuntimeDelegateArgument.BoundArgument); } static bool CompareDelegateArgumentEquality(DelegateArgument newBoundArgument, DelegateArgument oldBoundArgument) { if (newBoundArgument == null) { return oldBoundArgument == null; } else if (oldBoundArgument == null) { return false; } return (newBoundArgument.Name == oldBoundArgument.Name) && (newBoundArgument.Type == oldBoundArgument.Type) && (newBoundArgument.Direction == oldBoundArgument.Direction); } // this class helps to determine if anything in the private IdSpace has changed or not. // The only exception is addition/removal/rearrangement of RuntimeArguments and their Expressions. // Addition or removal of the RuntimeArguments with non-null Expressions will cause Id shift in the private IdSpace. // In such case, this PrivateIdSpaceMatcher returns an implementation Map which represents the id shift and RuntimeArguments change. class PrivateIdSpaceMatcher { DynamicUpdateMap privateMap; DynamicUpdateMapBuilder.NestedIdSpaceFinalizer nestedFinalizer; IdSpace originalPrivateIdSpace; IdSpace updatedPrivateIdSpace; // As PrivateIdSpaceMatcher progresses through the IdSpace pair, // only the structurally equal activity pairs that are members of the IdSpaces are enqueued to this queue. Queue<Tuple<Activity, Activity>> matchedActivities; bool argumentChangeDetected; public PrivateIdSpaceMatcher(DynamicUpdateMapBuilder.NestedIdSpaceFinalizer nestedFinalizer, IdSpace originalPrivateIdSpace, IdSpace updatedPrivateIdSpace) { this.privateMap = new DynamicUpdateMap() { IsForImplementation = true, NewDefinitionMemberCount = updatedPrivateIdSpace.MemberCount }; this.nestedFinalizer = nestedFinalizer; this.argumentChangeDetected = false; this.originalPrivateIdSpace = originalPrivateIdSpace; this.updatedPrivateIdSpace = updatedPrivateIdSpace; this.matchedActivities = new Queue<Tuple<Activity, Activity>>(); } public bool Match(out DynamicUpdateMap argumentChangesMap) { argumentChangesMap = null; int nextOriginalSubrootId = 0; int nextUpdatedSubrootId = 0; bool allSubtreeRootsEnqueued = false; // enqueue all subtree root pairs first while (!allSubtreeRootsEnqueued) { nextOriginalSubrootId = GetIndexOfNextSubtreeRoot(this.originalPrivateIdSpace, nextOriginalSubrootId); nextUpdatedSubrootId = GetIndexOfNextSubtreeRoot(this.updatedPrivateIdSpace, nextUpdatedSubrootId); if (nextOriginalSubrootId != -1 && nextUpdatedSubrootId != -1) { // found next disjoint subtree pair to match this.PrepareToMatchSubtree(this.updatedPrivateIdSpace[nextUpdatedSubrootId], this.originalPrivateIdSpace[nextOriginalSubrootId]); } else if (nextOriginalSubrootId == -1 && nextUpdatedSubrootId == -1) { // there are no more subtree root pair to process. allSubtreeRootsEnqueued = true; } else { // something other than Arguments must have changed return false; } } while (this.matchedActivities.Count > 0) { Tuple<Activity, Activity> pair = this.matchedActivities.Dequeue(); Activity originalActivity = pair.Item1; Activity currentActivity = pair.Item2; Fx.Assert(originalActivity.MemberOf == this.originalPrivateIdSpace && currentActivity.MemberOf == this.updatedPrivateIdSpace, "neither activities must be a reference."); if (currentActivity.GetType() != originalActivity.GetType() || currentActivity.RelationshipToParent != originalActivity.RelationshipToParent) { return false; } // there is no need to perform CompareChildEquality since we already compare ActivityId and activity.GetType() as above for all activities in the IdSpace, and check on the collection count if (!ActivityComparer.ListEquals( ActivityComparer.GetDeclaredChildren(currentActivity.Children, currentActivity), ActivityComparer.GetDeclaredChildren(originalActivity.Children, originalActivity), this.AddEqualChildren)) { return false; } // there is no need to perform CompareChildEquality since we already compare ActivityId and activity.GetType() as above for all activities in the IdSpace, and check on the collection count if (!ActivityComparer.ListEquals( ActivityComparer.GetDeclaredChildren(currentActivity.ImportedChildren, currentActivity), ActivityComparer.GetDeclaredChildren(originalActivity.ImportedChildren, originalActivity), this.AddEqualChildren)) { return false; } if (!ActivityComparer.ListEquals<ActivityDelegate>( ActivityComparer.GetDeclaredDelegates(currentActivity.Delegates, currentActivity), ActivityComparer.GetDeclaredDelegates(originalActivity.Delegates, originalActivity), this.CompareDelegateEqualityAndAddActivitiesPair)) { return false; } if (!ActivityComparer.ListEquals<ActivityDelegate>( ActivityComparer.GetDeclaredDelegates(currentActivity.ImportedDelegates, currentActivity), ActivityComparer.GetDeclaredDelegates(originalActivity.ImportedDelegates, originalActivity), this.CompareDelegateEqualityAndAddActivitiesPair)) { return false; } if (!ActivityComparer.ListEquals<Variable>(currentActivity.RuntimeVariables, originalActivity.RuntimeVariables, this.CompareVariableEqualityAndAddActivitiesPair)) { return false; } // with all runtime metadata except arguments matching, // the current activities pair qualifies as a matching entry // let's create an entry DynamicUpdateMapEntry entry = new DynamicUpdateMapEntry(originalActivity.InternalId, currentActivity.InternalId); this.privateMap.AddEntry(entry); if (!this.TryMatchingArguments(entry, originalActivity, currentActivity)) { return false; } } // there are no more activities-pair to process. // if we are here, it means we have successfully matched the private IdSpace pair if (this.argumentChangeDetected) { // return the generated map only if we have argument entries argumentChangesMap = this.privateMap; } return true; } // return -1 if no subroot is found since the previous index // idspace.Owner will always be non-null. static int GetIndexOfNextSubtreeRoot(IdSpace idspace, int previousIndex) { for (int i = previousIndex + 1; i <= idspace.MemberCount; i++) { if (object.ReferenceEquals(idspace[i].Parent, idspace.Owner)) { return i; } } return -1; } bool TryMatchingArguments(DynamicUpdateMapEntry entry, Activity originalActivity, Activity currentActivity) { // now, let's try creating argument entries IList<ArgumentInfo> oldArguments = ArgumentInfo.List(originalActivity); this.nestedFinalizer.CreateArgumentEntries(entry, currentActivity.RuntimeArguments, oldArguments); if (entry.HasEnvironmentUpdates) { if (entry.EnvironmentUpdateMap.HasArgumentEntries) { foreach (EnvironmentUpdateMapEntry argumentEntry in entry.EnvironmentUpdateMap.ArgumentEntries) { if (!argumentEntry.IsAddition) { // if it is a matching argument pair, // let's add them to the lists for further matching process. RuntimeArgument originalArg = originalActivity.RuntimeArguments[argumentEntry.OldOffset]; RuntimeArgument updatedArg = currentActivity.RuntimeArguments[argumentEntry.NewOffset]; if (!this.TryPreparingArgumentExpressions(originalArg, updatedArg)) { return false; } } } } // we need to also visit subtrees of Expressions of removed arguments IList<ArgumentInfo> newArgumentInfos = ArgumentInfo.List(currentActivity); foreach (RuntimeArgument oldRuntimeArgument in originalActivity.RuntimeArguments) { if (newArgumentInfos.IndexOf(new ArgumentInfo(oldRuntimeArgument)) == EnvironmentUpdateMapEntry.NonExistent) { // this is a removed argument. if (oldRuntimeArgument.IsBound && oldRuntimeArgument.BoundArgument.Expression != null && oldRuntimeArgument.BoundArgument.Expression.MemberOf == originalActivity.MemberOf) { // create an entry for removal of this expression this.privateMap.AddEntry(new DynamicUpdateMapEntry(oldRuntimeArgument.BoundArgument.Expression.InternalId, 0)); } } } DynamicUpdateMapBuilder.Finalizer.FillEnvironmentMapMemberCounts(entry.EnvironmentUpdateMap, currentActivity, originalActivity, oldArguments); this.argumentChangeDetected = true; } else if (currentActivity.RuntimeArguments != null && currentActivity.RuntimeArguments.Count > 0) { Fx.Assert(currentActivity.RuntimeArguments.Count == originalActivity.RuntimeArguments.Count, "RuntimeArguments.Count for both currentActivity and originalActivity must be equal."); // if we are here, we know RuntimeArguments matched between currentActivity and originalActivity // but we still need to prepare their Expressions for matching for (int i = 0; i < currentActivity.RuntimeArguments.Count; i++) { if (!this.TryPreparingArgumentExpressions(originalActivity.RuntimeArguments[i], currentActivity.RuntimeArguments[i])) { return false; } } } if (entry.IsRuntimeUpdateBlocked) { entry.EnvironmentUpdateMap = null; } return true; } bool TryPreparingArgumentExpressions(RuntimeArgument originalArg, RuntimeArgument updatedArg) { if (!ActivityComparer.CompareArgumentEquality(updatedArg, originalArg)) { return false; } if (updatedArg.BoundArgument != null && updatedArg.BoundArgument.Expression != null) { Fx.Assert(originalArg.BoundArgument != null && originalArg.BoundArgument.Expression != null, "both Expressions are either non-null or null."); this.PrepareToMatchSubtree(updatedArg.BoundArgument.Expression, originalArg.BoundArgument.Expression); } return true; } void PrepareToMatchSubtree(Activity currentActivity, Activity originalActivity) { Fx.Assert(currentActivity != null && originalActivity != null, "both activities must not be null."); if (originalActivity.MemberOf != this.originalPrivateIdSpace && currentActivity.MemberOf != this.updatedPrivateIdSpace) { // we ignore references from other IdSpaces return; } Fx.Assert(originalActivity.MemberOf == this.originalPrivateIdSpace && currentActivity.MemberOf == this.updatedPrivateIdSpace, "neither activities must be a reference."); // add originalActivity and currentActivity to the pair queue so that their subtrees are further processed for matching this.matchedActivities.Enqueue(new Tuple<Activity, Activity>(originalActivity, currentActivity)); } bool AddEqualChildren(Activity currentActivity, Activity originalActivity) { this.PrepareToMatchSubtree(currentActivity, originalActivity); return true; } bool CompareDelegateEqualityAndAddActivitiesPair(ActivityDelegate currentDelegate, ActivityDelegate originalDelegate) { if (!ActivityComparer.CompareDelegateEquality(currentDelegate, originalDelegate)) { return false; } if (currentDelegate.Handler != null) { Fx.Assert(originalDelegate.Handler != null, "both handlers are either non-null or null."); this.PrepareToMatchSubtree(currentDelegate.Handler, originalDelegate.Handler); } return true; } bool CompareVariableEqualityAndAddActivitiesPair(Variable currentVariable, Variable originalVariable) { if (!ActivityComparer.CompareVariableEquality(currentVariable, originalVariable)) { return false; } if (currentVariable.Default != null) { Fx.Assert(originalVariable.Default != null, "both Defaults are either non-null or null."); this.PrepareToMatchSubtree(currentVariable.Default, originalVariable.Default); } return true; } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Reflection; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Data; using RegionFlags = OpenSim.Framework.RegionFlags; using Npgsql; namespace OpenSim.Data.PGSQL { /// <summary> /// A PGSQL Interface for the Region Server. /// </summary> public class PGSQLRegionData : IRegionData { private string m_Realm; private List<string> m_ColumnNames = null; private string m_ConnectionString; private PGSQLManager m_database; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected Dictionary<string, string> m_FieldTypes = new Dictionary<string, string>(); protected virtual Assembly Assembly { get { return GetType().Assembly; } } public PGSQLRegionData(string connectionString, string realm) { m_Realm = realm; m_ConnectionString = connectionString; m_database = new PGSQLManager(connectionString); using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) { conn.Open(); Migration m = new Migration(conn, GetType().Assembly, "GridStore"); m.Update(); } LoadFieldTypes(); } private void LoadFieldTypes() { m_FieldTypes = new Dictionary<string, string>(); string query = string.Format(@"select column_name,data_type from INFORMATION_SCHEMA.COLUMNS where table_name = lower('{0}'); ", m_Realm); using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(query, conn)) { conn.Open(); using (NpgsqlDataReader rdr = cmd.ExecuteReader()) { while (rdr.Read()) { // query produces 0 to many rows of single column, so always add the first item in each row m_FieldTypes.Add((string)rdr[0], (string)rdr[1]); } } } } public List<RegionData> Get(string regionName, UUID scopeID) { string sql = "select * from "+m_Realm+" where lower(\"regionName\") like lower(:regionName) "; if (scopeID != UUID.Zero) sql += " and \"ScopeID\" = :scopeID"; sql += " order by lower(\"regionName\")"; using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) { cmd.Parameters.Add(m_database.CreateParameter("regionName", regionName)); if (scopeID != UUID.Zero) cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID)); conn.Open(); return RunCommand(cmd); } } public RegionData Get(int posX, int posY, UUID scopeID) { // extend database search for maximum region size area string sql = "select * from "+m_Realm+" where \"locX\" between :startX and :endX and \"locY\" between :startY and :endY"; if (scopeID != UUID.Zero) sql += " and \"ScopeID\" = :scopeID"; int startX = posX - (int)Constants.MaximumRegionSize; int startY = posY - (int)Constants.MaximumRegionSize; int endX = posX; int endY = posY; List<RegionData> ret; using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) { cmd.Parameters.Add(m_database.CreateParameter("startX", startX)); cmd.Parameters.Add(m_database.CreateParameter("startY", startY)); cmd.Parameters.Add(m_database.CreateParameter("endX", endX)); cmd.Parameters.Add(m_database.CreateParameter("endY", endY)); if (scopeID != UUID.Zero) cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID)); conn.Open(); ret = RunCommand(cmd); } if (ret.Count == 0) return null; // Find the first that contains pos RegionData rg = null; foreach (RegionData r in ret) { if (posX >= r.posX && posX < r.posX + r.sizeX && posY >= r.posY && posY < r.posY + r.sizeY) { rg = r; break; } } return rg; } public RegionData Get(UUID regionID, UUID scopeID) { string sql = "select * from "+m_Realm+" where uuid = :regionID"; if (scopeID != UUID.Zero) sql += " and \"ScopeID\" = :scopeID"; using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) { cmd.Parameters.Add(m_database.CreateParameter("regionID", regionID)); if (scopeID != UUID.Zero) cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID)); conn.Open(); List<RegionData> ret = RunCommand(cmd); if (ret.Count == 0) return null; return ret[0]; } } public List<RegionData> Get(int startX, int startY, int endX, int endY, UUID scopeID) { // extend database search for maximum region size area string sql = "select * from "+m_Realm+" where \"locX\" between :startX and :endX and \"locY\" between :startY and :endY"; if (scopeID != UUID.Zero) sql += " and \"ScopeID\" = :scopeID"; int qstartX = startX - (int)Constants.MaximumRegionSize; int qstartY = startY - (int)Constants.MaximumRegionSize; List<RegionData> dbret; using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) { cmd.Parameters.Add(m_database.CreateParameter("startX", qstartX)); cmd.Parameters.Add(m_database.CreateParameter("startY", qstartY)); cmd.Parameters.Add(m_database.CreateParameter("endX", endX)); cmd.Parameters.Add(m_database.CreateParameter("endY", endY)); if (scopeID != UUID.Zero) cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID)); conn.Open(); dbret = RunCommand(cmd); } List<RegionData> ret = new List<RegionData>(); if(dbret.Count == 0) return ret; foreach (RegionData r in dbret) { if (r.posX + r.sizeX > startX && r.posX <= endX && r.posY + r.sizeY > startY && r.posY <= endY) ret.Add(r); } return ret; } public List<RegionData> RunCommand(NpgsqlCommand cmd) { List<RegionData> retList = new List<RegionData>(); NpgsqlDataReader result = cmd.ExecuteReader(); while (result.Read()) { RegionData ret = new RegionData(); ret.Data = new Dictionary<string, object>(); UUID regionID; UUID.TryParse(result["uuid"].ToString(), out regionID); ret.RegionID = regionID; UUID scope; UUID.TryParse(result["ScopeID"].ToString(), out scope); ret.ScopeID = scope; ret.RegionName = result["regionName"].ToString(); ret.posX = Convert.ToInt32(result["locX"]); ret.posY = Convert.ToInt32(result["locY"]); ret.sizeX = Convert.ToInt32(result["sizeX"]); ret.sizeY = Convert.ToInt32(result["sizeY"]); if (m_ColumnNames == null) { m_ColumnNames = new List<string>(); DataTable schemaTable = result.GetSchemaTable(); foreach (DataRow row in schemaTable.Rows) m_ColumnNames.Add(row["ColumnName"].ToString()); } foreach (string s in m_ColumnNames) { if (s == "uuid") continue; if (s == "ScopeID") continue; if (s == "regionName") continue; if (s == "locX") continue; if (s == "locY") continue; ret.Data[s] = result[s].ToString(); } retList.Add(ret); } return retList; } public bool Store(RegionData data) { if (data.Data.ContainsKey("uuid")) data.Data.Remove("uuid"); if (data.Data.ContainsKey("ScopeID")) data.Data.Remove("ScopeID"); if (data.Data.ContainsKey("regionName")) data.Data.Remove("regionName"); if (data.Data.ContainsKey("posX")) data.Data.Remove("posX"); if (data.Data.ContainsKey("posY")) data.Data.Remove("posY"); if (data.Data.ContainsKey("sizeX")) data.Data.Remove("sizeX"); if (data.Data.ContainsKey("sizeY")) data.Data.Remove("sizeY"); if (data.Data.ContainsKey("locX")) data.Data.Remove("locX"); if (data.Data.ContainsKey("locY")) data.Data.Remove("locY"); string[] fields = new List<string>(data.Data.Keys).ToArray(); using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand()) { string update = "update " + m_Realm + " set \"locX\"=:posX, \"locY\"=:posY, \"sizeX\"=:sizeX, \"sizeY\"=:sizeY "; foreach (string field in fields) { update += ", "; update += " \"" + field + "\" = :" + field; if (m_FieldTypes.ContainsKey(field)) cmd.Parameters.Add(m_database.CreateParameter(field, data.Data[field], m_FieldTypes[field])); else cmd.Parameters.Add(m_database.CreateParameter(field, data.Data[field])); } update += " where uuid = :regionID"; if (data.ScopeID != UUID.Zero) update += " and \"ScopeID\" = :scopeID"; cmd.CommandText = update; cmd.Connection = conn; cmd.Parameters.Add(m_database.CreateParameter("regionID", data.RegionID)); cmd.Parameters.Add(m_database.CreateParameter("regionName", data.RegionName)); cmd.Parameters.Add(m_database.CreateParameter("scopeID", data.ScopeID)); cmd.Parameters.Add(m_database.CreateParameter("posX", data.posX)); cmd.Parameters.Add(m_database.CreateParameter("posY", data.posY)); cmd.Parameters.Add(m_database.CreateParameter("sizeX", data.sizeX)); cmd.Parameters.Add(m_database.CreateParameter("sizeY", data.sizeY)); conn.Open(); try { if (cmd.ExecuteNonQuery() < 1) { string insert = "insert into " + m_Realm + " (uuid, \"ScopeID\", \"locX\", \"locY\", \"sizeX\", \"sizeY\", \"regionName\", \"" + String.Join("\", \"", fields) + "\") values (:regionID, :scopeID, :posX, :posY, :sizeX, :sizeY, :regionName, :" + String.Join(", :", fields) + ")"; cmd.CommandText = insert; try { if (cmd.ExecuteNonQuery() < 1) { return false; } } catch (Exception ex) { m_log.Warn("[PGSQL Grid]: Error inserting into Regions table: " + ex.Message + ", INSERT sql: " + insert); } } } catch (Exception ex) { m_log.Warn("[PGSQL Grid]: Error updating Regions table: " + ex.Message + ", UPDATE sql: " + update); } } return true; } public bool SetDataItem(UUID regionID, string item, string value) { string sql = "update " + m_Realm + " set \"" + item + "\" = :" + item + " where uuid = :UUID"; using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) { cmd.Parameters.Add(m_database.CreateParameter("" + item, value)); cmd.Parameters.Add(m_database.CreateParameter("UUID", regionID)); conn.Open(); if (cmd.ExecuteNonQuery() > 0) return true; } return false; } public bool Delete(UUID regionID) { string sql = "delete from " + m_Realm + " where uuid = :UUID"; using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) { cmd.Parameters.Add(m_database.CreateParameter("UUID", regionID)); conn.Open(); if (cmd.ExecuteNonQuery() > 0) return true; } return false; } public List<RegionData> GetDefaultRegions(UUID scopeID) { return Get((int)RegionFlags.DefaultRegion, scopeID); } public List<RegionData> GetDefaultHypergridRegions(UUID scopeID) { return Get((int)RegionFlags.DefaultHGRegion, scopeID); } public List<RegionData> GetFallbackRegions(UUID scopeID, int x, int y) { List<RegionData> regions = Get((int)RegionFlags.FallbackRegion, scopeID); RegionDataDistanceCompare distanceComparer = new RegionDataDistanceCompare(x, y); regions.Sort(distanceComparer); return regions; } public List<RegionData> GetHyperlinks(UUID scopeID) { return Get((int)RegionFlags.Hyperlink, scopeID); } private List<RegionData> Get(int regionFlags, UUID scopeID) { string sql = "SELECT * FROM " + m_Realm + " WHERE (\"flags\" & " + regionFlags.ToString() + ") <> 0"; if (scopeID != UUID.Zero) sql += " AND \"ScopeID\" = :scopeID"; using (NpgsqlConnection conn = new NpgsqlConnection(m_ConnectionString)) using (NpgsqlCommand cmd = new NpgsqlCommand(sql, conn)) { cmd.Parameters.Add(m_database.CreateParameter("scopeID", scopeID)); conn.Open(); return RunCommand(cmd); } } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; // ERROR: Not supported in C#: OptionDeclaration using Microsoft.VisualBasic.PowerPacks; namespace _4PosBackOffice.NET { internal partial class frmItemGroup : System.Windows.Forms.Form { private void loadLanguage() { modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2375; //Stock Item / Stock Group Compare|Checked if (modRecordSet.rsLang.RecordCount){this.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;this.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2113; //Select Stock Item|Checked if (modRecordSet.rsLang.RecordCount){_lbl_0.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_0.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2378; //Get Stock Item|Checked if (modRecordSet.rsLang.RecordCount){cmdStockItem.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdStockItem.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2379; //Select a Group|Checked if (modRecordSet.rsLang.RecordCount){_lbl_1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2380; //Get a Group|Checked if (modRecordSet.rsLang.RecordCount){cmdGroup.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdGroup.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004; //Exit|Checked if (modRecordSet.rsLang.RecordCount){cmdExit.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdExit.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2382; //Sales Quantity|Checked if (modRecordSet.rsLang.RecordCount){_optDataType_0.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_optDataType_0.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2383; //Sales Value|Checked if (modRecordSet.rsLang.RecordCount){_optDataType_1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_optDataType_1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1269; //Load Report|Checked if (modRecordSet.rsLang.RecordCount){cmdLoad.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdLoad.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'"; //UPGRADE_ISSUE: Form property frmItemGroup.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"' if (modRecordSet.rsHelp.RecordCount) this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value; } private void cmdExit_Click(System.Object eventSender, System.EventArgs eventArgs) { this.Close(); } private void cmdGroup_Click(System.Object eventSender, System.EventArgs eventArgs) { ADODB.Recordset rs = default(ADODB.Recordset); int lID = 0; modReport.cnnDBreport.Execute("DELETE aftDataItem.* From aftDataItem WHERE (((aftDataItem.ftDataItem_PersonID)=" + modRecordSet.gPersonID + "));"); modReport.cnnDBreport.Execute("DELETE aftData.* From aftData WHERE (((aftData.ftData_PersonID)=" + modRecordSet.gPersonID + "));"); modReport.cnnDBreport.Execute("INSERT INTO aftData ( ftData_PersonID, ftData_FieldName, ftData_SQL, ftData_Heading ) SELECT LinkData.LinkData_PersonID, LinkData.LinkData_FieldName, LinkData.LinkData_SQL, LinkData.LinkData_Heading From LinkData WHERE (((LinkData.LinkData_LinkID)=2) AND ((LinkData.LinkData_SectionID)=1) AND ((LinkData.LinkData_PersonID)=" + modRecordSet.gPersonID + "));"); modReport.cnnDBreport.Execute("INSERT INTO aftDataItem ( ftDataItem_PersonID, ftDataItem_FieldName, ftDataItem_ID ) SELECT LinkDataItem.LinkDataItem_PersonID, LinkDataItem.LinkDataItem_FieldName, LinkDataItem.LinkDataItem_ID From LinkDataItem WHERE (((LinkDataItem.LinkDataItem_LinkID)=2) AND ((LinkDataItem.LinkDataItem_SectionID)=1) AND ((LinkDataItem.LinkDataItem_PersonID)=" + modRecordSet.gPersonID + "));"); My.MyProject.Forms.frmFilter.Close(); My.MyProject.Forms.frmFilter.buildCriteria(ref "StockItem"); My.MyProject.Forms.frmFilter.loadFilter(ref "StockItem"); My.MyProject.Forms.frmFilter.buildCriteria(ref "StockItem"); modReport.cnnDBreport.Execute("UPDATE Link SET Link.Link_Name = '" + Strings.Replace(My.MyProject.Forms.frmFilter.gHeading, "'", "''") + "', Link.Link_SQL = '" + Strings.Replace(My.MyProject.Forms.frmFilter.gCriteria, "'", "''") + "' WHERE (((Link.LinkID)=2) AND ((Link.Link_SectionID)=1) AND ((Link.Link_PersonID)=" + modRecordSet.gPersonID + "));"); modReport.cnnDBreport.Execute("DELETE LinkDataItem.* From LinkDataItem WHERE (((LinkDataItem.LinkDataItem_LinkID)=2) AND ((LinkDataItem.LinkDataItem_SectionID)=1) AND ((LinkDataItem.LinkDataItem_PersonID)=" + modRecordSet.gPersonID + "));"); modReport.cnnDBreport.Execute("DELETE LinkData.* From LinkData WHERE (((LinkData.LinkData_LinkID)=2) AND ((LinkData.LinkData_SectionID)=1) AND ((LinkData.LinkData_PersonID)=" + modRecordSet.gPersonID + "));"); modReport.cnnDBreport.Execute("INSERT INTO LinkData ( LinkData_LinkID, LinkData_SectionID, LinkData_PersonID, LinkData_FieldName, LinkData_SQL, LinkData_Heading ) SELECT 2, 1, aftData.ftData_PersonID, aftData.ftData_FieldName, aftData.ftData_SQL, aftData.ftData_Heading From aftData WHERE (((aftData.ftData_PersonID)=" + modRecordSet.gPersonID + "));"); modReport.cnnDBreport.Execute("INSERT INTO LinkDataItem ( LinkDataItem_LinkID, LinkDataItem_SectionID, LinkDataItem_PersonID, LinkDataItem_FieldName, LinkDataItem_ID ) SELECT 2, 1, aftDataItem.ftDataItem_PersonID, aftDataItem.ftDataItem_FieldName, aftDataItem.ftDataItem_ID From aftDataItem WHERE (((aftDataItem.ftDataItem_PersonID)=" + modRecordSet.gPersonID + "));"); lblGroup.Text = My.MyProject.Forms.frmFilter.gHeading; } private void cmdStockItem_Click(System.Object eventSender, System.EventArgs eventArgs) { ADODB.Recordset rs = default(ADODB.Recordset); int lID = 0; modReport.cnnDBreport.Execute("DELETE aftDataItem.* From aftDataItem WHERE (((aftDataItem.ftDataItem_PersonID)=" + modRecordSet.gPersonID + "));"); modReport.cnnDBreport.Execute("DELETE aftData.* From aftData WHERE (((aftData.ftData_PersonID)=" + modRecordSet.gPersonID + "));"); modReport.cnnDBreport.Execute("INSERT INTO aftData ( ftData_PersonID, ftData_FieldName, ftData_SQL, ftData_Heading ) SELECT LinkData.LinkData_PersonID, LinkData.LinkData_FieldName, LinkData.LinkData_SQL, LinkData.LinkData_Heading From LinkData WHERE (((LinkData.LinkData_LinkID)=1) AND ((LinkData.LinkData_SectionID)=1) AND ((LinkData.LinkData_PersonID)=" + modRecordSet.gPersonID + "));"); modReport.cnnDBreport.Execute("INSERT INTO aftDataItem ( ftDataItem_PersonID, ftDataItem_FieldName, ftDataItem_ID ) SELECT LinkDataItem.LinkDataItem_PersonID, LinkDataItem.LinkDataItem_FieldName, LinkDataItem.LinkDataItem_ID From LinkDataItem WHERE (((LinkDataItem.LinkDataItem_LinkID)=1) AND ((LinkDataItem.LinkDataItem_SectionID)=1) AND ((LinkDataItem.LinkDataItem_PersonID)=" + modRecordSet.gPersonID + "));"); My.MyProject.Forms.frmFilter.buildCriteria(ref "StockItem"); My.MyProject.Forms.frmFilter.Close(); lID = My.MyProject.Forms.frmStockList.getItem(); if (lID) { My.MyProject.Forms.frmFilter.buildCriteria(ref "StockItem"); rs = modRecordSet.getRS(ref "SELECT * FROM StockItem WHERE StockItemID=" + lID); modReport.cnnDBreport.Execute("UPDATE Link SET Link.Link_Name = ' " + Strings.Replace(rs.Fields("StockItem_Name").Value, "'", "''") + "', Link.Link_SQL = 'StockItemID=" + lID + "' WHERE (((Link.LinkID)=1) AND ((Link.Link_SectionID)=1) AND ((Link.Link_PersonID)=" + modRecordSet.gPersonID + "));"); modReport.cnnDBreport.Execute("DELETE LinkDataItem.* From LinkDataItem WHERE (((LinkDataItem.LinkDataItem_LinkID)=1) AND ((LinkDataItem.LinkDataItem_SectionID)=1) AND ((LinkDataItem.LinkDataItem_PersonID)=" + modRecordSet.gPersonID + "));"); modReport.cnnDBreport.Execute("DELETE LinkData.LinkData_LinkID, LinkData.LinkData_SectionID, LinkData.LinkData_PersonID, LinkData.* From LinkData WHERE (((LinkData.LinkData_LinkID)=1) AND ((LinkData.LinkData_SectionID)=1) AND ((LinkData.LinkData_PersonID)=" + modRecordSet.gPersonID + "));"); modReport.cnnDBreport.Execute("INSERT INTO LinkData ( LinkData_LinkID, LinkData_SectionID, LinkData_PersonID, LinkData_FieldName, LinkData_SQL, LinkData_Heading ) SELECT 1, 1, aftData.ftData_PersonID, aftData.ftData_FieldName, aftData.ftData_SQL, aftData.ftData_Heading From aftData WHERE (((aftData.ftData_PersonID)=" + modRecordSet.gPersonID + "));"); modReport.cnnDBreport.Execute("INSERT INTO LinkDataItem ( LinkDataItem_LinkID, LinkDataItem_SectionID, LinkDataItem_PersonID, LinkDataItem_FieldName, LinkDataItem_ID ) SELECT 1, 1, aftDataItem.ftDataItem_PersonID, aftDataItem.ftDataItem_FieldName, aftDataItem.ftDataItem_ID From aftDataItem WHERE (((aftDataItem.ftDataItem_PersonID)=" + modRecordSet.gPersonID + "));"); lblItem.Text = rs.Fields("StockItem_Name").Value; } } private void setup() { ADODB.Recordset rs = default(ADODB.Recordset); rs = modReport.getRSreport(ref "SELECT Link.Link_PersonID From Link WHERE (((Link.Link_PersonID)=" + modRecordSet.gPersonID + "));"); if (rs.BOF | rs.EOF) { modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 1, 1, " + modRecordSet.gPersonID + ", '', '';"); modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 2, 1, " + modRecordSet.gPersonID + ", '', '';"); modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 1, 2, " + modRecordSet.gPersonID + ", '', '';"); modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 2, 2, " + modRecordSet.gPersonID + ", '', '';"); modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 1, 3, " + modRecordSet.gPersonID + ", '', '';"); modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 2, 3, " + modRecordSet.gPersonID + ", '', '';"); modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 3, 3, " + modRecordSet.gPersonID + ", '', '';"); modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 4, 3, " + modRecordSet.gPersonID + ", '', '';"); modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 5, 3, " + modRecordSet.gPersonID + ", '', '';"); modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 6, 3, " + modRecordSet.gPersonID + ", '', '';"); modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 7, 3, " + modRecordSet.gPersonID + ", '', '';"); modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 8, 3, " + modRecordSet.gPersonID + ", '', '';"); modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 9, 3, " + modRecordSet.gPersonID + ", '', '';"); modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 10, 3, " + modRecordSet.gPersonID + ", '', '';"); } rs = modReport.getRSreport(ref "SELECT Link.Link_Name From Link WHERE (((Link.LinkID)=1) AND ((Link.Link_SectionID)=1) AND ((Link.Link_PersonID)=" + modRecordSet.gPersonID + "));"); lblItem.Text = rs.Fields("Link_Name").Value; rs = modReport.getRSreport(ref "SELECT Link.Link_Name From Link WHERE (((Link.LinkID)=2) AND ((Link.Link_SectionID)=1) AND ((Link.Link_PersonID)=" + modRecordSet.gPersonID + "));"); lblGroup.Text = rs.Fields("Link_Name").Value; } private void cmdLoad_Click(System.Object eventSender, System.EventArgs eventArgs) { ADODB.Recordset rs = default(ADODB.Recordset); ADODB.Recordset rsData = default(ADODB.Recordset); //Dim Report As New cryItemGroupCompare //ReportNone.Load("cryNoRecords.rpt") CrystalDecisions.CrystalReports.Engine.ReportDocument Report = new CrystalDecisions.CrystalReports.Engine.ReportDocument(); CrystalDecisions.CrystalReports.Engine.ReportDocument ReportNone = new CrystalDecisions.CrystalReports.Engine.ReportDocument(); Report.Load("cryItemGroupCompare.rpt"); ReportNone.Load("cryNoRecords"); modReport.cnnDBreport.Execute("DELETE LinkItem.* FROM LinkItem;"); rs = modReport.getRSreport(ref "SELECT * FROM Link Where LinkID=1 AND Link_SectionID=1"); modReport.cnnDBreport.Execute("INSERT INTO LinkItem ( LinkItem_LinkID, LinkItem_DayEndID, LinkItem_Value ) SELECT 1, DayEndStockItemLnk.DayEndStockItemLnk_DayEndID, DayEndStockItemLnk.DayEndStockItemLnk_QuantitySales FROM DayEndStockItemLnk INNER JOIN aStockItem ON DayEndStockItemLnk.DayEndStockItemLnk_StockItemID = aStockItem.StockItemID WHERE " + rs.Fields("Link_SQL").Value + ";"); rs = modReport.getRSreport(ref "SELECT * FROM Link Where LinkID=2 AND Link_SectionID=1"); modReport.cnnDBreport.Execute("INSERT INTO LinkItem ( LinkItem_LinkID, LinkItem_DayEndID, LinkItem_Value ) SELECT 2, DayEndStockItemLnk.DayEndStockItemLnk_DayEndID, Sum(DayEndStockItemLnk.DayEndStockItemLnk_QuantitySales) AS SumOfDayEndStockItemLnk_QuantitySales FROM DayEndStockItemLnk INNER JOIN aStockItem ON DayEndStockItemLnk.DayEndStockItemLnk_StockItemID = aStockItem.StockItemID " + rs.Fields("Link_SQL").Value + " GROUP BY DayEndStockItemLnk.DayEndStockItemLnk_DayEndID;"); System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor; rs = modReport.getRSreport(ref "SELECT Report.Report_Heading, aCompany.Company_Name FROM aCompany, Report;"); Report.SetParameterValue("txtCompanyName", rs.Fields("Company_Name")); Report.SetParameterValue("txtDayEnd", rs.Fields("Report_Heading")); rs.Close(); rs = modReport.getRSreport(ref "SELECT Link.* From Link Where (((Link.Link_SectionID) = 1)) ORDER BY Link.Link_SectionID;"); if (rs.BOF | rs.EOF) { ReportNone.SetParameterValue("txtCompanyName", Report.ParameterFields("txtCompanyName").ToString); ReportNone.SetParameterValue("txtTitle", Report.ParameterFields("txtTitle").ToString); My.MyProject.Forms.frmReportShow.Text = ReportNone.ParameterFields("txtTitle").ToString; My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = ReportNone; My.MyProject.Forms.frmReportShow.mReport = ReportNone; My.MyProject.Forms.frmReportShow.sMode = "0"; My.MyProject.Forms.frmReportShow.CRViewer1.Refresh(); System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default; My.MyProject.Forms.frmReportShow.ShowDialog(); return; } rsData = modReport.getRSreport(ref "SELECT LinkItem.*, Format([DayEnd_Date],'ddd dd mmm\", \"yyyy') AS dateName, DayEnd.DayEnd_Date FROM DayEnd INNER JOIN LinkItem ON DayEnd.DayEndID = LinkItem.LinkItem_DayEndID;"); if (rsData.BOF | rsData.EOF) { ReportNone.SetParameterValue("txtCompanyName", Report.ParameterFields("txtCompanyName").ToString); ReportNone.SetParameterValue("txtTitle", Report.ParameterFields("txtTitle").ToString); My.MyProject.Forms.frmReportShow.Text = ReportNone.ParameterFields("txtTitle").ToString; My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = ReportNone; My.MyProject.Forms.frmReportShow.mReport = ReportNone; My.MyProject.Forms.frmReportShow.sMode = "0"; My.MyProject.Forms.frmReportShow.CRViewer1.Refresh(); System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default; My.MyProject.Forms.frmReportShow.ShowDialog(); return; } Report.Database.Tables(1).SetDataSource(rs); Report.Database.Tables(2).SetDataSource(rsData); //Report.VerifyOnEveryPrint = True My.MyProject.Forms.frmReportShow.Text = Report.ParameterFields("txtTitle").ToString; My.MyProject.Forms.frmReportShow.CRViewer1.ReportSource = Report; My.MyProject.Forms.frmReportShow.mReport = Report; My.MyProject.Forms.frmReportShow.sMode = "0"; My.MyProject.Forms.frmReportShow.CRViewer1.Refresh(); System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default; My.MyProject.Forms.frmReportShow.ShowDialog(); } private void frmItemGroup_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs) { short KeyAscii = Strings.Asc(eventArgs.KeyChar); if (KeyAscii == 27) { KeyAscii = 0; this.Close(); } eventArgs.KeyChar = Strings.Chr(KeyAscii); if (KeyAscii == 0) { eventArgs.Handled = true; } } private void frmItemGroup_Load(System.Object eventSender, System.EventArgs eventArgs) { modRecordSet.openConnection(); modReport.openConnectionReport(); loadLanguage(); setup(); } } }
// MIT License - Copyright (C) The Mono.Xna Team // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. using System; using System.ComponentModel; using System.Runtime.Serialization; namespace Microsoft.Xna.Framework { /// <summary> /// Contains a collection of <see cref="CurveKey"/> points in 2D space and provides methods for evaluating features of the curve they define. /// </summary> // TODO : [TypeConverter(typeof(ExpandableObjectConverter))] public class Curve { #region Private Fields private CurveKeyCollection _keys; private CurveLoopType _postLoop; private CurveLoopType _preLoop; #endregion #region Public Properties /// <summary> /// Returns <c>true</c> if this curve is constant (has zero or one points); <c>false</c> otherwise. /// </summary> public bool IsConstant { get { return this._keys.Count <= 1; } } /// <summary> /// The collection of curve keys. /// </summary> public CurveKeyCollection Keys { get { return this._keys; } } /// <summary> /// Defines how to handle weighting values that are greater than the last control point in the curve. /// </summary> public CurveLoopType PostLoop { get { return this._postLoop; } set { this._postLoop = value; } } /// <summary> /// Defines how to handle weighting values that are less than the first control point in the curve. /// </summary> public CurveLoopType PreLoop { get { return this._preLoop; } set { this._preLoop = value; } } #endregion #region Public Constructors /// <summary> /// Constructs a curve. /// </summary> public Curve() { this._keys = new CurveKeyCollection(); } #endregion #region Public Methods /// <summary> /// Creates a copy of this curve. /// </summary> /// <returns>A copy of this curve.</returns> public Curve Clone() { Curve curve = new Curve(); curve._keys = this._keys.Clone(); curve._preLoop = this._preLoop; curve._postLoop = this._postLoop; return curve; } /// <summary> /// Evaluate the value at a position of this <see cref="Curve"/>. /// </summary> /// <param name="position">The position on this <see cref="Curve"/>.</param> /// <returns>Value at the position on this <see cref="Curve"/>.</returns> public float Evaluate(float position) { if (_keys.Count == 0) { return 0f; } if (_keys.Count == 1) { return _keys[0].Value; } CurveKey first = _keys[0]; CurveKey last = _keys[_keys.Count - 1]; if (position < first.Position) { switch (this.PreLoop) { case CurveLoopType.Constant: //constant return first.Value; case CurveLoopType.Linear: // linear y = a*x +b with a tangeant of last point return first.Value - first.TangentIn * (first.Position - position); case CurveLoopType.Cycle: //start -> end / start -> end int cycle = GetNumberOfCycle(position); float virtualPos = position - (cycle * (last.Position - first.Position)); return GetCurvePosition(virtualPos); case CurveLoopType.CycleOffset: //make the curve continue (with no step) so must up the curve each cycle of delta(value) cycle = GetNumberOfCycle(position); virtualPos = position - (cycle * (last.Position - first.Position)); return (GetCurvePosition(virtualPos) + cycle * (last.Value - first.Value)); case CurveLoopType.Oscillate: //go back on curve from end and target start // start-> end / end -> start cycle = GetNumberOfCycle(position); if (0 == cycle % 2f)//if pair virtualPos = position - (cycle * (last.Position - first.Position)); else virtualPos = last.Position - position + first.Position + (cycle * (last.Position - first.Position)); return GetCurvePosition(virtualPos); } } else if (position > last.Position) { int cycle; switch (this.PostLoop) { case CurveLoopType.Constant: //constant return last.Value; case CurveLoopType.Linear: // linear y = a*x +b with a tangeant of last point return last.Value + first.TangentOut * (position - last.Position); case CurveLoopType.Cycle: //start -> end / start -> end cycle = GetNumberOfCycle(position); float virtualPos = position - (cycle * (last.Position - first.Position)); return GetCurvePosition(virtualPos); case CurveLoopType.CycleOffset: //make the curve continue (with no step) so must up the curve each cycle of delta(value) cycle = GetNumberOfCycle(position); virtualPos = position - (cycle * (last.Position - first.Position)); return (GetCurvePosition(virtualPos) + cycle * (last.Value - first.Value)); case CurveLoopType.Oscillate: //go back on curve from end and target start // start-> end / end -> start cycle = GetNumberOfCycle(position); virtualPos = position - (cycle * (last.Position - first.Position)); if (0 == cycle % 2f)//if pair virtualPos = position - (cycle * (last.Position - first.Position)); else virtualPos = last.Position - position + first.Position + (cycle * (last.Position - first.Position)); return GetCurvePosition(virtualPos); } } //in curve return GetCurvePosition(position); } /// <summary> /// Computes tangents for all keys in the collection. /// </summary> /// <param name="tangentType">The tangent type for both in and out.</param> public void ComputeTangents (CurveTangent tangentType) { ComputeTangents(tangentType, tangentType); } /// <summary> /// Computes tangents for all keys in the collection. /// </summary> /// <param name="tangentInType">The tangent in-type. <see cref="CurveKey.TangentIn"/> for more details.</param> /// <param name="tangentOutType">The tangent out-type. <see cref="CurveKey.TangentOut"/> for more details.</param> public void ComputeTangents(CurveTangent tangentInType, CurveTangent tangentOutType) { for (var i = 0; i < Keys.Count; ++i) { ComputeTangent(i, tangentInType, tangentOutType); } } /// <summary> /// Computes tangent for the specific key in the collection. /// </summary> /// <param name="keyIndex">The index of a key in the collection.</param> /// <param name="tangentType">The tangent type for both in and out.</param> public void ComputeTangent(int keyIndex, CurveTangent tangentType) { ComputeTangent(keyIndex, tangentType, tangentType); } /// <summary> /// Computes tangent for the specific key in the collection. /// </summary> /// <param name="keyIndex">The index of key in the collection.</param> /// <param name="tangentInType">The tangent in-type. <see cref="CurveKey.TangentIn"/> for more details.</param> /// <param name="tangentOutType">The tangent out-type. <see cref="CurveKey.TangentOut"/> for more details.</param> public void ComputeTangent(int keyIndex, CurveTangent tangentInType, CurveTangent tangentOutType) { // See http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.curvetangent.aspx var key = _keys[keyIndex]; float p0, p, p1; p0 = p = p1 = key.Position; float v0, v, v1; v0 = v = v1 = key.Value; if ( keyIndex > 0 ) { p0 = _keys[keyIndex - 1].Position; v0 = _keys[keyIndex - 1].Value; } if (keyIndex < _keys.Count-1) { p1 = _keys[keyIndex + 1].Position; v1 = _keys[keyIndex + 1].Value; } switch (tangentInType) { case CurveTangent.Flat: key.TangentIn = 0; break; case CurveTangent.Linear: key.TangentIn = v - v0; break; case CurveTangent.Smooth: var pn = p1 - p0; if (Math.Abs(pn) < float.Epsilon) key.TangentIn = 0; else key.TangentIn = (v1 - v0) * ((p - p0) / pn); break; } switch (tangentOutType) { case CurveTangent.Flat: key.TangentOut = 0; break; case CurveTangent.Linear: key.TangentOut = v1 - v; break; case CurveTangent.Smooth: var pn = p1 - p0; if (Math.Abs(pn) < float.Epsilon) key.TangentOut = 0; else key.TangentOut = (v1 - v0) * ((p1 - p) / pn); break; } } #endregion #region Private Methods private int GetNumberOfCycle(float position) { float cycle = (position - _keys[0].Position) / (_keys[_keys.Count - 1].Position - _keys[0].Position); if (cycle < 0f) cycle--; return (int)cycle; } private float GetCurvePosition(float position) { //only for position in curve CurveKey prev = this._keys[0]; CurveKey next; for (int i = 1; i < this._keys.Count; ++i) { next = this.Keys[i]; if (next.Position >= position) { if (prev.Continuity == CurveContinuity.Step) { if (position >= 1f) { return next.Value; } return prev.Value; } float t = (position - prev.Position) / (next.Position - prev.Position);//to have t in [0,1] float ts = t * t; float tss = ts * t; //After a lot of search on internet I have found all about spline function // and bezier (phi'sss ancien) but finaly use hermite curve //http://en.wikipedia.org/wiki/Cubic_Hermite_spline //P(t) = (2*t^3 - 3t^2 + 1)*P0 + (t^3 - 2t^2 + t)m0 + (-2t^3 + 3t^2)P1 + (t^3-t^2)m1 //with P0.value = prev.value , m0 = prev.tangentOut, P1= next.value, m1 = next.TangentIn return (2 * tss - 3 * ts + 1f) * prev.Value + (tss - 2 * ts + t) * prev.TangentOut + (3 * ts - 2 * tss) * next.Value + (tss - ts) * next.TangentIn; } prev = next; } return 0f; } #endregion } }
// // (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. // namespace Revit.SDK.Samples.Truss.CS { /// <summary> /// window form contains one three picture box to show the /// profile of truss geometry and profile and tabControl. /// User can create truss, edit profile of truss and change type of truss members. /// </summary> partial class TrussForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.TrussTypeComboBox = new System.Windows.Forms.ComboBox(); this.TrussGraphicsTabControl = new System.Windows.Forms.TabControl(); this.ViewTabPage = new System.Windows.Forms.TabPage(); this.Notelabel = new System.Windows.Forms.Label(); this.ViewComboBox = new System.Windows.Forms.ComboBox(); this.ViewLabel = new System.Windows.Forms.Label(); this.CreateButton = new System.Windows.Forms.Button(); this.TrussMembersTabPage = new System.Windows.Forms.TabPage(); this.BeamTypeLabel = new System.Windows.Forms.Label(); this.ChangeBeamTypeButton = new System.Windows.Forms.Button(); this.BeamTypeComboBox = new System.Windows.Forms.ComboBox(); this.TrussMembersPictureBox = new System.Windows.Forms.PictureBox(); this.ProfileEditTabPage = new System.Windows.Forms.TabPage(); this.CleanChordbutton = new System.Windows.Forms.Button(); this.BottomChordButton = new System.Windows.Forms.Button(); this.TopChordButton = new System.Windows.Forms.Button(); this.UpdateButton = new System.Windows.Forms.Button(); this.RestoreButton = new System.Windows.Forms.Button(); this.ProfileEditPictureBox = new System.Windows.Forms.PictureBox(); this.TrussTypeLabel = new System.Windows.Forms.Label(); this.CloseButton = new System.Windows.Forms.Button(); this.TrussGraphicsTabControl.SuspendLayout(); this.ViewTabPage.SuspendLayout(); this.TrussMembersTabPage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.TrussMembersPictureBox)).BeginInit(); this.ProfileEditTabPage.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.ProfileEditPictureBox)).BeginInit(); this.SuspendLayout(); // // TrussTypeComboBox // this.TrussTypeComboBox.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend; this.TrussTypeComboBox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; this.TrussTypeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.TrussTypeComboBox.FormattingEnabled = true; this.TrussTypeComboBox.Location = new System.Drawing.Point(84, 6); this.TrussTypeComboBox.Name = "TrussTypeComboBox"; this.TrussTypeComboBox.Size = new System.Drawing.Size(212, 21); this.TrussTypeComboBox.TabIndex = 1; this.TrussTypeComboBox.SelectedIndexChanged += new System.EventHandler(this.TrussTypeComboBox_SelectedIndexChanged); // // TrussGraphicsTabControl // this.TrussGraphicsTabControl.Controls.Add(this.ViewTabPage); this.TrussGraphicsTabControl.Controls.Add(this.TrussMembersTabPage); this.TrussGraphicsTabControl.Controls.Add(this.ProfileEditTabPage); this.TrussGraphicsTabControl.Location = new System.Drawing.Point(12, 41); this.TrussGraphicsTabControl.Name = "TrussGraphicsTabControl"; this.TrussGraphicsTabControl.SelectedIndex = 0; this.TrussGraphicsTabControl.Size = new System.Drawing.Size(404, 343); this.TrussGraphicsTabControl.TabIndex = 2; this.TrussGraphicsTabControl.Selecting += new System.Windows.Forms.TabControlCancelEventHandler(this.TrussGraphicsTabControl_Selecting); this.TrussGraphicsTabControl.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.TrussGraphicsTabControl_KeyPress); // // ViewTabPage // this.ViewTabPage.Controls.Add(this.Notelabel); this.ViewTabPage.Controls.Add(this.ViewComboBox); this.ViewTabPage.Controls.Add(this.ViewLabel); this.ViewTabPage.Controls.Add(this.CreateButton); this.ViewTabPage.Location = new System.Drawing.Point(4, 22); this.ViewTabPage.Name = "ViewTabPage"; this.ViewTabPage.Padding = new System.Windows.Forms.Padding(3); this.ViewTabPage.Size = new System.Drawing.Size(396, 317); this.ViewTabPage.TabIndex = 0; this.ViewTabPage.Text = "Create Truss"; this.ViewTabPage.UseVisualStyleBackColor = true; // // Notelabel // this.Notelabel.AutoSize = true; this.Notelabel.Location = new System.Drawing.Point(6, 17); this.Notelabel.Name = "Notelabel"; this.Notelabel.Size = new System.Drawing.Size(155, 13); this.Notelabel.TabIndex = 5; this.Notelabel.Text = "Select a View to build truss on :"; // // ViewComboBox // this.ViewComboBox.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend; this.ViewComboBox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; this.ViewComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.ViewComboBox.FormattingEnabled = true; this.ViewComboBox.Location = new System.Drawing.Point(48, 57); this.ViewComboBox.Name = "ViewComboBox"; this.ViewComboBox.Size = new System.Drawing.Size(236, 21); this.ViewComboBox.TabIndex = 4; this.ViewComboBox.SelectedIndexChanged += new System.EventHandler(this.ViewComboBox_SelectedIndexChanged); // // ViewLabel // this.ViewLabel.AutoSize = true; this.ViewLabel.Location = new System.Drawing.Point(6, 60); this.ViewLabel.Name = "ViewLabel"; this.ViewLabel.Size = new System.Drawing.Size(36, 13); this.ViewLabel.TabIndex = 3; this.ViewLabel.Text = "View :"; // // CreateButton // this.CreateButton.Location = new System.Drawing.Point(301, 55); this.CreateButton.Name = "CreateButton"; this.CreateButton.Size = new System.Drawing.Size(80, 23); this.CreateButton.TabIndex = 2; this.CreateButton.Text = "&Create Truss"; this.CreateButton.UseVisualStyleBackColor = true; this.CreateButton.Click += new System.EventHandler(this.CreateButton_Click); // // TrussMembersTabPage // this.TrussMembersTabPage.Controls.Add(this.BeamTypeLabel); this.TrussMembersTabPage.Controls.Add(this.ChangeBeamTypeButton); this.TrussMembersTabPage.Controls.Add(this.BeamTypeComboBox); this.TrussMembersTabPage.Controls.Add(this.TrussMembersPictureBox); this.TrussMembersTabPage.Location = new System.Drawing.Point(4, 22); this.TrussMembersTabPage.Name = "TrussMembersTabPage"; this.TrussMembersTabPage.Padding = new System.Windows.Forms.Padding(3); this.TrussMembersTabPage.Size = new System.Drawing.Size(396, 317); this.TrussMembersTabPage.TabIndex = 1; this.TrussMembersTabPage.Text = "Truss Members"; this.TrussMembersTabPage.UseVisualStyleBackColor = true; // // BeamTypeLabel // this.BeamTypeLabel.AutoSize = true; this.BeamTypeLabel.Location = new System.Drawing.Point(6, 291); this.BeamTypeLabel.Name = "BeamTypeLabel"; this.BeamTypeLabel.Size = new System.Drawing.Size(67, 13); this.BeamTypeLabel.TabIndex = 3; this.BeamTypeLabel.Text = "Beam Type :"; // // ChangeBeamTypeButton // this.ChangeBeamTypeButton.Enabled = false; this.ChangeBeamTypeButton.Location = new System.Drawing.Point(309, 288); this.ChangeBeamTypeButton.Name = "ChangeBeamTypeButton"; this.ChangeBeamTypeButton.Size = new System.Drawing.Size(81, 21); this.ChangeBeamTypeButton.TabIndex = 2; this.ChangeBeamTypeButton.Text = "Change Type"; this.ChangeBeamTypeButton.UseVisualStyleBackColor = true; this.ChangeBeamTypeButton.Click += new System.EventHandler(this.ChangeBeamTypeButton_Click); // // BeamTypeComboBox // this.BeamTypeComboBox.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend; this.BeamTypeComboBox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; this.BeamTypeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.BeamTypeComboBox.Enabled = false; this.BeamTypeComboBox.FormattingEnabled = true; this.BeamTypeComboBox.Location = new System.Drawing.Point(79, 288); this.BeamTypeComboBox.Name = "BeamTypeComboBox"; this.BeamTypeComboBox.Size = new System.Drawing.Size(217, 21); this.BeamTypeComboBox.TabIndex = 1; this.BeamTypeComboBox.SelectedIndexChanged += new System.EventHandler(this.BeamTypeComboBox_SelectedIndexChanged); // // TrussMembersPictureBox // this.TrussMembersPictureBox.Location = new System.Drawing.Point(7, 7); this.TrussMembersPictureBox.Name = "TrussMembersPictureBox"; this.TrussMembersPictureBox.Size = new System.Drawing.Size(384, 274); this.TrussMembersPictureBox.TabIndex = 0; this.TrussMembersPictureBox.TabStop = false; this.TrussMembersPictureBox.MouseMove += new System.Windows.Forms.MouseEventHandler(this.TrussGeometryPictureBox_MouseMove); this.TrussMembersPictureBox.Paint += new System.Windows.Forms.PaintEventHandler(this.TrussGeometryPictureBox_Paint); this.TrussMembersPictureBox.MouseClick += new System.Windows.Forms.MouseEventHandler(this.TrussGeometryPictureBox_MouseClick); // // ProfileEditTabPage // this.ProfileEditTabPage.Controls.Add(this.CleanChordbutton); this.ProfileEditTabPage.Controls.Add(this.BottomChordButton); this.ProfileEditTabPage.Controls.Add(this.TopChordButton); this.ProfileEditTabPage.Controls.Add(this.UpdateButton); this.ProfileEditTabPage.Controls.Add(this.RestoreButton); this.ProfileEditTabPage.Controls.Add(this.ProfileEditPictureBox); this.ProfileEditTabPage.Location = new System.Drawing.Point(4, 22); this.ProfileEditTabPage.Name = "ProfileEditTabPage"; this.ProfileEditTabPage.Size = new System.Drawing.Size(396, 317); this.ProfileEditTabPage.TabIndex = 2; this.ProfileEditTabPage.Text = "Profile Edit"; this.ProfileEditTabPage.UseVisualStyleBackColor = true; // // CleanChordbutton // this.CleanChordbutton.Location = new System.Drawing.Point(177, 286); this.CleanChordbutton.Name = "CleanChordbutton"; this.CleanChordbutton.Size = new System.Drawing.Size(51, 23); this.CleanChordbutton.TabIndex = 8; this.CleanChordbutton.Text = "&Clean"; this.CleanChordbutton.UseVisualStyleBackColor = true; this.CleanChordbutton.Click += new System.EventHandler(this.CleanChordbutton_Click); // // BottomChordButton // this.BottomChordButton.Location = new System.Drawing.Point(88, 286); this.BottomChordButton.Name = "BottomChordButton"; this.BottomChordButton.Size = new System.Drawing.Size(83, 23); this.BottomChordButton.TabIndex = 7; this.BottomChordButton.Text = "&Bottom Chord"; this.BottomChordButton.UseVisualStyleBackColor = true; this.BottomChordButton.Click += new System.EventHandler(this.BottomChordButton_Click); // // TopChordButton // this.TopChordButton.Location = new System.Drawing.Point(7, 286); this.TopChordButton.Name = "TopChordButton"; this.TopChordButton.Size = new System.Drawing.Size(75, 23); this.TopChordButton.TabIndex = 6; this.TopChordButton.Text = "&Top Chord"; this.TopChordButton.UseVisualStyleBackColor = true; this.TopChordButton.Click += new System.EventHandler(this.TopChordButton_Click); // // UpdateButton // this.UpdateButton.Location = new System.Drawing.Point(315, 287); this.UpdateButton.Name = "UpdateButton"; this.UpdateButton.Size = new System.Drawing.Size(75, 23); this.UpdateButton.TabIndex = 5; this.UpdateButton.Text = "&Update"; this.UpdateButton.UseVisualStyleBackColor = true; this.UpdateButton.Click += new System.EventHandler(this.UpdateButton_Click); // // RestoreButton // this.RestoreButton.Location = new System.Drawing.Point(234, 287); this.RestoreButton.Name = "RestoreButton"; this.RestoreButton.Size = new System.Drawing.Size(75, 23); this.RestoreButton.TabIndex = 4; this.RestoreButton.Text = "&Restore"; this.RestoreButton.UseVisualStyleBackColor = true; this.RestoreButton.Click += new System.EventHandler(this.RestoreButton_Click); // // ProfileEditPictureBox // this.ProfileEditPictureBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.ProfileEditPictureBox.Cursor = System.Windows.Forms.Cursors.Default; this.ProfileEditPictureBox.Location = new System.Drawing.Point(7, 6); this.ProfileEditPictureBox.Name = "ProfileEditPictureBox"; this.ProfileEditPictureBox.Size = new System.Drawing.Size(384, 274); this.ProfileEditPictureBox.TabIndex = 3; this.ProfileEditPictureBox.TabStop = false; this.ProfileEditPictureBox.MouseMove += new System.Windows.Forms.MouseEventHandler(this.ProfileEditPictureBox_MouseMove); this.ProfileEditPictureBox.Paint += new System.Windows.Forms.PaintEventHandler(this.ProfileEditPictureBox_Paint); this.ProfileEditPictureBox.MouseClick += new System.Windows.Forms.MouseEventHandler(this.ProfileEditPictureBox_MouseClick); // // TrussTypeLabel // this.TrussTypeLabel.AutoSize = true; this.TrussTypeLabel.Location = new System.Drawing.Point(12, 9); this.TrussTypeLabel.Name = "TrussTypeLabel"; this.TrussTypeLabel.Size = new System.Drawing.Size(66, 13); this.TrussTypeLabel.TabIndex = 3; this.TrussTypeLabel.Text = "Truss Type :"; // // CloseButton // this.CloseButton.Location = new System.Drawing.Point(337, 390); this.CloseButton.Name = "CloseButton"; this.CloseButton.Size = new System.Drawing.Size(80, 23); this.CloseButton.TabIndex = 4; this.CloseButton.Text = "&Close"; this.CloseButton.UseVisualStyleBackColor = true; this.CloseButton.Click += new System.EventHandler(this.CloseButton_Click); // // TrussForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.CloseButton; this.ClientSize = new System.Drawing.Size(426, 420); this.Controls.Add(this.CloseButton); this.Controls.Add(this.TrussTypeLabel); this.Controls.Add(this.TrussGraphicsTabControl); this.Controls.Add(this.TrussTypeComboBox); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "TrussForm"; this.ShowInTaskbar = false; this.Text = "TrussForm"; this.Load += new System.EventHandler(this.TrussForm_Load); this.TrussGraphicsTabControl.ResumeLayout(false); this.ViewTabPage.ResumeLayout(false); this.ViewTabPage.PerformLayout(); this.TrussMembersTabPage.ResumeLayout(false); this.TrussMembersTabPage.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.TrussMembersPictureBox)).EndInit(); this.ProfileEditTabPage.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.ProfileEditPictureBox)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ComboBox TrussTypeComboBox; private System.Windows.Forms.TabControl TrussGraphicsTabControl; private System.Windows.Forms.TabPage ViewTabPage; private System.Windows.Forms.TabPage TrussMembersTabPage; private System.Windows.Forms.TabPage ProfileEditTabPage; private System.Windows.Forms.Button CreateButton; private System.Windows.Forms.PictureBox TrussMembersPictureBox; private System.Windows.Forms.Button UpdateButton; private System.Windows.Forms.Button RestoreButton; private System.Windows.Forms.PictureBox ProfileEditPictureBox; private System.Windows.Forms.Label TrussTypeLabel; private System.Windows.Forms.Button TopChordButton; private System.Windows.Forms.Button BottomChordButton; private System.Windows.Forms.Button CleanChordbutton; private System.Windows.Forms.Button ChangeBeamTypeButton; private System.Windows.Forms.ComboBox BeamTypeComboBox; private System.Windows.Forms.Label BeamTypeLabel; private System.Windows.Forms.ComboBox ViewComboBox; private System.Windows.Forms.Label ViewLabel; private System.Windows.Forms.Label Notelabel; private System.Windows.Forms.Button CloseButton; } }
// 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.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Tagging { /// <summary> /// Base type of all asynchronous tagger providers (<see cref="ITaggerProvider"/> and <see cref="IViewTaggerProvider"/>). /// </summary> internal abstract partial class AbstractAsynchronousTaggerProvider<TTag> where TTag : ITag { private readonly object _uniqueKey = new object(); private readonly IAsynchronousOperationListener _asyncListener; private readonly IForegroundNotificationService _notificationService; /// <summary> /// The behavior the tagger engine will have when text changes happen to the subject buffer /// it is attached to. Most taggers can simply use <see cref="TaggerTextChangeBehavior.None"/>. /// However, advanced taggers that want to perform specialized behavior depending on what has /// actually changed in the file can specify <see cref="TaggerTextChangeBehavior.TrackTextChanges"/>. /// /// If this is specified the tagger engine will track text changes and pass them along as /// <see cref="TaggerContext{TTag}.TextChangeRange"/> when calling /// <see cref="ProduceTagsAsync(TaggerContext{TTag})"/>. /// </summary> protected virtual TaggerTextChangeBehavior TextChangeBehavior => TaggerTextChangeBehavior.None; /// <summary> /// The bahavior the tagger will have when changes happen to the caret. /// </summary> protected virtual TaggerCaretChangeBehavior CaretChangeBehavior => TaggerCaretChangeBehavior.None; /// <summary> /// The behavior of tags that are created by the async tagger. This will matter for tags /// created for a previous version of a document that are mapped forward by the async /// tagging architecture. This value cannot be <see cref="SpanTrackingMode.Custom"/>. /// </summary> protected virtual SpanTrackingMode SpanTrackingMode => SpanTrackingMode.EdgeExclusive; /// <summary> /// Comparer used to determine if two <see cref="ITag"/>s are the same. This is used by /// the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> to determine if a previous set of /// computed tags and a current set of computed tags should be considered the same or not. /// If they are the same, then the UI will not be updated. If they are different then /// the UI will be updated for sets of tags that have been removed or added. /// </summary> protected virtual IEqualityComparer<TTag> TagComparer => EqualityComparer<TTag>.Default; /// <summary> /// Options controlling this tagger. The tagger infrastructure will check this option /// against the buffer it is associated with to see if it should tag or not. /// /// An empty enumerable, or null, can be returned to indicate that this tagger should /// run unconditionally. /// </summary> protected virtual IEnumerable<Option<bool>> Options => SpecializedCollections.EmptyEnumerable<Option<bool>>(); protected virtual IEnumerable<PerLanguageOption<bool>> PerLanguageOptions => SpecializedCollections.EmptyEnumerable<PerLanguageOption<bool>>(); protected AbstractAsynchronousTaggerProvider( IAsynchronousOperationListener asyncListener, IForegroundNotificationService notificationService) { this._asyncListener = asyncListener; this._notificationService = notificationService; } private TagSource CreateTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer) { return new TagSource(textViewOpt, subjectBuffer, this, _asyncListener, _notificationService); } internal IAccurateTagger<T> GetOrCreateTagger<T>(ITextView textViewOpt, ITextBuffer subjectBuffer) where T : ITag { if (!subjectBuffer.GetOption(EditorComponentOnOffOptions.Tagger)) { return null; } var tagSource = GetOrCreateTagSource(textViewOpt, subjectBuffer); return tagSource == null ? null : new Tagger(this._asyncListener, this._notificationService, tagSource, subjectBuffer) as IAccurateTagger<T>; } private TagSource GetOrCreateTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer) { TagSource tagSource; if (!this.TryRetrieveTagSource(textViewOpt, subjectBuffer, out tagSource)) { tagSource = this.CreateTagSource(textViewOpt, subjectBuffer); if (tagSource == null) { return null; } this.StoreTagSource(textViewOpt, subjectBuffer, tagSource); tagSource.Disposed += (s, e) => this.RemoveTagSource(textViewOpt, subjectBuffer); } return tagSource; } private bool TryRetrieveTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer, out TagSource tagSource) { return textViewOpt != null ? textViewOpt.TryGetPerSubjectBufferProperty(subjectBuffer, _uniqueKey, out tagSource) : subjectBuffer.Properties.TryGetProperty(_uniqueKey, out tagSource); } private void RemoveTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer) { if (textViewOpt != null) { textViewOpt.RemovePerSubjectBufferProperty<TagSource, ITextView>(subjectBuffer, _uniqueKey); } else { subjectBuffer.Properties.RemoveProperty(_uniqueKey); } } private void StoreTagSource(ITextView textViewOpt, ITextBuffer subjectBuffer, TagSource tagSource) { if (textViewOpt != null) { textViewOpt.AddPerSubjectBufferProperty(subjectBuffer, _uniqueKey, tagSource); } else { subjectBuffer.Properties.AddProperty(_uniqueKey, tagSource); } } /// <summary> /// Called by the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> infrastructure to /// determine the caret position. This value will be passed in as the value to /// <see cref="TaggerContext{TTag}.CaretPosition"/> in the call to /// <see cref="ProduceTagsAsync(TaggerContext{TTag})"/>. /// </summary> protected virtual SnapshotPoint? GetCaretPoint(ITextView textViewOpt, ITextBuffer subjectBuffer) { return textViewOpt?.GetCaretPoint(subjectBuffer); } /// <summary> /// Called by the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> infrastructure to determine /// the set of spans that it should asynchronously tag. This will be called in response to /// notifications from the <see cref="ITaggerEventSource"/> that something has changed, and /// will only be called from the UI thread. The tagger infrastructure will then determine /// the <see cref="DocumentSnapshotSpan"/>s associated with these <see cref="SnapshotSpan"/>s /// and will asycnhronously call into <see cref="ProduceTagsAsync(TaggerContext{TTag})"/> at some point in /// the future to produce tags for these spans. /// </summary> protected virtual IEnumerable<SnapshotSpan> GetSpansToTag(ITextView textViewOpt, ITextBuffer subjectBuffer) { // For a standard tagger, the spans to tag is the span of the entire snapshot. return new[] { subjectBuffer.CurrentSnapshot.GetFullSpan() }; } /// <summary> /// Creates the <see cref="ITaggerEventSource"/> that notifies the <see cref="AbstractAsynchronousTaggerProvider{TTag}"/> /// that it should recompute tags for the text buffer after an appropriate <see cref="TaggerDelay"/>. /// </summary> protected abstract ITaggerEventSource CreateEventSource(ITextView textViewOpt, ITextBuffer subjectBuffer); internal Task ProduceTagsAsync_ForTestingPurposesOnly(TaggerContext<TTag> context) { return ProduceTagsAsync(context); } /// <summary> /// Produce tags for the given context. /// </summary> protected virtual async Task ProduceTagsAsync(TaggerContext<TTag> context) { foreach (var spanToTag in context.SpansToTag) { context.CancellationToken.ThrowIfCancellationRequested(); await ProduceTagsAsync(context, spanToTag, GetCaretPosition(context.CaretPosition, spanToTag.SnapshotSpan)).ConfigureAwait(false); } } private static int? GetCaretPosition(SnapshotPoint? caretPosition, SnapshotSpan snapshotSpan) { return caretPosition.HasValue && caretPosition.Value.Snapshot == snapshotSpan.Snapshot ? caretPosition.Value.Position : (int?)null; } protected virtual Task ProduceTagsAsync(TaggerContext<TTag> context, DocumentSnapshotSpan spanToTag, int? caretPosition) { return SpecializedTasks.EmptyTask; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.ExceptionServices; using System.Runtime.Remoting; using System.Text; using System.Threading.Tasks; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.TestingHost.Utils; namespace Orleans.TestingHost { /// <summary> /// A host class for local testing with Orleans using in-process silos. /// Runs a Primary and optionally secondary silos in seperate app domains, and client in the main app domain. /// Additional silos can also be started in-process on demand if required for particular test cases. /// </summary> /// <remarks> /// Make sure that your test project references your test grains and test grain interfaces /// projects, and has CopyLocal=True set on those references [which should be the default]. /// </remarks> public class TestCluster { public SiloHandle Primary { get; private set; } public IReadOnlyList<SiloHandle> SecondarySilos => this.additionalSilos; protected readonly List<SiloHandle> additionalSilos = new List<SiloHandle>(); protected readonly Dictionary<string, byte[]> additionalAssemblies = new Dictionary<string, byte[]>(); public ClientConfiguration ClientConfiguration { get; private set; } public ClusterConfiguration ClusterConfiguration { get; private set; } private readonly StringBuilder log = new StringBuilder(); public string DeploymentId => this.ClusterConfiguration.Globals.DeploymentId; public IGrainFactory GrainFactory { get; private set; } protected Logger logger => GrainClient.Logger; /// <summary> /// Configure the default Primary test silo, plus client in-process. /// </summary> public TestCluster() : this(new TestClusterOptions()) { } /// <summary> /// Configures the test cluster plus client in-process. /// </summary> public TestCluster(TestClusterOptions options) : this(options.ClusterConfiguration, options.ClientConfiguration) { } /// <summary> /// Configures the test cluster plus default client in-process. /// </summary> public TestCluster(ClusterConfiguration clusterConfiguration) : this(clusterConfiguration, TestClusterOptions.BuildClientConfiguration(clusterConfiguration)) { } /// <summary> /// Configures the test cluster plus client in-process, /// using the specified silo and client config configurations. /// </summary> public TestCluster(ClusterConfiguration clusterConfiguration, ClientConfiguration clientConfiguration) { this.ClusterConfiguration = clusterConfiguration; this.ClientConfiguration = clientConfiguration; } /// <summary> /// Deploys the cluster using the specified configuration and starts the client in-process. /// It will start all the silos defined in the <see cref="Runtime.Configuration.ClusterConfiguration.Overrides"/> collection. /// </summary> public void Deploy() { this.Deploy(this.ClusterConfiguration.Overrides.Keys); } /// <summary> /// Deploys the cluster using the specified configuration and starts the client in-process. /// </summary> /// <param name="siloNames">Only deploy the specified silos which must also be present in the <see cref="Runtime.Configuration.ClusterConfiguration.Overrides"/> collection.</param> public void Deploy(IEnumerable<string> siloNames) { try { DeployAsync(siloNames).Wait(); } catch (AggregateException ex) { if (ex.InnerExceptions.Count > 1) throw; ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); } } /// <summary> /// Deploys the cluster using the specified configuration and starts the client in-process. /// </summary> /// <param name="siloNames">Only deploy the specified silos which must also be present in the <see cref="Runtime.Configuration.ClusterConfiguration.Overrides"/> collection.</param> public async Task DeployAsync(IEnumerable<string> siloNames) { if (Primary != null) throw new InvalidOperationException("Cluster host already deployed."); AppDomain.CurrentDomain.UnhandledException += ReportUnobservedException; try { string startMsg = "----------------------------- STARTING NEW UNIT TEST SILO HOST: " + GetType().FullName + " -------------------------------------"; WriteLog(startMsg); await InitializeAsync(siloNames); } catch (TimeoutException te) { FlushLogToConsole(); throw new TimeoutException("Timeout during test initialization", te); } catch (Exception ex) { StopAllSilos(); Exception baseExc = ex.GetBaseException(); FlushLogToConsole(); if (baseExc is TimeoutException) { throw new TimeoutException("Timeout during test initialization", ex); } // IMPORTANT: // Do NOT re-throw the original exception here, also not as an internal exception inside AggregateException // Due to the way MS tests works, if the original exception is an Orleans exception, // it's assembly might not be loaded yet in this phase of the test. // As a result, we will get "MSTest: Unit Test Adapter threw exception: Type is not resolved for member XXX" // and will loose the original exception. This makes debugging tests super hard! // The root cause has to do with us initializing our tests from Test constructor and not from TestInitialize method. // More details: http://dobrzanski.net/2010/09/20/mstest-unit-test-adapter-threw-exception-type-is-not-resolved-for-member/ //throw new Exception( // string.Format("Exception during test initialization: {0}", // TraceLogger.PrintException(baseExc))); throw; } } /// <summary> /// Get the list of current active silos. /// </summary> /// <returns>List of current silos.</returns> public IEnumerable<SiloHandle> GetActiveSilos() { WriteLog("GetActiveSilos: Primary={0} + {1} Additional={2}", Primary, additionalSilos.Count, Runtime.Utils.EnumerableToString(additionalSilos)); if (Primary?.Silo != null) yield return Primary; if (additionalSilos.Count > 0) foreach (var s in additionalSilos) if (s?.Silo != null) yield return s; } /// <summary> /// Find the silo handle for the specified silo address. /// </summary> /// <param name="siloAddress">Silo address to be found.</param> /// <returns>SiloHandle of the appropriate silo, or <c>null</c> if not found.</returns> public SiloHandle GetSiloForAddress(SiloAddress siloAddress) { List<SiloHandle> activeSilos = GetActiveSilos().ToList(); var ret = activeSilos.FirstOrDefault(s => s.Silo.SiloAddress.Equals(siloAddress)); return ret; } /// <summary> /// Wait for the silo liveness sub-system to detect and act on any recent cluster membership changes. /// </summary> /// <param name="didKill">Whether recent membership changes we done by graceful Stop.</param> public async Task WaitForLivenessToStabilizeAsync(bool didKill = false) { TimeSpan stabilizationTime = GetLivenessStabilizationTime(this.ClusterConfiguration.Globals, didKill); WriteLog(Environment.NewLine + Environment.NewLine + "WaitForLivenessToStabilize is about to sleep for {0}", stabilizationTime); await Task.Delay(stabilizationTime); WriteLog("WaitForLivenessToStabilize is done sleeping"); } private static TimeSpan GetLivenessStabilizationTime(GlobalConfiguration global, bool didKill = false) { TimeSpan stabilizationTime = TimeSpan.Zero; if (didKill) { // in case of hard kill (kill and not Stop), we should give silos time to detect failures first. stabilizationTime = TestingUtils.Multiply(global.ProbeTimeout, global.NumMissedProbesLimit); } if (global.UseLivenessGossip) { stabilizationTime += TimeSpan.FromSeconds(5); } else { stabilizationTime += TestingUtils.Multiply(global.TableRefreshTimeout, 2); } return stabilizationTime; } /// <summary> /// Start an additional silo, so that it joins the existing cluster. /// </summary> /// <returns>SiloHandle for the newly started silo.</returns> public SiloHandle StartAdditionalSilo() { var clusterConfig = this.ClusterConfiguration; short instanceNumber = (short)clusterConfig.Overrides.Count; var defaultNode = clusterConfig.Defaults; int baseSiloPort = defaultNode.Port; int baseGatewayPort = defaultNode.ProxyGatewayEndpoint.Port; var nodeConfig = TestClusterOptions.AddNodeConfiguration( this.ClusterConfiguration, Silo.SiloType.Secondary, instanceNumber, baseSiloPort, baseGatewayPort); SiloHandle instance = StartOrleansSilo( Silo.SiloType.Secondary, this.ClusterConfiguration, nodeConfig); additionalSilos.Add(instance); return instance; } /// <summary> /// Start a number of additional silo, so that they join the existing cluster. /// </summary> /// <param name="numExtraSilos">Number of additional silos to start.</param> /// <returns>List of SiloHandles for the newly started silos.</returns> public List<SiloHandle> StartAdditionalSilos(int numExtraSilos) { List<SiloHandle> instances = new List<SiloHandle>(); for (int i = 0; i < numExtraSilos; i++) { SiloHandle instance = StartAdditionalSilo(); instances.Add(instance); } return instances; } /// <summary> /// Stop any additional silos, not including the default Primary silo. /// </summary> public void StopSecondarySilos() { foreach (SiloHandle instance in this.additionalSilos.ToList()) { StopSilo(instance); } } /// <summary> /// Stops the default Primary silo. /// </summary> public void StopPrimarySilo() { try { GrainClient.Uninitialize(); } catch (Exception exc) { WriteLog("Exception Uninitializing grain client: {0}", exc); } StopSilo(Primary); } /// <summary> /// Stop all current silos. /// </summary> public void StopAllSilos() { StopSecondarySilos(); StopPrimarySilo(); AppDomain.CurrentDomain.UnhandledException -= ReportUnobservedException; } /// <summary> /// Do a semi-graceful Stop of the specified silo. /// </summary> /// <param name="instance">Silo to be stopped.</param> public void StopSilo(SiloHandle instance) { if (instance != null) { StopOrleansSilo(instance, true); if (Primary == instance) { Primary = null; } else { additionalSilos.Remove(instance); } } } /// <summary> /// Do an immediate Kill of the specified silo. /// </summary> /// <param name="instance">Silo to be killed.</param> public void KillSilo(SiloHandle instance) { if (instance != null) { // do NOT stop, just kill directly, to simulate crash. StopOrleansSilo(instance, false); } } /// <summary> /// Performs a hard kill on client. Client will not cleanup resources. /// </summary> public void KillClient() { GrainClient.HardKill(); } /// <summary> /// Do a Stop or Kill of the specified silo, followed by a restart. /// </summary> /// <param name="instance">Silo to be restarted.</param> public SiloHandle RestartSilo(SiloHandle instance) { if (instance != null) { var type = instance.Silo.Type; var siloName = instance.Name; StopSilo(instance); var newInstance = StartOrleansSilo(type, this.ClusterConfiguration, this.ClusterConfiguration.Overrides[siloName]); if (type == Silo.SiloType.Primary && siloName == Silo.PrimarySiloName) { Primary = newInstance; } else { additionalSilos.Add(newInstance); } return newInstance; } return null; } /// <summary> /// Restart a previously stopped. /// </summary> /// <param name="siloName">Silo to be restarted.</param> public SiloHandle RestartStoppedSecondarySilo(string siloName) { if (siloName == null) throw new ArgumentNullException(nameof(siloName)); var newInstance = StartOrleansSilo(Silo.SiloType.Secondary, this.ClusterConfiguration, this.ClusterConfiguration.Overrides[siloName]); additionalSilos.Add(newInstance); return newInstance; } #region Private methods /// <summary> /// Imports assemblies generated by runtime code generation from the provided silo. /// </summary> /// <param name="siloHandle">The silo.</param> private void ImportGeneratedAssemblies(SiloHandle siloHandle) { var generatedAssemblies = TryGetGeneratedAssemblies(siloHandle); if (generatedAssemblies != null) { foreach (var assembly in generatedAssemblies) { // If we have never seen generated code for this assembly before, or generated code might be // newer, store it for later silo creation. byte[] existing; if (!this.additionalAssemblies.TryGetValue(assembly.Key, out existing) || assembly.Value != null) { this.additionalAssemblies[assembly.Key] = assembly.Value; } } } } private Dictionary<string, byte[]> TryGetGeneratedAssemblies(SiloHandle siloHandle) { var tryToRetrieveGeneratedAssemblies = Task.Run(() => { try { var silo = siloHandle.Silo; if (silo?.TestHook != null) { var generatedAssemblies = new Silo.TestHooks.GeneratedAssemblies(); silo.TestHook.UpdateGeneratedAssemblies(generatedAssemblies); return generatedAssemblies.Assemblies; } } catch (Exception exc) { WriteLog("UpdateGeneratedAssemblies threw an exception. Ignoring it. Exception: {0}", exc); } return null; }); // best effort to try to import generated assemblies, otherwise move on. if (tryToRetrieveGeneratedAssemblies.Wait(TimeSpan.FromSeconds(3))) { return tryToRetrieveGeneratedAssemblies.Result; } return null; } public void InitializeClient() { WriteLog("Initializing Grain Client"); ClientConfiguration clientConfig = this.ClientConfiguration; if (Debugger.IsAttached) { // Test is running inside debugger - Make timeout ~= infinite clientConfig.ResponseTimeout = TimeSpan.FromMilliseconds(1000000); } GrainClient.Initialize(clientConfig); GrainFactory = GrainClient.GrainFactory; } private async Task InitializeAsync(IEnumerable<string> siloNames) { var silos = siloNames.ToList(); foreach (var siloName in silos) { if (!this.ClusterConfiguration.Overrides.Keys.Contains(siloName)) { throw new ArgumentOutOfRangeException(nameof(siloNames), $"Silo name {siloName} does not exist in the ClusterConfiguration.Overrides collection"); } } if (silos.Contains(Silo.PrimarySiloName)) { Primary = StartOrleansSilo(Silo.SiloType.Primary, this.ClusterConfiguration, this.ClusterConfiguration.Overrides[Silo.PrimarySiloName]); } var secondarySiloNames = silos.Where(name => !string.Equals(Silo.PrimarySiloName, name)).ToList(); if (secondarySiloNames.Count > 0) { var siloStartTasks = secondarySiloNames.Select(siloName => { return Task.Run(() => StartOrleansSilo(Silo.SiloType.Secondary, this.ClusterConfiguration, this.ClusterConfiguration.Overrides[siloName])); }).ToList(); try { await Task.WhenAll(siloStartTasks); } catch (Exception) { this.additionalSilos.AddRange(siloStartTasks.Where(t => t.Exception != null).Select(t => t.Result)); throw; } this.additionalSilos.AddRange(siloStartTasks.Select(t => t.Result)); } WriteLog("Done initializing cluster"); if (this.ClientConfiguration != null) { InitializeClient(); } } private SiloHandle StartOrleansSilo(Silo.SiloType type, ClusterConfiguration clusterConfig, NodeConfiguration nodeConfig) { return StartOrleansSilo(this, type, clusterConfig, nodeConfig); } public static SiloHandle StartOrleansSilo(TestCluster cluster, Silo.SiloType type, ClusterConfiguration clusterConfig, NodeConfiguration nodeConfig) { if (cluster == null) throw new ArgumentNullException(nameof(cluster)); var siloName = nodeConfig.SiloName; cluster.WriteLog("Starting a new silo in app domain {0} with config {1}", siloName, clusterConfig.ToString(siloName)); AppDomain appDomain; Silo silo = cluster.LoadSiloInNewAppDomain(siloName, type, clusterConfig, out appDomain); silo.Start(); SiloHandle retValue = new SiloHandle { Name = siloName, Silo = silo, NodeConfiguration = nodeConfig, Endpoint = silo.SiloAddress.Endpoint, AppDomain = appDomain, }; cluster.ImportGeneratedAssemblies(retValue); return retValue; } private void StopOrleansSilo(SiloHandle instance, bool stopGracefully) { var silo = instance.Silo; if (stopGracefully) { try { silo?.Shutdown(); } catch (RemotingException re) { WriteLog(re); /* Ignore error */ } catch (Exception exc) { WriteLog(exc); throw; } } ImportGeneratedAssemblies(instance); try { UnloadSiloInAppDomain(instance.AppDomain); } catch (Exception exc) { WriteLog(exc); throw; } instance.AppDomain = null; instance.Silo = null; instance.Process = null; } private Silo LoadSiloInNewAppDomain(string siloName, Silo.SiloType type, ClusterConfiguration config, out AppDomain appDomain) { AppDomainSetup setup = GetAppDomainSetupInfo(); appDomain = AppDomain.CreateDomain(siloName, null, setup); // Load each of the additional assemblies. Silo.TestHooks.CodeGeneratorOptimizer optimizer = null; foreach (var assembly in this.additionalAssemblies.Where(asm => asm.Value != null)) { if (optimizer == null) { optimizer = (Silo.TestHooks.CodeGeneratorOptimizer) appDomain.CreateInstanceFromAndUnwrap( "OrleansRuntime.dll", typeof(Silo.TestHooks.CodeGeneratorOptimizer).FullName, false, BindingFlags.Default, null, null, CultureInfo.CurrentCulture, new object[] { }); } optimizer.AddCachedAssembly(assembly.Key, assembly.Value); } var args = new object[] { siloName, type, config }; var silo = (Silo)appDomain.CreateInstanceFromAndUnwrap( "OrleansRuntime.dll", typeof(Silo).FullName, false, BindingFlags.Default, null, args, CultureInfo.CurrentCulture, new object[] { }); appDomain.UnhandledException += ReportUnobservedException; return silo; } private void UnloadSiloInAppDomain(AppDomain appDomain) { if (appDomain != null) { appDomain.UnhandledException -= ReportUnobservedException; AppDomain.Unload(appDomain); } } private static AppDomainSetup GetAppDomainSetupInfo() { AppDomain currentAppDomain = AppDomain.CurrentDomain; return new AppDomainSetup { ApplicationBase = Environment.CurrentDirectory, ConfigurationFile = currentAppDomain.SetupInformation.ConfigurationFile, ShadowCopyFiles = currentAppDomain.SetupInformation.ShadowCopyFiles, ShadowCopyDirectories = currentAppDomain.SetupInformation.ShadowCopyDirectories, CachePath = currentAppDomain.SetupInformation.CachePath }; } #endregion #region Tracing helper functions private static void ReportUnobservedException(object sender, UnhandledExceptionEventArgs eventArgs) { Exception exception = (Exception)eventArgs.ExceptionObject; // WriteLog("Unobserved exception: {0}", exception); } private void WriteLog(string format, params object[] args) { log.AppendFormat(format + Environment.NewLine, args); } private void FlushLogToConsole() { Console.WriteLine(log.ToString()); } private void WriteLog(object value) { WriteLog(value.ToString()); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Net.Security; using System.Runtime.CompilerServices; using System.Runtime.InteropServices.WindowsRuntime; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Threading.Tasks; using Windows.Foundation.Metadata; using Windows.Networking.Sockets; using Windows.Storage.Streams; using Windows.Web; using RTCertificate = Windows.Security.Cryptography.Certificates.Certificate; using RTCertificateQuery = Windows.Security.Cryptography.Certificates.CertificateQuery; using RTCertificateStores = Windows.Security.Cryptography.Certificates.CertificateStores; using RTWebSocketError = Windows.Networking.Sockets.WebSocketError; namespace System.Net.WebSockets { internal class WinRTWebSocket : WebSocket { #region Constants private const string HeaderNameCookie = "Cookie"; private const string ClientAuthenticationOID = "1.3.6.1.5.5.7.3.2"; #endregion private static readonly Lazy<bool> s_MessageWebSocketClientCertificateSupported = new Lazy<bool>(InitMessageWebSocketClientCertificateSupported); private static bool MessageWebSocketClientCertificateSupported => s_MessageWebSocketClientCertificateSupported.Value; private static readonly Lazy<bool> s_MessageWebSocketReceiveModeSupported = new Lazy<bool>(InitMessageWebSocketReceiveModeSupported); private static bool MessageWebSocketReceiveModeSupported => s_MessageWebSocketReceiveModeSupported.Value; private WebSocketCloseStatus? _closeStatus = null; private string _closeStatusDescription = null; private string _subProtocol = null; private bool _disposed = false; private object _stateLock = new object(); private int _pendingWriteOperation; private MessageWebSocket _messageWebSocket; private DataWriter _messageWriter; private WebSocketState _state = WebSocketState.None; private TaskCompletionSource<ArraySegment<byte>> _receiveAsyncBufferTcs; private TaskCompletionSource<WebSocketReceiveResult> _webSocketReceiveResultTcs; private TaskCompletionSource<WebSocketReceiveResult> _closeWebSocketReceiveResultTcs; public WinRTWebSocket() { _state = WebSocketState.None; } #region Properties public override WebSocketCloseStatus? CloseStatus { get { return _closeStatus; } } public override string CloseStatusDescription { get { return _closeStatusDescription; } } public override WebSocketState State { get { return _state; } } public override string SubProtocol { get { return _subProtocol; } } #endregion private static readonly WebSocketState[] s_validConnectStates = {WebSocketState.None}; private static readonly WebSocketState[] s_validConnectingStates = {WebSocketState.Connecting}; public async Task ConnectAsync(Uri uri, CancellationToken cancellationToken, ClientWebSocketOptions options) { InterlockedCheckAndUpdateState(WebSocketState.Connecting, s_validConnectStates); CheckValidState(s_validConnectingStates); _messageWebSocket = new MessageWebSocket(); foreach (var header in options.RequestHeaders) { _messageWebSocket.SetRequestHeader((string)header, options.RequestHeaders[(string)header]); } string cookies = options.Cookies == null ? null : options.Cookies.GetCookieHeader(uri); if (!string.IsNullOrEmpty(cookies)) { _messageWebSocket.SetRequestHeader(HeaderNameCookie, cookies); } var websocketControl = _messageWebSocket.Control; foreach (var subProtocol in options.RequestedSubProtocols) { websocketControl.SupportedProtocols.Add(subProtocol); } if (options.ClientCertificates.Count > 0) { if (!MessageWebSocketClientCertificateSupported) { throw new PlatformNotSupportedException(string.Format(CultureInfo.InvariantCulture, SR.net_WebSockets_UWPClientCertSupportRequiresWindows10GreaterThan1703)); } X509Certificate2 dotNetClientCert = CertificateHelper.GetEligibleClientCertificate(options.ClientCertificates); if (dotNetClientCert != null) { RTCertificate winRtClientCert = await CertificateHelper.ConvertDotNetClientCertToWinRtClientCertAsync(dotNetClientCert).ConfigureAwait(false); if (winRtClientCert == null) { throw new PlatformNotSupportedException(string.Format( CultureInfo.InvariantCulture, SR.net_WebSockets_UWPClientCertSupportRequiresCertInPersonalCertificateStore)); } websocketControl.ClientCertificate = winRtClientCert; } } // Try to opt into PartialMessage receive mode so that we can hand partial data back to the app as it arrives. // If the MessageWebSocketControl.ReceiveMode API surface is not available, the MessageWebSocket.MessageReceived // event will only get triggered when an entire WebSocket message has been received. This results in large memory // footprint and prevents "streaming" scenarios (e.g., WCF) from working properly. if (MessageWebSocketReceiveModeSupported) { // Always enable partial message receive mode if the WinRT API supports it. _messageWebSocket.Control.ReceiveMode = MessageWebSocketReceiveMode.PartialMessage; } try { _receiveAsyncBufferTcs = new TaskCompletionSource<ArraySegment<byte>>(); _closeWebSocketReceiveResultTcs = new TaskCompletionSource<WebSocketReceiveResult>(); _messageWebSocket.MessageReceived += OnMessageReceived; _messageWebSocket.Closed += OnCloseReceived; await _messageWebSocket.ConnectAsync(uri).AsTask(cancellationToken).ConfigureAwait(false); _subProtocol = _messageWebSocket.Information.Protocol; _messageWriter = new DataWriter(_messageWebSocket.OutputStream); } catch (Exception) { UpdateState(WebSocketState.Closed); throw; } UpdateState(WebSocketState.Open); } public override void Abort() { AbortInternal(); } private void AbortInternal(Exception customException = null) { lock (_stateLock) { if ((_state != WebSocketState.None) && (_state != WebSocketState.Connecting)) { UpdateState(WebSocketState.Aborted); } else { // ClientWebSocket Desktop behavior: a ws that was not connected will not switch state to Aborted. UpdateState(WebSocketState.Closed); } } CancelAllOperations(customException); Dispose(); } private void CancelAllOperations(Exception customException) { if (_receiveAsyncBufferTcs != null) { // This exception will be received by OnMessageReceived and won't be exposed // to user code. var exception = new OperationCanceledException("Aborted"); _receiveAsyncBufferTcs.TrySetException(exception); } if (_webSocketReceiveResultTcs != null) { if (customException != null) { _webSocketReceiveResultTcs.TrySetException(customException); } else { var exception = new WebSocketException( WebSocketError.InvalidState, SR.Format( SR.net_WebSockets_InvalidState_ClosedOrAborted, "System.Net.WebSockets.InternalClientWebSocket", "Aborted")); _webSocketReceiveResultTcs.TrySetException(exception); } } if (_closeWebSocketReceiveResultTcs != null) { if (customException != null) { _closeWebSocketReceiveResultTcs.TrySetException(customException); } else { var exception = new WebSocketException( WebSocketError.InvalidState, SR.Format( SR.net_WebSockets_InvalidState_ClosedOrAborted, "System.Net.WebSockets.InternalClientWebSocket", "Aborted")); _closeWebSocketReceiveResultTcs.TrySetException(exception); } } } private static readonly WebSocketState[] s_validCloseStates = { WebSocketState.Open, WebSocketState.CloseReceived, WebSocketState.CloseSent, WebSocketState.Closed }; public override async Task CloseAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); bool callClose = false; lock (_stateLock) { callClose = (_state != WebSocketState.CloseSent) && (_state != WebSocketState.Closed); } InterlockedCheckAndUpdateCloseState(WebSocketState.CloseSent, s_validCloseStates); using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken)) { if (callClose) { _messageWebSocket.Close((ushort) closeStatus, statusDescription ?? string.Empty); } var result = await _closeWebSocketReceiveResultTcs.Task.ConfigureAwait(false); _closeStatus = result.CloseStatus; _closeStatusDescription = result.CloseStatusDescription; InterlockedCheckAndUpdateCloseState(WebSocketState.CloseReceived, s_validCloseStates); } } private static readonly WebSocketState[] s_validCloseOutputStates = { WebSocketState.Open, WebSocketState.CloseReceived, WebSocketState.CloseSent }; public override Task CloseOutputAsync(WebSocketCloseStatus closeStatus, string statusDescription, CancellationToken cancellationToken) { CheckValidState(s_validCloseOutputStates); _messageWebSocket.Close((ushort)closeStatus, statusDescription ?? string.Empty); InterlockedCheckAndUpdateCloseState(WebSocketState.CloseSent, s_validCloseOutputStates); return Task.CompletedTask; } private void OnCloseReceived(IWebSocket sender, WebSocketClosedEventArgs args) { var recvResult = new WebSocketReceiveResult(0, WebSocketMessageType.Close, true, (WebSocketCloseStatus)args.Code, args.Reason); _closeWebSocketReceiveResultTcs.TrySetResult(recvResult); } public override void Dispose() { if (!_disposed) { lock (_stateLock) { if (!_disposed) { _disposed = true; if (_messageWebSocket != null) { _messageWebSocket.Dispose(); } if (_messageWriter != null) { _messageWriter.Dispose(); } } } } } private static readonly WebSocketState[] s_validReceiveStates = { WebSocketState.Open, WebSocketState.CloseSent }; public override async Task<WebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer, CancellationToken cancellationToken) { InterlockedCheckValidStates(s_validReceiveStates); using (CancellationTokenRegistration ctr = ThrowOrRegisterCancellation(cancellationToken)) { _webSocketReceiveResultTcs = new TaskCompletionSource<WebSocketReceiveResult>(); _receiveAsyncBufferTcs.TrySetResult(buffer); Task<WebSocketReceiveResult> completedTask = await Task.WhenAny( _webSocketReceiveResultTcs.Task, _closeWebSocketReceiveResultTcs.Task).ConfigureAwait(false); WebSocketReceiveResult result = completedTask.GetAwaiter().GetResult(); if (result.MessageType == WebSocketMessageType.Close) { _closeStatus = result.CloseStatus; _closeStatusDescription = result.CloseStatusDescription; InterlockedCheckAndUpdateCloseState(WebSocketState.CloseReceived, s_validCloseOutputStates); } else { _webSocketReceiveResultTcs = new TaskCompletionSource<WebSocketReceiveResult>(); } return result; } } private void OnMessageReceived(MessageWebSocket sender, MessageWebSocketMessageReceivedEventArgs args) { // GetDataReader() throws an exception when either: // (1) The underlying TCP connection is closed prematurely (e.g., FIN/RST received without sending/receiving a WebSocket Close frame). // (2) The server sends invalid data (e.g., corrupt HTTP headers or a message exceeding the MaxMessageSize). // // In both cases, the appropriate thing to do is to close the socket, as we have reached an unexpected state in // the WebSocket protocol. try { using (DataReader reader = args.GetDataReader()) { uint dataAvailable; while ((dataAvailable = reader.UnconsumedBufferLength) > 0) { ArraySegment<byte> buffer; try { buffer = _receiveAsyncBufferTcs.Task.GetAwaiter().GetResult(); } catch (OperationCanceledException) // Caused by Abort call on WebSocket { return; } _receiveAsyncBufferTcs = new TaskCompletionSource<ArraySegment<byte>>(); WebSocketMessageType messageType; if (args.MessageType == SocketMessageType.Binary) { messageType = WebSocketMessageType.Binary; } else { messageType = WebSocketMessageType.Text; } bool endOfMessage = false; uint readCount = Math.Min(dataAvailable, (uint) buffer.Count); if (readCount > 0) { IBuffer dataBuffer = reader.ReadBuffer(readCount); // Safe to cast readCount to int as the maximum value that readCount can be is buffer.Count. dataBuffer.CopyTo(0, buffer.Array, buffer.Offset, (int) readCount); } if (dataAvailable == readCount) { endOfMessage = !IsPartialMessageEvent(args); } WebSocketReceiveResult recvResult = new WebSocketReceiveResult((int) readCount, messageType, endOfMessage); _webSocketReceiveResultTcs.TrySetResult(recvResult); } } } catch (Exception exc) { // WinRT WebSockets always throw exceptions of type System.Exception. However, we can determine whether // or not we're dealing with a known error by using WinRT's WebSocketError.GetStatus method. WebErrorStatus status = RTWebSocketError.GetStatus(exc.HResult); WebSocketError actualError = WebSocketError.Faulted; switch (status) { case WebErrorStatus.ConnectionAborted: case WebErrorStatus.ConnectionReset: case WebErrorStatus.Disconnected: actualError = WebSocketError.ConnectionClosedPrematurely; break; } // Propagate a custom exception to any pending ReceiveAsync/CloseAsync operations and close the socket. WebSocketException customException = new WebSocketException(actualError, exc); AbortInternal(customException); } } private static readonly WebSocketState[] s_validSendStates = { WebSocketState.Open, WebSocketState.CloseReceived }; public override async Task SendAsync(ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken cancellationToken) { InterlockedCheckValidStates(s_validSendStates); if (cancellationToken.IsCancellationRequested) { Abort(); cancellationToken.ThrowIfCancellationRequested(); } var pendingWrite = Interlocked.CompareExchange(ref _pendingWriteOperation, 1, 0); if (pendingWrite == 1) { var exception = new InvalidOperationException(SR.Format(SR.net_Websockets_AlreadyOneOutstandingOperation, "SendAsync")); Abort(); throw exception; } try { _messageWriter.WriteBuffer(buffer.Array.AsBuffer(buffer.Offset, buffer.Count)); if (endOfMessage) { _messageWebSocket.Control.MessageType = messageType == WebSocketMessageType.Binary ? SocketMessageType.Binary : SocketMessageType.Utf8; await _messageWriter.StoreAsync().AsTask(cancellationToken).ConfigureAwait(false); } } catch (Exception) { cancellationToken.ThrowIfCancellationRequested(); throw; } finally { Interlocked.CompareExchange(ref _pendingWriteOperation, 0, 1); } } private CancellationTokenRegistration ThrowOrRegisterCancellation(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { Abort(); cancellationToken.ThrowIfCancellationRequested(); } CancellationTokenRegistration cancellationRegistration = cancellationToken.Register(s => { var thisRef = (WinRTWebSocket)s; // Propagate a custom exception to any pending ReceiveAsync/CloseAsync operations and close the socket. var customException = new OperationCanceledException(nameof(WebSocketState.Aborted)); thisRef.AbortInternal(customException); }, this); return cancellationRegistration; } #region State // Code related to state management // TODO (#7896): Refactor state into encapsulated class public void InterlockedCheckValidStates(WebSocketState[] validStates) { lock (_stateLock) { CheckValidState(validStates); } } private void InterlockedCheckAndUpdateState( WebSocketState newState, params WebSocketState[] validStates) { lock (_stateLock) { CheckValidState(validStates); UpdateState(newState); } } private void InterlockedCheckAndUpdateCloseState(WebSocketState newState, params WebSocketState[] validStates) { lock (_stateLock) { CheckValidState(validStates); if ((_state == WebSocketState.CloseReceived && newState == WebSocketState.CloseSent) || (_state == WebSocketState.CloseSent && newState == WebSocketState.CloseReceived) || ( _state == WebSocketState.Closed)) { _state = WebSocketState.Closed; } else { UpdateState(newState); } } } // Must be called with Lock taken. private void CheckValidState(WebSocketState[] validStates) { string validStatesText = string.Empty; if (validStates != null && validStates.Length > 0) { foreach (WebSocketState currentState in validStates) { if (_state == currentState) { // Ordering is important to maintain .Net 4.5 WebSocket implementation exception behavior. if (_disposed) { throw new ObjectDisposedException(GetType().FullName); } return; } } validStatesText = string.Join(", ", validStates); } throw new WebSocketException(SR.Format(SR.net_WebSockets_InvalidState, _state, validStatesText)); } private void UpdateState(WebSocketState value) { if ((_state != WebSocketState.Closed) && (_state != WebSocketState.Aborted)) { _state = value; } } #endregion #region Helpers private static bool InitMessageWebSocketClientCertificateSupported() { return ApiInformation.IsPropertyPresent( "Windows.Networking.Sockets.MessageWebSocketControl", "ClientCertificate"); } private static bool InitMessageWebSocketReceiveModeSupported() { return ApiInformation.IsPropertyPresent( "Windows.Networking.Sockets.MessageWebSocketControl", "ReceiveMode"); } private bool IsPartialMessageEvent(MessageWebSocketMessageReceivedEventArgs eventArgs) { if (MessageWebSocketReceiveModeSupported) { return !eventArgs.IsMessageComplete; } // When MessageWebSocketMessageReceivedEventArgs.IsMessageComplete is not available, WinRT's behavior // is always to wait for the entire WebSocket message to arrive before raising a MessageReceived event. return false; } #endregion Helpers } }
#region BSD License /* Copyright (c) 2004-2005 Matthew Holmes ([email protected]), Dan Moorehead ([email protected]) 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. * The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion #region CVS Information /* * $Source$ * $Author: sontek $ * $Date: 2008-05-05 17:03:34 -0700 (Mon, 05 May 2008) $ * $Revision: 269 $ */ #endregion using System; using System.IO; using System.Xml; using Prebuild.Core.Attributes; using Prebuild.Core.Interfaces; using Prebuild.Core.Utilities; using Prebuild.Core.Targets; namespace Prebuild.Core.Nodes { /// <summary> /// /// </summary> public enum BuildAction { /// <summary> /// /// </summary> None, /// <summary> /// /// </summary> Compile, /// <summary> /// /// </summary> Content, /// <summary> /// /// </summary> EmbeddedResource } /// <summary> /// /// </summary> public enum SubType { /// <summary> /// /// </summary> Code, /// <summary> /// /// </summary> Component, /// <summary> /// /// </summary> Designer, /// <summary> /// /// </summary> Form, /// <summary> /// /// </summary> Settings, /// <summary> /// /// </summary> UserControl, /// <summary> /// /// </summary> CodeBehind, } public enum CopyToOutput { Never, Always, PreserveNewest } /// <summary> /// /// </summary> [DataNode("File")] public class FileNode : DataNode { #region Fields private string m_Path; private string m_ResourceName = ""; private BuildAction? m_BuildAction; private bool m_Valid; private SubType? m_SubType; private CopyToOutput m_CopyToOutput = CopyToOutput.Never; private bool m_Link = false; private string m_LinkPath = string.Empty; private bool m_PreservePath = false; #endregion #region Properties /// <summary> /// /// </summary> public string Path { get { return m_Path; } } /// <summary> /// /// </summary> public string ResourceName { get { return m_ResourceName; } } /// <summary> /// /// </summary> public BuildAction BuildAction { get { if (m_BuildAction != null) return m_BuildAction.Value; else return GetBuildActionByFileName(this.Path); } } public CopyToOutput CopyToOutput { get { return this.m_CopyToOutput; } } public bool IsLink { get { return this.m_Link; } } public string LinkPath { get { return this.m_LinkPath; } } /// <summary> /// /// </summary> public SubType SubType { get { if (m_SubType != null) return m_SubType.Value; else return GetSubTypeByFileName(this.Path); } } /// <summary> /// /// </summary> public bool IsValid { get { return m_Valid; } } /// <summary> /// /// </summary> /// <param name="file"></param> /// <returns></returns> public bool PreservePath { get { return m_PreservePath; } } #endregion #region Public Methods /// <summary> /// /// </summary> /// <param name="node"></param> public override void Parse(XmlNode node) { string buildAction = Helper.AttributeValue(node, "buildAction", String.Empty); if (buildAction != string.Empty) m_BuildAction = (BuildAction)Enum.Parse(typeof(BuildAction), buildAction); string subType = Helper.AttributeValue(node, "subType", string.Empty); if (subType != String.Empty) m_SubType = (SubType)Enum.Parse(typeof(SubType), subType); m_ResourceName = Helper.AttributeValue(node, "resourceName", m_ResourceName.ToString()); this.m_Link = bool.Parse(Helper.AttributeValue(node, "link", bool.FalseString)); if ( this.m_Link == true ) { this.m_LinkPath = Helper.AttributeValue( node, "linkPath", string.Empty ); } this.m_CopyToOutput = (CopyToOutput) Enum.Parse(typeof(CopyToOutput), Helper.AttributeValue(node, "copyToOutput", this.m_CopyToOutput.ToString())); this.m_PreservePath = bool.Parse( Helper.AttributeValue( node, "preservePath", bool.FalseString ) ); if( node == null ) { throw new ArgumentNullException("node"); } m_Path = Helper.InterpolateForEnvironmentVariables(node.InnerText); if(m_Path == null) { m_Path = ""; } m_Path = m_Path.Trim(); m_Valid = true; if(!File.Exists(m_Path)) { m_Valid = false; Kernel.Instance.Log.Write(LogType.Warning, "File does not exist: {0}", m_Path); } } #endregion } }
// FileSystem.cs // Script#/Libraries/Node/Core // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Runtime.CompilerServices; namespace NodeApi.IO { [ScriptImport] [ScriptIgnoreNamespace] [ScriptDependency("fs")] [ScriptName("fs")] public static class FileSystem { public static void AppendFile(string fileName, string data) { } public static void AppendFile(string fileName, string data, Encoding encoding) { } public static void AppendFile(string fileName, string data, AsyncCallback callback) { } public static void AppendFile(string fileName, string data, Encoding encoding, AsyncCallback callback) { } public static void AppendFile(string fileName, Buffer data) { } public static void AppendFile(string fileName, Buffer data, AsyncCallback callback) { } public static void AppendFileSync(string fileName, string data) { } public static void AppendFileSync(string fileName, string data, Encoding encoding) { } public static void AppendFileSync(string fileName, Buffer data) { } public static void Close(FileDescriptor fd) { } public static void Close(FileDescriptor fd, AsyncCallback callback) { } public static void CloseSync(FileDescriptor fd) { } public static ReadStream CreateReadStream(string path) { return null; } public static ReadStream CreateReadStream(string path, ReadStreamOptions options) { return null; } public static WriteStream CreateWriteStream(string path) { return null; } public static WriteStream CreateWriteStream(string path, WriteStreamOptions options) { return null; } public static void Exists(string path, Action<bool> callback) { } public static bool ExistsSync(string path) { return false; } [ScriptName("mkdir")] public static void MakeDirectory(string path) { } [ScriptName("mkdir")] public static void MakeDirectory(string path, AsyncCallback callback) { } [ScriptName("mkdirSync")] public static void MakeDirectorySync(string path) { } public static void Open(string path, FileAccess flags, AsyncResultCallback<FileDescriptor> callback) { } public static void Open(string path, FileAccess flags, int mode, AsyncResultCallback<FileDescriptor> callback) { } public static FileDescriptor OpenSync(string path, string flags) { return null; } public static FileDescriptor OpenSync(string path, string flags, string mode) { return null; } public static void Read(FileDescriptor fd, Buffer buffer, int offset, int length, object position, AsyncResultCallback<int, Buffer> callback) { } public static int ReadSync(FileDescriptor fd, Buffer buffer, int offset, int length, object position) { return 0; } [ScriptName("readdir")] public static void ReadDirectory(string path, AsyncResultCallback<string[]> callback) { } [ScriptName("readdirSync")] public static string[] ReadDirectorySync(string path) { return null; } public static void ReadFile(string fileName, AsyncResultCallback<Buffer> callback) { } [ScriptName("readFile")] public static void ReadFileText(string fileName, Encoding encoding, AsyncResultCallback<string> callback) { } public static Buffer ReadFileSync(string fileName) { return null; } [ScriptName("readFileSync")] public static string ReadFileTextSync(string fileName, Encoding encoding) { return null; } [ScriptName("rmdir")] public static void RemoveDirectory(string path) { } [ScriptName("rmdir")] public static void RemoveDirectory(string path, AsyncCallback callback) { } [ScriptName("rmdirSync")] public static void RemoveDirectorySync(string path) { } public static void Rename(string oldPath, string newPath) { } public static void Rename(string oldPath, string newPath, AsyncCallback callback) { } public static void RenameSync(string oldPath, string newPath) { } public static void Stat(string path, AsyncResultCallback<FileStats> callback) { } public static FileStats StatSync(string path) { return null; } public static void Truncate(FileDescriptor fd, int length) { } public static void Truncate(FileDescriptor fd, int length, AsyncCallback callback) { } public static void TruncateSync(FileDescriptor fd, int length) { } public static FileSystemWatcher UnwatchFile(string fileName) { return null; } public static FileSystemWatcher UnwatchFile(string fileName, FileSystemListener listener) { return null; } public static FileSystemWatcher Watch(string fileName) { return null; } public static FileSystemWatcher Watch(string fileName, FileSystemListener listener) { return null; } public static FileSystemWatcher Watch(string fileName, FileSystemWatchOptions options, FileSystemListener listener) { return null; } public static void Write(FileDescriptor fd, Buffer buffer, int offset, int length, object position) { } public static void Write(FileDescriptor fd, Buffer buffer, int offset, int length, object position, AsyncResultCallback<int, Buffer> callback) { } public static int WriteSync(FileDescriptor fd, Buffer buffer, int offset, int length, object position) { return 0; } public static void WriteFile(string fileName, string data) { } public static void WriteFile(string fileName, string data, Encoding encoding) { } public static void WriteFile(string fileName, string data, AsyncCallback callback) { } public static void WriteFile(string fileName, string data, Encoding encoding, AsyncCallback callback) { } public static void WriteFile(string fileName, Buffer data) { } public static void WriteFile(string fileName, Buffer data, AsyncCallback callback) { } public static void WriteFileSync(string fileName, string data) { } public static void WriteFileSync(string fileName, string data, Encoding encoding) { } public static void WriteFileSync(string fileName, Buffer data) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; using System; using System.Collections; using System.Collections.Specialized; using GenStrings; namespace System.Collections.Specialized.Tests { public class ContainsValueStrTests { public const int MAX_LEN = 50; // max length of random strings [Fact] public void Test01() { IntlStrings intl; StringDictionary sd; string ind; // simple string values string[] values = { "", " ", "a", "aa", "text", " spaces", "1", "$%^#", "2222222222222222222222222", System.DateTime.Today.ToString(), Int32.MaxValue.ToString() }; // keys for simple string values string[] keys = { "zero", "one", " ", "", "aa", "1", System.DateTime.Today.ToString(), "$%^#", Int32.MaxValue.ToString(), " spaces", "2222222222222222222222222" }; int cnt = 0; // Count // initialize IntStrings intl = new IntlStrings(); // [] StringDictionary is constructed as expected //----------------------------------------------------------------- sd = new StringDictionary(); // [] check for empty dictionary // for (int i = 0; i < values.Length; i++) { if (sd.ContainsValue(values[i])) { Assert.False(true, string.Format("Error, returned true for empty dictionary", i)); } } // [] add simple strings and verify ContainsValue() // cnt = values.Length; for (int i = 0; i < cnt; i++) { sd.Add(keys[i], values[i]); } if (sd.Count != cnt) { Assert.False(true, string.Format("Error, count is {0} instead of {1}", sd.Count, cnt)); } for (int i = 0; i < cnt; i++) { // verify that collection contains all added items // if (!sd.ContainsValue(values[i])) { Assert.False(true, string.Format("Error, collection doesn't contain value \"{1}\"", i, values[i])); } if (!sd.ContainsKey(keys[i])) { Assert.False(true, string.Format("Error, collection doesn't contain key \"{1}\"", i, keys[i])); } } // // Intl strings // [] add Intl strings and verify ContainsValue() // int len = values.Length; string[] intlValues = new string[len * 2]; // fill array with unique strings // for (int i = 0; i < len * 2; i++) { string val = intl.GetRandomString(MAX_LEN); while (Array.IndexOf(intlValues, val) != -1) val = intl.GetRandomString(MAX_LEN); intlValues[i] = val; } Boolean caseInsensitive = false; for (int i = 0; i < len * 2; i++) { if (intlValues[i].Length != 0 && intlValues[i].ToLowerInvariant() == intlValues[i].ToUpperInvariant()) caseInsensitive = true; } // // will use first half of array as values and second half as keys // for (int i = 0; i < len; i++) { cnt = sd.Count; sd.Add(intlValues[i + len], intlValues[i]); if (sd.Count != cnt + 1) { Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, sd.Count, cnt + 1)); } // verify that collection contains newly added item // if (!sd.ContainsValue(intlValues[i])) { Assert.False(true, string.Format("Error, collection doesn't contain value of new item", i)); } if (!sd.ContainsKey(intlValues[i + len])) { Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i)); } // access the item // ind = intlValues[i + len]; if (String.Compare(sd[ind], intlValues[i]) != 0) { Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, sd[ind], intlValues[i])); } } // // add null string // [] add null string with non-null key and verify ContainsValue() // cnt = sd.Count; string k = "keykey"; sd.Add(k, null); if (sd.Count != cnt + 1) { Assert.False(true, string.Format("Error, count is {1} instead of {2}", sd.Count, cnt + 1)); } // verify that collection contains newly added item // if (!sd.ContainsValue(null)) { Assert.False(true, string.Format("Error, dictionary doesn't contain value null")); } // // [] Case sensitivity: search should be case-sensitive // sd.Clear(); if (sd.Count != 0) { Assert.False(true, string.Format("Error, count is {1} instead of {2} after Clear()", sd.Count, 0)); } string[] intlValuesLower = new string[len * 2]; // fill array with unique strings // for (int i = 0; i < len * 2; i++) { intlValues[i] = intlValues[i].ToUpperInvariant(); } for (int i = 0; i < len * 2; i++) { intlValuesLower[i] = intlValues[i].ToLowerInvariant(); } sd.Clear(); // // will use first half of array as values and second half as keys // for (int i = 0; i < len; i++) { cnt = sd.Count; sd.Add(intlValues[i + len], intlValues[i]); // adding uppercase strings if (sd.Count != cnt + 1) { Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, sd.Count, cnt + 1)); } // verify that collection contains newly added uppercase item // if (!sd.ContainsValue(intlValues[i])) { Assert.False(true, string.Format("Error, collection doesn't contain value of new item", i)); } if (!sd.ContainsKey(intlValues[i + len])) { Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i)); } // verify that collection doesn't contains lowercase item // if (!caseInsensitive && sd.ContainsValue(intlValuesLower[i])) { Assert.False(true, string.Format("Error, collection contains lowercase value of new item", i)); } // key is case insensitive if (!sd.ContainsKey(intlValuesLower[i + len])) { Assert.False(true, string.Format("Error, collection doesn't contain lowercase key of new item", i)); } } } } }
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Storage; using Microsoft.Xna.Framework.Content; using IRTaktiks.Components.Playable; using System.Threading; using IRTaktiks.Components.Scenario; namespace IRTaktiks.Components.Manager { /// <summary> /// Manager of animations. /// </summary> public class AnimationManager { #region Singleton /// <summary> /// The instance of the class. /// </summary> private static AnimationManager InstanceField; /// <summary> /// The instance of the class. /// </summary> public static AnimationManager Instance { get { if (InstanceField == null) InstanceField = new AnimationManager(); return InstanceField; } } /// <summary> /// Private constructor. /// </summary> private AnimationManager() { } #endregion #region AnimationType /// <summary> /// Type of animations. /// </summary> public enum AnimationType { /// <summary> /// Animation for Short attack. /// </summary> Short, /// <summary> /// Animation for Long attack. /// </summary> Long, /// <summary> /// Animation for Stealth skill. /// </summary> Stealth, /// <summary> /// Animation for Ambush skill. /// </summary> Ambush, /// <summary> /// Animation for Curse skill. /// </summary> Curse, /// <summary> /// Animation for Quick skill. /// </summary> Quick, /// <summary> /// Animation for Impact skill. /// </summary> Impact, /// <summary> /// Animation for Revenge skill. /// </summary> Revenge, /// <summary> /// Animation for Warcry skill. /// </summary> Warcry, /// <summary> /// Animation for Insane skill. /// </summary> Insane, /// <summary> /// Animation for Reject skill. /// </summary> Reject, /// <summary> /// Animation for Might skill. /// </summary> Might, /// <summary> /// Animation for Heal skill. /// </summary> Heal, /// <summary> /// Animation for Unseal skill. /// </summary> Unseal, /// <summary> /// Animation for Barrier skill. /// </summary> Barrier, /// <summary> /// Animation for Holy skill. /// </summary> Holy, /// <summary> /// Animation for Drain skill. /// </summary> Drain, /// <summary> /// Animation for Flame skill. /// </summary> Flame, /// <summary> /// Animation for Frost skill. /// </summary> Frost, /// <summary> /// Animation for Item usage. /// </summary> Item, /// <summary> /// Animation for Elixir. /// </summary> Elixir } #endregion #region Properties /// <summary> /// The particle manager of game. /// </summary> private ParticleManager ParticleManager; #endregion #region Initialize /// <summary> /// Initializes the animation manager. /// </summary> /// <param name="game">The instance of game.</param> public void Initialize(Game game) { this.ParticleManager = (game as IRTGame).ParticleManager; } #endregion #region Methods /// <summary> /// Do the respective animation in the specified position. /// </summary> /// <param name="type">Type of animation.</param> /// <param name="position">The central position of the animation.</param> public void QueueAnimation(AnimationType type, Vector2 position) { object[] parameters = new object[2]; parameters[0] = type; parameters[1] = position; ThreadPool.QueueUserWorkItem(Animate, parameters); } /// <summary> /// Do some animation. /// </summary> /// <param name="data">Data tranferred across the threads.</param> private void Animate(object data) { object[] parameters = data as object[]; AnimationType type = (AnimationType)parameters[0]; Vector2 position = (Vector2)parameters[1]; switch (type) { case AnimationType.Ambush: this.Ambush(position); break; case AnimationType.Barrier: this.Barrier(position); break; case AnimationType.Curse: this.Curse(position); break; case AnimationType.Drain: this.Drain(position); break; case AnimationType.Elixir: this.Elixir(position); break; case AnimationType.Flame: this.Flame(position); break; case AnimationType.Frost: this.Frost(position); break; case AnimationType.Heal: this.Heal(position); break; case AnimationType.Holy: this.Holy(position); break; case AnimationType.Impact: this.Impact(position); break; case AnimationType.Insane: this.Insane(position); break; case AnimationType.Item: this.Item(position); break; case AnimationType.Long: this.Long(position); break; case AnimationType.Might: this.Might(position); break; case AnimationType.Quick: this.Quick(position); break; case AnimationType.Reject: this.Reject(position); break; case AnimationType.Revenge: this.Revenge(position); break; case AnimationType.Short: this.Short(position); break; case AnimationType.Stealth: this.Stealth(position); break; case AnimationType.Unseal: this.Unseal(position); break; case AnimationType.Warcry: this.Warcry(position); break; } } #endregion #region Animations /// <summary> /// Execute the Animation. /// </summary> /// <param name="position">The target position.</param> private void None(Vector2 position) { int particles = 50; float lifeIncrement = 0.1f; float totalLife = 2.5f; Vector2 position1st = new Vector2(position.X - 5, position.Y - 5); Vector2 position2nd = new Vector2(position.X - 5, position.Y + 5); Vector2 position3rd = new Vector2(position.X + 5, position.Y - 5); Vector2 position4th = new Vector2(position.X + 5, position.Y + 5); this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Firework, lifeIncrement, totalLife, Color.Tan)); Thread.Sleep(50); this.ParticleManager.Queue(new ParticleEffect(position2nd, particles, ParticleEffect.EffectType.Firework, lifeIncrement, totalLife, Color.RoyalBlue)); Thread.Sleep(50); this.ParticleManager.Queue(new ParticleEffect(position3rd, particles, ParticleEffect.EffectType.Firework, lifeIncrement, totalLife, Color.IndianRed)); Thread.Sleep(50); this.ParticleManager.Queue(new ParticleEffect(position4th, particles, ParticleEffect.EffectType.Firework, lifeIncrement, totalLife, Color.SpringGreen)); } /// <summary> /// Execute the Animation. /// </summary> /// <param name="position">The target position.</param> private void Ambush(Vector2 position) { int sliceParticles = 30; int bloodParticles = 25; float sliceLifeIncrement = 0.2f; float bloodLifeIncrement = 0.3f; float sliceTotalLife = 2.5f; float bloodTotalLife = 3.0f; Vector2 slicePosition = new Vector2(position.X - 1, position.Y - 1); Vector2 bloodPosition1st = new Vector2(position.X + 1, position.Y + 1); Vector2 bloodPosition2st = new Vector2(position.X + 2, position.Y + 2); this.ParticleManager.Queue(new ParticleEffect(slicePosition, sliceParticles, ParticleEffect.EffectType.Slice, sliceLifeIncrement, sliceTotalLife, Color.Silver)); Thread.Sleep(100); this.ParticleManager.Queue(new ParticleEffect(bloodPosition1st, bloodParticles, ParticleEffect.EffectType.Flash45, bloodLifeIncrement, bloodTotalLife, Color.Red)); Thread.Sleep(100); this.ParticleManager.Queue(new ParticleEffect(bloodPosition2st, bloodParticles, ParticleEffect.EffectType.Flash0, bloodLifeIncrement, bloodTotalLife, Color.Red)); this.ParticleManager.Queue(new ParticleEffect(slicePosition, sliceParticles, ParticleEffect.EffectType.Slice, sliceLifeIncrement, sliceTotalLife, Color.Silver)); Thread.Sleep(100); this.ParticleManager.Queue(new ParticleEffect(bloodPosition1st, bloodParticles, ParticleEffect.EffectType.Flash45, bloodLifeIncrement, bloodTotalLife, Color.Red)); Thread.Sleep(100); this.ParticleManager.Queue(new ParticleEffect(bloodPosition2st, bloodParticles, ParticleEffect.EffectType.Flash0, bloodLifeIncrement, bloodTotalLife, Color.Red)); } /// <summary> /// Execute the Animation. /// </summary> /// <param name="position">The target position.</param> private void Barrier(Vector2 position) { int ringParticles = 50; int sphereParticles = 100; float ringLifeIncrement = 0.1f; float sphereLifeIncrement = 0.7f; float ringTotalLife = 4.5f; float sphereTotalLife = 21.0f; Vector2 position1st = new Vector2(position.X, position.Y); this.ParticleManager.Queue(new ParticleEffect(position1st, ringParticles, ParticleEffect.EffectType.Ring, ringLifeIncrement, ringTotalLife, Color.Silver)); Thread.Sleep(500); this.ParticleManager.Queue(new ParticleEffect(position1st, sphereParticles, ParticleEffect.EffectType.Sphere, sphereLifeIncrement, sphereTotalLife, Color.Silver)); } /// <summary> /// Execute the Animation. /// </summary> /// <param name="position">The target position.</param> private void Curse(Vector2 position) { int particles = 50; float lifeIncrement = 0.1f; float totalLife = 4.5f; Vector2 position1st = new Vector2(position.X - 12, position.Y + 15); Vector2 position2st = new Vector2(position.X - 0, position.Y - 15); Vector2 position3st = new Vector2(position.X - 20, position.Y + 0); Vector2 position4st = new Vector2(position.X + 12, position.Y + 15); Vector2 position5st = new Vector2(position.X + 20, position.Y + 0); this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Slice, lifeIncrement, totalLife, Color.Green)); this.ParticleManager.Queue(new ParticleEffect(position2st, particles, ParticleEffect.EffectType.Slice, lifeIncrement, totalLife, Color.Green)); this.ParticleManager.Queue(new ParticleEffect(position3st, particles, ParticleEffect.EffectType.Slice, lifeIncrement, totalLife, Color.Green)); this.ParticleManager.Queue(new ParticleEffect(position4st, particles, ParticleEffect.EffectType.Slice, lifeIncrement, totalLife, Color.Green)); this.ParticleManager.Queue(new ParticleEffect(position5st, particles, ParticleEffect.EffectType.Slice, lifeIncrement, totalLife, Color.Green)); } /// <summary> /// Execute the Animation. /// </summary> /// <param name="position">The target position.</param> private void Drain(Vector2 position) { int particles = 50; float lifeIncrement = 0.1f; float totalLife = 4.5f; Vector2 position1st = new Vector2(position.X, position.Y); this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Pillar, lifeIncrement, totalLife, Color.Red)); } /// <summary> /// Execute the Animation. /// </summary> /// <param name="position">The target position.</param> private void Elixir(Vector2 position) { int particles = 25; float lifeIncrement = 0.07f; float totalLife = 3.5f; Vector2 position1st = new Vector2(position.X - 15, position.Y + 15); Vector2 position2nd = new Vector2(position.X - 05, position.Y + 05); Vector2 position3rd = new Vector2(position.X + 05, position.Y - 05); Vector2 position4th = new Vector2(position.X + 15, position.Y - 15); this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Flash0, lifeIncrement, totalLife, Color.ForestGreen)); this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Flash45, lifeIncrement, totalLife, Color.ForestGreen)); this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Flash90, lifeIncrement, totalLife, Color.ForestGreen)); this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Flash135, lifeIncrement, totalLife, Color.ForestGreen)); Thread.Sleep(200); this.ParticleManager.Queue(new ParticleEffect(position2nd, particles, ParticleEffect.EffectType.Flash0, lifeIncrement, totalLife, Color.Crimson)); this.ParticleManager.Queue(new ParticleEffect(position2nd, particles, ParticleEffect.EffectType.Flash45, lifeIncrement, totalLife, Color.Crimson)); this.ParticleManager.Queue(new ParticleEffect(position2nd, particles, ParticleEffect.EffectType.Flash90, lifeIncrement, totalLife, Color.Crimson)); this.ParticleManager.Queue(new ParticleEffect(position2nd, particles, ParticleEffect.EffectType.Flash135, lifeIncrement, totalLife, Color.Crimson)); Thread.Sleep(200); this.ParticleManager.Queue(new ParticleEffect(position3rd, particles, ParticleEffect.EffectType.Flash0, lifeIncrement, totalLife, Color.Chocolate)); this.ParticleManager.Queue(new ParticleEffect(position3rd, particles, ParticleEffect.EffectType.Flash45, lifeIncrement, totalLife, Color.Chocolate)); this.ParticleManager.Queue(new ParticleEffect(position3rd, particles, ParticleEffect.EffectType.Flash90, lifeIncrement, totalLife, Color.Chocolate)); this.ParticleManager.Queue(new ParticleEffect(position3rd, particles, ParticleEffect.EffectType.Flash135, lifeIncrement, totalLife, Color.Chocolate)); Thread.Sleep(200); this.ParticleManager.Queue(new ParticleEffect(position4th, particles, ParticleEffect.EffectType.Flash0, lifeIncrement, totalLife, Color.BlueViolet)); this.ParticleManager.Queue(new ParticleEffect(position4th, particles, ParticleEffect.EffectType.Flash45, lifeIncrement, totalLife, Color.BlueViolet)); this.ParticleManager.Queue(new ParticleEffect(position4th, particles, ParticleEffect.EffectType.Flash90, lifeIncrement, totalLife, Color.BlueViolet)); this.ParticleManager.Queue(new ParticleEffect(position4th, particles, ParticleEffect.EffectType.Flash135, lifeIncrement, totalLife, Color.BlueViolet)); } /// <summary> /// Execute the Animation. /// </summary> /// <param name="position">The target position.</param> private void Flame(Vector2 position) { int particles1st = 25; int particles2nd = 10; int particles3rd = 5; float lifeIncrement1st = 0.02f; float lifeIncrement2nd = 0.04f; float lifeIncrement3rd = 0.06f; float totalLife = 3.0f; Vector2 position1st = new Vector2(position.X - 15, position.Y - 15); Vector2 position2nd = new Vector2(position.X - 10, position.Y - 10); Vector2 position3rd = new Vector2(position.X - 05, position.Y - 05); Vector2 position4th = new Vector2(position.X - 0, position.Y - 0); Vector2 position5th = new Vector2(position.X + 05, position.Y - 05); Vector2 position6th = new Vector2(position.X + 10, position.Y - 10); Vector2 position7th = new Vector2(position.X + 15, position.Y - 15); this.ParticleManager.Queue(new ParticleEffect(position1st, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.Gold)); this.ParticleManager.Queue(new ParticleEffect(position2nd, particles2nd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.Red)); this.ParticleManager.Queue(new ParticleEffect(position3rd, particles1st, ParticleEffect.EffectType.Losangle, lifeIncrement2nd, totalLife, Color.Goldenrod)); this.ParticleManager.Queue(new ParticleEffect(position4th, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.Red)); this.ParticleManager.Queue(new ParticleEffect(position5th, particles1st, ParticleEffect.EffectType.Losangle, lifeIncrement2nd, totalLife, Color.Tomato)); this.ParticleManager.Queue(new ParticleEffect(position6th, particles2nd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.Goldenrod)); this.ParticleManager.Queue(new ParticleEffect(position7th, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.Gold)); Thread.Sleep(150); this.ParticleManager.Queue(new ParticleEffect(position1st, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.Gold)); this.ParticleManager.Queue(new ParticleEffect(position2nd, particles2nd, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.Goldenrod)); this.ParticleManager.Queue(new ParticleEffect(position3rd, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement2nd, totalLife, Color.Red)); this.ParticleManager.Queue(new ParticleEffect(position4th, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.WhiteSmoke)); this.ParticleManager.Queue(new ParticleEffect(position5th, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement2nd, totalLife, Color.Red)); this.ParticleManager.Queue(new ParticleEffect(position6th, particles2nd, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.Goldenrod)); this.ParticleManager.Queue(new ParticleEffect(position7th, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.Gold)); Thread.Sleep(150); this.ParticleManager.Queue(new ParticleEffect(position1st, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.Gold)); this.ParticleManager.Queue(new ParticleEffect(position2nd, particles2nd, ParticleEffect.EffectType.Firework, lifeIncrement3rd, totalLife, Color.Goldenrod)); this.ParticleManager.Queue(new ParticleEffect(position3rd, particles1st, ParticleEffect.EffectType.Losangle, lifeIncrement2nd, totalLife, Color.Thistle)); this.ParticleManager.Queue(new ParticleEffect(position4th, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.Red)); this.ParticleManager.Queue(new ParticleEffect(position5th, particles1st, ParticleEffect.EffectType.Losangle, lifeIncrement2nd, totalLife, Color.Thistle)); this.ParticleManager.Queue(new ParticleEffect(position6th, particles2nd, ParticleEffect.EffectType.Firework, lifeIncrement3rd, totalLife, Color.Goldenrod)); this.ParticleManager.Queue(new ParticleEffect(position7th, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.Gold)); Thread.Sleep(150); this.ParticleManager.Queue(new ParticleEffect(position1st, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.Gold)); this.ParticleManager.Queue(new ParticleEffect(position2nd, particles2nd, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.Goldenrod)); this.ParticleManager.Queue(new ParticleEffect(position3rd, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement2nd, totalLife, Color.Red)); this.ParticleManager.Queue(new ParticleEffect(position4th, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.WhiteSmoke)); this.ParticleManager.Queue(new ParticleEffect(position5th, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement2nd, totalLife, Color.Red)); this.ParticleManager.Queue(new ParticleEffect(position6th, particles2nd, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.Goldenrod)); this.ParticleManager.Queue(new ParticleEffect(position7th, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.Gold)); } /// <summary> /// Execute the Animation. /// </summary> /// <param name="position">The target position.</param> private void Frost(Vector2 position) { int particles1st = 25; int particles2nd = 10; int particles3rd = 5; float lifeIncrement1st = 0.02f; float lifeIncrement2nd = 0.04f; float lifeIncrement3rd = 0.06f; float totalLife = 3.0f; Vector2 position1st = new Vector2(position.X - 15, position.Y - 15); Vector2 position2nd = new Vector2(position.X - 10, position.Y - 10); Vector2 position3rd = new Vector2(position.X - 05, position.Y - 05); Vector2 position4th = new Vector2(position.X - 0, position.Y - 0); Vector2 position5th = new Vector2(position.X + 05, position.Y - 05); Vector2 position6th = new Vector2(position.X + 10, position.Y - 10); Vector2 position7th = new Vector2(position.X + 15, position.Y - 15); this.ParticleManager.Queue(new ParticleEffect(position1st, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.Violet)); this.ParticleManager.Queue(new ParticleEffect(position2nd, particles2nd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.Aquamarine)); this.ParticleManager.Queue(new ParticleEffect(position3rd, particles1st, ParticleEffect.EffectType.Losangle, lifeIncrement2nd, totalLife, Color.ForestGreen)); this.ParticleManager.Queue(new ParticleEffect(position4th, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.Wheat)); this.ParticleManager.Queue(new ParticleEffect(position5th, particles1st, ParticleEffect.EffectType.Losangle, lifeIncrement2nd, totalLife, Color.Aquamarine)); this.ParticleManager.Queue(new ParticleEffect(position6th, particles2nd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.ForestGreen)); this.ParticleManager.Queue(new ParticleEffect(position7th, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.Violet)); Thread.Sleep(150); this.ParticleManager.Queue(new ParticleEffect(position1st, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.CornflowerBlue)); this.ParticleManager.Queue(new ParticleEffect(position2nd, particles2nd, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.CadetBlue)); this.ParticleManager.Queue(new ParticleEffect(position3rd, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement2nd, totalLife, Color.Blue)); this.ParticleManager.Queue(new ParticleEffect(position4th, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.Turquoise)); this.ParticleManager.Queue(new ParticleEffect(position5th, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement2nd, totalLife, Color.Blue)); this.ParticleManager.Queue(new ParticleEffect(position6th, particles2nd, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.CadetBlue)); this.ParticleManager.Queue(new ParticleEffect(position7th, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.CornflowerBlue)); Thread.Sleep(150); this.ParticleManager.Queue(new ParticleEffect(position1st, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.DarkBlue)); this.ParticleManager.Queue(new ParticleEffect(position2nd, particles2nd, ParticleEffect.EffectType.Firework, lifeIncrement3rd, totalLife, Color.CornflowerBlue)); this.ParticleManager.Queue(new ParticleEffect(position3rd, particles1st, ParticleEffect.EffectType.Losangle, lifeIncrement2nd, totalLife, Color.DarkViolet)); this.ParticleManager.Queue(new ParticleEffect(position4th, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.Blue)); this.ParticleManager.Queue(new ParticleEffect(position5th, particles1st, ParticleEffect.EffectType.Losangle, lifeIncrement2nd, totalLife, Color.DarkViolet)); this.ParticleManager.Queue(new ParticleEffect(position6th, particles2nd, ParticleEffect.EffectType.Firework, lifeIncrement3rd, totalLife, Color.CornflowerBlue)); this.ParticleManager.Queue(new ParticleEffect(position7th, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.DarkBlue)); Thread.Sleep(150); this.ParticleManager.Queue(new ParticleEffect(position1st, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.CornflowerBlue)); this.ParticleManager.Queue(new ParticleEffect(position2nd, particles2nd, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.DarkBlue)); this.ParticleManager.Queue(new ParticleEffect(position3rd, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement2nd, totalLife, Color.CornflowerBlue)); this.ParticleManager.Queue(new ParticleEffect(position4th, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.Blue)); this.ParticleManager.Queue(new ParticleEffect(position5th, particles1st, ParticleEffect.EffectType.Firework, lifeIncrement2nd, totalLife, Color.DarkViolet)); this.ParticleManager.Queue(new ParticleEffect(position6th, particles2nd, ParticleEffect.EffectType.Firework, lifeIncrement1st, totalLife, Color.CornflowerBlue)); this.ParticleManager.Queue(new ParticleEffect(position7th, particles3rd, ParticleEffect.EffectType.Losangle, lifeIncrement3rd, totalLife, Color.DarkBlue)); } /// <summary> /// Execute the Animation. /// </summary> /// <param name="position">The target position.</param> private void Heal(Vector2 position) { int particles = 50; float lifeIncrement = 0.07f; float totalLife = 5.0f; Vector2 position1st = new Vector2(position.X - 10, position.Y + 10); Vector2 position2nd = new Vector2(position.X + 10, position.Y - 10); Vector2 position3rd = new Vector2(position.X + 10, position.Y + 10); this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Flash0, lifeIncrement, totalLife, Color.ForestGreen)); this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Flash45, lifeIncrement, totalLife, Color.ForestGreen)); this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Flash90, lifeIncrement, totalLife, Color.ForestGreen)); this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Flash135, lifeIncrement, totalLife, Color.ForestGreen)); Thread.Sleep(200); this.ParticleManager.Queue(new ParticleEffect(position2nd, particles, ParticleEffect.EffectType.Flash0, lifeIncrement, totalLife, Color.Crimson)); this.ParticleManager.Queue(new ParticleEffect(position2nd, particles, ParticleEffect.EffectType.Flash45, lifeIncrement, totalLife, Color.Crimson)); this.ParticleManager.Queue(new ParticleEffect(position2nd, particles, ParticleEffect.EffectType.Flash90, lifeIncrement, totalLife, Color.Crimson)); this.ParticleManager.Queue(new ParticleEffect(position2nd, particles, ParticleEffect.EffectType.Flash135, lifeIncrement, totalLife, Color.Crimson)); Thread.Sleep(200); this.ParticleManager.Queue(new ParticleEffect(position3rd, particles, ParticleEffect.EffectType.Flash0, lifeIncrement, totalLife, Color.Chocolate)); this.ParticleManager.Queue(new ParticleEffect(position3rd, particles, ParticleEffect.EffectType.Flash45, lifeIncrement, totalLife, Color.Chocolate)); this.ParticleManager.Queue(new ParticleEffect(position3rd, particles, ParticleEffect.EffectType.Flash90, lifeIncrement, totalLife, Color.Chocolate)); this.ParticleManager.Queue(new ParticleEffect(position3rd, particles, ParticleEffect.EffectType.Flash135, lifeIncrement, totalLife, Color.Chocolate)); } /// <summary> /// Execute the Animation. /// </summary> /// <param name="position">The target position.</param> private void Holy(Vector2 position) { int particles = 50; float lifeIncrement = 0.06f; float totalLife = 3.0f; Vector2 horizontalPosition1st = new Vector2(position.X - 0, position.Y + 03); Vector2 horizontalPosition2nd = new Vector2(position.X - 0, position.Y + 0); Vector2 horizontalPosition3rd = new Vector2(position.X + 0, position.Y - 03); Vector2 verticalPosition1st = new Vector2(position.X - 03, position.Y + 0); Vector2 verticalPosition2nd = new Vector2(position.X - 0, position.Y + 0); Vector2 verticalPosition3rd = new Vector2(position.X + 03, position.Y - 0); this.ParticleManager.Queue(new ParticleEffect(horizontalPosition1st, particles, ParticleEffect.EffectType.Flash0, lifeIncrement, totalLife, Color.Goldenrod)); this.ParticleManager.Queue(new ParticleEffect(horizontalPosition2nd, particles, ParticleEffect.EffectType.Flash0, lifeIncrement, totalLife, Color.Goldenrod)); this.ParticleManager.Queue(new ParticleEffect(horizontalPosition3rd, particles, ParticleEffect.EffectType.Flash0, lifeIncrement, totalLife, Color.Goldenrod)); this.ParticleManager.Queue(new ParticleEffect(verticalPosition1st, particles, ParticleEffect.EffectType.Flash90, lifeIncrement, totalLife, Color.Goldenrod)); this.ParticleManager.Queue(new ParticleEffect(verticalPosition2nd, particles, ParticleEffect.EffectType.Flash90, lifeIncrement, totalLife, Color.Goldenrod)); this.ParticleManager.Queue(new ParticleEffect(verticalPosition3rd, particles, ParticleEffect.EffectType.Flash90, lifeIncrement, totalLife, Color.Goldenrod)); } /// <summary> /// Execute the Animation. /// </summary> /// <param name="position">The target position.</param> private void Impact(Vector2 position) { this.None(position); } /// <summary> /// Execute the Animation. /// </summary> /// <param name="position">The target position.</param> private void Insane(Vector2 position) { this.Flame(position); } /// <summary> /// Execute the Animation. /// </summary> /// <param name="position">The target position.</param> private void Item(Vector2 position) { int particles = 75; float lifeIncrement = 0.1f; float totalLife = 7.0f; Vector2 position1st = new Vector2(position.X, position.Y + 24); Vector2 position2nd = new Vector2(position.X, position.Y); this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Pillar, lifeIncrement, totalLife, Color.IndianRed)); } /// <summary> /// Execute the Animation. /// </summary> /// <param name="position">The target position.</param> private void Long(Vector2 position) { int particles = 50; float lifeIncrement = 0.1f; float totalLife = 2.5f; Vector2 position1st = new Vector2(position.X - 5, position.Y - 5); Vector2 position2nd = new Vector2(position.X - 5, position.Y + 5); Vector2 position3rd = new Vector2(position.X + 5, position.Y - 5); Vector2 position4th = new Vector2(position.X + 5, position.Y + 5); this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Firework, lifeIncrement, totalLife, Color.Orchid)); Thread.Sleep(50); this.ParticleManager.Queue(new ParticleEffect(position2nd, particles, ParticleEffect.EffectType.Firework, lifeIncrement, totalLife, Color.CadetBlue)); Thread.Sleep(50); this.ParticleManager.Queue(new ParticleEffect(position3rd, particles, ParticleEffect.EffectType.Firework, lifeIncrement, totalLife, Color.IndianRed)); Thread.Sleep(50); this.ParticleManager.Queue(new ParticleEffect(position4th, particles, ParticleEffect.EffectType.Firework, lifeIncrement, totalLife, Color.Cornsilk)); } /// <summary> /// Execute the Animation. /// </summary> /// <param name="position">The target position.</param> private void Might(Vector2 position) { int particles = 75; float lifeIncrement = 0.1f; float totalLife = 7.0f; Vector2 position1st = new Vector2(position.X, position.Y + 24); Vector2 position2nd = new Vector2(position.X, position.Y); this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Pillar, lifeIncrement, totalLife, Color.GhostWhite)); } /// <summary> /// Execute the Animation. /// </summary> /// <param name="position">The target position.</param> private void Quick(Vector2 position) { int particles = 75; float lifeIncrement = 0.1f; float totalLife = 7.0f; Vector2 position1st = new Vector2(position.X, position.Y + 24); Vector2 position2nd = new Vector2(position.X, position.Y); this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Pillar, lifeIncrement, totalLife, Color.Green)); } /// <summary> /// Execute the Animation. /// </summary> /// <param name="position">The target position.</param> private void Reject(Vector2 position) { this.None(position); } /// <summary> /// Execute the Animation. /// </summary> /// <param name="position">The target position.</param> private void Revenge(Vector2 position) { this.Long(position); } /// <summary> /// Execute the Animation. /// </summary> /// <param name="position">The target position.</param> private void Short(Vector2 position) { int particles = 50; float lifeIncrement = 0.1f; float totalLife = 4.0f; Vector2 position1st = new Vector2(position.X, position.Y - 10); Vector2 position2nd = new Vector2(position.X, position.Y + 10); Vector2 position3rd = new Vector2(position.X, position.Y); this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Flash45, lifeIncrement, totalLife, Color.Crimson)); this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Flash135, lifeIncrement, totalLife, Color.Chocolate)); this.ParticleManager.Queue(new ParticleEffect(position2nd, particles, ParticleEffect.EffectType.Flash45, lifeIncrement, totalLife, Color.DarkSeaGreen)); this.ParticleManager.Queue(new ParticleEffect(position2nd, particles, ParticleEffect.EffectType.Flash135, lifeIncrement, totalLife, Color.BlueViolet)); this.ParticleManager.Queue(new ParticleEffect(position3rd, particles, ParticleEffect.EffectType.Firework, lifeIncrement, totalLife / 2, Color.Red)); } /// <summary> /// Execute the Animation. /// </summary> /// <param name="position">The target position.</param> private void Stealth(Vector2 position) { int particles = 75; float lifeIncrement = 0.1f; float totalLife = 7.0f; Vector2 position1st = new Vector2(position.X, position.Y + 24); Vector2 position2nd = new Vector2(position.X, position.Y); this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Pillar, lifeIncrement, totalLife, Color.Black)); } /// <summary> /// Execute the Animation. /// </summary> /// <param name="position">The target position.</param> private void Unseal(Vector2 position) { this.Elixir(position); } /// <summary> /// Execute the Animation. /// </summary> /// <param name="position">The target position.</param> private void Warcry(Vector2 position) { int particles = 75; float lifeIncrement = 0.1f; float totalLife = 7.0f; Vector2 position1st = new Vector2(position.X, position.Y + 24); Vector2 position2nd = new Vector2(position.X, position.Y); this.ParticleManager.Queue(new ParticleEffect(position1st, particles, ParticleEffect.EffectType.Pillar, lifeIncrement, totalLife, Color.SaddleBrown)); } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ServiceBus.Fluent { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// SubscriptionsOperations operations. /// </summary> internal partial class SubscriptionsOperations : IServiceOperations<ServiceBusManagementClient>, ISubscriptionsOperations { /// <summary> /// Initializes a new instance of the SubscriptionsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal SubscriptionsOperations(ServiceBusManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the ServiceBusManagementClient /// </summary> public ServiceBusManagementClient Client { get; private set; } /// <summary> /// List all the subscriptions under a specified topic. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639400.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<SubscriptionInner>>> ListByTopicWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (namespaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName"); } if (namespaceName != null) { if (namespaceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50); } if (namespaceName.Length < 6) { throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6); } } if (topicName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "topicName"); } if (topicName != null) { if (topicName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "topicName", 1); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("namespaceName", namespaceName); tracingParameters.Add("topicName", topicName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByTopic", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/subscriptions").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{topicName}", System.Uri.EscapeDataString(topicName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<SubscriptionInner>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SubscriptionInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates a topic subscription. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639385.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='subscriptionName'> /// The subscription name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a subscription resource. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<SubscriptionInner>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, string subscriptionName, SubscriptionInner parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (namespaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName"); } if (namespaceName != null) { if (namespaceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50); } if (namespaceName.Length < 6) { throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6); } } if (topicName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "topicName"); } if (topicName != null) { if (topicName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "topicName", 1); } } if (subscriptionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionName"); } if (subscriptionName != null) { if (subscriptionName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "subscriptionName", 50); } if (subscriptionName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "subscriptionName", 1); } } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("namespaceName", namespaceName); tracingParameters.Add("topicName", topicName); tracingParameters.Add("subscriptionName", subscriptionName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/subscriptions/{subscriptionName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{topicName}", System.Uri.EscapeDataString(topicName)); _url = _url.Replace("{subscriptionName}", System.Uri.EscapeDataString(subscriptionName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<SubscriptionInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SubscriptionInner>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes a subscription from the specified topic. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639381.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='subscriptionName'> /// The subscription name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, string subscriptionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (namespaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName"); } if (namespaceName != null) { if (namespaceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50); } if (namespaceName.Length < 6) { throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6); } } if (topicName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "topicName"); } if (topicName != null) { if (topicName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "topicName", 1); } } if (subscriptionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionName"); } if (subscriptionName != null) { if (subscriptionName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "subscriptionName", 50); } if (subscriptionName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "subscriptionName", 1); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("namespaceName", namespaceName); tracingParameters.Add("topicName", topicName); tracingParameters.Add("subscriptionName", subscriptionName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/subscriptions/{subscriptionName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{topicName}", System.Uri.EscapeDataString(topicName)); _url = _url.Replace("{subscriptionName}", System.Uri.EscapeDataString(subscriptionName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Returns a subscription description for the specified topic. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639402.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='topicName'> /// The topic name. /// </param> /// <param name='subscriptionName'> /// The subscription name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<SubscriptionInner>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string topicName, string subscriptionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (namespaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "namespaceName"); } if (namespaceName != null) { if (namespaceName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "namespaceName", 50); } if (namespaceName.Length < 6) { throw new ValidationException(ValidationRules.MinLength, "namespaceName", 6); } } if (topicName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "topicName"); } if (topicName != null) { if (topicName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "topicName", 1); } } if (subscriptionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionName"); } if (subscriptionName != null) { if (subscriptionName.Length > 50) { throw new ValidationException(ValidationRules.MaxLength, "subscriptionName", 50); } if (subscriptionName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "subscriptionName", 1); } } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("namespaceName", namespaceName); tracingParameters.Add("topicName", topicName); tracingParameters.Add("subscriptionName", subscriptionName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}/subscriptions/{subscriptionName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{namespaceName}", System.Uri.EscapeDataString(namespaceName)); _url = _url.Replace("{topicName}", System.Uri.EscapeDataString(topicName)); _url = _url.Replace("{subscriptionName}", System.Uri.EscapeDataString(subscriptionName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<SubscriptionInner>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<SubscriptionInner>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// List all the subscriptions under a specified topic. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639400.aspx" /> /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<SubscriptionInner>>> ListByTopicNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByTopicNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<SubscriptionInner>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<SubscriptionInner>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using QuantConnect.Data; using QuantConnect.Interfaces; using QuantConnect.Orders; using QuantConnect.Securities; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// This regression algorithm tests In The Money (ITM) future option expiry for calls. /// We expect 3 orders from the algorithm, which are: /// /// * Initial entry, buy ES Call Option (expiring ITM) /// * Option exercise, receiving ES future contracts /// * Future contract liquidation, due to impending expiry /// /// Additionally, we test delistings for future options and assert that our /// portfolio holdings reflect the orders the algorithm has submitted. /// </summary> public class FutureOptionCallITMExpiryRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition { private Symbol _es19m20; private Symbol _esOption; private Symbol _expectedOptionContract; public override void Initialize() { SetStartDate(2020, 1, 5); SetEndDate(2020, 6, 30); _es19m20 = AddFutureContract( QuantConnect.Symbol.CreateFuture( Futures.Indices.SP500EMini, Market.CME, new DateTime(2020, 6, 19)), Resolution.Minute).Symbol; // Select a future option expiring ITM, and adds it to the algorithm. _esOption = AddFutureOptionContract(OptionChainProvider.GetOptionContractList(_es19m20, Time) .Where(x => x.ID.StrikePrice <= 3200m && x.ID.OptionRight == OptionRight.Call) .OrderByDescending(x => x.ID.StrikePrice) .Take(1) .Single(), Resolution.Minute).Symbol; _expectedOptionContract = QuantConnect.Symbol.CreateOption(_es19m20, Market.CME, OptionStyle.American, OptionRight.Call, 3200m, new DateTime(2020, 6, 19)); if (_esOption != _expectedOptionContract) { throw new Exception($"Contract {_expectedOptionContract} was not found in the chain"); } Schedule.On(DateRules.Tomorrow, TimeRules.AfterMarketOpen(_es19m20, 1), () => { MarketOrder(_esOption, 1); }); } public override void OnData(Slice data) { // Assert delistings, so that we can make sure that we receive the delisting warnings at // the expected time. These assertions detect bug #4872 foreach (var delisting in data.Delistings.Values) { if (delisting.Type == DelistingType.Warning) { if (delisting.Time != new DateTime(2020, 6, 19)) { throw new Exception($"Delisting warning issued at unexpected date: {delisting.Time}"); } } if (delisting.Type == DelistingType.Delisted) { if (delisting.Time != new DateTime(2020, 6, 20)) { throw new Exception($"Delisting happened at unexpected date: {delisting.Time}"); } } } } public override void OnOrderEvent(OrderEvent orderEvent) { if (orderEvent.Status != OrderStatus.Filled) { // There's lots of noise with OnOrderEvent, but we're only interested in fills. return; } if (!Securities.ContainsKey(orderEvent.Symbol)) { throw new Exception($"Order event Symbol not found in Securities collection: {orderEvent.Symbol}"); } var security = Securities[orderEvent.Symbol]; if (security.Symbol == _es19m20) { AssertFutureOptionOrderExercise(orderEvent, security, Securities[_expectedOptionContract]); } else if (security.Symbol == _expectedOptionContract) { AssertFutureOptionContractOrder(orderEvent, security); } else { throw new Exception($"Received order event for unknown Symbol: {orderEvent.Symbol}"); } Log($"{Time:yyyy-MM-dd HH:mm:ss} -- {orderEvent.Symbol} :: Price: {Securities[orderEvent.Symbol].Holdings.Price} Qty: {Securities[orderEvent.Symbol].Holdings.Quantity} Direction: {orderEvent.Direction} Msg: {orderEvent.Message}"); } private void AssertFutureOptionOrderExercise(OrderEvent orderEvent, Security future, Security optionContract) { var expectedLiquidationTimeUtc = new DateTime(2020, 6, 20, 4, 0, 0); if (orderEvent.Direction == OrderDirection.Sell && future.Holdings.Quantity != 0) { // We expect the contract to have been liquidated immediately throw new Exception($"Did not liquidate existing holdings for Symbol {future.Symbol}"); } if (orderEvent.Direction == OrderDirection.Sell && orderEvent.UtcTime != expectedLiquidationTimeUtc) { throw new Exception($"Liquidated future contract, but not at the expected time. Expected: {expectedLiquidationTimeUtc:yyyy-MM-dd HH:mm:ss} - found {orderEvent.UtcTime:yyyy-MM-dd HH:mm:ss}"); } // No way to detect option exercise orders or any other kind of special orders // other than matching strings, for now. if (orderEvent.Message.Contains("Option Exercise")) { if (orderEvent.FillPrice != 3200m) { throw new Exception("Option did not exercise at expected strike price (3200)"); } if (future.Holdings.Quantity != 1) { // Here, we expect to have some holdings in the underlying, but not in the future option anymore. throw new Exception($"Exercised option contract, but we have no holdings for Future {future.Symbol}"); } if (optionContract.Holdings.Quantity != 0) { throw new Exception($"Exercised option contract, but we have holdings for Option contract {optionContract.Symbol}"); } } } private void AssertFutureOptionContractOrder(OrderEvent orderEvent, Security option) { if (orderEvent.Direction == OrderDirection.Buy && option.Holdings.Quantity != 1) { throw new Exception($"No holdings were created for option contract {option.Symbol}"); } if (orderEvent.Direction == OrderDirection.Sell && option.Holdings.Quantity != 0) { throw new Exception($"Holdings were found after a filled option exercise"); } if (orderEvent.Message.Contains("Exercise") && option.Holdings.Quantity != 0) { throw new Exception($"Holdings were found after exercising option contract {option.Symbol}"); } } /// <summary> /// Ran at the end of the algorithm to ensure the algorithm has no holdings /// </summary> /// <exception cref="Exception">The algorithm has holdings</exception> public override void OnEndOfAlgorithm() { if (Portfolio.Invested) { throw new Exception($"Expected no holdings at end of algorithm, but are invested in: {string.Join(", ", Portfolio.Keys)}"); } } /// <summary> /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm. /// </summary> public bool CanRunLocally { get; } = true; /// <summary> /// This is used by the regression test system to indicate which languages this algorithm is written in. /// </summary> public Language[] Languages { get; } = { Language.CSharp, Language.Python }; /// <summary> /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm /// </summary> public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string> { {"Total Trades", "3"}, {"Average Win", "1.26%"}, {"Average Loss", "-7.41%"}, {"Compounding Annual Return", "-12.424%"}, {"Drawdown", "6.300%"}, {"Expectancy", "-0.415"}, {"Net Profit", "-6.252%"}, {"Sharpe Ratio", "-1.226"}, {"Probabilistic Sharpe Ratio", "0.002%"}, {"Loss Rate", "50%"}, {"Win Rate", "50%"}, {"Profit-Loss Ratio", "0.17"}, {"Alpha", "-0.086"}, {"Beta", "0.004"}, {"Annual Standard Deviation", "0.07"}, {"Annual Variance", "0.005"}, {"Information Ratio", "-0.283"}, {"Tracking Error", "0.379"}, {"Treynor Ratio", "-23.811"}, {"Total Fees", "$1.85"}, {"Estimated Strategy Capacity", "$270000000.00"}, {"Lowest Capacity Asset", "ES XFH59UPBIJ7O|ES XFH59UK0MYO1"}, {"Fitness Score", "0.008"}, {"Kelly Criterion Estimate", "0"}, {"Kelly Criterion Probability Value", "0"}, {"Sortino Ratio", "-0.205"}, {"Return Over Maximum Drawdown", "-1.989"}, {"Portfolio Turnover", "0.023"}, {"Total Insights Generated", "0"}, {"Total Insights Closed", "0"}, {"Total Insights Analysis Completed", "0"}, {"Long Insight Count", "0"}, {"Short Insight Count", "0"}, {"Long/Short Ratio", "100%"}, {"Estimated Monthly Alpha Value", "$0"}, {"Total Accumulated Estimated Alpha Value", "$0"}, {"Mean Population Estimated Insight Value", "$0"}, {"Mean Population Direction", "0%"}, {"Mean Population Magnitude", "0%"}, {"Rolling Averaged Population Direction", "0%"}, {"Rolling Averaged Population Magnitude", "0%"}, {"OrderListHash", "b738fdaf1dae6849884df9e51eb6482b"} }; } }
/* * 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 PriorityQueue = Lucene.Net.Util.PriorityQueue; namespace Lucene.Net.Search { /// <summary> Expert: Collects sorted results from Searchable's and collates them. /// The elements put into this queue must be of type FieldDoc. /// </summary> /// <since> lucene 1.4 /// </since> /// <version> $Id: FieldDocSortedHitQueue.java 590530 2007-10-31 01:28:25Z gsingers $ /// </version> class FieldDocSortedHitQueue : PriorityQueue { // this cannot contain AUTO fields - any AUTO fields should // have been resolved by the time this class is used. internal volatile SortField[] fields; // used in the case where the fields are sorted by locale // based strings internal volatile System.Globalization.CompareInfo[] collators; /// <summary> Creates a hit queue sorted by the given list of fields.</summary> /// <param name="fields">Fieldable names, in priority order (highest priority first). /// </param> /// <param name="size"> The number of hits to retain. Must be greater than zero. /// </param> internal FieldDocSortedHitQueue(SortField[] fields, int size) { this.fields = fields; this.collators = HasCollators(fields); Initialize(size); } /// <summary> Allows redefinition of sort fields if they are <code>null</code>. /// This is to handle the case using ParallelMultiSearcher where the /// original list contains AUTO and we don't know the actual sort /// type until the values come back. The fields can only be set once. /// This method is thread safe. /// </summary> /// <param name="">fields /// </param> internal virtual void SetFields(SortField[] fields) { lock (this) { if (this.fields == null) { this.fields = fields; this.collators = HasCollators(fields); } } } /// <summary>Returns the fields being used to sort. </summary> internal virtual SortField[] GetFields() { return fields; } /// <summary>Returns an array of collators, possibly <code>null</code>. The collators /// correspond to any SortFields which were given a specific locale. /// </summary> /// <param name="fields">Array of sort fields. /// </param> /// <returns> Array, possibly <code>null</code>. /// </returns> private System.Globalization.CompareInfo[] HasCollators(SortField[] fields) { if (fields == null) return null; System.Globalization.CompareInfo[] ret = new System.Globalization.CompareInfo[fields.Length]; for (int i = 0; i < fields.Length; ++i) { System.Globalization.CultureInfo locale = fields[i].GetLocale(); if (locale != null) ret[i] = locale.CompareInfo; } return ret; } /// <summary> Returns whether <code>a</code> is less relevant than <code>b</code>.</summary> /// <param name="a">ScoreDoc /// </param> /// <param name="b">ScoreDoc /// </param> /// <returns> <code>true</code> if document <code>a</code> should be sorted after document <code>b</code>. /// </returns> public override bool LessThan(object a, object b) { FieldDoc docA = (FieldDoc) a; FieldDoc docB = (FieldDoc) b; int n = fields.Length; int c = 0; for (int i = 0; i < n && c == 0; ++i) { int type = fields[i].GetType(); switch (type) { case SortField.SCORE: { float r1 = (float) ((System.Single) docA.fields[i]); float r2 = (float) ((System.Single) docB.fields[i]); if (r1 > r2) c = - 1; if (r1 < r2) c = 1; break; } case SortField.DOC: case SortField.INT: { int i1 = ((System.Int32) docA.fields[i]); int i2 = ((System.Int32) docB.fields[i]); if (i1 < i2) c = - 1; if (i1 > i2) c = 1; break; } case SortField.LONG: { long l1 = (long) ((System.Int64) docA.fields[i]); long l2 = (long) ((System.Int64) docB.fields[i]); if (l1 < l2) c = - 1; if (l1 > l2) c = 1; break; } case SortField.STRING: { System.String s1 = (System.String) docA.fields[i]; System.String s2 = (System.String) docB.fields[i]; // null values need to be sorted first, because of how FieldCache.getStringIndex() // works - in that routine, any documents without a value in the given field are // put first. If both are null, the next SortField is used if (s1 == null) c = (s2 == null) ? 0 : - 1; else if (s2 == null) c = 1; // else if (fields[i].GetLocale() == null) { c = String.CompareOrdinal(s1, s2); } else { c = collators[i].Compare(s1.ToString(), s2.ToString()); } break; } case SortField.FLOAT: { float f1 = (float) ((System.Single) docA.fields[i]); float f2 = (float) ((System.Single) docB.fields[i]); if (f1 < f2) c = - 1; if (f1 > f2) c = 1; break; } case SortField.DOUBLE: { double d1 = ((System.Double) docA.fields[i]); double d2 = ((System.Double) docB.fields[i]); if (d1 < d2) c = - 1; if (d1 > d2) c = 1; break; } case SortField.BYTE: { int i1 = (int)docA.fields[i]; //((Byte)docA.fields[i]).byteValue(); int i2 = (int)docB.fields[i]; //((Byte)docB.fields[i]).byteValue(); if (i1 < i2) c = -1; if (i1 > i2) c = 1; break; } case SortField.SHORT: { int i1 = (int)docA.fields[i]; //((Short)docA.fields[i]).shortValue(); int i2 = (int)docB.fields[i]; //((Short)docB.fields[i]).shortValue(); if (i1 < i2) c = -1; if (i1 > i2) c = 1; break; } case SortField.CUSTOM: { c = docA.fields[i].CompareTo(docB.fields[i]); break; } case SortField.AUTO: { // we cannot handle this - even if we determine the type of object (Float or // Integer), we don't necessarily know how to compare them (both SCORE and // FLOAT contain floats, but are sorted opposite of each other). Before // we get here, each AUTO should have been replaced with its actual value. throw new System.SystemException("FieldDocSortedHitQueue cannot use an AUTO SortField"); } default: { throw new System.SystemException("invalid SortField type: " + type); } } if (fields[i].GetReverse()) { c = - c; } } // avoid random sort order that could lead to duplicates (bug #31241): if (c == 0) return docA.doc > docB.doc; return c > 0; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void GetAndWithElementDouble0() { var test = new VectorGetAndWithElement__GetAndWithElementDouble0(); // Validates basic functionality works test.RunBasicScenario(); // Validates calling via reflection works test.RunReflectionScenario(); // Validates that invalid indices throws ArgumentOutOfRangeException test.RunArgumentOutOfRangeScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorGetAndWithElement__GetAndWithElementDouble0 { private static readonly int LargestVectorSize = 8; private static readonly int ElementCount = Unsafe.SizeOf<Vector64<Double>>() / sizeof(Double); public bool Succeeded { get; set; } = true; public void RunBasicScenario(int imm = 0, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario)); Double[] values = new Double[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetDouble(); } Vector64<Double> value = Vector64.Create(values[0]); bool succeeded = !expectedOutOfRangeException; try { Double result = value.GetElement(imm); ValidateGetResult(result, values); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Double.GetElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Double insertedValue = TestLibrary.Generator.GetDouble(); try { Vector64<Double> result2 = value.WithElement(imm, insertedValue); ValidateWithResult(result2, values, insertedValue); } catch (ArgumentOutOfRangeException) { succeeded = expectedOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Double.WithElement({imm}): {nameof(RunBasicScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunReflectionScenario(int imm = 0, bool expectedOutOfRangeException = false) { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario)); Double[] values = new Double[ElementCount]; for (int i = 0; i < ElementCount; i++) { values[i] = TestLibrary.Generator.GetDouble(); } Vector64<Double> value = Vector64.Create(values[0]); bool succeeded = !expectedOutOfRangeException; try { object result = typeof(Vector64) .GetMethod(nameof(Vector64.GetElement)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value, imm }); ValidateGetResult((Double)(result), values); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Double.GetElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } succeeded = !expectedOutOfRangeException; Double insertedValue = TestLibrary.Generator.GetDouble(); try { object result2 = typeof(Vector64) .GetMethod(nameof(Vector64.WithElement)) .MakeGenericMethod(typeof(Double)) .Invoke(null, new object[] { value, imm, insertedValue }); ValidateWithResult((Vector64<Double>)(result2), values, insertedValue); } catch (TargetInvocationException e) { succeeded = expectedOutOfRangeException && e.InnerException is ArgumentOutOfRangeException; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Double.WithElement({imm}): {nameof(RunReflectionScenario)} failed to throw ArgumentOutOfRangeException."); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } public void RunArgumentOutOfRangeScenario() { RunBasicScenario(0 - ElementCount, expectedOutOfRangeException: true); RunBasicScenario(0 + ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(0 - ElementCount, expectedOutOfRangeException: true); RunReflectionScenario(0 + ElementCount, expectedOutOfRangeException: true); } private void ValidateGetResult(Double result, Double[] values, [CallerMemberName] string method = "") { if (result != values[0]) { Succeeded = false; TestLibrary.TestFramework.LogInformation($"Vector64<Double.GetElement(0): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } private void ValidateWithResult(Vector64<Double> result, Double[] values, Double insertedValue, [CallerMemberName] string method = "") { Double[] resultElements = new Double[ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref resultElements[0]), result); ValidateWithResult(resultElements, values, insertedValue, method); } private void ValidateWithResult(Double[] result, Double[] values, Double insertedValue, [CallerMemberName] string method = "") { bool succeeded = true; for (int i = 0; i < ElementCount; i++) { if ((i != 0) && (result[i] != values[i])) { succeeded = false; break; } } if (result[0] != insertedValue) { succeeded = false; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector64<Double.WithElement(0): {method} failed:"); TestLibrary.TestFramework.LogInformation($" value: ({string.Join(", ", values)})"); TestLibrary.TestFramework.LogInformation($" insert: insertedValue"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Xunit; namespace System.IO.Compression.Tests { public partial class ZipFileTestBase : FileCleanupTestBase { public static string bad(string filename) => Path.Combine("ZipTestData", "badzipfiles", filename); public static string compat(string filename) => Path.Combine("ZipTestData", "compat", filename); public static string strange(string filename) => Path.Combine("ZipTestData", "StrangeZipFiles", filename); public static string zfile(string filename) => Path.Combine("ZipTestData", "refzipfiles", filename); public static string zfolder(string filename) => Path.Combine("ZipTestData", "refzipfolders", filename); public static string zmodified(string filename) => Path.Combine("ZipTestData", "modified", filename); protected TempFile CreateTempCopyFile(string path, string newPath) { TempFile newfile = new TempFile(newPath); File.Copy(path, newPath, overwrite: true); return newfile; } public static long LengthOfUnseekableStream(Stream s) { long totalBytes = 0; const int bufSize = 4096; byte[] buf = new byte[bufSize]; long bytesRead = 0; do { bytesRead = s.Read(buf, 0, bufSize); totalBytes += bytesRead; } while (bytesRead > 0); return totalBytes; } // reads exactly bytesToRead out of stream, unless it is out of bytes public static void ReadBytes(Stream stream, byte[] buffer, long bytesToRead) { int bytesLeftToRead; if (bytesToRead > int.MaxValue) { throw new NotImplementedException("64 bit addresses"); } else { bytesLeftToRead = (int)bytesToRead; } int totalBytesRead = 0; while (bytesLeftToRead > 0) { int bytesRead = stream.Read(buffer, totalBytesRead, bytesLeftToRead); if (bytesRead == 0) throw new IOException("Unexpected end of stream"); totalBytesRead += bytesRead; bytesLeftToRead -= bytesRead; } } public static bool ArraysEqual<T>(T[] a, T[] b) where T : IComparable<T> { if (a.Length != b.Length) return false; for (int i = 0; i < a.Length; i++) { if (a[i].CompareTo(b[i]) != 0) return false; } return true; } public static bool ArraysEqual<T>(T[] a, T[] b, int length) where T : IComparable<T> { for (int i = 0; i < length; i++) { if (a[i].CompareTo(b[i]) != 0) return false; } return true; } public static void StreamsEqual(Stream ast, Stream bst) { StreamsEqual(ast, bst, -1); } public static void StreamsEqual(Stream ast, Stream bst, int blocksToRead) { if (ast.CanSeek) ast.Seek(0, SeekOrigin.Begin); if (bst.CanSeek) bst.Seek(0, SeekOrigin.Begin); const int bufSize = 4096; byte[] ad = new byte[bufSize]; byte[] bd = new byte[bufSize]; int ac = 0; int bc = 0; int blocksRead = 0; //assume read doesn't do weird things do { if (blocksToRead != -1 && blocksRead >= blocksToRead) break; ac = ast.Read(ad, 0, 4096); bc = bst.Read(bd, 0, 4096); if (ac != bc) { bd = NormalizeLineEndings(bd); } Assert.True(ArraysEqual<byte>(ad, bd, ac), "Stream contents not equal: " + ast.ToString() + ", " + bst.ToString()); blocksRead++; } while (ac == 4096); } public static async Task IsZipSameAsDirAsync(string archiveFile, string directory, ZipArchiveMode mode) { await IsZipSameAsDirAsync(archiveFile, directory, mode, requireExplicit: false, checkTimes: false); } public static async Task IsZipSameAsDirAsync(string archiveFile, string directory, ZipArchiveMode mode, bool requireExplicit, bool checkTimes) { var s = await StreamHelpers.CreateTempCopyStream(archiveFile); IsZipSameAsDir(s, directory, mode, requireExplicit, checkTimes); } public static byte[] NormalizeLineEndings(byte[] str) { string rep = Text.Encoding.Default.GetString(str); rep = rep.Replace("\r\n", "\n"); rep = rep.Replace("\n", "\r\n"); return Text.Encoding.Default.GetBytes(rep); } public static void IsZipSameAsDir(Stream archiveFile, string directory, ZipArchiveMode mode, bool requireExplicit, bool checkTimes) { int count = 0; using (ZipArchive archive = new ZipArchive(archiveFile, mode)) { List<FileData> files = FileData.InPath(directory); Assert.All<FileData>(files, (file) => { count++; string entryName = file.FullName; if (file.IsFolder) entryName += Path.DirectorySeparatorChar; ZipArchiveEntry entry = archive.GetEntry(entryName); if (entry == null) { entryName = FlipSlashes(entryName); entry = archive.GetEntry(entryName); } if (file.IsFile) { Assert.NotNull(entry); long givenLength = entry.Length; var buffer = new byte[entry.Length]; using (Stream entrystream = entry.Open()) { entrystream.Read(buffer, 0, buffer.Length); #if NETCOREAPP uint zipcrc = entry.Crc32; Assert.Equal(CRC.CalculateCRC(buffer), zipcrc.ToString()); #endif if (file.Length != givenLength) { buffer = NormalizeLineEndings(buffer); } Assert.Equal(file.Length, buffer.Length); string crc = CRC.CalculateCRC(buffer); Assert.Equal(file.CRC, crc); } if (checkTimes) { const int zipTimestampResolution = 2; // Zip follows the FAT timestamp resolution of two seconds for file records DateTime lower = file.LastModifiedDate.AddSeconds(-zipTimestampResolution); DateTime upper = file.LastModifiedDate.AddSeconds(zipTimestampResolution); Assert.InRange(entry.LastWriteTime.Ticks, lower.Ticks, upper.Ticks); } Assert.Equal(file.Name, entry.Name); Assert.Equal(entryName, entry.FullName); Assert.Equal(entryName, entry.ToString()); Assert.Equal(archive, entry.Archive); } else if (file.IsFolder) { if (entry == null) //entry not found { string entryNameOtherSlash = FlipSlashes(entryName); bool isEmtpy = !files.Any( f => f.IsFile && (f.FullName.StartsWith(entryName, StringComparison.OrdinalIgnoreCase) || f.FullName.StartsWith(entryNameOtherSlash, StringComparison.OrdinalIgnoreCase))); if (requireExplicit || isEmtpy) { Assert.Contains("emptydir", entryName); } if ((!requireExplicit && !isEmtpy) || entryName.Contains("emptydir")) count--; //discount this entry } else { using (Stream es = entry.Open()) { try { Assert.Equal(0, es.Length); } catch (NotSupportedException) { try { Assert.Equal(-1, es.ReadByte()); } catch (Exception) { Console.WriteLine("Didn't return EOF"); throw; } } } } } }); Assert.Equal(count, archive.Entries.Count); } } private static string FlipSlashes(string name) { Debug.Assert(!(name.Contains("\\") && name.Contains("/"))); return name.Contains("\\") ? name.Replace("\\", "/") : name.Contains("/") ? name.Replace("/", "\\") : name; } public static void DirsEqual(string actual, string expected) { var expectedList = FileData.InPath(expected); var actualList = Directory.GetFiles(actual, "*.*", SearchOption.AllDirectories); var actualFolders = Directory.GetDirectories(actual, "*.*", SearchOption.AllDirectories); var actualCount = actualList.Length + actualFolders.Length; Assert.Equal(expectedList.Count, actualCount); ItemEqual(actualList, expectedList, isFile: true); ItemEqual(actualFolders, expectedList, isFile: false); } public static void DirFileNamesEqual(string actual, string expected) { IEnumerable<string> actualEntries = Directory.EnumerateFileSystemEntries(actual, "*", SearchOption.AllDirectories); IEnumerable<string> expectedEntries = Directory.EnumerateFileSystemEntries(expected, "*", SearchOption.AllDirectories); Assert.True(Enumerable.SequenceEqual(expectedEntries.Select(i => Path.GetFileName(i)), actualEntries.Select(i => Path.GetFileName(i)))); } private static void ItemEqual(string[] actualList, List<FileData> expectedList, bool isFile) { for (int i = 0; i < actualList.Length; i++) { var actualFile = actualList[i]; string aEntry = Path.GetFullPath(actualFile); string aName = Path.GetFileName(aEntry); var bData = expectedList.Where(f => string.Equals(f.Name, aName, StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); string bEntry = Path.GetFullPath(Path.Combine(bData.OrigFolder, bData.FullName)); string bName = Path.GetFileName(bEntry); // expected 'emptydir' folder doesn't exist because MSBuild doesn't copy empty dir if (!isFile && aName.Contains("emptydir") && bName.Contains("emptydir")) continue; //we want it to be false that one of them is a directory and the other isn't Assert.False(Directory.Exists(aEntry) ^ Directory.Exists(bEntry), "Directory in one is file in other"); //contents same if (isFile) { Stream sa = StreamHelpers.CreateTempCopyStream(aEntry).Result; Stream sb = StreamHelpers.CreateTempCopyStream(bEntry).Result; StreamsEqual(sa, sb); } } } /// <param name="useSpansForWriting">Tests the Span overloads of Write</param> /// <param name="writeInChunks">Writes in chunks of 5 to test Write with a nonzero offset</param> public static async Task CreateFromDir(string directory, Stream archiveStream, ZipArchiveMode mode, bool useSpansForWriting = false, bool writeInChunks = false) { var files = FileData.InPath(directory); using (ZipArchive archive = new ZipArchive(archiveStream, mode, true)) { foreach (var i in files) { if (i.IsFolder) { string entryName = i.FullName; ZipArchiveEntry e = archive.CreateEntry(entryName.Replace('\\', '/') + "/"); e.LastWriteTime = i.LastModifiedDate; } } foreach (var i in files) { if (i.IsFile) { string entryName = i.FullName; var installStream = await StreamHelpers.CreateTempCopyStream(Path.Combine(i.OrigFolder, i.FullName)); if (installStream != null) { ZipArchiveEntry e = archive.CreateEntry(entryName.Replace('\\', '/')); e.LastWriteTime = i.LastModifiedDate; using (Stream entryStream = e.Open()) { int bytesRead; var buffer = new byte[1024]; if (useSpansForWriting) { while ((bytesRead = installStream.Read(new Span<byte>(buffer))) != 0) { entryStream.Write(new ReadOnlySpan<byte>(buffer, 0, bytesRead)); } } else if (writeInChunks) { while ((bytesRead = installStream.Read(buffer, 0, buffer.Length)) != 0) { for (int k = 0; k < bytesRead; k += 5) entryStream.Write(buffer, k, Math.Min(5, bytesRead - k)); } } else { while ((bytesRead = installStream.Read(buffer, 0, buffer.Length)) != 0) { entryStream.Write(buffer, 0, bytesRead); } } } } } } } } internal static void AddEntry(ZipArchive archive, string name, string contents, DateTimeOffset lastWrite) { ZipArchiveEntry e = archive.CreateEntry(name); e.LastWriteTime = lastWrite; using (StreamWriter w = new StreamWriter(e.Open())) { w.WriteLine(contents); } } } }
// // TextPart.cs // // Author: Jeffrey Stedfast <[email protected]> // // Copyright (c) 2013-2015 Xamarin Inc. (www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.IO; using System.Text; #if PORTABLE using EncoderReplacementFallback = Portable.Text.EncoderReplacementFallback; using DecoderReplacementFallback = Portable.Text.DecoderReplacementFallback; using EncoderExceptionFallback = Portable.Text.EncoderExceptionFallback; using DecoderExceptionFallback = Portable.Text.DecoderExceptionFallback; using EncoderFallbackException = Portable.Text.EncoderFallbackException; using DecoderFallbackException = Portable.Text.DecoderFallbackException; using DecoderFallbackBuffer = Portable.Text.DecoderFallbackBuffer; using DecoderFallback = Portable.Text.DecoderFallback; using Encoding = Portable.Text.Encoding; using Encoder = Portable.Text.Encoder; using Decoder = Portable.Text.Decoder; #endif using MimeKit.IO; using MimeKit.IO.Filters; using MimeKit.Utils; namespace MimeKit { /// <summary> /// A Textual MIME part. /// </summary> /// <remarks> /// <para>Unless overridden, all textual parts parsed by the <see cref="MimeParser"/>, /// such as text/plain or text/html, will be represented by a <see cref="TextPart"/>.</para> /// <para>For more information about text media types, see section 4.1 of /// http://www.ietf.org/rfc/rfc2046.txt</para> /// </remarks> public class TextPart : MimePart { /// <summary> /// Initializes a new instance of the <see cref="MimeKit.TextPart"/> class. /// </summary> /// <remarks>This constructor is used by <see cref="MimeKit.MimeParser"/>.</remarks> /// <param name="entity">Information used by the constructor.</param> public TextPart (MimeEntityConstructorInfo entity) : base (entity) { } /// <summary> /// Initializes a new instance of the <see cref="MimeKit.TextPart"/> /// class with the specified text subtype. /// </summary> /// <remarks> /// Creates a new <see cref="TextPart"/> with the specified subtype. /// </remarks> /// <param name="subtype">The media subtype.</param> /// <param name="args">An array of initialization parameters: headers, charset encoding and text.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="subtype"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="args"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentException"> /// <para><paramref name="args"/> contains more than one <see cref="System.Text.Encoding"/>.</para> /// <para>-or-</para> /// <para><paramref name="args"/> contains more than one <see cref="System.String"/>.</para> /// <para>-or-</para> /// <para><paramref name="args"/> contains one or more arguments of an unknown type.</para> /// </exception> public TextPart (string subtype, params object[] args) : this (subtype) { if (args == null) throw new ArgumentNullException ("args"); // Default to UTF8 if not given. Encoding encoding = null; string text = null; foreach (object obj in args) { if (obj == null || TryInit (obj)) continue; var enc = obj as Encoding; if (enc != null) { if (encoding != null) throw new ArgumentException ("An encoding should not be specified more than once."); encoding = enc; continue; } var str = obj as string; if (str != null) { if (text != null) throw new ArgumentException ("The text should not be specified more than once."); text = str; continue; } throw new ArgumentException ("Unknown initialization parameter: " + obj.GetType ()); } if (text != null) { encoding = encoding ?? Encoding.UTF8; SetText (encoding, text); } } /// <summary> /// Initializes a new instance of the <see cref="MimeKit.TextPart"/> /// class with the specified text subtype. /// </summary> /// <remarks> /// Creates a new <see cref="TextPart"/> with the specified subtype. /// </remarks> /// <param name="subtype">The media subtype.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="subtype"/> is <c>null</c>. /// </exception> public TextPart (string subtype) : base ("text", subtype) { } /// <summary> /// Initializes a new instance of the <see cref="MimeKit.TextPart"/> /// class with a Content-Type of text/plain. /// </summary> /// <remarks> /// Creates a default <see cref="TextPart"/> with a mime-type of text/plain. /// </remarks> public TextPart () : base ("text", "plain") { } /// <summary> /// Gets whether or not this text part contains plain text. /// </summary> /// <remarks> /// Checks whether or not the text part's Content-Type is text/plain. /// </remarks> /// <value><c>true</c> if the text is html; otherwise, <c>false</c>.</value> public bool IsPlain { get { return ContentType.Matches ("text", "plain"); } } /// <summary> /// Gets whether or not this text part contains HTML. /// </summary> /// <remarks> /// Checks whether or not the text part's Content-Type is text/html. /// </remarks> /// <value><c>true</c> if the text is html; otherwise, <c>false</c>.</value> public bool IsHtml { get { return ContentType.Matches ("text", "html"); } } /// <summary> /// Gets the decoded text content. /// </summary> /// <remarks> /// <para>If the charset parameter on the <see cref="MimeEntity.ContentType"/> /// is set, it will be used in order to convert the raw content into unicode. /// If that fails or if the charset parameter is not set, iso-8859-1 will be /// used instead.</para> /// <para>For more control, use <see cref="GetText(System.Text.Encoding)"/> /// or <see cref="GetText(System.String)"/>.</para> /// </remarks> /// <value>The text.</value> public string Text { get { if (ContentObject == null) return string.Empty; var charset = ContentType.Parameters["charset"]; using (var memory = new MemoryStream ()) { ContentObject.DecodeTo (memory); #if PORTABLE var content = memory.ToArray (); #else var content = memory.GetBuffer (); #endif Encoding encoding = null; if (charset != null) { try { encoding = CharsetUtils.GetEncoding (charset); } catch (NotSupportedException) { } } if (encoding == null) { try { return CharsetUtils.UTF8.GetString (content, 0, (int) memory.Length); } catch (DecoderFallbackException) { // fall back to iso-8859-1 encoding = CharsetUtils.Latin1; } } return encoding.GetString (content, 0, (int) memory.Length); } } set { SetText (Encoding.UTF8, value); } } /// <summary> /// Gets the decoded text content using the provided charset encoding to /// override the charset specified in the Content-Type parameters. /// </summary> /// <remarks> /// Uses the provided charset encoding to convert the raw text content /// into a unicode string, overriding any charset specified in the /// Content-Type header. /// </remarks> /// <returns>The decoded text.</returns> /// <param name="encoding">The charset encoding to use.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="encoding"/> is <c>null</c>. /// </exception> public string GetText (Encoding encoding) { if (encoding == null) throw new ArgumentNullException ("encoding"); if (ContentObject == null) return string.Empty; using (var memory = new MemoryStream ()) { ContentObject.DecodeTo (memory); #if PORTABLE var buffer = memory.ToArray (); #else var buffer = memory.GetBuffer (); #endif return encoding.GetString (buffer, 0, (int) memory.Length); } } /// <summary> /// Gets the decoded text content using the provided charset to override /// the charset specified in the Content-Type parameters. /// </summary> /// <remarks> /// Uses the provided charset encoding to convert the raw text content /// into a unicode string, overriding any charset specified in the /// Content-Type header. /// </remarks> /// <returns>The decoded text.</returns> /// <param name="charset">The charset encoding to use.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="charset"/> is <c>null</c>. /// </exception> /// <exception cref="System.NotSupportedException"> /// The <paramref name="charset"/> is not supported. /// </exception> public string GetText (string charset) { if (charset == null) throw new ArgumentNullException ("charset"); return GetText (CharsetUtils.GetEncoding (charset)); } /// <summary> /// Sets the text content and the charset parameter in the Content-Type header. /// </summary> /// <remarks> /// This method is similar to setting the <see cref="Text"/> property, but allows /// specifying a charset encoding to use. Also updates the /// <see cref="ContentType.Charset"/> property. /// </remarks> /// <param name="encoding">The charset encoding.</param> /// <param name="text">The text content.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="encoding"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="text"/> is <c>null</c>.</para> /// </exception> public void SetText (Encoding encoding, string text) { if (encoding == null) throw new ArgumentNullException ("encoding"); if (text == null) throw new ArgumentNullException ("text"); ContentType.Parameters["charset"] = CharsetUtils.GetMimeCharset (encoding); var content = new MemoryStream (encoding.GetBytes (text)); ContentObject = new ContentObject (content); } /// <summary> /// Sets the text content and the charset parameter in the Content-Type header. /// </summary> /// <remarks> /// This method is similar to setting the <see cref="Text"/> property, but allows /// specifying a charset encoding to use. Also updates the /// <see cref="ContentType.Charset"/> property. /// </remarks> /// <param name="charset">The charset encoding.</param> /// <param name="text">The text content.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="charset"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="text"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.NotSupportedException"> /// The <paramref name="charset"/> is not supported. /// </exception> public void SetText (string charset, string text) { if (charset == null) throw new ArgumentNullException ("charset"); if (text == null) throw new ArgumentNullException ("text"); SetText (CharsetUtils.GetEncoding (charset), text); } } }
// // Pop3Engine.cs // // Author: Jeffrey Stedfast <[email protected]> // // Copyright (c) 2013-2015 Xamarin Inc. (www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.IO; using System.Text; using System.Threading; using System.Collections.Generic; #if NETFX_CORE using Encoding = Portable.Text.Encoding; using EncoderExceptionFallback = Portable.Text.EncoderExceptionFallback; using DecoderExceptionFallback = Portable.Text.DecoderExceptionFallback; using DecoderFallbackException = Portable.Text.DecoderFallbackException; #endif namespace MailKit.Net.Pop3 { /// <summary> /// The state of the <see cref="Pop3Engine"/>. /// </summary> enum Pop3EngineState { /// <summary> /// The Pop3Engine is in the disconnected state. /// </summary> Disconnected, /// <summary> /// The Pop3Engine is in the connected state. /// </summary> Connected, /// <summary> /// The Pop3Engine is in the transaction state, indicating that it is /// authenticated and may retrieve messages from the server. /// </summary> Transaction } /// <summary> /// A POP3 command engine. /// </summary> class Pop3Engine { static readonly Encoding UTF8 = Encoding.GetEncoding (65001, new EncoderExceptionFallback (), new DecoderExceptionFallback ()); static readonly Encoding Latin1 = Encoding.GetEncoding (28591); readonly List<Pop3Command> queue; Pop3Stream stream; int nextId; /// <summary> /// Initializes a new instance of the <see cref="MailKit.Net.Pop3.Pop3Engine"/> class. /// </summary> public Pop3Engine () { AuthenticationMechanisms = new HashSet<string> (); Capabilities = Pop3Capabilities.User; queue = new List<Pop3Command> (); nextId = 1; } /// <summary> /// Gets the authentication mechanisms supported by the POP3 server. /// </summary> /// <remarks> /// The authentication mechanisms are queried durring the /// <see cref="Connect"/> method. /// </remarks> /// <value>The authentication mechanisms.</value> public HashSet<string> AuthenticationMechanisms { get; private set; } /// <summary> /// Gets the capabilities supported by the POP3 server. /// </summary> /// <remarks> /// The capabilities will not be known until a successful connection /// has been made via the <see cref="Connect"/> method. /// </remarks> /// <value>The capabilities.</value> public Pop3Capabilities Capabilities { get; set; } /// <summary> /// Gets the underlying POP3 stream. /// </summary> /// <remarks> /// Gets the underlying POP3 stream. /// </remarks> /// <value>The pop3 stream.</value> public Pop3Stream Stream { get { return stream; } } /// <summary> /// Gets or sets the state of the engine. /// </summary> /// <remarks> /// Gets or sets the state of the engine. /// </remarks> /// <value>The engine state.</value> public Pop3EngineState State { get; internal set; } /// <summary> /// Gets whether or not the engine is currently connected to a POP3 server. /// </summary> /// <remarks> /// Gets whether or not the engine is currently connected to a POP3 server. /// </remarks> /// <value><c>true</c> if the engine is connected; otherwise, <c>false</c>.</value> public bool IsConnected { get { return stream != null && stream.IsConnected; } } /// <summary> /// Gets the APOP authentication token. /// </summary> /// <remarks> /// Gets the APOP authentication token. /// </remarks> /// <value>The APOP authentication token.</value> public string ApopToken { get; private set; } /// <summary> /// Gets the EXPIRE extension policy value. /// </summary> /// <remarks> /// Gets the EXPIRE extension policy value. /// </remarks> /// <value>The EXPIRE policy.</value> public int ExpirePolicy { get; private set; } /// <summary> /// Gets the implementation details of the server. /// </summary> /// <remarks> /// Gets the implementation details of the server. /// </remarks> /// <value>The implementation details.</value> public string Implementation { get; private set; } /// <summary> /// Gets the login delay. /// </summary> /// <remarks> /// Gets the login delay. /// </remarks> /// <value>The login delay.</value> public int LoginDelay { get; private set; } /// <summary> /// Takes posession of the <see cref="Pop3Stream"/> and reads the greeting. /// </summary> /// <remarks> /// Takes posession of the <see cref="Pop3Stream"/> and reads the greeting. /// </remarks> /// <param name="pop3">The pop3 stream.</param> /// <param name="cancellationToken">The cancellation token</param> public void Connect (Pop3Stream pop3, CancellationToken cancellationToken) { if (stream != null) stream.Dispose (); Capabilities = Pop3Capabilities.User; AuthenticationMechanisms.Clear (); State = Pop3EngineState.Disconnected; ApopToken = null; stream = pop3; // read the pop3 server greeting var greeting = ReadLine (cancellationToken).TrimEnd (); int index = greeting.IndexOf (' '); string token, text; if (index != -1) { token = greeting.Substring (0, index); while (index < greeting.Length && char.IsWhiteSpace (greeting[index])) index++; if (index < greeting.Length) text = greeting.Substring (index); else text = string.Empty; } else { text = string.Empty; token = greeting; } if (token != "+OK") { stream.Dispose (); stream = null; throw new Pop3ProtocolException (string.Format ("Unexpected greeting from server: {0}", greeting)); } index = text.IndexOf ('>'); if (text.Length > 0 && text[0] == '<' && index != -1) { ApopToken = text.Substring (0, index + 1); Capabilities |= Pop3Capabilities.Apop; } State = Pop3EngineState.Connected; } public event EventHandler<EventArgs> Disconnected; void OnDisconnected () { var handler = Disconnected; if (handler != null) handler (this, EventArgs.Empty); } /// <summary> /// Disconnects the <see cref="Pop3Engine"/>. /// </summary> /// <remarks> /// Disconnects the <see cref="Pop3Engine"/>. /// </remarks> public void Disconnect () { if (stream != null) { stream.Dispose (); stream = null; } if (State != Pop3EngineState.Disconnected) { State = Pop3EngineState.Disconnected; OnDisconnected (); } } /// <summary> /// Reads a single line from the <see cref="Pop3Stream"/>. /// </summary> /// <returns>The line.</returns> /// <param name="cancellationToken">The cancellation token.</param> /// <exception cref="System.InvalidOperationException"> /// The engine is not connected. /// </exception> /// <exception cref="System.OperationCanceledException"> /// The operation was canceled via the cancellation token. /// </exception> /// <exception cref="System.IO.IOException"> /// An I/O error occurred. /// </exception> public string ReadLine (CancellationToken cancellationToken) { if (stream == null) throw new InvalidOperationException (); using (var memory = new MemoryStream ()) { int offset, count; byte[] buf; while (!stream.ReadLine (out buf, out offset, out count, cancellationToken)) memory.Write (buf, offset, count); memory.Write (buf, offset, count); count = (int) memory.Length; #if !NETFX_CORE buf = memory.GetBuffer (); #else buf = memory.ToArray (); #endif try { return UTF8.GetString (buf, 0, count); } catch (DecoderFallbackException) { return Latin1.GetString (buf, 0, count); } } } public static Pop3CommandStatus GetCommandStatus (string response, out string text) { int index = response.IndexOf (' '); string token; if (index != -1) { token = response.Substring (0, index); while (index < response.Length && char.IsWhiteSpace (response[index])) index++; if (index < response.Length) text = response.Substring (index); else text = string.Empty; } else { text = string.Empty; token = response; } if (token == "+OK") return Pop3CommandStatus.Ok; if (token == "-ERR") return Pop3CommandStatus.Error; if (token == "+") return Pop3CommandStatus.Continue; return Pop3CommandStatus.ProtocolError; } void SendCommand (Pop3Command pc) { var buf = Encoding.UTF8.GetBytes (pc.Command + "\r\n"); stream.Write (buf, 0, buf.Length); } void ReadResponse (Pop3Command pc) { string response, text; try { response = ReadLine (pc.CancellationToken).TrimEnd (); } catch { pc.Status = Pop3CommandStatus.ProtocolError; Disconnect (); throw; } pc.Status = GetCommandStatus (response, out text); pc.StatusText = text; switch (pc.Status) { case Pop3CommandStatus.ProtocolError: Disconnect (); throw new Pop3ProtocolException (string.Format ("Unexpected response from server: {0}", response)); case Pop3CommandStatus.Continue: case Pop3CommandStatus.Ok: if (pc.Handler != null) { try { pc.Handler (this, pc, text); } catch { pc.Status = Pop3CommandStatus.ProtocolError; Disconnect (); throw; } } break; } } public int Iterate () { if (stream == null) throw new InvalidOperationException (); if (queue.Count == 0) return 0; int count = (Capabilities & Pop3Capabilities.Pipelining) != 0 ? queue.Count : 1; var cancellationToken = queue[0].CancellationToken; var active = new List<Pop3Command> (); if (cancellationToken.IsCancellationRequested) { queue.RemoveAll (x => x.CancellationToken.IsCancellationRequested); cancellationToken.ThrowIfCancellationRequested (); } for (int i = 0; i < count; i++) { var pc = queue[0]; if (i > 0 && !pc.CancellationToken.Equals (cancellationToken)) break; queue.RemoveAt (0); pc.Status = Pop3CommandStatus.Active; active.Add (pc); SendCommand (pc); } stream.Flush (cancellationToken); for (int i = 0; i < active.Count; i++) ReadResponse (active[i]); return active[active.Count - 1].Id; } public Pop3Command QueueCommand (CancellationToken cancellationToken, Pop3CommandHandler handler, string format, params object[] args) { var pc = new Pop3Command (cancellationToken, handler, format, args); pc.Id = nextId++; queue.Add (pc); return pc; } static void CapaHandler (Pop3Engine engine, Pop3Command pc, string text) { // clear all CAPA response capabilities (except the APOP capability) engine.Capabilities &= Pop3Capabilities.Apop; engine.AuthenticationMechanisms.Clear (); engine.Implementation = null; engine.ExpirePolicy = 0; engine.LoginDelay = 0; if (pc.Status != Pop3CommandStatus.Ok) return; string response; do { if ((response = engine.ReadLine (pc.CancellationToken).TrimEnd ()) == ".") break; int index = response.IndexOf (' '); string token, data; int value; if (index != -1) { token = response.Substring (0, index); while (index < response.Length && char.IsWhiteSpace (response[index])) index++; if (index < response.Length) data = response.Substring (index); else data = string.Empty; } else { data = string.Empty; token = response; } switch (token) { case "EXPIRE": engine.Capabilities |= Pop3Capabilities.Expire; var tokens = data.Split (' '); if (int.TryParse (tokens[0], out value)) engine.ExpirePolicy = value; else if (tokens[0] == "NEVER") engine.ExpirePolicy = -1; break; case "IMPLEMENTATION": engine.Implementation = data; break; case "LOGIN-DELAY": if (int.TryParse (data, out value)) { engine.Capabilities |= Pop3Capabilities.LoginDelay; engine.LoginDelay = value; } break; case "PIPELINING": engine.Capabilities |= Pop3Capabilities.Pipelining; break; case "RESP-CODES": engine.Capabilities |= Pop3Capabilities.ResponseCodes; break; case "SASL": engine.Capabilities |= Pop3Capabilities.Sasl; foreach (var authmech in data.Split (new [] { ' ' }, StringSplitOptions.RemoveEmptyEntries)) engine.AuthenticationMechanisms.Add (authmech); break; case "STLS": engine.Capabilities |= Pop3Capabilities.StartTLS; break; case "TOP": engine.Capabilities |= Pop3Capabilities.Top; break; case "UIDL": engine.Capabilities |= Pop3Capabilities.UIDL; break; case "USER": engine.Capabilities |= Pop3Capabilities.User; break; case "UTF8": engine.Capabilities |= Pop3Capabilities.UTF8; foreach (var item in data.Split (' ')) { if (item == "USER") engine.Capabilities |= Pop3Capabilities.UTF8User; } break; case "LANG": engine.Capabilities |= Pop3Capabilities.Lang; break; } } while (true); } public Pop3CommandStatus QueryCapabilities (CancellationToken cancellationToken) { if (stream == null) throw new InvalidOperationException (); var pc = QueueCommand (cancellationToken, CapaHandler, "CAPA"); while (Iterate () < pc.Id) { // continue processing commands... } return pc.Status; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using System.Drawing; using Android.Graphics; using Android.Content.PM; using Android.Hardware; using System.Threading.Tasks; using System.Threading; using Camera = Android.Hardware.Camera; namespace ZXing.Mobile { // based on https://github.com/xamarin/monodroid-samples/blob/master/ApiDemo/Graphics/CameraPreview.cs public class ZXingSurfaceView : SurfaceView, ISurfaceHolderCallback, Android.Hardware.Camera.IPreviewCallback, Android.Hardware.Camera.IAutoFocusCallback { private const int MIN_FRAME_WIDTH = 240; private const int MIN_FRAME_HEIGHT = 240; private const int MAX_FRAME_WIDTH = 600; private const int MAX_FRAME_HEIGHT = 400; CancellationTokenSource tokenSource; ISurfaceHolder surface_holder; Android.Hardware.Camera camera; MobileBarcodeScanningOptions options; Action<ZXing.Result> callback; Activity activity; bool isAnalyzing = false; bool wasScanned = false; bool isTorchOn = false; int cameraId = 0; static ManualResetEventSlim _cameraLockEvent = new ManualResetEventSlim(true); public ZXingSurfaceView (Activity activity) : base (activity) { this.activity = activity; Init (); } protected ZXingSurfaceView(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) { Init (); } void Init () { CheckPermissions (); this.surface_holder = Holder; this.surface_holder.AddCallback (this); this.surface_holder.SetType (SurfaceType.PushBuffers); this.tokenSource = new System.Threading.CancellationTokenSource(); } void CheckPermissions() { var perf = PerformanceCounter.Start (); Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "Checking Camera Permissions..."); if (!PlatformChecks.HasCameraPermission (this.Context)) { var msg = "ZXing.Net.Mobile requires permission to use the Camera (" + Android.Manifest.Permission.Camera + "), but was not found in your AndroidManifest.xml file."; Android.Util.Log.Error ("ZXing.Net.Mobile", msg); throw new UnauthorizedAccessException (msg); } PerformanceCounter.Stop (perf, "CheckPermissions took {0}ms"); } public void SurfaceCreated (ISurfaceHolder holder) { } public void SurfaceChanged (ISurfaceHolder holder, Format format, int w, int h) { if (camera == null) return; var perf = PerformanceCounter.Start (); var parameters = camera.GetParameters (); parameters.PreviewFormat = ImageFormatType.Nv21; var availableResolutions = new List<CameraResolution> (); foreach (var sps in parameters.SupportedPreviewSizes) { availableResolutions.Add (new CameraResolution { Width = sps.Width, Height = sps.Height }); } // Try and get a desired resolution from the options selector var resolution = options.GetResolution (availableResolutions); // If the user did not specify a resolution, let's try and find a suitable one if (resolution == null) { // Loop through all supported sizes foreach (var sps in parameters.SupportedPreviewSizes) { // Find one that's >= 640x360 but <= 1000x1000 // This will likely pick the *smallest* size in that range, which should be fine if (sps.Width >= 640 && sps.Width <= 1000 && sps.Height >= 360 && sps.Height <= 1000) { resolution = new CameraResolution { Width = sps.Width, Height = sps.Height }; break; } } } // Google Glass requires this fix to display the camera output correctly if (Build.Model.Contains ("Glass")) { resolution = new CameraResolution { Width = 640, Height = 360 }; // Glass requires 30fps parameters.SetPreviewFpsRange (30000, 30000); } // Hopefully a resolution was selected at some point if (resolution != null) { Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Selected Resolution: " + resolution.Width + "x" + resolution.Height); parameters.SetPreviewSize (resolution.Width, resolution.Height); } camera.SetParameters (parameters); SetCameraDisplayOrientation (this.activity); camera.SetPreviewDisplay (holder); camera.StartPreview (); //cameraResolution = new Size(parameters.PreviewSize.Width, parameters.PreviewSize.Height); PerformanceCounter.Stop (perf, "SurfaceChanged took {0}ms"); AutoFocus(); } public void SurfaceDestroyed (ISurfaceHolder holder) { ShutdownCamera (); } public byte[] rotateCounterClockwise(byte[] data, int width, int height) { var rotatedData = new byte[data.Length]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) rotatedData[x * height + height - y - 1] = data[x + y * width]; } return rotatedData; } DateTime lastPreviewAnalysis = DateTime.UtcNow; BarcodeReader barcodeReader = null; Task processingTask; public void OnPreviewFrame (byte [] bytes, Android.Hardware.Camera camera) { if (!isAnalyzing) return; //Check and see if we're still processing a previous frame if (processingTask != null && !processingTask.IsCompleted) return; if ((DateTime.UtcNow - lastPreviewAnalysis).TotalMilliseconds < options.DelayBetweenAnalyzingFrames) return; // Delay a minimum between scans if (wasScanned && ((DateTime.UtcNow - lastPreviewAnalysis).TotalMilliseconds < options.DelayBetweenContinuousScans)) return; wasScanned = false; var cameraParameters = camera.GetParameters(); var width = cameraParameters.PreviewSize.Width; var height = cameraParameters.PreviewSize.Height; //var img = new YuvImage(bytes, ImageFormatType.Nv21, cameraParameters.PreviewSize.Width, cameraParameters.PreviewSize.Height, null); lastPreviewAnalysis = DateTime.UtcNow; processingTask = Task.Factory.StartNew (() => { try { if (barcodeReader == null) { barcodeReader = new BarcodeReader (null, null, null, (p, w, h, f) => new PlanarYUVLuminanceSource (p, w, h, 0, 0, w, h, false)); //new PlanarYUVLuminanceSource(p, w, h, dataRect.Left, dataRect.Top, dataRect.Width(), dataRect.Height(), false)) if (this.options.TryHarder.HasValue) barcodeReader.Options.TryHarder = this.options.TryHarder.Value; if (this.options.PureBarcode.HasValue) barcodeReader.Options.PureBarcode = this.options.PureBarcode.Value; if (!string.IsNullOrEmpty (this.options.CharacterSet)) barcodeReader.Options.CharacterSet = this.options.CharacterSet; if (this.options.TryInverted.HasValue) barcodeReader.TryInverted = this.options.TryInverted.Value; if (this.options.PossibleFormats != null && this.options.PossibleFormats.Count > 0) { barcodeReader.Options.PossibleFormats = new List<BarcodeFormat> (); foreach (var pf in this.options.PossibleFormats) barcodeReader.Options.PossibleFormats.Add (pf); } } bool rotate = false; int newWidth = width; int newHeight = height; var cDegrees = getCameraDisplayOrientation(this.activity); if (cDegrees == 90 || cDegrees == 270) { rotate = true; newWidth = height; newHeight = width; } var start = PerformanceCounter.Start(); if (rotate) bytes = rotateCounterClockwise(bytes, width, height); var result = barcodeReader.Decode (bytes, newWidth, newHeight, RGBLuminanceSource.BitmapFormat.Unknown); PerformanceCounter.Stop(start, "Decode Time: {0} ms (width: " + width + ", height: " + height + ", degrees: " + cDegrees + ", rotate: " + rotate + ")"); if (result == null || string.IsNullOrEmpty (result.Text)) return; Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "Barcode Found: " + result.Text); wasScanned = true; callback (result); } catch (ReaderException) { Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "No barcode Found"); // ignore this exception; it happens every time there is a failed scan } catch (Exception) { // TODO: this one is unexpected.. log or otherwise handle it throw; } }); } public void OnAutoFocus (bool success, Android.Hardware.Camera camera) { Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "AutoFocused"); Task.Factory.StartNew(() => { int slept = 0; while (!tokenSource.IsCancellationRequested && slept < 2000) { System.Threading.Thread.Sleep(100); slept += 100; } if (!tokenSource.IsCancellationRequested) AutoFocus(); }); } public override bool OnTouchEvent (MotionEvent e) { var r = base.OnTouchEvent(e); AutoFocus(); return r; } public void AutoFocus() { if (camera != null) { if (!tokenSource.IsCancellationRequested) { Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "AutoFocus Requested"); try { camera.AutoFocus(this); } catch (Exception ex) { Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "AutoFocus Failed: {0}", ex); } } } } //int cameraDegrees = 0; int getCameraDisplayOrientation(Activity context) { var degrees = 0; var display = context.WindowManager.DefaultDisplay; var rotation = display.Rotation; switch(rotation) { case SurfaceOrientation.Rotation0: degrees = 0; break; case SurfaceOrientation.Rotation90: degrees = 90; break; case SurfaceOrientation.Rotation180: degrees = 180; break; case SurfaceOrientation.Rotation270: degrees = 270; break; } Camera.CameraInfo info = new Camera.CameraInfo(); Camera.GetCameraInfo(cameraId, info); int correctedDegrees = (360 + info.Orientation - degrees) % 360; return correctedDegrees; } public void SetCameraDisplayOrientation(Activity context) { var degrees = getCameraDisplayOrientation (context); Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "Changing Camera Orientation to: " + degrees); //cameraDegrees = degrees; try { camera.SetDisplayOrientation (degrees); } catch (Exception ex) { Android.Util.Log.Error (MobileBarcodeScanner.TAG, ex.ToString ()); } } public void ShutdownCamera () { tokenSource.Cancel(); if (camera == null) { ReleaseExclusiveAccess(); return; } var theCamera = camera; camera = null; // make this asyncronous so that we can return from the view straight away instead of waiting for the camera to release. Task.Factory.StartNew(() => { try { theCamera.SetPreviewCallback(null); theCamera.StopPreview(); theCamera.Release(); } catch (Exception e) { Android.Util.Log.Error(MobileBarcodeScanner.TAG, e.ToString()); } finally { ReleaseExclusiveAccess(); } }); } private void drawResultPoints(Bitmap barcode, ZXing.Result rawResult) { var points = rawResult.ResultPoints; if (points != null && points.Length > 0) { var canvas = new Canvas(barcode); Paint paint = new Paint(); paint.Color = Android.Graphics.Color.White; paint.StrokeWidth = 3.0f; paint.SetStyle(Paint.Style.Stroke); var border = new RectF(2, 2, barcode.Width - 2, barcode.Height - 2); canvas.DrawRect(border, paint); paint.Color = Android.Graphics.Color.Purple; if (points.Length == 2) { paint.StrokeWidth = 4.0f; drawLine(canvas, paint, points[0], points[1]); } else if (points.Length == 4 && (rawResult.BarcodeFormat == BarcodeFormat.UPC_A || rawResult.BarcodeFormat == BarcodeFormat.EAN_13)) { // Hacky special case -- draw two lines, for the barcode and metadata drawLine(canvas, paint, points[0], points[1]); drawLine(canvas, paint, points[2], points[3]); } else { paint.StrokeWidth = 10.0f; foreach (ResultPoint point in points) canvas.DrawPoint(point.X, point.Y, paint); } } } private void drawLine(Canvas canvas, Paint paint, ResultPoint a, ResultPoint b) { canvas.DrawLine(a.X, a.Y, b.X, b.Y, paint); } public Size FindBestPreviewSize(Android.Hardware.Camera.Parameters p, Size screenRes) { var max = p.SupportedPreviewSizes.Count; var s = p.SupportedPreviewSizes[max - 1]; return new Size(s.Width, s.Height); } private void GetExclusiveAccess() { Console.WriteLine ("Getting Camera Exclusive access"); var result = _cameraLockEvent.Wait(TimeSpan.FromSeconds(10)); if (!result) throw new Exception("Couldn't get exclusive access to the camera"); _cameraLockEvent.Reset(); Console.WriteLine ("Got Camera Exclusive access"); } private void ReleaseExclusiveAccess() { // release the camera exclusive access allowing it to be used again. Console.WriteLine ("Releasing Exclusive access to camera"); _cameraLockEvent.Set(); } public void StartScanning (MobileBarcodeScanningOptions options, Action<Result> callback) { this.callback = callback; this.options = options; lastPreviewAnalysis = DateTime.UtcNow.AddMilliseconds(options.InitialDelayBeforeAnalyzingFrames); isAnalyzing = true; Console.WriteLine ("StartScanning"); CheckPermissions (); var perf = PerformanceCounter.Start (); GetExclusiveAccess(); try { var version = Build.VERSION.SdkInt; if (version >= BuildVersionCodes.Gingerbread) { Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "Checking Number of cameras..."); var numCameras = Android.Hardware.Camera.NumberOfCameras; var camInfo = new Android.Hardware.Camera.CameraInfo(); var found = false; Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "Found " + numCameras + " cameras..."); var whichCamera = CameraFacing.Back; if (options.UseFrontCameraIfAvailable.HasValue && options.UseFrontCameraIfAvailable.Value) whichCamera = CameraFacing.Front; for (int i = 0; i < numCameras; i++) { Android.Hardware.Camera.GetCameraInfo(i, camInfo); if (camInfo.Facing == whichCamera) { Android.Util.Log.Debug (MobileBarcodeScanner.TAG, "Found " + whichCamera + " Camera, opening..."); camera = Android.Hardware.Camera.Open(i); cameraId = i; found = true; break; } } if (!found) { Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Finding " + whichCamera + " camera failed, opening camera 0..."); camera = Android.Hardware.Camera.Open(0); cameraId = 0; } } else { camera = Android.Hardware.Camera.Open(); } if (camera == null) Android.Util.Log.Debug(MobileBarcodeScanner.TAG, "Camera is null :("); camera.SetPreviewCallback (this); } catch (Exception ex) { ShutdownCamera (); Console.WriteLine("Setup Error: " + ex); } PerformanceCounter.Stop (perf, "SurfaceCreated took {0}ms"); } public void StartScanning (Action<Result> callback) { StartScanning (new MobileBarcodeScanningOptions (), callback); } public void StopScanning () { isAnalyzing = false; ShutdownCamera (); } public void PauseAnalysis () { isAnalyzing = false; } public void ResumeAnalysis () { isAnalyzing = true; } public void SetTorch (bool on) { if (!this.Context.PackageManager.HasSystemFeature(PackageManager.FeatureCameraFlash)) { Android.Util.Log.Info(MobileBarcodeScanner.TAG, "Flash not supported on this device"); return; } if (!PlatformChecks.HasFlashlightPermission (this.Context)) { var msg = "ZXing.Net.Mobile requires permission to use the Flash (" + Android.Manifest.Permission.Flashlight + "), but was not found in your AndroidManifest.xml file."; Android.Util.Log.Error (MobileBarcodeScanner.TAG, msg); throw new UnauthorizedAccessException (msg); } if (camera == null) { Android.Util.Log.Info(MobileBarcodeScanner.TAG, "NULL Camera"); return; } var p = camera.GetParameters(); var supportedFlashModes = p.SupportedFlashModes; if (supportedFlashModes == null) supportedFlashModes = new List<string>(); var flashMode= string.Empty; if (on) { if (supportedFlashModes.Contains(Android.Hardware.Camera.Parameters.FlashModeTorch)) flashMode = Android.Hardware.Camera.Parameters.FlashModeTorch; else if (supportedFlashModes.Contains(Android.Hardware.Camera.Parameters.FlashModeOn)) flashMode = Android.Hardware.Camera.Parameters.FlashModeOn; isTorchOn = true; } else { if ( supportedFlashModes.Contains(Android.Hardware.Camera.Parameters.FlashModeOff)) flashMode = Android.Hardware.Camera.Parameters.FlashModeOff; isTorchOn = false; } if (!string.IsNullOrEmpty(flashMode)) { p.FlashMode = flashMode; camera.SetParameters(p); } } public void ToggleTorch () { SetTorch (!isTorchOn); } public MobileBarcodeScanningOptions ScanningOptions { get { return options; } } public bool IsTorchOn { get { return isTorchOn; } } public bool IsAnalyzing { get { return isAnalyzing; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace BookShop.WebApi.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
//----------------------------------------------------------------------- // <copyright file="AreaLearningInGameController.cs" company="Google"> // // Copyright 2016 Google Inc. 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. // // </copyright> //----------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Threading; using System.Xml; using System.Xml.Serialization; using Tango; using UnityEngine; using UnityEngine.EventSystems; /// <summary> /// AreaLearningGUIController is responsible for the main game interaction. /// /// This class also takes care of loading / save persistent data(marker), and loop closure handling. /// </summary> public class AreaLearningInGameController : MonoBehaviour, ITangoPose, ITangoEvent, ITangoDepth { /// <summary> /// Prefabs of different colored markers. /// </summary> public GameObject[] m_markPrefabs; /// <summary> /// The point cloud object in the scene. /// </summary> public TangoPointCloud m_pointCloud; /// <summary> /// The canvas to place 2D game objects under. /// </summary> public Canvas m_canvas; /// <summary> /// The touch effect to place on taps. /// </summary> public RectTransform m_prefabTouchEffect; /// <summary> /// Saving progress UI text. /// </summary> public UnityEngine.UI.Text m_savingText; /// <summary> /// The Area Description currently loaded in the Tango Service. /// </summary> [HideInInspector] public AreaDescription m_curAreaDescription; #if UNITY_EDITOR /// <summary> /// Handles GUI text input in Editor where there is no device keyboard. /// If true, text input for naming new saved Area Description is displayed. /// </summary> private bool m_displayGuiTextInput; /// <summary> /// Handles GUI text input in Editor where there is no device keyboard. /// Contains text data for naming new saved Area Descriptions. /// </summary> private string m_guiTextInputContents; /// <summary> /// Handles GUI text input in Editor where there is no device keyboard. /// Indicates whether last text input was ended with confirmation or cancellation. /// </summary> private bool m_guiTextInputResult; #endif /// <summary> /// If set, then the depth camera is on and we are waiting for the next depth update. /// </summary> private bool m_findPlaneWaitingForDepth; /// <summary> /// A reference to TangoARPoseController instance. /// /// In this class, we need TangoARPoseController reference to get the timestamp and pose when we place a marker. /// The timestamp and pose is used for later loop closure position correction. /// </summary> private TangoPoseController m_poseController; /// <summary> /// List of markers placed in the scene. /// </summary> private List<GameObject> m_markerList = new List<GameObject>(); /// <summary> /// Reference to the newly placed marker. /// </summary> private GameObject newMarkObject = null; /// <summary> /// Current marker type. /// </summary> private int m_currentMarkType = 0; /// <summary> /// If set, this is the selected marker. /// </summary> private ARMarker m_selectedMarker; /// <summary> /// If set, this is the rectangle bounding the selected marker. /// </summary> private Rect m_selectedRect; /// <summary> /// If the interaction is initialized. /// /// Note that the initialization is triggered by the relocalization event. We don't want user to place object before /// the device is relocalized. /// </summary> private bool m_initialized = false; /// <summary> /// A reference to TangoApplication instance. /// </summary> private TangoApplication m_tangoApplication; private Thread m_saveThread; /// <summary> /// Unity Start function. /// /// We find and assign pose controller and tango application, and register this class to callback events. /// </summary> public void Start() { m_poseController = FindObjectOfType<TangoPoseController>(); m_tangoApplication = FindObjectOfType<TangoApplication>(); if (m_tangoApplication != null) { m_tangoApplication.Register(this); } } /// <summary> /// Unity Update function. /// /// Mainly handle the touch event and place mark in place. /// </summary> public void Update() { if (m_saveThread != null && m_saveThread.ThreadState != ThreadState.Running) { // After saving an Area Description or mark data, we reload the scene to restart the game. _UpdateMarkersForLoopClosures(); _SaveMarkerToDisk(); #pragma warning disable 618 Application.LoadLevel(Application.loadedLevel); #pragma warning restore 618 } if (Input.GetKey(KeyCode.Escape)) { #pragma warning disable 618 Application.LoadLevel(Application.loadedLevel); #pragma warning restore 618 } if (!m_initialized) { return; } if (EventSystem.current.IsPointerOverGameObject(0) || GUIUtility.hotControl != 0) { return; } if (Input.touchCount == 1) { Touch t = Input.GetTouch(0); Vector2 guiPosition = new Vector2(t.position.x, Screen.height - t.position.y); Camera cam = Camera.main; RaycastHit hitInfo; if (t.phase != TouchPhase.Began) { return; } if (m_selectedRect.Contains(guiPosition)) { // do nothing, the button will handle it } else if (Physics.Raycast(cam.ScreenPointToRay(t.position), out hitInfo)) { // Found a marker, select it (so long as it isn't disappearing)! GameObject tapped = hitInfo.collider.gameObject; if (!tapped.GetComponent<Animation>().isPlaying) { m_selectedMarker = tapped.GetComponent<ARMarker>(); } } else { // Place a new point at that location, clear selection m_selectedMarker = null; StartCoroutine(_WaitForDepthAndFindPlane(t.position)); // Because we may wait a small amount of time, this is a good place to play a small // animation so the user knows that their input was received. RectTransform touchEffectRectTransform = Instantiate(m_prefabTouchEffect) as RectTransform; touchEffectRectTransform.transform.SetParent(m_canvas.transform, false); Vector2 normalizedPosition = t.position; normalizedPosition.x /= Screen.width; normalizedPosition.y /= Screen.height; touchEffectRectTransform.anchorMin = touchEffectRectTransform.anchorMax = normalizedPosition; } } } /// <summary> /// Application onPause / onResume callback. /// </summary> /// <param name="pauseStatus"><c>true</c> if the application about to pause, otherwise <c>false</c>.</param> public void OnApplicationPause(bool pauseStatus) { if (pauseStatus && m_initialized) { // When application is backgrounded, we reload the level because the Tango Service is disconected. All // learned area and placed marker should be discarded as they are not saved. #pragma warning disable 618 Application.LoadLevel(Application.loadedLevel); #pragma warning restore 618 } } /// <summary> /// Unity OnGUI function. /// /// Mainly for removing markers. /// </summary> public void OnGUI() { if (m_selectedMarker != null) { Renderer selectedRenderer = m_selectedMarker.GetComponent<Renderer>(); // GUI's Y is flipped from the mouse's Y Rect screenRect = _WorldBoundsToScreen(Camera.main, selectedRenderer.bounds); float yMin = Screen.height - screenRect.yMin; float yMax = Screen.height - screenRect.yMax; screenRect.yMin = Mathf.Min(yMin, yMax); screenRect.yMax = Mathf.Max(yMin, yMax); if (GUI.Button(screenRect, "<size=30>Hide</size>")) { m_markerList.Remove(m_selectedMarker.gameObject); m_selectedMarker.SendMessage("Hide"); m_selectedMarker = null; m_selectedRect = new Rect(); } else { m_selectedRect = screenRect; } } else { m_selectedRect = new Rect(); } #if UNITY_EDITOR // Handle text input when there is no device keyboard in the editor. if (m_displayGuiTextInput) { Rect textBoxRect = new Rect(100, Screen.height - 200, Screen.width - 200, 100); Rect okButtonRect = textBoxRect; okButtonRect.y += 100; okButtonRect.width /= 2; Rect cancelButtonRect = okButtonRect; cancelButtonRect.x = textBoxRect.center.x; GUI.SetNextControlName("TextField"); GUIStyle customTextFieldStyle = new GUIStyle(GUI.skin.textField); customTextFieldStyle.alignment = TextAnchor.MiddleCenter; m_guiTextInputContents = GUI.TextField(textBoxRect, m_guiTextInputContents, customTextFieldStyle); GUI.FocusControl("TextField"); if (GUI.Button(okButtonRect, "OK") || (Event.current.type == EventType.keyDown && Event.current.character == '\n')) { m_displayGuiTextInput = false; m_guiTextInputResult = true; } else if (GUI.Button(cancelButtonRect, "Cancel")) { m_displayGuiTextInput = false; m_guiTextInputResult = false; } } #endif } /// <summary> /// Set the marker type. /// </summary> /// <param name="type">Marker type.</param> public void SetCurrentMarkType(int type) { if (type != m_currentMarkType) { m_currentMarkType = type; } } /// <summary> /// Save the game. /// /// Save will trigger 3 things: /// /// 1. Save the Area Description if the learning mode is on. /// 2. Bundle adjustment for all marker positions, please see _UpdateMarkersForLoopClosures() function header for /// more details. /// 3. Save all markers to xml, save the Area Description if the learning mode is on. /// 4. Reload the scene. /// </summary> public void Save() { StartCoroutine(_DoSaveCurrentAreaDescription()); } /// <summary> /// This is called each time a Tango event happens. /// </summary> /// <param name="tangoEvent">Tango event.</param> public void OnTangoEventAvailableEventHandler(Tango.TangoEvent tangoEvent) { // We will not have the saving progress when the learning mode is off. if (!m_tangoApplication.m_areaDescriptionLearningMode) { return; } if (tangoEvent.type == TangoEnums.TangoEventType.TANGO_EVENT_AREA_LEARNING && tangoEvent.event_key == "AreaDescriptionSaveProgress") { m_savingText.text = "Saving. " + (float.Parse(tangoEvent.event_value) * 100) + "%"; } } /// <summary> /// OnTangoPoseAvailable event from Tango. /// /// In this function, we only listen to the Start-Of-Service with respect to Area-Description frame pair. This pair /// indicates a relocalization or loop closure event happened, base on that, we either start the initialize the /// interaction or do a bundle adjustment for all marker position. /// </summary> /// <param name="poseData">Returned pose data from TangoService.</param> public void OnTangoPoseAvailable(Tango.TangoPoseData poseData) { // This frame pair's callback indicates that a loop closure or relocalization has happened. // // When learning mode is on, this callback indicates the loop closure event. Loop closure will happen when the // system recognizes a pre-visited area, the loop closure operation will correct the previously saved pose // to achieve more accurate result. (pose can be queried through GetPoseAtTime based on previously saved // timestamp). // Loop closure definition: https://en.wikipedia.org/wiki/Simultaneous_localization_and_mapping#Loop_closure // // When learning mode is off, and an Area Description is loaded, this callback indicates a // relocalization event. Relocalization is when the device finds out where it is with respect to the loaded // Area Description. In our case, when the device is relocalized, the markers will be loaded because we // know the relative device location to the markers. if (poseData.framePair.baseFrame == TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_AREA_DESCRIPTION && poseData.framePair.targetFrame == TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_START_OF_SERVICE && poseData.status_code == TangoEnums.TangoPoseStatusType.TANGO_POSE_VALID) { // When we get the first loop closure/ relocalization event, we initialized all the in-game interactions. if (!m_initialized) { m_initialized = true; if (m_curAreaDescription == null) { Debug.Log("AndroidInGameController.OnTangoPoseAvailable(): m_curAreaDescription is null"); return; } _LoadMarkerFromDisk(); } } } /// <summary> /// This is called each time new depth data is available. /// /// On the Tango tablet, the depth callback occurs at 5 Hz. /// </summary> /// <param name="tangoDepth">Tango depth.</param> public void OnTangoDepthAvailable(TangoUnityDepth tangoDepth) { // Don't handle depth here because the PointCloud may not have been updated yet. Just // tell the coroutine it can continue. m_findPlaneWaitingForDepth = false; } /// <summary> /// Actually do the Area Description save. /// </summary> /// <returns>Coroutine IEnumerator.</returns> private IEnumerator _DoSaveCurrentAreaDescription() { #if UNITY_EDITOR // Work around lack of on-screen keyboard in editor: if (m_displayGuiTextInput || m_saveThread != null) { yield break; } m_displayGuiTextInput = true; m_guiTextInputContents = "Unnamed"; while (m_displayGuiTextInput) { yield return null; } bool saveConfirmed = m_guiTextInputResult; #else if (TouchScreenKeyboard.visible || m_saveThread != null) { yield break; } TouchScreenKeyboard kb = TouchScreenKeyboard.Open("Unnamed"); while (!kb.done && !kb.wasCanceled) { yield return null; } bool saveConfirmed = kb.done; #endif if (saveConfirmed) { // Disable interaction before saving. m_initialized = false; m_savingText.gameObject.SetActive(true); if (m_tangoApplication.m_areaDescriptionLearningMode) { // The keyboard is not readable if you are not in the Unity main thread. Cache the value here. string name; #if UNITY_EDITOR name = m_guiTextInputContents; #else name = kb.text; #endif m_saveThread = new Thread(delegate() { // Start saving process in another thread. m_curAreaDescription = AreaDescription.SaveCurrent(); AreaDescription.Metadata metadata = m_curAreaDescription.GetMetadata(); metadata.m_name = name; m_curAreaDescription.SaveMetadata(metadata); }); m_saveThread.Start(); } else { _SaveMarkerToDisk(); #pragma warning disable 618 Application.LoadLevel(Application.loadedLevel); #pragma warning restore 618 } } } /// <summary> /// Correct all saved marks when loop closure happens. /// /// When Tango Service is in learning mode, the drift will accumulate overtime, but when the system sees a /// preexisting area, it will do a operation to correct all previously saved poses /// (the pose you can query with GetPoseAtTime). This operation is called loop closure. When loop closure happens, /// we will need to re-query all previously saved marker position in order to achieve the best result. /// This function is doing the querying job based on timestamp. /// </summary> private void _UpdateMarkersForLoopClosures() { // Adjust mark's position each time we have a loop closure detected. foreach (GameObject obj in m_markerList) { ARMarker tempMarker = obj.GetComponent<ARMarker>(); if (tempMarker.m_timestamp != -1.0f) { TangoCoordinateFramePair pair; TangoPoseData relocalizedPose = new TangoPoseData(); pair.baseFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_AREA_DESCRIPTION; pair.targetFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_DEVICE; PoseProvider.GetPoseAtTime(relocalizedPose, tempMarker.m_timestamp, pair); Matrix4x4 uwTDevice = TangoSupport.UNITY_WORLD_T_START_SERVICE * relocalizedPose.ToMatrix4x4() * TangoSupport.DEVICE_T_UNITY_CAMERA; Matrix4x4 uwTMarker = uwTDevice * tempMarker.m_deviceTMarker; obj.transform.position = uwTMarker.GetColumn(3); obj.transform.rotation = Quaternion.LookRotation(uwTMarker.GetColumn(2), uwTMarker.GetColumn(1)); } } } /// <summary> /// Write marker list to an xml file stored in application storage. /// </summary> private void _SaveMarkerToDisk() { // Compose a XML data list. List<MarkerData> xmlDataList = new List<MarkerData>(); foreach (GameObject obj in m_markerList) { // Add marks data to the list, we intentionally didn't add the timestamp, because the timestamp will not be // useful when the next time Tango Service is connected. The timestamp is only used for loop closure pose // correction in current Tango connection. MarkerData temp = new MarkerData(); temp.m_type = obj.GetComponent<ARMarker>().m_type; temp.m_position = obj.transform.position; temp.m_orientation = obj.transform.rotation; xmlDataList.Add(temp); } string path = Application.persistentDataPath + "/" + m_curAreaDescription.m_uuid + ".xml"; var serializer = new XmlSerializer(typeof(List<MarkerData>)); using (var stream = new FileStream(path, FileMode.Create)) { serializer.Serialize(stream, xmlDataList); } } /// <summary> /// Load marker list xml from application storage. /// </summary> private void _LoadMarkerFromDisk() { // Attempt to load the exsiting markers from storage. string path = Application.persistentDataPath + "/" + m_curAreaDescription.m_uuid + ".xml"; var serializer = new XmlSerializer(typeof(List<MarkerData>)); var stream = new FileStream(path, FileMode.Open); List<MarkerData> xmlDataList = serializer.Deserialize(stream) as List<MarkerData>; if (xmlDataList == null) { Debug.Log("AndroidInGameController._LoadMarkerFromDisk(): xmlDataList is null"); return; } m_markerList.Clear(); foreach (MarkerData mark in xmlDataList) { // Instantiate all markers' gameobject. GameObject temp = Instantiate(m_markPrefabs[mark.m_type], mark.m_position, mark.m_orientation) as GameObject; m_markerList.Add(temp); } } /// <summary> /// Convert a 3D bounding box represented by a <c>Bounds</c> object into a 2D /// rectangle represented by a <c>Rect</c> object. /// </summary> /// <returns>The 2D rectangle in Screen coordinates.</returns> /// <param name="cam">Camera to use.</param> /// <param name="bounds">3D bounding box.</param> private Rect _WorldBoundsToScreen(Camera cam, Bounds bounds) { Vector3 center = bounds.center; Vector3 extents = bounds.extents; Bounds screenBounds = new Bounds(cam.WorldToScreenPoint(center), Vector3.zero); screenBounds.Encapsulate(cam.WorldToScreenPoint(center + new Vector3(+extents.x, +extents.y, +extents.z))); screenBounds.Encapsulate(cam.WorldToScreenPoint(center + new Vector3(+extents.x, +extents.y, -extents.z))); screenBounds.Encapsulate(cam.WorldToScreenPoint(center + new Vector3(+extents.x, -extents.y, +extents.z))); screenBounds.Encapsulate(cam.WorldToScreenPoint(center + new Vector3(+extents.x, -extents.y, -extents.z))); screenBounds.Encapsulate(cam.WorldToScreenPoint(center + new Vector3(-extents.x, +extents.y, +extents.z))); screenBounds.Encapsulate(cam.WorldToScreenPoint(center + new Vector3(-extents.x, +extents.y, -extents.z))); screenBounds.Encapsulate(cam.WorldToScreenPoint(center + new Vector3(-extents.x, -extents.y, +extents.z))); screenBounds.Encapsulate(cam.WorldToScreenPoint(center + new Vector3(-extents.x, -extents.y, -extents.z))); return Rect.MinMaxRect(screenBounds.min.x, screenBounds.min.y, screenBounds.max.x, screenBounds.max.y); } /// <summary> /// Wait for the next depth update, then find the plane at the touch position. /// </summary> /// <returns>Coroutine IEnumerator.</returns> /// <param name="touchPosition">Touch position to find a plane at.</param> private IEnumerator _WaitForDepthAndFindPlane(Vector2 touchPosition) { m_findPlaneWaitingForDepth = true; // Turn on the camera and wait for a single depth update. m_tangoApplication.SetDepthCameraRate(TangoEnums.TangoDepthCameraRate.MAXIMUM); while (m_findPlaneWaitingForDepth) { yield return null; } m_tangoApplication.SetDepthCameraRate(TangoEnums.TangoDepthCameraRate.DISABLED); // Find the plane. Camera cam = Camera.main; Vector3 planeCenter; Plane plane; if (!m_pointCloud.FindPlane(cam, touchPosition, out planeCenter, out plane)) { yield break; } // Ensure the location is always facing the camera. This is like a LookRotation, but for the Y axis. Vector3 up = plane.normal; Vector3 forward; if (Vector3.Angle(plane.normal, cam.transform.forward) < 175) { Vector3 right = Vector3.Cross(up, cam.transform.forward).normalized; forward = Vector3.Cross(right, up).normalized; } else { // Normal is nearly parallel to camera look direction, the cross product would have too much // floating point error in it. forward = Vector3.Cross(up, cam.transform.right); } // Instantiate marker object. newMarkObject = Instantiate(m_markPrefabs[m_currentMarkType], planeCenter, Quaternion.LookRotation(forward, up)) as GameObject; ARMarker markerScript = newMarkObject.GetComponent<ARMarker>(); markerScript.m_type = m_currentMarkType; markerScript.m_timestamp = (float)m_poseController.LastPoseTimestamp; Matrix4x4 uwTDevice = Matrix4x4.TRS(m_poseController.transform.position, m_poseController.transform.rotation, Vector3.one); Matrix4x4 uwTMarker = Matrix4x4.TRS(newMarkObject.transform.position, newMarkObject.transform.rotation, Vector3.one); markerScript.m_deviceTMarker = Matrix4x4.Inverse(uwTDevice) * uwTMarker; m_markerList.Add(newMarkObject); m_selectedMarker = null; } /// <summary> /// Data container for marker. /// /// Used for serializing/deserializing marker to xml. /// </summary> [System.Serializable] public class MarkerData { /// <summary> /// Marker's type. /// /// Red, green or blue markers. In a real game scenario, this could be different game objects /// (e.g. banana, apple, watermelon, persimmons). /// </summary> [XmlElement("type")] public int m_type; /// <summary> /// Position of the this mark, with respect to the origin of the game world. /// </summary> [XmlElement("position")] public Vector3 m_position; /// <summary> /// Rotation of the this mark. /// </summary> [XmlElement("orientation")] public Quaternion m_orientation; } }
/* Copyright 2010 Google Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Net; using System.Text; using System.Threading; using Google.Apis.Authentication; using Google.Apis.Discovery; using Google.Apis.Logging; using Google.Apis.Testing; using Google.Apis.Util; #if !SILVERLIGHT using System.IO.Compression; #endif namespace Google.Apis.Requests { /// <summary> /// Request to a service. /// </summary> /// <remarks> /// Features which are not (yet) supported on SilverLight: /// - The UserAgent header. /// - GZip Compression /// </remarks> public class Request : IRequest { private const string UserAgent = "{0} google-api-dotnet-client/{1} {2}/{3}"; private const string GZipUserAgentSuffix = " (gzip)"; private const string GZipEncoding = "gzip"; /// <summary> /// The charset used for content encoding. /// </summary> public static readonly Encoding ContentCharset = Encoding.UTF8; private static readonly ILogger logger = ApplicationContext.Logger.ForType<Request>(); public const string DELETE = "DELETE"; public const string GET = "GET"; public const string PATCH = "PATCH"; public const string POST = "POST"; public const string PUT = "PUT"; /// <summary> /// Defines the maximum number of retries which should be made if a request fails. /// </summary> public int MaximumRetries { get; set; } /// <summary> /// Defines the factor by which the waiting time is multiplied between retry attempts. /// </summary> public double RetryWaitTimeIncreaseFactor { get; set; } /// <summary> /// Defines the initial waiting time, which is used once the first retry has failed. /// </summary> public int RetryInitialWaitTime { get; set; } private static readonly String ApiVersion = Utilities.GetLibraryVersion(); public static readonly ReadOnlyCollection<string> SupportedHttpMethods = new List<string> { POST, PUT, DELETE, GET, PATCH }.AsReadOnly(); private string applicationName; public Request() { applicationName = Utilities.GetAssemblyTitle() ?? "Unknown_Application"; Authenticator = new NullAuthenticator(); WebRequestFactory = new HttpRequestFactory(); Parameters = new ParameterCollection(); MaximumRetries = 3; RetryWaitTimeIncreaseFactor = 2.0; RetryInitialWaitTime = 1000; } /// <summary> /// The authenticator used for this request. /// </summary> internal IAuthenticator Authenticator { get; private set; } /// <summary> /// The developer API Key sent along with the request. /// </summary> internal String DeveloperKey { get; private set; } /// <summary> /// Set of method parameters. /// </summary> [VisibleForTestOnly] internal ParameterCollection Parameters { get; set; } /// <summary> /// The application name used within the user agent string. /// </summary> [VisibleForTestOnly] internal string ApplicationName { get { return applicationName; } } private IService Service { get; set; } private IMethod Method { get; set; } private Uri BaseURI { get; set; } private string RPCName { get; set; } // note: this property is apparently never used private string Body { get; set; } private ReturnType ReturnType { get; set; } private ETagAction ETagAction { get; set; } private string ETag { get; set; } private string FieldsMask { get; set; } private string UserIp { get; set; } private string QuotaUser { get; set; } /// <summary> /// Defines whether this request can be sent multiple times. /// </summary> public bool SupportsRetry { get { return true; } } #region IRequest Members /// <summary> /// The method to call /// </summary> /// <returns> /// A <see cref="Request"/> /// </returns> public IRequest On(string rpcName) { RPCName = rpcName; return this; } /// <summary> /// Sets the type of data that is expected to be returned from the request. /// /// Defaults to Json. /// </summary> /// <param name="returnType"> /// A <see cref="ReturnType"/> /// </param> /// <returns> /// A <see cref="Request"/> /// </returns> public IRequest Returning(ReturnType returnType) { ReturnType = returnType; return this; } /// <summary> /// Adds the parameters to the request. /// </summary> /// <returns> /// A <see cref="Request"/> /// </returns> public IRequest WithParameters(IDictionary<string, object> parameters) { Parameters = ParameterCollection.FromDictionary(parameters); return this; } /// <summary> /// Adds the parameters to the request. /// </summary> /// <returns> /// A <see cref="Request"/> /// </returns> public IRequest WithParameters(IEnumerable<KeyValuePair<string, string>> parameters) { Parameters = new ParameterCollection(parameters); return this; } /// <summary> /// Parses the specified querystring and adds these parameters to the request /// </summary> public IRequest WithParameters(string parameters) { Parameters = ParameterCollection.FromQueryString(parameters); return this; } /// <summary> /// Uses the string provied as the body of the request. /// </summary> public IRequest WithBody(string body) { Body = body; return this; } /// <summary> /// Uses the provided authenticator to add authentication information to this request. /// </summary> public IRequest WithAuthentication(IAuthenticator authenticator) { authenticator.ThrowIfNull("Authenticator"); Authenticator = authenticator; return this; } /// <summary> /// Adds the developer key to this request. /// </summary> public IRequest WithKey(string key) { DeveloperKey = key; return this; } /// <summary> /// Sets the ETag-behavior of this request. /// </summary> public IRequest WithETagAction(ETagAction action) { ETagAction = action; return this; } /// <summary> /// Adds an ETag to this request. /// </summary> public IRequest WithETag(string etag) { ETag = etag; return this; } /// <summary> /// Container struct for the asynchronous execution of a request. /// </summary> private struct AsyncExecutionState { /// <summary> /// The current try we are in. 1 based. /// </summary> public int Try; /// <summary> /// The time we will wait between the current and the next request if the current one fails. /// </summary> public double WaitTime; /// <summary> /// The method which will be called once the request has been completed. /// </summary> public Action<IAsyncRequestResult> ResponseHandler; /// <summary> /// The request which is currently being executed. /// </summary> public WebRequest CurrentRequest; } /// <summary> /// Represents the result of an asynchronous Request. /// </summary> private class AsyncRequestResult : IAsyncRequestResult { private readonly IResponse response; private readonly GoogleApiRequestException exception; public AsyncRequestResult(IResponse response) { this.response = response; } public AsyncRequestResult(GoogleApiRequestException exception) { this.exception = exception; } public IResponse GetResponse() { if (exception != null) // Request failed. { throw exception; } return response; // Request succeeded. } } /// <summary> /// Begins executing a request based upon the current execution state. /// </summary> /// <remarks>Does not check preconditions.</remarks> private void InternalBeginExecuteRequest(AsyncExecutionState state) { state.CurrentRequest.BeginGetResponse(InternalEndExecuteRequest, state); } /// <summary> /// Ends executing an asynchronous request. /// </summary> private void InternalEndExecuteRequest(IAsyncResult asyncResult) { AsyncExecutionState state = (AsyncExecutionState)asyncResult.AsyncState; AsyncRequestResult asyncRequestResult = null; bool retried = false; try { asyncRequestResult = new AsyncRequestResult(new Response( state.CurrentRequest.EndGetResponse(asyncResult))); } catch (WebException ex) { // Returns null if the attempt was retried. retried = HandleFailedRequest(state, ex, out asyncRequestResult); } catch (Exception ex) // Unknown exception. { asyncRequestResult = new AsyncRequestResult( new GoogleApiRequestException(Service, this, null, ex)); } finally { // If the async result is null, this indicates that the request was retried. // Another handler will be executed to respond to that attempt, so do not // call the handler yet. if (!retried) state.ResponseHandler(asyncRequestResult); } } /// <summary> /// Handles a failed request, and tries to fix it if possible. /// </summary> /// <remarks> /// Can not throw an exception. /// </remarks> /// <returns> /// Returns true if the request was handled and is being retried. /// Returns false if the request could not be retried. /// </returns> private bool HandleFailedRequest(AsyncExecutionState state, WebException exception, out AsyncRequestResult asyncRequestResult) { try { RequestError error = null; // Try to get an error response object. if (exception.Response != null) { IResponse errorResponse = new Response(exception.Response); error = Service.DeserializeError(errorResponse); } // Try to handle the response somehow. if (SupportsRetry && state.Try < MaximumRetries) { // Wait some time before sending another request. Thread.Sleep((int)state.WaitTime); state.WaitTime *= RetryWaitTimeIncreaseFactor; state.Try++; foreach (IErrorResponseHandler handler in GetErrorResponseHandlers()) { if (handler.CanHandleErrorResponse(exception, error)) { // The provided handler was able to handle this error. Retry sending the request. handler.HandleErrorResponse(exception, error, state.CurrentRequest); logger.Warning("Retrying request [{0}]", this); // Begin a new request and when it is completed being assembled, execute it // asynchronously. state.CurrentRequest = CreateWebRequest((request) => { InternalBeginExecuteRequest(state); }); // Signal that this begin/end request pair has no result because it has been retried. asyncRequestResult = null; return true; } } } // Retrieve additional information about the http response (if applicable). HttpStatusCode status = 0; HttpWebResponse httpResponse = exception.Response as HttpWebResponse; if (httpResponse != null) { status = httpResponse.StatusCode; } // We were unable to handle the exception. Throw it wrapped in a GoogleApiRequestException. asyncRequestResult = new AsyncRequestResult( new GoogleApiRequestException(Service, this, error, exception) { HttpStatusCode = status }); } catch (Exception) { asyncRequestResult = new AsyncRequestResult( new GoogleApiRequestException(Service, this, null, exception)); } return false; } /// <summary> /// Executes the request asynchronously, and calls the specified delegate once done. /// </summary> /// <param name="responseHandler">The method to call once a response has been received.</param> public void ExecuteRequestAsync(Action<IAsyncRequestResult> responseHandler) { // Validate the input. var validator = new MethodValidator(Method, Parameters); if (validator.ValidateAllParameters() == false) { throw new InvalidOperationException("Request parameter validation failed for [" + this + "]"); } // Begin a new request and when it is completed being assembled, execute it asynchronously. CreateWebRequest((request) => { // When the request is completed constructing, execute it. var state = new AsyncExecutionState() { ResponseHandler = responseHandler, Try = 1, WaitTime = RetryInitialWaitTime, CurrentRequest = request }; InternalBeginExecuteRequest(state); }); } /// <summary> /// Executes a request given the configuration options supplied. /// </summary> /// <returns> /// A <see cref="Stream"/> /// </returns> public IResponse ExecuteRequest() { AutoResetEvent waitHandle = new AutoResetEvent(false); IAsyncRequestResult result = null; ExecuteRequestAsync(r => { result = r; waitHandle.Set(); }); waitHandle.WaitOne(); return result.GetResponse(); } #endregion /// <summary> /// Returns all error response handlers associated with this request. /// </summary> [VisibleForTestOnly] internal IEnumerable<IErrorResponseHandler> GetErrorResponseHandlers() { // Check if the current authenticator can handle error responses. IErrorResponseHandler authenticator = Authenticator as IErrorResponseHandler; if (authenticator != null) { yield return authenticator; } } /// <summary> /// Given an API method, create the appropriate Request for it. /// </summary> public static IRequest CreateRequest(IService service, IMethod method) { switch (method.HttpMethod) { case GET: case PUT: case POST: case DELETE: case PATCH: return new Request { Service = service, Method = method, BaseURI = service.BaseUri }; default: throw new NotSupportedException( string.Format( "The HttpMethod[{0}] of Method[{1}] in Service[{2}] was not supported", method.HttpMethod, method.Name, service.Name)); } } /// <summary> /// Sets the Application name on the UserAgent String. /// </summary> /// <param name="name"> /// A <see cref="System.String"/> /// </param> public IRequest WithAppName(string name) { applicationName = name; return this; } /// <summary> /// Specifies the partial field mask of this method. /// The response of this request will only contain the fields specified in this mask. /// </summary> /// <param name="mask">Selector specifying which fields to include in a partial response.</param> public IRequest WithFields(string mask) { FieldsMask = mask; return this; } /// <summary> /// IP address of the site where the request originates. Use this if you want to enforce per-user limits. /// </summary> public IRequest WithUserIp(string userIp) { UserIp = userIp; return this; } /// <summary> /// Available to use for quota purposes for server-side applications. /// Can be any arbitrary string assigned to a user, but should not exceed 40 characters. /// Overrides UserIp if both are provided. /// </summary> public IRequest WithQuotaUser(string quotaUser) { QuotaUser = quotaUser; return this; } /// <summary> /// Builds the resulting Url for the whole request. /// </summary> [VisibleForTestOnly] internal HttpWebRequest BuildRequest() { var requestBuilder = new HttpWebRequestBuilder() { BaseUri = Service.BaseUri, Path = Method.RestPath, Method = Method.HttpMethod, }; requestBuilder.AddParameter(RequestParameterType.Query, "alt", ReturnType == ReturnType.Json?"json":"atom"); requestBuilder.AddParameter(RequestParameterType.Query, "key", DeveloperKey); requestBuilder.AddParameter(RequestParameterType.Query, "fields", FieldsMask); requestBuilder.AddParameter(RequestParameterType.Query, "userIp", UserIp); requestBuilder.AddParameter(RequestParameterType.Query, "quotaUser", QuotaUser); // Replace the substitution parameters. foreach (var parameter in Parameters) { IParameter parameterDefinition;// = Method.Parameters[parameter.Key]; if (!(Method.Parameters.TryGetValue(parameter.Key, out parameterDefinition) || Service.Parameters.TryGetValue(parameter.Key, out parameterDefinition) )) { throw new GoogleApiException(Service, String.Format("Invalid parameter \"{0}\" specified.", parameter.Key)); } string value = parameter.Value; if (value.IsNullOrEmpty()) // If the parameter is present and has no value, use the default. { value = parameterDefinition.DefaultValue; } switch (parameterDefinition.ParameterType) { case "path": requestBuilder.AddParameter(RequestParameterType.Path, parameter.Key, value); break; case "query": // If the parameter is optional and no value is given, don't add to url. if (parameterDefinition.IsRequired && String.IsNullOrEmpty(value)) { throw new GoogleApiException(Service, String.Format("Required parameter \"{0}\" missing.", parameter.Key)); } requestBuilder.AddParameter(RequestParameterType.Query, parameter.Key, value); break; default: throw new NotSupportedException( "Found an unsupported Parametertype [" + parameterDefinition.ParameterType + "]"); } } return requestBuilder.GetWebRequest(); } private static string GetReturnMimeType(ReturnType returnType) { switch (returnType) { case ReturnType.Atom: return "application/atom+xml"; case ReturnType.Json: return "application/json"; default: throw new ArgumentOutOfRangeException("returnType", "Unknown Return-type: " + returnType); } } /// <summary> /// Returns the default ETagAction for a specific http verb. /// </summary> [VisibleForTestOnly] internal static ETagAction GetDefaultETagAction(string httpVerb) { switch (httpVerb) { default: return ETagAction.Ignore; case GET: // Incoming data should only be updated if it has been changed on the server. return ETagAction.IfNoneMatch; case PUT: // Outgoing data should only be commited if it hasn't been changed on the server. case POST: case PATCH: case DELETE: return ETagAction.IfMatch; } } private ICreateHttpRequest webRequestFactory; /// <summary> /// Factory used to create HttpWebRequest objects. /// </summary> public ICreateHttpRequest WebRequestFactory { get { return this.webRequestFactory; } set { value.ThrowIfNull("HttpRequestFactory"); this.webRequestFactory = value; } } /// <summary> /// Creates the ready-to-send WebRequest containing all the data specified in this request class. /// </summary> /// <param name="onRequestReady">An action to execute when the request has been prepared.</param> [VisibleForTestOnly] internal WebRequest CreateWebRequest(Action<WebRequest> onRequestReady) { HttpWebRequest request = BuildRequest(); // Create the request. Authenticator.ApplyAuthenticationToRequest(request); // Insert the content type and user agent. request.ContentType = string.Format( "{0}; charset={1}", GetReturnMimeType(ReturnType), ContentCharset.WebName); string appName = FormatForUserAgent(ApplicationName); string apiVersion = FormatForUserAgent(ApiVersion); string platform = FormatForUserAgent(Environment.OSVersion.Platform.ToString()); string platformVer = FormatForUserAgent(Environment.OSVersion.Version.ToString()); // The UserAgent header can only be set on a non-Silverlight platform. // Silverlight uses the user agent of the browser instead. #if !SILVERLIGHT request.UserAgent = String.Format(UserAgent, appName, apiVersion, platform, platformVer); #endif // Add the E-tag header: if (!string.IsNullOrEmpty(ETag)) { ETagAction action = this.ETagAction; if (action == ETagAction.Default) { action = GetDefaultETagAction(request.Method); } switch (action) { case ETagAction.IfMatch: request.Headers[HttpRequestHeader.IfMatch] = ETag; break; case ETagAction.IfNoneMatch: request.Headers[HttpRequestHeader.IfNoneMatch] = ETag; break; } } // Check if compression is supported. #if !SILVERLIGHT if (Service.GZipEnabled) { request.UserAgent += GZipUserAgentSuffix; request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; } #endif // Attach a body if a POST and there is something to attach. if (HttpMethodHasBody(request.Method)) { if (!string.IsNullOrEmpty(Body)) { AttachBody(request, onRequestReady); return request; } else { // Set the "Content-Length" header, which is required for every http method declaring a body. This // is required as e.g. the google servers will throw a "411 - Length required" error otherwise. #if !SILVERLIGHT request.ContentLength = 0; #else // Set by the browser on Silverlight. Cannot be modified by the user. #endif } } onRequestReady(request); return request; } [VisibleForTestOnly] internal string FormatForUserAgent(string fragment) { return fragment.Replace(' ', '_'); } /// <summary> /// Adds the body of this request to the specified WebRequest. /// </summary> /// <param name="request">The WebRequest which needs a body attached.</param> /// <param name="onRequestReady">An action to complete when the request is ready.</param> /// <remarks>Automatically applies GZip-compression if globally enabled.</remarks> [VisibleForTestOnly] internal void AttachBody(WebRequest request, Action<WebRequest> onRequestReady) { request.BeginGetRequestStream(new AsyncCallback(EndAttachBody), new object[] { request, onRequestReady }); } /// <summary> /// Complete the attach-body portion of the request and continue executing the call. /// </summary> /// <param name="asyncResult">The asyncResult of the attach body call.</param> internal void EndAttachBody(IAsyncResult asyncResult) { object[] state = (object[])asyncResult.AsyncState; WebRequest request = (WebRequest)state[0]; Action<WebRequest> onRequestReady = (Action<WebRequest>)state[1]; Stream bodyStream = request.EndGetRequestStream(asyncResult); // If enabled: Encapsulate in GZipStream. #if !SILVERLIGHT if (Service.GZipEnabled) { // Change the content encoding and apply a gzip filter. request.Headers.Add(HttpRequestHeader.ContentEncoding, GZipEncoding); bodyStream = new GZipStream(bodyStream, CompressionMode.Compress); } #endif // Write data into the stream. using (bodyStream) { byte[] postBody = ContentCharset.GetBytes(Body); bodyStream.Write(postBody, 0, postBody.Length); } onRequestReady(request); } /// <summary> /// Returns true if this http method can have a body. /// </summary> public static bool HttpMethodHasBody(string httpMethod) { switch (httpMethod) { case DELETE: case GET: return false; case PATCH: case POST: case PUT: return true; default: throw new NotSupportedException(string.Format("The HttpMethod[{0}] is not supported", httpMethod)); } } public override string ToString() { return string.Format("{0}({1} @ {2})", GetType(), Method.Name, BuildRequest().RequestUri); } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace System.ServiceModel.Dispatcher { using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Xml.XPath; internal class SubExpr { internal int var; internal int refCount; // opcodes internal bool useSpecial; Opcode ops; SubExpr parent; protected List<SubExpr> children; internal SubExpr(SubExpr parent, Opcode ops, int var) { this.children = new List<SubExpr>(2); this.var = var; this.parent = parent; this.useSpecial = false; if (parent != null) { this.ops = new InternalSubExprOpcode(parent); this.ops.Attach(ops); this.useSpecial = parent is SubExprHeader && ((SelectOpcode)ops).Criteria.Axis.Type == QueryAxisType.Child; } else { this.ops = ops; } } internal Opcode FirstOp { get { if (this.parent == null) { return this.ops; } else { return this.ops.Next; } } } internal int Variable { get { return this.var; } } internal SubExprOpcode Add(Opcode opseq, SubExprEliminator elim) { Opcode start = this.FirstOp; Opcode ops = opseq; while (start != null && ops != null && start.Equals(ops)) { start = start.Next; ops = ops.Next; } if (ops == null) { if (start == null) { return new SubExprOpcode(this); } else { SubExpr e = this.BranchAt(start, elim); return new SubExprOpcode(e); } } else { if (start == null) { ops.DetachFromParent(); for (int i = 0; i < this.children.Count; ++i) { if (this.children[i].FirstOp.Equals(ops)) { return this.children[i].Add(ops, elim); } } SubExpr e = new SubExpr(this, ops, elim.NewVarID()); this.AddChild(e); return new SubExprOpcode(e); } else { SubExpr e = this.BranchAt(start, elim); ops.DetachFromParent(); SubExpr ee = new SubExpr(e, ops, elim.NewVarID()); e.AddChild(ee); return new SubExprOpcode(ee); } } } internal virtual void AddChild(SubExpr expr) { this.children.Add(expr); } SubExpr BranchAt(Opcode op, SubExprEliminator elim) { Opcode firstOp = this.FirstOp; if (this.parent != null) { this.parent.RemoveChild(this); } else { elim.Exprs.Remove(this); } firstOp.DetachFromParent(); op.DetachFromParent(); SubExpr e = new SubExpr(this.parent, firstOp, elim.NewVarID()); if (this.parent != null) { this.parent.AddChild(e); } else { elim.Exprs.Add(e); } e.AddChild(this); this.parent = e; this.ops = new InternalSubExprOpcode(e); this.ops.Attach(op); return e; } internal void CleanUp(SubExprEliminator elim) { if (this.refCount == 0) { if (this.children.Count == 0) { if (this.parent == null) { elim.Exprs.Remove(this); } else { this.parent.RemoveChild(this); this.parent.CleanUp(elim); } } else if (this.children.Count == 1) { SubExpr child = this.children[0]; Opcode op = child.FirstOp; op.DetachFromParent(); Opcode op2 = this.ops; while (op2.Next != null) { op2 = op2.Next; } op2.Attach(op); child.ops = this.ops; if (this.parent == null) { elim.Exprs.Remove(this); elim.Exprs.Add(child); child.parent = null; } else { this.parent.RemoveChild(this); this.parent.AddChild(child); child.parent = this.parent; } } } } internal void DecRef(SubExprEliminator elim) { this.refCount--; CleanUp(elim); } internal void Eval(ProcessingContext context) { int count = 0, marker = context.Processor.CounterMarker; Opcode op = this.ops; if (this.useSpecial) { op.EvalSpecial(context); context.LoadVariable(this.var); //context.Processor.CounterMarker = marker; return; } while (op != null) { op = op.Eval(context); } count = context.Processor.ElapsedCount(marker); //context.Processor.CounterMarker = marker; context.SaveVariable(this.var, count); } internal virtual void EvalSpecial(ProcessingContext context) { this.Eval(context); } internal void IncRef() { this.refCount++; } internal virtual void RemoveChild(SubExpr expr) { this.children.Remove(expr); } internal void Renumber(SubExprEliminator elim) { this.var = elim.NewVarID(); for (int i = 0; i < this.children.Count; ++i) { this.children[i].Renumber(elim); } } internal void Trim() { this.children.Capacity = this.children.Count; this.ops.Trim(); for (int i = 0; i < this.children.Count; ++i) { this.children[i].Trim(); } } #if DEBUG_FILTER internal void Write(TextWriter outStream) { outStream.WriteLine("======================="); outStream.WriteLine("= SubExpr #" + this.var.ToString() + " (" + this.refCount.ToString() + ")"); outStream.WriteLine("======================="); for(Opcode o = this.ops; o != null; o = o.Next) { outStream.WriteLine(o.ToString()); } outStream.WriteLine(""); for(int i = 0; i < this.children.Count; ++i) { this.children[i].Write(outStream); } } #endif } internal class SubExprHeader : SubExpr { // WS, [....], Can probably combine these // WS, [....], Make this data structure less ugly (if possible) Dictionary<string, Dictionary<string, List<SubExpr>>> nameLookup; Dictionary<SubExpr, MyInt> indexLookup; internal SubExprHeader(Opcode ops, int var) : base(null, ops, var) { this.nameLookup = new Dictionary<string, Dictionary<string, List<SubExpr>>>(); this.indexLookup = new Dictionary<SubExpr, MyInt>(); this.IncRef(); // Prevent cleanup } internal override void AddChild(SubExpr expr) { base.AddChild(expr); RebuildIndex(); if (expr.useSpecial) { NodeQName qname = ((SelectOpcode)(expr.FirstOp)).Criteria.QName; string ns = qname.Namespace; Dictionary<string, List<SubExpr>> nextLookup; if (!this.nameLookup.TryGetValue(ns, out nextLookup)) { nextLookup = new Dictionary<string, List<SubExpr>>(); this.nameLookup.Add(ns, nextLookup); } string name = qname.Name; List<SubExpr> exprs = new List<SubExpr>(); if (!nextLookup.TryGetValue(name, out exprs)) { exprs = new List<SubExpr>(); nextLookup.Add(name, exprs); } exprs.Add(expr); } } internal override void EvalSpecial(ProcessingContext context) { int marker = context.Processor.CounterMarker; if (!context.LoadVariable(this.var)) { XPathMessageContext.HeaderFun.InvokeInternal(context, 0); context.SaveVariable(this.var, context.Processor.ElapsedCount(marker)); } // WS, [....], see if we can put this array in the processor to save // an allocation. Perhaps we can use the variables slot we're going to fill NodeSequence[] childSequences = new NodeSequence[this.children.Count]; NodeSequence seq = context.Sequences[context.TopSequenceArg.basePtr].Sequence; for (int i = 0; i < this.children.Count; ++i) { childSequences[i] = context.CreateSequence(); childSequences[i].StartNodeset(); } // Perform the index SeekableXPathNavigator nav = seq[0].GetNavigator(); if (nav.MoveToFirstChild()) { do { if (nav.NodeType == XPathNodeType.Element) { List<SubExpr> lst; string name = nav.LocalName; string ns = nav.NamespaceURI; Dictionary<string, List<SubExpr>> nextLookup; if (this.nameLookup.TryGetValue(ns, out nextLookup)) { if (nextLookup.TryGetValue(name, out lst)) { for (int i = 0; i < lst.Count; ++i) { childSequences[this.indexLookup[lst[i]].i].Add(nav); } } if (nextLookup.TryGetValue(QueryDataModel.Wildcard, out lst)) { for (int i = 0; i < lst.Count; ++i) { childSequences[this.indexLookup[lst[i]].i].Add(nav); } } } if (this.nameLookup.TryGetValue(QueryDataModel.Wildcard, out nextLookup)) { if (nextLookup.TryGetValue(QueryDataModel.Wildcard, out lst)) { for (int i = 0; i < lst.Count; ++i) { childSequences[this.indexLookup[lst[i]].i].Add(nav); } } } } } while (nav.MoveToNext()); } int secondMarker = context.Processor.CounterMarker; for (int i = 0; i < this.children.Count; ++i) { if (this.children[i].useSpecial) { childSequences[i].StopNodeset(); context.Processor.CounterMarker = secondMarker; context.PushSequenceFrame(); context.PushSequence(childSequences[i]); Opcode op = this.children[i].FirstOp.Next; while (op != null) { op = op.Eval(context); } context.SaveVariable(this.children[i].var, context.Processor.ElapsedCount(marker)); context.PopSequenceFrame(); } else { context.ReleaseSequence(childSequences[i]); //context.SetVariable(this.children[i].Variable, null, 0); } } context.Processor.CounterMarker = marker; } internal void RebuildIndex() { this.indexLookup.Clear(); for (int i = 0; i < this.children.Count; ++i) { this.indexLookup.Add(this.children[i], new MyInt(i)); } } internal override void RemoveChild(SubExpr expr) { base.RemoveChild(expr); RebuildIndex(); if (expr.useSpecial) { NodeQName qname = ((SelectOpcode)(expr.FirstOp)).Criteria.QName; string ns = qname.Namespace; Dictionary<string, List<SubExpr>> nextLookup; if (this.nameLookup.TryGetValue(ns, out nextLookup)) { string name = qname.Name; List<SubExpr> exprs; if (nextLookup.TryGetValue(name, out exprs)) { exprs.Remove(expr); if (exprs.Count == 0) { nextLookup.Remove(name); } } if (nextLookup.Count == 0) { this.nameLookup.Remove(ns); } } } } internal class MyInt { internal int i; internal MyInt(int i) { this.i = i; } } } internal class SubExprEliminator { List<SubExpr> exprList; int nextVar; Dictionary<object, List<SubExpr>> removalMapping; internal SubExprEliminator() { this.removalMapping = new Dictionary<object, List<SubExpr>>(); this.exprList = new List<SubExpr>(); Opcode op = new XPathMessageFunctionCallOpcode(XPathMessageContext.HeaderFun, 0); SubExprHeader header = new SubExprHeader(op, 0); this.exprList.Add(header); this.nextVar = 1; } internal List<SubExpr> Exprs { get { return this.exprList; } } internal int VariableCount { get { return this.nextVar; } } internal Opcode Add(object item, Opcode ops) { List<SubExpr> exprs = new List<SubExpr>(); this.removalMapping.Add(item, exprs); while (ops.Next != null) { ops = ops.Next; } Opcode res = ops; while (ops != null) { if (IsExprStarter(ops)) { Opcode start = ops; Opcode p = ops.Prev; ops.DetachFromParent(); ops = ops.Next; while (ops.ID == OpcodeID.Select) { ops = ops.Next; } ops.DetachFromParent(); SubExpr e = null; for (int i = 0; i < this.exprList.Count; ++i) { if (this.exprList[i].FirstOp.Equals(start)) { e = this.exprList[i]; break; } } SubExprOpcode o; if (e == null) { e = new SubExpr(null, start, NewVarID()); this.exprList.Add(e); o = new SubExprOpcode(e); } else { o = e.Add(start, this); } o.Expr.IncRef(); exprs.Add(o.Expr); o.Attach(ops); ops = o; if (p != null) { p.Attach(ops); } } res = ops; ops = ops.Prev; } return res; } internal static bool IsExprStarter(Opcode op) { if (op.ID == OpcodeID.SelectRoot) { return true; } if (op.ID == OpcodeID.XsltInternalFunction) { XPathMessageFunctionCallOpcode fop = (XPathMessageFunctionCallOpcode)op; if (fop.ReturnType == XPathResultType.NodeSet && fop.ArgCount == 0) { return true; } } return false; } internal int NewVarID() { return nextVar++; } internal void Remove(object item) { List<SubExpr> exprs; if (this.removalMapping.TryGetValue(item, out exprs)) { for (int i = 0; i < exprs.Count; ++i) { exprs[i].DecRef(this); } this.removalMapping.Remove(item); Renumber(); } } void Renumber() { this.nextVar = 0; for (int i = 0; i < this.exprList.Count; ++i) { this.exprList[i].Renumber(this); } } internal void Trim() { this.exprList.Capacity = this.exprList.Count; for (int i = 0; i < this.exprList.Count; ++i) { this.exprList[i].Trim(); } } #if DEBUG_FILTER internal void Write(TextWriter outStream) { for(int i = 0; i < this.exprList.Count; ++i) { this.exprList[i].Write(outStream); } } #endif } internal class SubExprOpcode : Opcode { protected SubExpr expr; internal SubExprOpcode(SubExpr expr) : base(OpcodeID.SubExpr) { this.expr = expr; } internal SubExpr Expr { get { return expr; } } internal override bool Equals(Opcode op) { if (base.Equals(op)) { SubExprOpcode sop = op as SubExprOpcode; if (sop != null) { return this.expr == sop.expr; } } return false; } internal override Opcode Eval(ProcessingContext context) { if (!context.LoadVariable(this.expr.Variable)) { context.PushSequenceFrame(); NodeSequence seq = context.CreateSequence(); seq.Add(context.Processor.ContextNode); context.PushSequence(seq); int marker = context.Processor.CounterMarker; try { this.expr.Eval(context); } catch (XPathNavigatorException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e.Process(this)); } catch (NavigatorInvalidBodyAccessException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e.Process(this)); } context.Processor.CounterMarker = marker; context.PopSequenceFrame(); context.PopSequenceFrame(); context.LoadVariable(this.expr.Variable); } return this.next; } internal override Opcode EvalSpecial(ProcessingContext context) { try { this.expr.EvalSpecial(context); } catch (XPathNavigatorException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e.Process(this)); } catch (NavigatorInvalidBodyAccessException e) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(e.Process(this)); } return this.next; } #if DEBUG_FILTER public override string ToString() { return string.Format("{0} #{1}", base.ToString(), this.expr.Variable.ToString()); } #endif } internal class InternalSubExprOpcode : SubExprOpcode { internal InternalSubExprOpcode(SubExpr expr) : base(expr) { } internal override Opcode Eval(ProcessingContext context) { if (!context.LoadVariable(this.expr.Variable)) { this.expr.Eval(context); } return this.next; } internal override Opcode EvalSpecial(ProcessingContext context) { this.expr.EvalSpecial(context); return this.next; } } }
/* * 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 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.Collections.Generic; using System.IO; using System.Xml; using log4net.Config; using NUnit.Framework; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.Framework.Scenes.Serialization; using OpenSim.Tests.Common; using OpenSim.Tests.Common.Setup; namespace OpenSim.Region.CoreModules.World.Serialiser.Tests { [TestFixture] public class SerialiserTests { private string xml = @" <SceneObjectGroup> <RootPart> <SceneObjectPart xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> <AllowedDrop>false</AllowedDrop> <CreatorID><Guid>a6dacf01-4636-4bb9-8a97-30609438af9d</Guid></CreatorID> <FolderID><Guid>e6a5a05e-e8cc-4816-8701-04165e335790</Guid></FolderID> <InventorySerial>1</InventorySerial> <TaskInventory /> <ObjectFlags>0</ObjectFlags> <UUID><Guid>e6a5a05e-e8cc-4816-8701-04165e335790</Guid></UUID> <LocalId>2698615125</LocalId> <Name>PrimMyRide</Name> <Material>0</Material> <PassTouches>false</PassTouches> <RegionHandle>1099511628032000</RegionHandle> <ScriptAccessPin>0</ScriptAccessPin> <GroupPosition><X>147.23</X><Y>92.698</Y><Z>22.78084</Z></GroupPosition> <OffsetPosition><X>0</X><Y>0</Y><Z>0</Z></OffsetPosition> <RotationOffset><X>-4.371139E-08</X><Y>-1</Y><Z>-4.371139E-08</Z><W>0</W></RotationOffset> <Velocity><X>0</X><Y>0</Y><Z>0</Z></Velocity> <RotationalVelocity><X>0</X><Y>0</Y><Z>0</Z></RotationalVelocity> <AngularVelocity><X>0</X><Y>0</Y><Z>0</Z></AngularVelocity> <Acceleration><X>0</X><Y>0</Y><Z>0</Z></Acceleration> <Description /> <Color /> <Text /> <SitName /> <TouchName /> <LinkNum>0</LinkNum> <ClickAction>0</ClickAction> <Shape> <ProfileCurve>1</ProfileCurve> <TextureEntry>AAAAAAAAERGZmQAAAAAABQCVlZUAAAAAQEAAAABAQAAAAAAAAAAAAAAAAAAAAA==</TextureEntry> <ExtraParams>AA==</ExtraParams> <PathBegin>0</PathBegin> <PathCurve>16</PathCurve> <PathEnd>0</PathEnd> <PathRadiusOffset>0</PathRadiusOffset> <PathRevolutions>0</PathRevolutions> <PathScaleX>100</PathScaleX> <PathScaleY>100</PathScaleY> <PathShearX>0</PathShearX> <PathShearY>0</PathShearY> <PathSkew>0</PathSkew> <PathTaperX>0</PathTaperX> <PathTaperY>0</PathTaperY> <PathTwist>0</PathTwist> <PathTwistBegin>0</PathTwistBegin> <PCode>9</PCode> <ProfileBegin>0</ProfileBegin> <ProfileEnd>0</ProfileEnd> <ProfileHollow>0</ProfileHollow> <Scale><X>10</X><Y>10</Y><Z>0.5</Z></Scale> <State>0</State> <ProfileShape>Square</ProfileShape> <HollowShape>Same</HollowShape> <SculptTexture><Guid>00000000-0000-0000-0000-000000000000</Guid></SculptTexture> <SculptType>0</SculptType><SculptData /> <FlexiSoftness>0</FlexiSoftness> <FlexiTension>0</FlexiTension> <FlexiDrag>0</FlexiDrag> <FlexiGravity>0</FlexiGravity> <FlexiWind>0</FlexiWind> <FlexiForceX>0</FlexiForceX> <FlexiForceY>0</FlexiForceY> <FlexiForceZ>0</FlexiForceZ> <LightColorR>0</LightColorR> <LightColorG>0</LightColorG> <LightColorB>0</LightColorB> <LightColorA>1</LightColorA> <LightRadius>0</LightRadius> <LightCutoff>0</LightCutoff> <LightFalloff>0</LightFalloff> <LightIntensity>1</LightIntensity> <FlexiEntry>false</FlexiEntry> <LightEntry>false</LightEntry> <SculptEntry>false</SculptEntry> </Shape> <Scale><X>10</X><Y>10</Y><Z>0.5</Z></Scale> <UpdateFlag>0</UpdateFlag> <SitTargetOrientation><X>0</X><Y>0</Y><Z>0</Z><W>1</W></SitTargetOrientation> <SitTargetPosition><X>0</X><Y>0</Y><Z>0</Z></SitTargetPosition> <SitTargetPositionLL><X>0</X><Y>0</Y><Z>0</Z></SitTargetPositionLL> <SitTargetOrientationLL><X>0</X><Y>0</Y><Z>0</Z><W>1</W></SitTargetOrientationLL> <ParentID>0</ParentID> <CreationDate>1211330445</CreationDate> <Category>0</Category> <SalePrice>0</SalePrice> <ObjectSaleType>0</ObjectSaleType> <OwnershipCost>0</OwnershipCost> <GroupID><Guid>00000000-0000-0000-0000-000000000000</Guid></GroupID> <OwnerID><Guid>a6dacf01-4636-4bb9-8a97-30609438af9d</Guid></OwnerID> <LastOwnerID><Guid>a6dacf01-4636-4bb9-8a97-30609438af9d</Guid></LastOwnerID> <BaseMask>2147483647</BaseMask> <OwnerMask>2147483647</OwnerMask> <GroupMask>0</GroupMask> <EveryoneMask>0</EveryoneMask> <NextOwnerMask>2147483647</NextOwnerMask> <Flags>None</Flags> <CollisionSound><Guid>00000000-0000-0000-0000-000000000000</Guid></CollisionSound> <CollisionSoundVolume>0</CollisionSoundVolume> </SceneObjectPart> </RootPart> <OtherParts /> </SceneObjectGroup>"; private string xml2 = @" <SceneObjectGroup> <SceneObjectPart xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> <CreatorID><UUID>b46ef588-411e-4a8b-a284-d7dcfe8e74ef</UUID></CreatorID> <FolderID><UUID>9be68fdd-f740-4a0f-9675-dfbbb536b946</UUID></FolderID> <InventorySerial>0</InventorySerial> <TaskInventory /> <ObjectFlags>0</ObjectFlags> <UUID><UUID>9be68fdd-f740-4a0f-9675-dfbbb536b946</UUID></UUID> <LocalId>720005</LocalId> <Name>PrimFun</Name> <Material>0</Material> <RegionHandle>1099511628032000</RegionHandle> <ScriptAccessPin>0</ScriptAccessPin> <GroupPosition><X>153.9854</X><Y>121.4908</Y><Z>62.21781</Z></GroupPosition> <OffsetPosition><X>0</X><Y>0</Y><Z>0</Z></OffsetPosition> <RotationOffset><X>0</X><Y>0</Y><Z>0</Z><W>1</W></RotationOffset> <Velocity><X>0</X><Y>0</Y><Z>0</Z></Velocity> <RotationalVelocity><X>0</X><Y>0</Y><Z>0</Z></RotationalVelocity> <AngularVelocity><X>0</X><Y>0</Y><Z>0</Z></AngularVelocity> <Acceleration><X>0</X><Y>0</Y><Z>0</Z></Acceleration> <Description /> <Color /> <Text /> <SitName /> <TouchName /> <LinkNum>0</LinkNum> <ClickAction>0</ClickAction> <Shape> <PathBegin>0</PathBegin> <PathCurve>16</PathCurve> <PathEnd>0</PathEnd> <PathRadiusOffset>0</PathRadiusOffset> <PathRevolutions>0</PathRevolutions> <PathScaleX>200</PathScaleX> <PathScaleY>200</PathScaleY> <PathShearX>0</PathShearX> <PathShearY>0</PathShearY> <PathSkew>0</PathSkew> <PathTaperX>0</PathTaperX> <PathTaperY>0</PathTaperY> <PathTwist>0</PathTwist> <PathTwistBegin>0</PathTwistBegin> <PCode>9</PCode> <ProfileBegin>0</ProfileBegin> <ProfileEnd>0</ProfileEnd> <ProfileHollow>0</ProfileHollow> <Scale><X>1.283131</X><Y>5.903858</Y><Z>4.266288</Z></Scale> <State>0</State> <ProfileShape>Circle</ProfileShape> <HollowShape>Same</HollowShape> <ProfileCurve>0</ProfileCurve> <TextureEntry>iVVnRyTLQ+2SC0fK7RVGXwJ6yc/SU4RDA5nhJbLUw3R1AAAAAAAAaOw8QQOhPSRAAKE9JEAAAAAAAAAAAAAAAAAAAAA=</TextureEntry> <ExtraParams>AA==</ExtraParams> </Shape> <Scale><X>1.283131</X><Y>5.903858</Y><Z>4.266288</Z></Scale> <UpdateFlag>0</UpdateFlag> <SitTargetOrientation><w>0</w><x>0</x><y>0</y><z>1</z></SitTargetOrientation> <SitTargetPosition><x>0</x><y>0</y><z>0</z></SitTargetPosition> <SitTargetPositionLL><X>0</X><Y>0</Y><Z>0</Z></SitTargetPositionLL> <SitTargetOrientationLL><X>0</X><Y>0</Y><Z>1</Z><W>0</W></SitTargetOrientationLL> <ParentID>0</ParentID> <CreationDate>1216066902</CreationDate> <Category>0</Category> <SalePrice>0</SalePrice> <ObjectSaleType>0</ObjectSaleType> <OwnershipCost>0</OwnershipCost> <GroupID><UUID>00000000-0000-0000-0000-000000000000</UUID></GroupID> <OwnerID><UUID>b46ef588-411e-4a8b-a284-d7dcfe8e74ef</UUID></OwnerID> <LastOwnerID><UUID>b46ef588-411e-4a8b-a284-d7dcfe8e74ef</UUID></LastOwnerID> <BaseMask>2147483647</BaseMask> <OwnerMask>2147483647</OwnerMask> <GroupMask>0</GroupMask> <EveryoneMask>0</EveryoneMask> <NextOwnerMask>2147483647</NextOwnerMask> <Flags>None</Flags> <SitTargetAvatar><UUID>00000000-0000-0000-0000-000000000000</UUID></SitTargetAvatar> </SceneObjectPart> <OtherParts /> </SceneObjectGroup>"; protected Scene m_scene; protected SerialiserModule m_serialiserModule; [TestFixtureSetUp] public void Init() { m_serialiserModule = new SerialiserModule(); m_scene = SceneSetupHelpers.SetupScene(); SceneSetupHelpers.SetupSceneModules(m_scene, m_serialiserModule); } [Test] public void TestDeserializeXml() { TestHelper.InMethod(); //log4net.Config.XmlConfigurator.Configure(); SceneObjectGroup so = SceneObjectSerializer.FromOriginalXmlFormat(xml); SceneObjectPart rootPart = so.RootPart; Assert.That(rootPart.UUID, Is.EqualTo(new UUID("e6a5a05e-e8cc-4816-8701-04165e335790"))); Assert.That(rootPart.CreatorID, Is.EqualTo(new UUID("a6dacf01-4636-4bb9-8a97-30609438af9d"))); Assert.That(rootPart.Name, Is.EqualTo("PrimMyRide")); // TODO: Check other properties } [Test] public void TestSerializeXml() { TestHelper.InMethod(); //log4net.Config.XmlConfigurator.Configure(); string rpName = "My Little Donkey"; UUID rpUuid = UUID.Parse("00000000-0000-0000-0000-000000000964"); UUID rpCreatorId = UUID.Parse("00000000-0000-0000-0000-000000000915"); PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere(); // Vector3 groupPosition = new Vector3(10, 20, 30); // Quaternion rotationOffset = new Quaternion(20, 30, 40, 50); // Vector3 offsetPosition = new Vector3(5, 10, 15); SceneObjectPart rp = new SceneObjectPart(); rp.UUID = rpUuid; rp.Name = rpName; rp.CreatorID = rpCreatorId; rp.Shape = shape; SceneObjectGroup so = new SceneObjectGroup(rp); // Need to add the object to the scene so that the request to get script state succeeds m_scene.AddSceneObject(so); string xml = SceneObjectSerializer.ToOriginalXmlFormat(so); XmlTextReader xtr = new XmlTextReader(new StringReader(xml)); xtr.ReadStartElement("SceneObjectGroup"); xtr.ReadStartElement("RootPart"); xtr.ReadStartElement("SceneObjectPart"); UUID uuid = UUID.Zero; string name = null; UUID creatorId = UUID.Zero; while (xtr.Read() && xtr.Name != "SceneObjectPart") { if (xtr.NodeType != XmlNodeType.Element) continue; switch (xtr.Name) { case "UUID": xtr.ReadStartElement("UUID"); try { uuid = UUID.Parse(xtr.ReadElementString("UUID")); xtr.ReadEndElement(); } catch { } // ignore everything but <UUID><UUID>...</UUID></UUID> break; case "Name": name = xtr.ReadElementContentAsString(); break; case "CreatorID": xtr.ReadStartElement("CreatorID"); creatorId = UUID.Parse(xtr.ReadElementString("UUID")); xtr.ReadEndElement(); break; } } xtr.ReadEndElement(); xtr.ReadEndElement(); xtr.ReadStartElement("OtherParts"); xtr.ReadEndElement(); xtr.Close(); // TODO: More checks Assert.That(uuid, Is.EqualTo(rpUuid)); Assert.That(name, Is.EqualTo(rpName)); Assert.That(creatorId, Is.EqualTo(rpCreatorId)); } [Test] public void TestDeserializeXml2() { TestHelper.InMethod(); //log4net.Config.XmlConfigurator.Configure(); SceneObjectGroup so = m_serialiserModule.DeserializeGroupFromXml2(xml2); SceneObjectPart rootPart = so.RootPart; Assert.That(rootPart.UUID, Is.EqualTo(new UUID("9be68fdd-f740-4a0f-9675-dfbbb536b946"))); Assert.That(rootPart.CreatorID, Is.EqualTo(new UUID("b46ef588-411e-4a8b-a284-d7dcfe8e74ef"))); Assert.That(rootPart.Name, Is.EqualTo("PrimFun")); // TODO: Check other properties } [Test] public void TestSerializeXml2() { TestHelper.InMethod(); //log4net.Config.XmlConfigurator.Configure(); string rpName = "My Little Pony"; UUID rpUuid = UUID.Parse("00000000-0000-0000-0000-000000000064"); UUID rpCreatorId = UUID.Parse("00000000-0000-0000-0000-000000000015"); PrimitiveBaseShape shape = PrimitiveBaseShape.CreateSphere(); // Vector3 groupPosition = new Vector3(10, 20, 30); // Quaternion rotationOffset = new Quaternion(20, 30, 40, 50); // Vector3 offsetPosition = new Vector3(5, 10, 15); SceneObjectPart rp = new SceneObjectPart(); rp.UUID = rpUuid; rp.Name = rpName; rp.CreatorID = rpCreatorId; rp.Shape = shape; SceneObjectGroup so = new SceneObjectGroup(rp); // Need to add the object to the scene so that the request to get script state succeeds m_scene.AddSceneObject(so); Dictionary<string, object> options = new Dictionary<string, object>(); options["old-guids"] = true; string xml2 = m_serialiserModule.SerializeGroupToXml2(so, options); XmlTextReader xtr = new XmlTextReader(new StringReader(xml2)); xtr.ReadStartElement("SceneObjectGroup"); xtr.ReadStartElement("SceneObjectPart"); UUID uuid = UUID.Zero; string name = null; UUID creatorId = UUID.Zero; while (xtr.Read() && xtr.Name != "SceneObjectPart") { if (xtr.NodeType != XmlNodeType.Element) continue; switch (xtr.Name) { case "UUID": xtr.ReadStartElement("UUID"); uuid = UUID.Parse(xtr.ReadElementString("Guid")); xtr.ReadEndElement(); break; case "Name": name = xtr.ReadElementContentAsString(); break; case "CreatorID": xtr.ReadStartElement("CreatorID"); creatorId = UUID.Parse(xtr.ReadElementString("Guid")); xtr.ReadEndElement(); break; } } xtr.ReadEndElement(); xtr.ReadStartElement("OtherParts"); xtr.ReadEndElement(); xtr.Close(); // TODO: More checks Assert.That(uuid, Is.EqualTo(rpUuid)); Assert.That(name, Is.EqualTo(rpName)); Assert.That(creatorId, Is.EqualTo(rpCreatorId)); } } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace AnonReadSecureWriteWeb { public static class TokenHelper { #region public methods /// <summary> /// Configures .Net to trust all certificates when making network calls. This is used so that calls /// to an https SharePoint server without a valid certificate are not rejected. This should only be used during /// testing, and should never be used in a production app. /// </summary> public static void TrustAllCertificates() { //Trust all certificates ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) return request.Form[paramName]; if (!string.IsNullOrEmpty(request.QueryString[paramName])) return request.QueryString[paramName]; } return null; } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) return request.Form[paramName]; if (!string.IsNullOrEmpty(request.QueryString[paramName])) return request.QueryString[paramName]; } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (ClientCertificate != null) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (ClientCertificate != null) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; const string bearer = "Bearer realm=\""; int realmIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal) + bearer.Length; if (bearerResponseHeader.Length > realmIndex) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } #endregion #region private fields // // Configuration Constants // private const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; private const int TokenLifetimeMinutes = 1000000; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.AddMinutes(TokenLifetimeMinutes), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.AddMinutes(10), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } private static string EnsureTrailingSlash(string url) { if (!String.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } public class OAuthTokenPair { public string AccessToken; public string RefreshToken; } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
namespace StockSharp.Algo.Storages.Binary.Snapshot { using System; using System.Runtime.InteropServices; using Ecng.Common; using Ecng.Interop; using StockSharp.Messages; using Key = System.Tuple<Messages.SecurityId, string, string>; /// <summary> /// Implementation of <see cref="ISnapshotSerializer{TKey,TMessage}"/> in binary format for <see cref="PositionChangeMessage"/>. /// </summary> public class PositionBinarySnapshotSerializer : ISnapshotSerializer<Key, PositionChangeMessage> { [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)] private struct PositionSnapshot { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Sizes.S100)] public string SecurityId; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Sizes.S100)] public string Portfolio; public long LastChangeServerTime; public long LastChangeLocalTime; public BlittableDecimal? BeginValue; public BlittableDecimal? CurrentValue; public BlittableDecimal? BlockedValue; public BlittableDecimal? CurrentPrice; public BlittableDecimal? AveragePrice; public BlittableDecimal? UnrealizedPnL; public BlittableDecimal? RealizedPnL; public BlittableDecimal? VariationMargin; public short? Currency; public BlittableDecimal? Leverage; public BlittableDecimal? Commission; public BlittableDecimal? CurrentValueInLots; public byte? State; public long? ExpirationDate; public BlittableDecimal? CommissionTaker; public BlittableDecimal? CommissionMaker; public BlittableDecimal? SettlementPrice; public int? BuyOrdersCount; public int? SellOrdersCount; public BlittableDecimal? BuyOrdersMargin; public BlittableDecimal? SellOrdersMargin; public BlittableDecimal? OrdersMargin; public int? OrdersCount; public int? TradesCount; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Sizes.S100)] public string DepoName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Sizes.S100)] public string BoardCode; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Sizes.S100)] public string ClientCode; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Sizes.S100)] public string Description; public int? LimitType; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Sizes.S100)] public string StrategyId; public int? Side; public SnapshotDataType? BuildFrom; } Version ISnapshotSerializer<Key, PositionChangeMessage>.Version { get; } = SnapshotVersions.V24; string ISnapshotSerializer<Key, PositionChangeMessage>.Name => "Positions"; byte[] ISnapshotSerializer<Key, PositionChangeMessage>.Serialize(Version version, PositionChangeMessage message) { if (version == null) throw new ArgumentNullException(nameof(version)); if (message == null) throw new ArgumentNullException(nameof(message)); var snapshot = new PositionSnapshot { SecurityId = message.SecurityId.ToStringId().VerifySize(Sizes.S100), Portfolio = message.PortfolioName.VerifySize(Sizes.S100), LastChangeServerTime = message.ServerTime.To<long>(), LastChangeLocalTime = message.LocalTime.To<long>(), DepoName = message.DepoName, LimitType = (int?)message.LimitType, BoardCode = message.BoardCode, ClientCode = message.ClientCode, Description = message.Description, StrategyId = message.StrategyId, Side = (int?)message.Side, BuildFrom = message.BuildFrom == null ? default(SnapshotDataType?) : (SnapshotDataType)message.BuildFrom, }; foreach (var change in message.Changes) { switch (change.Key) { case PositionChangeTypes.BeginValue: snapshot.BeginValue = (BlittableDecimal)(decimal)change.Value; break; case PositionChangeTypes.CurrentValue: snapshot.CurrentValue = (BlittableDecimal)(decimal)change.Value; break; case PositionChangeTypes.BlockedValue: snapshot.BlockedValue = (BlittableDecimal)(decimal)change.Value; break; case PositionChangeTypes.CurrentPrice: snapshot.CurrentPrice = (BlittableDecimal)(decimal)change.Value; break; case PositionChangeTypes.AveragePrice: snapshot.AveragePrice = (BlittableDecimal)(decimal)change.Value; break; case PositionChangeTypes.UnrealizedPnL: snapshot.UnrealizedPnL = (BlittableDecimal)(decimal)change.Value; break; case PositionChangeTypes.RealizedPnL: snapshot.RealizedPnL = (BlittableDecimal)(decimal)change.Value; break; case PositionChangeTypes.VariationMargin: snapshot.VariationMargin = (BlittableDecimal)(decimal)change.Value; break; case PositionChangeTypes.Currency: snapshot.Currency = (short)(CurrencyTypes)change.Value; break; case PositionChangeTypes.Leverage: snapshot.Leverage = (BlittableDecimal)(decimal)change.Value; break; case PositionChangeTypes.Commission: snapshot.Commission = (BlittableDecimal)(decimal)change.Value; break; case PositionChangeTypes.CurrentValueInLots: snapshot.CurrentValueInLots = (BlittableDecimal)(decimal)change.Value; break; case PositionChangeTypes.State: snapshot.State = (byte)(PortfolioStates)change.Value; break; case PositionChangeTypes.ExpirationDate: snapshot.ExpirationDate = change.Value.To<long?>(); break; case PositionChangeTypes.CommissionTaker: snapshot.CommissionTaker = (BlittableDecimal)(decimal)change.Value; break; case PositionChangeTypes.CommissionMaker: snapshot.CommissionMaker = (BlittableDecimal)(decimal)change.Value; break; case PositionChangeTypes.SettlementPrice: snapshot.SettlementPrice = (BlittableDecimal)(decimal)change.Value; break; case PositionChangeTypes.BuyOrdersCount: snapshot.BuyOrdersCount = (int)change.Value; break; case PositionChangeTypes.SellOrdersCount: snapshot.SellOrdersCount = (int)change.Value; break; case PositionChangeTypes.BuyOrdersMargin: snapshot.BuyOrdersMargin = (BlittableDecimal)(decimal)change.Value; break; case PositionChangeTypes.SellOrdersMargin: snapshot.SellOrdersMargin = (BlittableDecimal)(decimal)change.Value; break; case PositionChangeTypes.OrdersMargin: snapshot.OrdersMargin = (BlittableDecimal)(decimal)change.Value; break; case PositionChangeTypes.OrdersCount: snapshot.OrdersCount = (int)change.Value; break; case PositionChangeTypes.TradesCount: snapshot.TradesCount = (int)change.Value; break; default: throw new InvalidOperationException(change.Key.To<string>()); } } var buffer = new byte[typeof(PositionSnapshot).SizeOf()]; var ptr = snapshot.StructToPtr(); ptr.CopyTo(buffer); ptr.FreeHGlobal(); return buffer; } PositionChangeMessage ISnapshotSerializer<Key, PositionChangeMessage>.Deserialize(Version version, byte[] buffer) { if (version == null) throw new ArgumentNullException(nameof(version)); using (var handle = new GCHandle<byte[]>(buffer)) { var snapshot = handle.CreatePointer().ToStruct<PositionSnapshot>(true); var posMsg = new PositionChangeMessage { SecurityId = snapshot.SecurityId.ToSecurityId(), PortfolioName = snapshot.Portfolio, ServerTime = snapshot.LastChangeServerTime.To<DateTimeOffset>(), LocalTime = snapshot.LastChangeLocalTime.To<DateTimeOffset>(), ClientCode = snapshot.ClientCode, DepoName = snapshot.DepoName, BoardCode = snapshot.BoardCode, LimitType = (TPlusLimits?)snapshot.LimitType, Description = snapshot.Description, StrategyId = snapshot.StrategyId, Side = (Sides?)snapshot.Side, BuildFrom = snapshot.BuildFrom, } .TryAdd(PositionChangeTypes.BeginValue, snapshot.BeginValue, true) .TryAdd(PositionChangeTypes.CurrentValue, snapshot.CurrentValue, true) .TryAdd(PositionChangeTypes.BlockedValue, snapshot.BlockedValue, true) .TryAdd(PositionChangeTypes.CurrentPrice, snapshot.CurrentPrice, true) .TryAdd(PositionChangeTypes.AveragePrice, snapshot.AveragePrice, true) .TryAdd(PositionChangeTypes.UnrealizedPnL, snapshot.UnrealizedPnL, true) .TryAdd(PositionChangeTypes.RealizedPnL, snapshot.RealizedPnL, true) .TryAdd(PositionChangeTypes.VariationMargin, snapshot.VariationMargin, true) .TryAdd(PositionChangeTypes.Leverage, snapshot.Leverage, true) .TryAdd(PositionChangeTypes.Commission, snapshot.Commission, true) .TryAdd(PositionChangeTypes.CurrentValueInLots, snapshot.CurrentValueInLots, true) .TryAdd(PositionChangeTypes.CommissionTaker, snapshot.CommissionTaker, true) .TryAdd(PositionChangeTypes.CommissionMaker, snapshot.CommissionMaker, true) .TryAdd(PositionChangeTypes.SettlementPrice, snapshot.SettlementPrice, true) .TryAdd(PositionChangeTypes.ExpirationDate, snapshot.ExpirationDate.To<DateTimeOffset?>()) .TryAdd(PositionChangeTypes.BuyOrdersCount, snapshot.BuyOrdersCount, true) .TryAdd(PositionChangeTypes.SellOrdersCount, snapshot.SellOrdersCount, true) .TryAdd(PositionChangeTypes.BuyOrdersMargin, snapshot.BuyOrdersMargin, true) .TryAdd(PositionChangeTypes.SellOrdersMargin, snapshot.SellOrdersMargin, true) .TryAdd(PositionChangeTypes.OrdersMargin, snapshot.OrdersMargin, true) .TryAdd(PositionChangeTypes.OrdersCount, snapshot.OrdersCount, true) .TryAdd(PositionChangeTypes.TradesCount, snapshot.TradesCount, true) .TryAdd(PositionChangeTypes.State, snapshot.State?.ToEnum<PortfolioStates>()) ; if (snapshot.Currency != null) posMsg.Add(PositionChangeTypes.Currency, (CurrencyTypes)snapshot.Currency.Value); return posMsg; } } Key ISnapshotSerializer<Key, PositionChangeMessage>.GetKey(PositionChangeMessage message) => Tuple.Create(message.SecurityId, message.PortfolioName, message.StrategyId ?? string.Empty); void ISnapshotSerializer<Key, PositionChangeMessage>.Update(PositionChangeMessage message, PositionChangeMessage changes) { foreach (var pair in changes.Changes) { message.Changes[pair.Key] = pair.Value; } if (changes.LimitType != null) message.LimitType = changes.LimitType; if (!changes.DepoName.IsEmpty()) message.DepoName = changes.DepoName; if (!changes.ClientCode.IsEmpty()) message.ClientCode = changes.ClientCode; if (!changes.BoardCode.IsEmpty()) message.BoardCode = changes.BoardCode; if (!changes.Description.IsEmpty()) message.Description = changes.Description; if (!changes.StrategyId.IsEmpty()) message.StrategyId = changes.StrategyId; if (changes.Side != null) message.Side = changes.Side; if (changes.BuildFrom != default) message.BuildFrom = changes.BuildFrom; message.LocalTime = changes.LocalTime; message.ServerTime = changes.ServerTime; } DataType ISnapshotSerializer<Key, PositionChangeMessage>.DataType => DataType.PositionChanges; } }
using System.ComponentModel; using System.ComponentModel.Design; using System.Drawing; // found at http://www.codeproject.com/Articles/53318/C-Custom-Control-Featuring-a-Collapsible-Panel namespace DotNetControlsEx { public class CollapsiblePanelActionList : DesignerActionList { public CollapsiblePanelActionList(IComponent component) : base(component) { } public string LeftTitle { get { return ((CollapsiblePanel)this.Component).HeaderText; } set { PropertyDescriptor property = TypeDescriptor.GetProperties(this.Component)["HeaderText"]; property.SetValue(this.Component, value); } } public bool UseAnimation { get { return ((CollapsiblePanel)this.Component).UseAnimation; } set { PropertyDescriptor property = TypeDescriptor.GetProperties(this.Component)["UseAnimation"]; property.SetValue(this.Component, value); } } public bool Collapsed { get { return ((CollapsiblePanel)this.Component).Collapse; } set { PropertyDescriptor property = TypeDescriptor.GetProperties(this.Component)["Collapse"]; property.SetValue(this.Component, value); } } public bool ShowSeparator { get { return ((CollapsiblePanel)this.Component).ShowHeaderSeparator; } set { PropertyDescriptor property = TypeDescriptor.GetProperties(this.Component)["ShowHeaderSeparator"]; property.SetValue(this.Component, value); } } public bool UseRoundedCorner { get { return ((CollapsiblePanel)this.Component).RoundedCorners; } set { PropertyDescriptor property = TypeDescriptor.GetProperties(this.Component)["RoundedCorners"]; property.SetValue(this.Component, value); } } public int HeaderCornersRadius { get { return ((CollapsiblePanel)this.Component).HeaderCornersRadius; } set { PropertyDescriptor property = TypeDescriptor.GetProperties(this.Component)["HeaderCornersRadius"]; property.SetValue(this.Component, value); } } public Image HeaderImage { get { return ((CollapsiblePanel)this.Component).HeaderImage; } set { PropertyDescriptor property = TypeDescriptor.GetProperties(this.Component)["HeaderImage"]; property.SetValue(this.Component, value); } } public override DesignerActionItemCollection GetSortedActionItems() { DesignerActionItemCollection items = new DesignerActionItemCollection(); items.Add(new DesignerActionHeaderItem("Header Parameters")); items.Add(new DesignerActionPropertyItem("Title", "Panel's header text")); items.Add(new DesignerActionPropertyItem("HeaderImage", "Image")); items.Add(new DesignerActionPropertyItem("UseAnimation", "Animated panel")); items.Add(new DesignerActionPropertyItem("Collapsed", "Collapse")); items.Add(new DesignerActionPropertyItem("ShowSeparator", "Show borders")); items.Add(new DesignerActionPropertyItem("UseRoundedCorner","Rounded corners")); items.Add(new DesignerActionPropertyItem("HeaderCornersRadius", "Corner's radius [5,10]")); return items; } } public class CollapsiblePanelExActionList : DesignerActionList { public CollapsiblePanelExActionList(IComponent component) : base(component) { } public string LeftTitle { get { return ((CollapsiblePanelEx)this.Component).LeftHeaderText; } set { PropertyDescriptor property = TypeDescriptor.GetProperties(this.Component)["LeftHeaderText"]; property.SetValue(this.Component, value); } } public string CenterTitle { get { return ((CollapsiblePanelEx)this.Component).CenterHeaderText; } set { PropertyDescriptor property = TypeDescriptor.GetProperties(this.Component)["CenterHeaderText"]; property.SetValue(this.Component, value); } } public bool UseAnimation { get { return ((CollapsiblePanelEx)this.Component).UseAnimation; } set { PropertyDescriptor property = TypeDescriptor.GetProperties(this.Component)["UseAnimation"]; property.SetValue(this.Component, value); } } public bool Collapsed { get { return ((CollapsiblePanelEx)this.Component).Collapse; } set { PropertyDescriptor property = TypeDescriptor.GetProperties(this.Component)["Collapse"]; property.SetValue(this.Component, value); } } public bool ShowSeparator { get { return ((CollapsiblePanelEx)this.Component).ShowHeaderSeparator; } set { PropertyDescriptor property = TypeDescriptor.GetProperties(this.Component)["ShowHeaderSeparator"]; property.SetValue(this.Component, value); } } public bool UseRoundedCorner { get { return ((CollapsiblePanelEx)this.Component).RoundedCorners; } set { PropertyDescriptor property = TypeDescriptor.GetProperties(this.Component)["RoundedCorners"]; property.SetValue(this.Component, value); } } public int HeaderCornersRadius { get { return ((CollapsiblePanelEx)this.Component).HeaderCornersRadius; } set { PropertyDescriptor property = TypeDescriptor.GetProperties(this.Component)["HeaderCornersRadius"]; property.SetValue(this.Component, value); } } public Image HeaderImage { get { return ((CollapsiblePanelEx)this.Component).HeaderImage; } set { PropertyDescriptor property = TypeDescriptor.GetProperties(this.Component)["HeaderImage"]; property.SetValue(this.Component, value); } } public override DesignerActionItemCollection GetSortedActionItems() { DesignerActionItemCollection items = new DesignerActionItemCollection(); items.Add(new DesignerActionHeaderItem("Header Parameters")); items.Add(new DesignerActionPropertyItem("LeftTitle", "Panel's header text (left justified)")); items.Add(new DesignerActionPropertyItem("CenterTitle", "Panel's header text (centered)")); items.Add(new DesignerActionPropertyItem("HeaderImage", "Image")); items.Add(new DesignerActionPropertyItem("UseAnimation", "Animated panel")); items.Add(new DesignerActionPropertyItem("Collapsed", "Collapse")); items.Add(new DesignerActionPropertyItem("ShowSeparator", "Show borders")); items.Add(new DesignerActionPropertyItem("UseRoundedCorner", "Rounded corners")); items.Add(new DesignerActionPropertyItem("HeaderCornersRadius", "Corner's radius [5,10]")); return items; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; namespace System.Net { internal class IPAddressParser { private const int MaxIPv4StringLength = 15; // 4 numbers separated by 3 periods, with up to 3 digits per number internal static unsafe IPAddress Parse(ReadOnlySpan<char> ipSpan, bool tryParse) { if (ipSpan.Contains(':')) { // The address is parsed as IPv6 if and only if it contains a colon. This is valid because // we don't support/parse a port specification at the end of an IPv4 address. ushort* numbers = stackalloc ushort[IPAddressParserStatics.IPv6AddressShorts]; new Span<ushort>(numbers, IPAddressParserStatics.IPv6AddressShorts).Clear(); if (Ipv6StringToAddress(ipSpan, numbers, IPAddressParserStatics.IPv6AddressShorts, out uint scope)) { return new IPAddress(numbers, IPAddressParserStatics.IPv6AddressShorts, scope); } } else if (Ipv4StringToAddress(ipSpan, out long address)) { return new IPAddress(address); } if (tryParse) { return null; } throw new FormatException(SR.dns_bad_ip_address, new SocketException(SocketError.InvalidArgument)); } internal static unsafe string IPv4AddressToString(uint address) { char* addressString = stackalloc char[MaxIPv4StringLength]; int charsWritten = IPv4AddressToStringHelper(address, addressString); return new string(addressString, 0, charsWritten); } internal static unsafe void IPv4AddressToString(uint address, StringBuilder destination) { char* addressString = stackalloc char[MaxIPv4StringLength]; int charsWritten = IPv4AddressToStringHelper(address, addressString); destination.Append(addressString, charsWritten); } internal static unsafe bool IPv4AddressToString(uint address, Span<char> formatted, out int charsWritten) { if (formatted.Length < MaxIPv4StringLength) { charsWritten = 0; return false; } fixed (char* formattedPtr = &MemoryMarshal.GetReference(formatted)) { charsWritten = IPv4AddressToStringHelper(address, formattedPtr); } return true; } private static unsafe int IPv4AddressToStringHelper(uint address, char* addressString) { int offset = 0; FormatIPv4AddressNumber((int)(address & 0xFF), addressString, ref offset); addressString[offset++] = '.'; FormatIPv4AddressNumber((int)((address >> 8) & 0xFF), addressString, ref offset); addressString[offset++] = '.'; FormatIPv4AddressNumber((int)((address >> 16) & 0xFF), addressString, ref offset); addressString[offset++] = '.'; FormatIPv4AddressNumber((int)((address >> 24) & 0xFF), addressString, ref offset); return offset; } internal static string IPv6AddressToString(ushort[] address, uint scopeId) { Debug.Assert(address != null); Debug.Assert(address.Length == IPAddressParserStatics.IPv6AddressShorts); StringBuilder buffer = IPv6AddressToStringHelper(address, scopeId); return StringBuilderCache.GetStringAndRelease(buffer); } internal static bool IPv6AddressToString(ushort[] address, uint scopeId, Span<char> destination, out int charsWritten) { Debug.Assert(address != null); Debug.Assert(address.Length == IPAddressParserStatics.IPv6AddressShorts); StringBuilder buffer = IPv6AddressToStringHelper(address, scopeId); if (destination.Length < buffer.Length) { StringBuilderCache.Release(buffer); charsWritten = 0; return false; } buffer.CopyTo(0, destination, buffer.Length); charsWritten = buffer.Length; StringBuilderCache.Release(buffer); return true; } internal static StringBuilder IPv6AddressToStringHelper(ushort[] address, uint scopeId) { const int INET6_ADDRSTRLEN = 65; StringBuilder buffer = StringBuilderCache.Acquire(INET6_ADDRSTRLEN); if (IPv6AddressHelper.ShouldHaveIpv4Embedded(address)) { // We need to treat the last 2 ushorts as a 4-byte IPv4 address, // so output the first 6 ushorts normally, followed by the IPv4 address. AppendSections(address, 0, 6, buffer); if (buffer[buffer.Length - 1] != ':') { buffer.Append(':'); } IPv4AddressToString(ExtractIPv4Address(address), buffer); } else { // No IPv4 address. Output all 8 sections as part of the IPv6 address // with normal formatting rules. AppendSections(address, 0, 8, buffer); } // If there's a scope ID, append it. if (scopeId != 0) { buffer.Append('%').Append(scopeId); } return buffer; } private static unsafe void FormatIPv4AddressNumber(int number, char* addressString, ref int offset) { // Math.DivRem has no overload for byte, assert here for safety Debug.Assert(number < 256); offset += number > 99 ? 3 : number > 9 ? 2 : 1; int i = offset; do { number = Math.DivRem(number, 10, out int rem); addressString[--i] = (char)('0' + rem); } while (number != 0); } public static unsafe bool Ipv4StringToAddress(ReadOnlySpan<char> ipSpan, out long address) { int end = ipSpan.Length; long tmpAddr; fixed (char* ipStringPtr = &MemoryMarshal.GetReference(ipSpan)) { tmpAddr = IPv4AddressHelper.ParseNonCanonical(ipStringPtr, 0, ref end, notImplicitFile: true); } if (tmpAddr != IPv4AddressHelper.Invalid && end == ipSpan.Length) { // IPv4AddressHelper.ParseNonCanonical returns the bytes in the inverse order. // Reverse them and return success. address = ((0xFF000000 & tmpAddr) >> 24) | ((0x00FF0000 & tmpAddr) >> 8) | ((0x0000FF00 & tmpAddr) << 8) | ((0x000000FF & tmpAddr) << 24); return true; } else { // Failed to parse the address. address = 0; return false; } } public static unsafe bool Ipv6StringToAddress(ReadOnlySpan<char> ipSpan, ushort* numbers, int numbersLength, out uint scope) { Debug.Assert(numbers != null); Debug.Assert(numbersLength >= IPAddressParserStatics.IPv6AddressShorts); int end = ipSpan.Length; bool isValid = false; fixed (char* ipStringPtr = &MemoryMarshal.GetReference(ipSpan)) { isValid = IPv6AddressHelper.IsValidStrict(ipStringPtr, 0, ref end); } if (isValid || (end != ipSpan.Length)) { string scopeId = null; IPv6AddressHelper.Parse(ipSpan, numbers, 0, ref scopeId); long result = 0; if (!string.IsNullOrEmpty(scopeId)) { if (scopeId.Length < 2) { scope = 0; return false; } for (int i = 1; i < scopeId.Length; i++) { char c = scopeId[i]; if (c < '0' || c > '9') { scope = 0; return false; } result = (result * 10) + (c - '0'); if (result > uint.MaxValue) { scope = 0; return false; } } } scope = (uint)result; return true; } scope = 0; return false; } /// <summary> /// Appends each of the numbers in address in indexed range [fromInclusive, toExclusive), /// while also replacing the longest sequence of 0s found in that range with "::", as long /// as the sequence is more than one 0. /// </summary> private static void AppendSections(ushort[] address, int fromInclusive, int toExclusive, StringBuilder buffer) { // Find the longest sequence of zeros to be combined into a "::" (int zeroStart, int zeroEnd) = IPv6AddressHelper.FindCompressionRange(address, fromInclusive, toExclusive); bool needsColon = false; // Output all of the numbers before the zero sequence for (int i = fromInclusive; i < zeroStart; i++) { if (needsColon) { buffer.Append(':'); } needsColon = true; AppendHex(address[i], buffer); } // Output the zero sequence if there is one if (zeroStart >= 0) { buffer.Append("::"); needsColon = false; fromInclusive = zeroEnd; } // Output everything after the zero sequence for (int i = fromInclusive; i < toExclusive; i++) { if (needsColon) { buffer.Append(':'); } needsColon = true; AppendHex(address[i], buffer); } } /// <summary>Appends a number as hexadecimal (without the leading "0x") to the StringBuilder.</summary> private static unsafe void AppendHex(ushort value, StringBuilder buffer) { const int MaxLength = sizeof(ushort) * 2; // two hex chars per byte char* chars = stackalloc char[MaxLength]; int pos = MaxLength; do { int rem = value % 16; value /= 16; chars[--pos] = rem < 10 ? (char)('0' + rem) : (char)('a' + (rem - 10)); Debug.Assert(pos >= 0); } while (value != 0); buffer.Append(chars + pos, MaxLength - pos); } /// <summary>Extracts the IPv4 address from the end of the IPv6 address byte array.</summary> private static uint ExtractIPv4Address(ushort[] address) => (uint)(Reverse(address[7]) << 16) | Reverse(address[6]); /// <summary>Reverses the two bytes in the ushort.</summary> private static ushort Reverse(ushort number) => (ushort)(((number >> 8) & 0xFF) | ((number << 8) & 0xFF00)); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Baseline; using Marten.Events; using Marten.Events.Projections; using Microsoft.Extensions.DependencyInjection; namespace Marten.Testing.Events.Examples { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMarten(opts => { opts.Connection("some connection"); // Direct Marten to update the Project aggregate // inline as new events are captured opts .Projections .SelfAggregate<Project>(ProjectionLifecycle.Inline); }); } } public class NewProjectCommand { public string Name { get; set; } public string[] Tasks { get; set; } public string ProjectId { get; set; } } public class NewProjectHandler { private readonly IDocumentSession _session; public NewProjectHandler(IDocumentSession session) { _session = session; } public Task Handle(NewProjectCommand command) { var timestamp = DateTimeOffset.Now; var started = new ProjectStarted {Name = command.Name, Timestamp = timestamp}; var tasks = command.Tasks .Select(name => new TaskRecorded {Timestamp = timestamp, Title = name}); _session.Events.StartStream(command.ProjectId, started); _session.Events.Append(command.ProjectId, tasks); return _session.SaveChangesAsync(); } } public class Project { private readonly IList<ProjectTask> _tasks = new List<ProjectTask>(); public Project(ProjectStarted started) { Version = 1; Name = started.Name; StartedTime = started.Timestamp; } // This gets set by Marten public Guid Id { get; set; } public long Version { get; set; } public DateTimeOffset StartedTime { get; private set; } public DateTimeOffset? CompletedTime { get; private set; } public string Name { get; private set; } public ProjectTask[] Tasks { get { return _tasks.ToArray(); } set { _tasks.Clear(); _tasks.AddRange(value); } } public void Apply(TaskRecorded recorded, IEvent e) { Version = e.Version; var task = new ProjectTask { Title = recorded.Title, Number = _tasks.Max(x => x.Number) + 1, Recorded = recorded.Timestamp }; _tasks.Add(task); } public void Apply(TaskStarted started, IEvent e) { // Update the Project document based on the event version Version = e.Version; var task = _tasks.FirstOrDefault(x => x.Number == started.Number); // Remember this isn't production code:) if (task != null) task.Started = started.Timestamp; } public void Apply(TaskFinished finished, IEvent e) { Version = e.Version; var task = _tasks.FirstOrDefault(x => x.Number == finished.Number); // Remember this isn't production code:) if (task != null) task.Finished = finished.Timestamp; } public void Apply(ProjectCompleted completed, IEvent e) { Version = e.Version; CompletedTime = completed.Timestamp; } } public class ProjectTask { public string Title { get; set; } public DateTimeOffset? Started { get; set; } public DateTimeOffset? Finished { get; set; } public int Number { get; set; } public DateTimeOffset Recorded { get; set; } } public class ProjectStarted { public string Name { get; set; } public DateTimeOffset Timestamp { get; set; } } public class TaskRecorded { public string Title { get; set; } public DateTimeOffset Timestamp { get; set; } } public class TaskStarted { public int Number { get; set; } public DateTimeOffset Timestamp { get; set; } } public class TaskFinished { public int Number { get; set; } public DateTimeOffset? Timestamp { get; set; } } public class ProjectCompleted { public DateTimeOffset Timestamp { get; set; } } public class CreateTaskCommand { public string ProjectId { get; set; } public string Title { get; set; } } public class CreateTaskHandler { private readonly IDocumentSession _session; public CreateTaskHandler(IDocumentSession session) { _session = session; } public Task Handle(CreateTaskCommand command) { var recorded = new TaskRecorded { Timestamp = DateTimeOffset.UtcNow, Title = command.Title }; _session.Events.Append(command.ProjectId, recorded); return _session.SaveChangesAsync(); } } public class CompleteTaskCommand { public string ProjectId { get; set; } public int TaskNumber { get; set; } // This is the version of the project data // that was being edited in the user interface public long ExpectedVersion { get; set; } } public class CompleteTaskHandler { private readonly IDocumentSession _session; public CompleteTaskHandler(IDocumentSession session) { _session = session; } public Task Handle(CompleteTaskCommand command) { var @event = new TaskFinished { Number = command.TaskNumber, Timestamp = DateTimeOffset.UtcNow }; _session.Events.Append( command.ProjectId, // Using this overload will make Marten do // an optimistic concurrency check against // the existing version of the project event // stream as it commits command.ExpectedVersion, @event); return _session.SaveChangesAsync(); } } public class CompleteTaskHandler2 { private readonly IDocumentSession _session; public CompleteTaskHandler2(IDocumentSession session) { _session = session; } public Task Handle(CompleteTaskCommand command) { var @event = new TaskFinished { Number = command.TaskNumber, Timestamp = DateTimeOffset.UtcNow }; // If some other process magically zips // in and updates this project event stream // between the call to AppendOptimistic() // and SaveChangesAsync(), Marten will detect // that and reject the transaction _session.Events.AppendOptimistic( command.ProjectId, @event); return _session.SaveChangesAsync(); } } public class CompleteTaskHandler3 { private readonly IDocumentSession _session; public CompleteTaskHandler3(IDocumentSession session) { _session = session; } public Task Handle(CompleteTaskCommand command) { var @event = new TaskFinished { Number = command.TaskNumber, Timestamp = DateTimeOffset.UtcNow }; // This tries to acquire an exclusive // lock on the stream identified by // command.ProjectId in the database // so that only one process at a time // can update this event stream _session.Events.AppendExclusive( command.ProjectId, @event); return _session.SaveChangesAsync(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Xml.XPath; using FT = MS.Internal.Xml.XPath.Function.FunctionType; namespace MS.Internal.Xml.XPath { internal sealed class QueryBuilder { // Note: Up->Down, Down->Up: // For operators order is normal: 1 + 2 --> Operator+(1, 2) // For paths order is reversed: a/b -> ChildQuery_B(input: ChildQuery_A(input: ContextQuery())) // Input flags. We pass them Up->Down. // Using them upper query set states which controls how inner query will be built. enum Flags { None = 0x00, SmartDesc = 0x01, PosFilter = 0x02, // Node has this flag set when it has position predicate applied to it Filter = 0x04, // Subtree we compiling will be filtered. i.e. Flag not set on rightmost filter. } // Output props. We return them Down->Up. // These are properties of Query tree we have built already. // These properties are closely related to QueryProps exposed by Query node itself. // They have the following difference: // QueryProps describe property of node they are (belong like Reverse) // these Props describe accumulated properties of the tree (like nonFlat) enum Props { None = 0x00, PosFilter = 0x01, // This filter or inner filter was positional: foo[1] or foo[1][true()] HasPosition = 0x02, // Expression may ask position() of the context HasLast = 0x04, // Expression may ask last() of the context NonFlat = 0x08, // Some nodes may be descendent of others } // comment are approximate. This is my best understanding: private string _query; private bool _allowVar; private bool _allowKey; private bool _allowCurrent; private bool _needContext; private BaseAxisQuery _firstInput; // Input of the leftmost predicate. Set by leftmost predicate, used in rightmost one private void Reset() { _parseDepth = 0; _needContext = false; } private Query ProcessAxis(Axis root, Flags flags, out Props props) { Query result = null; if (root.Prefix.Length > 0) { _needContext = true; } _firstInput = null; Query qyInput; { if (root.Input != null) { Flags inputFlags = Flags.None; if ((flags & Flags.PosFilter) == 0) { Axis input = root.Input as Axis; if (input != null) { if ( root.TypeOfAxis == Axis.AxisType.Child && input.TypeOfAxis == Axis.AxisType.DescendantOrSelf && input.NodeType == XPathNodeType.All ) { Query qyGrandInput; if (input.Input != null) { qyGrandInput = ProcessNode(input.Input, Flags.SmartDesc, out props); } else { qyGrandInput = new ContextQuery(); props = Props.None; } result = new DescendantQuery(qyGrandInput, root.Name, root.Prefix, root.NodeType, false, input.AbbrAxis); if ((props & Props.NonFlat) != 0) { result = new DocumentOrderQuery(result); } props |= Props.NonFlat; return result; } } if (root.TypeOfAxis == Axis.AxisType.Descendant || root.TypeOfAxis == Axis.AxisType.DescendantOrSelf) { inputFlags |= Flags.SmartDesc; } } qyInput = ProcessNode(root.Input, inputFlags, out props); } else { qyInput = new ContextQuery(); props = Props.None; } } switch (root.TypeOfAxis) { case Axis.AxisType.Ancestor: result = new XPathAncestorQuery(qyInput, root.Name, root.Prefix, root.NodeType, false); props |= Props.NonFlat; break; case Axis.AxisType.AncestorOrSelf: result = new XPathAncestorQuery(qyInput, root.Name, root.Prefix, root.NodeType, true); props |= Props.NonFlat; break; case Axis.AxisType.Child: if ((props & Props.NonFlat) != 0) { result = new CacheChildrenQuery(qyInput, root.Name, root.Prefix, root.NodeType); } else { result = new ChildrenQuery(qyInput, root.Name, root.Prefix, root.NodeType); } break; case Axis.AxisType.Parent: result = new ParentQuery(qyInput, root.Name, root.Prefix, root.NodeType); break; case Axis.AxisType.Descendant: if ((flags & Flags.SmartDesc) != 0) { result = new DescendantOverDescendantQuery(qyInput, false, root.Name, root.Prefix, root.NodeType, /*abbrAxis:*/false); } else { result = new DescendantQuery(qyInput, root.Name, root.Prefix, root.NodeType, false, /*abbrAxis:*/false); if ((props & Props.NonFlat) != 0) { result = new DocumentOrderQuery(result); } } props |= Props.NonFlat; break; case Axis.AxisType.DescendantOrSelf: if ((flags & Flags.SmartDesc) != 0) { result = new DescendantOverDescendantQuery(qyInput, true, root.Name, root.Prefix, root.NodeType, root.AbbrAxis); } else { result = new DescendantQuery(qyInput, root.Name, root.Prefix, root.NodeType, true, root.AbbrAxis); if ((props & Props.NonFlat) != 0) { result = new DocumentOrderQuery(result); } } props |= Props.NonFlat; break; case Axis.AxisType.Preceding: result = new PrecedingQuery(qyInput, root.Name, root.Prefix, root.NodeType); props |= Props.NonFlat; break; case Axis.AxisType.Following: result = new FollowingQuery(qyInput, root.Name, root.Prefix, root.NodeType); props |= Props.NonFlat; break; case Axis.AxisType.FollowingSibling: result = new FollSiblingQuery(qyInput, root.Name, root.Prefix, root.NodeType); if ((props & Props.NonFlat) != 0) { result = new DocumentOrderQuery(result); } break; case Axis.AxisType.PrecedingSibling: result = new PreSiblingQuery(qyInput, root.Name, root.Prefix, root.NodeType); break; case Axis.AxisType.Attribute: result = new AttributeQuery(qyInput, root.Name, root.Prefix, root.NodeType); break; case Axis.AxisType.Self: result = new XPathSelfQuery(qyInput, root.Name, root.Prefix, root.NodeType); break; case Axis.AxisType.Namespace: if ((root.NodeType == XPathNodeType.All || root.NodeType == XPathNodeType.Element || root.NodeType == XPathNodeType.Attribute) && root.Prefix.Length == 0) { result = new NamespaceQuery(qyInput, root.Name, root.Prefix, root.NodeType); } else { result = new EmptyQuery(); } break; default: throw XPathException.Create(SR.Xp_NotSupported, _query); } return result; } private static bool CanBeNumber(Query q) { return ( q.StaticType == XPathResultType.Any || q.StaticType == XPathResultType.Number ); } private Query ProcessFilter(Filter root, Flags flags, out Props props) { bool first = ((flags & Flags.Filter) == 0); Props propsCond; Query cond = ProcessNode(root.Condition, Flags.None, out propsCond); if ( CanBeNumber(cond) || (propsCond & (Props.HasPosition | Props.HasLast)) != 0 ) { propsCond |= Props.HasPosition; flags |= Flags.PosFilter; } // We don't want DescendantOverDescendant pattern to be recognized here (in case descendent::foo[expr]/descendant::bar) // So we clean this flag here: flags &= ~Flags.SmartDesc; // ToDo: Instead it would be nice to wrap descendent::foo[expr] into special query that will flatten it -- i.e. // remove all nodes that are descendant of other nodes. This is very easy because for sorted nodesets all children // follow its parent. One step caching. This can be easily done by rightmost DescendantQuery itself. // Interesting note! Can we guarantee that DescendantOverDescendant returns flat nodeset? This definitely true if it's input is flat. Query qyInput = ProcessNode(root.Input, flags | Flags.Filter, out props); if (root.Input.Type != AstNode.AstType.Filter) { // Props.PosFilter is for nested filters only. // We clean it here to avoid cleaning it in all other ast nodes. props &= ~Props.PosFilter; } if ((propsCond & Props.HasPosition) != 0) { // this condition is positional rightmost filter should be avare of this. props |= Props.PosFilter; } /*merging predicates*/ { FilterQuery qyFilter = qyInput as FilterQuery; if (qyFilter != null && (propsCond & Props.HasPosition) == 0 && qyFilter.Condition.StaticType != XPathResultType.Any) { Query prevCond = qyFilter.Condition; if (prevCond.StaticType == XPathResultType.Number) { prevCond = new LogicalExpr(Operator.Op.EQ, new NodeFunctions(FT.FuncPosition, null), prevCond); } cond = new BooleanExpr(Operator.Op.AND, prevCond, cond); qyInput = qyFilter.qyInput; } } if ((props & Props.PosFilter) != 0 && qyInput is DocumentOrderQuery) { qyInput = ((DocumentOrderQuery)qyInput).input; } if (_firstInput == null) { _firstInput = qyInput as BaseAxisQuery; } bool merge = (qyInput.Properties & QueryProps.Merge) != 0; bool reverse = (qyInput.Properties & QueryProps.Reverse) != 0; if ((propsCond & Props.HasPosition) != 0) { if (reverse) { qyInput = new ReversePositionQuery(qyInput); } else if ((propsCond & Props.HasLast) != 0) { qyInput = new ForwardPositionQuery(qyInput); } } if (first && _firstInput != null) { if (merge && (props & Props.PosFilter) != 0) { qyInput = new FilterQuery(qyInput, cond, /*noPosition:*/false); Query parent = _firstInput.qyInput; if (!(parent is ContextQuery)) { // we don't need to wrap filter with MergeFilterQuery when cardinality is parent <: ? _firstInput.qyInput = new ContextQuery(); _firstInput = null; return new MergeFilterQuery(parent, qyInput); } _firstInput = null; return qyInput; } _firstInput = null; } return new FilterQuery(qyInput, cond, /*noPosition:*/(propsCond & Props.HasPosition) == 0); } private Query ProcessOperator(Operator root, out Props props) { Props props1, props2; Query op1 = ProcessNode(root.Operand1, Flags.None, out props1); Query op2 = ProcessNode(root.Operand2, Flags.None, out props2); props = props1 | props2; switch (root.OperatorType) { case Operator.Op.PLUS: case Operator.Op.MINUS: case Operator.Op.MUL: case Operator.Op.MOD: case Operator.Op.DIV: return new NumericExpr(root.OperatorType, op1, op2); case Operator.Op.LT: case Operator.Op.GT: case Operator.Op.LE: case Operator.Op.GE: case Operator.Op.EQ: case Operator.Op.NE: return new LogicalExpr(root.OperatorType, op1, op2); case Operator.Op.OR: case Operator.Op.AND: return new BooleanExpr(root.OperatorType, op1, op2); case Operator.Op.UNION: props |= Props.NonFlat; return new UnionExpr(op1, op2); default: return null; } } private Query ProcessVariable(Variable root) { _needContext = true; if (!_allowVar) { throw XPathException.Create(SR.Xp_InvalidKeyPattern, _query); } return new VariableQuery(root.Localname, root.Prefix); } private Query ProcessFunction(Function root, out Props props) { props = Props.None; Query qy = null; switch (root.TypeOfFunction) { case FT.FuncLast: qy = new NodeFunctions(root.TypeOfFunction, null); props |= Props.HasLast; return qy; case FT.FuncPosition: qy = new NodeFunctions(root.TypeOfFunction, null); props |= Props.HasPosition; return qy; case FT.FuncCount: return new NodeFunctions(FT.FuncCount, ProcessNode((AstNode)(root.ArgumentList[0]), Flags.None, out props) ); case FT.FuncID: qy = new IDQuery(ProcessNode((AstNode)(root.ArgumentList[0]), Flags.None, out props)); props |= Props.NonFlat; return qy; case FT.FuncLocalName: case FT.FuncNameSpaceUri: case FT.FuncName: if (root.ArgumentList != null && root.ArgumentList.Count > 0) { return new NodeFunctions(root.TypeOfFunction, ProcessNode((AstNode)(root.ArgumentList[0]), Flags.None, out props) ); } else { return new NodeFunctions(root.TypeOfFunction, null); } case FT.FuncString: case FT.FuncConcat: case FT.FuncStartsWith: case FT.FuncContains: case FT.FuncSubstringBefore: case FT.FuncSubstringAfter: case FT.FuncSubstring: case FT.FuncStringLength: case FT.FuncNormalize: case FT.FuncTranslate: return new StringFunctions(root.TypeOfFunction, ProcessArguments(root.ArgumentList, out props)); case FT.FuncNumber: case FT.FuncSum: case FT.FuncFloor: case FT.FuncCeiling: case FT.FuncRound: if (root.ArgumentList != null && root.ArgumentList.Count > 0) { return new NumberFunctions(root.TypeOfFunction, ProcessNode((AstNode)root.ArgumentList[0], Flags.None, out props) ); } else { return new NumberFunctions(Function.FunctionType.FuncNumber, null); } case FT.FuncTrue: case FT.FuncFalse: return new BooleanFunctions(root.TypeOfFunction, null); case FT.FuncNot: case FT.FuncLang: case FT.FuncBoolean: return new BooleanFunctions(root.TypeOfFunction, ProcessNode((AstNode)root.ArgumentList[0], Flags.None, out props) ); case FT.FuncUserDefined: _needContext = true; if (!_allowCurrent && root.Name == "current" && root.Prefix.Length == 0) { throw XPathException.Create(SR.Xp_CurrentNotAllowed); } if (!_allowKey && root.Name == "key" && root.Prefix.Length == 0) { throw XPathException.Create(SR.Xp_InvalidKeyPattern, _query); } qy = new FunctionQuery(root.Prefix, root.Name, ProcessArguments(root.ArgumentList, out props)); props |= Props.NonFlat; return qy; default: throw XPathException.Create(SR.Xp_NotSupported, _query); } } List<Query> ProcessArguments(List<AstNode> args, out Props props) { int numArgs = args != null ? args.Count : 0; List<Query> argList = new List<Query>(numArgs); props = Props.None; for (int count = 0; count < numArgs; count++) { Props argProps; argList.Add(ProcessNode((AstNode)args[count], Flags.None, out argProps)); props |= argProps; } return argList; } private int _parseDepth = 0; private const int MaxParseDepth = 1024; private Query ProcessNode(AstNode root, Flags flags, out Props props) { if (++_parseDepth > MaxParseDepth) { throw XPathException.Create(SR.Xp_QueryTooComplex); } Debug.Assert(root != null, "root != null"); Query result = null; props = Props.None; switch (root.Type) { case AstNode.AstType.Axis: result = ProcessAxis((Axis)root, flags, out props); break; case AstNode.AstType.Operator: result = ProcessOperator((Operator)root, out props); break; case AstNode.AstType.Filter: result = ProcessFilter((Filter)root, flags, out props); break; case AstNode.AstType.ConstantOperand: result = new OperandQuery(((Operand)root).OperandValue); break; case AstNode.AstType.Variable: result = ProcessVariable((Variable)root); break; case AstNode.AstType.Function: result = ProcessFunction((Function)root, out props); break; case AstNode.AstType.Group: result = new GroupQuery(ProcessNode(((Group)root).GroupNode, Flags.None, out props)); break; case AstNode.AstType.Root: result = new AbsoluteQuery(); break; default: Debug.Fail("Unknown QueryType encountered!!"); break; } --_parseDepth; return result; } private Query Build(AstNode root, string query) { Reset(); Props props; _query = query; Query result = ProcessNode(root, Flags.None, out props); return result; } internal Query Build(string query, bool allowVar, bool allowKey) { _allowVar = allowVar; _allowKey = allowKey; _allowCurrent = true; return Build(XPathParser.ParseXPathExpression(query), query); } internal Query Build(string query, out bool needContext) { Query result = Build(query, true, true); needContext = _needContext; return result; } internal Query BuildPatternQuery(string query, bool allowVar, bool allowKey) { _allowVar = allowVar; _allowKey = allowKey; _allowCurrent = false; return Build(XPathParser.ParseXPathPattern(query), query); } internal Query BuildPatternQuery(string query, out bool needContext) { Query result = BuildPatternQuery(query, true, true); needContext = _needContext; return result; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.AzureStack.Management; using Microsoft.AzureStack.Management.Models; using Newtonsoft.Json.Linq; namespace Microsoft.AzureStack.Management { /// <summary> /// Operations on the offer (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXX.aspx for /// more information) /// </summary> internal partial class OfferOperations : IServiceOperations<AzureStackClient>, IOfferOperations { /// <summary> /// Initializes a new instance of the OfferOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal OfferOperations(AzureStackClient client) { this._client = client; } private AzureStackClient _client; /// <summary> /// Gets a reference to the /// Microsoft.AzureStack.Management.AzureStackClient. /// </summary> public AzureStackClient Client { get { return this._client; } } /// <summary> /// Gets an offer given its Id. /// </summary> /// <param name='offerId'> /// Required. The full offer Id in format /// /delegatedProviders/{providerId}/offers/{offerName} /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The offer get result. /// </returns> public async Task<OfferGetResult> GetAsync(string offerId, CancellationToken cancellationToken) { // Validate if (offerId == null) { throw new ArgumentNullException("offerId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("offerId", offerId); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + Uri.EscapeDataString(offerId); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result OfferGetResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new OfferGetResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { OfferDefinition offerInstance = new OfferDefinition(); result.Offer = offerInstance; JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); offerInstance.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); offerInstance.Name = nameInstance; } JToken displayNameValue = responseDoc["displayName"]; if (displayNameValue != null && displayNameValue.Type != JTokenType.Null) { string displayNameInstance = ((string)displayNameValue); offerInstance.DisplayName = displayNameInstance; } JToken descriptionValue = responseDoc["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); offerInstance.Description = descriptionInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the price of the offer. /// </summary> /// <param name='offerId'> /// Required. the full offer ID /// /delegatedProviders/{providerId}/offers/{offerId}. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Offer price result. /// </returns> public async Task<OfferGetPriceResult> GetPriceAsync(string offerId, CancellationToken cancellationToken) { // Validate if (offerId == null) { throw new ArgumentNullException("offerId"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("offerId", offerId); TracingAdapter.Enter(invocationId, this, "GetPriceAsync", tracingParameters); } // Construct URL string url = ""; url = url + Uri.EscapeDataString(offerId); url = url + "/estimatePrice"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result OfferGetPriceResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new OfferGetPriceResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { PriceDefinition priceInstance = new PriceDefinition(); result.Price = priceInstance; JToken amountValue = responseDoc["amount"]; if (amountValue != null && amountValue.Type != JTokenType.Null) { decimal amountInstance = ((decimal)amountValue); priceInstance.Amount = amountInstance; } JToken currencyCodeValue = responseDoc["currencyCode"]; if (currencyCodeValue != null && currencyCodeValue.Type != JTokenType.Null) { string currencyCodeInstance = ((string)currencyCodeValue); priceInstance.CurrencyCode = currencyCodeInstance; } JToken captionValue = responseDoc["caption"]; if (captionValue != null && captionValue.Type != JTokenType.Null) { string captionInstance = ((string)captionValue); priceInstance.Caption = captionInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the public offers under the provider which has the given /// provider identifier /// </summary> /// <param name='providerIdentifier'> /// Required. The provider identifier, we get the public offers under /// that provider. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Result of the offer /// </returns> public async Task<OfferListResult> ListAsync(string providerIdentifier, CancellationToken cancellationToken) { // Validate if (providerIdentifier == null) { throw new ArgumentNullException("providerIdentifier"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("providerIdentifier", providerIdentifier); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/delegatedProviders/"; url = url + Uri.EscapeDataString(providerIdentifier); url = url + "/offers"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result OfferListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new OfferListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { OfferDefinition offerDefinitionInstance = new OfferDefinition(); result.Offers.Add(offerDefinitionInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); offerDefinitionInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); offerDefinitionInstance.Name = nameInstance; } JToken displayNameValue = valueValue["displayName"]; if (displayNameValue != null && displayNameValue.Type != JTokenType.Null) { string displayNameInstance = ((string)displayNameValue); offerDefinitionInstance.DisplayName = displayNameInstance; } JToken descriptionValue = valueValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); offerDefinitionInstance.Description = descriptionInstance; } } } JToken odatanextLinkValue = responseDoc["@odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = ((string)odatanextLinkValue); result.NextLink = odatanextLinkInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Lists the offer with the next link /// </summary> /// <param name='nextLink'> /// Required. The URL to get the next set of offers /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Result of the offer /// </returns> public async Task<OfferListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken) { // Validate if (nextLink == null) { throw new ArgumentNullException("nextLink"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextLink", nextLink); TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters); } // Construct URL string url = ""; url = url + Uri.EscapeDataString(nextLink); url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result OfferListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new OfferListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { OfferDefinition offerDefinitionInstance = new OfferDefinition(); result.Offers.Add(offerDefinitionInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); offerDefinitionInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); offerDefinitionInstance.Name = nameInstance; } JToken displayNameValue = valueValue["displayName"]; if (displayNameValue != null && displayNameValue.Type != JTokenType.Null) { string displayNameInstance = ((string)displayNameValue); offerDefinitionInstance.DisplayName = displayNameInstance; } JToken descriptionValue = valueValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); offerDefinitionInstance.Description = descriptionInstance; } } } JToken odatanextLinkValue = responseDoc["@odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = ((string)odatanextLinkValue); result.NextLink = odatanextLinkInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the public offers under the zero day (root) provider /// </summary> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Result of the offer /// </returns> public async Task<OfferListResult> ListUnderRootProviderAsync(CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); TracingAdapter.Enter(invocationId, this, "ListUnderRootProviderAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/offers"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=" + Uri.EscapeDataString(this.Client.ApiVersion)); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result OfferListResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new OfferListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { OfferDefinition offerDefinitionInstance = new OfferDefinition(); result.Offers.Add(offerDefinitionInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); offerDefinitionInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); offerDefinitionInstance.Name = nameInstance; } JToken displayNameValue = valueValue["displayName"]; if (displayNameValue != null && displayNameValue.Type != JTokenType.Null) { string displayNameInstance = ((string)displayNameValue); offerDefinitionInstance.DisplayName = displayNameInstance; } JToken descriptionValue = valueValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); offerDefinitionInstance.Description = descriptionInstance; } } } JToken odatanextLinkValue = responseDoc["@odata.nextLink"]; if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null) { string odatanextLinkInstance = ((string)odatanextLinkValue); result.NextLink = odatanextLinkInstance; } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Enyim.Caching.Memcached.Results; using Enyim.Caching.Memcached.Results.Extensions; namespace Enyim.Caching.Memcached.Protocol.Binary { public class MultiGetOperation : BinaryMultiItemOperation, IMultiGetOperation { private static readonly Enyim.Caching.ILog log = Enyim.Caching.LogManager.GetLogger(typeof(MultiGetOperation)); private Dictionary<string, CacheItem> result; private Dictionary<int, string> idToKey; private int noopId; public MultiGetOperation(IList<string> keys) : base(keys) { } protected override BinaryRequest Build(string key) { var request = new BinaryRequest(OpCode.GetQ) { Key = key }; return request; } protected internal override IList<ArraySegment<byte>> GetBuffer() { var keys = this.Keys; if (keys == null || keys.Count == 0) { if (log.IsWarnEnabled) log.Warn("Empty multiget!"); return new ArraySegment<byte>[0]; } if (log.IsDebugEnabled) log.DebugFormat("Building multi-get for {0} keys", keys.Count); // map the command's correlationId to the item key, // so we can use GetQ (which only returns the item data) this.idToKey = new Dictionary<int, string>(); // get ops have 2 segments, header + key var buffers = new List<ArraySegment<byte>>(keys.Count * 2); foreach (var key in keys) { var request = this.Build(key); request.CreateBuffer(buffers); // we use this to map the responses to the keys idToKey[request.CorrelationId] = key; } // uncork the server var noop = new BinaryRequest(OpCode.NoOp); this.noopId = noop.CorrelationId; noop.CreateBuffer(buffers); return buffers; } private PooledSocket currentSocket; private BinaryResponse asyncReader; private bool? asyncLoopState; private Action<bool> afterAsyncRead; protected internal override System.Threading.Tasks.Task<IOperationResult> ReadResponseAsync(PooledSocket socket) { throw new NotImplementedException(); } protected internal override bool ReadResponseAsync(PooledSocket socket, Action<bool> next) { this.result = new Dictionary<string, CacheItem>(); this.Cas = new Dictionary<string, ulong>(); this.currentSocket = socket; this.asyncReader = new BinaryResponse(); this.asyncLoopState = null; this.afterAsyncRead = next; return this.DoReadAsync(); } private bool DoReadAsync() { bool ioPending; var reader = this.asyncReader; while (this.asyncLoopState == null) { var readSuccess = reader.ReadAsync(this.currentSocket, this.EndReadAsync, out ioPending); this.StatusCode = reader.StatusCode; if (ioPending) return readSuccess; if (!readSuccess) this.asyncLoopState = false; else if (reader.CorrelationId == this.noopId) this.asyncLoopState = true; else this.StoreResult(reader); } this.afterAsyncRead((bool)this.asyncLoopState); return true; } private void EndReadAsync(bool readSuccess) { if (!readSuccess) this.asyncLoopState = false; else if (this.asyncReader.CorrelationId == this.noopId) this.asyncLoopState = true; else StoreResult(this.asyncReader); this.DoReadAsync(); } private void StoreResult(BinaryResponse reader) { string key; // find the key to the response if (!this.idToKey.TryGetValue(reader.CorrelationId, out key)) { // we're not supposed to get here tho log.WarnFormat("Found response with CorrelationId {0}, but no key is matching it.", reader.CorrelationId); } else { if (log.IsDebugEnabled) log.DebugFormat("Reading item {0}", key); // deserialize the response var flags = (ushort)BinaryConverter.DecodeInt32(reader.Extra, 0); this.result[key] = new CacheItem(flags, reader.Data); this.Cas[key] = reader.CAS; } } protected internal override IOperationResult ReadResponse(PooledSocket socket) { this.result = new Dictionary<string, CacheItem>(); this.Cas = new Dictionary<string, ulong>(); var result = new TextOperationResult(); var response = new BinaryResponse(); while (response.Read(socket)) { this.StatusCode = response.StatusCode; // found the noop, quit if (response.CorrelationId == this.noopId) return result.Pass(); string key; // find the key to the response if (!this.idToKey.TryGetValue(response.CorrelationId, out key)) { // we're not supposed to get here tho log.WarnFormat("Found response with CorrelationId {0}, but no key is matching it.", response.CorrelationId); continue; } if (log.IsDebugEnabled) log.DebugFormat("Reading item {0}", key); // deserialize the response int flags = BinaryConverter.DecodeInt32(response.Extra, 0); this.result[key] = new CacheItem((ushort)flags, response.Data); this.Cas[key] = response.CAS; } // finished reading but we did not find the NOOP return result.Fail("Found response with CorrelationId {0}, but no key is matching it."); } public Dictionary<string, CacheItem> Result { get { return this.result; } } Dictionary<string, CacheItem> IMultiGetOperation.Result { get { return this.result; } } } } #region [ License information ] /* ************************************************************ * * Copyright (c) 2010 Attila Kisk? enyim.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ************************************************************/ #endregion
// 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.Composition; using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.Suppression { [ExportSuppressionFixProvider(PredefinedCodeFixProviderNames.Suppression, LanguageNames.CSharp), Shared] internal class CSharpSuppressionCodeFixProvider : AbstractSuppressionCodeFixProvider { protected override Task<SyntaxTriviaList> CreatePragmaRestoreDirectiveTriviaAsync(Diagnostic diagnostic, Func<SyntaxNode, Task<SyntaxNode>> formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine) { var restoreKeyword = SyntaxFactory.Token(SyntaxKind.RestoreKeyword); return CreatePragmaDirectiveTriviaAsync(restoreKeyword, diagnostic, formatNode, needsLeadingEndOfLine, needsTrailingEndOfLine); } protected override Task<SyntaxTriviaList> CreatePragmaDisableDirectiveTriviaAsync( Diagnostic diagnostic, Func<SyntaxNode, Task<SyntaxNode>> formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine) { var disableKeyword = SyntaxFactory.Token(SyntaxKind.DisableKeyword); return CreatePragmaDirectiveTriviaAsync(disableKeyword, diagnostic, formatNode, needsLeadingEndOfLine, needsTrailingEndOfLine); } private async Task<SyntaxTriviaList> CreatePragmaDirectiveTriviaAsync( SyntaxToken disableOrRestoreKeyword, Diagnostic diagnostic, Func<SyntaxNode, Task<SyntaxNode>> formatNode, bool needsLeadingEndOfLine, bool needsTrailingEndOfLine) { var id = SyntaxFactory.IdentifierName(diagnostic.Id); var ids = new SeparatedSyntaxList<ExpressionSyntax>().Add(id); var pragmaDirective = SyntaxFactory.PragmaWarningDirectiveTrivia(disableOrRestoreKeyword, ids, true); pragmaDirective = (PragmaWarningDirectiveTriviaSyntax)await formatNode(pragmaDirective).ConfigureAwait(false); var pragmaDirectiveTrivia = SyntaxFactory.Trivia(pragmaDirective); var endOfLineTrivia = SyntaxFactory.ElasticCarriageReturnLineFeed; var triviaList = SyntaxFactory.TriviaList(pragmaDirectiveTrivia); var title = diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture); if (!string.IsNullOrWhiteSpace(title)) { var titleComment = SyntaxFactory.Comment(string.Format(" // {0}", title)).WithAdditionalAnnotations(Formatter.Annotation); triviaList = triviaList.Add(titleComment); } if (needsLeadingEndOfLine) { triviaList = triviaList.Insert(0, endOfLineTrivia); } if (needsTrailingEndOfLine) { triviaList = triviaList.Add(endOfLineTrivia); } return triviaList; } protected override string DefaultFileExtension { get { return ".cs"; } } protected override string SingleLineCommentStart { get { return "//"; } } protected override bool IsAttributeListWithAssemblyAttributes(SyntaxNode node) { var attributeList = node as AttributeListSyntax; return attributeList != null && attributeList.Target != null && attributeList.Target.Identifier.Kind() == SyntaxKind.AssemblyKeyword; } protected override bool IsEndOfLine(SyntaxTrivia trivia) { return trivia.Kind() == SyntaxKind.EndOfLineTrivia; } protected override bool IsEndOfFileToken(SyntaxToken token) { return token.Kind() == SyntaxKind.EndOfFileToken; } protected override async Task<SyntaxNode> AddGlobalSuppressMessageAttributeAsync(SyntaxNode newRoot, ISymbol targetSymbol, Diagnostic diagnostic, Workspace workspace, CancellationToken cancellationToken) { var compilationRoot = (CompilationUnitSyntax)newRoot; var isFirst = !compilationRoot.AttributeLists.Any(); var leadingTriviaForAttributeList = isFirst && !compilationRoot.HasLeadingTrivia ? SyntaxFactory.TriviaList(SyntaxFactory.Comment(GlobalSuppressionsFileHeaderComment)) : default(SyntaxTriviaList); var attributeList = CreateAttributeList(targetSymbol, diagnostic, leadingTrivia: leadingTriviaForAttributeList, needsLeadingEndOfLine: !isFirst); attributeList = (AttributeListSyntax)await Formatter.FormatAsync(attributeList, workspace, cancellationToken: cancellationToken).ConfigureAwait(false); return compilationRoot.AddAttributeLists(attributeList); } private AttributeListSyntax CreateAttributeList( ISymbol targetSymbol, Diagnostic diagnostic, SyntaxTriviaList leadingTrivia, bool needsLeadingEndOfLine) { var attributeArguments = CreateAttributeArguments(targetSymbol, diagnostic); var attribute = SyntaxFactory.Attribute(SyntaxFactory.ParseName(SuppressMessageAttributeName), attributeArguments); var attributes = new SeparatedSyntaxList<AttributeSyntax>().Add(attribute); var targetSpecifier = SyntaxFactory.AttributeTargetSpecifier(SyntaxFactory.Token(SyntaxKind.AssemblyKeyword)); var attributeList = SyntaxFactory.AttributeList(targetSpecifier, attributes); var endOfLineTrivia = SyntaxFactory.ElasticCarriageReturnLineFeed; var triviaList = SyntaxFactory.TriviaList(); if (needsLeadingEndOfLine) { triviaList = triviaList.Add(endOfLineTrivia); } return attributeList.WithLeadingTrivia(leadingTrivia.AddRange(triviaList)); } private AttributeArgumentListSyntax CreateAttributeArguments(ISymbol targetSymbol, Diagnostic diagnostic) { // SuppressMessage("Rule Category", "Rule Id", Justification = nameof(Justification), Scope = nameof(Scope), Target = nameof(Target)) var category = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(diagnostic.Descriptor.Category)); var categoryArgument = SyntaxFactory.AttributeArgument(category); var title = diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture); var ruleIdText = string.IsNullOrWhiteSpace(title) ? diagnostic.Id : string.Format("{0}:{1}", diagnostic.Id, title); var ruleId = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(ruleIdText)); var ruleIdArgument = SyntaxFactory.AttributeArgument(ruleId); var justificationExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(FeaturesResources.Pending)); var justificationArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Justification"), nameColon: null, expression: justificationExpr); var attributeArgumentList = SyntaxFactory.AttributeArgumentList().AddArguments(categoryArgument, ruleIdArgument, justificationArgument); var scopeString = GetScopeString(targetSymbol.Kind); if (scopeString != null) { var scopeExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(scopeString)); var scopeArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Scope"), nameColon: null, expression: scopeExpr); var targetString = GetTargetString(targetSymbol); var targetExpr = SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(targetString)); var targetArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals("Target"), nameColon: null, expression: targetExpr); attributeArgumentList = attributeArgumentList.AddArguments(scopeArgument, targetArgument); } return attributeArgumentList; } protected override bool IsSingleAttributeInAttributeList(SyntaxNode attribute) { var attributeSyntax = attribute as AttributeSyntax; if (attributeSyntax != null) { var attributeList = attributeSyntax.Parent as AttributeListSyntax; return attributeList != null && attributeList.Attributes.Count == 1; } return false; } protected override bool IsAnyPragmaDirectiveForId(SyntaxTrivia trivia, string id, out bool enableDirective, out bool hasMultipleIds) { if (trivia.Kind() == SyntaxKind.PragmaWarningDirectiveTrivia) { var pragmaWarning = (PragmaWarningDirectiveTriviaSyntax)trivia.GetStructure(); enableDirective = pragmaWarning.DisableOrRestoreKeyword.Kind() == SyntaxKind.RestoreKeyword; hasMultipleIds = pragmaWarning.ErrorCodes.Count > 1; return pragmaWarning.ErrorCodes.Any(n => n.ToString() == id); } enableDirective = false; hasMultipleIds = false; return false; } protected override SyntaxTrivia TogglePragmaDirective(SyntaxTrivia trivia) { var pragmaWarning = (PragmaWarningDirectiveTriviaSyntax)trivia.GetStructure(); var currentKeyword = pragmaWarning.DisableOrRestoreKeyword; var toggledKeywordKind = currentKeyword.Kind() == SyntaxKind.DisableKeyword ? SyntaxKind.RestoreKeyword : SyntaxKind.DisableKeyword; var toggledToken = SyntaxFactory.Token(currentKeyword.LeadingTrivia, toggledKeywordKind, currentKeyword.TrailingTrivia); var newPragmaWarning = pragmaWarning.WithDisableOrRestoreKeyword(toggledToken); return SyntaxFactory.Trivia(newPragmaWarning); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace System.Runtime.Serialization { using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Threading; using System.Xml; using System.Linq; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; using System.Security; // The interface is a perf optimization. // Only KeyValuePairAdapter should implement the interface. internal interface IKeyValuePairAdapter { } //Special Adapter class to serialize KeyValuePair as Dictionary needs it when polymorphism is involved [DataContract(Namespace = "http://schemas.datacontract.org/2004/07/System.Collections.Generic")] internal class KeyValuePairAdapter<K, T> : IKeyValuePairAdapter { private K _kvpKey; private T _kvpValue; public KeyValuePairAdapter(KeyValuePair<K, T> kvPair) { _kvpKey = kvPair.Key; _kvpValue = kvPair.Value; } [DataMember(Name = "key")] public K Key { get { return _kvpKey; } set { _kvpKey = value; } } [DataMember(Name = "value")] public T Value { get { return _kvpValue; } set { _kvpValue = value; } } internal KeyValuePair<K, T> GetKeyValuePair() { return new KeyValuePair<K, T>(_kvpKey, _kvpValue); } internal static KeyValuePairAdapter<K, T> GetKeyValuePairAdapter(KeyValuePair<K, T> kvPair) { return new KeyValuePairAdapter<K, T>(kvPair); } } #if USE_REFEMIT public interface IKeyValue #else internal interface IKeyValue #endif { object Key { get; set; } object Value { get; set; } } [DataContract(Namespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays")] #if USE_REFEMIT public struct KeyValue<K, V> : IKeyValue #else internal struct KeyValue<K, V> : IKeyValue #endif { private K _key; private V _value; internal KeyValue(K key, V value) { _key = key; _value = value; } [DataMember(IsRequired = true)] public K Key { get { return _key; } set { _key = value; } } [DataMember(IsRequired = true)] public V Value { get { return _value; } set { _value = value; } } object IKeyValue.Key { get { return _key; } set { _key = (K)value; } } object IKeyValue.Value { get { return _value; } set { _value = (V)value; } } } #if NET_NATIVE public enum CollectionKind : byte #else internal enum CollectionKind : byte #endif { None, GenericDictionary, Dictionary, GenericList, GenericCollection, List, GenericEnumerable, Collection, Enumerable, Array, } #if USE_REFEMIT || NET_NATIVE public sealed class CollectionDataContract : DataContract #else internal sealed class CollectionDataContract : DataContract #endif { private XmlDictionaryString _collectionItemName; private XmlDictionaryString _childElementNamespace; private DataContract _itemContract; private CollectionDataContractCriticalHelper _helper; public CollectionDataContract(CollectionKind kind) : base(new CollectionDataContractCriticalHelper(kind)) { InitCollectionDataContract(this); } internal CollectionDataContract(Type type) : base(new CollectionDataContractCriticalHelper(type)) { InitCollectionDataContract(this); } private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor) : base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor)) { InitCollectionDataContract(GetSharedTypeContract(type)); } private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor, bool isConstructorCheckRequired) : base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor, isConstructorCheckRequired)) { InitCollectionDataContract(GetSharedTypeContract(type)); } private CollectionDataContract(Type type, string invalidCollectionInSharedContractMessage) : base(new CollectionDataContractCriticalHelper(type, invalidCollectionInSharedContractMessage)) { InitCollectionDataContract(GetSharedTypeContract(type)); } private void InitCollectionDataContract(DataContract sharedTypeContract) { _helper = base.Helper as CollectionDataContractCriticalHelper; _collectionItemName = _helper.CollectionItemName; if (_helper.Kind == CollectionKind.Dictionary || _helper.Kind == CollectionKind.GenericDictionary) { _itemContract = _helper.ItemContract; } _helper.SharedTypeContract = sharedTypeContract; } private static Type[] KnownInterfaces { get { return CollectionDataContractCriticalHelper.KnownInterfaces; } } internal CollectionKind Kind { get { return _helper.Kind; } } public Type ItemType { get { return _helper.ItemType; } set { _helper.ItemType = value; } } public DataContract ItemContract { get { return _itemContract ?? _helper.ItemContract; } set { _itemContract = value; _helper.ItemContract = value; } } internal DataContract SharedTypeContract { get { return _helper.SharedTypeContract; } } public string ItemName { get { return _helper.ItemName; } set { _helper.ItemName = value; } } public XmlDictionaryString CollectionItemName { get { return _collectionItemName; } set { _collectionItemName = value; } } public string KeyName { get { return _helper.KeyName; } set { _helper.KeyName = value; } } public string ValueName { get { return _helper.ValueName; } set { _helper.ValueName = value; } } internal bool IsDictionary { get { return KeyName != null; } } public XmlDictionaryString ChildElementNamespace { get { if (_childElementNamespace == null) { lock (this) { if (_childElementNamespace == null) { if (_helper.ChildElementNamespace == null && !IsDictionary) { XmlDictionaryString tempChildElementNamespace = ClassDataContract.GetChildNamespaceToDeclare(this, ItemType, new XmlDictionary()); Interlocked.MemoryBarrier(); _helper.ChildElementNamespace = tempChildElementNamespace; } _childElementNamespace = _helper.ChildElementNamespace; } } } return _childElementNamespace; } } internal bool IsConstructorCheckRequired { get { return _helper.IsConstructorCheckRequired; } set { _helper.IsConstructorCheckRequired = value; } } internal MethodInfo GetEnumeratorMethod { get { return _helper.GetEnumeratorMethod; } } internal MethodInfo AddMethod { get { return _helper.AddMethod; } } internal ConstructorInfo Constructor { get { return _helper.Constructor; } } public override DataContractDictionary KnownDataContracts { get { return _helper.KnownDataContracts; } set { _helper.KnownDataContracts = value; } } internal string InvalidCollectionInSharedContractMessage { get { return _helper.InvalidCollectionInSharedContractMessage; } } #if NET_NATIVE private XmlFormatCollectionWriterDelegate _xmlFormatWriterDelegate; public XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate #else internal XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate #endif { get { #if NET_NATIVE if (DataContractSerializer.Option == SerializationOption.CodeGenOnly || (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup && _xmlFormatWriterDelegate != null)) { return _xmlFormatWriterDelegate; } #endif if (_helper.XmlFormatWriterDelegate == null) { lock (this) { if (_helper.XmlFormatWriterDelegate == null) { XmlFormatCollectionWriterDelegate tempDelegate = new XmlFormatWriterGenerator().GenerateCollectionWriter(this); Interlocked.MemoryBarrier(); _helper.XmlFormatWriterDelegate = tempDelegate; } } } return _helper.XmlFormatWriterDelegate; } set { #if NET_NATIVE _xmlFormatWriterDelegate = value; #endif } } #if NET_NATIVE private XmlFormatCollectionReaderDelegate _xmlFormatReaderDelegate; public XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate #else internal XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate #endif { get { #if NET_NATIVE if (DataContractSerializer.Option == SerializationOption.CodeGenOnly || (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup && _xmlFormatReaderDelegate != null)) { return _xmlFormatReaderDelegate; } #endif if (_helper.XmlFormatReaderDelegate == null) { lock (this) { if (_helper.XmlFormatReaderDelegate == null) { XmlFormatCollectionReaderDelegate tempDelegate = new XmlFormatReaderGenerator().GenerateCollectionReader(this); Interlocked.MemoryBarrier(); _helper.XmlFormatReaderDelegate = tempDelegate; } } } return _helper.XmlFormatReaderDelegate; } set { #if NET_NATIVE _xmlFormatReaderDelegate = value; #endif } } #if NET_NATIVE private XmlFormatGetOnlyCollectionReaderDelegate _xmlFormatGetOnlyCollectionReaderDelegate; public XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate #else internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate #endif { get { #if NET_NATIVE if (DataContractSerializer.Option == SerializationOption.CodeGenOnly || (DataContractSerializer.Option == SerializationOption.ReflectionAsBackup && _xmlFormatGetOnlyCollectionReaderDelegate != null)) { return _xmlFormatGetOnlyCollectionReaderDelegate; } #endif if (_helper.XmlFormatGetOnlyCollectionReaderDelegate == null) { lock (this) { if (_helper.XmlFormatGetOnlyCollectionReaderDelegate == null) { if (UnderlyingType.IsInterface && (Kind == CollectionKind.Enumerable || Kind == CollectionKind.Collection || Kind == CollectionKind.GenericEnumerable)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.GetOnlyCollectionMustHaveAddMethod, GetClrTypeFullName(UnderlyingType)))); } Debug.Assert(AddMethod != null || Kind == CollectionKind.Array, "Add method cannot be null if the collection is being used as a get-only property"); XmlFormatGetOnlyCollectionReaderDelegate tempDelegate = new XmlFormatReaderGenerator().GenerateGetOnlyCollectionReader(this); Interlocked.MemoryBarrier(); _helper.XmlFormatGetOnlyCollectionReaderDelegate = tempDelegate; } } } return _helper.XmlFormatGetOnlyCollectionReaderDelegate; } set { #if NET_NATIVE _xmlFormatGetOnlyCollectionReaderDelegate = value; #endif } } internal void IncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { _helper.IncrementCollectionCount(xmlWriter, obj, context); } internal IEnumerator GetEnumeratorForCollection(object obj, out Type enumeratorReturnType) { return _helper.GetEnumeratorForCollection(obj, out enumeratorReturnType); } private class CollectionDataContractCriticalHelper : DataContract.DataContractCriticalHelper { private static Type[] s_knownInterfaces; private Type _itemType; private CollectionKind _kind; private readonly MethodInfo _getEnumeratorMethod, _addMethod; private readonly ConstructorInfo _constructor; private DataContract _itemContract; private DataContract _sharedTypeContract; private DataContractDictionary _knownDataContracts; private bool _isKnownTypeAttributeChecked; private string _itemName; private bool _itemNameSetExplicit; private XmlDictionaryString _collectionItemName; private string _keyName; private string _valueName; private XmlDictionaryString _childElementNamespace; private string _invalidCollectionInSharedContractMessage; private XmlFormatCollectionReaderDelegate _xmlFormatReaderDelegate; private XmlFormatGetOnlyCollectionReaderDelegate _xmlFormatGetOnlyCollectionReaderDelegate; private XmlFormatCollectionWriterDelegate _xmlFormatWriterDelegate; private bool _isConstructorCheckRequired = false; internal static Type[] KnownInterfaces { get { if (s_knownInterfaces == null) { // Listed in priority order s_knownInterfaces = new Type[] { Globals.TypeOfIDictionaryGeneric, Globals.TypeOfIDictionary, Globals.TypeOfIListGeneric, Globals.TypeOfICollectionGeneric, Globals.TypeOfIList, Globals.TypeOfIEnumerableGeneric, Globals.TypeOfICollection, Globals.TypeOfIEnumerable }; } return s_knownInterfaces; } } private void Init(CollectionKind kind, Type itemType, CollectionDataContractAttribute collectionContractAttribute) { _kind = kind; if (itemType != null) { _itemType = itemType; bool isDictionary = (kind == CollectionKind.Dictionary || kind == CollectionKind.GenericDictionary); string itemName = null, keyName = null, valueName = null; if (collectionContractAttribute != null) { if (collectionContractAttribute.IsItemNameSetExplicitly) { if (collectionContractAttribute.ItemName == null || collectionContractAttribute.ItemName.Length == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractItemName, DataContract.GetClrTypeFullName(UnderlyingType)))); itemName = DataContract.EncodeLocalName(collectionContractAttribute.ItemName); _itemNameSetExplicit = true; } if (collectionContractAttribute.IsKeyNameSetExplicitly) { if (collectionContractAttribute.KeyName == null || collectionContractAttribute.KeyName.Length == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractKeyName, DataContract.GetClrTypeFullName(UnderlyingType)))); if (!isDictionary) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractKeyNoDictionary, DataContract.GetClrTypeFullName(UnderlyingType), collectionContractAttribute.KeyName))); keyName = DataContract.EncodeLocalName(collectionContractAttribute.KeyName); } if (collectionContractAttribute.IsValueNameSetExplicitly) { if (collectionContractAttribute.ValueName == null || collectionContractAttribute.ValueName.Length == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractValueName, DataContract.GetClrTypeFullName(UnderlyingType)))); if (!isDictionary) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidCollectionContractValueNoDictionary, DataContract.GetClrTypeFullName(UnderlyingType), collectionContractAttribute.ValueName))); valueName = DataContract.EncodeLocalName(collectionContractAttribute.ValueName); } } XmlDictionary dictionary = isDictionary ? new XmlDictionary(5) : new XmlDictionary(3); this.Name = dictionary.Add(this.StableName.Name); this.Namespace = dictionary.Add(this.StableName.Namespace); _itemName = itemName ?? DataContract.GetStableName(DataContract.UnwrapNullableType(itemType)).Name; _collectionItemName = dictionary.Add(_itemName); if (isDictionary) { _keyName = keyName ?? Globals.KeyLocalName; _valueName = valueName ?? Globals.ValueLocalName; } } if (collectionContractAttribute != null) { this.IsReference = collectionContractAttribute.IsReference; } } internal CollectionDataContractCriticalHelper(CollectionKind kind) : base() { Init(kind, null, null); } // array internal CollectionDataContractCriticalHelper(Type type) : base(type) { if (type == Globals.TypeOfArray) type = Globals.TypeOfObjectArray; if (type.GetArrayRank() > 1) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SupportForMultidimensionalArraysNotPresent))); this.StableName = DataContract.GetStableName(type); Init(CollectionKind.Array, type.GetElementType(), null); } // collection internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor) : base(type) { if (getEnumeratorMethod == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveGetEnumeratorMethod, DataContract.GetClrTypeFullName(type)))); if (addMethod == null && !type.IsInterface) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveAddMethod, DataContract.GetClrTypeFullName(type)))); if (itemType == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveItemType, DataContract.GetClrTypeFullName(type)))); CollectionDataContractAttribute collectionContractAttribute; this.StableName = DataContract.GetCollectionStableName(type, itemType, out collectionContractAttribute); Init(kind, itemType, collectionContractAttribute); _getEnumeratorMethod = getEnumeratorMethod; _addMethod = addMethod; _constructor = constructor; } // collection internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor, bool isConstructorCheckRequired) : this(type, kind, itemType, getEnumeratorMethod, addMethod, constructor) { _isConstructorCheckRequired = isConstructorCheckRequired; } internal CollectionDataContractCriticalHelper(Type type, string invalidCollectionInSharedContractMessage) : base(type) { Init(CollectionKind.Collection, null /*itemType*/, null); _invalidCollectionInSharedContractMessage = invalidCollectionInSharedContractMessage; } internal CollectionKind Kind { get { return _kind; } } internal Type ItemType { get { return _itemType; } set { _itemType = value; } } internal DataContract ItemContract { get { if (_itemContract == null && UnderlyingType != null) { if (IsDictionary) { if (String.CompareOrdinal(KeyName, ValueName) == 0) { DataContract.ThrowInvalidDataContractException( SR.Format(SR.DupKeyValueName, DataContract.GetClrTypeFullName(UnderlyingType), KeyName), UnderlyingType); } _itemContract = ClassDataContract.CreateClassDataContractForKeyValue(ItemType, Namespace, new string[] { KeyName, ValueName }); // Ensure that DataContract gets added to the static DataContract cache for dictionary items DataContract.GetDataContract(ItemType); } else { _itemContract = DataContract.GetDataContractFromGeneratedAssembly(ItemType); if (_itemContract == null) { _itemContract = DataContract.GetDataContract(ItemType); } } } return _itemContract; } set { _itemContract = value; } } internal DataContract SharedTypeContract { get { return _sharedTypeContract; } set { _sharedTypeContract = value; } } internal string ItemName { get { return _itemName; } set { _itemName = value; } } internal bool IsConstructorCheckRequired { get { return _isConstructorCheckRequired; } set { _isConstructorCheckRequired = value; } } public XmlDictionaryString CollectionItemName { get { return _collectionItemName; } } internal string KeyName { get { return _keyName; } set { _keyName = value; } } internal string ValueName { get { return _valueName; } set { _valueName = value; } } internal bool IsDictionary => KeyName != null; public XmlDictionaryString ChildElementNamespace { get { return _childElementNamespace; } set { _childElementNamespace = value; } } internal MethodInfo GetEnumeratorMethod => _getEnumeratorMethod; internal MethodInfo AddMethod => _addMethod; internal ConstructorInfo Constructor => _constructor; internal override DataContractDictionary KnownDataContracts { get { if (!_isKnownTypeAttributeChecked && UnderlyingType != null) { lock (this) { if (!_isKnownTypeAttributeChecked) { _knownDataContracts = DataContract.ImportKnownTypeAttributes(this.UnderlyingType); Interlocked.MemoryBarrier(); _isKnownTypeAttributeChecked = true; } } } return _knownDataContracts; } set { _knownDataContracts = value; } } internal string InvalidCollectionInSharedContractMessage => _invalidCollectionInSharedContractMessage; internal bool ItemNameSetExplicit => _itemNameSetExplicit; internal XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate { get { return _xmlFormatWriterDelegate; } set { _xmlFormatWriterDelegate = value; } } internal XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate { get { return _xmlFormatReaderDelegate; } set { _xmlFormatReaderDelegate = value; } } internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate { get { return _xmlFormatGetOnlyCollectionReaderDelegate; } set { _xmlFormatGetOnlyCollectionReaderDelegate = value; } } private delegate void IncrementCollectionCountDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context); private IncrementCollectionCountDelegate _incrementCollectionCountDelegate = null; private static void DummyIncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { } internal void IncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { if (_incrementCollectionCountDelegate == null) { switch (Kind) { case CollectionKind.Collection: case CollectionKind.List: case CollectionKind.Dictionary: { _incrementCollectionCountDelegate = (x, o, c) => { context.IncrementCollectionCount(x, (ICollection)o); }; } break; case CollectionKind.GenericCollection: case CollectionKind.GenericList: { var buildIncrementCollectionCountDelegate = s_buildIncrementCollectionCountDelegateMethod.MakeGenericMethod(ItemType); _incrementCollectionCountDelegate = (IncrementCollectionCountDelegate)buildIncrementCollectionCountDelegate.Invoke(null, Array.Empty<object>()); } break; case CollectionKind.GenericDictionary: { var buildIncrementCollectionCountDelegate = s_buildIncrementCollectionCountDelegateMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(ItemType.GetGenericArguments())); _incrementCollectionCountDelegate = (IncrementCollectionCountDelegate)buildIncrementCollectionCountDelegate.Invoke(null, Array.Empty<object>()); } break; default: // Do nothing. _incrementCollectionCountDelegate = DummyIncrementCollectionCount; break; } } _incrementCollectionCountDelegate(xmlWriter, obj, context); } private static MethodInfo s_buildIncrementCollectionCountDelegateMethod = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildIncrementCollectionCountDelegate), Globals.ScanAllMembers); private static IncrementCollectionCountDelegate BuildIncrementCollectionCountDelegate<T>() { return (xmlwriter, obj, context) => { context.IncrementCollectionCountGeneric<T>(xmlwriter, (ICollection<T>)obj); }; } private delegate IEnumerator CreateGenericDictionaryEnumeratorDelegate(IEnumerator enumerator); private CreateGenericDictionaryEnumeratorDelegate _createGenericDictionaryEnumeratorDelegate; internal IEnumerator GetEnumeratorForCollection(object obj, out Type enumeratorReturnType) { IEnumerator enumerator = ((IEnumerable)obj).GetEnumerator(); if (Kind == CollectionKind.GenericDictionary) { if (_createGenericDictionaryEnumeratorDelegate == null) { var keyValueTypes = ItemType.GetGenericArguments(); var buildCreateGenericDictionaryEnumerator = s_buildCreateGenericDictionaryEnumerator.MakeGenericMethod(keyValueTypes[0], keyValueTypes[1]); _createGenericDictionaryEnumeratorDelegate = (CreateGenericDictionaryEnumeratorDelegate)buildCreateGenericDictionaryEnumerator.Invoke(null, Array.Empty<object>()); } enumerator = _createGenericDictionaryEnumeratorDelegate(enumerator); } else if (Kind == CollectionKind.Dictionary) { enumerator = new DictionaryEnumerator(((IDictionary)obj).GetEnumerator()); } enumeratorReturnType = EnumeratorReturnType; return enumerator; } private Type _enumeratorReturnType; public Type EnumeratorReturnType { get { _enumeratorReturnType = _enumeratorReturnType ?? GetCollectionEnumeratorReturnType(); return _enumeratorReturnType; } } private Type GetCollectionEnumeratorReturnType() { Type enumeratorReturnType; if (Kind == CollectionKind.GenericDictionary) { var keyValueTypes = ItemType.GetGenericArguments(); enumeratorReturnType = Globals.TypeOfKeyValue.MakeGenericType(keyValueTypes); } else if (Kind == CollectionKind.Dictionary) { enumeratorReturnType = Globals.TypeOfObject; } else if (Kind == CollectionKind.GenericCollection || Kind == CollectionKind.GenericList) { enumeratorReturnType = ItemType; } else { var enumeratorType = GetEnumeratorMethod.ReturnType; if (enumeratorType.IsGenericType) { MethodInfo getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>()); enumeratorReturnType = getCurrentMethod.ReturnType; } else { enumeratorReturnType = Globals.TypeOfObject; } } return enumeratorReturnType; } private static MethodInfo s_buildCreateGenericDictionaryEnumerator = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildCreateGenericDictionaryEnumerator), Globals.ScanAllMembers); private static CreateGenericDictionaryEnumeratorDelegate BuildCreateGenericDictionaryEnumerator<K, V>() { return (enumerator) => { return new GenericDictionaryEnumerator<K, V>((IEnumerator<KeyValuePair<K, V>>)enumerator); }; } } private DataContract GetSharedTypeContract(Type type) { if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false)) { return this; } if (type.IsDefined(Globals.TypeOfDataContractAttribute, false)) { return new ClassDataContract(type); } return null; } internal static bool IsCollectionInterface(Type type) { if (type.IsGenericType) type = type.GetGenericTypeDefinition(); return ((IList<Type>)KnownInterfaces).Contains(type); } internal static bool IsCollection(Type type) { Type itemType; return IsCollection(type, out itemType); } internal static bool IsCollection(Type type, out Type itemType) { return IsCollectionHelper(type, out itemType, true /*constructorRequired*/); } internal static bool IsCollection(Type type, bool constructorRequired) { Type itemType; return IsCollectionHelper(type, out itemType, constructorRequired); } private static bool IsCollectionHelper(Type type, out Type itemType, bool constructorRequired) { if (type.IsArray && DataContract.GetBuiltInDataContract(type) == null) { itemType = type.GetElementType(); return true; } DataContract dataContract; return IsCollectionOrTryCreate(type, false /*tryCreate*/, out dataContract, out itemType, constructorRequired); } internal static bool TryCreate(Type type, out DataContract dataContract) { Type itemType; return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, true /*constructorRequired*/); } internal static bool CreateGetOnlyCollectionDataContract(Type type, out DataContract dataContract) { Type itemType; if (type.IsArray) { dataContract = new CollectionDataContract(type); return true; } else { return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, false /*constructorRequired*/); } } internal static bool TryCreateGetOnlyCollectionDataContract(Type type, out DataContract dataContract) { dataContract = DataContract.GetDataContractFromGeneratedAssembly(type); if (dataContract == null) { Type itemType; if (type.IsArray) { dataContract = new CollectionDataContract(type); return true; } else { return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, false /*constructorRequired*/); } } else { if (dataContract is CollectionDataContract) { return true; } else { dataContract = null; return false; } } } internal static MethodInfo GetTargetMethodWithName(string name, Type type, Type interfaceType) { Type t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault(); if (t == null) return null; return t.GetMethod(name); } private static bool IsArraySegment(Type t) { return t.IsGenericType && (t.GetGenericTypeDefinition() == typeof(ArraySegment<>)); } private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataContract dataContract, out Type itemType, bool constructorRequired) { dataContract = null; itemType = Globals.TypeOfObject; if (DataContract.GetBuiltInDataContract(type) != null) { return HandleIfInvalidCollection(type, tryCreate, false/*hasCollectionDataContract*/, false/*isBaseTypeCollection*/, SR.CollectionTypeCannotBeBuiltIn, null, ref dataContract); } MethodInfo addMethod, getEnumeratorMethod; bool hasCollectionDataContract = IsCollectionDataContract(type); Type baseType = type.BaseType; bool isBaseTypeCollection = (baseType != null && baseType != Globals.TypeOfObject && baseType != Globals.TypeOfValueType && baseType != Globals.TypeOfUri) ? IsCollection(baseType) : false; if (type.IsDefined(Globals.TypeOfDataContractAttribute, false)) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection, SR.CollectionTypeCannotHaveDataContract, null, ref dataContract); } if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type) || IsArraySegment(type)) { return false; } if (!Globals.TypeOfIEnumerable.IsAssignableFrom(type)) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection, SR.CollectionTypeIsNotIEnumerable, null, ref dataContract); } if (type.IsInterface) { Type interfaceTypeToCheck = type.IsGenericType ? type.GetGenericTypeDefinition() : type; Type[] knownInterfaces = KnownInterfaces; for (int i = 0; i < knownInterfaces.Length; i++) { if (knownInterfaces[i] == interfaceTypeToCheck) { addMethod = null; if (type.IsGenericType) { Type[] genericArgs = type.GetGenericArguments(); if (interfaceTypeToCheck == Globals.TypeOfIDictionaryGeneric) { itemType = Globals.TypeOfKeyValue.MakeGenericType(genericArgs); addMethod = type.GetMethod(Globals.AddMethodName); getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(genericArgs)).GetMethod(Globals.GetEnumeratorMethodName); } else { itemType = genericArgs[0]; // ICollection<T> has AddMethod var collectionType = Globals.TypeOfICollectionGeneric.MakeGenericType(itemType); if (collectionType.IsAssignableFrom(type)) { addMethod = collectionType.GetMethod(Globals.AddMethodName); } getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(itemType).GetMethod(Globals.GetEnumeratorMethodName); } } else { if (interfaceTypeToCheck == Globals.TypeOfIDictionary) { itemType = typeof(KeyValue<object, object>); addMethod = type.GetMethod(Globals.AddMethodName); } else { itemType = Globals.TypeOfObject; // IList has AddMethod if (interfaceTypeToCheck == Globals.TypeOfIList) { addMethod = type.GetMethod(Globals.AddMethodName); } } getEnumeratorMethod = Globals.TypeOfIEnumerable.GetMethod(Globals.GetEnumeratorMethodName); } if (tryCreate) dataContract = new CollectionDataContract(type, (CollectionKind)(i + 1), itemType, getEnumeratorMethod, addMethod, null/*defaultCtor*/); return true; } } } ConstructorInfo defaultCtor = null; if (!type.IsValueType) { defaultCtor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Array.Empty<Type>()); if (defaultCtor == null && constructorRequired) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection/*createContractWithException*/, SR.CollectionTypeDoesNotHaveDefaultCtor, null, ref dataContract); } } Type knownInterfaceType = null; CollectionKind kind = CollectionKind.None; bool multipleDefinitions = false; Type[] interfaceTypes = type.GetInterfaces(); foreach (Type interfaceType in interfaceTypes) { Type interfaceTypeToCheck = interfaceType.IsGenericType ? interfaceType.GetGenericTypeDefinition() : interfaceType; Type[] knownInterfaces = KnownInterfaces; for (int i = 0; i < knownInterfaces.Length; i++) { if (knownInterfaces[i] == interfaceTypeToCheck) { CollectionKind currentKind = (CollectionKind)(i + 1); if (kind == CollectionKind.None || currentKind < kind) { kind = currentKind; knownInterfaceType = interfaceType; multipleDefinitions = false; } else if ((kind & currentKind) == currentKind) multipleDefinitions = true; break; } } } if (kind == CollectionKind.None) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection, SR.CollectionTypeIsNotIEnumerable, null, ref dataContract); } if (kind == CollectionKind.Enumerable || kind == CollectionKind.Collection || kind == CollectionKind.GenericEnumerable) { if (multipleDefinitions) knownInterfaceType = Globals.TypeOfIEnumerable; itemType = knownInterfaceType.IsGenericType ? knownInterfaceType.GetGenericArguments()[0] : Globals.TypeOfObject; GetCollectionMethods(type, knownInterfaceType, new Type[] { itemType }, false /*addMethodOnInterface*/, out getEnumeratorMethod, out addMethod); if (addMethod == null) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection/*createContractWithException*/, SR.CollectionTypeDoesNotHaveAddMethod, DataContract.GetClrTypeFullName(itemType), ref dataContract); } if (tryCreate) dataContract = new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, addMethod, defaultCtor, !constructorRequired); } else { if (multipleDefinitions) { return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, isBaseTypeCollection/*createContractWithException*/, SR.CollectionTypeHasMultipleDefinitionsOfInterface, KnownInterfaces[(int)kind - 1].Name, ref dataContract); } Type[] addMethodTypeArray = null; switch (kind) { case CollectionKind.GenericDictionary: addMethodTypeArray = knownInterfaceType.GetGenericArguments(); bool isOpenGeneric = knownInterfaceType.IsGenericTypeDefinition || (addMethodTypeArray[0].IsGenericParameter && addMethodTypeArray[1].IsGenericParameter); itemType = isOpenGeneric ? Globals.TypeOfKeyValue : Globals.TypeOfKeyValue.MakeGenericType(addMethodTypeArray); break; case CollectionKind.Dictionary: addMethodTypeArray = new Type[] { Globals.TypeOfObject, Globals.TypeOfObject }; itemType = Globals.TypeOfKeyValue.MakeGenericType(addMethodTypeArray); break; case CollectionKind.GenericList: case CollectionKind.GenericCollection: addMethodTypeArray = knownInterfaceType.GetGenericArguments(); itemType = addMethodTypeArray[0]; break; case CollectionKind.List: itemType = Globals.TypeOfObject; addMethodTypeArray = new Type[] { itemType }; break; } if (tryCreate) { GetCollectionMethods(type, knownInterfaceType, addMethodTypeArray, true /*addMethodOnInterface*/, out getEnumeratorMethod, out addMethod); dataContract = DataContract.GetDataContractFromGeneratedAssembly(type); if (dataContract == null) { dataContract = new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, addMethod, defaultCtor, !constructorRequired); } } } return true; } internal static bool IsCollectionDataContract(Type type) { return type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false); } private static bool HandleIfInvalidCollection(Type type, bool tryCreate, bool hasCollectionDataContract, bool createContractWithException, string message, string param, ref DataContract dataContract) { if (hasCollectionDataContract) { if (tryCreate) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(GetInvalidCollectionMessage(message, SR.Format(SR.InvalidCollectionDataContract, DataContract.GetClrTypeFullName(type)), param))); return true; } if (createContractWithException) { if (tryCreate) dataContract = new CollectionDataContract(type, GetInvalidCollectionMessage(message, SR.Format(SR.InvalidCollectionType, DataContract.GetClrTypeFullName(type)), param)); return true; } return false; } private static string GetInvalidCollectionMessage(string message, string nestedMessage, string param) { return (param == null) ? SR.Format(message, nestedMessage) : SR.Format(message, nestedMessage, param); } private static void FindCollectionMethodsOnInterface(Type type, Type interfaceType, ref MethodInfo addMethod, ref MethodInfo getEnumeratorMethod) { Type t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault(); if (t != null) { addMethod = t.GetMethod(Globals.AddMethodName) ?? addMethod; getEnumeratorMethod = t.GetMethod(Globals.GetEnumeratorMethodName) ?? getEnumeratorMethod; } } private static void GetCollectionMethods(Type type, Type interfaceType, Type[] addMethodTypeArray, bool addMethodOnInterface, out MethodInfo getEnumeratorMethod, out MethodInfo addMethod) { addMethod = getEnumeratorMethod = null; if (addMethodOnInterface) { addMethod = type.GetMethod(Globals.AddMethodName, BindingFlags.Instance | BindingFlags.Public, addMethodTypeArray); if (addMethod == null || addMethod.GetParameters()[0].ParameterType != addMethodTypeArray[0]) { FindCollectionMethodsOnInterface(type, interfaceType, ref addMethod, ref getEnumeratorMethod); if (addMethod == null) { Type[] parentInterfaceTypes = interfaceType.GetInterfaces(); foreach (Type parentInterfaceType in parentInterfaceTypes) { if (IsKnownInterface(parentInterfaceType)) { FindCollectionMethodsOnInterface(type, parentInterfaceType, ref addMethod, ref getEnumeratorMethod); if (addMethod == null) { break; } } } } } } else { // GetMethod returns Add() method with parameter closest matching T in assignability/inheritance chain addMethod = type.GetMethod(Globals.AddMethodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, addMethodTypeArray); if (addMethod == null) return; } if (getEnumeratorMethod == null) { getEnumeratorMethod = type.GetMethod(Globals.GetEnumeratorMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>()); if (getEnumeratorMethod == null || !Globals.TypeOfIEnumerator.IsAssignableFrom(getEnumeratorMethod.ReturnType)) { Type ienumerableInterface = interfaceType.GetInterfaces().Where(t => t.FullName.StartsWith("System.Collections.Generic.IEnumerable")).FirstOrDefault(); if (ienumerableInterface == null) ienumerableInterface = Globals.TypeOfIEnumerable; getEnumeratorMethod = GetTargetMethodWithName(Globals.GetEnumeratorMethodName, type, ienumerableInterface); } } } private static bool IsKnownInterface(Type type) { Type typeToCheck = type.IsGenericType ? type.GetGenericTypeDefinition() : type; foreach (Type knownInterfaceType in KnownInterfaces) { if (typeToCheck == knownInterfaceType) { return true; } } return false; } internal override DataContract GetValidContract(SerializationMode mode) { if (InvalidCollectionInSharedContractMessage != null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(InvalidCollectionInSharedContractMessage)); return this; } internal override DataContract GetValidContract() { if (this.IsConstructorCheckRequired) { CheckConstructor(); } return this; } private void CheckConstructor() { if (this.Constructor == null) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionTypeDoesNotHaveDefaultCtor, DataContract.GetClrTypeFullName(this.UnderlyingType)))); } else { this.IsConstructorCheckRequired = false; } } internal override bool IsValidContract(SerializationMode mode) { return (InvalidCollectionInSharedContractMessage == null); } /// <SecurityNote> /// Review - calculates whether this collection requires MemberAccessPermission for deserialization. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal bool RequiresMemberAccessForRead(SecurityException securityException) { if (!IsTypeVisible(UnderlyingType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustCollectionContractTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (ItemType != null && !IsTypeVisible(ItemType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustCollectionContractTypeNotPublic, DataContract.GetClrTypeFullName(ItemType)), securityException)); } return true; } if (ConstructorRequiresMemberAccess(Constructor)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustCollectionContractNoPublicConstructor, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (MethodRequiresMemberAccess(this.AddMethod)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustCollectionContractAddMethodNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), this.AddMethod.Name), securityException)); } return true; } return false; } /// <SecurityNote> /// Review - calculates whether this collection requires MemberAccessPermission for serialization. /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// </SecurityNote> internal bool RequiresMemberAccessForWrite(SecurityException securityException) { if (!IsTypeVisible(UnderlyingType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustCollectionContractTypeNotPublic, DataContract.GetClrTypeFullName(UnderlyingType)), securityException)); } return true; } if (ItemType != null && !IsTypeVisible(ItemType)) { if (securityException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new SecurityException(SR.Format( SR.PartialTrustCollectionContractTypeNotPublic, DataContract.GetClrTypeFullName(ItemType)), securityException)); } return true; } return false; } public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { // IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset. context.IsGetOnlyCollection = false; XmlFormatWriterDelegate(xmlWriter, obj, context, this); } public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) { xmlReader.Read(); object o = null; if (context.IsGetOnlyCollection) { // IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset. context.IsGetOnlyCollection = false; #if NET_NATIVE if (XmlFormatGetOnlyCollectionReaderDelegate == null) { throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, UnderlyingType.ToString())); } #endif XmlFormatGetOnlyCollectionReaderDelegate(xmlReader, context, CollectionItemName, Namespace, this); } else { o = XmlFormatReaderDelegate(xmlReader, context, CollectionItemName, Namespace, this); } xmlReader.ReadEndElement(); return o; } internal class DictionaryEnumerator : IEnumerator<KeyValue<object, object>> { private IDictionaryEnumerator _enumerator; public DictionaryEnumerator(IDictionaryEnumerator enumerator) { _enumerator = enumerator; } public void Dispose() { GC.SuppressFinalize(this); } public bool MoveNext() { return _enumerator.MoveNext(); } public KeyValue<object, object> Current { get { return new KeyValue<object, object>(_enumerator.Key, _enumerator.Value); } } object System.Collections.IEnumerator.Current { get { return Current; } } public void Reset() { _enumerator.Reset(); } } internal class GenericDictionaryEnumerator<K, V> : IEnumerator<KeyValue<K, V>> { private IEnumerator<KeyValuePair<K, V>> _enumerator; public GenericDictionaryEnumerator(IEnumerator<KeyValuePair<K, V>> enumerator) { _enumerator = enumerator; } public void Dispose() { GC.SuppressFinalize(this); } public bool MoveNext() { return _enumerator.MoveNext(); } public KeyValue<K, V> Current { get { KeyValuePair<K, V> current = _enumerator.Current; return new KeyValue<K, V>(current.Key, current.Value); } } object System.Collections.IEnumerator.Current { get { return Current; } } public void Reset() { _enumerator.Reset(); } } } }
// Copyright 2016 Google Inc. 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 Google.Api.Gax.ResourceNames; using Google.Cloud.ClientTesting; using Google.Cloud.Logging.V2; using Google.Protobuf.WellKnownTypes; using log4net; using log4net.Appender; using log4net.Config; using log4net.Core; using System; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using System.Xml; using Xunit; namespace Google.Cloud.Logging.Log4Net.Snippets { [SnippetOutputCollector] [Collection(nameof(Log4NetSnippetFixture))] public class GoogleStackdriverAppenderSnippets { private class Program { } private readonly Log4NetSnippetFixture _fixture; public GoogleStackdriverAppenderSnippets(Log4NetSnippetFixture fixture) { _fixture = fixture; } // SampleResource: log4net-template.xml [Fact] public void Overview() { DateTime startTime = DateTime.UtcNow; string projectId = _fixture.ProjectId; string logId = _fixture.LogId + $"-{Guid.NewGuid()}"; string fileName = "log4net.xml"; string resourceName = typeof(GoogleStackdriverAppenderSnippets).Namespace + ".log4net-template.xml"; string xml; using (var stream = typeof(GoogleStackdriverAppenderSnippets).Assembly .GetManifestResourceStream(resourceName)) { using (var reader = new StreamReader(stream)) { xml = reader.ReadToEnd(); } } xml = xml.Replace("PROJECT_ID", projectId).Replace("LOG_ID", logId); Assert.False(File.Exists(fileName), "Test would overwrite existing file"); File.WriteAllText(fileName, xml); try { // Resource: log4net-template.xml log4net_template // Sample: Overview // Configure log4net to use Google Cloud Logging from the XML configuration file. XmlConfigurator.Configure(LogManager.GetRepository(GetType().Assembly), new FileInfo("log4net.xml")); // Retrieve a logger for this context. ILog log = LogManager.GetLogger(typeof(Program)); // Log some information. This log entry will be sent to Google Cloud Logging. log.Info("An exciting log entry!"); // Flush buffered log entries before program exit. // This is required because log entries are buffered locally before being sent to Google Cloud Logging. // LogManager.Flush() only works in the full .NET framework (not in .NET Core): bool flushCompleted = LogManager.Flush(10_000); // On .NET Core, the specific repository needs to be flushed: bool repositoryFlushCompleted = ((IFlushable)LogManager.GetRepository(GetType().Assembly)).Flush(10_000); // End sample Assert.True(repositoryFlushCompleted); var logClient = LoggingServiceV2Client.Create(); var logName = LogName.FromProjectLog(projectId, logId); string formattedTime = XmlConvert.ToString(startTime.AddMinutes(-3), XmlDateTimeSerializationMode.Utc); string filter = $"timestamp >= \"{formattedTime}\" AND logName=\"{logName}\" AND \"An exciting log entry!\""; // Wait up to 30 seconds for the log entry to appear in Google Cloud Logging. for (int i = 0; i < 30; i++) { var logEntry = logClient.ListLogEntries( resourceNames: new[] { ProjectName.FromProject(projectId) }, filter: filter, orderBy: "timestamp desc") .FirstOrDefault(); if (logEntry != null) { Assert.Contains("An exciting log entry!", logEntry.TextPayload); return; } Thread.Sleep(1_000); } Assert.False(true, "Log entry failed to appear in Google Cloud Logging."); } finally { File.Delete(fileName); } } // SampleResource: log4net-custom-labels-template.xml [Fact] public void CustomLabels() { DateTime startTime = DateTime.UtcNow; string projectId = _fixture.ProjectId; string logId = _fixture.LogId + $"-{Guid.NewGuid()}"; string fileName = "log4net.xml"; string resourceName = typeof(GoogleStackdriverAppenderSnippets).Namespace + ".log4net-custom-labels-template.xml"; string xml; using (var stream = typeof(GoogleStackdriverAppenderSnippets).Assembly .GetManifestResourceStream(resourceName)) { using (var reader = new StreamReader(stream)) { xml = reader.ReadToEnd(); } } xml = xml.Replace("PROJECT_ID", projectId).Replace("LOG_ID", logId); Assert.False(File.Exists(fileName), "Test would overwrite existing file"); File.WriteAllText(fileName, xml); try { // Resource: log4net-custom-labels-template.xml log4net_custom_labels_template // Sample: Custom_Labels // Configure log4net to use Google Cloud Logging from the XML configuration file. XmlConfigurator.Configure(LogManager.GetRepository(GetType().Assembly), new FileInfo("log4net.xml")); // Retrieve a logger for this context. ILog log = LogManager.GetLogger(typeof(Program)); // Set a property using one of the GlobaContext, ThreadContext or LogicalThreadContext classes. LogicalThreadContext.Properties["property_for_label"] = "my label value"; // Log some information. This log entry will be sent to Google Cloud Logging with a label // {"label_from_property", "my label value"}. The label key "label_from_property" is the one // specified in configuration for a custom label that gets its value from the "property_for_label" // property. log.Info("An exciting log entry!"); // Flush buffered log entries before program exit. // This is required because log entries are buffered locally before being sent to Google Cloud Logging. // LogManager.Flush() only works in the full .NET framework (not in .NET Core): bool flushCompleted = LogManager.Flush(10_000); // On .NET Core, the specific repository needs to be flushed: bool repositoryFlushCompleted = ((IFlushable)LogManager.GetRepository(GetType().Assembly)).Flush(10_000); // End sample Assert.True(repositoryFlushCompleted); var logClient = LoggingServiceV2Client.Create(); var logName = LogName.FromProjectLog(projectId, logId); string formattedTime = XmlConvert.ToString(startTime.AddMinutes(-3), XmlDateTimeSerializationMode.Utc); string filter = $"timestamp >= \"{formattedTime}\" AND logName=\"{logName}\" AND \"An exciting log entry!\""; // Wait up to 30 seconds for the log entry to appear in Google Cloud Logging. for (int i = 0; i < 30; i++) { var logEntry = logClient.ListLogEntries( resourceNames: new[] { ProjectName.FromProject(projectId) }, filter: filter, orderBy: "timestamp desc") .FirstOrDefault(); if (logEntry != null) { Assert.Contains("An exciting log entry!", logEntry.TextPayload); Assert.Contains(logEntry.Labels, label => label.Key == "label_from_property" && label.Value == "my label value"); return; } Thread.Sleep(1_000); } Assert.False(true, "Log entry failed to appear in Google Cloud Logging."); } finally { File.Delete(fileName); } } #pragma warning disable xUnit1013 // Public method should be marked as test // This cannot be a unit test as ASP.NET cannot run in this environment. public void Overview_AspNet() #pragma warning restore xUnit1013 // Public method should be marked as test { // Resource: log4net-aspnet-template.xml log4net_aspnet_template // Sample: Overview_AspNet // Load log4net configuration from Web.config log4net.Config.XmlConfigurator.Configure(LogManager.GetRepository(GetType().Assembly)); // End sample } // Sample: IJsonLayout public class SampleJsonLayout : IJsonLayout, IOptionHandler { public Struct _template; public int SampleConfigurationValue { get; set; } public void ActivateOptions() { _template = new Struct(); _template.Fields["SampleConfiguration"] = Value.ForNumber(SampleConfigurationValue); } public Struct Format(LoggingEvent loggingEvent) { Struct ret = _template.Clone(); ret.Fields["Message"] = Value.ForString(loggingEvent.RenderedMessage); if (loggingEvent.ExceptionObject != null) { ret.Fields["Exception"] = Value.ForString(loggingEvent.ExceptionObject.Message); } return ret; } } // End sample } }
// 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.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.ImplementType; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; namespace Microsoft.CodeAnalysis.ImplementInterface { internal abstract partial class AbstractImplementInterfaceService { internal partial class ImplementInterfaceCodeAction { private ISymbol GenerateProperty( Compilation compilation, IPropertySymbol property, Accessibility accessibility, DeclarationModifiers modifiers, bool generateAbstractly, bool useExplicitInterfaceSymbol, string memberName, ImplementTypePropertyGenerationBehavior propertyGenerationBehavior, CancellationToken cancellationToken) { var factory = this.Document.GetLanguageService<SyntaxGenerator>(); var attributesToRemove = AttributesToRemove(compilation); var getAccessor = GenerateGetAccessor( compilation, property, accessibility, generateAbstractly, useExplicitInterfaceSymbol, propertyGenerationBehavior, attributesToRemove, cancellationToken); var setAccessor = GenerateSetAccessor( compilation, property, accessibility, generateAbstractly, useExplicitInterfaceSymbol, propertyGenerationBehavior, attributesToRemove, cancellationToken); var syntaxFacts = Document.GetLanguageService<ISyntaxFactsService>(); var parameterNames = NameGenerator.EnsureUniqueness( property.Parameters.Select(p => p.Name).ToList(), isCaseSensitive: syntaxFacts.IsCaseSensitive); var updatedProperty = property.RenameParameters(parameterNames); updatedProperty = updatedProperty.RemoveAttributeFromParameters(attributesToRemove); // TODO(cyrusn): Delegate through throughMember if it's non-null. return CodeGenerationSymbolFactory.CreatePropertySymbol( updatedProperty, accessibility: accessibility, modifiers: modifiers, explicitInterfaceImplementations: useExplicitInterfaceSymbol ? ImmutableArray.Create(property) : default, name: memberName, getMethod: getAccessor, setMethod: setAccessor); } /// <summary> /// Lists compiler attributes that we want to remove. /// The TupleElementNames attribute is compiler generated (it is used for naming tuple element names). /// We never want to place it in source code. /// Same thing for the Dynamic attribute. /// </summary> private INamedTypeSymbol[] AttributesToRemove(Compilation compilation) { return new[] { compilation.ComAliasNameAttributeType(), compilation.TupleElementNamesAttributeType(), compilation.DynamicAttributeType() }; } private IMethodSymbol GenerateSetAccessor( Compilation compilation, IPropertySymbol property, Accessibility accessibility, bool generateAbstractly, bool useExplicitInterfaceSymbol, ImplementTypePropertyGenerationBehavior propertyGenerationBehavior, INamedTypeSymbol[] attributesToRemove, CancellationToken cancellationToken) { if (property.SetMethod == null) { return null; } if (property.GetMethod == null) { // Can't have an auto-prop with just a setter. propertyGenerationBehavior = ImplementTypePropertyGenerationBehavior.PreferThrowingProperties; } var setMethod = property.SetMethod.RemoveInaccessibleAttributesAndAttributesOfTypes( this.State.ClassOrStructType, attributesToRemove); return CodeGenerationSymbolFactory.CreateAccessorSymbol( setMethod, attributes: default(ImmutableArray<AttributeData>), accessibility: accessibility, explicitInterfaceImplementations: useExplicitInterfaceSymbol ? ImmutableArray.Create(property.SetMethod) : default, statements: GetSetAccessorStatements( compilation, property, generateAbstractly, propertyGenerationBehavior, cancellationToken)); } private IMethodSymbol GenerateGetAccessor( Compilation compilation, IPropertySymbol property, Accessibility accessibility, bool generateAbstractly, bool useExplicitInterfaceSymbol, ImplementTypePropertyGenerationBehavior propertyGenerationBehavior, INamedTypeSymbol[] attributesToRemove, CancellationToken cancellationToken) { if (property.GetMethod == null) { return null; } var getMethod = property.GetMethod.RemoveInaccessibleAttributesAndAttributesOfTypes( this.State.ClassOrStructType, attributesToRemove); return CodeGenerationSymbolFactory.CreateAccessorSymbol( getMethod, attributes: default(ImmutableArray<AttributeData>), accessibility: accessibility, explicitInterfaceImplementations: useExplicitInterfaceSymbol ? ImmutableArray.Create(property.GetMethod) : default, statements: GetGetAccessorStatements( compilation, property, generateAbstractly, propertyGenerationBehavior, cancellationToken)); } private ImmutableArray<SyntaxNode> GetSetAccessorStatements( Compilation compilation, IPropertySymbol property, bool generateAbstractly, ImplementTypePropertyGenerationBehavior propertyGenerationBehavior, CancellationToken cancellationToken) { if (generateAbstractly) { return default(ImmutableArray<SyntaxNode>); } var factory = this.Document.GetLanguageService<SyntaxGenerator>(); if (ThroughMember != null) { var throughExpression = CreateThroughExpression(factory); SyntaxNode expression; if (property.IsIndexer) { expression = throughExpression; } else { expression = factory.MemberAccessExpression( throughExpression, factory.IdentifierName(property.Name)); } if (property.Parameters.Length > 0) { var arguments = factory.CreateArguments(property.Parameters.As<IParameterSymbol>()); expression = factory.ElementAccessExpression(expression, arguments); } expression = factory.AssignmentStatement(expression, factory.IdentifierName("value")); return ImmutableArray.Create(factory.ExpressionStatement(expression)); } return propertyGenerationBehavior == ImplementTypePropertyGenerationBehavior.PreferAutoProperties ? default(ImmutableArray<SyntaxNode>) : factory.CreateThrowNotImplementedStatementBlock(compilation); } private ImmutableArray<SyntaxNode> GetGetAccessorStatements( Compilation compilation, IPropertySymbol property, bool generateAbstractly, ImplementTypePropertyGenerationBehavior propertyGenerationBehavior, CancellationToken cancellationToken) { if (generateAbstractly) { return default(ImmutableArray<SyntaxNode>); } var factory = this.Document.GetLanguageService<SyntaxGenerator>(); if (ThroughMember != null) { var throughExpression = CreateThroughExpression(factory); SyntaxNode expression; if (property.IsIndexer) { expression = throughExpression; } else { expression = factory.MemberAccessExpression( throughExpression, factory.IdentifierName(property.Name)); } if (property.Parameters.Length > 0) { var arguments = factory.CreateArguments(property.Parameters.As<IParameterSymbol>()); expression = factory.ElementAccessExpression(expression, arguments); } return ImmutableArray.Create(factory.ReturnStatement(expression)); } return propertyGenerationBehavior == ImplementTypePropertyGenerationBehavior.PreferAutoProperties ? default(ImmutableArray<SyntaxNode>) : factory.CreateThrowNotImplementedStatementBlock(compilation); } } } }
namespace OauthPKCE { using System; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Runtime.InteropServices; using System.Threading.Tasks; using Dropbox.Api; partial class Program { // Add an ApiKey (from https://www.dropbox.com/developers/apps) here private const string ApiKey = "XXXXXXXXXXXXXXX"; // This loopback host is for demo purpose. If this port is not // available on your machine you need to update this URL with an unused port. private const string LoopbackHost = "http://127.0.0.1:52475/"; // URL to receive OAuth 2 redirect from Dropbox server. // You also need to register this redirect URL on https://www.dropbox.com/developers/apps. private readonly Uri RedirectUri = new Uri(LoopbackHost + "authorize"); // URL to receive access token from JS. private readonly Uri JSRedirectUri = new Uri(LoopbackHost + "token"); [DllImport("kernel32.dll", ExactSpelling = true)] private static extern IntPtr GetConsoleWindow(); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool SetForegroundWindow(IntPtr hWnd); [STAThread] static int Main(string[] args) { var instance = new Program(); try { Console.WriteLine("Example OAuth PKCE Application"); var task = Task.Run((Func<Task<int>>)instance.Run); task.Wait(); return task.Result; } catch (Exception e) { Console.WriteLine(e); throw e; } } private async Task<int> Run() { DropboxCertHelper.InitializeCertPinning(); var uid = await this.AcquireAccessToken(null, IncludeGrantedScopes.None); if (string.IsNullOrEmpty(uid)) { return 1; } // Specify socket level timeout which decides maximum waiting time when no bytes are // received by the socket. var httpClient = new HttpClient(new WebRequestHandler { ReadWriteTimeout = 10 * 1000 }) { // Specify request level timeout which decides maximum time that can be spent on // download/upload files. Timeout = TimeSpan.FromMinutes(20) }; try { var config = new DropboxClientConfig("SimplePKCEOAuthApp") { HttpClient = httpClient }; var client = new DropboxClient(Settings.Default.RefreshToken, ApiKey, config); // This call should succeed since the correct scope has been acquired await GetCurrentAccount(client); Console.WriteLine("Oauth PKCE Test Complete!"); Console.WriteLine("Exit with any key"); Console.ReadKey(); } catch (HttpException e) { Console.WriteLine("Exception reported from RPC layer"); Console.WriteLine(" Status code: {0}", e.StatusCode); Console.WriteLine(" Message : {0}", e.Message); if (e.RequestUri != null) { Console.WriteLine(" Request uri: {0}", e.RequestUri); } } return 0; } /// <summary> /// Handles the redirect from Dropbox server. Because we are using token flow, the local /// http server cannot directly receive the URL fragment. We need to return a HTML page with /// inline JS which can send URL fragment to local server as URL parameter. /// </summary> /// <param name="http">The http listener.</param> /// <returns>The <see cref="Task"/></returns> private async Task HandleOAuth2Redirect(HttpListener http) { var context = await http.GetContextAsync(); // We only care about request to RedirectUri endpoint. while (context.Request.Url.AbsolutePath != RedirectUri.AbsolutePath) { context = await http.GetContextAsync(); } context.Response.ContentType = "text/html"; // Respond with a page which runs JS and sends URL fragment as query string // to TokenRedirectUri. using (var file = File.OpenRead("index.html")) { file.CopyTo(context.Response.OutputStream); } context.Response.OutputStream.Close(); } /// <summary> /// Handle the redirect from JS and process raw redirect URI with fragment to /// complete the authorization flow. /// </summary> /// <param name="http">The http listener.</param> /// <returns>The <see cref="OAuth2Response"/></returns> private async Task<Uri> HandleJSRedirect(HttpListener http) { var context = await http.GetContextAsync(); // We only care about request to TokenRedirectUri endpoint. while (context.Request.Url.AbsolutePath != JSRedirectUri.AbsolutePath) { context = await http.GetContextAsync(); } var redirectUri = new Uri(context.Request.QueryString["url_with_fragment"]); return redirectUri; } /// <summary> /// Acquires a dropbox access token and saves it to the default settings for the app. /// <para> /// This fetches the access token from the applications settings, if it is not found there /// (or if the user chooses to reset the settings) then the UI in <see cref="LoginForm"/> is /// displayed to authorize the user. /// </para> /// </summary> /// <returns>A valid uid if a token was acquired or null.</returns> private async Task<string> AcquireAccessToken(string[] scopeList, IncludeGrantedScopes includeGrantedScopes) { Console.Write("Reset settings (Y/N) "); if (Console.ReadKey().Key == ConsoleKey.Y) { Settings.Default.Reset(); } Console.WriteLine(); var accessToken = Settings.Default.AccessToken; var refreshToken = Settings.Default.RefreshToken; if (string.IsNullOrEmpty(accessToken)) { try { Console.WriteLine("Waiting for credentials."); var state = Guid.NewGuid().ToString("N"); var OAuthFlow = new PKCEOAuthFlow(); var authorizeUri = OAuthFlow.GetAuthorizeUri(OAuthResponseType.Code, ApiKey, RedirectUri.ToString(), state: state, tokenAccessType: TokenAccessType.Offline, scopeList: scopeList, includeGrantedScopes: includeGrantedScopes); var http = new HttpListener(); http.Prefixes.Add(LoopbackHost); http.Start(); System.Diagnostics.Process.Start(authorizeUri.ToString()); // Handle OAuth redirect and send URL fragment to local server using JS. await HandleOAuth2Redirect(http); // Handle redirect from JS and process OAuth response. var redirectUri = await HandleJSRedirect(http); Console.WriteLine("Exchanging code for token"); var tokenResult = await OAuthFlow.ProcessCodeFlowAsync(redirectUri, ApiKey, RedirectUri.ToString(), state); Console.WriteLine("Finished Exchanging Code for Token"); // Bring console window to the front. SetForegroundWindow(GetConsoleWindow()); accessToken = tokenResult.AccessToken; refreshToken = tokenResult.RefreshToken; var uid = tokenResult.Uid; Console.WriteLine("Uid: {0}", uid); Console.WriteLine("AccessToken: {0}", accessToken); if (tokenResult.RefreshToken != null) { Console.WriteLine("RefreshToken: {0}", refreshToken); Settings.Default.RefreshToken = refreshToken; } if (tokenResult.ExpiresAt != null) { Console.WriteLine("ExpiresAt: {0}", tokenResult.ExpiresAt); } if (tokenResult.ScopeList != null) { Console.WriteLine("Scopes: {0}", String.Join(" ", tokenResult.ScopeList)); } Settings.Default.AccessToken = accessToken; Settings.Default.Uid = uid; Settings.Default.Save(); http.Stop(); return uid; } catch (Exception e) { Console.WriteLine("Error: {0}", e.Message); return null; } } return null; } /// <summary> /// Gets information about the currently authorized account. /// <para> /// This demonstrates calling a simple rpc style api from the Users namespace. /// </para> /// </summary> /// <param name="client">The Dropbox client.</param> /// <returns>An asynchronous task.</returns> private async Task GetCurrentAccount(DropboxClient client) { try { Console.WriteLine("Current Account:"); var full = await client.Users.GetCurrentAccountAsync(); Console.WriteLine("Account id : {0}", full.AccountId); Console.WriteLine("Country : {0}", full.Country); Console.WriteLine("Email : {0}", full.Email); Console.WriteLine("Is paired : {0}", full.IsPaired ? "Yes" : "No"); Console.WriteLine("Locale : {0}", full.Locale); Console.WriteLine("Name"); Console.WriteLine(" Display : {0}", full.Name.DisplayName); Console.WriteLine(" Familiar : {0}", full.Name.FamiliarName); Console.WriteLine(" Given : {0}", full.Name.GivenName); Console.WriteLine(" Surname : {0}", full.Name.Surname); Console.WriteLine("Referral link : {0}", full.ReferralLink); if (full.Team != null) { Console.WriteLine("Team"); Console.WriteLine(" Id : {0}", full.Team.Id); Console.WriteLine(" Name : {0}", full.Team.Name); } else { Console.WriteLine("Team - None"); } } catch (Exception e) { throw e; } } } }
using UnityEngine; using System.Collections; using UnityEditor; [CustomEditor(typeof(EasyJoystick))] public class GUIEasyJoystickInspector : Editor{ GUIStyle paddingStyle1; public GUIEasyJoystickInspector(){ paddingStyle1 = new GUIStyle(); paddingStyle1.padding = new RectOffset(15,0,0,0); } void OnEnable(){ EasyJoystick t = (EasyJoystick)target; if (t.areaTexture==null){ t.areaTexture = (Texture)Resources.Load("RadialJoy_Area"); EditorUtility.SetDirty(t); } if (t.touchTexture==null){ t.touchTexture = (Texture)Resources.Load("RadialJoy_Touch"); EditorUtility.SetDirty(t); } if (t.deadTexture==null){ t.deadTexture = (Texture)Resources.Load("RadialJoy_Dead"); EditorUtility.SetDirty(t); } t.showDebugRadius = true; } void OnDisable(){ EasyJoystick t = (EasyJoystick)target; t.showDebugRadius = false; } public override void OnInspectorGUI(){ EasyJoystick t = (EasyJoystick)target; // Joystick Properties t.showProperties = HTEditorToolKit.DrawTitleFoldOut( t.showProperties,"Joystick properties"); if (t.showProperties){ EditorGUILayout.BeginVertical(paddingStyle1); t.name = EditorGUILayout.TextField("Joystick name",t.name); t.enable = EditorGUILayout.Toggle("Enable joystick",t.enable); t.isActivated = EditorGUILayout.Toggle("Activated",t.isActivated); t.showDebugRadius = EditorGUILayout.Toggle("Show debug area",t.showDebugRadius); HTEditorToolKit.DrawSeparatorLine(paddingStyle1.padding.left); EditorGUILayout.Separator(); t.useFixedUpdate = EditorGUILayout.Toggle("Use fixed update",t.useFixedUpdate); t.isUseGuiLayout = EditorGUILayout.Toggle("Use GUI Layout",t.isUseGuiLayout); if (!t.isUseGuiLayout){ EditorGUILayout.HelpBox("This lets you skip the GUI layout phase (Increase GUI performance). It can only be used if you do not use GUI.Window and GUILayout inside of this OnGUI call.",MessageType.Warning); } EditorGUILayout.EndVertical(); } t.showPosition = HTEditorToolKit.DrawTitleFoldOut( t.showPosition,"Joystick position & size"); if (t.showPosition){ // Dynamic joystick t.DynamicJoystick = EditorGUILayout.Toggle("Dynamic joystick",t.DynamicJoystick); if (t.DynamicJoystick){ t.area = (EasyJoystick.DynamicArea) EditorGUILayout.EnumPopup("Free area",t.area); } else{ t.JoyAnchor = (EasyJoystick.JoystickAnchor)EditorGUILayout.EnumPopup("Anchor",t.JoyAnchor); t.JoystickPositionOffset = EditorGUILayout.Vector2Field("Offset",t.JoystickPositionOffset); } HTEditorToolKit.DrawSeparatorLine(paddingStyle1.padding.left); EditorGUILayout.Separator(); t.ZoneRadius = EditorGUILayout.FloatField("Area radius",t.ZoneRadius); t.TouchSize = EditorGUILayout.FloatField("Touch radius",t.TouchSize); t.RestrictArea = EditorGUILayout.Toggle(" Restrict to area",t.RestrictArea); t.resetFingerExit = EditorGUILayout.Toggle(" Reset finger exit",t.resetFingerExit); t.deadZone = EditorGUILayout.FloatField("Dead zone radius",t.deadZone); } // Joystick axes properties t.showInteraction =HTEditorToolKit.DrawTitleFoldOut( t.showInteraction,"Joystick axes properties & events"); if (t.showInteraction){ EditorGUILayout.BeginVertical(paddingStyle1); // Interaction t.Interaction = (EasyJoystick.InteractionType)EditorGUILayout.EnumPopup("Interaction type",t.Interaction); if (t.Interaction == EasyJoystick.InteractionType.EventNotification || t.Interaction == EasyJoystick.InteractionType.DirectAndEvent){ t.useBroadcast = EditorGUILayout.Toggle("Broadcast messages",t.useBroadcast); if (t.useBroadcast){ t.receiverGameObject =(GameObject) EditorGUILayout.ObjectField(" Receiver gameobject",t.receiverGameObject,typeof(GameObject),true); t.messageMode =(EasyJoystick.Broadcast) EditorGUILayout.EnumPopup(" Sending mode",t.messageMode); } } HTEditorToolKit.DrawSeparatorLine(paddingStyle1.padding.left); // X axis GUI.color = new Color(255f/255f,69f/255f,40f/255f); t.enableXaxis = EditorGUILayout.BeginToggleGroup("Enable X axis",t.enableXaxis); GUI.color = Color.white; if (t.enableXaxis){ EditorGUILayout.BeginVertical(paddingStyle1); t.speed.x = EditorGUILayout.FloatField("Speed",t.speed.x); t.inverseXAxis = EditorGUILayout.Toggle("Inverse axis",t.inverseXAxis); EditorGUILayout.Separator(); if (t.Interaction == EasyJoystick.InteractionType.Direct || t.Interaction == EasyJoystick.InteractionType.DirectAndEvent){ t.XAxisTransform = (Transform)EditorGUILayout.ObjectField("Joystick X to",t.XAxisTransform,typeof(Transform),true); if ( t.XAxisTransform!=null){ // characterCollider if (t.XAxisTransform.GetComponent<CharacterController>() && (t.XTI==EasyJoystick.PropertiesInfluenced.Translate || t.XTI==EasyJoystick.PropertiesInfluenced.TranslateLocal)){ EditorGUILayout.HelpBox("CharacterController detected",MessageType.Info); t.xAxisGravity = EditorGUILayout.FloatField("Gravity",t.xAxisGravity); } else{ t.xAxisGravity=0; } t.XTI = (EasyJoystick.PropertiesInfluenced)EditorGUILayout.EnumPopup("Influenced",t.XTI); switch( t.xAI){ case EasyJoystick.AxisInfluenced.X: GUI.color = new Color(255f/255f,69f/255f,40f/255f); break; case EasyJoystick.AxisInfluenced.Y: GUI.color = Color.green; break; case EasyJoystick.AxisInfluenced.Z: GUI.color = new Color(63f/255f,131f/255f,245f/255f); break; } t.xAI = (EasyJoystick.AxisInfluenced)EditorGUILayout.EnumPopup("Axis influenced",t.xAI); GUI.color = Color.white; EditorGUILayout.Separator(); if (t.XTI == EasyJoystick.PropertiesInfluenced.RotateLocal){ // auto stab t.enableXAutoStab = EditorGUILayout.Toggle( "AutoStab",t.enableXAutoStab); if (t.enableXAutoStab){ EditorGUILayout.BeginVertical(paddingStyle1); t.ThresholdX = EditorGUILayout.FloatField("Threshold ", t.ThresholdX); t.StabSpeedX = EditorGUILayout.FloatField("Speed",t.StabSpeedX); EditorGUILayout.EndVertical(); } EditorGUILayout.Separator(); // Clamp t.enableXClamp = EditorGUILayout.Toggle("Clamp rotation",t.enableXClamp); if (t.enableXClamp){ EditorGUILayout.BeginVertical(paddingStyle1); t.clampXMax = EditorGUILayout.FloatField("Max angle value",t.clampXMax); t.clampXMin = EditorGUILayout.FloatField("Min angle value",t.clampXMin); EditorGUILayout.EndVertical(); } } } } EditorGUILayout.EndVertical(); } EditorGUILayout.EndToggleGroup(); HTEditorToolKit.DrawSeparatorLine(paddingStyle1.padding.left); // Y axis GUI.color = Color.green; t.enableYaxis = EditorGUILayout.BeginToggleGroup("Enable Y axis",t.enableYaxis); GUI.color = Color.white; if (t.enableYaxis){ EditorGUILayout.BeginVertical(paddingStyle1); t.speed.y = EditorGUILayout.FloatField("Speed",t.speed.y); t.inverseYAxis = EditorGUILayout.Toggle("Inverse axis",t.inverseYAxis); EditorGUILayout.Separator(); if (t.Interaction == EasyJoystick.InteractionType.Direct || t.Interaction == EasyJoystick.InteractionType.DirectAndEvent){ t.YAxisTransform = (Transform)EditorGUILayout.ObjectField("Joystick Y to",t.YAxisTransform,typeof(Transform),true); if ( t.YAxisTransform!=null){ // characterCollider if (t.YAxisTransform.GetComponent<CharacterController>() && (t.YTI==EasyJoystick.PropertiesInfluenced.Translate || t.YTI==EasyJoystick.PropertiesInfluenced.TranslateLocal)){ EditorGUILayout.HelpBox("CharacterController detected",MessageType.Info); t.yAxisGravity = EditorGUILayout.FloatField("Gravity",t.yAxisGravity); } else{ t.yAxisGravity=0; } t.YTI = (EasyJoystick.PropertiesInfluenced)EditorGUILayout.EnumPopup("Influenced",t.YTI); switch( t.yAI){ case EasyJoystick.AxisInfluenced.X: GUI.color = new Color(255f/255f,69f/255f,40f/255f); break; case EasyJoystick.AxisInfluenced.Y: GUI.color = Color.green; break; case EasyJoystick.AxisInfluenced.Z: GUI.color = new Color(63f/255f,131f/255f,245f/255f); break; } t.yAI = (EasyJoystick.AxisInfluenced)EditorGUILayout.EnumPopup("Axis influenced",t.yAI); GUI.color = Color.white; EditorGUILayout.Separator(); if (t.YTI == EasyJoystick.PropertiesInfluenced.RotateLocal){ // auto stab t.enableYAutoStab = EditorGUILayout.Toggle( "AutoStab",t.enableYAutoStab); if (t.enableYAutoStab){ EditorGUILayout.BeginVertical(paddingStyle1); t.ThresholdY = EditorGUILayout.FloatField("Threshold ", t.ThresholdY); t.StabSpeedY = EditorGUILayout.FloatField("Speed",t.StabSpeedY); EditorGUILayout.EndVertical(); } EditorGUILayout.Separator(); // Clamp t.enableYClamp = EditorGUILayout.Toggle("Clamp rotation",t.enableYClamp); if (t.enableYClamp){ EditorGUILayout.BeginVertical(paddingStyle1); t.clampYMax = EditorGUILayout.FloatField("Max angle value",t.clampYMax); t.clampYMin = EditorGUILayout.FloatField("Min angle value",t.clampYMin); EditorGUILayout.EndVertical(); } } } } EditorGUILayout.EndVertical(); } EditorGUILayout.EndToggleGroup(); HTEditorToolKit.DrawSeparatorLine(paddingStyle1.padding.left); EditorGUILayout.Separator(); // Smoothing return t.enableSmoothing = EditorGUILayout.BeginToggleGroup("Smoothing return",t.enableSmoothing); if (t.enableSmoothing){ EditorGUILayout.BeginVertical(paddingStyle1); t.Smoothing = EditorGUILayout.Vector2Field( "Smoothing",t.Smoothing); EditorGUILayout.EndVertical(); } EditorGUILayout.EndToggleGroup(); t.enableInertia = EditorGUILayout.BeginToggleGroup("Enable inertia",t.enableInertia); if (t.enableInertia){ EditorGUILayout.BeginVertical(paddingStyle1); t.Inertia = EditorGUILayout.Vector2Field( "Inertia",t.Inertia); EditorGUILayout.EndVertical(); } EditorGUILayout.EndToggleGroup(); EditorGUILayout.EndVertical(); } // Joystick Texture t.showAppearance = HTEditorToolKit.DrawTitleFoldOut( t.showAppearance,"Joystick textures"); if (t.showAppearance){ EditorGUILayout.BeginVertical(paddingStyle1); t.guiDepth = EditorGUILayout.IntField("Gui depth",t.guiDepth); EditorGUILayout.Separator(); t.showZone = EditorGUILayout.Toggle("Show area",t.showZone); if (t.showZone){ t.areaColor = EditorGUILayout.ColorField( "Color",t.areaColor); t.areaTexture = (Texture)EditorGUILayout.ObjectField("Area texture",t.areaTexture,typeof(Texture),true); } EditorGUILayout.Separator(); t.showTouch = EditorGUILayout.Toggle("Show touch",t.showTouch); if (t.showTouch){ t.touchColor = EditorGUILayout.ColorField("Color",t.touchColor); t.touchTexture = (Texture)EditorGUILayout.ObjectField("Area texture",t.touchTexture,typeof(Texture),true); } EditorGUILayout.Separator(); t.showDeadZone = EditorGUILayout.Toggle("Show dead",t.showDeadZone); if (t.showDeadZone){ t.deadTexture = (Texture)EditorGUILayout.ObjectField("Dead zone texture",t.deadTexture,typeof(Texture),true); } EditorGUILayout.EndVertical(); } // Refresh if (GUI.changed){ EditorUtility.SetDirty(t); } } }
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using StructureMap.Configuration.DSL; using StructureMap.Pipeline; using StructureMap.Pipeline.Lazy; using StructureMap.TypeRules; using StructureMap.Util; namespace StructureMap.Graph { /// <summary> /// Models the runtime configuration of a StructureMap Container /// </summary> public class PluginGraph : IPluginGraph, IFamilyCollection, IDisposable { private readonly ConcurrentDictionary<Type, PluginFamily> _families = new ConcurrentDictionary<Type, PluginFamily>(); private readonly IList<IFamilyPolicy> _policies = new List<IFamilyPolicy>(); private readonly ConcurrentDictionary<Type, bool> _missingTypes = new ConcurrentDictionary<Type, bool>(); private readonly List<Registry> _registries = new List<Registry>(); private readonly LifecycleObjectCache _singletonCache = new LifecycleObjectCache(); private readonly LightweightCache<string, PluginGraph> _profiles; public TransientTracking TransientTracking = TransientTracking.DefaultNotTrackedAtRoot; public string Name { get; set; } /// <summary> /// Specifies interception, construction selection, and setter usage policies /// </summary> public readonly Policies Policies; /// <summary> /// Holds a cache of concrete types that can be considered for closing generic interface /// types /// </summary> public readonly IList<Type> ConnectedConcretions = new List<Type>(); /// <summary> /// Creates a top level PluginGraph with the default policies /// </summary> /// <param name="profile"></param> /// <returns></returns> public static PluginGraph CreateRoot(string profile = null) { var graph = new PluginGraph(); graph.ProfileName = profile ?? "DEFAULT"; graph.Families[typeof(Func<>)].SetDefault(new FuncFactoryTemplate()); graph.Families[typeof(Func<,>)].SetDefault(new FuncWithArgFactoryTemplate()); graph.Families[typeof(Lazy<>)].SetDefault(new LazyFactoryTemplate()); return graph; } internal void addCloseGenericPolicyTo() { var policy = new CloseGenericFamilyPolicy(this); AddFamilyPolicy(policy); AddFamilyPolicy(new FuncBuildByNamePolicy()); AddFamilyPolicy(new EnumerableFamilyPolicy()); } internal PluginGraph NewChild() { return new PluginGraph { Parent = this }; } internal PluginGraph ToNestedGraph() { return new PluginGraph { Parent = this, ProfileName = ProfileName + " - Nested" }; } private PluginGraph() { Policies = new Policies(this); _profiles = new LightweightCache<string, PluginGraph>(name => new PluginGraph {ProfileName = name, Parent = this}); ProfileName = "DEFAULT"; } public PluginGraph Parent { get; private set; } /// <summary> /// The profile name of this PluginGraph or "DEFAULT" if it is the top /// </summary> public string ProfileName { get; private set; } /// <summary> /// The cache for all singleton scoped objects /// </summary> public LifecycleObjectCache SingletonCache { get { return _singletonCache; } } /// <summary> /// Fetch the PluginGraph for the named profile. Will /// create a new one on the fly for unrecognized names. /// Is case sensitive /// </summary> /// <param name="name"></param> /// <returns></returns> public PluginGraph Profile(string name) { return _profiles[name]; } /// <summary> /// All the currently known profiles /// </summary> public IEnumerable<PluginGraph> Profiles { get { return _profiles.ToArray(); } } IEnumerator IEnumerable.GetEnumerator() { return _families.Select(x => x.Value).ToArray().GetEnumerator(); } IEnumerator<PluginFamily> IEnumerable<PluginFamily>.GetEnumerator() { return _families.Select(x => x.Value).ToArray().As<IEnumerable<PluginFamily>>().GetEnumerator(); } PluginFamily IFamilyCollection.this[Type pluginType] { get { return _families.GetOrAdd(pluginType, type => { var family = _policies.FirstValue(x => x.Build(type)) ?? new PluginFamily(type); family.Owner = this; return family; }); } set { _families[pluginType] = value; } } bool IFamilyCollection.Has(Type pluginType) { return _families.ContainsKey(pluginType); } /// <summary> /// Add a new family policy that can create new PluginFamily's on demand /// when there is no pre-existing family /// </summary> /// <param name="policy"></param> public void AddFamilyPolicy(IFamilyPolicy policy) { _policies.Insert(0, policy); } /// <summary> /// The list of Registry objects used to create this container /// </summary> internal List<Registry> Registries { get { return _registries; } } /// <summary> /// Access to all the known PluginFamily members /// </summary> public IFamilyCollection Families { get { return this; } } /// <summary> /// The top most PluginGraph. If this is the root, will return itself. /// If a Profiled PluginGraph, returns its ultimate parent /// </summary> public PluginGraph Root { get { return Parent == null ? this : Parent.Root; } } internal bool IsRunningConfigure { get; set; } /// <summary> /// Adds the concreteType as an Instance of the pluginType /// </summary> /// <param name = "pluginType"></param> /// <param name = "concreteType"></param> public virtual void AddType(Type pluginType, Type concreteType) { Families[pluginType].AddType(concreteType); } /// <summary> /// Adds the concreteType as an Instance of the pluginType with a name /// </summary> /// <param name = "pluginType"></param> /// <param name = "concreteType"></param> /// <param name = "name"></param> public virtual void AddType(Type pluginType, Type concreteType, string name) { Families[pluginType].AddType(concreteType, name); } public readonly Queue<Registry> QueuedRegistries = new Queue<Registry>(); /// <summary> /// Adds a Registry by type. Requires that the Registry class have a no argument /// public constructor /// </summary> /// <param name="type"></param> public void ImportRegistry(Type type) { var all = Registries.Concat(QueuedRegistries); if (all.Any(x => x.GetType() == type)) return; try { var registry = (Registry) Activator.CreateInstance(type); QueuedRegistries.Enqueue(registry); } catch (Exception e) { throw new StructureMapException( "Unable to create an instance for Registry type '{0}'. Please check the inner exception for details" .ToFormat(type.GetFullName()), e); } } public void ImportRegistry(Registry registry) { var all = Registries.Concat(QueuedRegistries).ToArray(); if (Registry.RegistryExists(all, registry)) return; QueuedRegistries.Enqueue(registry); } public void AddFamily(PluginFamily family) { family.Owner = this; _families[family.PluginType] = family; } public bool HasInstance(Type pluginType, string name) { if (!HasFamily(pluginType)) { return false; } return Families[pluginType].GetInstance(name) != null; } internal PluginFamily FindExistingOrCreateFamily(Type pluginType) { if (_families.ContainsKey(pluginType)) return _families[pluginType]; var family = new PluginFamily(pluginType); _families[pluginType] = family; return family; } /// <summary> /// Does a PluginFamily already exist for the pluginType? Will also test for open generic /// definition of a generic closed type /// </summary> /// <param name="pluginType"></param> /// <returns></returns> public bool HasFamily(Type pluginType) { if (_families.ContainsKey(pluginType)) return true; if (_missingTypes.ContainsKey(pluginType)) return false; if (_policies.Where(x => x.AppliesToHasFamilyChecks).ToArray().Any(x => x.Build(pluginType) != null)) { return true; } _missingTypes.AddOrUpdate(pluginType, true, (type, b) => true); return false; } /// <summary> /// Can this PluginGraph resolve a default instance /// for the pluginType? /// </summary> /// <param name="pluginType"></param> /// <returns></returns> public bool HasDefaultForPluginType(Type pluginType) { if (!HasFamily(pluginType)) { return false; } return Families[pluginType].GetDefaultInstance() != null; } /// <summary> /// Removes a PluginFamily from this PluginGraph /// and disposes that family and all of its Instance's /// </summary> /// <param name="pluginType"></param> public void EjectFamily(Type pluginType) { if (_families.ContainsKey(pluginType)) { PluginFamily family = null; if (_families.TryRemove(pluginType, out family)) { family.SafeDispose(); } } } internal void EachInstance(Action<Type, Instance> action) { _families.Each(family => family.Value.Instances.Each(i => action(family.Value.PluginType, i))); } /// <summary> /// Find a named instance for a given PluginType /// </summary> /// <param name="pluginType"></param> /// <param name="name"></param> /// <returns></returns> public Instance FindInstance(Type pluginType, string name) { if (!HasFamily(pluginType)) return null; return Families[pluginType].GetInstance(name); } /// <summary> /// Returns every instance in the PluginGraph for the pluginType /// </summary> /// <param name="pluginType"></param> /// <returns></returns> public IEnumerable<Instance> AllInstances(Type pluginType) { if (HasFamily(pluginType)) { return Families[pluginType].Instances; } return Enumerable.Empty<Instance>(); } void IDisposable.Dispose() { _families.Each( family => { family.Value.Instances.Each(instance => { _singletonCache.Eject(family.Value.PluginType, instance); if (instance is IDisposable) { instance.SafeDispose(); } }); }); _profiles.Each(x => x.SafeDispose()); _profiles.Clear(); var containerFamily = _families[typeof (IContainer)]; PluginFamily c; _families.TryRemove(typeof (IContainer), out c); containerFamily.RemoveAll(); _missingTypes.Clear(); _families.Each(x => x.SafeDispose()); _families.Clear(); } internal void ClearTypeMisses() { _missingTypes.Clear(); } } public interface IFamilyCollection : IEnumerable<PluginFamily> { PluginFamily this[Type pluginType] { get; set; } bool Has(Type pluginType); } }
/************************************************************************************ Filename : ONSPAudioSource.cs Content : Interface into the Oculus Native Spatializer Plugin Created : September 14, 2015 Authors : Peter Giokaris Copyright : Copyright 2015 Oculus VR, Inc. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.1 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculusvr.com/licenses/LICENSE-3.1 Unless required by applicable law or agreed to in writing, the Oculus VR SDK distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************************/ // Uncomment below to test access of read-only spatializer parameters //#define TEST_READONLY_PARAMETERS using UnityEngine; using System; using System.Collections; using System.Runtime.InteropServices; public class ONSPAudioSource : MonoBehaviour { #if TEST_READONLY_PARAMETERS // Spatializer read-only system parameters (global) static int readOnly_GlobalRelectionOn = 8; static int readOnly_NumberOfUsedSpatializedVoices = 9; #endif // Import functions public const string strONSPS = "AudioPluginOculusSpatializer"; [DllImport(strONSPS)] private static extern void ONSP_GetGlobalRoomReflectionValues(ref bool reflOn, ref bool reverbOn, ref float width, ref float height, ref float length); // Public [SerializeField] private bool enableSpatialization = true; public bool EnableSpatialization { get { return enableSpatialization; } set { enableSpatialization = value; } } [SerializeField] private float gain = 0.0f; public float Gain { get { return gain; } set { gain = Mathf.Clamp(value, 0.0f, 24.0f); } } [SerializeField] private bool useInvSqr = false; public bool UseInvSqr { get { return useInvSqr; } set { useInvSqr = value; } } [SerializeField] private float near = 1.0f; public float Near { get { return near; } set { near = Mathf.Clamp(value, 0.0f, 1000000.0f); } } [SerializeField] private float far = 10.0f; public float Far { get { return far; } set { far = Mathf.Clamp(value, 0.0f, 1000000.0f); } } [SerializeField] private float volumetricRadius = 0.0f; public float VolumetricRadius { get { return volumetricRadius; } set { volumetricRadius = Mathf.Clamp(value, 0.0f, 1000.0f); } } [SerializeField] private bool enableRfl = false; public bool EnableRfl { get { return enableRfl; } set { enableRfl = value; } } /// <summary> /// Awake this instance. /// </summary> void Awake() { // We might iterate through multiple sources / game object var source = GetComponent<AudioSource>(); SetParameters(ref source); } /// <summary> /// Start this instance. /// </summary> void Start() { } /// <summary> /// Update this instance. /// </summary> void Update() { // We might iterate through multiple sources / game object var source = GetComponent<AudioSource>(); // READ-ONLY PARAMETER TEST #if TEST_READONLY_PARAMETERS float rfl_enabled = 0.0f; source.GetSpatializerFloat(readOnly_GlobalRelectionOn, out rfl_enabled); float num_voices = 0.0f; source.GetSpatializerFloat(readOnly_NumberOfUsedSpatializedVoices, out num_voices); String readOnly = System.String.Format ("Read only values: refl enabled: {0:F0} num voices: {1:F0}", rfl_enabled, num_voices); Debug.Log(readOnly); #endif // Check to see if we should disable spatializion if ((Application.isPlaying == false) || (AudioListener.pause == true) || (source.isPlaying == false) || (source.isActiveAndEnabled == false) ) { source.spatialize = false; return; } else { SetParameters(ref source); } } /// <summary> /// Sets the parameters. /// </summary> /// <param name="source">Source.</param> public void SetParameters(ref AudioSource source) { // See if we should enable spatialization source.spatialize = enableSpatialization; source.SetSpatializerFloat(0, gain); // All inputs are floats; convert bool to 0.0 and 1.0 if(useInvSqr == true) source.SetSpatializerFloat(1, 1.0f); else source.SetSpatializerFloat(1, 0.0f); source.SetSpatializerFloat(2, near); source.SetSpatializerFloat(3, far); source.SetSpatializerFloat(4, volumetricRadius); if(enableRfl == true) source.SetSpatializerFloat(5, 0.0f); else source.SetSpatializerFloat(5, 1.0f); } private static ONSPAudioSource RoomReflectionGizmoAS = null; /// <summary> /// /// </summary> void OnDrawGizmos() { // Are we the first one created? make sure to set our static ONSPAudioSource // for drawing out room parameters once if(RoomReflectionGizmoAS == null) { RoomReflectionGizmoAS = this; } Color c; const float colorSolidAlpha = 0.1f; // Draw the near/far spheres // Near (orange) c.r = 1.0f; c.g = 0.5f; c.b = 0.0f; c.a = 1.0f; Gizmos.color = c; Gizmos.DrawWireSphere(transform.position, Near); c.a = colorSolidAlpha; Gizmos.color = c; Gizmos.DrawSphere(transform.position, Near); // Far (red) c.r = 1.0f; c.g = 0.0f; c.b = 0.0f; c.a = 1.0f; Gizmos.color = Color.red; Gizmos.DrawWireSphere(transform.position, Far); c.a = colorSolidAlpha; Gizmos.color = c; Gizmos.DrawSphere(transform.position, Far); // VolumetricRadius (purple) c.r = 1.0f; c.g = 0.0f; c.b = 1.0f; c.a = 1.0f; Gizmos.color = c; Gizmos.DrawWireSphere(transform.position, VolumetricRadius); c.a = colorSolidAlpha; Gizmos.color = c; Gizmos.DrawSphere(transform.position, VolumetricRadius); // Draw room parameters ONCE only, provided reflection engine is on if (RoomReflectionGizmoAS == this) { // Get global room parameters (write new C api to get reflection values) bool reflOn = false; bool reverbOn = false; float width = 1.0f; float height = 1.0f; float length = 1.0f; ONSP_GetGlobalRoomReflectionValues(ref reflOn, ref reverbOn, ref width, ref height, ref length); // TO DO: Get the room reflection values and render those out as well (like we do in the VST) if((Camera.main != null) && (reflOn == true)) { // Set color of cube (cyan is early reflections only, white is with reverb on) if(reverbOn == true) c = Color.white; else c = Color.cyan; Gizmos.color = c; Gizmos.DrawWireCube(Camera.main.transform.position, new Vector3(width, height, length)); c.a = colorSolidAlpha; Gizmos.color = c; Gizmos.DrawCube(Camera.main.transform.position, new Vector3(width, height, length)); } } } /// <summary> /// /// </summary> void OnDestroy() { // We will null out single pointer instance // of the room reflection gizmo since we are being destroyed. // Any ONSPAS that is alive or born will re-set this pointer // so that we only draw it once if(RoomReflectionGizmoAS == this) { RoomReflectionGizmoAS = null; } } }
// // App.cs // // Author: // Ruben Vermeersch <[email protected]> // Stephane Delcroix <[email protected]> // // Copyright (C) 2009-2010 Novell, Inc. // Copyright (C) 2010 Ruben Vermeersch // Copyright (C) 2009-2010 Stephane Delcroix // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Threading; using Unique; using Mono.Unix; using Hyena; using FSpot.Core; using FSpot.Database; using FSpot.Imaging; using FSpot.Settings; using FSpot.Thumbnail; using FSpot.Utils; namespace FSpot { public class App : Unique.App { static object sync_handle = new object (); #region public API static App app; public static App Instance { get { lock (sync_handle) { if (app == null) app = new App (); } return app; } } Thread constructing_organizer = null; public MainWindow Organizer { get { lock (sync_handle) { if (organizer == null) { if (constructing_organizer == Thread.CurrentThread) { throw new Exception ("Recursively tried to acquire App.Organizer!"); } constructing_organizer = Thread.CurrentThread; organizer = new MainWindow (Database); Register (organizer.Window); } } return organizer; } } public Db Database { get { lock (sync_handle) { if (db == null) { if (!File.Exists (Global.BaseDirectory)) Directory.CreateDirectory (Global.BaseDirectory); db = new Db (Container.Resolve<IImageFileFactory> (), Container.Resolve<IThumbnailService> (), new UpdaterUI ()); try { db.Init (Path.Combine (Global.BaseDirectory, "photos.db"), true); } catch (Exception e) { new FSpot.UI.Dialog.RepairDbDialog (e, db.Repair (), null); db.Init (Path.Combine (Global.BaseDirectory, "photos.db"), true); } } } return db; } } public TinyIoCContainer Container { get { return TinyIoCContainer.Current; } } public void Import (string path) { if (IsRunning) { var md = new MessageData (); md.Text = path; SendMessage (Command.Import, md); return; } HandleImport (path); } public void Organize () { if (IsRunning) { SendMessage (Command.Organize, null); return; } HandleOrganize (); } public void Shutdown () { if (IsRunning) { SendMessage (Command.Shutdown, null); return; } HandleShutdown (); } public void Slideshow (string tagname) { if (IsRunning) { var md = new MessageData (); md.Text = tagname ?? string.Empty; SendMessage (Command.Slideshow, md); return; } HandleSlideshow (tagname); } public void View (SafeUri uri) { View (new[] {uri}); } public void View (IEnumerable<SafeUri> uris) { var uri_s = from uri in uris select uri.ToString (); View (uri_s); } public void View (string uri) { View (new[] {uri}); } public void View (IEnumerable<string> uris) { if (IsRunning) { var md = new MessageData (); md.Uris = uris.ToArray (); SendMessage (Command.View, md); return; } HandleView (uris.ToArray()); } #endregion #region private ctor and stuffs enum Command { Invalid = 0, Import, View, Organize, Shutdown, Version, Slideshow, } List<Gtk.Window> toplevels; MainWindow organizer; Db db; App (): base ("org.gnome.FSpot.Core", null, "Import", Command.Import, "View", Command.View, "Organize", Command.Organize, "Shutdown", Command.Shutdown, "Slideshow", Command.Slideshow) { toplevels = new List<Gtk.Window> (); if (IsRunning) { Log.Information ("Found active FSpot process"); } else { MessageReceived += HandleMessageReceived; } FSpot.FileSystem.ModuleController.RegisterTypes (Container); FSpot.Imaging.ModuleController.RegisterTypes (Container); FSpot.Import.ModuleController.RegisterTypes (Container); FSpot.Thumbnail.ModuleController.RegisterTypes (Container); } void SendMessage (Command command, MessageData md) { SendMessage ((Unique.Command)command, md); } #endregion #region Command Handlers void HandleMessageReceived (object sender, MessageReceivedArgs e) { switch ((Command)e.Command) { case Command.Import: HandleImport (e.MessageData.Text); e.RetVal = Response.Ok; break; case Command.Organize: HandleOrganize (); e.RetVal = Response.Ok; break; case Command.Shutdown: HandleShutdown (); e.RetVal = Response.Ok; break; case Command.Slideshow: HandleSlideshow (e.MessageData.Text); e.RetVal = Response.Ok; break; case Command.View: HandleView (e.MessageData.Uris); e.RetVal = Response.Ok; break; case Command.Invalid: default: Log.Debug ("Wrong command received"); break; } } void HandleImport (string path) { // Some users get wonky URIs here, trying to work around below. // https://bugzilla.gnome.org/show_bug.cgi?id=629248 if (path != null && path.StartsWith ("gphoto2:usb:")) { path = string.Format ("gphoto2://[{0}]", path.Substring (8)); } Hyena.Log.DebugFormat ("Importing from {0}", path); Organizer.Window.Present (); Organizer.ImportFile (path == null ? null : new SafeUri(path)); } void HandleOrganize () { if (Database.Empty) HandleImport (null); else Organizer.Window.Present (); } void HandleShutdown () { try { Instance.Organizer.Close (); } catch { Environment.Exit (0); } } //FIXME move all this in a standalone class void HandleSlideshow (string tagname) { Tag tag; FSpot.Widgets.SlideShow slideshow = null; if (!string.IsNullOrEmpty (tagname)) tag = Database.Tags.GetTagByName (tagname); else tag = Database.Tags.GetTagById (Preferences.Get<int> (Preferences.SCREENSAVER_TAG)); IPhoto[] photos; if (tag != null) photos = ObsoletePhotoQueries.Query (new Tag[] {tag}); else if (Preferences.Get<int> (Preferences.SCREENSAVER_TAG) == 0) photos = ObsoletePhotoQueries.Query (new Tag [] {}); else photos = new IPhoto [0]; // Minimum delay 1 second; default is 4s var delay = Math.Max (1.0, Preferences.Get<double> (Preferences.SCREENSAVER_DELAY)); var window = new XScreenSaverSlide (); window.ModifyFg (Gtk.StateType.Normal, new Gdk.Color (127, 127, 127)); window.ModifyBg (Gtk.StateType.Normal, new Gdk.Color (0, 0, 0)); if (photos.Length > 0) { Array.Sort (photos, new IPhotoComparer.RandomSort ()); slideshow = new FSpot.Widgets.SlideShow (new BrowsablePointer (new PhotoList (photos), 0), (uint)(delay * 1000), true); window.Add (slideshow); } else { Gtk.HBox outer = new Gtk.HBox (); Gtk.HBox hbox = new Gtk.HBox (); Gtk.VBox vbox = new Gtk.VBox (); outer.PackStart (new Gtk.Label (string.Empty)); outer.PackStart (vbox, false, false, 0); vbox.PackStart (new Gtk.Label (string.Empty)); vbox.PackStart (hbox, false, false, 0); hbox.PackStart (new Gtk.Image (Gtk.Stock.DialogWarning, Gtk.IconSize.Dialog), false, false, 0); outer.PackStart (new Gtk.Label (string.Empty)); string msg; string long_msg; if (tag != null) { msg = string.Format (Catalog.GetString ("No photos matching {0} found"), tag.Name); long_msg = string.Format (Catalog.GetString ("The tag \"{0}\" is not applied to any photos. Try adding\n" + "the tag to some photos or selecting a different tag in the\n" + "F-Spot preference dialog."), tag.Name); } else { msg = Catalog.GetString ("Search returned no results"); long_msg = Catalog.GetString ("The tag F-Spot is looking for does not exist. Try\n" + "selecting a different tag in the F-Spot preference\n" + "dialog."); } Gtk.Label label = new Gtk.Label (msg); hbox.PackStart (label, false, false, 0); Gtk.Label long_label = new Gtk.Label (long_msg); long_label.Markup = string.Format ("<small>{0}</small>", long_msg); vbox.PackStart (long_label, false, false, 0); vbox.PackStart (new Gtk.Label (string.Empty)); window.Add (outer); label.ModifyFg (Gtk.StateType.Normal, new Gdk.Color (127, 127, 127)); label.ModifyBg (Gtk.StateType.Normal, new Gdk.Color (0, 0, 0)); long_label.ModifyFg (Gtk.StateType.Normal, new Gdk.Color (127, 127, 127)); long_label.ModifyBg (Gtk.StateType.Normal, new Gdk.Color (0, 0, 0)); } window.ShowAll (); Register (window); GLib.Idle.Add (delegate { if (slideshow != null) slideshow.Start (); return false; }); } void HandleView (string[] uris) { var ul = new List<SafeUri> (); foreach (var u in uris) ul.Add (new SafeUri (u, true)); try { Register (new FSpot.SingleView (ul.ToArray ()).Window); } catch (Exception e) { Log.Exception (e); Log.Debug ("no real valid path to view from"); } } #endregion #region Track toplevel windows void Register (Gtk.Window window) { toplevels.Add (window); window.Destroyed += HandleDestroyed; } void HandleDestroyed (object sender, EventArgs e) { toplevels.Remove (sender as Gtk.Window); if (toplevels.Count == 0) { Log.Information ("Exiting..."); Banshee.Kernel.Scheduler.Dispose (); Database.Dispose (); ImageLoaderThread.CleanAll (); Gtk.Application.Quit (); } if (organizer != null && organizer.Window == sender) organizer = null; } #endregion } }